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 ForRedeclaration); 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, ForRedeclaration); 826 827 // Build the variable that holds the non-decomposed object. 828 bool AddToScope = true; 829 NamedDecl *New = 830 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 831 MultiTemplateParamsArg(), AddToScope, Bindings); 832 if (AddToScope) { 833 S->AddDecl(New); 834 CurContext->addHiddenDecl(New); 835 } 836 837 if (isInOpenMPDeclareTargetContext()) 838 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 839 840 return New; 841 } 842 843 static bool checkSimpleDecomposition( 844 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 845 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 846 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 847 if ((int64_t)Bindings.size() != NumElems) { 848 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 849 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 850 << (NumElems < Bindings.size()); 851 return true; 852 } 853 854 unsigned I = 0; 855 for (auto *B : Bindings) { 856 SourceLocation Loc = B->getLocation(); 857 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 858 if (E.isInvalid()) 859 return true; 860 E = GetInit(Loc, E.get(), I++); 861 if (E.isInvalid()) 862 return true; 863 B->setBinding(ElemType, E.get()); 864 } 865 866 return false; 867 } 868 869 static bool checkArrayLikeDecomposition(Sema &S, 870 ArrayRef<BindingDecl *> Bindings, 871 ValueDecl *Src, QualType DecompType, 872 const llvm::APSInt &NumElems, 873 QualType ElemType) { 874 return checkSimpleDecomposition( 875 S, Bindings, Src, DecompType, NumElems, ElemType, 876 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 877 ExprResult E = S.ActOnIntegerConstant(Loc, I); 878 if (E.isInvalid()) 879 return ExprError(); 880 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 881 }); 882 } 883 884 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 885 ValueDecl *Src, QualType DecompType, 886 const ConstantArrayType *CAT) { 887 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 888 llvm::APSInt(CAT->getSize()), 889 CAT->getElementType()); 890 } 891 892 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 893 ValueDecl *Src, QualType DecompType, 894 const VectorType *VT) { 895 return checkArrayLikeDecomposition( 896 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 897 S.Context.getQualifiedType(VT->getElementType(), 898 DecompType.getQualifiers())); 899 } 900 901 static bool checkComplexDecomposition(Sema &S, 902 ArrayRef<BindingDecl *> Bindings, 903 ValueDecl *Src, QualType DecompType, 904 const ComplexType *CT) { 905 return checkSimpleDecomposition( 906 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 907 S.Context.getQualifiedType(CT->getElementType(), 908 DecompType.getQualifiers()), 909 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 910 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 911 }); 912 } 913 914 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 915 TemplateArgumentListInfo &Args) { 916 SmallString<128> SS; 917 llvm::raw_svector_ostream OS(SS); 918 bool First = true; 919 for (auto &Arg : Args.arguments()) { 920 if (!First) 921 OS << ", "; 922 Arg.getArgument().print(PrintingPolicy, OS); 923 First = false; 924 } 925 return OS.str(); 926 } 927 928 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 929 SourceLocation Loc, StringRef Trait, 930 TemplateArgumentListInfo &Args, 931 unsigned DiagID) { 932 auto DiagnoseMissing = [&] { 933 if (DiagID) 934 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 935 Args); 936 return true; 937 }; 938 939 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 940 NamespaceDecl *Std = S.getStdNamespace(); 941 if (!Std) 942 return DiagnoseMissing(); 943 944 // Look up the trait itself, within namespace std. We can diagnose various 945 // problems with this lookup even if we've been asked to not diagnose a 946 // missing specialization, because this can only fail if the user has been 947 // declaring their own names in namespace std or we don't support the 948 // standard library implementation in use. 949 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 950 Loc, Sema::LookupOrdinaryName); 951 if (!S.LookupQualifiedName(Result, Std)) 952 return DiagnoseMissing(); 953 if (Result.isAmbiguous()) 954 return true; 955 956 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 957 if (!TraitTD) { 958 Result.suppressDiagnostics(); 959 NamedDecl *Found = *Result.begin(); 960 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 961 S.Diag(Found->getLocation(), diag::note_declared_at); 962 return true; 963 } 964 965 // Build the template-id. 966 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 967 if (TraitTy.isNull()) 968 return true; 969 if (!S.isCompleteType(Loc, TraitTy)) { 970 if (DiagID) 971 S.RequireCompleteType( 972 Loc, TraitTy, DiagID, 973 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 974 return true; 975 } 976 977 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 978 assert(RD && "specialization of class template is not a class?"); 979 980 // Look up the member of the trait type. 981 S.LookupQualifiedName(TraitMemberLookup, RD); 982 return TraitMemberLookup.isAmbiguous(); 983 } 984 985 static TemplateArgumentLoc 986 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 987 uint64_t I) { 988 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 989 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 990 } 991 992 static TemplateArgumentLoc 993 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 994 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 995 } 996 997 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 998 999 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1000 llvm::APSInt &Size) { 1001 EnterExpressionEvaluationContext ContextRAII( 1002 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1003 1004 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1005 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1006 1007 // Form template argument list for tuple_size<T>. 1008 TemplateArgumentListInfo Args(Loc, Loc); 1009 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1010 1011 // If there's no tuple_size specialization, it's not tuple-like. 1012 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0)) 1013 return IsTupleLike::NotTupleLike; 1014 1015 // If we get this far, we've committed to the tuple interpretation, but 1016 // we can still fail if there actually isn't a usable ::value. 1017 1018 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1019 LookupResult &R; 1020 TemplateArgumentListInfo &Args; 1021 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1022 : R(R), Args(Args) {} 1023 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1024 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1025 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1026 } 1027 } Diagnoser(R, Args); 1028 1029 if (R.empty()) { 1030 Diagnoser.diagnoseNotICE(S, Loc, SourceRange()); 1031 return IsTupleLike::Error; 1032 } 1033 1034 ExprResult E = 1035 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1036 if (E.isInvalid()) 1037 return IsTupleLike::Error; 1038 1039 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1040 if (E.isInvalid()) 1041 return IsTupleLike::Error; 1042 1043 return IsTupleLike::TupleLike; 1044 } 1045 1046 /// \return std::tuple_element<I, T>::type. 1047 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1048 unsigned I, QualType T) { 1049 // Form template argument list for tuple_element<I, T>. 1050 TemplateArgumentListInfo Args(Loc, Loc); 1051 Args.addArgument( 1052 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1053 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1054 1055 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1056 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1057 if (lookupStdTypeTraitMember( 1058 S, R, Loc, "tuple_element", Args, 1059 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1060 return QualType(); 1061 1062 auto *TD = R.getAsSingle<TypeDecl>(); 1063 if (!TD) { 1064 R.suppressDiagnostics(); 1065 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1066 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1067 if (!R.empty()) 1068 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1069 return QualType(); 1070 } 1071 1072 return S.Context.getTypeDeclType(TD); 1073 } 1074 1075 namespace { 1076 struct BindingDiagnosticTrap { 1077 Sema &S; 1078 DiagnosticErrorTrap Trap; 1079 BindingDecl *BD; 1080 1081 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1082 : S(S), Trap(S.Diags), BD(BD) {} 1083 ~BindingDiagnosticTrap() { 1084 if (Trap.hasErrorOccurred()) 1085 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1086 } 1087 }; 1088 } 1089 1090 static bool checkTupleLikeDecomposition(Sema &S, 1091 ArrayRef<BindingDecl *> Bindings, 1092 VarDecl *Src, QualType DecompType, 1093 const llvm::APSInt &TupleSize) { 1094 if ((int64_t)Bindings.size() != TupleSize) { 1095 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1096 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1097 << (TupleSize < Bindings.size()); 1098 return true; 1099 } 1100 1101 if (Bindings.empty()) 1102 return false; 1103 1104 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1105 1106 // [dcl.decomp]p3: 1107 // The unqualified-id get is looked up in the scope of E by class member 1108 // access lookup 1109 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1110 bool UseMemberGet = false; 1111 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1112 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1113 S.LookupQualifiedName(MemberGet, RD); 1114 if (MemberGet.isAmbiguous()) 1115 return true; 1116 UseMemberGet = !MemberGet.empty(); 1117 S.FilterAcceptableTemplateNames(MemberGet); 1118 } 1119 1120 unsigned I = 0; 1121 for (auto *B : Bindings) { 1122 BindingDiagnosticTrap Trap(S, B); 1123 SourceLocation Loc = B->getLocation(); 1124 1125 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1126 if (E.isInvalid()) 1127 return true; 1128 1129 // e is an lvalue if the type of the entity is an lvalue reference and 1130 // an xvalue otherwise 1131 if (!Src->getType()->isLValueReferenceType()) 1132 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1133 E.get(), nullptr, VK_XValue); 1134 1135 TemplateArgumentListInfo Args(Loc, Loc); 1136 Args.addArgument( 1137 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1138 1139 if (UseMemberGet) { 1140 // if [lookup of member get] finds at least one declaration, the 1141 // initializer is e.get<i-1>(). 1142 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1143 CXXScopeSpec(), SourceLocation(), nullptr, 1144 MemberGet, &Args, nullptr); 1145 if (E.isInvalid()) 1146 return true; 1147 1148 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc); 1149 } else { 1150 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1151 // in the associated namespaces. 1152 Expr *Get = UnresolvedLookupExpr::Create( 1153 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1154 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1155 UnresolvedSetIterator(), UnresolvedSetIterator()); 1156 1157 Expr *Arg = E.get(); 1158 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc); 1159 } 1160 if (E.isInvalid()) 1161 return true; 1162 Expr *Init = E.get(); 1163 1164 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1165 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1166 if (T.isNull()) 1167 return true; 1168 1169 // each vi is a variable of type "reference to T" initialized with the 1170 // initializer, where the reference is an lvalue reference if the 1171 // initializer is an lvalue and an rvalue reference otherwise 1172 QualType RefType = 1173 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1174 if (RefType.isNull()) 1175 return true; 1176 auto *RefVD = VarDecl::Create( 1177 S.Context, Src->getDeclContext(), Loc, Loc, 1178 B->getDeclName().getAsIdentifierInfo(), RefType, 1179 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1180 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1181 RefVD->setTSCSpec(Src->getTSCSpec()); 1182 RefVD->setImplicit(); 1183 if (Src->isInlineSpecified()) 1184 RefVD->setInlineSpecified(); 1185 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1186 1187 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1188 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1189 InitializationSequence Seq(S, Entity, Kind, Init); 1190 E = Seq.Perform(S, Entity, Kind, Init); 1191 if (E.isInvalid()) 1192 return true; 1193 E = S.ActOnFinishFullExpr(E.get(), Loc); 1194 if (E.isInvalid()) 1195 return true; 1196 RefVD->setInit(E.get()); 1197 RefVD->checkInitIsICE(); 1198 1199 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1200 DeclarationNameInfo(B->getDeclName(), Loc), 1201 RefVD); 1202 if (E.isInvalid()) 1203 return true; 1204 1205 B->setBinding(T, E.get()); 1206 I++; 1207 } 1208 1209 return false; 1210 } 1211 1212 /// Find the base class to decompose in a built-in decomposition of a class type. 1213 /// This base class search is, unfortunately, not quite like any other that we 1214 /// perform anywhere else in C++. 1215 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S, 1216 SourceLocation Loc, 1217 const CXXRecordDecl *RD, 1218 CXXCastPath &BasePath) { 1219 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1220 CXXBasePath &Path) { 1221 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1222 }; 1223 1224 const CXXRecordDecl *ClassWithFields = nullptr; 1225 if (RD->hasDirectFields()) 1226 // [dcl.decomp]p4: 1227 // Otherwise, all of E's non-static data members shall be public direct 1228 // members of E ... 1229 ClassWithFields = RD; 1230 else { 1231 // ... or of ... 1232 CXXBasePaths Paths; 1233 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1234 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1235 // If no classes have fields, just decompose RD itself. (This will work 1236 // if and only if zero bindings were provided.) 1237 return RD; 1238 } 1239 1240 CXXBasePath *BestPath = nullptr; 1241 for (auto &P : Paths) { 1242 if (!BestPath) 1243 BestPath = &P; 1244 else if (!S.Context.hasSameType(P.back().Base->getType(), 1245 BestPath->back().Base->getType())) { 1246 // ... the same ... 1247 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1248 << false << RD << BestPath->back().Base->getType() 1249 << P.back().Base->getType(); 1250 return nullptr; 1251 } else if (P.Access < BestPath->Access) { 1252 BestPath = &P; 1253 } 1254 } 1255 1256 // ... unambiguous ... 1257 QualType BaseType = BestPath->back().Base->getType(); 1258 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1259 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1260 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1261 return nullptr; 1262 } 1263 1264 // ... public base class of E. 1265 if (BestPath->Access != AS_public) { 1266 S.Diag(Loc, diag::err_decomp_decl_non_public_base) 1267 << RD << BaseType; 1268 for (auto &BS : *BestPath) { 1269 if (BS.Base->getAccessSpecifier() != AS_public) { 1270 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path) 1271 << (BS.Base->getAccessSpecifier() == AS_protected) 1272 << (BS.Base->getAccessSpecifierAsWritten() == AS_none); 1273 break; 1274 } 1275 } 1276 return nullptr; 1277 } 1278 1279 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1280 S.BuildBasePathArray(Paths, BasePath); 1281 } 1282 1283 // The above search did not check whether the selected class itself has base 1284 // classes with fields, so check that now. 1285 CXXBasePaths Paths; 1286 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1287 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1288 << (ClassWithFields == RD) << RD << ClassWithFields 1289 << Paths.front().back().Base->getType(); 1290 return nullptr; 1291 } 1292 1293 return ClassWithFields; 1294 } 1295 1296 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1297 ValueDecl *Src, QualType DecompType, 1298 const CXXRecordDecl *RD) { 1299 CXXCastPath BasePath; 1300 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath); 1301 if (!RD) 1302 return true; 1303 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1304 DecompType.getQualifiers()); 1305 1306 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1307 unsigned NumFields = 1308 std::count_if(RD->field_begin(), RD->field_end(), 1309 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1310 assert(Bindings.size() != NumFields); 1311 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1312 << DecompType << (unsigned)Bindings.size() << NumFields 1313 << (NumFields < Bindings.size()); 1314 return true; 1315 }; 1316 1317 // all of E's non-static data members shall be public [...] members, 1318 // E shall not have an anonymous union member, ... 1319 unsigned I = 0; 1320 for (auto *FD : RD->fields()) { 1321 if (FD->isUnnamedBitfield()) 1322 continue; 1323 1324 if (FD->isAnonymousStructOrUnion()) { 1325 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1326 << DecompType << FD->getType()->isUnionType(); 1327 S.Diag(FD->getLocation(), diag::note_declared_at); 1328 return true; 1329 } 1330 1331 // We have a real field to bind. 1332 if (I >= Bindings.size()) 1333 return DiagnoseBadNumberOfBindings(); 1334 auto *B = Bindings[I++]; 1335 1336 SourceLocation Loc = B->getLocation(); 1337 if (FD->getAccess() != AS_public) { 1338 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType; 1339 1340 // Determine whether the access specifier was explicit. 1341 bool Implicit = true; 1342 for (const auto *D : RD->decls()) { 1343 if (declaresSameEntity(D, FD)) 1344 break; 1345 if (isa<AccessSpecDecl>(D)) { 1346 Implicit = false; 1347 break; 1348 } 1349 } 1350 1351 S.Diag(FD->getLocation(), diag::note_access_natural) 1352 << (FD->getAccess() == AS_protected) << Implicit; 1353 return true; 1354 } 1355 1356 // Initialize the binding to Src.FD. 1357 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1358 if (E.isInvalid()) 1359 return true; 1360 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1361 VK_LValue, &BasePath); 1362 if (E.isInvalid()) 1363 return true; 1364 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1365 CXXScopeSpec(), FD, 1366 DeclAccessPair::make(FD, FD->getAccess()), 1367 DeclarationNameInfo(FD->getDeclName(), Loc)); 1368 if (E.isInvalid()) 1369 return true; 1370 1371 // If the type of the member is T, the referenced type is cv T, where cv is 1372 // the cv-qualification of the decomposition expression. 1373 // 1374 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1375 // 'const' to the type of the field. 1376 Qualifiers Q = DecompType.getQualifiers(); 1377 if (FD->isMutable()) 1378 Q.removeConst(); 1379 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1380 } 1381 1382 if (I != Bindings.size()) 1383 return DiagnoseBadNumberOfBindings(); 1384 1385 return false; 1386 } 1387 1388 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1389 QualType DecompType = DD->getType(); 1390 1391 // If the type of the decomposition is dependent, then so is the type of 1392 // each binding. 1393 if (DecompType->isDependentType()) { 1394 for (auto *B : DD->bindings()) 1395 B->setType(Context.DependentTy); 1396 return; 1397 } 1398 1399 DecompType = DecompType.getNonReferenceType(); 1400 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1401 1402 // C++1z [dcl.decomp]/2: 1403 // If E is an array type [...] 1404 // As an extension, we also support decomposition of built-in complex and 1405 // vector types. 1406 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1407 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1408 DD->setInvalidDecl(); 1409 return; 1410 } 1411 if (auto *VT = DecompType->getAs<VectorType>()) { 1412 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1413 DD->setInvalidDecl(); 1414 return; 1415 } 1416 if (auto *CT = DecompType->getAs<ComplexType>()) { 1417 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1418 DD->setInvalidDecl(); 1419 return; 1420 } 1421 1422 // C++1z [dcl.decomp]/3: 1423 // if the expression std::tuple_size<E>::value is a well-formed integral 1424 // constant expression, [...] 1425 llvm::APSInt TupleSize(32); 1426 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1427 case IsTupleLike::Error: 1428 DD->setInvalidDecl(); 1429 return; 1430 1431 case IsTupleLike::TupleLike: 1432 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1433 DD->setInvalidDecl(); 1434 return; 1435 1436 case IsTupleLike::NotTupleLike: 1437 break; 1438 } 1439 1440 // C++1z [dcl.dcl]/8: 1441 // [E shall be of array or non-union class type] 1442 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1443 if (!RD || RD->isUnion()) { 1444 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1445 << DD << !RD << DecompType; 1446 DD->setInvalidDecl(); 1447 return; 1448 } 1449 1450 // C++1z [dcl.decomp]/4: 1451 // all of E's non-static data members shall be [...] direct members of 1452 // E or of the same unambiguous public base class of E, ... 1453 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1454 DD->setInvalidDecl(); 1455 } 1456 1457 /// \brief Merge the exception specifications of two variable declarations. 1458 /// 1459 /// This is called when there's a redeclaration of a VarDecl. The function 1460 /// checks if the redeclaration might have an exception specification and 1461 /// validates compatibility and merges the specs if necessary. 1462 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1463 // Shortcut if exceptions are disabled. 1464 if (!getLangOpts().CXXExceptions) 1465 return; 1466 1467 assert(Context.hasSameType(New->getType(), Old->getType()) && 1468 "Should only be called if types are otherwise the same."); 1469 1470 QualType NewType = New->getType(); 1471 QualType OldType = Old->getType(); 1472 1473 // We're only interested in pointers and references to functions, as well 1474 // as pointers to member functions. 1475 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1476 NewType = R->getPointeeType(); 1477 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1478 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1479 NewType = P->getPointeeType(); 1480 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1481 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1482 NewType = M->getPointeeType(); 1483 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1484 } 1485 1486 if (!NewType->isFunctionProtoType()) 1487 return; 1488 1489 // There's lots of special cases for functions. For function pointers, system 1490 // libraries are hopefully not as broken so that we don't need these 1491 // workarounds. 1492 if (CheckEquivalentExceptionSpec( 1493 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1494 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1495 New->setInvalidDecl(); 1496 } 1497 } 1498 1499 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1500 /// function declaration are well-formed according to C++ 1501 /// [dcl.fct.default]. 1502 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1503 unsigned NumParams = FD->getNumParams(); 1504 unsigned p; 1505 1506 // Find first parameter with a default argument 1507 for (p = 0; p < NumParams; ++p) { 1508 ParmVarDecl *Param = FD->getParamDecl(p); 1509 if (Param->hasDefaultArg()) 1510 break; 1511 } 1512 1513 // C++11 [dcl.fct.default]p4: 1514 // In a given function declaration, each parameter subsequent to a parameter 1515 // with a default argument shall have a default argument supplied in this or 1516 // a previous declaration or shall be a function parameter pack. A default 1517 // argument shall not be redefined by a later declaration (not even to the 1518 // same value). 1519 unsigned LastMissingDefaultArg = 0; 1520 for (; p < NumParams; ++p) { 1521 ParmVarDecl *Param = FD->getParamDecl(p); 1522 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1523 if (Param->isInvalidDecl()) 1524 /* We already complained about this parameter. */; 1525 else if (Param->getIdentifier()) 1526 Diag(Param->getLocation(), 1527 diag::err_param_default_argument_missing_name) 1528 << Param->getIdentifier(); 1529 else 1530 Diag(Param->getLocation(), 1531 diag::err_param_default_argument_missing); 1532 1533 LastMissingDefaultArg = p; 1534 } 1535 } 1536 1537 if (LastMissingDefaultArg > 0) { 1538 // Some default arguments were missing. Clear out all of the 1539 // default arguments up to (and including) the last missing 1540 // default argument, so that we leave the function parameters 1541 // in a semantically valid state. 1542 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1543 ParmVarDecl *Param = FD->getParamDecl(p); 1544 if (Param->hasDefaultArg()) { 1545 Param->setDefaultArg(nullptr); 1546 } 1547 } 1548 } 1549 } 1550 1551 // CheckConstexprParameterTypes - Check whether a function's parameter types 1552 // are all literal types. If so, return true. If not, produce a suitable 1553 // diagnostic and return false. 1554 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1555 const FunctionDecl *FD) { 1556 unsigned ArgIndex = 0; 1557 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1558 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1559 e = FT->param_type_end(); 1560 i != e; ++i, ++ArgIndex) { 1561 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1562 SourceLocation ParamLoc = PD->getLocation(); 1563 if (!(*i)->isDependentType() && 1564 SemaRef.RequireLiteralType(ParamLoc, *i, 1565 diag::err_constexpr_non_literal_param, 1566 ArgIndex+1, PD->getSourceRange(), 1567 isa<CXXConstructorDecl>(FD))) 1568 return false; 1569 } 1570 return true; 1571 } 1572 1573 /// \brief Get diagnostic %select index for tag kind for 1574 /// record diagnostic message. 1575 /// WARNING: Indexes apply to particular diagnostics only! 1576 /// 1577 /// \returns diagnostic %select index. 1578 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1579 switch (Tag) { 1580 case TTK_Struct: return 0; 1581 case TTK_Interface: return 1; 1582 case TTK_Class: return 2; 1583 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1584 } 1585 } 1586 1587 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 1588 // the requirements of a constexpr function definition or a constexpr 1589 // constructor definition. If so, return true. If not, produce appropriate 1590 // diagnostics and return false. 1591 // 1592 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1593 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 1594 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1595 if (MD && MD->isInstance()) { 1596 // C++11 [dcl.constexpr]p4: 1597 // The definition of a constexpr constructor shall satisfy the following 1598 // constraints: 1599 // - the class shall not have any virtual base classes; 1600 const CXXRecordDecl *RD = MD->getParent(); 1601 if (RD->getNumVBases()) { 1602 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1603 << isa<CXXConstructorDecl>(NewFD) 1604 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1605 for (const auto &I : RD->vbases()) 1606 Diag(I.getLocStart(), 1607 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 1608 return false; 1609 } 1610 } 1611 1612 if (!isa<CXXConstructorDecl>(NewFD)) { 1613 // C++11 [dcl.constexpr]p3: 1614 // The definition of a constexpr function shall satisfy the following 1615 // constraints: 1616 // - it shall not be virtual; 1617 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1618 if (Method && Method->isVirtual()) { 1619 Method = Method->getCanonicalDecl(); 1620 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1621 1622 // If it's not obvious why this function is virtual, find an overridden 1623 // function which uses the 'virtual' keyword. 1624 const CXXMethodDecl *WrittenVirtual = Method; 1625 while (!WrittenVirtual->isVirtualAsWritten()) 1626 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1627 if (WrittenVirtual != Method) 1628 Diag(WrittenVirtual->getLocation(), 1629 diag::note_overridden_virtual_function); 1630 return false; 1631 } 1632 1633 // - its return type shall be a literal type; 1634 QualType RT = NewFD->getReturnType(); 1635 if (!RT->isDependentType() && 1636 RequireLiteralType(NewFD->getLocation(), RT, 1637 diag::err_constexpr_non_literal_return)) 1638 return false; 1639 } 1640 1641 // - each of its parameter types shall be a literal type; 1642 if (!CheckConstexprParameterTypes(*this, NewFD)) 1643 return false; 1644 1645 return true; 1646 } 1647 1648 /// Check the given declaration statement is legal within a constexpr function 1649 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1650 /// 1651 /// \return true if the body is OK (maybe only as an extension), false if we 1652 /// have diagnosed a problem. 1653 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1654 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 1655 // C++11 [dcl.constexpr]p3 and p4: 1656 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1657 // contain only 1658 for (const auto *DclIt : DS->decls()) { 1659 switch (DclIt->getKind()) { 1660 case Decl::StaticAssert: 1661 case Decl::Using: 1662 case Decl::UsingShadow: 1663 case Decl::UsingDirective: 1664 case Decl::UnresolvedUsingTypename: 1665 case Decl::UnresolvedUsingValue: 1666 // - static_assert-declarations 1667 // - using-declarations, 1668 // - using-directives, 1669 continue; 1670 1671 case Decl::Typedef: 1672 case Decl::TypeAlias: { 1673 // - typedef declarations and alias-declarations that do not define 1674 // classes or enumerations, 1675 const auto *TN = cast<TypedefNameDecl>(DclIt); 1676 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1677 // Don't allow variably-modified types in constexpr functions. 1678 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1679 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1680 << TL.getSourceRange() << TL.getType() 1681 << isa<CXXConstructorDecl>(Dcl); 1682 return false; 1683 } 1684 continue; 1685 } 1686 1687 case Decl::Enum: 1688 case Decl::CXXRecord: 1689 // C++1y allows types to be defined, not just declared. 1690 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 1691 SemaRef.Diag(DS->getLocStart(), 1692 SemaRef.getLangOpts().CPlusPlus14 1693 ? diag::warn_cxx11_compat_constexpr_type_definition 1694 : diag::ext_constexpr_type_definition) 1695 << isa<CXXConstructorDecl>(Dcl); 1696 continue; 1697 1698 case Decl::EnumConstant: 1699 case Decl::IndirectField: 1700 case Decl::ParmVar: 1701 // These can only appear with other declarations which are banned in 1702 // C++11 and permitted in C++1y, so ignore them. 1703 continue; 1704 1705 case Decl::Var: 1706 case Decl::Decomposition: { 1707 // C++1y [dcl.constexpr]p3 allows anything except: 1708 // a definition of a variable of non-literal type or of static or 1709 // thread storage duration or for which no initialization is performed. 1710 const auto *VD = cast<VarDecl>(DclIt); 1711 if (VD->isThisDeclarationADefinition()) { 1712 if (VD->isStaticLocal()) { 1713 SemaRef.Diag(VD->getLocation(), 1714 diag::err_constexpr_local_var_static) 1715 << isa<CXXConstructorDecl>(Dcl) 1716 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1717 return false; 1718 } 1719 if (!VD->getType()->isDependentType() && 1720 SemaRef.RequireLiteralType( 1721 VD->getLocation(), VD->getType(), 1722 diag::err_constexpr_local_var_non_literal_type, 1723 isa<CXXConstructorDecl>(Dcl))) 1724 return false; 1725 if (!VD->getType()->isDependentType() && 1726 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1727 SemaRef.Diag(VD->getLocation(), 1728 diag::err_constexpr_local_var_no_init) 1729 << isa<CXXConstructorDecl>(Dcl); 1730 return false; 1731 } 1732 } 1733 SemaRef.Diag(VD->getLocation(), 1734 SemaRef.getLangOpts().CPlusPlus14 1735 ? diag::warn_cxx11_compat_constexpr_local_var 1736 : diag::ext_constexpr_local_var) 1737 << isa<CXXConstructorDecl>(Dcl); 1738 continue; 1739 } 1740 1741 case Decl::NamespaceAlias: 1742 case Decl::Function: 1743 // These are disallowed in C++11 and permitted in C++1y. Allow them 1744 // everywhere as an extension. 1745 if (!Cxx1yLoc.isValid()) 1746 Cxx1yLoc = DS->getLocStart(); 1747 continue; 1748 1749 default: 1750 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1751 << isa<CXXConstructorDecl>(Dcl); 1752 return false; 1753 } 1754 } 1755 1756 return true; 1757 } 1758 1759 /// Check that the given field is initialized within a constexpr constructor. 1760 /// 1761 /// \param Dcl The constexpr constructor being checked. 1762 /// \param Field The field being checked. This may be a member of an anonymous 1763 /// struct or union nested within the class being checked. 1764 /// \param Inits All declarations, including anonymous struct/union members and 1765 /// indirect members, for which any initialization was provided. 1766 /// \param Diagnosed Set to true if an error is produced. 1767 static void CheckConstexprCtorInitializer(Sema &SemaRef, 1768 const FunctionDecl *Dcl, 1769 FieldDecl *Field, 1770 llvm::SmallSet<Decl*, 16> &Inits, 1771 bool &Diagnosed) { 1772 if (Field->isInvalidDecl()) 1773 return; 1774 1775 if (Field->isUnnamedBitfield()) 1776 return; 1777 1778 // Anonymous unions with no variant members and empty anonymous structs do not 1779 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1780 // indirect fields don't need initializing. 1781 if (Field->isAnonymousStructOrUnion() && 1782 (Field->getType()->isUnionType() 1783 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1784 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1785 return; 1786 1787 if (!Inits.count(Field)) { 1788 if (!Diagnosed) { 1789 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1790 Diagnosed = true; 1791 } 1792 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1793 } else if (Field->isAnonymousStructOrUnion()) { 1794 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1795 for (auto *I : RD->fields()) 1796 // If an anonymous union contains an anonymous struct of which any member 1797 // is initialized, all members must be initialized. 1798 if (!RD->isUnion() || Inits.count(I)) 1799 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1800 } 1801 } 1802 1803 /// Check the provided statement is allowed in a constexpr function 1804 /// definition. 1805 static bool 1806 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1807 SmallVectorImpl<SourceLocation> &ReturnStmts, 1808 SourceLocation &Cxx1yLoc) { 1809 // - its function-body shall be [...] a compound-statement that contains only 1810 switch (S->getStmtClass()) { 1811 case Stmt::NullStmtClass: 1812 // - null statements, 1813 return true; 1814 1815 case Stmt::DeclStmtClass: 1816 // - static_assert-declarations 1817 // - using-declarations, 1818 // - using-directives, 1819 // - typedef declarations and alias-declarations that do not define 1820 // classes or enumerations, 1821 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1822 return false; 1823 return true; 1824 1825 case Stmt::ReturnStmtClass: 1826 // - and exactly one return statement; 1827 if (isa<CXXConstructorDecl>(Dcl)) { 1828 // C++1y allows return statements in constexpr constructors. 1829 if (!Cxx1yLoc.isValid()) 1830 Cxx1yLoc = S->getLocStart(); 1831 return true; 1832 } 1833 1834 ReturnStmts.push_back(S->getLocStart()); 1835 return true; 1836 1837 case Stmt::CompoundStmtClass: { 1838 // C++1y allows compound-statements. 1839 if (!Cxx1yLoc.isValid()) 1840 Cxx1yLoc = S->getLocStart(); 1841 1842 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1843 for (auto *BodyIt : CompStmt->body()) { 1844 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1845 Cxx1yLoc)) 1846 return false; 1847 } 1848 return true; 1849 } 1850 1851 case Stmt::AttributedStmtClass: 1852 if (!Cxx1yLoc.isValid()) 1853 Cxx1yLoc = S->getLocStart(); 1854 return true; 1855 1856 case Stmt::IfStmtClass: { 1857 // C++1y allows if-statements. 1858 if (!Cxx1yLoc.isValid()) 1859 Cxx1yLoc = S->getLocStart(); 1860 1861 IfStmt *If = cast<IfStmt>(S); 1862 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1863 Cxx1yLoc)) 1864 return false; 1865 if (If->getElse() && 1866 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1867 Cxx1yLoc)) 1868 return false; 1869 return true; 1870 } 1871 1872 case Stmt::WhileStmtClass: 1873 case Stmt::DoStmtClass: 1874 case Stmt::ForStmtClass: 1875 case Stmt::CXXForRangeStmtClass: 1876 case Stmt::ContinueStmtClass: 1877 // C++1y allows all of these. We don't allow them as extensions in C++11, 1878 // because they don't make sense without variable mutation. 1879 if (!SemaRef.getLangOpts().CPlusPlus14) 1880 break; 1881 if (!Cxx1yLoc.isValid()) 1882 Cxx1yLoc = S->getLocStart(); 1883 for (Stmt *SubStmt : S->children()) 1884 if (SubStmt && 1885 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1886 Cxx1yLoc)) 1887 return false; 1888 return true; 1889 1890 case Stmt::SwitchStmtClass: 1891 case Stmt::CaseStmtClass: 1892 case Stmt::DefaultStmtClass: 1893 case Stmt::BreakStmtClass: 1894 // C++1y allows switch-statements, and since they don't need variable 1895 // mutation, we can reasonably allow them in C++11 as an extension. 1896 if (!Cxx1yLoc.isValid()) 1897 Cxx1yLoc = S->getLocStart(); 1898 for (Stmt *SubStmt : S->children()) 1899 if (SubStmt && 1900 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1901 Cxx1yLoc)) 1902 return false; 1903 return true; 1904 1905 default: 1906 if (!isa<Expr>(S)) 1907 break; 1908 1909 // C++1y allows expression-statements. 1910 if (!Cxx1yLoc.isValid()) 1911 Cxx1yLoc = S->getLocStart(); 1912 return true; 1913 } 1914 1915 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1916 << isa<CXXConstructorDecl>(Dcl); 1917 return false; 1918 } 1919 1920 /// Check the body for the given constexpr function declaration only contains 1921 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1922 /// 1923 /// \return true if the body is OK, false if we have diagnosed a problem. 1924 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1925 if (isa<CXXTryStmt>(Body)) { 1926 // C++11 [dcl.constexpr]p3: 1927 // The definition of a constexpr function shall satisfy the following 1928 // constraints: [...] 1929 // - its function-body shall be = delete, = default, or a 1930 // compound-statement 1931 // 1932 // C++11 [dcl.constexpr]p4: 1933 // In the definition of a constexpr constructor, [...] 1934 // - its function-body shall not be a function-try-block; 1935 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1936 << isa<CXXConstructorDecl>(Dcl); 1937 return false; 1938 } 1939 1940 SmallVector<SourceLocation, 4> ReturnStmts; 1941 1942 // - its function-body shall be [...] a compound-statement that contains only 1943 // [... list of cases ...] 1944 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1945 SourceLocation Cxx1yLoc; 1946 for (auto *BodyIt : CompBody->body()) { 1947 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1948 return false; 1949 } 1950 1951 if (Cxx1yLoc.isValid()) 1952 Diag(Cxx1yLoc, 1953 getLangOpts().CPlusPlus14 1954 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1955 : diag::ext_constexpr_body_invalid_stmt) 1956 << isa<CXXConstructorDecl>(Dcl); 1957 1958 if (const CXXConstructorDecl *Constructor 1959 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1960 const CXXRecordDecl *RD = Constructor->getParent(); 1961 // DR1359: 1962 // - every non-variant non-static data member and base class sub-object 1963 // shall be initialized; 1964 // DR1460: 1965 // - if the class is a union having variant members, exactly one of them 1966 // shall be initialized; 1967 if (RD->isUnion()) { 1968 if (Constructor->getNumCtorInitializers() == 0 && 1969 RD->hasVariantMembers()) { 1970 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1971 return false; 1972 } 1973 } else if (!Constructor->isDependentContext() && 1974 !Constructor->isDelegatingConstructor()) { 1975 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1976 1977 // Skip detailed checking if we have enough initializers, and we would 1978 // allow at most one initializer per member. 1979 bool AnyAnonStructUnionMembers = false; 1980 unsigned Fields = 0; 1981 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1982 E = RD->field_end(); I != E; ++I, ++Fields) { 1983 if (I->isAnonymousStructOrUnion()) { 1984 AnyAnonStructUnionMembers = true; 1985 break; 1986 } 1987 } 1988 // DR1460: 1989 // - if the class is a union-like class, but is not a union, for each of 1990 // its anonymous union members having variant members, exactly one of 1991 // them shall be initialized; 1992 if (AnyAnonStructUnionMembers || 1993 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1994 // Check initialization of non-static data members. Base classes are 1995 // always initialized so do not need to be checked. Dependent bases 1996 // might not have initializers in the member initializer list. 1997 llvm::SmallSet<Decl*, 16> Inits; 1998 for (const auto *I: Constructor->inits()) { 1999 if (FieldDecl *FD = I->getMember()) 2000 Inits.insert(FD); 2001 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2002 Inits.insert(ID->chain_begin(), ID->chain_end()); 2003 } 2004 2005 bool Diagnosed = false; 2006 for (auto *I : RD->fields()) 2007 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 2008 if (Diagnosed) 2009 return false; 2010 } 2011 } 2012 } else { 2013 if (ReturnStmts.empty()) { 2014 // C++1y doesn't require constexpr functions to contain a 'return' 2015 // statement. We still do, unless the return type might be void, because 2016 // otherwise if there's no return statement, the function cannot 2017 // be used in a core constant expression. 2018 bool OK = getLangOpts().CPlusPlus14 && 2019 (Dcl->getReturnType()->isVoidType() || 2020 Dcl->getReturnType()->isDependentType()); 2021 Diag(Dcl->getLocation(), 2022 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2023 : diag::err_constexpr_body_no_return); 2024 if (!OK) 2025 return false; 2026 } else if (ReturnStmts.size() > 1) { 2027 Diag(ReturnStmts.back(), 2028 getLangOpts().CPlusPlus14 2029 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2030 : diag::ext_constexpr_body_multiple_return); 2031 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2032 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 2033 } 2034 } 2035 2036 // C++11 [dcl.constexpr]p5: 2037 // if no function argument values exist such that the function invocation 2038 // substitution would produce a constant expression, the program is 2039 // ill-formed; no diagnostic required. 2040 // C++11 [dcl.constexpr]p3: 2041 // - every constructor call and implicit conversion used in initializing the 2042 // return value shall be one of those allowed in a constant expression. 2043 // C++11 [dcl.constexpr]p4: 2044 // - every constructor involved in initializing non-static data members and 2045 // base class sub-objects shall be a constexpr constructor. 2046 SmallVector<PartialDiagnosticAt, 8> Diags; 2047 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 2048 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 2049 << isa<CXXConstructorDecl>(Dcl); 2050 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2051 Diag(Diags[I].first, Diags[I].second); 2052 // Don't return false here: we allow this for compatibility in 2053 // system headers. 2054 } 2055 2056 return true; 2057 } 2058 2059 /// isCurrentClassName - Determine whether the identifier II is the 2060 /// name of the class type currently being defined. In the case of 2061 /// nested classes, this will only return true if II is the name of 2062 /// the innermost class. 2063 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 2064 const CXXScopeSpec *SS) { 2065 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2066 2067 CXXRecordDecl *CurDecl; 2068 if (SS && SS->isSet() && !SS->isInvalid()) { 2069 DeclContext *DC = computeDeclContext(*SS, true); 2070 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2071 } else 2072 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2073 2074 if (CurDecl && CurDecl->getIdentifier()) 2075 return &II == CurDecl->getIdentifier(); 2076 return false; 2077 } 2078 2079 /// \brief Determine whether the identifier II is a typo for the name of 2080 /// the class type currently being defined. If so, update it to the identifier 2081 /// that should have been used. 2082 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2083 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2084 2085 if (!getLangOpts().SpellChecking) 2086 return false; 2087 2088 CXXRecordDecl *CurDecl; 2089 if (SS && SS->isSet() && !SS->isInvalid()) { 2090 DeclContext *DC = computeDeclContext(*SS, true); 2091 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2092 } else 2093 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2094 2095 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2096 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2097 < II->getLength()) { 2098 II = CurDecl->getIdentifier(); 2099 return true; 2100 } 2101 2102 return false; 2103 } 2104 2105 /// \brief Determine whether the given class is a base class of the given 2106 /// class, including looking at dependent bases. 2107 static bool findCircularInheritance(const CXXRecordDecl *Class, 2108 const CXXRecordDecl *Current) { 2109 SmallVector<const CXXRecordDecl*, 8> Queue; 2110 2111 Class = Class->getCanonicalDecl(); 2112 while (true) { 2113 for (const auto &I : Current->bases()) { 2114 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2115 if (!Base) 2116 continue; 2117 2118 Base = Base->getDefinition(); 2119 if (!Base) 2120 continue; 2121 2122 if (Base->getCanonicalDecl() == Class) 2123 return true; 2124 2125 Queue.push_back(Base); 2126 } 2127 2128 if (Queue.empty()) 2129 return false; 2130 2131 Current = Queue.pop_back_val(); 2132 } 2133 2134 return false; 2135 } 2136 2137 /// \brief Check the validity of a C++ base class specifier. 2138 /// 2139 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2140 /// and returns NULL otherwise. 2141 CXXBaseSpecifier * 2142 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2143 SourceRange SpecifierRange, 2144 bool Virtual, AccessSpecifier Access, 2145 TypeSourceInfo *TInfo, 2146 SourceLocation EllipsisLoc) { 2147 QualType BaseType = TInfo->getType(); 2148 2149 // C++ [class.union]p1: 2150 // A union shall not have base classes. 2151 if (Class->isUnion()) { 2152 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2153 << SpecifierRange; 2154 return nullptr; 2155 } 2156 2157 if (EllipsisLoc.isValid() && 2158 !TInfo->getType()->containsUnexpandedParameterPack()) { 2159 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2160 << TInfo->getTypeLoc().getSourceRange(); 2161 EllipsisLoc = SourceLocation(); 2162 } 2163 2164 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2165 2166 if (BaseType->isDependentType()) { 2167 // Make sure that we don't have circular inheritance among our dependent 2168 // bases. For non-dependent bases, the check for completeness below handles 2169 // this. 2170 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2171 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2172 ((BaseDecl = BaseDecl->getDefinition()) && 2173 findCircularInheritance(Class, BaseDecl))) { 2174 Diag(BaseLoc, diag::err_circular_inheritance) 2175 << BaseType << Context.getTypeDeclType(Class); 2176 2177 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2178 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2179 << BaseType; 2180 2181 return nullptr; 2182 } 2183 } 2184 2185 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2186 Class->getTagKind() == TTK_Class, 2187 Access, TInfo, EllipsisLoc); 2188 } 2189 2190 // Base specifiers must be record types. 2191 if (!BaseType->isRecordType()) { 2192 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2193 return nullptr; 2194 } 2195 2196 // C++ [class.union]p1: 2197 // A union shall not be used as a base class. 2198 if (BaseType->isUnionType()) { 2199 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2200 return nullptr; 2201 } 2202 2203 // For the MS ABI, propagate DLL attributes to base class templates. 2204 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2205 if (Attr *ClassAttr = getDLLAttr(Class)) { 2206 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2207 BaseType->getAsCXXRecordDecl())) { 2208 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2209 BaseLoc); 2210 } 2211 } 2212 } 2213 2214 // C++ [class.derived]p2: 2215 // The class-name in a base-specifier shall not be an incompletely 2216 // defined class. 2217 if (RequireCompleteType(BaseLoc, BaseType, 2218 diag::err_incomplete_base_class, SpecifierRange)) { 2219 Class->setInvalidDecl(); 2220 return nullptr; 2221 } 2222 2223 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2224 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2225 assert(BaseDecl && "Record type has no declaration"); 2226 BaseDecl = BaseDecl->getDefinition(); 2227 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2228 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2229 assert(CXXBaseDecl && "Base type is not a C++ type"); 2230 2231 // A class which contains a flexible array member is not suitable for use as a 2232 // base class: 2233 // - If the layout determines that a base comes before another base, 2234 // the flexible array member would index into the subsequent base. 2235 // - If the layout determines that base comes before the derived class, 2236 // the flexible array member would index into the derived class. 2237 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2238 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2239 << CXXBaseDecl->getDeclName(); 2240 return nullptr; 2241 } 2242 2243 // C++ [class]p3: 2244 // If a class is marked final and it appears as a base-type-specifier in 2245 // base-clause, the program is ill-formed. 2246 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2247 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2248 << CXXBaseDecl->getDeclName() 2249 << FA->isSpelledAsSealed(); 2250 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2251 << CXXBaseDecl->getDeclName() << FA->getRange(); 2252 return nullptr; 2253 } 2254 2255 if (BaseDecl->isInvalidDecl()) 2256 Class->setInvalidDecl(); 2257 2258 // Create the base specifier. 2259 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2260 Class->getTagKind() == TTK_Class, 2261 Access, TInfo, EllipsisLoc); 2262 } 2263 2264 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2265 /// one entry in the base class list of a class specifier, for 2266 /// example: 2267 /// class foo : public bar, virtual private baz { 2268 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2269 BaseResult 2270 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2271 ParsedAttributes &Attributes, 2272 bool Virtual, AccessSpecifier Access, 2273 ParsedType basetype, SourceLocation BaseLoc, 2274 SourceLocation EllipsisLoc) { 2275 if (!classdecl) 2276 return true; 2277 2278 AdjustDeclIfTemplate(classdecl); 2279 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2280 if (!Class) 2281 return true; 2282 2283 // We haven't yet attached the base specifiers. 2284 Class->setIsParsingBaseSpecifiers(); 2285 2286 // We do not support any C++11 attributes on base-specifiers yet. 2287 // Diagnose any attributes we see. 2288 if (!Attributes.empty()) { 2289 for (AttributeList *Attr = Attributes.getList(); Attr; 2290 Attr = Attr->getNext()) { 2291 if (Attr->isInvalid() || 2292 Attr->getKind() == AttributeList::IgnoredAttribute) 2293 continue; 2294 Diag(Attr->getLoc(), 2295 Attr->getKind() == AttributeList::UnknownAttribute 2296 ? diag::warn_unknown_attribute_ignored 2297 : diag::err_base_specifier_attribute) 2298 << Attr->getName(); 2299 } 2300 } 2301 2302 TypeSourceInfo *TInfo = nullptr; 2303 GetTypeFromParser(basetype, &TInfo); 2304 2305 if (EllipsisLoc.isInvalid() && 2306 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2307 UPPC_BaseType)) 2308 return true; 2309 2310 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2311 Virtual, Access, TInfo, 2312 EllipsisLoc)) 2313 return BaseSpec; 2314 else 2315 Class->setInvalidDecl(); 2316 2317 return true; 2318 } 2319 2320 /// Use small set to collect indirect bases. As this is only used 2321 /// locally, there's no need to abstract the small size parameter. 2322 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2323 2324 /// \brief Recursively add the bases of Type. Don't add Type itself. 2325 static void 2326 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2327 const QualType &Type) 2328 { 2329 // Even though the incoming type is a base, it might not be 2330 // a class -- it could be a template parm, for instance. 2331 if (auto Rec = Type->getAs<RecordType>()) { 2332 auto Decl = Rec->getAsCXXRecordDecl(); 2333 2334 // Iterate over its bases. 2335 for (const auto &BaseSpec : Decl->bases()) { 2336 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2337 .getUnqualifiedType(); 2338 if (Set.insert(Base).second) 2339 // If we've not already seen it, recurse. 2340 NoteIndirectBases(Context, Set, Base); 2341 } 2342 } 2343 } 2344 2345 /// \brief Performs the actual work of attaching the given base class 2346 /// specifiers to a C++ class. 2347 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2348 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2349 if (Bases.empty()) 2350 return false; 2351 2352 // Used to keep track of which base types we have already seen, so 2353 // that we can properly diagnose redundant direct base types. Note 2354 // that the key is always the unqualified canonical type of the base 2355 // class. 2356 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2357 2358 // Used to track indirect bases so we can see if a direct base is 2359 // ambiguous. 2360 IndirectBaseSet IndirectBaseTypes; 2361 2362 // Copy non-redundant base specifiers into permanent storage. 2363 unsigned NumGoodBases = 0; 2364 bool Invalid = false; 2365 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2366 QualType NewBaseType 2367 = Context.getCanonicalType(Bases[idx]->getType()); 2368 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2369 2370 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2371 if (KnownBase) { 2372 // C++ [class.mi]p3: 2373 // A class shall not be specified as a direct base class of a 2374 // derived class more than once. 2375 Diag(Bases[idx]->getLocStart(), 2376 diag::err_duplicate_base_class) 2377 << KnownBase->getType() 2378 << Bases[idx]->getSourceRange(); 2379 2380 // Delete the duplicate base class specifier; we're going to 2381 // overwrite its pointer later. 2382 Context.Deallocate(Bases[idx]); 2383 2384 Invalid = true; 2385 } else { 2386 // Okay, add this new base class. 2387 KnownBase = Bases[idx]; 2388 Bases[NumGoodBases++] = Bases[idx]; 2389 2390 // Note this base's direct & indirect bases, if there could be ambiguity. 2391 if (Bases.size() > 1) 2392 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2393 2394 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2395 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2396 if (Class->isInterface() && 2397 (!RD->isInterfaceLike() || 2398 KnownBase->getAccessSpecifier() != AS_public)) { 2399 // The Microsoft extension __interface does not permit bases that 2400 // are not themselves public interfaces. 2401 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 2402 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 2403 << RD->getSourceRange(); 2404 Invalid = true; 2405 } 2406 if (RD->hasAttr<WeakAttr>()) 2407 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2408 } 2409 } 2410 } 2411 2412 // Attach the remaining base class specifiers to the derived class. 2413 Class->setBases(Bases.data(), NumGoodBases); 2414 2415 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2416 // Check whether this direct base is inaccessible due to ambiguity. 2417 QualType BaseType = Bases[idx]->getType(); 2418 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2419 .getUnqualifiedType(); 2420 2421 if (IndirectBaseTypes.count(CanonicalBase)) { 2422 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2423 /*DetectVirtual=*/true); 2424 bool found 2425 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2426 assert(found); 2427 (void)found; 2428 2429 if (Paths.isAmbiguous(CanonicalBase)) 2430 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 2431 << BaseType << getAmbiguousPathsDisplayString(Paths) 2432 << Bases[idx]->getSourceRange(); 2433 else 2434 assert(Bases[idx]->isVirtual()); 2435 } 2436 2437 // Delete the base class specifier, since its data has been copied 2438 // into the CXXRecordDecl. 2439 Context.Deallocate(Bases[idx]); 2440 } 2441 2442 return Invalid; 2443 } 2444 2445 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2446 /// class, after checking whether there are any duplicate base 2447 /// classes. 2448 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2449 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2450 if (!ClassDecl || Bases.empty()) 2451 return; 2452 2453 AdjustDeclIfTemplate(ClassDecl); 2454 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2455 } 2456 2457 /// \brief Determine whether the type \p Derived is a C++ class that is 2458 /// derived from the type \p Base. 2459 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2460 if (!getLangOpts().CPlusPlus) 2461 return false; 2462 2463 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2464 if (!DerivedRD) 2465 return false; 2466 2467 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2468 if (!BaseRD) 2469 return false; 2470 2471 // If either the base or the derived type is invalid, don't try to 2472 // check whether one is derived from the other. 2473 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2474 return false; 2475 2476 // FIXME: In a modules build, do we need the entire path to be visible for us 2477 // to be able to use the inheritance relationship? 2478 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2479 return false; 2480 2481 return DerivedRD->isDerivedFrom(BaseRD); 2482 } 2483 2484 /// \brief Determine whether the type \p Derived is a C++ class that is 2485 /// derived from the type \p Base. 2486 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2487 CXXBasePaths &Paths) { 2488 if (!getLangOpts().CPlusPlus) 2489 return false; 2490 2491 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2492 if (!DerivedRD) 2493 return false; 2494 2495 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2496 if (!BaseRD) 2497 return false; 2498 2499 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2500 return false; 2501 2502 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2503 } 2504 2505 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2506 CXXCastPath &BasePathArray) { 2507 assert(BasePathArray.empty() && "Base path array must be empty!"); 2508 assert(Paths.isRecordingPaths() && "Must record paths!"); 2509 2510 const CXXBasePath &Path = Paths.front(); 2511 2512 // We first go backward and check if we have a virtual base. 2513 // FIXME: It would be better if CXXBasePath had the base specifier for 2514 // the nearest virtual base. 2515 unsigned Start = 0; 2516 for (unsigned I = Path.size(); I != 0; --I) { 2517 if (Path[I - 1].Base->isVirtual()) { 2518 Start = I - 1; 2519 break; 2520 } 2521 } 2522 2523 // Now add all bases. 2524 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2525 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2526 } 2527 2528 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2529 /// conversion (where Derived and Base are class types) is 2530 /// well-formed, meaning that the conversion is unambiguous (and 2531 /// that all of the base classes are accessible). Returns true 2532 /// and emits a diagnostic if the code is ill-formed, returns false 2533 /// otherwise. Loc is the location where this routine should point to 2534 /// if there is an error, and Range is the source range to highlight 2535 /// if there is an error. 2536 /// 2537 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2538 /// diagnostic for the respective type of error will be suppressed, but the 2539 /// check for ill-formed code will still be performed. 2540 bool 2541 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2542 unsigned InaccessibleBaseID, 2543 unsigned AmbigiousBaseConvID, 2544 SourceLocation Loc, SourceRange Range, 2545 DeclarationName Name, 2546 CXXCastPath *BasePath, 2547 bool IgnoreAccess) { 2548 // First, determine whether the path from Derived to Base is 2549 // ambiguous. This is slightly more expensive than checking whether 2550 // the Derived to Base conversion exists, because here we need to 2551 // explore multiple paths to determine if there is an ambiguity. 2552 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2553 /*DetectVirtual=*/false); 2554 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2555 assert(DerivationOkay && 2556 "Can only be used with a derived-to-base conversion"); 2557 (void)DerivationOkay; 2558 2559 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 2560 if (!IgnoreAccess) { 2561 // Check that the base class can be accessed. 2562 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 2563 InaccessibleBaseID)) { 2564 case AR_inaccessible: 2565 return true; 2566 case AR_accessible: 2567 case AR_dependent: 2568 case AR_delayed: 2569 break; 2570 } 2571 } 2572 2573 // Build a base path if necessary. 2574 if (BasePath) 2575 BuildBasePathArray(Paths, *BasePath); 2576 return false; 2577 } 2578 2579 if (AmbigiousBaseConvID) { 2580 // We know that the derived-to-base conversion is ambiguous, and 2581 // we're going to produce a diagnostic. Perform the derived-to-base 2582 // search just one more time to compute all of the possible paths so 2583 // that we can print them out. This is more expensive than any of 2584 // the previous derived-to-base checks we've done, but at this point 2585 // performance isn't as much of an issue. 2586 Paths.clear(); 2587 Paths.setRecordingPaths(true); 2588 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2589 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2590 (void)StillOkay; 2591 2592 // Build up a textual representation of the ambiguous paths, e.g., 2593 // D -> B -> A, that will be used to illustrate the ambiguous 2594 // conversions in the diagnostic. We only print one of the paths 2595 // to each base class subobject. 2596 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2597 2598 Diag(Loc, AmbigiousBaseConvID) 2599 << Derived << Base << PathDisplayStr << Range << Name; 2600 } 2601 return true; 2602 } 2603 2604 bool 2605 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2606 SourceLocation Loc, SourceRange Range, 2607 CXXCastPath *BasePath, 2608 bool IgnoreAccess) { 2609 return CheckDerivedToBaseConversion( 2610 Derived, Base, diag::err_upcast_to_inaccessible_base, 2611 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2612 BasePath, IgnoreAccess); 2613 } 2614 2615 2616 /// @brief Builds a string representing ambiguous paths from a 2617 /// specific derived class to different subobjects of the same base 2618 /// class. 2619 /// 2620 /// This function builds a string that can be used in error messages 2621 /// to show the different paths that one can take through the 2622 /// inheritance hierarchy to go from the derived class to different 2623 /// subobjects of a base class. The result looks something like this: 2624 /// @code 2625 /// struct D -> struct B -> struct A 2626 /// struct D -> struct C -> struct A 2627 /// @endcode 2628 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2629 std::string PathDisplayStr; 2630 std::set<unsigned> DisplayedPaths; 2631 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2632 Path != Paths.end(); ++Path) { 2633 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2634 // We haven't displayed a path to this particular base 2635 // class subobject yet. 2636 PathDisplayStr += "\n "; 2637 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2638 for (CXXBasePath::const_iterator Element = Path->begin(); 2639 Element != Path->end(); ++Element) 2640 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2641 } 2642 } 2643 2644 return PathDisplayStr; 2645 } 2646 2647 //===----------------------------------------------------------------------===// 2648 // C++ class member Handling 2649 //===----------------------------------------------------------------------===// 2650 2651 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2652 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 2653 SourceLocation ASLoc, 2654 SourceLocation ColonLoc, 2655 AttributeList *Attrs) { 2656 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2657 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2658 ASLoc, ColonLoc); 2659 CurContext->addHiddenDecl(ASDecl); 2660 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2661 } 2662 2663 /// CheckOverrideControl - Check C++11 override control semantics. 2664 void Sema::CheckOverrideControl(NamedDecl *D) { 2665 if (D->isInvalidDecl()) 2666 return; 2667 2668 // We only care about "override" and "final" declarations. 2669 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2670 return; 2671 2672 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2673 2674 // We can't check dependent instance methods. 2675 if (MD && MD->isInstance() && 2676 (MD->getParent()->hasAnyDependentBases() || 2677 MD->getType()->isDependentType())) 2678 return; 2679 2680 if (MD && !MD->isVirtual()) { 2681 // If we have a non-virtual method, check if if hides a virtual method. 2682 // (In that case, it's most likely the method has the wrong type.) 2683 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2684 FindHiddenVirtualMethods(MD, OverloadedMethods); 2685 2686 if (!OverloadedMethods.empty()) { 2687 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2688 Diag(OA->getLocation(), 2689 diag::override_keyword_hides_virtual_member_function) 2690 << "override" << (OverloadedMethods.size() > 1); 2691 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2692 Diag(FA->getLocation(), 2693 diag::override_keyword_hides_virtual_member_function) 2694 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2695 << (OverloadedMethods.size() > 1); 2696 } 2697 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2698 MD->setInvalidDecl(); 2699 return; 2700 } 2701 // Fall through into the general case diagnostic. 2702 // FIXME: We might want to attempt typo correction here. 2703 } 2704 2705 if (!MD || !MD->isVirtual()) { 2706 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2707 Diag(OA->getLocation(), 2708 diag::override_keyword_only_allowed_on_virtual_member_functions) 2709 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2710 D->dropAttr<OverrideAttr>(); 2711 } 2712 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2713 Diag(FA->getLocation(), 2714 diag::override_keyword_only_allowed_on_virtual_member_functions) 2715 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2716 << FixItHint::CreateRemoval(FA->getLocation()); 2717 D->dropAttr<FinalAttr>(); 2718 } 2719 return; 2720 } 2721 2722 // C++11 [class.virtual]p5: 2723 // If a function is marked with the virt-specifier override and 2724 // does not override a member function of a base class, the program is 2725 // ill-formed. 2726 bool HasOverriddenMethods = 2727 MD->begin_overridden_methods() != MD->end_overridden_methods(); 2728 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2729 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2730 << MD->getDeclName(); 2731 } 2732 2733 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2734 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2735 return; 2736 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2737 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 2738 return; 2739 2740 SourceLocation Loc = MD->getLocation(); 2741 SourceLocation SpellingLoc = Loc; 2742 if (getSourceManager().isMacroArgExpansion(Loc)) 2743 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 2744 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2745 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2746 return; 2747 2748 if (MD->size_overridden_methods() > 0) { 2749 unsigned DiagID = isa<CXXDestructorDecl>(MD) 2750 ? diag::warn_destructor_marked_not_override_overriding 2751 : diag::warn_function_marked_not_override_overriding; 2752 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 2753 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2754 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2755 } 2756 } 2757 2758 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2759 /// function overrides a virtual member function marked 'final', according to 2760 /// C++11 [class.virtual]p4. 2761 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2762 const CXXMethodDecl *Old) { 2763 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2764 if (!FA) 2765 return false; 2766 2767 Diag(New->getLocation(), diag::err_final_function_overridden) 2768 << New->getDeclName() 2769 << FA->isSpelledAsSealed(); 2770 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2771 return true; 2772 } 2773 2774 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2775 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2776 // FIXME: Destruction of ObjC lifetime types has side-effects. 2777 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2778 return !RD->isCompleteDefinition() || 2779 !RD->hasTrivialDefaultConstructor() || 2780 !RD->hasTrivialDestructor(); 2781 return false; 2782 } 2783 2784 static AttributeList *getMSPropertyAttr(AttributeList *list) { 2785 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 2786 if (it->isDeclspecPropertyAttribute()) 2787 return it; 2788 return nullptr; 2789 } 2790 2791 // Check if there is a field shadowing. 2792 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 2793 DeclarationName FieldName, 2794 const CXXRecordDecl *RD) { 2795 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 2796 return; 2797 2798 // To record a shadowed field in a base 2799 std::map<CXXRecordDecl*, NamedDecl*> Bases; 2800 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 2801 CXXBasePath &Path) { 2802 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 2803 // Record an ambiguous path directly 2804 if (Bases.find(Base) != Bases.end()) 2805 return true; 2806 for (const auto Field : Base->lookup(FieldName)) { 2807 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 2808 Field->getAccess() != AS_private) { 2809 assert(Field->getAccess() != AS_none); 2810 assert(Bases.find(Base) == Bases.end()); 2811 Bases[Base] = Field; 2812 return true; 2813 } 2814 } 2815 return false; 2816 }; 2817 2818 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2819 /*DetectVirtual=*/true); 2820 if (!RD->lookupInBases(FieldShadowed, Paths)) 2821 return; 2822 2823 for (const auto &P : Paths) { 2824 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 2825 auto It = Bases.find(Base); 2826 // Skip duplicated bases 2827 if (It == Bases.end()) 2828 continue; 2829 auto BaseField = It->second; 2830 assert(BaseField->getAccess() != AS_private); 2831 if (AS_none != 2832 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 2833 Diag(Loc, diag::warn_shadow_field) 2834 << FieldName.getAsString() << RD->getName() << Base->getName(); 2835 Diag(BaseField->getLocation(), diag::note_shadow_field); 2836 Bases.erase(It); 2837 } 2838 } 2839 } 2840 2841 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2842 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2843 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2844 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2845 /// present (but parsing it has been deferred). 2846 NamedDecl * 2847 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2848 MultiTemplateParamsArg TemplateParameterLists, 2849 Expr *BW, const VirtSpecifiers &VS, 2850 InClassInitStyle InitStyle) { 2851 const DeclSpec &DS = D.getDeclSpec(); 2852 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2853 DeclarationName Name = NameInfo.getName(); 2854 SourceLocation Loc = NameInfo.getLoc(); 2855 2856 // For anonymous bitfields, the location should point to the type. 2857 if (Loc.isInvalid()) 2858 Loc = D.getLocStart(); 2859 2860 Expr *BitWidth = static_cast<Expr*>(BW); 2861 2862 assert(isa<CXXRecordDecl>(CurContext)); 2863 assert(!DS.isFriendSpecified()); 2864 2865 bool isFunc = D.isDeclarationOfFunction(); 2866 AttributeList *MSPropertyAttr = 2867 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2868 2869 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2870 // The Microsoft extension __interface only permits public member functions 2871 // and prohibits constructors, destructors, operators, non-public member 2872 // functions, static methods and data members. 2873 unsigned InvalidDecl; 2874 bool ShowDeclName = true; 2875 if (!isFunc && 2876 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 2877 InvalidDecl = 0; 2878 else if (!isFunc) 2879 InvalidDecl = 1; 2880 else if (AS != AS_public) 2881 InvalidDecl = 2; 2882 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2883 InvalidDecl = 3; 2884 else switch (Name.getNameKind()) { 2885 case DeclarationName::CXXConstructorName: 2886 InvalidDecl = 4; 2887 ShowDeclName = false; 2888 break; 2889 2890 case DeclarationName::CXXDestructorName: 2891 InvalidDecl = 5; 2892 ShowDeclName = false; 2893 break; 2894 2895 case DeclarationName::CXXOperatorName: 2896 case DeclarationName::CXXConversionFunctionName: 2897 InvalidDecl = 6; 2898 break; 2899 2900 default: 2901 InvalidDecl = 0; 2902 break; 2903 } 2904 2905 if (InvalidDecl) { 2906 if (ShowDeclName) 2907 Diag(Loc, diag::err_invalid_member_in_interface) 2908 << (InvalidDecl-1) << Name; 2909 else 2910 Diag(Loc, diag::err_invalid_member_in_interface) 2911 << (InvalidDecl-1) << ""; 2912 return nullptr; 2913 } 2914 } 2915 2916 // C++ 9.2p6: A member shall not be declared to have automatic storage 2917 // duration (auto, register) or with the extern storage-class-specifier. 2918 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2919 // data members and cannot be applied to names declared const or static, 2920 // and cannot be applied to reference members. 2921 switch (DS.getStorageClassSpec()) { 2922 case DeclSpec::SCS_unspecified: 2923 case DeclSpec::SCS_typedef: 2924 case DeclSpec::SCS_static: 2925 break; 2926 case DeclSpec::SCS_mutable: 2927 if (isFunc) { 2928 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2929 2930 // FIXME: It would be nicer if the keyword was ignored only for this 2931 // declarator. Otherwise we could get follow-up errors. 2932 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2933 } 2934 break; 2935 default: 2936 Diag(DS.getStorageClassSpecLoc(), 2937 diag::err_storageclass_invalid_for_member); 2938 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2939 break; 2940 } 2941 2942 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2943 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2944 !isFunc); 2945 2946 if (DS.isConstexprSpecified() && isInstField) { 2947 SemaDiagnosticBuilder B = 2948 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2949 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2950 if (InitStyle == ICIS_NoInit) { 2951 B << 0 << 0; 2952 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2953 B << FixItHint::CreateRemoval(ConstexprLoc); 2954 else { 2955 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2956 D.getMutableDeclSpec().ClearConstexprSpec(); 2957 const char *PrevSpec; 2958 unsigned DiagID; 2959 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2960 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2961 (void)Failed; 2962 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2963 } 2964 } else { 2965 B << 1; 2966 const char *PrevSpec; 2967 unsigned DiagID; 2968 if (D.getMutableDeclSpec().SetStorageClassSpec( 2969 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2970 Context.getPrintingPolicy())) { 2971 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2972 "This is the only DeclSpec that should fail to be applied"); 2973 B << 1; 2974 } else { 2975 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2976 isInstField = false; 2977 } 2978 } 2979 } 2980 2981 NamedDecl *Member; 2982 if (isInstField) { 2983 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2984 2985 // Data members must have identifiers for names. 2986 if (!Name.isIdentifier()) { 2987 Diag(Loc, diag::err_bad_variable_name) 2988 << Name; 2989 return nullptr; 2990 } 2991 2992 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2993 2994 // Member field could not be with "template" keyword. 2995 // So TemplateParameterLists should be empty in this case. 2996 if (TemplateParameterLists.size()) { 2997 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2998 if (TemplateParams->size()) { 2999 // There is no such thing as a member field template. 3000 Diag(D.getIdentifierLoc(), diag::err_template_member) 3001 << II 3002 << SourceRange(TemplateParams->getTemplateLoc(), 3003 TemplateParams->getRAngleLoc()); 3004 } else { 3005 // There is an extraneous 'template<>' for this member. 3006 Diag(TemplateParams->getTemplateLoc(), 3007 diag::err_template_member_noparams) 3008 << II 3009 << SourceRange(TemplateParams->getTemplateLoc(), 3010 TemplateParams->getRAngleLoc()); 3011 } 3012 return nullptr; 3013 } 3014 3015 if (SS.isSet() && !SS.isInvalid()) { 3016 // The user provided a superfluous scope specifier inside a class 3017 // definition: 3018 // 3019 // class X { 3020 // int X::member; 3021 // }; 3022 if (DeclContext *DC = computeDeclContext(SS, false)) 3023 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 3024 else 3025 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3026 << Name << SS.getRange(); 3027 3028 SS.clear(); 3029 } 3030 3031 if (MSPropertyAttr) { 3032 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3033 BitWidth, InitStyle, AS, MSPropertyAttr); 3034 if (!Member) 3035 return nullptr; 3036 isInstField = false; 3037 } else { 3038 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3039 BitWidth, InitStyle, AS); 3040 if (!Member) 3041 return nullptr; 3042 } 3043 3044 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3045 } else { 3046 Member = HandleDeclarator(S, D, TemplateParameterLists); 3047 if (!Member) 3048 return nullptr; 3049 3050 // Non-instance-fields can't have a bitfield. 3051 if (BitWidth) { 3052 if (Member->isInvalidDecl()) { 3053 // don't emit another diagnostic. 3054 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3055 // C++ 9.6p3: A bit-field shall not be a static member. 3056 // "static member 'A' cannot be a bit-field" 3057 Diag(Loc, diag::err_static_not_bitfield) 3058 << Name << BitWidth->getSourceRange(); 3059 } else if (isa<TypedefDecl>(Member)) { 3060 // "typedef member 'x' cannot be a bit-field" 3061 Diag(Loc, diag::err_typedef_not_bitfield) 3062 << Name << BitWidth->getSourceRange(); 3063 } else { 3064 // A function typedef ("typedef int f(); f a;"). 3065 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3066 Diag(Loc, diag::err_not_integral_type_bitfield) 3067 << Name << cast<ValueDecl>(Member)->getType() 3068 << BitWidth->getSourceRange(); 3069 } 3070 3071 BitWidth = nullptr; 3072 Member->setInvalidDecl(); 3073 } 3074 3075 Member->setAccess(AS); 3076 3077 // If we have declared a member function template or static data member 3078 // template, set the access of the templated declaration as well. 3079 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3080 FunTmpl->getTemplatedDecl()->setAccess(AS); 3081 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3082 VarTmpl->getTemplatedDecl()->setAccess(AS); 3083 } 3084 3085 if (VS.isOverrideSpecified()) 3086 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3087 if (VS.isFinalSpecified()) 3088 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3089 VS.isFinalSpelledSealed())); 3090 3091 if (VS.getLastLocation().isValid()) { 3092 // Update the end location of a method that has a virt-specifiers. 3093 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3094 MD->setRangeEnd(VS.getLastLocation()); 3095 } 3096 3097 CheckOverrideControl(Member); 3098 3099 assert((Name || isInstField) && "No identifier for non-field ?"); 3100 3101 if (isInstField) { 3102 FieldDecl *FD = cast<FieldDecl>(Member); 3103 FieldCollector->Add(FD); 3104 3105 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3106 // Remember all explicit private FieldDecls that have a name, no side 3107 // effects and are not part of a dependent type declaration. 3108 if (!FD->isImplicit() && FD->getDeclName() && 3109 FD->getAccess() == AS_private && 3110 !FD->hasAttr<UnusedAttr>() && 3111 !FD->getParent()->isDependentContext() && 3112 !InitializationHasSideEffects(*FD)) 3113 UnusedPrivateFields.insert(FD); 3114 } 3115 } 3116 3117 return Member; 3118 } 3119 3120 namespace { 3121 class UninitializedFieldVisitor 3122 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3123 Sema &S; 3124 // List of Decls to generate a warning on. Also remove Decls that become 3125 // initialized. 3126 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3127 // List of base classes of the record. Classes are removed after their 3128 // initializers. 3129 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3130 // Vector of decls to be removed from the Decl set prior to visiting the 3131 // nodes. These Decls may have been initialized in the prior initializer. 3132 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3133 // If non-null, add a note to the warning pointing back to the constructor. 3134 const CXXConstructorDecl *Constructor; 3135 // Variables to hold state when processing an initializer list. When 3136 // InitList is true, special case initialization of FieldDecls matching 3137 // InitListFieldDecl. 3138 bool InitList; 3139 FieldDecl *InitListFieldDecl; 3140 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3141 3142 public: 3143 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3144 UninitializedFieldVisitor(Sema &S, 3145 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3146 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3147 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3148 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3149 3150 // Returns true if the use of ME is not an uninitialized use. 3151 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3152 bool CheckReferenceOnly) { 3153 llvm::SmallVector<FieldDecl*, 4> Fields; 3154 bool ReferenceField = false; 3155 while (ME) { 3156 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3157 if (!FD) 3158 return false; 3159 Fields.push_back(FD); 3160 if (FD->getType()->isReferenceType()) 3161 ReferenceField = true; 3162 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3163 } 3164 3165 // Binding a reference to an unintialized field is not an 3166 // uninitialized use. 3167 if (CheckReferenceOnly && !ReferenceField) 3168 return true; 3169 3170 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3171 // Discard the first field since it is the field decl that is being 3172 // initialized. 3173 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3174 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3175 } 3176 3177 for (auto UsedIter = UsedFieldIndex.begin(), 3178 UsedEnd = UsedFieldIndex.end(), 3179 OrigIter = InitFieldIndex.begin(), 3180 OrigEnd = InitFieldIndex.end(); 3181 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3182 if (*UsedIter < *OrigIter) 3183 return true; 3184 if (*UsedIter > *OrigIter) 3185 break; 3186 } 3187 3188 return false; 3189 } 3190 3191 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3192 bool AddressOf) { 3193 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3194 return; 3195 3196 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3197 // or union. 3198 MemberExpr *FieldME = ME; 3199 3200 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3201 3202 Expr *Base = ME; 3203 while (MemberExpr *SubME = 3204 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3205 3206 if (isa<VarDecl>(SubME->getMemberDecl())) 3207 return; 3208 3209 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3210 if (!FD->isAnonymousStructOrUnion()) 3211 FieldME = SubME; 3212 3213 if (!FieldME->getType().isPODType(S.Context)) 3214 AllPODFields = false; 3215 3216 Base = SubME->getBase(); 3217 } 3218 3219 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3220 return; 3221 3222 if (AddressOf && AllPODFields) 3223 return; 3224 3225 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3226 3227 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3228 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3229 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3230 } 3231 3232 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3233 QualType T = BaseCast->getType(); 3234 if (T->isPointerType() && 3235 BaseClasses.count(T->getPointeeType())) { 3236 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3237 << T->getPointeeType() << FoundVD; 3238 } 3239 } 3240 } 3241 3242 if (!Decls.count(FoundVD)) 3243 return; 3244 3245 const bool IsReference = FoundVD->getType()->isReferenceType(); 3246 3247 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3248 // Special checking for initializer lists. 3249 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3250 return; 3251 } 3252 } else { 3253 // Prevent double warnings on use of unbounded references. 3254 if (CheckReferenceOnly && !IsReference) 3255 return; 3256 } 3257 3258 unsigned diag = IsReference 3259 ? diag::warn_reference_field_is_uninit 3260 : diag::warn_field_is_uninit; 3261 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3262 if (Constructor) 3263 S.Diag(Constructor->getLocation(), 3264 diag::note_uninit_in_this_constructor) 3265 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3266 3267 } 3268 3269 void HandleValue(Expr *E, bool AddressOf) { 3270 E = E->IgnoreParens(); 3271 3272 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3273 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3274 AddressOf /*AddressOf*/); 3275 return; 3276 } 3277 3278 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3279 Visit(CO->getCond()); 3280 HandleValue(CO->getTrueExpr(), AddressOf); 3281 HandleValue(CO->getFalseExpr(), AddressOf); 3282 return; 3283 } 3284 3285 if (BinaryConditionalOperator *BCO = 3286 dyn_cast<BinaryConditionalOperator>(E)) { 3287 Visit(BCO->getCond()); 3288 HandleValue(BCO->getFalseExpr(), AddressOf); 3289 return; 3290 } 3291 3292 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3293 HandleValue(OVE->getSourceExpr(), AddressOf); 3294 return; 3295 } 3296 3297 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3298 switch (BO->getOpcode()) { 3299 default: 3300 break; 3301 case(BO_PtrMemD): 3302 case(BO_PtrMemI): 3303 HandleValue(BO->getLHS(), AddressOf); 3304 Visit(BO->getRHS()); 3305 return; 3306 case(BO_Comma): 3307 Visit(BO->getLHS()); 3308 HandleValue(BO->getRHS(), AddressOf); 3309 return; 3310 } 3311 } 3312 3313 Visit(E); 3314 } 3315 3316 void CheckInitListExpr(InitListExpr *ILE) { 3317 InitFieldIndex.push_back(0); 3318 for (auto Child : ILE->children()) { 3319 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3320 CheckInitListExpr(SubList); 3321 } else { 3322 Visit(Child); 3323 } 3324 ++InitFieldIndex.back(); 3325 } 3326 InitFieldIndex.pop_back(); 3327 } 3328 3329 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3330 FieldDecl *Field, const Type *BaseClass) { 3331 // Remove Decls that may have been initialized in the previous 3332 // initializer. 3333 for (ValueDecl* VD : DeclsToRemove) 3334 Decls.erase(VD); 3335 DeclsToRemove.clear(); 3336 3337 Constructor = FieldConstructor; 3338 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3339 3340 if (ILE && Field) { 3341 InitList = true; 3342 InitListFieldDecl = Field; 3343 InitFieldIndex.clear(); 3344 CheckInitListExpr(ILE); 3345 } else { 3346 InitList = false; 3347 Visit(E); 3348 } 3349 3350 if (Field) 3351 Decls.erase(Field); 3352 if (BaseClass) 3353 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3354 } 3355 3356 void VisitMemberExpr(MemberExpr *ME) { 3357 // All uses of unbounded reference fields will warn. 3358 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3359 } 3360 3361 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3362 if (E->getCastKind() == CK_LValueToRValue) { 3363 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3364 return; 3365 } 3366 3367 Inherited::VisitImplicitCastExpr(E); 3368 } 3369 3370 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3371 if (E->getConstructor()->isCopyConstructor()) { 3372 Expr *ArgExpr = E->getArg(0); 3373 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3374 if (ILE->getNumInits() == 1) 3375 ArgExpr = ILE->getInit(0); 3376 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3377 if (ICE->getCastKind() == CK_NoOp) 3378 ArgExpr = ICE->getSubExpr(); 3379 HandleValue(ArgExpr, false /*AddressOf*/); 3380 return; 3381 } 3382 Inherited::VisitCXXConstructExpr(E); 3383 } 3384 3385 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3386 Expr *Callee = E->getCallee(); 3387 if (isa<MemberExpr>(Callee)) { 3388 HandleValue(Callee, false /*AddressOf*/); 3389 for (auto Arg : E->arguments()) 3390 Visit(Arg); 3391 return; 3392 } 3393 3394 Inherited::VisitCXXMemberCallExpr(E); 3395 } 3396 3397 void VisitCallExpr(CallExpr *E) { 3398 // Treat std::move as a use. 3399 if (E->isCallToStdMove()) { 3400 HandleValue(E->getArg(0), /*AddressOf=*/false); 3401 return; 3402 } 3403 3404 Inherited::VisitCallExpr(E); 3405 } 3406 3407 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3408 Expr *Callee = E->getCallee(); 3409 3410 if (isa<UnresolvedLookupExpr>(Callee)) 3411 return Inherited::VisitCXXOperatorCallExpr(E); 3412 3413 Visit(Callee); 3414 for (auto Arg : E->arguments()) 3415 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3416 } 3417 3418 void VisitBinaryOperator(BinaryOperator *E) { 3419 // If a field assignment is detected, remove the field from the 3420 // uninitiailized field set. 3421 if (E->getOpcode() == BO_Assign) 3422 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3423 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3424 if (!FD->getType()->isReferenceType()) 3425 DeclsToRemove.push_back(FD); 3426 3427 if (E->isCompoundAssignmentOp()) { 3428 HandleValue(E->getLHS(), false /*AddressOf*/); 3429 Visit(E->getRHS()); 3430 return; 3431 } 3432 3433 Inherited::VisitBinaryOperator(E); 3434 } 3435 3436 void VisitUnaryOperator(UnaryOperator *E) { 3437 if (E->isIncrementDecrementOp()) { 3438 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3439 return; 3440 } 3441 if (E->getOpcode() == UO_AddrOf) { 3442 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3443 HandleValue(ME->getBase(), true /*AddressOf*/); 3444 return; 3445 } 3446 } 3447 3448 Inherited::VisitUnaryOperator(E); 3449 } 3450 }; 3451 3452 // Diagnose value-uses of fields to initialize themselves, e.g. 3453 // foo(foo) 3454 // where foo is not also a parameter to the constructor. 3455 // Also diagnose across field uninitialized use such as 3456 // x(y), y(x) 3457 // TODO: implement -Wuninitialized and fold this into that framework. 3458 static void DiagnoseUninitializedFields( 3459 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3460 3461 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3462 Constructor->getLocation())) { 3463 return; 3464 } 3465 3466 if (Constructor->isInvalidDecl()) 3467 return; 3468 3469 const CXXRecordDecl *RD = Constructor->getParent(); 3470 3471 if (RD->getDescribedClassTemplate()) 3472 return; 3473 3474 // Holds fields that are uninitialized. 3475 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3476 3477 // At the beginning, all fields are uninitialized. 3478 for (auto *I : RD->decls()) { 3479 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3480 UninitializedFields.insert(FD); 3481 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3482 UninitializedFields.insert(IFD->getAnonField()); 3483 } 3484 } 3485 3486 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3487 for (auto I : RD->bases()) 3488 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3489 3490 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3491 return; 3492 3493 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3494 UninitializedFields, 3495 UninitializedBaseClasses); 3496 3497 for (const auto *FieldInit : Constructor->inits()) { 3498 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3499 break; 3500 3501 Expr *InitExpr = FieldInit->getInit(); 3502 if (!InitExpr) 3503 continue; 3504 3505 if (CXXDefaultInitExpr *Default = 3506 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3507 InitExpr = Default->getExpr(); 3508 if (!InitExpr) 3509 continue; 3510 // In class initializers will point to the constructor. 3511 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3512 FieldInit->getAnyMember(), 3513 FieldInit->getBaseClass()); 3514 } else { 3515 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3516 FieldInit->getAnyMember(), 3517 FieldInit->getBaseClass()); 3518 } 3519 } 3520 } 3521 } // namespace 3522 3523 /// \brief Enter a new C++ default initializer scope. After calling this, the 3524 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3525 /// parsing or instantiating the initializer failed. 3526 void Sema::ActOnStartCXXInClassMemberInitializer() { 3527 // Create a synthetic function scope to represent the call to the constructor 3528 // that notionally surrounds a use of this initializer. 3529 PushFunctionScope(); 3530 } 3531 3532 /// \brief This is invoked after parsing an in-class initializer for a 3533 /// non-static C++ class member, and after instantiating an in-class initializer 3534 /// in a class template. Such actions are deferred until the class is complete. 3535 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3536 SourceLocation InitLoc, 3537 Expr *InitExpr) { 3538 // Pop the notional constructor scope we created earlier. 3539 PopFunctionScopeInfo(nullptr, D); 3540 3541 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3542 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3543 "must set init style when field is created"); 3544 3545 if (!InitExpr) { 3546 D->setInvalidDecl(); 3547 if (FD) 3548 FD->removeInClassInitializer(); 3549 return; 3550 } 3551 3552 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3553 FD->setInvalidDecl(); 3554 FD->removeInClassInitializer(); 3555 return; 3556 } 3557 3558 ExprResult Init = InitExpr; 3559 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3560 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 3561 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 3562 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 3563 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 3564 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3565 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3566 if (Init.isInvalid()) { 3567 FD->setInvalidDecl(); 3568 return; 3569 } 3570 } 3571 3572 // C++11 [class.base.init]p7: 3573 // The initialization of each base and member constitutes a 3574 // full-expression. 3575 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 3576 if (Init.isInvalid()) { 3577 FD->setInvalidDecl(); 3578 return; 3579 } 3580 3581 InitExpr = Init.get(); 3582 3583 FD->setInClassInitializer(InitExpr); 3584 } 3585 3586 /// \brief Find the direct and/or virtual base specifiers that 3587 /// correspond to the given base type, for use in base initialization 3588 /// within a constructor. 3589 static bool FindBaseInitializer(Sema &SemaRef, 3590 CXXRecordDecl *ClassDecl, 3591 QualType BaseType, 3592 const CXXBaseSpecifier *&DirectBaseSpec, 3593 const CXXBaseSpecifier *&VirtualBaseSpec) { 3594 // First, check for a direct base class. 3595 DirectBaseSpec = nullptr; 3596 for (const auto &Base : ClassDecl->bases()) { 3597 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3598 // We found a direct base of this type. That's what we're 3599 // initializing. 3600 DirectBaseSpec = &Base; 3601 break; 3602 } 3603 } 3604 3605 // Check for a virtual base class. 3606 // FIXME: We might be able to short-circuit this if we know in advance that 3607 // there are no virtual bases. 3608 VirtualBaseSpec = nullptr; 3609 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3610 // We haven't found a base yet; search the class hierarchy for a 3611 // virtual base class. 3612 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3613 /*DetectVirtual=*/false); 3614 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3615 SemaRef.Context.getTypeDeclType(ClassDecl), 3616 BaseType, Paths)) { 3617 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3618 Path != Paths.end(); ++Path) { 3619 if (Path->back().Base->isVirtual()) { 3620 VirtualBaseSpec = Path->back().Base; 3621 break; 3622 } 3623 } 3624 } 3625 } 3626 3627 return DirectBaseSpec || VirtualBaseSpec; 3628 } 3629 3630 /// \brief Handle a C++ member initializer using braced-init-list syntax. 3631 MemInitResult 3632 Sema::ActOnMemInitializer(Decl *ConstructorD, 3633 Scope *S, 3634 CXXScopeSpec &SS, 3635 IdentifierInfo *MemberOrBase, 3636 ParsedType TemplateTypeTy, 3637 const DeclSpec &DS, 3638 SourceLocation IdLoc, 3639 Expr *InitList, 3640 SourceLocation EllipsisLoc) { 3641 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3642 DS, IdLoc, InitList, 3643 EllipsisLoc); 3644 } 3645 3646 /// \brief Handle a C++ member initializer using parentheses syntax. 3647 MemInitResult 3648 Sema::ActOnMemInitializer(Decl *ConstructorD, 3649 Scope *S, 3650 CXXScopeSpec &SS, 3651 IdentifierInfo *MemberOrBase, 3652 ParsedType TemplateTypeTy, 3653 const DeclSpec &DS, 3654 SourceLocation IdLoc, 3655 SourceLocation LParenLoc, 3656 ArrayRef<Expr *> Args, 3657 SourceLocation RParenLoc, 3658 SourceLocation EllipsisLoc) { 3659 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 3660 Args, RParenLoc); 3661 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3662 DS, IdLoc, List, EllipsisLoc); 3663 } 3664 3665 namespace { 3666 3667 // Callback to only accept typo corrections that can be a valid C++ member 3668 // intializer: either a non-static field member or a base class. 3669 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 3670 public: 3671 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3672 : ClassDecl(ClassDecl) {} 3673 3674 bool ValidateCandidate(const TypoCorrection &candidate) override { 3675 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3676 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3677 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3678 return isa<TypeDecl>(ND); 3679 } 3680 return false; 3681 } 3682 3683 private: 3684 CXXRecordDecl *ClassDecl; 3685 }; 3686 3687 } 3688 3689 /// \brief Handle a C++ member initializer. 3690 MemInitResult 3691 Sema::BuildMemInitializer(Decl *ConstructorD, 3692 Scope *S, 3693 CXXScopeSpec &SS, 3694 IdentifierInfo *MemberOrBase, 3695 ParsedType TemplateTypeTy, 3696 const DeclSpec &DS, 3697 SourceLocation IdLoc, 3698 Expr *Init, 3699 SourceLocation EllipsisLoc) { 3700 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3701 if (!Res.isUsable()) 3702 return true; 3703 Init = Res.get(); 3704 3705 if (!ConstructorD) 3706 return true; 3707 3708 AdjustDeclIfTemplate(ConstructorD); 3709 3710 CXXConstructorDecl *Constructor 3711 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3712 if (!Constructor) { 3713 // The user wrote a constructor initializer on a function that is 3714 // not a C++ constructor. Ignore the error for now, because we may 3715 // have more member initializers coming; we'll diagnose it just 3716 // once in ActOnMemInitializers. 3717 return true; 3718 } 3719 3720 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3721 3722 // C++ [class.base.init]p2: 3723 // Names in a mem-initializer-id are looked up in the scope of the 3724 // constructor's class and, if not found in that scope, are looked 3725 // up in the scope containing the constructor's definition. 3726 // [Note: if the constructor's class contains a member with the 3727 // same name as a direct or virtual base class of the class, a 3728 // mem-initializer-id naming the member or base class and composed 3729 // of a single identifier refers to the class member. A 3730 // mem-initializer-id for the hidden base class may be specified 3731 // using a qualified name. ] 3732 if (!SS.getScopeRep() && !TemplateTypeTy) { 3733 // Look for a member, first. 3734 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3735 if (!Result.empty()) { 3736 ValueDecl *Member; 3737 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3738 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 3739 if (EllipsisLoc.isValid()) 3740 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 3741 << MemberOrBase 3742 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 3743 3744 return BuildMemberInitializer(Member, Init, IdLoc); 3745 } 3746 } 3747 } 3748 // It didn't name a member, so see if it names a class. 3749 QualType BaseType; 3750 TypeSourceInfo *TInfo = nullptr; 3751 3752 if (TemplateTypeTy) { 3753 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 3754 } else if (DS.getTypeSpecType() == TST_decltype) { 3755 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3756 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 3757 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 3758 return true; 3759 } else { 3760 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 3761 LookupParsedName(R, S, &SS); 3762 3763 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 3764 if (!TyD) { 3765 if (R.isAmbiguous()) return true; 3766 3767 // We don't want access-control diagnostics here. 3768 R.suppressDiagnostics(); 3769 3770 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 3771 bool NotUnknownSpecialization = false; 3772 DeclContext *DC = computeDeclContext(SS, false); 3773 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 3774 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 3775 3776 if (!NotUnknownSpecialization) { 3777 // When the scope specifier can refer to a member of an unknown 3778 // specialization, we take it as a type name. 3779 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 3780 SS.getWithLocInContext(Context), 3781 *MemberOrBase, IdLoc); 3782 if (BaseType.isNull()) 3783 return true; 3784 3785 TInfo = Context.CreateTypeSourceInfo(BaseType); 3786 DependentNameTypeLoc TL = 3787 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 3788 if (!TL.isNull()) { 3789 TL.setNameLoc(IdLoc); 3790 TL.setElaboratedKeywordLoc(SourceLocation()); 3791 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3792 } 3793 3794 R.clear(); 3795 R.setLookupName(MemberOrBase); 3796 } 3797 } 3798 3799 // If no results were found, try to correct typos. 3800 TypoCorrection Corr; 3801 if (R.empty() && BaseType.isNull() && 3802 (Corr = CorrectTypo( 3803 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 3804 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 3805 CTK_ErrorRecovery, ClassDecl))) { 3806 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 3807 // We have found a non-static data member with a similar 3808 // name to what was typed; complain and initialize that 3809 // member. 3810 diagnoseTypo(Corr, 3811 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3812 << MemberOrBase << true); 3813 return BuildMemberInitializer(Member, Init, IdLoc); 3814 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3815 const CXXBaseSpecifier *DirectBaseSpec; 3816 const CXXBaseSpecifier *VirtualBaseSpec; 3817 if (FindBaseInitializer(*this, ClassDecl, 3818 Context.getTypeDeclType(Type), 3819 DirectBaseSpec, VirtualBaseSpec)) { 3820 // We have found a direct or virtual base class with a 3821 // similar name to what was typed; complain and initialize 3822 // that base class. 3823 diagnoseTypo(Corr, 3824 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3825 << MemberOrBase << false, 3826 PDiag() /*Suppress note, we provide our own.*/); 3827 3828 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3829 : VirtualBaseSpec; 3830 Diag(BaseSpec->getLocStart(), 3831 diag::note_base_class_specified_here) 3832 << BaseSpec->getType() 3833 << BaseSpec->getSourceRange(); 3834 3835 TyD = Type; 3836 } 3837 } 3838 } 3839 3840 if (!TyD && BaseType.isNull()) { 3841 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3842 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3843 return true; 3844 } 3845 } 3846 3847 if (BaseType.isNull()) { 3848 BaseType = Context.getTypeDeclType(TyD); 3849 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3850 if (SS.isSet()) { 3851 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3852 BaseType); 3853 TInfo = Context.CreateTypeSourceInfo(BaseType); 3854 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 3855 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 3856 TL.setElaboratedKeywordLoc(SourceLocation()); 3857 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3858 } 3859 } 3860 } 3861 3862 if (!TInfo) 3863 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3864 3865 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3866 } 3867 3868 /// Checks a member initializer expression for cases where reference (or 3869 /// pointer) members are bound to by-value parameters (or their addresses). 3870 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 3871 Expr *Init, 3872 SourceLocation IdLoc) { 3873 QualType MemberTy = Member->getType(); 3874 3875 // We only handle pointers and references currently. 3876 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3877 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3878 return; 3879 3880 const bool IsPointer = MemberTy->isPointerType(); 3881 if (IsPointer) { 3882 if (const UnaryOperator *Op 3883 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3884 // The only case we're worried about with pointers requires taking the 3885 // address. 3886 if (Op->getOpcode() != UO_AddrOf) 3887 return; 3888 3889 Init = Op->getSubExpr(); 3890 } else { 3891 // We only handle address-of expression initializers for pointers. 3892 return; 3893 } 3894 } 3895 3896 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3897 // We only warn when referring to a non-reference parameter declaration. 3898 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3899 if (!Parameter || Parameter->getType()->isReferenceType()) 3900 return; 3901 3902 S.Diag(Init->getExprLoc(), 3903 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3904 : diag::warn_bind_ref_member_to_parameter) 3905 << Member << Parameter << Init->getSourceRange(); 3906 } else { 3907 // Other initializers are fine. 3908 return; 3909 } 3910 3911 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3912 << (unsigned)IsPointer; 3913 } 3914 3915 MemInitResult 3916 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3917 SourceLocation IdLoc) { 3918 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3919 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3920 assert((DirectMember || IndirectMember) && 3921 "Member must be a FieldDecl or IndirectFieldDecl"); 3922 3923 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3924 return true; 3925 3926 if (Member->isInvalidDecl()) 3927 return true; 3928 3929 MultiExprArg Args; 3930 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3931 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3932 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3933 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3934 } else { 3935 // Template instantiation doesn't reconstruct ParenListExprs for us. 3936 Args = Init; 3937 } 3938 3939 SourceRange InitRange = Init->getSourceRange(); 3940 3941 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3942 // Can't check initialization for a member of dependent type or when 3943 // any of the arguments are type-dependent expressions. 3944 DiscardCleanupsInEvaluationContext(); 3945 } else { 3946 bool InitList = false; 3947 if (isa<InitListExpr>(Init)) { 3948 InitList = true; 3949 Args = Init; 3950 } 3951 3952 // Initialize the member. 3953 InitializedEntity MemberEntity = 3954 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3955 : InitializedEntity::InitializeMember(IndirectMember, 3956 nullptr); 3957 InitializationKind Kind = 3958 InitList ? InitializationKind::CreateDirectList(IdLoc) 3959 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3960 InitRange.getEnd()); 3961 3962 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3963 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3964 nullptr); 3965 if (MemberInit.isInvalid()) 3966 return true; 3967 3968 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3969 3970 // C++11 [class.base.init]p7: 3971 // The initialization of each base and member constitutes a 3972 // full-expression. 3973 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3974 if (MemberInit.isInvalid()) 3975 return true; 3976 3977 Init = MemberInit.get(); 3978 } 3979 3980 if (DirectMember) { 3981 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 3982 InitRange.getBegin(), Init, 3983 InitRange.getEnd()); 3984 } else { 3985 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 3986 InitRange.getBegin(), Init, 3987 InitRange.getEnd()); 3988 } 3989 } 3990 3991 MemInitResult 3992 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 3993 CXXRecordDecl *ClassDecl) { 3994 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3995 if (!LangOpts.CPlusPlus11) 3996 return Diag(NameLoc, diag::err_delegating_ctor) 3997 << TInfo->getTypeLoc().getLocalSourceRange(); 3998 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 3999 4000 bool InitList = true; 4001 MultiExprArg Args = Init; 4002 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4003 InitList = false; 4004 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4005 } 4006 4007 SourceRange InitRange = Init->getSourceRange(); 4008 // Initialize the object. 4009 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4010 QualType(ClassDecl->getTypeForDecl(), 0)); 4011 InitializationKind Kind = 4012 InitList ? InitializationKind::CreateDirectList(NameLoc) 4013 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4014 InitRange.getEnd()); 4015 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4016 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4017 Args, nullptr); 4018 if (DelegationInit.isInvalid()) 4019 return true; 4020 4021 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4022 "Delegating constructor with no target?"); 4023 4024 // C++11 [class.base.init]p7: 4025 // The initialization of each base and member constitutes a 4026 // full-expression. 4027 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 4028 InitRange.getBegin()); 4029 if (DelegationInit.isInvalid()) 4030 return true; 4031 4032 // If we are in a dependent context, template instantiation will 4033 // perform this type-checking again. Just save the arguments that we 4034 // received in a ParenListExpr. 4035 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4036 // of the information that we have about the base 4037 // initializer. However, deconstructing the ASTs is a dicey process, 4038 // and this approach is far more likely to get the corner cases right. 4039 if (CurContext->isDependentContext()) 4040 DelegationInit = Init; 4041 4042 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4043 DelegationInit.getAs<Expr>(), 4044 InitRange.getEnd()); 4045 } 4046 4047 MemInitResult 4048 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4049 Expr *Init, CXXRecordDecl *ClassDecl, 4050 SourceLocation EllipsisLoc) { 4051 SourceLocation BaseLoc 4052 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4053 4054 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4055 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4056 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4057 4058 // C++ [class.base.init]p2: 4059 // [...] Unless the mem-initializer-id names a nonstatic data 4060 // member of the constructor's class or a direct or virtual base 4061 // of that class, the mem-initializer is ill-formed. A 4062 // mem-initializer-list can initialize a base class using any 4063 // name that denotes that base class type. 4064 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4065 4066 SourceRange InitRange = Init->getSourceRange(); 4067 if (EllipsisLoc.isValid()) { 4068 // This is a pack expansion. 4069 if (!BaseType->containsUnexpandedParameterPack()) { 4070 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4071 << SourceRange(BaseLoc, InitRange.getEnd()); 4072 4073 EllipsisLoc = SourceLocation(); 4074 } 4075 } else { 4076 // Check for any unexpanded parameter packs. 4077 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4078 return true; 4079 4080 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4081 return true; 4082 } 4083 4084 // Check for direct and virtual base classes. 4085 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4086 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4087 if (!Dependent) { 4088 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4089 BaseType)) 4090 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4091 4092 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4093 VirtualBaseSpec); 4094 4095 // C++ [base.class.init]p2: 4096 // Unless the mem-initializer-id names a nonstatic data member of the 4097 // constructor's class or a direct or virtual base of that class, the 4098 // mem-initializer is ill-formed. 4099 if (!DirectBaseSpec && !VirtualBaseSpec) { 4100 // If the class has any dependent bases, then it's possible that 4101 // one of those types will resolve to the same type as 4102 // BaseType. Therefore, just treat this as a dependent base 4103 // class initialization. FIXME: Should we try to check the 4104 // initialization anyway? It seems odd. 4105 if (ClassDecl->hasAnyDependentBases()) 4106 Dependent = true; 4107 else 4108 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4109 << BaseType << Context.getTypeDeclType(ClassDecl) 4110 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4111 } 4112 } 4113 4114 if (Dependent) { 4115 DiscardCleanupsInEvaluationContext(); 4116 4117 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4118 /*IsVirtual=*/false, 4119 InitRange.getBegin(), Init, 4120 InitRange.getEnd(), EllipsisLoc); 4121 } 4122 4123 // C++ [base.class.init]p2: 4124 // If a mem-initializer-id is ambiguous because it designates both 4125 // a direct non-virtual base class and an inherited virtual base 4126 // class, the mem-initializer is ill-formed. 4127 if (DirectBaseSpec && VirtualBaseSpec) 4128 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4129 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4130 4131 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4132 if (!BaseSpec) 4133 BaseSpec = VirtualBaseSpec; 4134 4135 // Initialize the base. 4136 bool InitList = true; 4137 MultiExprArg Args = Init; 4138 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4139 InitList = false; 4140 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4141 } 4142 4143 InitializedEntity BaseEntity = 4144 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4145 InitializationKind Kind = 4146 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4147 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4148 InitRange.getEnd()); 4149 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4150 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4151 if (BaseInit.isInvalid()) 4152 return true; 4153 4154 // C++11 [class.base.init]p7: 4155 // The initialization of each base and member constitutes a 4156 // full-expression. 4157 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 4158 if (BaseInit.isInvalid()) 4159 return true; 4160 4161 // If we are in a dependent context, template instantiation will 4162 // perform this type-checking again. Just save the arguments that we 4163 // received in a ParenListExpr. 4164 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4165 // of the information that we have about the base 4166 // initializer. However, deconstructing the ASTs is a dicey process, 4167 // and this approach is far more likely to get the corner cases right. 4168 if (CurContext->isDependentContext()) 4169 BaseInit = Init; 4170 4171 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4172 BaseSpec->isVirtual(), 4173 InitRange.getBegin(), 4174 BaseInit.getAs<Expr>(), 4175 InitRange.getEnd(), EllipsisLoc); 4176 } 4177 4178 // Create a static_cast\<T&&>(expr). 4179 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4180 if (T.isNull()) T = E->getType(); 4181 QualType TargetType = SemaRef.BuildReferenceType( 4182 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4183 SourceLocation ExprLoc = E->getLocStart(); 4184 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4185 TargetType, ExprLoc); 4186 4187 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4188 SourceRange(ExprLoc, ExprLoc), 4189 E->getSourceRange()).get(); 4190 } 4191 4192 /// ImplicitInitializerKind - How an implicit base or member initializer should 4193 /// initialize its base or member. 4194 enum ImplicitInitializerKind { 4195 IIK_Default, 4196 IIK_Copy, 4197 IIK_Move, 4198 IIK_Inherit 4199 }; 4200 4201 static bool 4202 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4203 ImplicitInitializerKind ImplicitInitKind, 4204 CXXBaseSpecifier *BaseSpec, 4205 bool IsInheritedVirtualBase, 4206 CXXCtorInitializer *&CXXBaseInit) { 4207 InitializedEntity InitEntity 4208 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4209 IsInheritedVirtualBase); 4210 4211 ExprResult BaseInit; 4212 4213 switch (ImplicitInitKind) { 4214 case IIK_Inherit: 4215 case IIK_Default: { 4216 InitializationKind InitKind 4217 = InitializationKind::CreateDefault(Constructor->getLocation()); 4218 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4219 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4220 break; 4221 } 4222 4223 case IIK_Move: 4224 case IIK_Copy: { 4225 bool Moving = ImplicitInitKind == IIK_Move; 4226 ParmVarDecl *Param = Constructor->getParamDecl(0); 4227 QualType ParamType = Param->getType().getNonReferenceType(); 4228 4229 Expr *CopyCtorArg = 4230 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4231 SourceLocation(), Param, false, 4232 Constructor->getLocation(), ParamType, 4233 VK_LValue, nullptr); 4234 4235 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4236 4237 // Cast to the base class to avoid ambiguities. 4238 QualType ArgTy = 4239 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4240 ParamType.getQualifiers()); 4241 4242 if (Moving) { 4243 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4244 } 4245 4246 CXXCastPath BasePath; 4247 BasePath.push_back(BaseSpec); 4248 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4249 CK_UncheckedDerivedToBase, 4250 Moving ? VK_XValue : VK_LValue, 4251 &BasePath).get(); 4252 4253 InitializationKind InitKind 4254 = InitializationKind::CreateDirect(Constructor->getLocation(), 4255 SourceLocation(), SourceLocation()); 4256 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4257 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4258 break; 4259 } 4260 } 4261 4262 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4263 if (BaseInit.isInvalid()) 4264 return true; 4265 4266 CXXBaseInit = 4267 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4268 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4269 SourceLocation()), 4270 BaseSpec->isVirtual(), 4271 SourceLocation(), 4272 BaseInit.getAs<Expr>(), 4273 SourceLocation(), 4274 SourceLocation()); 4275 4276 return false; 4277 } 4278 4279 static bool RefersToRValueRef(Expr *MemRef) { 4280 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4281 return Referenced->getType()->isRValueReferenceType(); 4282 } 4283 4284 static bool 4285 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4286 ImplicitInitializerKind ImplicitInitKind, 4287 FieldDecl *Field, IndirectFieldDecl *Indirect, 4288 CXXCtorInitializer *&CXXMemberInit) { 4289 if (Field->isInvalidDecl()) 4290 return true; 4291 4292 SourceLocation Loc = Constructor->getLocation(); 4293 4294 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4295 bool Moving = ImplicitInitKind == IIK_Move; 4296 ParmVarDecl *Param = Constructor->getParamDecl(0); 4297 QualType ParamType = Param->getType().getNonReferenceType(); 4298 4299 // Suppress copying zero-width bitfields. 4300 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 4301 return false; 4302 4303 Expr *MemberExprBase = 4304 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4305 SourceLocation(), Param, false, 4306 Loc, ParamType, VK_LValue, nullptr); 4307 4308 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4309 4310 if (Moving) { 4311 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4312 } 4313 4314 // Build a reference to this field within the parameter. 4315 CXXScopeSpec SS; 4316 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4317 Sema::LookupMemberName); 4318 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4319 : cast<ValueDecl>(Field), AS_public); 4320 MemberLookup.resolveKind(); 4321 ExprResult CtorArg 4322 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4323 ParamType, Loc, 4324 /*IsArrow=*/false, 4325 SS, 4326 /*TemplateKWLoc=*/SourceLocation(), 4327 /*FirstQualifierInScope=*/nullptr, 4328 MemberLookup, 4329 /*TemplateArgs=*/nullptr, 4330 /*S*/nullptr); 4331 if (CtorArg.isInvalid()) 4332 return true; 4333 4334 // C++11 [class.copy]p15: 4335 // - if a member m has rvalue reference type T&&, it is direct-initialized 4336 // with static_cast<T&&>(x.m); 4337 if (RefersToRValueRef(CtorArg.get())) { 4338 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4339 } 4340 4341 InitializedEntity Entity = 4342 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4343 /*Implicit*/ true) 4344 : InitializedEntity::InitializeMember(Field, nullptr, 4345 /*Implicit*/ true); 4346 4347 // Direct-initialize to use the copy constructor. 4348 InitializationKind InitKind = 4349 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4350 4351 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4352 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4353 ExprResult MemberInit = 4354 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4355 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4356 if (MemberInit.isInvalid()) 4357 return true; 4358 4359 if (Indirect) 4360 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4361 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4362 else 4363 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4364 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4365 return false; 4366 } 4367 4368 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4369 "Unhandled implicit init kind!"); 4370 4371 QualType FieldBaseElementType = 4372 SemaRef.Context.getBaseElementType(Field->getType()); 4373 4374 if (FieldBaseElementType->isRecordType()) { 4375 InitializedEntity InitEntity = 4376 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4377 /*Implicit*/ true) 4378 : InitializedEntity::InitializeMember(Field, nullptr, 4379 /*Implicit*/ true); 4380 InitializationKind InitKind = 4381 InitializationKind::CreateDefault(Loc); 4382 4383 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4384 ExprResult MemberInit = 4385 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4386 4387 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4388 if (MemberInit.isInvalid()) 4389 return true; 4390 4391 if (Indirect) 4392 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4393 Indirect, Loc, 4394 Loc, 4395 MemberInit.get(), 4396 Loc); 4397 else 4398 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4399 Field, Loc, Loc, 4400 MemberInit.get(), 4401 Loc); 4402 return false; 4403 } 4404 4405 if (!Field->getParent()->isUnion()) { 4406 if (FieldBaseElementType->isReferenceType()) { 4407 SemaRef.Diag(Constructor->getLocation(), 4408 diag::err_uninitialized_member_in_ctor) 4409 << (int)Constructor->isImplicit() 4410 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4411 << 0 << Field->getDeclName(); 4412 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4413 return true; 4414 } 4415 4416 if (FieldBaseElementType.isConstQualified()) { 4417 SemaRef.Diag(Constructor->getLocation(), 4418 diag::err_uninitialized_member_in_ctor) 4419 << (int)Constructor->isImplicit() 4420 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4421 << 1 << Field->getDeclName(); 4422 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4423 return true; 4424 } 4425 } 4426 4427 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4428 // ARC and Weak: 4429 // Default-initialize Objective-C pointers to NULL. 4430 CXXMemberInit 4431 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4432 Loc, Loc, 4433 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4434 Loc); 4435 return false; 4436 } 4437 4438 // Nothing to initialize. 4439 CXXMemberInit = nullptr; 4440 return false; 4441 } 4442 4443 namespace { 4444 struct BaseAndFieldInfo { 4445 Sema &S; 4446 CXXConstructorDecl *Ctor; 4447 bool AnyErrorsInInits; 4448 ImplicitInitializerKind IIK; 4449 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4450 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4451 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4452 4453 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4454 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4455 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4456 if (Ctor->getInheritedConstructor()) 4457 IIK = IIK_Inherit; 4458 else if (Generated && Ctor->isCopyConstructor()) 4459 IIK = IIK_Copy; 4460 else if (Generated && Ctor->isMoveConstructor()) 4461 IIK = IIK_Move; 4462 else 4463 IIK = IIK_Default; 4464 } 4465 4466 bool isImplicitCopyOrMove() const { 4467 switch (IIK) { 4468 case IIK_Copy: 4469 case IIK_Move: 4470 return true; 4471 4472 case IIK_Default: 4473 case IIK_Inherit: 4474 return false; 4475 } 4476 4477 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4478 } 4479 4480 bool addFieldInitializer(CXXCtorInitializer *Init) { 4481 AllToInit.push_back(Init); 4482 4483 // Check whether this initializer makes the field "used". 4484 if (Init->getInit()->HasSideEffects(S.Context)) 4485 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4486 4487 return false; 4488 } 4489 4490 bool isInactiveUnionMember(FieldDecl *Field) { 4491 RecordDecl *Record = Field->getParent(); 4492 if (!Record->isUnion()) 4493 return false; 4494 4495 if (FieldDecl *Active = 4496 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4497 return Active != Field->getCanonicalDecl(); 4498 4499 // In an implicit copy or move constructor, ignore any in-class initializer. 4500 if (isImplicitCopyOrMove()) 4501 return true; 4502 4503 // If there's no explicit initialization, the field is active only if it 4504 // has an in-class initializer... 4505 if (Field->hasInClassInitializer()) 4506 return false; 4507 // ... or it's an anonymous struct or union whose class has an in-class 4508 // initializer. 4509 if (!Field->isAnonymousStructOrUnion()) 4510 return true; 4511 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4512 return !FieldRD->hasInClassInitializer(); 4513 } 4514 4515 /// \brief Determine whether the given field is, or is within, a union member 4516 /// that is inactive (because there was an initializer given for a different 4517 /// member of the union, or because the union was not initialized at all). 4518 bool isWithinInactiveUnionMember(FieldDecl *Field, 4519 IndirectFieldDecl *Indirect) { 4520 if (!Indirect) 4521 return isInactiveUnionMember(Field); 4522 4523 for (auto *C : Indirect->chain()) { 4524 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4525 if (Field && isInactiveUnionMember(Field)) 4526 return true; 4527 } 4528 return false; 4529 } 4530 }; 4531 } 4532 4533 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 4534 /// array type. 4535 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4536 if (T->isIncompleteArrayType()) 4537 return true; 4538 4539 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4540 if (!ArrayT->getSize()) 4541 return true; 4542 4543 T = ArrayT->getElementType(); 4544 } 4545 4546 return false; 4547 } 4548 4549 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4550 FieldDecl *Field, 4551 IndirectFieldDecl *Indirect = nullptr) { 4552 if (Field->isInvalidDecl()) 4553 return false; 4554 4555 // Overwhelmingly common case: we have a direct initializer for this field. 4556 if (CXXCtorInitializer *Init = 4557 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4558 return Info.addFieldInitializer(Init); 4559 4560 // C++11 [class.base.init]p8: 4561 // if the entity is a non-static data member that has a 4562 // brace-or-equal-initializer and either 4563 // -- the constructor's class is a union and no other variant member of that 4564 // union is designated by a mem-initializer-id or 4565 // -- the constructor's class is not a union, and, if the entity is a member 4566 // of an anonymous union, no other member of that union is designated by 4567 // a mem-initializer-id, 4568 // the entity is initialized as specified in [dcl.init]. 4569 // 4570 // We also apply the same rules to handle anonymous structs within anonymous 4571 // unions. 4572 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4573 return false; 4574 4575 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4576 ExprResult DIE = 4577 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4578 if (DIE.isInvalid()) 4579 return true; 4580 CXXCtorInitializer *Init; 4581 if (Indirect) 4582 Init = new (SemaRef.Context) 4583 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4584 SourceLocation(), DIE.get(), SourceLocation()); 4585 else 4586 Init = new (SemaRef.Context) 4587 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4588 SourceLocation(), DIE.get(), SourceLocation()); 4589 return Info.addFieldInitializer(Init); 4590 } 4591 4592 // Don't initialize incomplete or zero-length arrays. 4593 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4594 return false; 4595 4596 // Don't try to build an implicit initializer if there were semantic 4597 // errors in any of the initializers (and therefore we might be 4598 // missing some that the user actually wrote). 4599 if (Info.AnyErrorsInInits) 4600 return false; 4601 4602 CXXCtorInitializer *Init = nullptr; 4603 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4604 Indirect, Init)) 4605 return true; 4606 4607 if (!Init) 4608 return false; 4609 4610 return Info.addFieldInitializer(Init); 4611 } 4612 4613 bool 4614 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4615 CXXCtorInitializer *Initializer) { 4616 assert(Initializer->isDelegatingInitializer()); 4617 Constructor->setNumCtorInitializers(1); 4618 CXXCtorInitializer **initializer = 4619 new (Context) CXXCtorInitializer*[1]; 4620 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4621 Constructor->setCtorInitializers(initializer); 4622 4623 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4624 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4625 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4626 } 4627 4628 DelegatingCtorDecls.push_back(Constructor); 4629 4630 DiagnoseUninitializedFields(*this, Constructor); 4631 4632 return false; 4633 } 4634 4635 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4636 ArrayRef<CXXCtorInitializer *> Initializers) { 4637 if (Constructor->isDependentContext()) { 4638 // Just store the initializers as written, they will be checked during 4639 // instantiation. 4640 if (!Initializers.empty()) { 4641 Constructor->setNumCtorInitializers(Initializers.size()); 4642 CXXCtorInitializer **baseOrMemberInitializers = 4643 new (Context) CXXCtorInitializer*[Initializers.size()]; 4644 memcpy(baseOrMemberInitializers, Initializers.data(), 4645 Initializers.size() * sizeof(CXXCtorInitializer*)); 4646 Constructor->setCtorInitializers(baseOrMemberInitializers); 4647 } 4648 4649 // Let template instantiation know whether we had errors. 4650 if (AnyErrors) 4651 Constructor->setInvalidDecl(); 4652 4653 return false; 4654 } 4655 4656 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4657 4658 // We need to build the initializer AST according to order of construction 4659 // and not what user specified in the Initializers list. 4660 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4661 if (!ClassDecl) 4662 return true; 4663 4664 bool HadError = false; 4665 4666 for (unsigned i = 0; i < Initializers.size(); i++) { 4667 CXXCtorInitializer *Member = Initializers[i]; 4668 4669 if (Member->isBaseInitializer()) 4670 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4671 else { 4672 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4673 4674 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4675 for (auto *C : F->chain()) { 4676 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4677 if (FD && FD->getParent()->isUnion()) 4678 Info.ActiveUnionMember.insert(std::make_pair( 4679 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4680 } 4681 } else if (FieldDecl *FD = Member->getMember()) { 4682 if (FD->getParent()->isUnion()) 4683 Info.ActiveUnionMember.insert(std::make_pair( 4684 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4685 } 4686 } 4687 } 4688 4689 // Keep track of the direct virtual bases. 4690 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4691 for (auto &I : ClassDecl->bases()) { 4692 if (I.isVirtual()) 4693 DirectVBases.insert(&I); 4694 } 4695 4696 // Push virtual bases before others. 4697 for (auto &VBase : ClassDecl->vbases()) { 4698 if (CXXCtorInitializer *Value 4699 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4700 // [class.base.init]p7, per DR257: 4701 // A mem-initializer where the mem-initializer-id names a virtual base 4702 // class is ignored during execution of a constructor of any class that 4703 // is not the most derived class. 4704 if (ClassDecl->isAbstract()) { 4705 // FIXME: Provide a fixit to remove the base specifier. This requires 4706 // tracking the location of the associated comma for a base specifier. 4707 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4708 << VBase.getType() << ClassDecl; 4709 DiagnoseAbstractType(ClassDecl); 4710 } 4711 4712 Info.AllToInit.push_back(Value); 4713 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4714 // [class.base.init]p8, per DR257: 4715 // If a given [...] base class is not named by a mem-initializer-id 4716 // [...] and the entity is not a virtual base class of an abstract 4717 // class, then [...] the entity is default-initialized. 4718 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4719 CXXCtorInitializer *CXXBaseInit; 4720 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4721 &VBase, IsInheritedVirtualBase, 4722 CXXBaseInit)) { 4723 HadError = true; 4724 continue; 4725 } 4726 4727 Info.AllToInit.push_back(CXXBaseInit); 4728 } 4729 } 4730 4731 // Non-virtual bases. 4732 for (auto &Base : ClassDecl->bases()) { 4733 // Virtuals are in the virtual base list and already constructed. 4734 if (Base.isVirtual()) 4735 continue; 4736 4737 if (CXXCtorInitializer *Value 4738 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4739 Info.AllToInit.push_back(Value); 4740 } else if (!AnyErrors) { 4741 CXXCtorInitializer *CXXBaseInit; 4742 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4743 &Base, /*IsInheritedVirtualBase=*/false, 4744 CXXBaseInit)) { 4745 HadError = true; 4746 continue; 4747 } 4748 4749 Info.AllToInit.push_back(CXXBaseInit); 4750 } 4751 } 4752 4753 // Fields. 4754 for (auto *Mem : ClassDecl->decls()) { 4755 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4756 // C++ [class.bit]p2: 4757 // A declaration for a bit-field that omits the identifier declares an 4758 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4759 // initialized. 4760 if (F->isUnnamedBitfield()) 4761 continue; 4762 4763 // If we're not generating the implicit copy/move constructor, then we'll 4764 // handle anonymous struct/union fields based on their individual 4765 // indirect fields. 4766 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4767 continue; 4768 4769 if (CollectFieldInitializer(*this, Info, F)) 4770 HadError = true; 4771 continue; 4772 } 4773 4774 // Beyond this point, we only consider default initialization. 4775 if (Info.isImplicitCopyOrMove()) 4776 continue; 4777 4778 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4779 if (F->getType()->isIncompleteArrayType()) { 4780 assert(ClassDecl->hasFlexibleArrayMember() && 4781 "Incomplete array type is not valid"); 4782 continue; 4783 } 4784 4785 // Initialize each field of an anonymous struct individually. 4786 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4787 HadError = true; 4788 4789 continue; 4790 } 4791 } 4792 4793 unsigned NumInitializers = Info.AllToInit.size(); 4794 if (NumInitializers > 0) { 4795 Constructor->setNumCtorInitializers(NumInitializers); 4796 CXXCtorInitializer **baseOrMemberInitializers = 4797 new (Context) CXXCtorInitializer*[NumInitializers]; 4798 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4799 NumInitializers * sizeof(CXXCtorInitializer*)); 4800 Constructor->setCtorInitializers(baseOrMemberInitializers); 4801 4802 // Constructors implicitly reference the base and member 4803 // destructors. 4804 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4805 Constructor->getParent()); 4806 } 4807 4808 return HadError; 4809 } 4810 4811 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4812 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4813 const RecordDecl *RD = RT->getDecl(); 4814 if (RD->isAnonymousStructOrUnion()) { 4815 for (auto *Field : RD->fields()) 4816 PopulateKeysForFields(Field, IdealInits); 4817 return; 4818 } 4819 } 4820 IdealInits.push_back(Field->getCanonicalDecl()); 4821 } 4822 4823 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4824 return Context.getCanonicalType(BaseType).getTypePtr(); 4825 } 4826 4827 static const void *GetKeyForMember(ASTContext &Context, 4828 CXXCtorInitializer *Member) { 4829 if (!Member->isAnyMemberInitializer()) 4830 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4831 4832 return Member->getAnyMember()->getCanonicalDecl(); 4833 } 4834 4835 static void DiagnoseBaseOrMemInitializerOrder( 4836 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4837 ArrayRef<CXXCtorInitializer *> Inits) { 4838 if (Constructor->getDeclContext()->isDependentContext()) 4839 return; 4840 4841 // Don't check initializers order unless the warning is enabled at the 4842 // location of at least one initializer. 4843 bool ShouldCheckOrder = false; 4844 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4845 CXXCtorInitializer *Init = Inits[InitIndex]; 4846 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4847 Init->getSourceLocation())) { 4848 ShouldCheckOrder = true; 4849 break; 4850 } 4851 } 4852 if (!ShouldCheckOrder) 4853 return; 4854 4855 // Build the list of bases and members in the order that they'll 4856 // actually be initialized. The explicit initializers should be in 4857 // this same order but may be missing things. 4858 SmallVector<const void*, 32> IdealInitKeys; 4859 4860 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4861 4862 // 1. Virtual bases. 4863 for (const auto &VBase : ClassDecl->vbases()) 4864 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4865 4866 // 2. Non-virtual bases. 4867 for (const auto &Base : ClassDecl->bases()) { 4868 if (Base.isVirtual()) 4869 continue; 4870 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4871 } 4872 4873 // 3. Direct fields. 4874 for (auto *Field : ClassDecl->fields()) { 4875 if (Field->isUnnamedBitfield()) 4876 continue; 4877 4878 PopulateKeysForFields(Field, IdealInitKeys); 4879 } 4880 4881 unsigned NumIdealInits = IdealInitKeys.size(); 4882 unsigned IdealIndex = 0; 4883 4884 CXXCtorInitializer *PrevInit = nullptr; 4885 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4886 CXXCtorInitializer *Init = Inits[InitIndex]; 4887 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4888 4889 // Scan forward to try to find this initializer in the idealized 4890 // initializers list. 4891 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4892 if (InitKey == IdealInitKeys[IdealIndex]) 4893 break; 4894 4895 // If we didn't find this initializer, it must be because we 4896 // scanned past it on a previous iteration. That can only 4897 // happen if we're out of order; emit a warning. 4898 if (IdealIndex == NumIdealInits && PrevInit) { 4899 Sema::SemaDiagnosticBuilder D = 4900 SemaRef.Diag(PrevInit->getSourceLocation(), 4901 diag::warn_initializer_out_of_order); 4902 4903 if (PrevInit->isAnyMemberInitializer()) 4904 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4905 else 4906 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4907 4908 if (Init->isAnyMemberInitializer()) 4909 D << 0 << Init->getAnyMember()->getDeclName(); 4910 else 4911 D << 1 << Init->getTypeSourceInfo()->getType(); 4912 4913 // Move back to the initializer's location in the ideal list. 4914 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4915 if (InitKey == IdealInitKeys[IdealIndex]) 4916 break; 4917 4918 assert(IdealIndex < NumIdealInits && 4919 "initializer not found in initializer list"); 4920 } 4921 4922 PrevInit = Init; 4923 } 4924 } 4925 4926 namespace { 4927 bool CheckRedundantInit(Sema &S, 4928 CXXCtorInitializer *Init, 4929 CXXCtorInitializer *&PrevInit) { 4930 if (!PrevInit) { 4931 PrevInit = Init; 4932 return false; 4933 } 4934 4935 if (FieldDecl *Field = Init->getAnyMember()) 4936 S.Diag(Init->getSourceLocation(), 4937 diag::err_multiple_mem_initialization) 4938 << Field->getDeclName() 4939 << Init->getSourceRange(); 4940 else { 4941 const Type *BaseClass = Init->getBaseClass(); 4942 assert(BaseClass && "neither field nor base"); 4943 S.Diag(Init->getSourceLocation(), 4944 diag::err_multiple_base_initialization) 4945 << QualType(BaseClass, 0) 4946 << Init->getSourceRange(); 4947 } 4948 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4949 << 0 << PrevInit->getSourceRange(); 4950 4951 return true; 4952 } 4953 4954 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4955 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4956 4957 bool CheckRedundantUnionInit(Sema &S, 4958 CXXCtorInitializer *Init, 4959 RedundantUnionMap &Unions) { 4960 FieldDecl *Field = Init->getAnyMember(); 4961 RecordDecl *Parent = Field->getParent(); 4962 NamedDecl *Child = Field; 4963 4964 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4965 if (Parent->isUnion()) { 4966 UnionEntry &En = Unions[Parent]; 4967 if (En.first && En.first != Child) { 4968 S.Diag(Init->getSourceLocation(), 4969 diag::err_multiple_mem_union_initialization) 4970 << Field->getDeclName() 4971 << Init->getSourceRange(); 4972 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4973 << 0 << En.second->getSourceRange(); 4974 return true; 4975 } 4976 if (!En.first) { 4977 En.first = Child; 4978 En.second = Init; 4979 } 4980 if (!Parent->isAnonymousStructOrUnion()) 4981 return false; 4982 } 4983 4984 Child = Parent; 4985 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4986 } 4987 4988 return false; 4989 } 4990 } 4991 4992 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4993 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4994 SourceLocation ColonLoc, 4995 ArrayRef<CXXCtorInitializer*> MemInits, 4996 bool AnyErrors) { 4997 if (!ConstructorDecl) 4998 return; 4999 5000 AdjustDeclIfTemplate(ConstructorDecl); 5001 5002 CXXConstructorDecl *Constructor 5003 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5004 5005 if (!Constructor) { 5006 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5007 return; 5008 } 5009 5010 // Mapping for the duplicate initializers check. 5011 // For member initializers, this is keyed with a FieldDecl*. 5012 // For base initializers, this is keyed with a Type*. 5013 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5014 5015 // Mapping for the inconsistent anonymous-union initializers check. 5016 RedundantUnionMap MemberUnions; 5017 5018 bool HadError = false; 5019 for (unsigned i = 0; i < MemInits.size(); i++) { 5020 CXXCtorInitializer *Init = MemInits[i]; 5021 5022 // Set the source order index. 5023 Init->setSourceOrder(i); 5024 5025 if (Init->isAnyMemberInitializer()) { 5026 const void *Key = GetKeyForMember(Context, Init); 5027 if (CheckRedundantInit(*this, Init, Members[Key]) || 5028 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5029 HadError = true; 5030 } else if (Init->isBaseInitializer()) { 5031 const void *Key = GetKeyForMember(Context, Init); 5032 if (CheckRedundantInit(*this, Init, Members[Key])) 5033 HadError = true; 5034 } else { 5035 assert(Init->isDelegatingInitializer()); 5036 // This must be the only initializer 5037 if (MemInits.size() != 1) { 5038 Diag(Init->getSourceLocation(), 5039 diag::err_delegating_initializer_alone) 5040 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5041 // We will treat this as being the only initializer. 5042 } 5043 SetDelegatingInitializer(Constructor, MemInits[i]); 5044 // Return immediately as the initializer is set. 5045 return; 5046 } 5047 } 5048 5049 if (HadError) 5050 return; 5051 5052 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5053 5054 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5055 5056 DiagnoseUninitializedFields(*this, Constructor); 5057 } 5058 5059 void 5060 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5061 CXXRecordDecl *ClassDecl) { 5062 // Ignore dependent contexts. Also ignore unions, since their members never 5063 // have destructors implicitly called. 5064 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5065 return; 5066 5067 // FIXME: all the access-control diagnostics are positioned on the 5068 // field/base declaration. That's probably good; that said, the 5069 // user might reasonably want to know why the destructor is being 5070 // emitted, and we currently don't say. 5071 5072 // Non-static data members. 5073 for (auto *Field : ClassDecl->fields()) { 5074 if (Field->isInvalidDecl()) 5075 continue; 5076 5077 // Don't destroy incomplete or zero-length arrays. 5078 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5079 continue; 5080 5081 QualType FieldType = Context.getBaseElementType(Field->getType()); 5082 5083 const RecordType* RT = FieldType->getAs<RecordType>(); 5084 if (!RT) 5085 continue; 5086 5087 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5088 if (FieldClassDecl->isInvalidDecl()) 5089 continue; 5090 if (FieldClassDecl->hasIrrelevantDestructor()) 5091 continue; 5092 // The destructor for an implicit anonymous union member is never invoked. 5093 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5094 continue; 5095 5096 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5097 assert(Dtor && "No dtor found for FieldClassDecl!"); 5098 CheckDestructorAccess(Field->getLocation(), Dtor, 5099 PDiag(diag::err_access_dtor_field) 5100 << Field->getDeclName() 5101 << FieldType); 5102 5103 MarkFunctionReferenced(Location, Dtor); 5104 DiagnoseUseOfDecl(Dtor, Location); 5105 } 5106 5107 // We only potentially invoke the destructors of potentially constructed 5108 // subobjects. 5109 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5110 5111 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5112 5113 // Bases. 5114 for (const auto &Base : ClassDecl->bases()) { 5115 // Bases are always records in a well-formed non-dependent class. 5116 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5117 5118 // Remember direct virtual bases. 5119 if (Base.isVirtual()) { 5120 if (!VisitVirtualBases) 5121 continue; 5122 DirectVirtualBases.insert(RT); 5123 } 5124 5125 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5126 // If our base class is invalid, we probably can't get its dtor anyway. 5127 if (BaseClassDecl->isInvalidDecl()) 5128 continue; 5129 if (BaseClassDecl->hasIrrelevantDestructor()) 5130 continue; 5131 5132 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5133 assert(Dtor && "No dtor found for BaseClassDecl!"); 5134 5135 // FIXME: caret should be on the start of the class name 5136 CheckDestructorAccess(Base.getLocStart(), Dtor, 5137 PDiag(diag::err_access_dtor_base) 5138 << Base.getType() 5139 << Base.getSourceRange(), 5140 Context.getTypeDeclType(ClassDecl)); 5141 5142 MarkFunctionReferenced(Location, Dtor); 5143 DiagnoseUseOfDecl(Dtor, Location); 5144 } 5145 5146 if (!VisitVirtualBases) 5147 return; 5148 5149 // Virtual bases. 5150 for (const auto &VBase : ClassDecl->vbases()) { 5151 // Bases are always records in a well-formed non-dependent class. 5152 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5153 5154 // Ignore direct virtual bases. 5155 if (DirectVirtualBases.count(RT)) 5156 continue; 5157 5158 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5159 // If our base class is invalid, we probably can't get its dtor anyway. 5160 if (BaseClassDecl->isInvalidDecl()) 5161 continue; 5162 if (BaseClassDecl->hasIrrelevantDestructor()) 5163 continue; 5164 5165 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5166 assert(Dtor && "No dtor found for BaseClassDecl!"); 5167 if (CheckDestructorAccess( 5168 ClassDecl->getLocation(), Dtor, 5169 PDiag(diag::err_access_dtor_vbase) 5170 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5171 Context.getTypeDeclType(ClassDecl)) == 5172 AR_accessible) { 5173 CheckDerivedToBaseConversion( 5174 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5175 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5176 SourceRange(), DeclarationName(), nullptr); 5177 } 5178 5179 MarkFunctionReferenced(Location, Dtor); 5180 DiagnoseUseOfDecl(Dtor, Location); 5181 } 5182 } 5183 5184 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5185 if (!CDtorDecl) 5186 return; 5187 5188 if (CXXConstructorDecl *Constructor 5189 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5190 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5191 DiagnoseUninitializedFields(*this, Constructor); 5192 } 5193 } 5194 5195 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5196 if (!getLangOpts().CPlusPlus) 5197 return false; 5198 5199 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5200 if (!RD) 5201 return false; 5202 5203 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5204 // class template specialization here, but doing so breaks a lot of code. 5205 5206 // We can't answer whether something is abstract until it has a 5207 // definition. If it's currently being defined, we'll walk back 5208 // over all the declarations when we have a full definition. 5209 const CXXRecordDecl *Def = RD->getDefinition(); 5210 if (!Def || Def->isBeingDefined()) 5211 return false; 5212 5213 return RD->isAbstract(); 5214 } 5215 5216 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5217 TypeDiagnoser &Diagnoser) { 5218 if (!isAbstractType(Loc, T)) 5219 return false; 5220 5221 T = Context.getBaseElementType(T); 5222 Diagnoser.diagnose(*this, Loc, T); 5223 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5224 return true; 5225 } 5226 5227 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5228 // Check if we've already emitted the list of pure virtual functions 5229 // for this class. 5230 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5231 return; 5232 5233 // If the diagnostic is suppressed, don't emit the notes. We're only 5234 // going to emit them once, so try to attach them to a diagnostic we're 5235 // actually going to show. 5236 if (Diags.isLastDiagnosticIgnored()) 5237 return; 5238 5239 CXXFinalOverriderMap FinalOverriders; 5240 RD->getFinalOverriders(FinalOverriders); 5241 5242 // Keep a set of seen pure methods so we won't diagnose the same method 5243 // more than once. 5244 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5245 5246 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5247 MEnd = FinalOverriders.end(); 5248 M != MEnd; 5249 ++M) { 5250 for (OverridingMethods::iterator SO = M->second.begin(), 5251 SOEnd = M->second.end(); 5252 SO != SOEnd; ++SO) { 5253 // C++ [class.abstract]p4: 5254 // A class is abstract if it contains or inherits at least one 5255 // pure virtual function for which the final overrider is pure 5256 // virtual. 5257 5258 // 5259 if (SO->second.size() != 1) 5260 continue; 5261 5262 if (!SO->second.front().Method->isPure()) 5263 continue; 5264 5265 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5266 continue; 5267 5268 Diag(SO->second.front().Method->getLocation(), 5269 diag::note_pure_virtual_function) 5270 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5271 } 5272 } 5273 5274 if (!PureVirtualClassDiagSet) 5275 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5276 PureVirtualClassDiagSet->insert(RD); 5277 } 5278 5279 namespace { 5280 struct AbstractUsageInfo { 5281 Sema &S; 5282 CXXRecordDecl *Record; 5283 CanQualType AbstractType; 5284 bool Invalid; 5285 5286 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5287 : S(S), Record(Record), 5288 AbstractType(S.Context.getCanonicalType( 5289 S.Context.getTypeDeclType(Record))), 5290 Invalid(false) {} 5291 5292 void DiagnoseAbstractType() { 5293 if (Invalid) return; 5294 S.DiagnoseAbstractType(Record); 5295 Invalid = true; 5296 } 5297 5298 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5299 }; 5300 5301 struct CheckAbstractUsage { 5302 AbstractUsageInfo &Info; 5303 const NamedDecl *Ctx; 5304 5305 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5306 : Info(Info), Ctx(Ctx) {} 5307 5308 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5309 switch (TL.getTypeLocClass()) { 5310 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5311 #define TYPELOC(CLASS, PARENT) \ 5312 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5313 #include "clang/AST/TypeLocNodes.def" 5314 } 5315 } 5316 5317 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5318 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5319 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5320 if (!TL.getParam(I)) 5321 continue; 5322 5323 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5324 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5325 } 5326 } 5327 5328 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5329 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5330 } 5331 5332 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5333 // Visit the type parameters from a permissive context. 5334 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5335 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5336 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5337 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5338 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5339 // TODO: other template argument types? 5340 } 5341 } 5342 5343 // Visit pointee types from a permissive context. 5344 #define CheckPolymorphic(Type) \ 5345 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5346 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5347 } 5348 CheckPolymorphic(PointerTypeLoc) 5349 CheckPolymorphic(ReferenceTypeLoc) 5350 CheckPolymorphic(MemberPointerTypeLoc) 5351 CheckPolymorphic(BlockPointerTypeLoc) 5352 CheckPolymorphic(AtomicTypeLoc) 5353 5354 /// Handle all the types we haven't given a more specific 5355 /// implementation for above. 5356 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5357 // Every other kind of type that we haven't called out already 5358 // that has an inner type is either (1) sugar or (2) contains that 5359 // inner type in some way as a subobject. 5360 if (TypeLoc Next = TL.getNextTypeLoc()) 5361 return Visit(Next, Sel); 5362 5363 // If there's no inner type and we're in a permissive context, 5364 // don't diagnose. 5365 if (Sel == Sema::AbstractNone) return; 5366 5367 // Check whether the type matches the abstract type. 5368 QualType T = TL.getType(); 5369 if (T->isArrayType()) { 5370 Sel = Sema::AbstractArrayType; 5371 T = Info.S.Context.getBaseElementType(T); 5372 } 5373 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5374 if (CT != Info.AbstractType) return; 5375 5376 // It matched; do some magic. 5377 if (Sel == Sema::AbstractArrayType) { 5378 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5379 << T << TL.getSourceRange(); 5380 } else { 5381 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5382 << Sel << T << TL.getSourceRange(); 5383 } 5384 Info.DiagnoseAbstractType(); 5385 } 5386 }; 5387 5388 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5389 Sema::AbstractDiagSelID Sel) { 5390 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5391 } 5392 5393 } 5394 5395 /// Check for invalid uses of an abstract type in a method declaration. 5396 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5397 CXXMethodDecl *MD) { 5398 // No need to do the check on definitions, which require that 5399 // the return/param types be complete. 5400 if (MD->doesThisDeclarationHaveABody()) 5401 return; 5402 5403 // For safety's sake, just ignore it if we don't have type source 5404 // information. This should never happen for non-implicit methods, 5405 // but... 5406 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5407 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5408 } 5409 5410 /// Check for invalid uses of an abstract type within a class definition. 5411 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5412 CXXRecordDecl *RD) { 5413 for (auto *D : RD->decls()) { 5414 if (D->isImplicit()) continue; 5415 5416 // Methods and method templates. 5417 if (isa<CXXMethodDecl>(D)) { 5418 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5419 } else if (isa<FunctionTemplateDecl>(D)) { 5420 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5421 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5422 5423 // Fields and static variables. 5424 } else if (isa<FieldDecl>(D)) { 5425 FieldDecl *FD = cast<FieldDecl>(D); 5426 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5427 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5428 } else if (isa<VarDecl>(D)) { 5429 VarDecl *VD = cast<VarDecl>(D); 5430 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5431 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5432 5433 // Nested classes and class templates. 5434 } else if (isa<CXXRecordDecl>(D)) { 5435 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5436 } else if (isa<ClassTemplateDecl>(D)) { 5437 CheckAbstractClassUsage(Info, 5438 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5439 } 5440 } 5441 } 5442 5443 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) { 5444 Attr *ClassAttr = getDLLAttr(Class); 5445 if (!ClassAttr) 5446 return; 5447 5448 assert(ClassAttr->getKind() == attr::DLLExport); 5449 5450 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5451 5452 if (TSK == TSK_ExplicitInstantiationDeclaration) 5453 // Don't go any further if this is just an explicit instantiation 5454 // declaration. 5455 return; 5456 5457 for (Decl *Member : Class->decls()) { 5458 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5459 if (!MD) 5460 continue; 5461 5462 if (Member->getAttr<DLLExportAttr>()) { 5463 if (MD->isUserProvided()) { 5464 // Instantiate non-default class member functions ... 5465 5466 // .. except for certain kinds of template specializations. 5467 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5468 continue; 5469 5470 S.MarkFunctionReferenced(Class->getLocation(), MD); 5471 5472 // The function will be passed to the consumer when its definition is 5473 // encountered. 5474 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5475 MD->isCopyAssignmentOperator() || 5476 MD->isMoveAssignmentOperator()) { 5477 // Synthesize and instantiate non-trivial implicit methods, explicitly 5478 // defaulted methods, and the copy and move assignment operators. The 5479 // latter are exported even if they are trivial, because the address of 5480 // an operator can be taken and should compare equal across libraries. 5481 DiagnosticErrorTrap Trap(S.Diags); 5482 S.MarkFunctionReferenced(Class->getLocation(), MD); 5483 if (Trap.hasErrorOccurred()) { 5484 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5485 << Class->getName() << !S.getLangOpts().CPlusPlus11; 5486 break; 5487 } 5488 5489 // There is no later point when we will see the definition of this 5490 // function, so pass it to the consumer now. 5491 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5492 } 5493 } 5494 } 5495 } 5496 5497 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5498 CXXRecordDecl *Class) { 5499 // Only the MS ABI has default constructor closures, so we don't need to do 5500 // this semantic checking anywhere else. 5501 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5502 return; 5503 5504 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5505 for (Decl *Member : Class->decls()) { 5506 // Look for exported default constructors. 5507 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5508 if (!CD || !CD->isDefaultConstructor()) 5509 continue; 5510 auto *Attr = CD->getAttr<DLLExportAttr>(); 5511 if (!Attr) 5512 continue; 5513 5514 // If the class is non-dependent, mark the default arguments as ODR-used so 5515 // that we can properly codegen the constructor closure. 5516 if (!Class->isDependentContext()) { 5517 for (ParmVarDecl *PD : CD->parameters()) { 5518 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5519 S.DiscardCleanupsInEvaluationContext(); 5520 } 5521 } 5522 5523 if (LastExportedDefaultCtor) { 5524 S.Diag(LastExportedDefaultCtor->getLocation(), 5525 diag::err_attribute_dll_ambiguous_default_ctor) 5526 << Class; 5527 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5528 << CD->getDeclName(); 5529 return; 5530 } 5531 LastExportedDefaultCtor = CD; 5532 } 5533 } 5534 5535 /// \brief Check class-level dllimport/dllexport attribute. 5536 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5537 Attr *ClassAttr = getDLLAttr(Class); 5538 5539 // MSVC inherits DLL attributes to partial class template specializations. 5540 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5541 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5542 if (Attr *TemplateAttr = 5543 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5544 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5545 A->setInherited(true); 5546 ClassAttr = A; 5547 } 5548 } 5549 } 5550 5551 if (!ClassAttr) 5552 return; 5553 5554 if (!Class->isExternallyVisible()) { 5555 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5556 << Class << ClassAttr; 5557 return; 5558 } 5559 5560 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5561 !ClassAttr->isInherited()) { 5562 // Diagnose dll attributes on members of class with dll attribute. 5563 for (Decl *Member : Class->decls()) { 5564 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5565 continue; 5566 InheritableAttr *MemberAttr = getDLLAttr(Member); 5567 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5568 continue; 5569 5570 Diag(MemberAttr->getLocation(), 5571 diag::err_attribute_dll_member_of_dll_class) 5572 << MemberAttr << ClassAttr; 5573 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5574 Member->setInvalidDecl(); 5575 } 5576 } 5577 5578 if (Class->getDescribedClassTemplate()) 5579 // Don't inherit dll attribute until the template is instantiated. 5580 return; 5581 5582 // The class is either imported or exported. 5583 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5584 5585 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5586 5587 // Ignore explicit dllexport on explicit class template instantiation declarations. 5588 if (ClassExported && !ClassAttr->isInherited() && 5589 TSK == TSK_ExplicitInstantiationDeclaration) { 5590 Class->dropAttr<DLLExportAttr>(); 5591 return; 5592 } 5593 5594 // Force declaration of implicit members so they can inherit the attribute. 5595 ForceDeclarationOfImplicitMembers(Class); 5596 5597 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5598 // seem to be true in practice? 5599 5600 for (Decl *Member : Class->decls()) { 5601 VarDecl *VD = dyn_cast<VarDecl>(Member); 5602 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5603 5604 // Only methods and static fields inherit the attributes. 5605 if (!VD && !MD) 5606 continue; 5607 5608 if (MD) { 5609 // Don't process deleted methods. 5610 if (MD->isDeleted()) 5611 continue; 5612 5613 if (MD->isInlined()) { 5614 // MinGW does not import or export inline methods. 5615 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5616 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) 5617 continue; 5618 5619 // MSVC versions before 2015 don't export the move assignment operators 5620 // and move constructor, so don't attempt to import/export them if 5621 // we have a definition. 5622 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5623 if ((MD->isMoveAssignmentOperator() || 5624 (Ctor && Ctor->isMoveConstructor())) && 5625 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5626 continue; 5627 5628 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5629 // operator is exported anyway. 5630 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5631 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5632 continue; 5633 } 5634 } 5635 5636 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5637 continue; 5638 5639 if (!getDLLAttr(Member)) { 5640 auto *NewAttr = 5641 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5642 NewAttr->setInherited(true); 5643 Member->addAttr(NewAttr); 5644 } 5645 } 5646 5647 if (ClassExported) 5648 DelayedDllExportClasses.push_back(Class); 5649 } 5650 5651 /// \brief Perform propagation of DLL attributes from a derived class to a 5652 /// templated base class for MS compatibility. 5653 void Sema::propagateDLLAttrToBaseClassTemplate( 5654 CXXRecordDecl *Class, Attr *ClassAttr, 5655 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5656 if (getDLLAttr( 5657 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5658 // If the base class template has a DLL attribute, don't try to change it. 5659 return; 5660 } 5661 5662 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5663 if (!getDLLAttr(BaseTemplateSpec) && 5664 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5665 TSK == TSK_ImplicitInstantiation)) { 5666 // The template hasn't been instantiated yet (or it has, but only as an 5667 // explicit instantiation declaration or implicit instantiation, which means 5668 // we haven't codegenned any members yet), so propagate the attribute. 5669 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5670 NewAttr->setInherited(true); 5671 BaseTemplateSpec->addAttr(NewAttr); 5672 5673 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5674 // needs to be run again to work see the new attribute. Otherwise this will 5675 // get run whenever the template is instantiated. 5676 if (TSK != TSK_Undeclared) 5677 checkClassLevelDLLAttribute(BaseTemplateSpec); 5678 5679 return; 5680 } 5681 5682 if (getDLLAttr(BaseTemplateSpec)) { 5683 // The template has already been specialized or instantiated with an 5684 // attribute, explicitly or through propagation. We should not try to change 5685 // it. 5686 return; 5687 } 5688 5689 // The template was previously instantiated or explicitly specialized without 5690 // a dll attribute, It's too late for us to add an attribute, so warn that 5691 // this is unsupported. 5692 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5693 << BaseTemplateSpec->isExplicitSpecialization(); 5694 Diag(ClassAttr->getLocation(), diag::note_attribute); 5695 if (BaseTemplateSpec->isExplicitSpecialization()) { 5696 Diag(BaseTemplateSpec->getLocation(), 5697 diag::note_template_class_explicit_specialization_was_here) 5698 << BaseTemplateSpec; 5699 } else { 5700 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5701 diag::note_template_class_instantiation_was_here) 5702 << BaseTemplateSpec; 5703 } 5704 } 5705 5706 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5707 SourceLocation DefaultLoc) { 5708 switch (S.getSpecialMember(MD)) { 5709 case Sema::CXXDefaultConstructor: 5710 S.DefineImplicitDefaultConstructor(DefaultLoc, 5711 cast<CXXConstructorDecl>(MD)); 5712 break; 5713 case Sema::CXXCopyConstructor: 5714 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5715 break; 5716 case Sema::CXXCopyAssignment: 5717 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5718 break; 5719 case Sema::CXXDestructor: 5720 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5721 break; 5722 case Sema::CXXMoveConstructor: 5723 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5724 break; 5725 case Sema::CXXMoveAssignment: 5726 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5727 break; 5728 case Sema::CXXInvalid: 5729 llvm_unreachable("Invalid special member."); 5730 } 5731 } 5732 5733 /// Determine whether a type is permitted to be passed or returned in 5734 /// registers, per C++ [class.temporary]p3. 5735 static bool computeCanPassInRegisters(Sema &S, CXXRecordDecl *D) { 5736 if (D->isDependentType() || D->isInvalidDecl()) 5737 return false; 5738 5739 // Per C++ [class.temporary]p3, the relevant condition is: 5740 // each copy constructor, move constructor, and destructor of X is 5741 // either trivial or deleted, and X has at least one non-deleted copy 5742 // or move constructor 5743 bool HasNonDeletedCopyOrMove = false; 5744 5745 if (D->needsImplicitCopyConstructor() && 5746 !D->defaultedCopyConstructorIsDeleted()) { 5747 if (!D->hasTrivialCopyConstructor()) 5748 return false; 5749 HasNonDeletedCopyOrMove = true; 5750 } 5751 5752 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 5753 !D->defaultedMoveConstructorIsDeleted()) { 5754 if (!D->hasTrivialMoveConstructor()) 5755 return false; 5756 HasNonDeletedCopyOrMove = true; 5757 } 5758 5759 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 5760 !D->hasTrivialDestructor()) 5761 return false; 5762 5763 for (const CXXMethodDecl *MD : D->methods()) { 5764 if (MD->isDeleted()) 5765 continue; 5766 5767 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 5768 if (CD && CD->isCopyOrMoveConstructor()) 5769 HasNonDeletedCopyOrMove = true; 5770 else if (!isa<CXXDestructorDecl>(MD)) 5771 continue; 5772 5773 if (!MD->isTrivial()) 5774 return false; 5775 } 5776 5777 return HasNonDeletedCopyOrMove; 5778 } 5779 5780 /// \brief Perform semantic checks on a class definition that has been 5781 /// completing, introducing implicitly-declared members, checking for 5782 /// abstract types, etc. 5783 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 5784 if (!Record) 5785 return; 5786 5787 if (Record->isAbstract() && !Record->isInvalidDecl()) { 5788 AbstractUsageInfo Info(*this, Record); 5789 CheckAbstractClassUsage(Info, Record); 5790 } 5791 5792 // If this is not an aggregate type and has no user-declared constructor, 5793 // complain about any non-static data members of reference or const scalar 5794 // type, since they will never get initializers. 5795 if (!Record->isInvalidDecl() && !Record->isDependentType() && 5796 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 5797 !Record->isLambda()) { 5798 bool Complained = false; 5799 for (const auto *F : Record->fields()) { 5800 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 5801 continue; 5802 5803 if (F->getType()->isReferenceType() || 5804 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 5805 if (!Complained) { 5806 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 5807 << Record->getTagKind() << Record; 5808 Complained = true; 5809 } 5810 5811 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 5812 << F->getType()->isReferenceType() 5813 << F->getDeclName(); 5814 } 5815 } 5816 } 5817 5818 if (Record->getIdentifier()) { 5819 // C++ [class.mem]p13: 5820 // If T is the name of a class, then each of the following shall have a 5821 // name different from T: 5822 // - every member of every anonymous union that is a member of class T. 5823 // 5824 // C++ [class.mem]p14: 5825 // In addition, if class T has a user-declared constructor (12.1), every 5826 // non-static data member of class T shall have a name different from T. 5827 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 5828 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 5829 ++I) { 5830 NamedDecl *D = *I; 5831 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 5832 isa<IndirectFieldDecl>(D)) { 5833 Diag(D->getLocation(), diag::err_member_name_of_class) 5834 << D->getDeclName(); 5835 break; 5836 } 5837 } 5838 } 5839 5840 // Warn if the class has virtual methods but non-virtual public destructor. 5841 if (Record->isPolymorphic() && !Record->isDependentType()) { 5842 CXXDestructorDecl *dtor = Record->getDestructor(); 5843 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 5844 !Record->hasAttr<FinalAttr>()) 5845 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 5846 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 5847 } 5848 5849 if (Record->isAbstract()) { 5850 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 5851 Diag(Record->getLocation(), diag::warn_abstract_final_class) 5852 << FA->isSpelledAsSealed(); 5853 DiagnoseAbstractType(Record); 5854 } 5855 } 5856 5857 bool HasMethodWithOverrideControl = false, 5858 HasOverridingMethodWithoutOverrideControl = false; 5859 if (!Record->isDependentType()) { 5860 for (auto *M : Record->methods()) { 5861 // See if a method overloads virtual methods in a base 5862 // class without overriding any. 5863 if (!M->isStatic()) 5864 DiagnoseHiddenVirtualMethods(M); 5865 if (M->hasAttr<OverrideAttr>()) 5866 HasMethodWithOverrideControl = true; 5867 else if (M->size_overridden_methods() > 0) 5868 HasOverridingMethodWithoutOverrideControl = true; 5869 // Check whether the explicitly-defaulted special members are valid. 5870 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 5871 CheckExplicitlyDefaultedSpecialMember(M); 5872 5873 // For an explicitly defaulted or deleted special member, we defer 5874 // determining triviality until the class is complete. That time is now! 5875 CXXSpecialMember CSM = getSpecialMember(M); 5876 if (!M->isImplicit() && !M->isUserProvided()) { 5877 if (CSM != CXXInvalid) { 5878 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 5879 5880 // Inform the class that we've finished declaring this member. 5881 Record->finishedDefaultedOrDeletedMember(M); 5882 } 5883 } 5884 5885 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 5886 M->hasAttr<DLLExportAttr>()) { 5887 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5888 M->isTrivial() && 5889 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 5890 CSM == CXXDestructor)) 5891 M->dropAttr<DLLExportAttr>(); 5892 5893 if (M->hasAttr<DLLExportAttr>()) { 5894 DefineImplicitSpecialMember(*this, M, M->getLocation()); 5895 ActOnFinishInlineFunctionDef(M); 5896 } 5897 } 5898 } 5899 } 5900 5901 if (HasMethodWithOverrideControl && 5902 HasOverridingMethodWithoutOverrideControl) { 5903 // At least one method has the 'override' control declared. 5904 // Diagnose all other overridden methods which do not have 'override' specified on them. 5905 for (auto *M : Record->methods()) 5906 DiagnoseAbsenceOfOverrideControl(M); 5907 } 5908 5909 // ms_struct is a request to use the same ABI rules as MSVC. Check 5910 // whether this class uses any C++ features that are implemented 5911 // completely differently in MSVC, and if so, emit a diagnostic. 5912 // That diagnostic defaults to an error, but we allow projects to 5913 // map it down to a warning (or ignore it). It's a fairly common 5914 // practice among users of the ms_struct pragma to mass-annotate 5915 // headers, sweeping up a bunch of types that the project doesn't 5916 // really rely on MSVC-compatible layout for. We must therefore 5917 // support "ms_struct except for C++ stuff" as a secondary ABI. 5918 if (Record->isMsStruct(Context) && 5919 (Record->isPolymorphic() || Record->getNumBases())) { 5920 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 5921 } 5922 5923 checkClassLevelDLLAttribute(Record); 5924 5925 Record->setCanPassInRegisters(computeCanPassInRegisters(*this, Record)); 5926 } 5927 5928 /// Look up the special member function that would be called by a special 5929 /// member function for a subobject of class type. 5930 /// 5931 /// \param Class The class type of the subobject. 5932 /// \param CSM The kind of special member function. 5933 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 5934 /// \param ConstRHS True if this is a copy operation with a const object 5935 /// on its RHS, that is, if the argument to the outer special member 5936 /// function is 'const' and this is not a field marked 'mutable'. 5937 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 5938 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 5939 unsigned FieldQuals, bool ConstRHS) { 5940 unsigned LHSQuals = 0; 5941 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 5942 LHSQuals = FieldQuals; 5943 5944 unsigned RHSQuals = FieldQuals; 5945 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 5946 RHSQuals = 0; 5947 else if (ConstRHS) 5948 RHSQuals |= Qualifiers::Const; 5949 5950 return S.LookupSpecialMember(Class, CSM, 5951 RHSQuals & Qualifiers::Const, 5952 RHSQuals & Qualifiers::Volatile, 5953 false, 5954 LHSQuals & Qualifiers::Const, 5955 LHSQuals & Qualifiers::Volatile); 5956 } 5957 5958 class Sema::InheritedConstructorInfo { 5959 Sema &S; 5960 SourceLocation UseLoc; 5961 5962 /// A mapping from the base classes through which the constructor was 5963 /// inherited to the using shadow declaration in that base class (or a null 5964 /// pointer if the constructor was declared in that base class). 5965 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 5966 InheritedFromBases; 5967 5968 public: 5969 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 5970 ConstructorUsingShadowDecl *Shadow) 5971 : S(S), UseLoc(UseLoc) { 5972 bool DiagnosedMultipleConstructedBases = false; 5973 CXXRecordDecl *ConstructedBase = nullptr; 5974 UsingDecl *ConstructedBaseUsing = nullptr; 5975 5976 // Find the set of such base class subobjects and check that there's a 5977 // unique constructed subobject. 5978 for (auto *D : Shadow->redecls()) { 5979 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 5980 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 5981 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 5982 5983 InheritedFromBases.insert( 5984 std::make_pair(DNominatedBase->getCanonicalDecl(), 5985 DShadow->getNominatedBaseClassShadowDecl())); 5986 if (DShadow->constructsVirtualBase()) 5987 InheritedFromBases.insert( 5988 std::make_pair(DConstructedBase->getCanonicalDecl(), 5989 DShadow->getConstructedBaseClassShadowDecl())); 5990 else 5991 assert(DNominatedBase == DConstructedBase); 5992 5993 // [class.inhctor.init]p2: 5994 // If the constructor was inherited from multiple base class subobjects 5995 // of type B, the program is ill-formed. 5996 if (!ConstructedBase) { 5997 ConstructedBase = DConstructedBase; 5998 ConstructedBaseUsing = D->getUsingDecl(); 5999 } else if (ConstructedBase != DConstructedBase && 6000 !Shadow->isInvalidDecl()) { 6001 if (!DiagnosedMultipleConstructedBases) { 6002 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6003 << Shadow->getTargetDecl(); 6004 S.Diag(ConstructedBaseUsing->getLocation(), 6005 diag::note_ambiguous_inherited_constructor_using) 6006 << ConstructedBase; 6007 DiagnosedMultipleConstructedBases = true; 6008 } 6009 S.Diag(D->getUsingDecl()->getLocation(), 6010 diag::note_ambiguous_inherited_constructor_using) 6011 << DConstructedBase; 6012 } 6013 } 6014 6015 if (DiagnosedMultipleConstructedBases) 6016 Shadow->setInvalidDecl(); 6017 } 6018 6019 /// Find the constructor to use for inherited construction of a base class, 6020 /// and whether that base class constructor inherits the constructor from a 6021 /// virtual base class (in which case it won't actually invoke it). 6022 std::pair<CXXConstructorDecl *, bool> 6023 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6024 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6025 if (It == InheritedFromBases.end()) 6026 return std::make_pair(nullptr, false); 6027 6028 // This is an intermediary class. 6029 if (It->second) 6030 return std::make_pair( 6031 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6032 It->second->constructsVirtualBase()); 6033 6034 // This is the base class from which the constructor was inherited. 6035 return std::make_pair(Ctor, false); 6036 } 6037 }; 6038 6039 /// Is the special member function which would be selected to perform the 6040 /// specified operation on the specified class type a constexpr constructor? 6041 static bool 6042 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6043 Sema::CXXSpecialMember CSM, unsigned Quals, 6044 bool ConstRHS, 6045 CXXConstructorDecl *InheritedCtor = nullptr, 6046 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6047 // If we're inheriting a constructor, see if we need to call it for this base 6048 // class. 6049 if (InheritedCtor) { 6050 assert(CSM == Sema::CXXDefaultConstructor); 6051 auto BaseCtor = 6052 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6053 if (BaseCtor) 6054 return BaseCtor->isConstexpr(); 6055 } 6056 6057 if (CSM == Sema::CXXDefaultConstructor) 6058 return ClassDecl->hasConstexprDefaultConstructor(); 6059 6060 Sema::SpecialMemberOverloadResult SMOR = 6061 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6062 if (!SMOR.getMethod()) 6063 // A constructor we wouldn't select can't be "involved in initializing" 6064 // anything. 6065 return true; 6066 return SMOR.getMethod()->isConstexpr(); 6067 } 6068 6069 /// Determine whether the specified special member function would be constexpr 6070 /// if it were implicitly defined. 6071 static bool defaultedSpecialMemberIsConstexpr( 6072 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6073 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6074 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6075 if (!S.getLangOpts().CPlusPlus11) 6076 return false; 6077 6078 // C++11 [dcl.constexpr]p4: 6079 // In the definition of a constexpr constructor [...] 6080 bool Ctor = true; 6081 switch (CSM) { 6082 case Sema::CXXDefaultConstructor: 6083 if (Inherited) 6084 break; 6085 // Since default constructor lookup is essentially trivial (and cannot 6086 // involve, for instance, template instantiation), we compute whether a 6087 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6088 // 6089 // This is important for performance; we need to know whether the default 6090 // constructor is constexpr to determine whether the type is a literal type. 6091 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6092 6093 case Sema::CXXCopyConstructor: 6094 case Sema::CXXMoveConstructor: 6095 // For copy or move constructors, we need to perform overload resolution. 6096 break; 6097 6098 case Sema::CXXCopyAssignment: 6099 case Sema::CXXMoveAssignment: 6100 if (!S.getLangOpts().CPlusPlus14) 6101 return false; 6102 // In C++1y, we need to perform overload resolution. 6103 Ctor = false; 6104 break; 6105 6106 case Sema::CXXDestructor: 6107 case Sema::CXXInvalid: 6108 return false; 6109 } 6110 6111 // -- if the class is a non-empty union, or for each non-empty anonymous 6112 // union member of a non-union class, exactly one non-static data member 6113 // shall be initialized; [DR1359] 6114 // 6115 // If we squint, this is guaranteed, since exactly one non-static data member 6116 // will be initialized (if the constructor isn't deleted), we just don't know 6117 // which one. 6118 if (Ctor && ClassDecl->isUnion()) 6119 return CSM == Sema::CXXDefaultConstructor 6120 ? ClassDecl->hasInClassInitializer() || 6121 !ClassDecl->hasVariantMembers() 6122 : true; 6123 6124 // -- the class shall not have any virtual base classes; 6125 if (Ctor && ClassDecl->getNumVBases()) 6126 return false; 6127 6128 // C++1y [class.copy]p26: 6129 // -- [the class] is a literal type, and 6130 if (!Ctor && !ClassDecl->isLiteral()) 6131 return false; 6132 6133 // -- every constructor involved in initializing [...] base class 6134 // sub-objects shall be a constexpr constructor; 6135 // -- the assignment operator selected to copy/move each direct base 6136 // class is a constexpr function, and 6137 for (const auto &B : ClassDecl->bases()) { 6138 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6139 if (!BaseType) continue; 6140 6141 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6142 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6143 InheritedCtor, Inherited)) 6144 return false; 6145 } 6146 6147 // -- every constructor involved in initializing non-static data members 6148 // [...] shall be a constexpr constructor; 6149 // -- every non-static data member and base class sub-object shall be 6150 // initialized 6151 // -- for each non-static data member of X that is of class type (or array 6152 // thereof), the assignment operator selected to copy/move that member is 6153 // a constexpr function 6154 for (const auto *F : ClassDecl->fields()) { 6155 if (F->isInvalidDecl()) 6156 continue; 6157 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6158 continue; 6159 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6160 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6161 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6162 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6163 BaseType.getCVRQualifiers(), 6164 ConstArg && !F->isMutable())) 6165 return false; 6166 } else if (CSM == Sema::CXXDefaultConstructor) { 6167 return false; 6168 } 6169 } 6170 6171 // All OK, it's constexpr! 6172 return true; 6173 } 6174 6175 static Sema::ImplicitExceptionSpecification 6176 ComputeDefaultedSpecialMemberExceptionSpec( 6177 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6178 Sema::InheritedConstructorInfo *ICI); 6179 6180 static Sema::ImplicitExceptionSpecification 6181 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6182 auto CSM = S.getSpecialMember(MD); 6183 if (CSM != Sema::CXXInvalid) 6184 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6185 6186 auto *CD = cast<CXXConstructorDecl>(MD); 6187 assert(CD->getInheritedConstructor() && 6188 "only special members have implicit exception specs"); 6189 Sema::InheritedConstructorInfo ICI( 6190 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6191 return ComputeDefaultedSpecialMemberExceptionSpec( 6192 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6193 } 6194 6195 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6196 CXXMethodDecl *MD) { 6197 FunctionProtoType::ExtProtoInfo EPI; 6198 6199 // Build an exception specification pointing back at this member. 6200 EPI.ExceptionSpec.Type = EST_Unevaluated; 6201 EPI.ExceptionSpec.SourceDecl = MD; 6202 6203 // Set the calling convention to the default for C++ instance methods. 6204 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6205 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6206 /*IsCXXMethod=*/true)); 6207 return EPI; 6208 } 6209 6210 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6211 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6212 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6213 return; 6214 6215 // Evaluate the exception specification. 6216 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6217 auto ESI = IES.getExceptionSpec(); 6218 6219 // Update the type of the special member to use it. 6220 UpdateExceptionSpec(MD, ESI); 6221 6222 // A user-provided destructor can be defined outside the class. When that 6223 // happens, be sure to update the exception specification on both 6224 // declarations. 6225 const FunctionProtoType *CanonicalFPT = 6226 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6227 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6228 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6229 } 6230 6231 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6232 CXXRecordDecl *RD = MD->getParent(); 6233 CXXSpecialMember CSM = getSpecialMember(MD); 6234 6235 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6236 "not an explicitly-defaulted special member"); 6237 6238 // Whether this was the first-declared instance of the constructor. 6239 // This affects whether we implicitly add an exception spec and constexpr. 6240 bool First = MD == MD->getCanonicalDecl(); 6241 6242 bool HadError = false; 6243 6244 // C++11 [dcl.fct.def.default]p1: 6245 // A function that is explicitly defaulted shall 6246 // -- be a special member function (checked elsewhere), 6247 // -- have the same type (except for ref-qualifiers, and except that a 6248 // copy operation can take a non-const reference) as an implicit 6249 // declaration, and 6250 // -- not have default arguments. 6251 unsigned ExpectedParams = 1; 6252 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6253 ExpectedParams = 0; 6254 if (MD->getNumParams() != ExpectedParams) { 6255 // This also checks for default arguments: a copy or move constructor with a 6256 // default argument is classified as a default constructor, and assignment 6257 // operations and destructors can't have default arguments. 6258 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6259 << CSM << MD->getSourceRange(); 6260 HadError = true; 6261 } else if (MD->isVariadic()) { 6262 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6263 << CSM << MD->getSourceRange(); 6264 HadError = true; 6265 } 6266 6267 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6268 6269 bool CanHaveConstParam = false; 6270 if (CSM == CXXCopyConstructor) 6271 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6272 else if (CSM == CXXCopyAssignment) 6273 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6274 6275 QualType ReturnType = Context.VoidTy; 6276 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6277 // Check for return type matching. 6278 ReturnType = Type->getReturnType(); 6279 QualType ExpectedReturnType = 6280 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 6281 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6282 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6283 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6284 HadError = true; 6285 } 6286 6287 // A defaulted special member cannot have cv-qualifiers. 6288 if (Type->getTypeQuals()) { 6289 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6290 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6291 HadError = true; 6292 } 6293 } 6294 6295 // Check for parameter type matching. 6296 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6297 bool HasConstParam = false; 6298 if (ExpectedParams && ArgType->isReferenceType()) { 6299 // Argument must be reference to possibly-const T. 6300 QualType ReferentType = ArgType->getPointeeType(); 6301 HasConstParam = ReferentType.isConstQualified(); 6302 6303 if (ReferentType.isVolatileQualified()) { 6304 Diag(MD->getLocation(), 6305 diag::err_defaulted_special_member_volatile_param) << CSM; 6306 HadError = true; 6307 } 6308 6309 if (HasConstParam && !CanHaveConstParam) { 6310 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6311 Diag(MD->getLocation(), 6312 diag::err_defaulted_special_member_copy_const_param) 6313 << (CSM == CXXCopyAssignment); 6314 // FIXME: Explain why this special member can't be const. 6315 } else { 6316 Diag(MD->getLocation(), 6317 diag::err_defaulted_special_member_move_const_param) 6318 << (CSM == CXXMoveAssignment); 6319 } 6320 HadError = true; 6321 } 6322 } else if (ExpectedParams) { 6323 // A copy assignment operator can take its argument by value, but a 6324 // defaulted one cannot. 6325 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6326 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6327 HadError = true; 6328 } 6329 6330 // C++11 [dcl.fct.def.default]p2: 6331 // An explicitly-defaulted function may be declared constexpr only if it 6332 // would have been implicitly declared as constexpr, 6333 // Do not apply this rule to members of class templates, since core issue 1358 6334 // makes such functions always instantiate to constexpr functions. For 6335 // functions which cannot be constexpr (for non-constructors in C++11 and for 6336 // destructors in C++1y), this is checked elsewhere. 6337 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6338 HasConstParam); 6339 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6340 : isa<CXXConstructorDecl>(MD)) && 6341 MD->isConstexpr() && !Constexpr && 6342 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6343 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 6344 // FIXME: Explain why the special member can't be constexpr. 6345 HadError = true; 6346 } 6347 6348 // and may have an explicit exception-specification only if it is compatible 6349 // with the exception-specification on the implicit declaration. 6350 if (Type->hasExceptionSpec()) { 6351 // Delay the check if this is the first declaration of the special member, 6352 // since we may not have parsed some necessary in-class initializers yet. 6353 if (First) { 6354 // If the exception specification needs to be instantiated, do so now, 6355 // before we clobber it with an EST_Unevaluated specification below. 6356 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6357 InstantiateExceptionSpec(MD->getLocStart(), MD); 6358 Type = MD->getType()->getAs<FunctionProtoType>(); 6359 } 6360 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6361 } else 6362 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6363 } 6364 6365 // If a function is explicitly defaulted on its first declaration, 6366 if (First) { 6367 // -- it is implicitly considered to be constexpr if the implicit 6368 // definition would be, 6369 MD->setConstexpr(Constexpr); 6370 6371 // -- it is implicitly considered to have the same exception-specification 6372 // as if it had been implicitly declared, 6373 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6374 EPI.ExceptionSpec.Type = EST_Unevaluated; 6375 EPI.ExceptionSpec.SourceDecl = MD; 6376 MD->setType(Context.getFunctionType(ReturnType, 6377 llvm::makeArrayRef(&ArgType, 6378 ExpectedParams), 6379 EPI)); 6380 } 6381 6382 if (ShouldDeleteSpecialMember(MD, CSM)) { 6383 if (First) { 6384 SetDeclDeleted(MD, MD->getLocation()); 6385 } else { 6386 // C++11 [dcl.fct.def.default]p4: 6387 // [For a] user-provided explicitly-defaulted function [...] if such a 6388 // function is implicitly defined as deleted, the program is ill-formed. 6389 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6390 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6391 HadError = true; 6392 } 6393 } 6394 6395 if (HadError) 6396 MD->setInvalidDecl(); 6397 } 6398 6399 /// Check whether the exception specification provided for an 6400 /// explicitly-defaulted special member matches the exception specification 6401 /// that would have been generated for an implicit special member, per 6402 /// C++11 [dcl.fct.def.default]p2. 6403 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6404 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6405 // If the exception specification was explicitly specified but hadn't been 6406 // parsed when the method was defaulted, grab it now. 6407 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6408 SpecifiedType = 6409 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6410 6411 // Compute the implicit exception specification. 6412 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6413 /*IsCXXMethod=*/true); 6414 FunctionProtoType::ExtProtoInfo EPI(CC); 6415 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD); 6416 EPI.ExceptionSpec = IES.getExceptionSpec(); 6417 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6418 Context.getFunctionType(Context.VoidTy, None, EPI)); 6419 6420 // Ensure that it matches. 6421 CheckEquivalentExceptionSpec( 6422 PDiag(diag::err_incorrect_defaulted_exception_spec) 6423 << getSpecialMember(MD), PDiag(), 6424 ImplicitType, SourceLocation(), 6425 SpecifiedType, MD->getLocation()); 6426 } 6427 6428 void Sema::CheckDelayedMemberExceptionSpecs() { 6429 decltype(DelayedExceptionSpecChecks) Checks; 6430 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 6431 6432 std::swap(Checks, DelayedExceptionSpecChecks); 6433 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 6434 6435 // Perform any deferred checking of exception specifications for virtual 6436 // destructors. 6437 for (auto &Check : Checks) 6438 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6439 6440 // Check that any explicitly-defaulted methods have exception specifications 6441 // compatible with their implicit exception specifications. 6442 for (auto &Spec : Specs) 6443 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6444 } 6445 6446 namespace { 6447 /// CRTP base class for visiting operations performed by a special member 6448 /// function (or inherited constructor). 6449 template<typename Derived> 6450 struct SpecialMemberVisitor { 6451 Sema &S; 6452 CXXMethodDecl *MD; 6453 Sema::CXXSpecialMember CSM; 6454 Sema::InheritedConstructorInfo *ICI; 6455 6456 // Properties of the special member, computed for convenience. 6457 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6458 6459 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6460 Sema::InheritedConstructorInfo *ICI) 6461 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6462 switch (CSM) { 6463 case Sema::CXXDefaultConstructor: 6464 case Sema::CXXCopyConstructor: 6465 case Sema::CXXMoveConstructor: 6466 IsConstructor = true; 6467 break; 6468 case Sema::CXXCopyAssignment: 6469 case Sema::CXXMoveAssignment: 6470 IsAssignment = true; 6471 break; 6472 case Sema::CXXDestructor: 6473 break; 6474 case Sema::CXXInvalid: 6475 llvm_unreachable("invalid special member kind"); 6476 } 6477 6478 if (MD->getNumParams()) { 6479 if (const ReferenceType *RT = 6480 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6481 ConstArg = RT->getPointeeType().isConstQualified(); 6482 } 6483 } 6484 6485 Derived &getDerived() { return static_cast<Derived&>(*this); } 6486 6487 /// Is this a "move" special member? 6488 bool isMove() const { 6489 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6490 } 6491 6492 /// Look up the corresponding special member in the given class. 6493 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6494 unsigned Quals, bool IsMutable) { 6495 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6496 ConstArg && !IsMutable); 6497 } 6498 6499 /// Look up the constructor for the specified base class to see if it's 6500 /// overridden due to this being an inherited constructor. 6501 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6502 if (!ICI) 6503 return {}; 6504 assert(CSM == Sema::CXXDefaultConstructor); 6505 auto *BaseCtor = 6506 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6507 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6508 return MD; 6509 return {}; 6510 } 6511 6512 /// A base or member subobject. 6513 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6514 6515 /// Get the location to use for a subobject in diagnostics. 6516 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6517 // FIXME: For an indirect virtual base, the direct base leading to 6518 // the indirect virtual base would be a more useful choice. 6519 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6520 return B->getBaseTypeLoc(); 6521 else 6522 return Subobj.get<FieldDecl*>()->getLocation(); 6523 } 6524 6525 enum BasesToVisit { 6526 /// Visit all non-virtual (direct) bases. 6527 VisitNonVirtualBases, 6528 /// Visit all direct bases, virtual or not. 6529 VisitDirectBases, 6530 /// Visit all non-virtual bases, and all virtual bases if the class 6531 /// is not abstract. 6532 VisitPotentiallyConstructedBases, 6533 /// Visit all direct or virtual bases. 6534 VisitAllBases 6535 }; 6536 6537 // Visit the bases and members of the class. 6538 bool visit(BasesToVisit Bases) { 6539 CXXRecordDecl *RD = MD->getParent(); 6540 6541 if (Bases == VisitPotentiallyConstructedBases) 6542 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6543 6544 for (auto &B : RD->bases()) 6545 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6546 getDerived().visitBase(&B)) 6547 return true; 6548 6549 if (Bases == VisitAllBases) 6550 for (auto &B : RD->vbases()) 6551 if (getDerived().visitBase(&B)) 6552 return true; 6553 6554 for (auto *F : RD->fields()) 6555 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 6556 getDerived().visitField(F)) 6557 return true; 6558 6559 return false; 6560 } 6561 }; 6562 } 6563 6564 namespace { 6565 struct SpecialMemberDeletionInfo 6566 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 6567 bool Diagnose; 6568 6569 SourceLocation Loc; 6570 6571 bool AllFieldsAreConst; 6572 6573 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6574 Sema::CXXSpecialMember CSM, 6575 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6576 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 6577 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 6578 6579 bool inUnion() const { return MD->getParent()->isUnion(); } 6580 6581 Sema::CXXSpecialMember getEffectiveCSM() { 6582 return ICI ? Sema::CXXInvalid : CSM; 6583 } 6584 6585 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 6586 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 6587 6588 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6589 bool shouldDeleteForField(FieldDecl *FD); 6590 bool shouldDeleteForAllConstMembers(); 6591 6592 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6593 unsigned Quals); 6594 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6595 Sema::SpecialMemberOverloadResult SMOR, 6596 bool IsDtorCallInCtor); 6597 6598 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6599 }; 6600 } 6601 6602 /// Is the given special member inaccessible when used on the given 6603 /// sub-object. 6604 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6605 CXXMethodDecl *target) { 6606 /// If we're operating on a base class, the object type is the 6607 /// type of this special member. 6608 QualType objectTy; 6609 AccessSpecifier access = target->getAccess(); 6610 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6611 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6612 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6613 6614 // If we're operating on a field, the object type is the type of the field. 6615 } else { 6616 objectTy = S.Context.getTypeDeclType(target->getParent()); 6617 } 6618 6619 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6620 } 6621 6622 /// Check whether we should delete a special member due to the implicit 6623 /// definition containing a call to a special member of a subobject. 6624 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6625 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 6626 bool IsDtorCallInCtor) { 6627 CXXMethodDecl *Decl = SMOR.getMethod(); 6628 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6629 6630 int DiagKind = -1; 6631 6632 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6633 DiagKind = !Decl ? 0 : 1; 6634 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6635 DiagKind = 2; 6636 else if (!isAccessible(Subobj, Decl)) 6637 DiagKind = 3; 6638 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6639 !Decl->isTrivial()) { 6640 // A member of a union must have a trivial corresponding special member. 6641 // As a weird special case, a destructor call from a union's constructor 6642 // must be accessible and non-deleted, but need not be trivial. Such a 6643 // destructor is never actually called, but is semantically checked as 6644 // if it were. 6645 DiagKind = 4; 6646 } 6647 6648 if (DiagKind == -1) 6649 return false; 6650 6651 if (Diagnose) { 6652 if (Field) { 6653 S.Diag(Field->getLocation(), 6654 diag::note_deleted_special_member_class_subobject) 6655 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6656 << Field << DiagKind << IsDtorCallInCtor; 6657 } else { 6658 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6659 S.Diag(Base->getLocStart(), 6660 diag::note_deleted_special_member_class_subobject) 6661 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6662 << Base->getType() << DiagKind << IsDtorCallInCtor; 6663 } 6664 6665 if (DiagKind == 1) 6666 S.NoteDeletedFunction(Decl); 6667 // FIXME: Explain inaccessibility if DiagKind == 3. 6668 } 6669 6670 return true; 6671 } 6672 6673 /// Check whether we should delete a special member function due to having a 6674 /// direct or virtual base class or non-static data member of class type M. 6675 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6676 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6677 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6678 bool IsMutable = Field && Field->isMutable(); 6679 6680 // C++11 [class.ctor]p5: 6681 // -- any direct or virtual base class, or non-static data member with no 6682 // brace-or-equal-initializer, has class type M (or array thereof) and 6683 // either M has no default constructor or overload resolution as applied 6684 // to M's default constructor results in an ambiguity or in a function 6685 // that is deleted or inaccessible 6686 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6687 // -- a direct or virtual base class B that cannot be copied/moved because 6688 // overload resolution, as applied to B's corresponding special member, 6689 // results in an ambiguity or a function that is deleted or inaccessible 6690 // from the defaulted special member 6691 // C++11 [class.dtor]p5: 6692 // -- any direct or virtual base class [...] has a type with a destructor 6693 // that is deleted or inaccessible 6694 if (!(CSM == Sema::CXXDefaultConstructor && 6695 Field && Field->hasInClassInitializer()) && 6696 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 6697 false)) 6698 return true; 6699 6700 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 6701 // -- any direct or virtual base class or non-static data member has a 6702 // type with a destructor that is deleted or inaccessible 6703 if (IsConstructor) { 6704 Sema::SpecialMemberOverloadResult SMOR = 6705 S.LookupSpecialMember(Class, Sema::CXXDestructor, 6706 false, false, false, false, false); 6707 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 6708 return true; 6709 } 6710 6711 return false; 6712 } 6713 6714 /// Check whether we should delete a special member function due to the class 6715 /// having a particular direct or virtual base class. 6716 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 6717 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 6718 // If program is correct, BaseClass cannot be null, but if it is, the error 6719 // must be reported elsewhere. 6720 if (!BaseClass) 6721 return false; 6722 // If we have an inheriting constructor, check whether we're calling an 6723 // inherited constructor instead of a default constructor. 6724 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 6725 if (auto *BaseCtor = SMOR.getMethod()) { 6726 // Note that we do not check access along this path; other than that, 6727 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 6728 // FIXME: Check that the base has a usable destructor! Sink this into 6729 // shouldDeleteForClassSubobject. 6730 if (BaseCtor->isDeleted() && Diagnose) { 6731 S.Diag(Base->getLocStart(), 6732 diag::note_deleted_special_member_class_subobject) 6733 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6734 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false; 6735 S.NoteDeletedFunction(BaseCtor); 6736 } 6737 return BaseCtor->isDeleted(); 6738 } 6739 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 6740 } 6741 6742 /// Check whether we should delete a special member function due to the class 6743 /// having a particular non-static data member. 6744 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 6745 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 6746 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 6747 6748 if (CSM == Sema::CXXDefaultConstructor) { 6749 // For a default constructor, all references must be initialized in-class 6750 // and, if a union, it must have a non-const member. 6751 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 6752 if (Diagnose) 6753 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6754 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 6755 return true; 6756 } 6757 // C++11 [class.ctor]p5: any non-variant non-static data member of 6758 // const-qualified type (or array thereof) with no 6759 // brace-or-equal-initializer does not have a user-provided default 6760 // constructor. 6761 if (!inUnion() && FieldType.isConstQualified() && 6762 !FD->hasInClassInitializer() && 6763 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 6764 if (Diagnose) 6765 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6766 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 6767 return true; 6768 } 6769 6770 if (inUnion() && !FieldType.isConstQualified()) 6771 AllFieldsAreConst = false; 6772 } else if (CSM == Sema::CXXCopyConstructor) { 6773 // For a copy constructor, data members must not be of rvalue reference 6774 // type. 6775 if (FieldType->isRValueReferenceType()) { 6776 if (Diagnose) 6777 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 6778 << MD->getParent() << FD << FieldType; 6779 return true; 6780 } 6781 } else if (IsAssignment) { 6782 // For an assignment operator, data members must not be of reference type. 6783 if (FieldType->isReferenceType()) { 6784 if (Diagnose) 6785 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6786 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 6787 return true; 6788 } 6789 if (!FieldRecord && FieldType.isConstQualified()) { 6790 // C++11 [class.copy]p23: 6791 // -- a non-static data member of const non-class type (or array thereof) 6792 if (Diagnose) 6793 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6794 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 6795 return true; 6796 } 6797 } 6798 6799 if (FieldRecord) { 6800 // Some additional restrictions exist on the variant members. 6801 if (!inUnion() && FieldRecord->isUnion() && 6802 FieldRecord->isAnonymousStructOrUnion()) { 6803 bool AllVariantFieldsAreConst = true; 6804 6805 // FIXME: Handle anonymous unions declared within anonymous unions. 6806 for (auto *UI : FieldRecord->fields()) { 6807 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 6808 6809 if (!UnionFieldType.isConstQualified()) 6810 AllVariantFieldsAreConst = false; 6811 6812 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 6813 if (UnionFieldRecord && 6814 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 6815 UnionFieldType.getCVRQualifiers())) 6816 return true; 6817 } 6818 6819 // At least one member in each anonymous union must be non-const 6820 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 6821 !FieldRecord->field_empty()) { 6822 if (Diagnose) 6823 S.Diag(FieldRecord->getLocation(), 6824 diag::note_deleted_default_ctor_all_const) 6825 << !!ICI << MD->getParent() << /*anonymous union*/1; 6826 return true; 6827 } 6828 6829 // Don't check the implicit member of the anonymous union type. 6830 // This is technically non-conformant, but sanity demands it. 6831 return false; 6832 } 6833 6834 if (shouldDeleteForClassSubobject(FieldRecord, FD, 6835 FieldType.getCVRQualifiers())) 6836 return true; 6837 } 6838 6839 return false; 6840 } 6841 6842 /// C++11 [class.ctor] p5: 6843 /// A defaulted default constructor for a class X is defined as deleted if 6844 /// X is a union and all of its variant members are of const-qualified type. 6845 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 6846 // This is a silly definition, because it gives an empty union a deleted 6847 // default constructor. Don't do that. 6848 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 6849 bool AnyFields = false; 6850 for (auto *F : MD->getParent()->fields()) 6851 if ((AnyFields = !F->isUnnamedBitfield())) 6852 break; 6853 if (!AnyFields) 6854 return false; 6855 if (Diagnose) 6856 S.Diag(MD->getParent()->getLocation(), 6857 diag::note_deleted_default_ctor_all_const) 6858 << !!ICI << MD->getParent() << /*not anonymous union*/0; 6859 return true; 6860 } 6861 return false; 6862 } 6863 6864 /// Determine whether a defaulted special member function should be defined as 6865 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 6866 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 6867 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 6868 InheritedConstructorInfo *ICI, 6869 bool Diagnose) { 6870 if (MD->isInvalidDecl()) 6871 return false; 6872 CXXRecordDecl *RD = MD->getParent(); 6873 assert(!RD->isDependentType() && "do deletion after instantiation"); 6874 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 6875 return false; 6876 6877 // C++11 [expr.lambda.prim]p19: 6878 // The closure type associated with a lambda-expression has a 6879 // deleted (8.4.3) default constructor and a deleted copy 6880 // assignment operator. 6881 if (RD->isLambda() && 6882 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 6883 if (Diagnose) 6884 Diag(RD->getLocation(), diag::note_lambda_decl); 6885 return true; 6886 } 6887 6888 // For an anonymous struct or union, the copy and assignment special members 6889 // will never be used, so skip the check. For an anonymous union declared at 6890 // namespace scope, the constructor and destructor are used. 6891 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 6892 RD->isAnonymousStructOrUnion()) 6893 return false; 6894 6895 // C++11 [class.copy]p7, p18: 6896 // If the class definition declares a move constructor or move assignment 6897 // operator, an implicitly declared copy constructor or copy assignment 6898 // operator is defined as deleted. 6899 if (MD->isImplicit() && 6900 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 6901 CXXMethodDecl *UserDeclaredMove = nullptr; 6902 6903 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 6904 // deletion of the corresponding copy operation, not both copy operations. 6905 // MSVC 2015 has adopted the standards conforming behavior. 6906 bool DeletesOnlyMatchingCopy = 6907 getLangOpts().MSVCCompat && 6908 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 6909 6910 if (RD->hasUserDeclaredMoveConstructor() && 6911 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 6912 if (!Diagnose) return true; 6913 6914 // Find any user-declared move constructor. 6915 for (auto *I : RD->ctors()) { 6916 if (I->isMoveConstructor()) { 6917 UserDeclaredMove = I; 6918 break; 6919 } 6920 } 6921 assert(UserDeclaredMove); 6922 } else if (RD->hasUserDeclaredMoveAssignment() && 6923 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 6924 if (!Diagnose) return true; 6925 6926 // Find any user-declared move assignment operator. 6927 for (auto *I : RD->methods()) { 6928 if (I->isMoveAssignmentOperator()) { 6929 UserDeclaredMove = I; 6930 break; 6931 } 6932 } 6933 assert(UserDeclaredMove); 6934 } 6935 6936 if (UserDeclaredMove) { 6937 Diag(UserDeclaredMove->getLocation(), 6938 diag::note_deleted_copy_user_declared_move) 6939 << (CSM == CXXCopyAssignment) << RD 6940 << UserDeclaredMove->isMoveAssignmentOperator(); 6941 return true; 6942 } 6943 } 6944 6945 // Do access control from the special member function 6946 ContextRAII MethodContext(*this, MD); 6947 6948 // C++11 [class.dtor]p5: 6949 // -- for a virtual destructor, lookup of the non-array deallocation function 6950 // results in an ambiguity or in a function that is deleted or inaccessible 6951 if (CSM == CXXDestructor && MD->isVirtual()) { 6952 FunctionDecl *OperatorDelete = nullptr; 6953 DeclarationName Name = 6954 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6955 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 6956 OperatorDelete, /*Diagnose*/false)) { 6957 if (Diagnose) 6958 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 6959 return true; 6960 } 6961 } 6962 6963 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 6964 6965 // Per DR1611, do not consider virtual bases of constructors of abstract 6966 // classes, since we are not going to construct them. 6967 // Per DR1658, do not consider virtual bases of destructors of abstract 6968 // classes either. 6969 // Per DR2180, for assignment operators we only assign (and thus only 6970 // consider) direct bases. 6971 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 6972 : SMI.VisitPotentiallyConstructedBases)) 6973 return true; 6974 6975 if (SMI.shouldDeleteForAllConstMembers()) 6976 return true; 6977 6978 if (getLangOpts().CUDA) { 6979 // We should delete the special member in CUDA mode if target inference 6980 // failed. 6981 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 6982 Diagnose); 6983 } 6984 6985 return false; 6986 } 6987 6988 /// Perform lookup for a special member of the specified kind, and determine 6989 /// whether it is trivial. If the triviality can be determined without the 6990 /// lookup, skip it. This is intended for use when determining whether a 6991 /// special member of a containing object is trivial, and thus does not ever 6992 /// perform overload resolution for default constructors. 6993 /// 6994 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 6995 /// member that was most likely to be intended to be trivial, if any. 6996 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 6997 Sema::CXXSpecialMember CSM, unsigned Quals, 6998 bool ConstRHS, CXXMethodDecl **Selected) { 6999 if (Selected) 7000 *Selected = nullptr; 7001 7002 switch (CSM) { 7003 case Sema::CXXInvalid: 7004 llvm_unreachable("not a special member"); 7005 7006 case Sema::CXXDefaultConstructor: 7007 // C++11 [class.ctor]p5: 7008 // A default constructor is trivial if: 7009 // - all the [direct subobjects] have trivial default constructors 7010 // 7011 // Note, no overload resolution is performed in this case. 7012 if (RD->hasTrivialDefaultConstructor()) 7013 return true; 7014 7015 if (Selected) { 7016 // If there's a default constructor which could have been trivial, dig it 7017 // out. Otherwise, if there's any user-provided default constructor, point 7018 // to that as an example of why there's not a trivial one. 7019 CXXConstructorDecl *DefCtor = nullptr; 7020 if (RD->needsImplicitDefaultConstructor()) 7021 S.DeclareImplicitDefaultConstructor(RD); 7022 for (auto *CI : RD->ctors()) { 7023 if (!CI->isDefaultConstructor()) 7024 continue; 7025 DefCtor = CI; 7026 if (!DefCtor->isUserProvided()) 7027 break; 7028 } 7029 7030 *Selected = DefCtor; 7031 } 7032 7033 return false; 7034 7035 case Sema::CXXDestructor: 7036 // C++11 [class.dtor]p5: 7037 // A destructor is trivial if: 7038 // - all the direct [subobjects] have trivial destructors 7039 if (RD->hasTrivialDestructor()) 7040 return true; 7041 7042 if (Selected) { 7043 if (RD->needsImplicitDestructor()) 7044 S.DeclareImplicitDestructor(RD); 7045 *Selected = RD->getDestructor(); 7046 } 7047 7048 return false; 7049 7050 case Sema::CXXCopyConstructor: 7051 // C++11 [class.copy]p12: 7052 // A copy constructor is trivial if: 7053 // - the constructor selected to copy each direct [subobject] is trivial 7054 if (RD->hasTrivialCopyConstructor()) { 7055 if (Quals == Qualifiers::Const) 7056 // We must either select the trivial copy constructor or reach an 7057 // ambiguity; no need to actually perform overload resolution. 7058 return true; 7059 } else if (!Selected) { 7060 return false; 7061 } 7062 // In C++98, we are not supposed to perform overload resolution here, but we 7063 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7064 // cases like B as having a non-trivial copy constructor: 7065 // struct A { template<typename T> A(T&); }; 7066 // struct B { mutable A a; }; 7067 goto NeedOverloadResolution; 7068 7069 case Sema::CXXCopyAssignment: 7070 // C++11 [class.copy]p25: 7071 // A copy assignment operator is trivial if: 7072 // - the assignment operator selected to copy each direct [subobject] is 7073 // trivial 7074 if (RD->hasTrivialCopyAssignment()) { 7075 if (Quals == Qualifiers::Const) 7076 return true; 7077 } else if (!Selected) { 7078 return false; 7079 } 7080 // In C++98, we are not supposed to perform overload resolution here, but we 7081 // treat that as a language defect. 7082 goto NeedOverloadResolution; 7083 7084 case Sema::CXXMoveConstructor: 7085 case Sema::CXXMoveAssignment: 7086 NeedOverloadResolution: 7087 Sema::SpecialMemberOverloadResult SMOR = 7088 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7089 7090 // The standard doesn't describe how to behave if the lookup is ambiguous. 7091 // We treat it as not making the member non-trivial, just like the standard 7092 // mandates for the default constructor. This should rarely matter, because 7093 // the member will also be deleted. 7094 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7095 return true; 7096 7097 if (!SMOR.getMethod()) { 7098 assert(SMOR.getKind() == 7099 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7100 return false; 7101 } 7102 7103 // We deliberately don't check if we found a deleted special member. We're 7104 // not supposed to! 7105 if (Selected) 7106 *Selected = SMOR.getMethod(); 7107 return SMOR.getMethod()->isTrivial(); 7108 } 7109 7110 llvm_unreachable("unknown special method kind"); 7111 } 7112 7113 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7114 for (auto *CI : RD->ctors()) 7115 if (!CI->isImplicit()) 7116 return CI; 7117 7118 // Look for constructor templates. 7119 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7120 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7121 if (CXXConstructorDecl *CD = 7122 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7123 return CD; 7124 } 7125 7126 return nullptr; 7127 } 7128 7129 /// The kind of subobject we are checking for triviality. The values of this 7130 /// enumeration are used in diagnostics. 7131 enum TrivialSubobjectKind { 7132 /// The subobject is a base class. 7133 TSK_BaseClass, 7134 /// The subobject is a non-static data member. 7135 TSK_Field, 7136 /// The object is actually the complete object. 7137 TSK_CompleteObject 7138 }; 7139 7140 /// Check whether the special member selected for a given type would be trivial. 7141 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7142 QualType SubType, bool ConstRHS, 7143 Sema::CXXSpecialMember CSM, 7144 TrivialSubobjectKind Kind, 7145 bool Diagnose) { 7146 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7147 if (!SubRD) 7148 return true; 7149 7150 CXXMethodDecl *Selected; 7151 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7152 ConstRHS, Diagnose ? &Selected : nullptr)) 7153 return true; 7154 7155 if (Diagnose) { 7156 if (ConstRHS) 7157 SubType.addConst(); 7158 7159 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7160 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7161 << Kind << SubType.getUnqualifiedType(); 7162 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7163 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7164 } else if (!Selected) 7165 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7166 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7167 else if (Selected->isUserProvided()) { 7168 if (Kind == TSK_CompleteObject) 7169 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7170 << Kind << SubType.getUnqualifiedType() << CSM; 7171 else { 7172 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7173 << Kind << SubType.getUnqualifiedType() << CSM; 7174 S.Diag(Selected->getLocation(), diag::note_declared_at); 7175 } 7176 } else { 7177 if (Kind != TSK_CompleteObject) 7178 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7179 << Kind << SubType.getUnqualifiedType() << CSM; 7180 7181 // Explain why the defaulted or deleted special member isn't trivial. 7182 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 7183 } 7184 } 7185 7186 return false; 7187 } 7188 7189 /// Check whether the members of a class type allow a special member to be 7190 /// trivial. 7191 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7192 Sema::CXXSpecialMember CSM, 7193 bool ConstArg, bool Diagnose) { 7194 for (const auto *FI : RD->fields()) { 7195 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7196 continue; 7197 7198 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7199 7200 // Pretend anonymous struct or union members are members of this class. 7201 if (FI->isAnonymousStructOrUnion()) { 7202 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7203 CSM, ConstArg, Diagnose)) 7204 return false; 7205 continue; 7206 } 7207 7208 // C++11 [class.ctor]p5: 7209 // A default constructor is trivial if [...] 7210 // -- no non-static data member of its class has a 7211 // brace-or-equal-initializer 7212 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7213 if (Diagnose) 7214 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7215 return false; 7216 } 7217 7218 // Objective C ARC 4.3.5: 7219 // [...] nontrivally ownership-qualified types are [...] not trivially 7220 // default constructible, copy constructible, move constructible, copy 7221 // assignable, move assignable, or destructible [...] 7222 if (FieldType.hasNonTrivialObjCLifetime()) { 7223 if (Diagnose) 7224 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7225 << RD << FieldType.getObjCLifetime(); 7226 return false; 7227 } 7228 7229 bool ConstRHS = ConstArg && !FI->isMutable(); 7230 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7231 CSM, TSK_Field, Diagnose)) 7232 return false; 7233 } 7234 7235 return true; 7236 } 7237 7238 /// Diagnose why the specified class does not have a trivial special member of 7239 /// the given kind. 7240 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7241 QualType Ty = Context.getRecordType(RD); 7242 7243 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7244 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7245 TSK_CompleteObject, /*Diagnose*/true); 7246 } 7247 7248 /// Determine whether a defaulted or deleted special member function is trivial, 7249 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7250 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7251 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7252 bool Diagnose) { 7253 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7254 7255 CXXRecordDecl *RD = MD->getParent(); 7256 7257 bool ConstArg = false; 7258 7259 // C++11 [class.copy]p12, p25: [DR1593] 7260 // A [special member] is trivial if [...] its parameter-type-list is 7261 // equivalent to the parameter-type-list of an implicit declaration [...] 7262 switch (CSM) { 7263 case CXXDefaultConstructor: 7264 case CXXDestructor: 7265 // Trivial default constructors and destructors cannot have parameters. 7266 break; 7267 7268 case CXXCopyConstructor: 7269 case CXXCopyAssignment: { 7270 // Trivial copy operations always have const, non-volatile parameter types. 7271 ConstArg = true; 7272 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7273 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7274 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7275 if (Diagnose) 7276 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7277 << Param0->getSourceRange() << Param0->getType() 7278 << Context.getLValueReferenceType( 7279 Context.getRecordType(RD).withConst()); 7280 return false; 7281 } 7282 break; 7283 } 7284 7285 case CXXMoveConstructor: 7286 case CXXMoveAssignment: { 7287 // Trivial move operations always have non-cv-qualified parameters. 7288 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7289 const RValueReferenceType *RT = 7290 Param0->getType()->getAs<RValueReferenceType>(); 7291 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7292 if (Diagnose) 7293 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7294 << Param0->getSourceRange() << Param0->getType() 7295 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7296 return false; 7297 } 7298 break; 7299 } 7300 7301 case CXXInvalid: 7302 llvm_unreachable("not a special member"); 7303 } 7304 7305 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7306 if (Diagnose) 7307 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7308 diag::note_nontrivial_default_arg) 7309 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7310 return false; 7311 } 7312 if (MD->isVariadic()) { 7313 if (Diagnose) 7314 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7315 return false; 7316 } 7317 7318 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7319 // A copy/move [constructor or assignment operator] is trivial if 7320 // -- the [member] selected to copy/move each direct base class subobject 7321 // is trivial 7322 // 7323 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7324 // A [default constructor or destructor] is trivial if 7325 // -- all the direct base classes have trivial [default constructors or 7326 // destructors] 7327 for (const auto &BI : RD->bases()) 7328 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 7329 ConstArg, CSM, TSK_BaseClass, Diagnose)) 7330 return false; 7331 7332 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7333 // A copy/move [constructor or assignment operator] for a class X is 7334 // trivial if 7335 // -- for each non-static data member of X that is of class type (or array 7336 // thereof), the constructor selected to copy/move that member is 7337 // trivial 7338 // 7339 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7340 // A [default constructor or destructor] is trivial if 7341 // -- for all of the non-static data members of its class that are of class 7342 // type (or array thereof), each such class has a trivial [default 7343 // constructor or destructor] 7344 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 7345 return false; 7346 7347 // C++11 [class.dtor]p5: 7348 // A destructor is trivial if [...] 7349 // -- the destructor is not virtual 7350 if (CSM == CXXDestructor && MD->isVirtual()) { 7351 if (Diagnose) 7352 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7353 return false; 7354 } 7355 7356 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7357 // A [special member] for class X is trivial if [...] 7358 // -- class X has no virtual functions and no virtual base classes 7359 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7360 if (!Diagnose) 7361 return false; 7362 7363 if (RD->getNumVBases()) { 7364 // Check for virtual bases. We already know that the corresponding 7365 // member in all bases is trivial, so vbases must all be direct. 7366 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7367 assert(BS.isVirtual()); 7368 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 7369 return false; 7370 } 7371 7372 // Must have a virtual method. 7373 for (const auto *MI : RD->methods()) { 7374 if (MI->isVirtual()) { 7375 SourceLocation MLoc = MI->getLocStart(); 7376 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7377 return false; 7378 } 7379 } 7380 7381 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7382 } 7383 7384 // Looks like it's trivial! 7385 return true; 7386 } 7387 7388 namespace { 7389 struct FindHiddenVirtualMethod { 7390 Sema *S; 7391 CXXMethodDecl *Method; 7392 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7393 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7394 7395 private: 7396 /// Check whether any most overriden method from MD in Methods 7397 static bool CheckMostOverridenMethods( 7398 const CXXMethodDecl *MD, 7399 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7400 if (MD->size_overridden_methods() == 0) 7401 return Methods.count(MD->getCanonicalDecl()); 7402 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7403 E = MD->end_overridden_methods(); 7404 I != E; ++I) 7405 if (CheckMostOverridenMethods(*I, Methods)) 7406 return true; 7407 return false; 7408 } 7409 7410 public: 7411 /// Member lookup function that determines whether a given C++ 7412 /// method overloads virtual methods in a base class without overriding any, 7413 /// to be used with CXXRecordDecl::lookupInBases(). 7414 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7415 RecordDecl *BaseRecord = 7416 Specifier->getType()->getAs<RecordType>()->getDecl(); 7417 7418 DeclarationName Name = Method->getDeclName(); 7419 assert(Name.getNameKind() == DeclarationName::Identifier); 7420 7421 bool foundSameNameMethod = false; 7422 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7423 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7424 Path.Decls = Path.Decls.slice(1)) { 7425 NamedDecl *D = Path.Decls.front(); 7426 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7427 MD = MD->getCanonicalDecl(); 7428 foundSameNameMethod = true; 7429 // Interested only in hidden virtual methods. 7430 if (!MD->isVirtual()) 7431 continue; 7432 // If the method we are checking overrides a method from its base 7433 // don't warn about the other overloaded methods. Clang deviates from 7434 // GCC by only diagnosing overloads of inherited virtual functions that 7435 // do not override any other virtual functions in the base. GCC's 7436 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7437 // function from a base class. These cases may be better served by a 7438 // warning (not specific to virtual functions) on call sites when the 7439 // call would select a different function from the base class, were it 7440 // visible. 7441 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7442 if (!S->IsOverload(Method, MD, false)) 7443 return true; 7444 // Collect the overload only if its hidden. 7445 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7446 overloadedMethods.push_back(MD); 7447 } 7448 } 7449 7450 if (foundSameNameMethod) 7451 OverloadedMethods.append(overloadedMethods.begin(), 7452 overloadedMethods.end()); 7453 return foundSameNameMethod; 7454 } 7455 }; 7456 } // end anonymous namespace 7457 7458 /// \brief Add the most overriden methods from MD to Methods 7459 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7460 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7461 if (MD->size_overridden_methods() == 0) 7462 Methods.insert(MD->getCanonicalDecl()); 7463 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7464 E = MD->end_overridden_methods(); 7465 I != E; ++I) 7466 AddMostOverridenMethods(*I, Methods); 7467 } 7468 7469 /// \brief Check if a method overloads virtual methods in a base class without 7470 /// overriding any. 7471 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7472 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7473 if (!MD->getDeclName().isIdentifier()) 7474 return; 7475 7476 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7477 /*bool RecordPaths=*/false, 7478 /*bool DetectVirtual=*/false); 7479 FindHiddenVirtualMethod FHVM; 7480 FHVM.Method = MD; 7481 FHVM.S = this; 7482 7483 // Keep the base methods that were overriden or introduced in the subclass 7484 // by 'using' in a set. A base method not in this set is hidden. 7485 CXXRecordDecl *DC = MD->getParent(); 7486 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7487 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7488 NamedDecl *ND = *I; 7489 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7490 ND = shad->getTargetDecl(); 7491 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7492 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7493 } 7494 7495 if (DC->lookupInBases(FHVM, Paths)) 7496 OverloadedMethods = FHVM.OverloadedMethods; 7497 } 7498 7499 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7500 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7501 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7502 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7503 PartialDiagnostic PD = PDiag( 7504 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7505 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7506 Diag(overloadedMD->getLocation(), PD); 7507 } 7508 } 7509 7510 /// \brief Diagnose methods which overload virtual methods in a base class 7511 /// without overriding any. 7512 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7513 if (MD->isInvalidDecl()) 7514 return; 7515 7516 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7517 return; 7518 7519 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7520 FindHiddenVirtualMethods(MD, OverloadedMethods); 7521 if (!OverloadedMethods.empty()) { 7522 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7523 << MD << (OverloadedMethods.size() > 1); 7524 7525 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7526 } 7527 } 7528 7529 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 7530 Decl *TagDecl, 7531 SourceLocation LBrac, 7532 SourceLocation RBrac, 7533 AttributeList *AttrList) { 7534 if (!TagDecl) 7535 return; 7536 7537 AdjustDeclIfTemplate(TagDecl); 7538 7539 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 7540 if (l->getKind() != AttributeList::AT_Visibility) 7541 continue; 7542 l->setInvalid(); 7543 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 7544 l->getName(); 7545 } 7546 7547 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7548 // strict aliasing violation! 7549 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7550 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7551 7552 CheckCompletedCXXClass(dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 7553 } 7554 7555 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7556 /// special functions, such as the default constructor, copy 7557 /// constructor, or destructor, to the given C++ class (C++ 7558 /// [special]p1). This routine can only be executed just before the 7559 /// definition of the class is complete. 7560 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7561 if (ClassDecl->needsImplicitDefaultConstructor()) { 7562 ++ASTContext::NumImplicitDefaultConstructors; 7563 7564 if (ClassDecl->hasInheritedConstructor()) 7565 DeclareImplicitDefaultConstructor(ClassDecl); 7566 } 7567 7568 if (ClassDecl->needsImplicitCopyConstructor()) { 7569 ++ASTContext::NumImplicitCopyConstructors; 7570 7571 // If the properties or semantics of the copy constructor couldn't be 7572 // determined while the class was being declared, force a declaration 7573 // of it now. 7574 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7575 ClassDecl->hasInheritedConstructor()) 7576 DeclareImplicitCopyConstructor(ClassDecl); 7577 // For the MS ABI we need to know whether the copy ctor is deleted. A 7578 // prerequisite for deleting the implicit copy ctor is that the class has a 7579 // move ctor or move assignment that is either user-declared or whose 7580 // semantics are inherited from a subobject. FIXME: We should provide a more 7581 // direct way for CodeGen to ask whether the constructor was deleted. 7582 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 7583 (ClassDecl->hasUserDeclaredMoveConstructor() || 7584 ClassDecl->needsOverloadResolutionForMoveConstructor() || 7585 ClassDecl->hasUserDeclaredMoveAssignment() || 7586 ClassDecl->needsOverloadResolutionForMoveAssignment())) 7587 DeclareImplicitCopyConstructor(ClassDecl); 7588 } 7589 7590 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7591 ++ASTContext::NumImplicitMoveConstructors; 7592 7593 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7594 ClassDecl->hasInheritedConstructor()) 7595 DeclareImplicitMoveConstructor(ClassDecl); 7596 } 7597 7598 if (ClassDecl->needsImplicitCopyAssignment()) { 7599 ++ASTContext::NumImplicitCopyAssignmentOperators; 7600 7601 // If we have a dynamic class, then the copy assignment operator may be 7602 // virtual, so we have to declare it immediately. This ensures that, e.g., 7603 // it shows up in the right place in the vtable and that we diagnose 7604 // problems with the implicit exception specification. 7605 if (ClassDecl->isDynamicClass() || 7606 ClassDecl->needsOverloadResolutionForCopyAssignment() || 7607 ClassDecl->hasInheritedAssignment()) 7608 DeclareImplicitCopyAssignment(ClassDecl); 7609 } 7610 7611 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 7612 ++ASTContext::NumImplicitMoveAssignmentOperators; 7613 7614 // Likewise for the move assignment operator. 7615 if (ClassDecl->isDynamicClass() || 7616 ClassDecl->needsOverloadResolutionForMoveAssignment() || 7617 ClassDecl->hasInheritedAssignment()) 7618 DeclareImplicitMoveAssignment(ClassDecl); 7619 } 7620 7621 if (ClassDecl->needsImplicitDestructor()) { 7622 ++ASTContext::NumImplicitDestructors; 7623 7624 // If we have a dynamic class, then the destructor may be virtual, so we 7625 // have to declare the destructor immediately. This ensures that, e.g., it 7626 // shows up in the right place in the vtable and that we diagnose problems 7627 // with the implicit exception specification. 7628 if (ClassDecl->isDynamicClass() || 7629 ClassDecl->needsOverloadResolutionForDestructor()) 7630 DeclareImplicitDestructor(ClassDecl); 7631 } 7632 } 7633 7634 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 7635 if (!D) 7636 return 0; 7637 7638 // The order of template parameters is not important here. All names 7639 // get added to the same scope. 7640 SmallVector<TemplateParameterList *, 4> ParameterLists; 7641 7642 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 7643 D = TD->getTemplatedDecl(); 7644 7645 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 7646 ParameterLists.push_back(PSD->getTemplateParameters()); 7647 7648 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 7649 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 7650 ParameterLists.push_back(DD->getTemplateParameterList(i)); 7651 7652 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7653 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 7654 ParameterLists.push_back(FTD->getTemplateParameters()); 7655 } 7656 } 7657 7658 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 7659 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 7660 ParameterLists.push_back(TD->getTemplateParameterList(i)); 7661 7662 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 7663 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 7664 ParameterLists.push_back(CTD->getTemplateParameters()); 7665 } 7666 } 7667 7668 unsigned Count = 0; 7669 for (TemplateParameterList *Params : ParameterLists) { 7670 if (Params->size() > 0) 7671 // Ignore explicit specializations; they don't contribute to the template 7672 // depth. 7673 ++Count; 7674 for (NamedDecl *Param : *Params) { 7675 if (Param->getDeclName()) { 7676 S->AddDecl(Param); 7677 IdResolver.AddDecl(Param); 7678 } 7679 } 7680 } 7681 7682 return Count; 7683 } 7684 7685 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7686 if (!RecordD) return; 7687 AdjustDeclIfTemplate(RecordD); 7688 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 7689 PushDeclContext(S, Record); 7690 } 7691 7692 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7693 if (!RecordD) return; 7694 PopDeclContext(); 7695 } 7696 7697 /// This is used to implement the constant expression evaluation part of the 7698 /// attribute enable_if extension. There is nothing in standard C++ which would 7699 /// require reentering parameters. 7700 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 7701 if (!Param) 7702 return; 7703 7704 S->AddDecl(Param); 7705 if (Param->getDeclName()) 7706 IdResolver.AddDecl(Param); 7707 } 7708 7709 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 7710 /// parsing a top-level (non-nested) C++ class, and we are now 7711 /// parsing those parts of the given Method declaration that could 7712 /// not be parsed earlier (C++ [class.mem]p2), such as default 7713 /// arguments. This action should enter the scope of the given 7714 /// Method declaration as if we had just parsed the qualified method 7715 /// name. However, it should not bring the parameters into scope; 7716 /// that will be performed by ActOnDelayedCXXMethodParameter. 7717 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7718 } 7719 7720 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 7721 /// C++ method declaration. We're (re-)introducing the given 7722 /// function parameter into scope for use in parsing later parts of 7723 /// the method declaration. For example, we could see an 7724 /// ActOnParamDefaultArgument event for this parameter. 7725 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 7726 if (!ParamD) 7727 return; 7728 7729 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 7730 7731 // If this parameter has an unparsed default argument, clear it out 7732 // to make way for the parsed default argument. 7733 if (Param->hasUnparsedDefaultArg()) 7734 Param->setDefaultArg(nullptr); 7735 7736 S->AddDecl(Param); 7737 if (Param->getDeclName()) 7738 IdResolver.AddDecl(Param); 7739 } 7740 7741 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 7742 /// processing the delayed method declaration for Method. The method 7743 /// declaration is now considered finished. There may be a separate 7744 /// ActOnStartOfFunctionDef action later (not necessarily 7745 /// immediately!) for this method, if it was also defined inside the 7746 /// class body. 7747 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7748 if (!MethodD) 7749 return; 7750 7751 AdjustDeclIfTemplate(MethodD); 7752 7753 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 7754 7755 // Now that we have our default arguments, check the constructor 7756 // again. It could produce additional diagnostics or affect whether 7757 // the class has implicitly-declared destructors, among other 7758 // things. 7759 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 7760 CheckConstructor(Constructor); 7761 7762 // Check the default arguments, which we may have added. 7763 if (!Method->isInvalidDecl()) 7764 CheckCXXDefaultArguments(Method); 7765 } 7766 7767 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 7768 /// the well-formedness of the constructor declarator @p D with type @p 7769 /// R. If there are any errors in the declarator, this routine will 7770 /// emit diagnostics and set the invalid bit to true. In any case, the type 7771 /// will be updated to reflect a well-formed type for the constructor and 7772 /// returned. 7773 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 7774 StorageClass &SC) { 7775 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7776 7777 // C++ [class.ctor]p3: 7778 // A constructor shall not be virtual (10.3) or static (9.4). A 7779 // constructor can be invoked for a const, volatile or const 7780 // volatile object. A constructor shall not be declared const, 7781 // volatile, or const volatile (9.3.2). 7782 if (isVirtual) { 7783 if (!D.isInvalidType()) 7784 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7785 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 7786 << SourceRange(D.getIdentifierLoc()); 7787 D.setInvalidType(); 7788 } 7789 if (SC == SC_Static) { 7790 if (!D.isInvalidType()) 7791 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7792 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7793 << SourceRange(D.getIdentifierLoc()); 7794 D.setInvalidType(); 7795 SC = SC_None; 7796 } 7797 7798 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7799 diagnoseIgnoredQualifiers( 7800 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 7801 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 7802 D.getDeclSpec().getRestrictSpecLoc(), 7803 D.getDeclSpec().getAtomicSpecLoc()); 7804 D.setInvalidType(); 7805 } 7806 7807 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7808 if (FTI.TypeQuals != 0) { 7809 if (FTI.TypeQuals & Qualifiers::Const) 7810 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7811 << "const" << SourceRange(D.getIdentifierLoc()); 7812 if (FTI.TypeQuals & Qualifiers::Volatile) 7813 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7814 << "volatile" << SourceRange(D.getIdentifierLoc()); 7815 if (FTI.TypeQuals & Qualifiers::Restrict) 7816 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7817 << "restrict" << SourceRange(D.getIdentifierLoc()); 7818 D.setInvalidType(); 7819 } 7820 7821 // C++0x [class.ctor]p4: 7822 // A constructor shall not be declared with a ref-qualifier. 7823 if (FTI.hasRefQualifier()) { 7824 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 7825 << FTI.RefQualifierIsLValueRef 7826 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7827 D.setInvalidType(); 7828 } 7829 7830 // Rebuild the function type "R" without any type qualifiers (in 7831 // case any of the errors above fired) and with "void" as the 7832 // return type, since constructors don't have return types. 7833 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7834 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 7835 return R; 7836 7837 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 7838 EPI.TypeQuals = 0; 7839 EPI.RefQualifier = RQ_None; 7840 7841 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 7842 } 7843 7844 /// CheckConstructor - Checks a fully-formed constructor for 7845 /// well-formedness, issuing any diagnostics required. Returns true if 7846 /// the constructor declarator is invalid. 7847 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 7848 CXXRecordDecl *ClassDecl 7849 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 7850 if (!ClassDecl) 7851 return Constructor->setInvalidDecl(); 7852 7853 // C++ [class.copy]p3: 7854 // A declaration of a constructor for a class X is ill-formed if 7855 // its first parameter is of type (optionally cv-qualified) X and 7856 // either there are no other parameters or else all other 7857 // parameters have default arguments. 7858 if (!Constructor->isInvalidDecl() && 7859 ((Constructor->getNumParams() == 1) || 7860 (Constructor->getNumParams() > 1 && 7861 Constructor->getParamDecl(1)->hasDefaultArg())) && 7862 Constructor->getTemplateSpecializationKind() 7863 != TSK_ImplicitInstantiation) { 7864 QualType ParamType = Constructor->getParamDecl(0)->getType(); 7865 QualType ClassTy = Context.getTagDeclType(ClassDecl); 7866 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 7867 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 7868 const char *ConstRef 7869 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 7870 : " const &"; 7871 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 7872 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 7873 7874 // FIXME: Rather that making the constructor invalid, we should endeavor 7875 // to fix the type. 7876 Constructor->setInvalidDecl(); 7877 } 7878 } 7879 } 7880 7881 /// CheckDestructor - Checks a fully-formed destructor definition for 7882 /// well-formedness, issuing any diagnostics required. Returns true 7883 /// on error. 7884 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 7885 CXXRecordDecl *RD = Destructor->getParent(); 7886 7887 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 7888 SourceLocation Loc; 7889 7890 if (!Destructor->isImplicit()) 7891 Loc = Destructor->getLocation(); 7892 else 7893 Loc = RD->getLocation(); 7894 7895 // If we have a virtual destructor, look up the deallocation function 7896 if (FunctionDecl *OperatorDelete = 7897 FindDeallocationFunctionForDestructor(Loc, RD)) { 7898 MarkFunctionReferenced(Loc, OperatorDelete); 7899 Destructor->setOperatorDelete(OperatorDelete); 7900 } 7901 } 7902 7903 return false; 7904 } 7905 7906 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 7907 /// the well-formednes of the destructor declarator @p D with type @p 7908 /// R. If there are any errors in the declarator, this routine will 7909 /// emit diagnostics and set the declarator to invalid. Even if this happens, 7910 /// will be updated to reflect a well-formed type for the destructor and 7911 /// returned. 7912 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 7913 StorageClass& SC) { 7914 // C++ [class.dtor]p1: 7915 // [...] A typedef-name that names a class is a class-name 7916 // (7.1.3); however, a typedef-name that names a class shall not 7917 // be used as the identifier in the declarator for a destructor 7918 // declaration. 7919 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 7920 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 7921 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7922 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 7923 else if (const TemplateSpecializationType *TST = 7924 DeclaratorType->getAs<TemplateSpecializationType>()) 7925 if (TST->isTypeAlias()) 7926 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7927 << DeclaratorType << 1; 7928 7929 // C++ [class.dtor]p2: 7930 // A destructor is used to destroy objects of its class type. A 7931 // destructor takes no parameters, and no return type can be 7932 // specified for it (not even void). The address of a destructor 7933 // shall not be taken. A destructor shall not be static. A 7934 // destructor can be invoked for a const, volatile or const 7935 // volatile object. A destructor shall not be declared const, 7936 // volatile or const volatile (9.3.2). 7937 if (SC == SC_Static) { 7938 if (!D.isInvalidType()) 7939 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 7940 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7941 << SourceRange(D.getIdentifierLoc()) 7942 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7943 7944 SC = SC_None; 7945 } 7946 if (!D.isInvalidType()) { 7947 // Destructors don't have return types, but the parser will 7948 // happily parse something like: 7949 // 7950 // class X { 7951 // float ~X(); 7952 // }; 7953 // 7954 // The return type will be eliminated later. 7955 if (D.getDeclSpec().hasTypeSpecifier()) 7956 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 7957 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7958 << SourceRange(D.getIdentifierLoc()); 7959 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7960 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 7961 SourceLocation(), 7962 D.getDeclSpec().getConstSpecLoc(), 7963 D.getDeclSpec().getVolatileSpecLoc(), 7964 D.getDeclSpec().getRestrictSpecLoc(), 7965 D.getDeclSpec().getAtomicSpecLoc()); 7966 D.setInvalidType(); 7967 } 7968 } 7969 7970 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7971 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 7972 if (FTI.TypeQuals & Qualifiers::Const) 7973 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7974 << "const" << SourceRange(D.getIdentifierLoc()); 7975 if (FTI.TypeQuals & Qualifiers::Volatile) 7976 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7977 << "volatile" << SourceRange(D.getIdentifierLoc()); 7978 if (FTI.TypeQuals & Qualifiers::Restrict) 7979 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7980 << "restrict" << SourceRange(D.getIdentifierLoc()); 7981 D.setInvalidType(); 7982 } 7983 7984 // C++0x [class.dtor]p2: 7985 // A destructor shall not be declared with a ref-qualifier. 7986 if (FTI.hasRefQualifier()) { 7987 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 7988 << FTI.RefQualifierIsLValueRef 7989 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7990 D.setInvalidType(); 7991 } 7992 7993 // Make sure we don't have any parameters. 7994 if (FTIHasNonVoidParameters(FTI)) { 7995 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 7996 7997 // Delete the parameters. 7998 FTI.freeParams(); 7999 D.setInvalidType(); 8000 } 8001 8002 // Make sure the destructor isn't variadic. 8003 if (FTI.isVariadic) { 8004 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8005 D.setInvalidType(); 8006 } 8007 8008 // Rebuild the function type "R" without any type qualifiers or 8009 // parameters (in case any of the errors above fired) and with 8010 // "void" as the return type, since destructors don't have return 8011 // types. 8012 if (!D.isInvalidType()) 8013 return R; 8014 8015 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8016 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8017 EPI.Variadic = false; 8018 EPI.TypeQuals = 0; 8019 EPI.RefQualifier = RQ_None; 8020 return Context.getFunctionType(Context.VoidTy, None, EPI); 8021 } 8022 8023 static void extendLeft(SourceRange &R, SourceRange Before) { 8024 if (Before.isInvalid()) 8025 return; 8026 R.setBegin(Before.getBegin()); 8027 if (R.getEnd().isInvalid()) 8028 R.setEnd(Before.getEnd()); 8029 } 8030 8031 static void extendRight(SourceRange &R, SourceRange After) { 8032 if (After.isInvalid()) 8033 return; 8034 if (R.getBegin().isInvalid()) 8035 R.setBegin(After.getBegin()); 8036 R.setEnd(After.getEnd()); 8037 } 8038 8039 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8040 /// well-formednes of the conversion function declarator @p D with 8041 /// type @p R. If there are any errors in the declarator, this routine 8042 /// will emit diagnostics and return true. Otherwise, it will return 8043 /// false. Either way, the type @p R will be updated to reflect a 8044 /// well-formed type for the conversion operator. 8045 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8046 StorageClass& SC) { 8047 // C++ [class.conv.fct]p1: 8048 // Neither parameter types nor return type can be specified. The 8049 // type of a conversion function (8.3.5) is "function taking no 8050 // parameter returning conversion-type-id." 8051 if (SC == SC_Static) { 8052 if (!D.isInvalidType()) 8053 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8054 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8055 << D.getName().getSourceRange(); 8056 D.setInvalidType(); 8057 SC = SC_None; 8058 } 8059 8060 TypeSourceInfo *ConvTSI = nullptr; 8061 QualType ConvType = 8062 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8063 8064 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 8065 // Conversion functions don't have return types, but the parser will 8066 // happily parse something like: 8067 // 8068 // class X { 8069 // float operator bool(); 8070 // }; 8071 // 8072 // The return type will be changed later anyway. 8073 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8074 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8075 << SourceRange(D.getIdentifierLoc()); 8076 D.setInvalidType(); 8077 } 8078 8079 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8080 8081 // Make sure we don't have any parameters. 8082 if (Proto->getNumParams() > 0) { 8083 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8084 8085 // Delete the parameters. 8086 D.getFunctionTypeInfo().freeParams(); 8087 D.setInvalidType(); 8088 } else if (Proto->isVariadic()) { 8089 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8090 D.setInvalidType(); 8091 } 8092 8093 // Diagnose "&operator bool()" and other such nonsense. This 8094 // is actually a gcc extension which we don't support. 8095 if (Proto->getReturnType() != ConvType) { 8096 bool NeedsTypedef = false; 8097 SourceRange Before, After; 8098 8099 // Walk the chunks and extract information on them for our diagnostic. 8100 bool PastFunctionChunk = false; 8101 for (auto &Chunk : D.type_objects()) { 8102 switch (Chunk.Kind) { 8103 case DeclaratorChunk::Function: 8104 if (!PastFunctionChunk) { 8105 if (Chunk.Fun.HasTrailingReturnType) { 8106 TypeSourceInfo *TRT = nullptr; 8107 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8108 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8109 } 8110 PastFunctionChunk = true; 8111 break; 8112 } 8113 // Fall through. 8114 case DeclaratorChunk::Array: 8115 NeedsTypedef = true; 8116 extendRight(After, Chunk.getSourceRange()); 8117 break; 8118 8119 case DeclaratorChunk::Pointer: 8120 case DeclaratorChunk::BlockPointer: 8121 case DeclaratorChunk::Reference: 8122 case DeclaratorChunk::MemberPointer: 8123 case DeclaratorChunk::Pipe: 8124 extendLeft(Before, Chunk.getSourceRange()); 8125 break; 8126 8127 case DeclaratorChunk::Paren: 8128 extendLeft(Before, Chunk.Loc); 8129 extendRight(After, Chunk.EndLoc); 8130 break; 8131 } 8132 } 8133 8134 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8135 After.isValid() ? After.getBegin() : 8136 D.getIdentifierLoc(); 8137 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8138 DB << Before << After; 8139 8140 if (!NeedsTypedef) { 8141 DB << /*don't need a typedef*/0; 8142 8143 // If we can provide a correct fix-it hint, do so. 8144 if (After.isInvalid() && ConvTSI) { 8145 SourceLocation InsertLoc = 8146 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 8147 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8148 << FixItHint::CreateInsertionFromRange( 8149 InsertLoc, CharSourceRange::getTokenRange(Before)) 8150 << FixItHint::CreateRemoval(Before); 8151 } 8152 } else if (!Proto->getReturnType()->isDependentType()) { 8153 DB << /*typedef*/1 << Proto->getReturnType(); 8154 } else if (getLangOpts().CPlusPlus11) { 8155 DB << /*alias template*/2 << Proto->getReturnType(); 8156 } else { 8157 DB << /*might not be fixable*/3; 8158 } 8159 8160 // Recover by incorporating the other type chunks into the result type. 8161 // Note, this does *not* change the name of the function. This is compatible 8162 // with the GCC extension: 8163 // struct S { &operator int(); } s; 8164 // int &r = s.operator int(); // ok in GCC 8165 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8166 ConvType = Proto->getReturnType(); 8167 } 8168 8169 // C++ [class.conv.fct]p4: 8170 // The conversion-type-id shall not represent a function type nor 8171 // an array type. 8172 if (ConvType->isArrayType()) { 8173 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8174 ConvType = Context.getPointerType(ConvType); 8175 D.setInvalidType(); 8176 } else if (ConvType->isFunctionType()) { 8177 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8178 ConvType = Context.getPointerType(ConvType); 8179 D.setInvalidType(); 8180 } 8181 8182 // Rebuild the function type "R" without any parameters (in case any 8183 // of the errors above fired) and with the conversion type as the 8184 // return type. 8185 if (D.isInvalidType()) 8186 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8187 8188 // C++0x explicit conversion operators. 8189 if (D.getDeclSpec().isExplicitSpecified()) 8190 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8191 getLangOpts().CPlusPlus11 ? 8192 diag::warn_cxx98_compat_explicit_conversion_functions : 8193 diag::ext_explicit_conversion_functions) 8194 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 8195 } 8196 8197 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8198 /// the declaration of the given C++ conversion function. This routine 8199 /// is responsible for recording the conversion function in the C++ 8200 /// class, if possible. 8201 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8202 assert(Conversion && "Expected to receive a conversion function declaration"); 8203 8204 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8205 8206 // Make sure we aren't redeclaring the conversion function. 8207 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8208 8209 // C++ [class.conv.fct]p1: 8210 // [...] A conversion function is never used to convert a 8211 // (possibly cv-qualified) object to the (possibly cv-qualified) 8212 // same object type (or a reference to it), to a (possibly 8213 // cv-qualified) base class of that type (or a reference to it), 8214 // or to (possibly cv-qualified) void. 8215 // FIXME: Suppress this warning if the conversion function ends up being a 8216 // virtual function that overrides a virtual function in a base class. 8217 QualType ClassType 8218 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8219 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8220 ConvType = ConvTypeRef->getPointeeType(); 8221 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8222 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8223 /* Suppress diagnostics for instantiations. */; 8224 else if (ConvType->isRecordType()) { 8225 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8226 if (ConvType == ClassType) 8227 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8228 << ClassType; 8229 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8230 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8231 << ClassType << ConvType; 8232 } else if (ConvType->isVoidType()) { 8233 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8234 << ClassType << ConvType; 8235 } 8236 8237 if (FunctionTemplateDecl *ConversionTemplate 8238 = Conversion->getDescribedFunctionTemplate()) 8239 return ConversionTemplate; 8240 8241 return Conversion; 8242 } 8243 8244 namespace { 8245 /// Utility class to accumulate and print a diagnostic listing the invalid 8246 /// specifier(s) on a declaration. 8247 struct BadSpecifierDiagnoser { 8248 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8249 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8250 ~BadSpecifierDiagnoser() { 8251 Diagnostic << Specifiers; 8252 } 8253 8254 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8255 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8256 } 8257 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8258 return check(SpecLoc, 8259 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8260 } 8261 void check(SourceLocation SpecLoc, const char *Spec) { 8262 if (SpecLoc.isInvalid()) return; 8263 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8264 if (!Specifiers.empty()) Specifiers += " "; 8265 Specifiers += Spec; 8266 } 8267 8268 Sema &S; 8269 Sema::SemaDiagnosticBuilder Diagnostic; 8270 std::string Specifiers; 8271 }; 8272 } 8273 8274 /// Check the validity of a declarator that we parsed for a deduction-guide. 8275 /// These aren't actually declarators in the grammar, so we need to check that 8276 /// the user didn't specify any pieces that are not part of the deduction-guide 8277 /// grammar. 8278 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8279 StorageClass &SC) { 8280 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8281 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8282 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8283 8284 // C++ [temp.deduct.guide]p3: 8285 // A deduction-gide shall be declared in the same scope as the 8286 // corresponding class template. 8287 if (!CurContext->getRedeclContext()->Equals( 8288 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8289 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8290 << GuidedTemplateDecl; 8291 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8292 } 8293 8294 auto &DS = D.getMutableDeclSpec(); 8295 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8296 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8297 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8298 DS.isNoreturnSpecified() || DS.isConstexprSpecified() || 8299 DS.isConceptSpecified()) { 8300 BadSpecifierDiagnoser Diagnoser( 8301 *this, D.getIdentifierLoc(), 8302 diag::err_deduction_guide_invalid_specifier); 8303 8304 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8305 DS.ClearStorageClassSpecs(); 8306 SC = SC_None; 8307 8308 // 'explicit' is permitted. 8309 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8310 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8311 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8312 Diagnoser.check(DS.getConceptSpecLoc(), "concept"); 8313 DS.ClearConstexprSpec(); 8314 DS.ClearConceptSpec(); 8315 8316 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8317 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8318 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8319 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8320 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8321 DS.ClearTypeQualifiers(); 8322 8323 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8324 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8325 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8326 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8327 DS.ClearTypeSpecType(); 8328 } 8329 8330 if (D.isInvalidType()) 8331 return; 8332 8333 // Check the declarator is simple enough. 8334 bool FoundFunction = false; 8335 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8336 if (Chunk.Kind == DeclaratorChunk::Paren) 8337 continue; 8338 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8339 Diag(D.getDeclSpec().getLocStart(), 8340 diag::err_deduction_guide_with_complex_decl) 8341 << D.getSourceRange(); 8342 break; 8343 } 8344 if (!Chunk.Fun.hasTrailingReturnType()) { 8345 Diag(D.getName().getLocStart(), 8346 diag::err_deduction_guide_no_trailing_return_type); 8347 break; 8348 } 8349 8350 // Check that the return type is written as a specialization of 8351 // the template specified as the deduction-guide's name. 8352 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8353 TypeSourceInfo *TSI = nullptr; 8354 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8355 assert(TSI && "deduction guide has valid type but invalid return type?"); 8356 bool AcceptableReturnType = false; 8357 bool MightInstantiateToSpecialization = false; 8358 if (auto RetTST = 8359 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8360 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8361 bool TemplateMatches = 8362 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8363 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8364 AcceptableReturnType = true; 8365 else { 8366 // This could still instantiate to the right type, unless we know it 8367 // names the wrong class template. 8368 auto *TD = SpecifiedName.getAsTemplateDecl(); 8369 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8370 !TemplateMatches); 8371 } 8372 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8373 MightInstantiateToSpecialization = true; 8374 } 8375 8376 if (!AcceptableReturnType) { 8377 Diag(TSI->getTypeLoc().getLocStart(), 8378 diag::err_deduction_guide_bad_trailing_return_type) 8379 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization 8380 << TSI->getTypeLoc().getSourceRange(); 8381 } 8382 8383 // Keep going to check that we don't have any inner declarator pieces (we 8384 // could still have a function returning a pointer to a function). 8385 FoundFunction = true; 8386 } 8387 8388 if (D.isFunctionDefinition()) 8389 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8390 } 8391 8392 //===----------------------------------------------------------------------===// 8393 // Namespace Handling 8394 //===----------------------------------------------------------------------===// 8395 8396 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 8397 /// reopened. 8398 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8399 SourceLocation Loc, 8400 IdentifierInfo *II, bool *IsInline, 8401 NamespaceDecl *PrevNS) { 8402 assert(*IsInline != PrevNS->isInline()); 8403 8404 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8405 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8406 // inline namespaces, with the intention of bringing names into namespace std. 8407 // 8408 // We support this just well enough to get that case working; this is not 8409 // sufficient to support reopening namespaces as inline in general. 8410 if (*IsInline && II && II->getName().startswith("__atomic") && 8411 S.getSourceManager().isInSystemHeader(Loc)) { 8412 // Mark all prior declarations of the namespace as inline. 8413 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8414 NS = NS->getPreviousDecl()) 8415 NS->setInline(*IsInline); 8416 // Patch up the lookup table for the containing namespace. This isn't really 8417 // correct, but it's good enough for this particular case. 8418 for (auto *I : PrevNS->decls()) 8419 if (auto *ND = dyn_cast<NamedDecl>(I)) 8420 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8421 return; 8422 } 8423 8424 if (PrevNS->isInline()) 8425 // The user probably just forgot the 'inline', so suggest that it 8426 // be added back. 8427 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8428 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8429 else 8430 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8431 8432 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8433 *IsInline = PrevNS->isInline(); 8434 } 8435 8436 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8437 /// definition. 8438 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 8439 SourceLocation InlineLoc, 8440 SourceLocation NamespaceLoc, 8441 SourceLocation IdentLoc, 8442 IdentifierInfo *II, 8443 SourceLocation LBrace, 8444 AttributeList *AttrList, 8445 UsingDirectiveDecl *&UD) { 8446 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8447 // For anonymous namespace, take the location of the left brace. 8448 SourceLocation Loc = II ? IdentLoc : LBrace; 8449 bool IsInline = InlineLoc.isValid(); 8450 bool IsInvalid = false; 8451 bool IsStd = false; 8452 bool AddToKnown = false; 8453 Scope *DeclRegionScope = NamespcScope->getParent(); 8454 8455 NamespaceDecl *PrevNS = nullptr; 8456 if (II) { 8457 // C++ [namespace.def]p2: 8458 // The identifier in an original-namespace-definition shall not 8459 // have been previously defined in the declarative region in 8460 // which the original-namespace-definition appears. The 8461 // identifier in an original-namespace-definition is the name of 8462 // the namespace. Subsequently in that declarative region, it is 8463 // treated as an original-namespace-name. 8464 // 8465 // Since namespace names are unique in their scope, and we don't 8466 // look through using directives, just look for any ordinary names 8467 // as if by qualified name lookup. 8468 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration); 8469 LookupQualifiedName(R, CurContext->getRedeclContext()); 8470 NamedDecl *PrevDecl = 8471 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8472 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8473 8474 if (PrevNS) { 8475 // This is an extended namespace definition. 8476 if (IsInline != PrevNS->isInline()) 8477 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8478 &IsInline, PrevNS); 8479 } else if (PrevDecl) { 8480 // This is an invalid name redefinition. 8481 Diag(Loc, diag::err_redefinition_different_kind) 8482 << II; 8483 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8484 IsInvalid = true; 8485 // Continue on to push Namespc as current DeclContext and return it. 8486 } else if (II->isStr("std") && 8487 CurContext->getRedeclContext()->isTranslationUnit()) { 8488 // This is the first "real" definition of the namespace "std", so update 8489 // our cache of the "std" namespace to point at this definition. 8490 PrevNS = getStdNamespace(); 8491 IsStd = true; 8492 AddToKnown = !IsInline; 8493 } else { 8494 // We've seen this namespace for the first time. 8495 AddToKnown = !IsInline; 8496 } 8497 } else { 8498 // Anonymous namespaces. 8499 8500 // Determine whether the parent already has an anonymous namespace. 8501 DeclContext *Parent = CurContext->getRedeclContext(); 8502 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8503 PrevNS = TU->getAnonymousNamespace(); 8504 } else { 8505 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8506 PrevNS = ND->getAnonymousNamespace(); 8507 } 8508 8509 if (PrevNS && IsInline != PrevNS->isInline()) 8510 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8511 &IsInline, PrevNS); 8512 } 8513 8514 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8515 StartLoc, Loc, II, PrevNS); 8516 if (IsInvalid) 8517 Namespc->setInvalidDecl(); 8518 8519 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8520 AddPragmaAttributes(DeclRegionScope, Namespc); 8521 8522 // FIXME: Should we be merging attributes? 8523 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8524 PushNamespaceVisibilityAttr(Attr, Loc); 8525 8526 if (IsStd) 8527 StdNamespace = Namespc; 8528 if (AddToKnown) 8529 KnownNamespaces[Namespc] = false; 8530 8531 if (II) { 8532 PushOnScopeChains(Namespc, DeclRegionScope); 8533 } else { 8534 // Link the anonymous namespace into its parent. 8535 DeclContext *Parent = CurContext->getRedeclContext(); 8536 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8537 TU->setAnonymousNamespace(Namespc); 8538 } else { 8539 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8540 } 8541 8542 CurContext->addDecl(Namespc); 8543 8544 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8545 // behaves as if it were replaced by 8546 // namespace unique { /* empty body */ } 8547 // using namespace unique; 8548 // namespace unique { namespace-body } 8549 // where all occurrences of 'unique' in a translation unit are 8550 // replaced by the same identifier and this identifier differs 8551 // from all other identifiers in the entire program. 8552 8553 // We just create the namespace with an empty name and then add an 8554 // implicit using declaration, just like the standard suggests. 8555 // 8556 // CodeGen enforces the "universally unique" aspect by giving all 8557 // declarations semantically contained within an anonymous 8558 // namespace internal linkage. 8559 8560 if (!PrevNS) { 8561 UD = UsingDirectiveDecl::Create(Context, Parent, 8562 /* 'using' */ LBrace, 8563 /* 'namespace' */ SourceLocation(), 8564 /* qualifier */ NestedNameSpecifierLoc(), 8565 /* identifier */ SourceLocation(), 8566 Namespc, 8567 /* Ancestor */ Parent); 8568 UD->setImplicit(); 8569 Parent->addDecl(UD); 8570 } 8571 } 8572 8573 ActOnDocumentableDecl(Namespc); 8574 8575 // Although we could have an invalid decl (i.e. the namespace name is a 8576 // redefinition), push it as current DeclContext and try to continue parsing. 8577 // FIXME: We should be able to push Namespc here, so that the each DeclContext 8578 // for the namespace has the declarations that showed up in that particular 8579 // namespace definition. 8580 PushDeclContext(NamespcScope, Namespc); 8581 return Namespc; 8582 } 8583 8584 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 8585 /// is a namespace alias, returns the namespace it points to. 8586 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 8587 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 8588 return AD->getNamespace(); 8589 return dyn_cast_or_null<NamespaceDecl>(D); 8590 } 8591 8592 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 8593 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 8594 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 8595 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 8596 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 8597 Namespc->setRBraceLoc(RBrace); 8598 PopDeclContext(); 8599 if (Namespc->hasAttr<VisibilityAttr>()) 8600 PopPragmaVisibility(true, RBrace); 8601 } 8602 8603 CXXRecordDecl *Sema::getStdBadAlloc() const { 8604 return cast_or_null<CXXRecordDecl>( 8605 StdBadAlloc.get(Context.getExternalSource())); 8606 } 8607 8608 EnumDecl *Sema::getStdAlignValT() const { 8609 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 8610 } 8611 8612 NamespaceDecl *Sema::getStdNamespace() const { 8613 return cast_or_null<NamespaceDecl>( 8614 StdNamespace.get(Context.getExternalSource())); 8615 } 8616 8617 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 8618 if (!StdExperimentalNamespaceCache) { 8619 if (auto Std = getStdNamespace()) { 8620 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 8621 SourceLocation(), LookupNamespaceName); 8622 if (!LookupQualifiedName(Result, Std) || 8623 !(StdExperimentalNamespaceCache = 8624 Result.getAsSingle<NamespaceDecl>())) 8625 Result.suppressDiagnostics(); 8626 } 8627 } 8628 return StdExperimentalNamespaceCache; 8629 } 8630 8631 /// \brief Retrieve the special "std" namespace, which may require us to 8632 /// implicitly define the namespace. 8633 NamespaceDecl *Sema::getOrCreateStdNamespace() { 8634 if (!StdNamespace) { 8635 // The "std" namespace has not yet been defined, so build one implicitly. 8636 StdNamespace = NamespaceDecl::Create(Context, 8637 Context.getTranslationUnitDecl(), 8638 /*Inline=*/false, 8639 SourceLocation(), SourceLocation(), 8640 &PP.getIdentifierTable().get("std"), 8641 /*PrevDecl=*/nullptr); 8642 getStdNamespace()->setImplicit(true); 8643 } 8644 8645 return getStdNamespace(); 8646 } 8647 8648 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 8649 assert(getLangOpts().CPlusPlus && 8650 "Looking for std::initializer_list outside of C++."); 8651 8652 // We're looking for implicit instantiations of 8653 // template <typename E> class std::initializer_list. 8654 8655 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 8656 return false; 8657 8658 ClassTemplateDecl *Template = nullptr; 8659 const TemplateArgument *Arguments = nullptr; 8660 8661 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8662 8663 ClassTemplateSpecializationDecl *Specialization = 8664 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 8665 if (!Specialization) 8666 return false; 8667 8668 Template = Specialization->getSpecializedTemplate(); 8669 Arguments = Specialization->getTemplateArgs().data(); 8670 } else if (const TemplateSpecializationType *TST = 8671 Ty->getAs<TemplateSpecializationType>()) { 8672 Template = dyn_cast_or_null<ClassTemplateDecl>( 8673 TST->getTemplateName().getAsTemplateDecl()); 8674 Arguments = TST->getArgs(); 8675 } 8676 if (!Template) 8677 return false; 8678 8679 if (!StdInitializerList) { 8680 // Haven't recognized std::initializer_list yet, maybe this is it. 8681 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 8682 if (TemplateClass->getIdentifier() != 8683 &PP.getIdentifierTable().get("initializer_list") || 8684 !getStdNamespace()->InEnclosingNamespaceSetOf( 8685 TemplateClass->getDeclContext())) 8686 return false; 8687 // This is a template called std::initializer_list, but is it the right 8688 // template? 8689 TemplateParameterList *Params = Template->getTemplateParameters(); 8690 if (Params->getMinRequiredArguments() != 1) 8691 return false; 8692 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 8693 return false; 8694 8695 // It's the right template. 8696 StdInitializerList = Template; 8697 } 8698 8699 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 8700 return false; 8701 8702 // This is an instance of std::initializer_list. Find the argument type. 8703 if (Element) 8704 *Element = Arguments[0].getAsType(); 8705 return true; 8706 } 8707 8708 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 8709 NamespaceDecl *Std = S.getStdNamespace(); 8710 if (!Std) { 8711 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8712 return nullptr; 8713 } 8714 8715 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 8716 Loc, Sema::LookupOrdinaryName); 8717 if (!S.LookupQualifiedName(Result, Std)) { 8718 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8719 return nullptr; 8720 } 8721 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 8722 if (!Template) { 8723 Result.suppressDiagnostics(); 8724 // We found something weird. Complain about the first thing we found. 8725 NamedDecl *Found = *Result.begin(); 8726 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 8727 return nullptr; 8728 } 8729 8730 // We found some template called std::initializer_list. Now verify that it's 8731 // correct. 8732 TemplateParameterList *Params = Template->getTemplateParameters(); 8733 if (Params->getMinRequiredArguments() != 1 || 8734 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 8735 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 8736 return nullptr; 8737 } 8738 8739 return Template; 8740 } 8741 8742 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 8743 if (!StdInitializerList) { 8744 StdInitializerList = LookupStdInitializerList(*this, Loc); 8745 if (!StdInitializerList) 8746 return QualType(); 8747 } 8748 8749 TemplateArgumentListInfo Args(Loc, Loc); 8750 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 8751 Context.getTrivialTypeSourceInfo(Element, 8752 Loc))); 8753 return Context.getCanonicalType( 8754 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 8755 } 8756 8757 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 8758 // C++ [dcl.init.list]p2: 8759 // A constructor is an initializer-list constructor if its first parameter 8760 // is of type std::initializer_list<E> or reference to possibly cv-qualified 8761 // std::initializer_list<E> for some type E, and either there are no other 8762 // parameters or else all other parameters have default arguments. 8763 if (Ctor->getNumParams() < 1 || 8764 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 8765 return false; 8766 8767 QualType ArgType = Ctor->getParamDecl(0)->getType(); 8768 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 8769 ArgType = RT->getPointeeType().getUnqualifiedType(); 8770 8771 return isStdInitializerList(ArgType, nullptr); 8772 } 8773 8774 /// \brief Determine whether a using statement is in a context where it will be 8775 /// apply in all contexts. 8776 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 8777 switch (CurContext->getDeclKind()) { 8778 case Decl::TranslationUnit: 8779 return true; 8780 case Decl::LinkageSpec: 8781 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 8782 default: 8783 return false; 8784 } 8785 } 8786 8787 namespace { 8788 8789 // Callback to only accept typo corrections that are namespaces. 8790 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 8791 public: 8792 bool ValidateCandidate(const TypoCorrection &candidate) override { 8793 if (NamedDecl *ND = candidate.getCorrectionDecl()) 8794 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 8795 return false; 8796 } 8797 }; 8798 8799 } 8800 8801 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 8802 CXXScopeSpec &SS, 8803 SourceLocation IdentLoc, 8804 IdentifierInfo *Ident) { 8805 R.clear(); 8806 if (TypoCorrection Corrected = 8807 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 8808 llvm::make_unique<NamespaceValidatorCCC>(), 8809 Sema::CTK_ErrorRecovery)) { 8810 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 8811 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 8812 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 8813 Ident->getName().equals(CorrectedStr); 8814 S.diagnoseTypo(Corrected, 8815 S.PDiag(diag::err_using_directive_member_suggest) 8816 << Ident << DC << DroppedSpecifier << SS.getRange(), 8817 S.PDiag(diag::note_namespace_defined_here)); 8818 } else { 8819 S.diagnoseTypo(Corrected, 8820 S.PDiag(diag::err_using_directive_suggest) << Ident, 8821 S.PDiag(diag::note_namespace_defined_here)); 8822 } 8823 R.addDecl(Corrected.getFoundDecl()); 8824 return true; 8825 } 8826 return false; 8827 } 8828 8829 Decl *Sema::ActOnUsingDirective(Scope *S, 8830 SourceLocation UsingLoc, 8831 SourceLocation NamespcLoc, 8832 CXXScopeSpec &SS, 8833 SourceLocation IdentLoc, 8834 IdentifierInfo *NamespcName, 8835 AttributeList *AttrList) { 8836 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8837 assert(NamespcName && "Invalid NamespcName."); 8838 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 8839 8840 // This can only happen along a recovery path. 8841 while (S->isTemplateParamScope()) 8842 S = S->getParent(); 8843 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8844 8845 UsingDirectiveDecl *UDir = nullptr; 8846 NestedNameSpecifier *Qualifier = nullptr; 8847 if (SS.isSet()) 8848 Qualifier = SS.getScopeRep(); 8849 8850 // Lookup namespace name. 8851 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 8852 LookupParsedName(R, S, &SS); 8853 if (R.isAmbiguous()) 8854 return nullptr; 8855 8856 if (R.empty()) { 8857 R.clear(); 8858 // Allow "using namespace std;" or "using namespace ::std;" even if 8859 // "std" hasn't been defined yet, for GCC compatibility. 8860 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 8861 NamespcName->isStr("std")) { 8862 Diag(IdentLoc, diag::ext_using_undefined_std); 8863 R.addDecl(getOrCreateStdNamespace()); 8864 R.resolveKind(); 8865 } 8866 // Otherwise, attempt typo correction. 8867 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 8868 } 8869 8870 if (!R.empty()) { 8871 NamedDecl *Named = R.getRepresentativeDecl(); 8872 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 8873 assert(NS && "expected namespace decl"); 8874 8875 // The use of a nested name specifier may trigger deprecation warnings. 8876 DiagnoseUseOfDecl(Named, IdentLoc); 8877 8878 // C++ [namespace.udir]p1: 8879 // A using-directive specifies that the names in the nominated 8880 // namespace can be used in the scope in which the 8881 // using-directive appears after the using-directive. During 8882 // unqualified name lookup (3.4.1), the names appear as if they 8883 // were declared in the nearest enclosing namespace which 8884 // contains both the using-directive and the nominated 8885 // namespace. [Note: in this context, "contains" means "contains 8886 // directly or indirectly". ] 8887 8888 // Find enclosing context containing both using-directive and 8889 // nominated namespace. 8890 DeclContext *CommonAncestor = cast<DeclContext>(NS); 8891 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 8892 CommonAncestor = CommonAncestor->getParent(); 8893 8894 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 8895 SS.getWithLocInContext(Context), 8896 IdentLoc, Named, CommonAncestor); 8897 8898 if (IsUsingDirectiveInToplevelContext(CurContext) && 8899 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 8900 Diag(IdentLoc, diag::warn_using_directive_in_header); 8901 } 8902 8903 PushUsingDirective(S, UDir); 8904 } else { 8905 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8906 } 8907 8908 if (UDir) 8909 ProcessDeclAttributeList(S, UDir, AttrList); 8910 8911 return UDir; 8912 } 8913 8914 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 8915 // If the scope has an associated entity and the using directive is at 8916 // namespace or translation unit scope, add the UsingDirectiveDecl into 8917 // its lookup structure so qualified name lookup can find it. 8918 DeclContext *Ctx = S->getEntity(); 8919 if (Ctx && !Ctx->isFunctionOrMethod()) 8920 Ctx->addDecl(UDir); 8921 else 8922 // Otherwise, it is at block scope. The using-directives will affect lookup 8923 // only to the end of the scope. 8924 S->PushUsingDirective(UDir); 8925 } 8926 8927 8928 Decl *Sema::ActOnUsingDeclaration(Scope *S, 8929 AccessSpecifier AS, 8930 SourceLocation UsingLoc, 8931 SourceLocation TypenameLoc, 8932 CXXScopeSpec &SS, 8933 UnqualifiedId &Name, 8934 SourceLocation EllipsisLoc, 8935 AttributeList *AttrList) { 8936 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8937 8938 if (SS.isEmpty()) { 8939 Diag(Name.getLocStart(), diag::err_using_requires_qualname); 8940 return nullptr; 8941 } 8942 8943 switch (Name.getKind()) { 8944 case UnqualifiedId::IK_ImplicitSelfParam: 8945 case UnqualifiedId::IK_Identifier: 8946 case UnqualifiedId::IK_OperatorFunctionId: 8947 case UnqualifiedId::IK_LiteralOperatorId: 8948 case UnqualifiedId::IK_ConversionFunctionId: 8949 break; 8950 8951 case UnqualifiedId::IK_ConstructorName: 8952 case UnqualifiedId::IK_ConstructorTemplateId: 8953 // C++11 inheriting constructors. 8954 Diag(Name.getLocStart(), 8955 getLangOpts().CPlusPlus11 ? 8956 diag::warn_cxx98_compat_using_decl_constructor : 8957 diag::err_using_decl_constructor) 8958 << SS.getRange(); 8959 8960 if (getLangOpts().CPlusPlus11) break; 8961 8962 return nullptr; 8963 8964 case UnqualifiedId::IK_DestructorName: 8965 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 8966 << SS.getRange(); 8967 return nullptr; 8968 8969 case UnqualifiedId::IK_TemplateId: 8970 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 8971 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 8972 return nullptr; 8973 8974 case UnqualifiedId::IK_DeductionGuideName: 8975 llvm_unreachable("cannot parse qualified deduction guide name"); 8976 } 8977 8978 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 8979 DeclarationName TargetName = TargetNameInfo.getName(); 8980 if (!TargetName) 8981 return nullptr; 8982 8983 // Warn about access declarations. 8984 if (UsingLoc.isInvalid()) { 8985 Diag(Name.getLocStart(), 8986 getLangOpts().CPlusPlus11 ? diag::err_access_decl 8987 : diag::warn_access_decl_deprecated) 8988 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 8989 } 8990 8991 if (EllipsisLoc.isInvalid()) { 8992 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 8993 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 8994 return nullptr; 8995 } else { 8996 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 8997 !TargetNameInfo.containsUnexpandedParameterPack()) { 8998 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 8999 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 9000 EllipsisLoc = SourceLocation(); 9001 } 9002 } 9003 9004 NamedDecl *UD = 9005 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9006 SS, TargetNameInfo, EllipsisLoc, AttrList, 9007 /*IsInstantiation*/false); 9008 if (UD) 9009 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9010 9011 return UD; 9012 } 9013 9014 /// \brief Determine whether a using declaration considers the given 9015 /// declarations as "equivalent", e.g., if they are redeclarations of 9016 /// the same entity or are both typedefs of the same type. 9017 static bool 9018 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9019 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9020 return true; 9021 9022 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9023 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9024 return Context.hasSameType(TD1->getUnderlyingType(), 9025 TD2->getUnderlyingType()); 9026 9027 return false; 9028 } 9029 9030 9031 /// Determines whether to create a using shadow decl for a particular 9032 /// decl, given the set of decls existing prior to this using lookup. 9033 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9034 const LookupResult &Previous, 9035 UsingShadowDecl *&PrevShadow) { 9036 // Diagnose finding a decl which is not from a base class of the 9037 // current class. We do this now because there are cases where this 9038 // function will silently decide not to build a shadow decl, which 9039 // will pre-empt further diagnostics. 9040 // 9041 // We don't need to do this in C++11 because we do the check once on 9042 // the qualifier. 9043 // 9044 // FIXME: diagnose the following if we care enough: 9045 // struct A { int foo; }; 9046 // struct B : A { using A::foo; }; 9047 // template <class T> struct C : A {}; 9048 // template <class T> struct D : C<T> { using B::foo; } // <--- 9049 // This is invalid (during instantiation) in C++03 because B::foo 9050 // resolves to the using decl in B, which is not a base class of D<T>. 9051 // We can't diagnose it immediately because C<T> is an unknown 9052 // specialization. The UsingShadowDecl in D<T> then points directly 9053 // to A::foo, which will look well-formed when we instantiate. 9054 // The right solution is to not collapse the shadow-decl chain. 9055 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9056 DeclContext *OrigDC = Orig->getDeclContext(); 9057 9058 // Handle enums and anonymous structs. 9059 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9060 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9061 while (OrigRec->isAnonymousStructOrUnion()) 9062 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9063 9064 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9065 if (OrigDC == CurContext) { 9066 Diag(Using->getLocation(), 9067 diag::err_using_decl_nested_name_specifier_is_current_class) 9068 << Using->getQualifierLoc().getSourceRange(); 9069 Diag(Orig->getLocation(), diag::note_using_decl_target); 9070 Using->setInvalidDecl(); 9071 return true; 9072 } 9073 9074 Diag(Using->getQualifierLoc().getBeginLoc(), 9075 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9076 << Using->getQualifier() 9077 << cast<CXXRecordDecl>(CurContext) 9078 << Using->getQualifierLoc().getSourceRange(); 9079 Diag(Orig->getLocation(), diag::note_using_decl_target); 9080 Using->setInvalidDecl(); 9081 return true; 9082 } 9083 } 9084 9085 if (Previous.empty()) return false; 9086 9087 NamedDecl *Target = Orig; 9088 if (isa<UsingShadowDecl>(Target)) 9089 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9090 9091 // If the target happens to be one of the previous declarations, we 9092 // don't have a conflict. 9093 // 9094 // FIXME: but we might be increasing its access, in which case we 9095 // should redeclare it. 9096 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9097 bool FoundEquivalentDecl = false; 9098 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9099 I != E; ++I) { 9100 NamedDecl *D = (*I)->getUnderlyingDecl(); 9101 // We can have UsingDecls in our Previous results because we use the same 9102 // LookupResult for checking whether the UsingDecl itself is a valid 9103 // redeclaration. 9104 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9105 continue; 9106 9107 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9108 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9109 PrevShadow = Shadow; 9110 FoundEquivalentDecl = true; 9111 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9112 // We don't conflict with an existing using shadow decl of an equivalent 9113 // declaration, but we're not a redeclaration of it. 9114 FoundEquivalentDecl = true; 9115 } 9116 9117 if (isVisible(D)) 9118 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9119 } 9120 9121 if (FoundEquivalentDecl) 9122 return false; 9123 9124 if (FunctionDecl *FD = Target->getAsFunction()) { 9125 NamedDecl *OldDecl = nullptr; 9126 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9127 /*IsForUsingDecl*/ true)) { 9128 case Ovl_Overload: 9129 return false; 9130 9131 case Ovl_NonFunction: 9132 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9133 break; 9134 9135 // We found a decl with the exact signature. 9136 case Ovl_Match: 9137 // If we're in a record, we want to hide the target, so we 9138 // return true (without a diagnostic) to tell the caller not to 9139 // build a shadow decl. 9140 if (CurContext->isRecord()) 9141 return true; 9142 9143 // If we're not in a record, this is an error. 9144 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9145 break; 9146 } 9147 9148 Diag(Target->getLocation(), diag::note_using_decl_target); 9149 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9150 Using->setInvalidDecl(); 9151 return true; 9152 } 9153 9154 // Target is not a function. 9155 9156 if (isa<TagDecl>(Target)) { 9157 // No conflict between a tag and a non-tag. 9158 if (!Tag) return false; 9159 9160 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9161 Diag(Target->getLocation(), diag::note_using_decl_target); 9162 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9163 Using->setInvalidDecl(); 9164 return true; 9165 } 9166 9167 // No conflict between a tag and a non-tag. 9168 if (!NonTag) return false; 9169 9170 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9171 Diag(Target->getLocation(), diag::note_using_decl_target); 9172 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9173 Using->setInvalidDecl(); 9174 return true; 9175 } 9176 9177 /// Determine whether a direct base class is a virtual base class. 9178 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9179 if (!Derived->getNumVBases()) 9180 return false; 9181 for (auto &B : Derived->bases()) 9182 if (B.getType()->getAsCXXRecordDecl() == Base) 9183 return B.isVirtual(); 9184 llvm_unreachable("not a direct base class"); 9185 } 9186 9187 /// Builds a shadow declaration corresponding to a 'using' declaration. 9188 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9189 UsingDecl *UD, 9190 NamedDecl *Orig, 9191 UsingShadowDecl *PrevDecl) { 9192 // If we resolved to another shadow declaration, just coalesce them. 9193 NamedDecl *Target = Orig; 9194 if (isa<UsingShadowDecl>(Target)) { 9195 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9196 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9197 } 9198 9199 NamedDecl *NonTemplateTarget = Target; 9200 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9201 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9202 9203 UsingShadowDecl *Shadow; 9204 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 9205 bool IsVirtualBase = 9206 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9207 UD->getQualifier()->getAsRecordDecl()); 9208 Shadow = ConstructorUsingShadowDecl::Create( 9209 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9210 } else { 9211 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9212 Target); 9213 } 9214 UD->addShadowDecl(Shadow); 9215 9216 Shadow->setAccess(UD->getAccess()); 9217 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9218 Shadow->setInvalidDecl(); 9219 9220 Shadow->setPreviousDecl(PrevDecl); 9221 9222 if (S) 9223 PushOnScopeChains(Shadow, S); 9224 else 9225 CurContext->addDecl(Shadow); 9226 9227 9228 return Shadow; 9229 } 9230 9231 /// Hides a using shadow declaration. This is required by the current 9232 /// using-decl implementation when a resolvable using declaration in a 9233 /// class is followed by a declaration which would hide or override 9234 /// one or more of the using decl's targets; for example: 9235 /// 9236 /// struct Base { void foo(int); }; 9237 /// struct Derived : Base { 9238 /// using Base::foo; 9239 /// void foo(int); 9240 /// }; 9241 /// 9242 /// The governing language is C++03 [namespace.udecl]p12: 9243 /// 9244 /// When a using-declaration brings names from a base class into a 9245 /// derived class scope, member functions in the derived class 9246 /// override and/or hide member functions with the same name and 9247 /// parameter types in a base class (rather than conflicting). 9248 /// 9249 /// There are two ways to implement this: 9250 /// (1) optimistically create shadow decls when they're not hidden 9251 /// by existing declarations, or 9252 /// (2) don't create any shadow decls (or at least don't make them 9253 /// visible) until we've fully parsed/instantiated the class. 9254 /// The problem with (1) is that we might have to retroactively remove 9255 /// a shadow decl, which requires several O(n) operations because the 9256 /// decl structures are (very reasonably) not designed for removal. 9257 /// (2) avoids this but is very fiddly and phase-dependent. 9258 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9259 if (Shadow->getDeclName().getNameKind() == 9260 DeclarationName::CXXConversionFunctionName) 9261 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9262 9263 // Remove it from the DeclContext... 9264 Shadow->getDeclContext()->removeDecl(Shadow); 9265 9266 // ...and the scope, if applicable... 9267 if (S) { 9268 S->RemoveDecl(Shadow); 9269 IdResolver.RemoveDecl(Shadow); 9270 } 9271 9272 // ...and the using decl. 9273 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9274 9275 // TODO: complain somehow if Shadow was used. It shouldn't 9276 // be possible for this to happen, because...? 9277 } 9278 9279 /// Find the base specifier for a base class with the given type. 9280 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 9281 QualType DesiredBase, 9282 bool &AnyDependentBases) { 9283 // Check whether the named type is a direct base class. 9284 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 9285 for (auto &Base : Derived->bases()) { 9286 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 9287 if (CanonicalDesiredBase == BaseType) 9288 return &Base; 9289 if (BaseType->isDependentType()) 9290 AnyDependentBases = true; 9291 } 9292 return nullptr; 9293 } 9294 9295 namespace { 9296 class UsingValidatorCCC : public CorrectionCandidateCallback { 9297 public: 9298 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 9299 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 9300 : HasTypenameKeyword(HasTypenameKeyword), 9301 IsInstantiation(IsInstantiation), OldNNS(NNS), 9302 RequireMemberOf(RequireMemberOf) {} 9303 9304 bool ValidateCandidate(const TypoCorrection &Candidate) override { 9305 NamedDecl *ND = Candidate.getCorrectionDecl(); 9306 9307 // Keywords are not valid here. 9308 if (!ND || isa<NamespaceDecl>(ND)) 9309 return false; 9310 9311 // Completely unqualified names are invalid for a 'using' declaration. 9312 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 9313 return false; 9314 9315 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 9316 // reject. 9317 9318 if (RequireMemberOf) { 9319 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9320 if (FoundRecord && FoundRecord->isInjectedClassName()) { 9321 // No-one ever wants a using-declaration to name an injected-class-name 9322 // of a base class, unless they're declaring an inheriting constructor. 9323 ASTContext &Ctx = ND->getASTContext(); 9324 if (!Ctx.getLangOpts().CPlusPlus11) 9325 return false; 9326 QualType FoundType = Ctx.getRecordType(FoundRecord); 9327 9328 // Check that the injected-class-name is named as a member of its own 9329 // type; we don't want to suggest 'using Derived::Base;', since that 9330 // means something else. 9331 NestedNameSpecifier *Specifier = 9332 Candidate.WillReplaceSpecifier() 9333 ? Candidate.getCorrectionSpecifier() 9334 : OldNNS; 9335 if (!Specifier->getAsType() || 9336 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 9337 return false; 9338 9339 // Check that this inheriting constructor declaration actually names a 9340 // direct base class of the current class. 9341 bool AnyDependentBases = false; 9342 if (!findDirectBaseWithType(RequireMemberOf, 9343 Ctx.getRecordType(FoundRecord), 9344 AnyDependentBases) && 9345 !AnyDependentBases) 9346 return false; 9347 } else { 9348 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 9349 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 9350 return false; 9351 9352 // FIXME: Check that the base class member is accessible? 9353 } 9354 } else { 9355 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9356 if (FoundRecord && FoundRecord->isInjectedClassName()) 9357 return false; 9358 } 9359 9360 if (isa<TypeDecl>(ND)) 9361 return HasTypenameKeyword || !IsInstantiation; 9362 9363 return !HasTypenameKeyword; 9364 } 9365 9366 private: 9367 bool HasTypenameKeyword; 9368 bool IsInstantiation; 9369 NestedNameSpecifier *OldNNS; 9370 CXXRecordDecl *RequireMemberOf; 9371 }; 9372 } // end anonymous namespace 9373 9374 /// Builds a using declaration. 9375 /// 9376 /// \param IsInstantiation - Whether this call arises from an 9377 /// instantiation of an unresolved using declaration. We treat 9378 /// the lookup differently for these declarations. 9379 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 9380 SourceLocation UsingLoc, 9381 bool HasTypenameKeyword, 9382 SourceLocation TypenameLoc, 9383 CXXScopeSpec &SS, 9384 DeclarationNameInfo NameInfo, 9385 SourceLocation EllipsisLoc, 9386 AttributeList *AttrList, 9387 bool IsInstantiation) { 9388 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9389 SourceLocation IdentLoc = NameInfo.getLoc(); 9390 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9391 9392 // FIXME: We ignore attributes for now. 9393 9394 // For an inheriting constructor declaration, the name of the using 9395 // declaration is the name of a constructor in this class, not in the 9396 // base class. 9397 DeclarationNameInfo UsingName = NameInfo; 9398 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9399 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9400 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9401 Context.getCanonicalType(Context.getRecordType(RD)))); 9402 9403 // Do the redeclaration lookup in the current scope. 9404 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9405 ForRedeclaration); 9406 Previous.setHideTags(false); 9407 if (S) { 9408 LookupName(Previous, S); 9409 9410 // It is really dumb that we have to do this. 9411 LookupResult::Filter F = Previous.makeFilter(); 9412 while (F.hasNext()) { 9413 NamedDecl *D = F.next(); 9414 if (!isDeclInScope(D, CurContext, S)) 9415 F.erase(); 9416 // If we found a local extern declaration that's not ordinarily visible, 9417 // and this declaration is being added to a non-block scope, ignore it. 9418 // We're only checking for scope conflicts here, not also for violations 9419 // of the linkage rules. 9420 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9421 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9422 F.erase(); 9423 } 9424 F.done(); 9425 } else { 9426 assert(IsInstantiation && "no scope in non-instantiation"); 9427 if (CurContext->isRecord()) 9428 LookupQualifiedName(Previous, CurContext); 9429 else { 9430 // No redeclaration check is needed here; in non-member contexts we 9431 // diagnosed all possible conflicts with other using-declarations when 9432 // building the template: 9433 // 9434 // For a dependent non-type using declaration, the only valid case is 9435 // if we instantiate to a single enumerator. We check for conflicts 9436 // between shadow declarations we introduce, and we check in the template 9437 // definition for conflicts between a non-type using declaration and any 9438 // other declaration, which together covers all cases. 9439 // 9440 // A dependent typename using declaration will never successfully 9441 // instantiate, since it will always name a class member, so we reject 9442 // that in the template definition. 9443 } 9444 } 9445 9446 // Check for invalid redeclarations. 9447 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 9448 SS, IdentLoc, Previous)) 9449 return nullptr; 9450 9451 // Check for bad qualifiers. 9452 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 9453 IdentLoc)) 9454 return nullptr; 9455 9456 DeclContext *LookupContext = computeDeclContext(SS); 9457 NamedDecl *D; 9458 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9459 if (!LookupContext || EllipsisLoc.isValid()) { 9460 if (HasTypenameKeyword) { 9461 // FIXME: not all declaration name kinds are legal here 9462 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 9463 UsingLoc, TypenameLoc, 9464 QualifierLoc, 9465 IdentLoc, NameInfo.getName(), 9466 EllipsisLoc); 9467 } else { 9468 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 9469 QualifierLoc, NameInfo, EllipsisLoc); 9470 } 9471 D->setAccess(AS); 9472 CurContext->addDecl(D); 9473 return D; 9474 } 9475 9476 auto Build = [&](bool Invalid) { 9477 UsingDecl *UD = 9478 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 9479 UsingName, HasTypenameKeyword); 9480 UD->setAccess(AS); 9481 CurContext->addDecl(UD); 9482 UD->setInvalidDecl(Invalid); 9483 return UD; 9484 }; 9485 auto BuildInvalid = [&]{ return Build(true); }; 9486 auto BuildValid = [&]{ return Build(false); }; 9487 9488 if (RequireCompleteDeclContext(SS, LookupContext)) 9489 return BuildInvalid(); 9490 9491 // Look up the target name. 9492 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9493 9494 // Unlike most lookups, we don't always want to hide tag 9495 // declarations: tag names are visible through the using declaration 9496 // even if hidden by ordinary names, *except* in a dependent context 9497 // where it's important for the sanity of two-phase lookup. 9498 if (!IsInstantiation) 9499 R.setHideTags(false); 9500 9501 // For the purposes of this lookup, we have a base object type 9502 // equal to that of the current context. 9503 if (CurContext->isRecord()) { 9504 R.setBaseObjectType( 9505 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 9506 } 9507 9508 LookupQualifiedName(R, LookupContext); 9509 9510 // Try to correct typos if possible. If constructor name lookup finds no 9511 // results, that means the named class has no explicit constructors, and we 9512 // suppressed declaring implicit ones (probably because it's dependent or 9513 // invalid). 9514 if (R.empty() && 9515 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 9516 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 9517 // it will believe that glibc provides a ::gets in cases where it does not, 9518 // and will try to pull it into namespace std with a using-declaration. 9519 // Just ignore the using-declaration in that case. 9520 auto *II = NameInfo.getName().getAsIdentifierInfo(); 9521 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 9522 CurContext->isStdNamespace() && 9523 isa<TranslationUnitDecl>(LookupContext) && 9524 getSourceManager().isInSystemHeader(UsingLoc)) 9525 return nullptr; 9526 if (TypoCorrection Corrected = CorrectTypo( 9527 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 9528 llvm::make_unique<UsingValidatorCCC>( 9529 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 9530 dyn_cast<CXXRecordDecl>(CurContext)), 9531 CTK_ErrorRecovery)) { 9532 // We reject candidates where DroppedSpecifier == true, hence the 9533 // literal '0' below. 9534 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 9535 << NameInfo.getName() << LookupContext << 0 9536 << SS.getRange()); 9537 9538 // If we picked a correction with no attached Decl we can't do anything 9539 // useful with it, bail out. 9540 NamedDecl *ND = Corrected.getCorrectionDecl(); 9541 if (!ND) 9542 return BuildInvalid(); 9543 9544 // If we corrected to an inheriting constructor, handle it as one. 9545 auto *RD = dyn_cast<CXXRecordDecl>(ND); 9546 if (RD && RD->isInjectedClassName()) { 9547 // The parent of the injected class name is the class itself. 9548 RD = cast<CXXRecordDecl>(RD->getParent()); 9549 9550 // Fix up the information we'll use to build the using declaration. 9551 if (Corrected.WillReplaceSpecifier()) { 9552 NestedNameSpecifierLocBuilder Builder; 9553 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 9554 QualifierLoc.getSourceRange()); 9555 QualifierLoc = Builder.getWithLocInContext(Context); 9556 } 9557 9558 // In this case, the name we introduce is the name of a derived class 9559 // constructor. 9560 auto *CurClass = cast<CXXRecordDecl>(CurContext); 9561 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9562 Context.getCanonicalType(Context.getRecordType(CurClass)))); 9563 UsingName.setNamedTypeInfo(nullptr); 9564 for (auto *Ctor : LookupConstructors(RD)) 9565 R.addDecl(Ctor); 9566 R.resolveKind(); 9567 } else { 9568 // FIXME: Pick up all the declarations if we found an overloaded 9569 // function. 9570 UsingName.setName(ND->getDeclName()); 9571 R.addDecl(ND); 9572 } 9573 } else { 9574 Diag(IdentLoc, diag::err_no_member) 9575 << NameInfo.getName() << LookupContext << SS.getRange(); 9576 return BuildInvalid(); 9577 } 9578 } 9579 9580 if (R.isAmbiguous()) 9581 return BuildInvalid(); 9582 9583 if (HasTypenameKeyword) { 9584 // If we asked for a typename and got a non-type decl, error out. 9585 if (!R.getAsSingle<TypeDecl>()) { 9586 Diag(IdentLoc, diag::err_using_typename_non_type); 9587 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9588 Diag((*I)->getUnderlyingDecl()->getLocation(), 9589 diag::note_using_decl_target); 9590 return BuildInvalid(); 9591 } 9592 } else { 9593 // If we asked for a non-typename and we got a type, error out, 9594 // but only if this is an instantiation of an unresolved using 9595 // decl. Otherwise just silently find the type name. 9596 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 9597 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 9598 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 9599 return BuildInvalid(); 9600 } 9601 } 9602 9603 // C++14 [namespace.udecl]p6: 9604 // A using-declaration shall not name a namespace. 9605 if (R.getAsSingle<NamespaceDecl>()) { 9606 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 9607 << SS.getRange(); 9608 return BuildInvalid(); 9609 } 9610 9611 // C++14 [namespace.udecl]p7: 9612 // A using-declaration shall not name a scoped enumerator. 9613 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 9614 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 9615 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 9616 << SS.getRange(); 9617 return BuildInvalid(); 9618 } 9619 } 9620 9621 UsingDecl *UD = BuildValid(); 9622 9623 // Some additional rules apply to inheriting constructors. 9624 if (UsingName.getName().getNameKind() == 9625 DeclarationName::CXXConstructorName) { 9626 // Suppress access diagnostics; the access check is instead performed at the 9627 // point of use for an inheriting constructor. 9628 R.suppressDiagnostics(); 9629 if (CheckInheritingConstructorUsingDecl(UD)) 9630 return UD; 9631 } 9632 9633 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9634 UsingShadowDecl *PrevDecl = nullptr; 9635 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 9636 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 9637 } 9638 9639 return UD; 9640 } 9641 9642 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 9643 ArrayRef<NamedDecl *> Expansions) { 9644 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 9645 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 9646 isa<UsingPackDecl>(InstantiatedFrom)); 9647 9648 auto *UPD = 9649 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 9650 UPD->setAccess(InstantiatedFrom->getAccess()); 9651 CurContext->addDecl(UPD); 9652 return UPD; 9653 } 9654 9655 /// Additional checks for a using declaration referring to a constructor name. 9656 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 9657 assert(!UD->hasTypename() && "expecting a constructor name"); 9658 9659 const Type *SourceType = UD->getQualifier()->getAsType(); 9660 assert(SourceType && 9661 "Using decl naming constructor doesn't have type in scope spec."); 9662 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 9663 9664 // Check whether the named type is a direct base class. 9665 bool AnyDependentBases = false; 9666 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 9667 AnyDependentBases); 9668 if (!Base && !AnyDependentBases) { 9669 Diag(UD->getUsingLoc(), 9670 diag::err_using_decl_constructor_not_in_direct_base) 9671 << UD->getNameInfo().getSourceRange() 9672 << QualType(SourceType, 0) << TargetClass; 9673 UD->setInvalidDecl(); 9674 return true; 9675 } 9676 9677 if (Base) 9678 Base->setInheritConstructors(); 9679 9680 return false; 9681 } 9682 9683 /// Checks that the given using declaration is not an invalid 9684 /// redeclaration. Note that this is checking only for the using decl 9685 /// itself, not for any ill-formedness among the UsingShadowDecls. 9686 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 9687 bool HasTypenameKeyword, 9688 const CXXScopeSpec &SS, 9689 SourceLocation NameLoc, 9690 const LookupResult &Prev) { 9691 NestedNameSpecifier *Qual = SS.getScopeRep(); 9692 9693 // C++03 [namespace.udecl]p8: 9694 // C++0x [namespace.udecl]p10: 9695 // A using-declaration is a declaration and can therefore be used 9696 // repeatedly where (and only where) multiple declarations are 9697 // allowed. 9698 // 9699 // That's in non-member contexts. 9700 if (!CurContext->getRedeclContext()->isRecord()) { 9701 // A dependent qualifier outside a class can only ever resolve to an 9702 // enumeration type. Therefore it conflicts with any other non-type 9703 // declaration in the same scope. 9704 // FIXME: How should we check for dependent type-type conflicts at block 9705 // scope? 9706 if (Qual->isDependent() && !HasTypenameKeyword) { 9707 for (auto *D : Prev) { 9708 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 9709 bool OldCouldBeEnumerator = 9710 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 9711 Diag(NameLoc, 9712 OldCouldBeEnumerator ? diag::err_redefinition 9713 : diag::err_redefinition_different_kind) 9714 << Prev.getLookupName(); 9715 Diag(D->getLocation(), diag::note_previous_definition); 9716 return true; 9717 } 9718 } 9719 } 9720 return false; 9721 } 9722 9723 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 9724 NamedDecl *D = *I; 9725 9726 bool DTypename; 9727 NestedNameSpecifier *DQual; 9728 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 9729 DTypename = UD->hasTypename(); 9730 DQual = UD->getQualifier(); 9731 } else if (UnresolvedUsingValueDecl *UD 9732 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 9733 DTypename = false; 9734 DQual = UD->getQualifier(); 9735 } else if (UnresolvedUsingTypenameDecl *UD 9736 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 9737 DTypename = true; 9738 DQual = UD->getQualifier(); 9739 } else continue; 9740 9741 // using decls differ if one says 'typename' and the other doesn't. 9742 // FIXME: non-dependent using decls? 9743 if (HasTypenameKeyword != DTypename) continue; 9744 9745 // using decls differ if they name different scopes (but note that 9746 // template instantiation can cause this check to trigger when it 9747 // didn't before instantiation). 9748 if (Context.getCanonicalNestedNameSpecifier(Qual) != 9749 Context.getCanonicalNestedNameSpecifier(DQual)) 9750 continue; 9751 9752 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 9753 Diag(D->getLocation(), diag::note_using_decl) << 1; 9754 return true; 9755 } 9756 9757 return false; 9758 } 9759 9760 9761 /// Checks that the given nested-name qualifier used in a using decl 9762 /// in the current context is appropriately related to the current 9763 /// scope. If an error is found, diagnoses it and returns true. 9764 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 9765 bool HasTypename, 9766 const CXXScopeSpec &SS, 9767 const DeclarationNameInfo &NameInfo, 9768 SourceLocation NameLoc) { 9769 DeclContext *NamedContext = computeDeclContext(SS); 9770 9771 if (!CurContext->isRecord()) { 9772 // C++03 [namespace.udecl]p3: 9773 // C++0x [namespace.udecl]p8: 9774 // A using-declaration for a class member shall be a member-declaration. 9775 9776 // If we weren't able to compute a valid scope, it might validly be a 9777 // dependent class scope or a dependent enumeration unscoped scope. If 9778 // we have a 'typename' keyword, the scope must resolve to a class type. 9779 if ((HasTypename && !NamedContext) || 9780 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 9781 auto *RD = NamedContext 9782 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 9783 : nullptr; 9784 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 9785 RD = nullptr; 9786 9787 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 9788 << SS.getRange(); 9789 9790 // If we have a complete, non-dependent source type, try to suggest a 9791 // way to get the same effect. 9792 if (!RD) 9793 return true; 9794 9795 // Find what this using-declaration was referring to. 9796 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9797 R.setHideTags(false); 9798 R.suppressDiagnostics(); 9799 LookupQualifiedName(R, RD); 9800 9801 if (R.getAsSingle<TypeDecl>()) { 9802 if (getLangOpts().CPlusPlus11) { 9803 // Convert 'using X::Y;' to 'using Y = X::Y;'. 9804 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 9805 << 0 // alias declaration 9806 << FixItHint::CreateInsertion(SS.getBeginLoc(), 9807 NameInfo.getName().getAsString() + 9808 " = "); 9809 } else { 9810 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 9811 SourceLocation InsertLoc = 9812 getLocForEndOfToken(NameInfo.getLocEnd()); 9813 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 9814 << 1 // typedef declaration 9815 << FixItHint::CreateReplacement(UsingLoc, "typedef") 9816 << FixItHint::CreateInsertion( 9817 InsertLoc, " " + NameInfo.getName().getAsString()); 9818 } 9819 } else if (R.getAsSingle<VarDecl>()) { 9820 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9821 // repeating the type of the static data member here. 9822 FixItHint FixIt; 9823 if (getLangOpts().CPlusPlus11) { 9824 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9825 FixIt = FixItHint::CreateReplacement( 9826 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 9827 } 9828 9829 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9830 << 2 // reference declaration 9831 << FixIt; 9832 } else if (R.getAsSingle<EnumConstantDecl>()) { 9833 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9834 // repeating the type of the enumeration here, and we can't do so if 9835 // the type is anonymous. 9836 FixItHint FixIt; 9837 if (getLangOpts().CPlusPlus11) { 9838 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9839 FixIt = FixItHint::CreateReplacement( 9840 UsingLoc, 9841 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 9842 } 9843 9844 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9845 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 9846 << FixIt; 9847 } 9848 return true; 9849 } 9850 9851 // Otherwise, this might be valid. 9852 return false; 9853 } 9854 9855 // The current scope is a record. 9856 9857 // If the named context is dependent, we can't decide much. 9858 if (!NamedContext) { 9859 // FIXME: in C++0x, we can diagnose if we can prove that the 9860 // nested-name-specifier does not refer to a base class, which is 9861 // still possible in some cases. 9862 9863 // Otherwise we have to conservatively report that things might be 9864 // okay. 9865 return false; 9866 } 9867 9868 if (!NamedContext->isRecord()) { 9869 // Ideally this would point at the last name in the specifier, 9870 // but we don't have that level of source info. 9871 Diag(SS.getRange().getBegin(), 9872 diag::err_using_decl_nested_name_specifier_is_not_class) 9873 << SS.getScopeRep() << SS.getRange(); 9874 return true; 9875 } 9876 9877 if (!NamedContext->isDependentContext() && 9878 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 9879 return true; 9880 9881 if (getLangOpts().CPlusPlus11) { 9882 // C++11 [namespace.udecl]p3: 9883 // In a using-declaration used as a member-declaration, the 9884 // nested-name-specifier shall name a base class of the class 9885 // being defined. 9886 9887 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 9888 cast<CXXRecordDecl>(NamedContext))) { 9889 if (CurContext == NamedContext) { 9890 Diag(NameLoc, 9891 diag::err_using_decl_nested_name_specifier_is_current_class) 9892 << SS.getRange(); 9893 return true; 9894 } 9895 9896 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 9897 Diag(SS.getRange().getBegin(), 9898 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9899 << SS.getScopeRep() 9900 << cast<CXXRecordDecl>(CurContext) 9901 << SS.getRange(); 9902 } 9903 return true; 9904 } 9905 9906 return false; 9907 } 9908 9909 // C++03 [namespace.udecl]p4: 9910 // A using-declaration used as a member-declaration shall refer 9911 // to a member of a base class of the class being defined [etc.]. 9912 9913 // Salient point: SS doesn't have to name a base class as long as 9914 // lookup only finds members from base classes. Therefore we can 9915 // diagnose here only if we can prove that that can't happen, 9916 // i.e. if the class hierarchies provably don't intersect. 9917 9918 // TODO: it would be nice if "definitely valid" results were cached 9919 // in the UsingDecl and UsingShadowDecl so that these checks didn't 9920 // need to be repeated. 9921 9922 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 9923 auto Collect = [&Bases](const CXXRecordDecl *Base) { 9924 Bases.insert(Base); 9925 return true; 9926 }; 9927 9928 // Collect all bases. Return false if we find a dependent base. 9929 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 9930 return false; 9931 9932 // Returns true if the base is dependent or is one of the accumulated base 9933 // classes. 9934 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 9935 return !Bases.count(Base); 9936 }; 9937 9938 // Return false if the class has a dependent base or if it or one 9939 // of its bases is present in the base set of the current context. 9940 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 9941 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 9942 return false; 9943 9944 Diag(SS.getRange().getBegin(), 9945 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9946 << SS.getScopeRep() 9947 << cast<CXXRecordDecl>(CurContext) 9948 << SS.getRange(); 9949 9950 return true; 9951 } 9952 9953 Decl *Sema::ActOnAliasDeclaration(Scope *S, 9954 AccessSpecifier AS, 9955 MultiTemplateParamsArg TemplateParamLists, 9956 SourceLocation UsingLoc, 9957 UnqualifiedId &Name, 9958 AttributeList *AttrList, 9959 TypeResult Type, 9960 Decl *DeclFromDeclSpec) { 9961 // Skip up to the relevant declaration scope. 9962 while (S->isTemplateParamScope()) 9963 S = S->getParent(); 9964 assert((S->getFlags() & Scope::DeclScope) && 9965 "got alias-declaration outside of declaration scope"); 9966 9967 if (Type.isInvalid()) 9968 return nullptr; 9969 9970 bool Invalid = false; 9971 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 9972 TypeSourceInfo *TInfo = nullptr; 9973 GetTypeFromParser(Type.get(), &TInfo); 9974 9975 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 9976 return nullptr; 9977 9978 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 9979 UPPC_DeclarationType)) { 9980 Invalid = true; 9981 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 9982 TInfo->getTypeLoc().getBeginLoc()); 9983 } 9984 9985 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 9986 LookupName(Previous, S); 9987 9988 // Warn about shadowing the name of a template parameter. 9989 if (Previous.isSingleResult() && 9990 Previous.getFoundDecl()->isTemplateParameter()) { 9991 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 9992 Previous.clear(); 9993 } 9994 9995 assert(Name.Kind == UnqualifiedId::IK_Identifier && 9996 "name in alias declaration must be an identifier"); 9997 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 9998 Name.StartLocation, 9999 Name.Identifier, TInfo); 10000 10001 NewTD->setAccess(AS); 10002 10003 if (Invalid) 10004 NewTD->setInvalidDecl(); 10005 10006 ProcessDeclAttributeList(S, NewTD, AttrList); 10007 AddPragmaAttributes(S, NewTD); 10008 10009 CheckTypedefForVariablyModifiedType(S, NewTD); 10010 Invalid |= NewTD->isInvalidDecl(); 10011 10012 bool Redeclaration = false; 10013 10014 NamedDecl *NewND; 10015 if (TemplateParamLists.size()) { 10016 TypeAliasTemplateDecl *OldDecl = nullptr; 10017 TemplateParameterList *OldTemplateParams = nullptr; 10018 10019 if (TemplateParamLists.size() != 1) { 10020 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10021 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10022 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10023 } 10024 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10025 10026 // Check that we can declare a template here. 10027 if (CheckTemplateDeclScope(S, TemplateParams)) 10028 return nullptr; 10029 10030 // Only consider previous declarations in the same scope. 10031 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10032 /*ExplicitInstantiationOrSpecialization*/false); 10033 if (!Previous.empty()) { 10034 Redeclaration = true; 10035 10036 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10037 if (!OldDecl && !Invalid) { 10038 Diag(UsingLoc, diag::err_redefinition_different_kind) 10039 << Name.Identifier; 10040 10041 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10042 if (OldD->getLocation().isValid()) 10043 Diag(OldD->getLocation(), diag::note_previous_definition); 10044 10045 Invalid = true; 10046 } 10047 10048 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10049 if (TemplateParameterListsAreEqual(TemplateParams, 10050 OldDecl->getTemplateParameters(), 10051 /*Complain=*/true, 10052 TPL_TemplateMatch)) 10053 OldTemplateParams = OldDecl->getTemplateParameters(); 10054 else 10055 Invalid = true; 10056 10057 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10058 if (!Invalid && 10059 !Context.hasSameType(OldTD->getUnderlyingType(), 10060 NewTD->getUnderlyingType())) { 10061 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10062 // but we can't reasonably accept it. 10063 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10064 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10065 if (OldTD->getLocation().isValid()) 10066 Diag(OldTD->getLocation(), diag::note_previous_definition); 10067 Invalid = true; 10068 } 10069 } 10070 } 10071 10072 // Merge any previous default template arguments into our parameters, 10073 // and check the parameter list. 10074 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10075 TPC_TypeAliasTemplate)) 10076 return nullptr; 10077 10078 TypeAliasTemplateDecl *NewDecl = 10079 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10080 Name.Identifier, TemplateParams, 10081 NewTD); 10082 NewTD->setDescribedAliasTemplate(NewDecl); 10083 10084 NewDecl->setAccess(AS); 10085 10086 if (Invalid) 10087 NewDecl->setInvalidDecl(); 10088 else if (OldDecl) 10089 NewDecl->setPreviousDecl(OldDecl); 10090 10091 NewND = NewDecl; 10092 } else { 10093 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10094 setTagNameForLinkagePurposes(TD, NewTD); 10095 handleTagNumbering(TD, S); 10096 } 10097 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10098 NewND = NewTD; 10099 } 10100 10101 PushOnScopeChains(NewND, S); 10102 ActOnDocumentableDecl(NewND); 10103 return NewND; 10104 } 10105 10106 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10107 SourceLocation AliasLoc, 10108 IdentifierInfo *Alias, CXXScopeSpec &SS, 10109 SourceLocation IdentLoc, 10110 IdentifierInfo *Ident) { 10111 10112 // Lookup the namespace name. 10113 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10114 LookupParsedName(R, S, &SS); 10115 10116 if (R.isAmbiguous()) 10117 return nullptr; 10118 10119 if (R.empty()) { 10120 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10121 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10122 return nullptr; 10123 } 10124 } 10125 assert(!R.isAmbiguous() && !R.empty()); 10126 NamedDecl *ND = R.getRepresentativeDecl(); 10127 10128 // Check if we have a previous declaration with the same name. 10129 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10130 ForRedeclaration); 10131 LookupName(PrevR, S); 10132 10133 // Check we're not shadowing a template parameter. 10134 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10135 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10136 PrevR.clear(); 10137 } 10138 10139 // Filter out any other lookup result from an enclosing scope. 10140 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10141 /*AllowInlineNamespace*/false); 10142 10143 // Find the previous declaration and check that we can redeclare it. 10144 NamespaceAliasDecl *Prev = nullptr; 10145 if (PrevR.isSingleResult()) { 10146 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10147 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10148 // We already have an alias with the same name that points to the same 10149 // namespace; check that it matches. 10150 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10151 Prev = AD; 10152 } else if (isVisible(PrevDecl)) { 10153 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10154 << Alias; 10155 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10156 << AD->getNamespace(); 10157 return nullptr; 10158 } 10159 } else if (isVisible(PrevDecl)) { 10160 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10161 ? diag::err_redefinition 10162 : diag::err_redefinition_different_kind; 10163 Diag(AliasLoc, DiagID) << Alias; 10164 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10165 return nullptr; 10166 } 10167 } 10168 10169 // The use of a nested name specifier may trigger deprecation warnings. 10170 DiagnoseUseOfDecl(ND, IdentLoc); 10171 10172 NamespaceAliasDecl *AliasDecl = 10173 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10174 Alias, SS.getWithLocInContext(Context), 10175 IdentLoc, ND); 10176 if (Prev) 10177 AliasDecl->setPreviousDecl(Prev); 10178 10179 PushOnScopeChains(AliasDecl, S); 10180 return AliasDecl; 10181 } 10182 10183 namespace { 10184 struct SpecialMemberExceptionSpecInfo 10185 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10186 SourceLocation Loc; 10187 Sema::ImplicitExceptionSpecification ExceptSpec; 10188 10189 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10190 Sema::CXXSpecialMember CSM, 10191 Sema::InheritedConstructorInfo *ICI, 10192 SourceLocation Loc) 10193 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10194 10195 bool visitBase(CXXBaseSpecifier *Base); 10196 bool visitField(FieldDecl *FD); 10197 10198 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10199 unsigned Quals); 10200 10201 void visitSubobjectCall(Subobject Subobj, 10202 Sema::SpecialMemberOverloadResult SMOR); 10203 }; 10204 } 10205 10206 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10207 auto *RT = Base->getType()->getAs<RecordType>(); 10208 if (!RT) 10209 return false; 10210 10211 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10212 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10213 if (auto *BaseCtor = SMOR.getMethod()) { 10214 visitSubobjectCall(Base, BaseCtor); 10215 return false; 10216 } 10217 10218 visitClassSubobject(BaseClass, Base, 0); 10219 return false; 10220 } 10221 10222 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10223 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10224 Expr *E = FD->getInClassInitializer(); 10225 if (!E) 10226 // FIXME: It's a little wasteful to build and throw away a 10227 // CXXDefaultInitExpr here. 10228 // FIXME: We should have a single context note pointing at Loc, and 10229 // this location should be MD->getLocation() instead, since that's 10230 // the location where we actually use the default init expression. 10231 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10232 if (E) 10233 ExceptSpec.CalledExpr(E); 10234 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10235 ->getAs<RecordType>()) { 10236 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10237 FD->getType().getCVRQualifiers()); 10238 } 10239 return false; 10240 } 10241 10242 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10243 Subobject Subobj, 10244 unsigned Quals) { 10245 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10246 bool IsMutable = Field && Field->isMutable(); 10247 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10248 } 10249 10250 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10251 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10252 // Note, if lookup fails, it doesn't matter what exception specification we 10253 // choose because the special member will be deleted. 10254 if (CXXMethodDecl *MD = SMOR.getMethod()) 10255 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10256 } 10257 10258 static Sema::ImplicitExceptionSpecification 10259 ComputeDefaultedSpecialMemberExceptionSpec( 10260 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 10261 Sema::InheritedConstructorInfo *ICI) { 10262 CXXRecordDecl *ClassDecl = MD->getParent(); 10263 10264 // C++ [except.spec]p14: 10265 // An implicitly declared special member function (Clause 12) shall have an 10266 // exception-specification. [...] 10267 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc); 10268 if (ClassDecl->isInvalidDecl()) 10269 return Info.ExceptSpec; 10270 10271 // C++1z [except.spec]p7: 10272 // [Look for exceptions thrown by] a constructor selected [...] to 10273 // initialize a potentially constructed subobject, 10274 // C++1z [except.spec]p8: 10275 // The exception specification for an implicitly-declared destructor, or a 10276 // destructor without a noexcept-specifier, is potentially-throwing if and 10277 // only if any of the destructors for any of its potentially constructed 10278 // subojects is potentially throwing. 10279 // FIXME: We respect the first rule but ignore the "potentially constructed" 10280 // in the second rule to resolve a core issue (no number yet) that would have 10281 // us reject: 10282 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 10283 // struct B : A {}; 10284 // struct C : B { void f(); }; 10285 // ... due to giving B::~B() a non-throwing exception specification. 10286 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 10287 : Info.VisitAllBases); 10288 10289 return Info.ExceptSpec; 10290 } 10291 10292 namespace { 10293 /// RAII object to register a special member as being currently declared. 10294 struct DeclaringSpecialMember { 10295 Sema &S; 10296 Sema::SpecialMemberDecl D; 10297 Sema::ContextRAII SavedContext; 10298 bool WasAlreadyBeingDeclared; 10299 10300 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 10301 : S(S), D(RD, CSM), SavedContext(S, RD) { 10302 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 10303 if (WasAlreadyBeingDeclared) 10304 // This almost never happens, but if it does, ensure that our cache 10305 // doesn't contain a stale result. 10306 S.SpecialMemberCache.clear(); 10307 else { 10308 // Register a note to be produced if we encounter an error while 10309 // declaring the special member. 10310 Sema::CodeSynthesisContext Ctx; 10311 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 10312 // FIXME: We don't have a location to use here. Using the class's 10313 // location maintains the fiction that we declare all special members 10314 // with the class, but (1) it's not clear that lying about that helps our 10315 // users understand what's going on, and (2) there may be outer contexts 10316 // on the stack (some of which are relevant) and printing them exposes 10317 // our lies. 10318 Ctx.PointOfInstantiation = RD->getLocation(); 10319 Ctx.Entity = RD; 10320 Ctx.SpecialMember = CSM; 10321 S.pushCodeSynthesisContext(Ctx); 10322 } 10323 } 10324 ~DeclaringSpecialMember() { 10325 if (!WasAlreadyBeingDeclared) { 10326 S.SpecialMembersBeingDeclared.erase(D); 10327 S.popCodeSynthesisContext(); 10328 } 10329 } 10330 10331 /// \brief Are we already trying to declare this special member? 10332 bool isAlreadyBeingDeclared() const { 10333 return WasAlreadyBeingDeclared; 10334 } 10335 }; 10336 } 10337 10338 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 10339 // Look up any existing declarations, but don't trigger declaration of all 10340 // implicit special members with this name. 10341 DeclarationName Name = FD->getDeclName(); 10342 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 10343 ForRedeclaration); 10344 for (auto *D : FD->getParent()->lookup(Name)) 10345 if (auto *Acceptable = R.getAcceptableDecl(D)) 10346 R.addDecl(Acceptable); 10347 R.resolveKind(); 10348 R.suppressDiagnostics(); 10349 10350 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 10351 } 10352 10353 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 10354 CXXRecordDecl *ClassDecl) { 10355 // C++ [class.ctor]p5: 10356 // A default constructor for a class X is a constructor of class X 10357 // that can be called without an argument. If there is no 10358 // user-declared constructor for class X, a default constructor is 10359 // implicitly declared. An implicitly-declared default constructor 10360 // is an inline public member of its class. 10361 assert(ClassDecl->needsImplicitDefaultConstructor() && 10362 "Should not build implicit default constructor!"); 10363 10364 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 10365 if (DSM.isAlreadyBeingDeclared()) 10366 return nullptr; 10367 10368 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10369 CXXDefaultConstructor, 10370 false); 10371 10372 // Create the actual constructor declaration. 10373 CanQualType ClassType 10374 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10375 SourceLocation ClassLoc = ClassDecl->getLocation(); 10376 DeclarationName Name 10377 = Context.DeclarationNames.getCXXConstructorName(ClassType); 10378 DeclarationNameInfo NameInfo(Name, ClassLoc); 10379 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 10380 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 10381 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 10382 /*isImplicitlyDeclared=*/true, Constexpr); 10383 DefaultCon->setAccess(AS_public); 10384 DefaultCon->setDefaulted(); 10385 10386 if (getLangOpts().CUDA) { 10387 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 10388 DefaultCon, 10389 /* ConstRHS */ false, 10390 /* Diagnose */ false); 10391 } 10392 10393 // Build an exception specification pointing back at this constructor. 10394 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 10395 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10396 10397 // We don't need to use SpecialMemberIsTrivial here; triviality for default 10398 // constructors is easy to compute. 10399 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 10400 10401 // Note that we have declared this constructor. 10402 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 10403 10404 Scope *S = getScopeForContext(ClassDecl); 10405 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 10406 10407 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 10408 SetDeclDeleted(DefaultCon, ClassLoc); 10409 10410 if (S) 10411 PushOnScopeChains(DefaultCon, S, false); 10412 ClassDecl->addDecl(DefaultCon); 10413 10414 return DefaultCon; 10415 } 10416 10417 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 10418 CXXConstructorDecl *Constructor) { 10419 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 10420 !Constructor->doesThisDeclarationHaveABody() && 10421 !Constructor->isDeleted()) && 10422 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 10423 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10424 return; 10425 10426 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10427 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 10428 10429 SynthesizedFunctionScope Scope(*this, Constructor); 10430 10431 // The exception specification is needed because we are defining the 10432 // function. 10433 ResolveExceptionSpec(CurrentLocation, 10434 Constructor->getType()->castAs<FunctionProtoType>()); 10435 MarkVTableUsed(CurrentLocation, ClassDecl); 10436 10437 // Add a context note for diagnostics produced after this point. 10438 Scope.addContextNote(CurrentLocation); 10439 10440 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 10441 Constructor->setInvalidDecl(); 10442 return; 10443 } 10444 10445 SourceLocation Loc = Constructor->getLocEnd().isValid() 10446 ? Constructor->getLocEnd() 10447 : Constructor->getLocation(); 10448 Constructor->setBody(new (Context) CompoundStmt(Loc)); 10449 Constructor->markUsed(Context); 10450 10451 if (ASTMutationListener *L = getASTMutationListener()) { 10452 L->CompletedImplicitDefinition(Constructor); 10453 } 10454 10455 DiagnoseUninitializedFields(*this, Constructor); 10456 } 10457 10458 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 10459 // Perform any delayed checks on exception specifications. 10460 CheckDelayedMemberExceptionSpecs(); 10461 } 10462 10463 /// Find or create the fake constructor we synthesize to model constructing an 10464 /// object of a derived class via a constructor of a base class. 10465 CXXConstructorDecl * 10466 Sema::findInheritingConstructor(SourceLocation Loc, 10467 CXXConstructorDecl *BaseCtor, 10468 ConstructorUsingShadowDecl *Shadow) { 10469 CXXRecordDecl *Derived = Shadow->getParent(); 10470 SourceLocation UsingLoc = Shadow->getLocation(); 10471 10472 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 10473 // For now we use the name of the base class constructor as a member of the 10474 // derived class to indicate a (fake) inherited constructor name. 10475 DeclarationName Name = BaseCtor->getDeclName(); 10476 10477 // Check to see if we already have a fake constructor for this inherited 10478 // constructor call. 10479 for (NamedDecl *Ctor : Derived->lookup(Name)) 10480 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 10481 ->getInheritedConstructor() 10482 .getConstructor(), 10483 BaseCtor)) 10484 return cast<CXXConstructorDecl>(Ctor); 10485 10486 DeclarationNameInfo NameInfo(Name, UsingLoc); 10487 TypeSourceInfo *TInfo = 10488 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 10489 FunctionProtoTypeLoc ProtoLoc = 10490 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 10491 10492 // Check the inherited constructor is valid and find the list of base classes 10493 // from which it was inherited. 10494 InheritedConstructorInfo ICI(*this, Loc, Shadow); 10495 10496 bool Constexpr = 10497 BaseCtor->isConstexpr() && 10498 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 10499 false, BaseCtor, &ICI); 10500 10501 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 10502 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 10503 BaseCtor->isExplicit(), /*Inline=*/true, 10504 /*ImplicitlyDeclared=*/true, Constexpr, 10505 InheritedConstructor(Shadow, BaseCtor)); 10506 if (Shadow->isInvalidDecl()) 10507 DerivedCtor->setInvalidDecl(); 10508 10509 // Build an unevaluated exception specification for this fake constructor. 10510 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 10511 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10512 EPI.ExceptionSpec.Type = EST_Unevaluated; 10513 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 10514 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 10515 FPT->getParamTypes(), EPI)); 10516 10517 // Build the parameter declarations. 10518 SmallVector<ParmVarDecl *, 16> ParamDecls; 10519 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 10520 TypeSourceInfo *TInfo = 10521 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 10522 ParmVarDecl *PD = ParmVarDecl::Create( 10523 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 10524 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 10525 PD->setScopeInfo(0, I); 10526 PD->setImplicit(); 10527 // Ensure attributes are propagated onto parameters (this matters for 10528 // format, pass_object_size, ...). 10529 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 10530 ParamDecls.push_back(PD); 10531 ProtoLoc.setParam(I, PD); 10532 } 10533 10534 // Set up the new constructor. 10535 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 10536 DerivedCtor->setAccess(BaseCtor->getAccess()); 10537 DerivedCtor->setParams(ParamDecls); 10538 Derived->addDecl(DerivedCtor); 10539 10540 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 10541 SetDeclDeleted(DerivedCtor, UsingLoc); 10542 10543 return DerivedCtor; 10544 } 10545 10546 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 10547 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 10548 Ctor->getInheritedConstructor().getShadowDecl()); 10549 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 10550 /*Diagnose*/true); 10551 } 10552 10553 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 10554 CXXConstructorDecl *Constructor) { 10555 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10556 assert(Constructor->getInheritedConstructor() && 10557 !Constructor->doesThisDeclarationHaveABody() && 10558 !Constructor->isDeleted()); 10559 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10560 return; 10561 10562 // Initializations are performed "as if by a defaulted default constructor", 10563 // so enter the appropriate scope. 10564 SynthesizedFunctionScope Scope(*this, Constructor); 10565 10566 // The exception specification is needed because we are defining the 10567 // function. 10568 ResolveExceptionSpec(CurrentLocation, 10569 Constructor->getType()->castAs<FunctionProtoType>()); 10570 MarkVTableUsed(CurrentLocation, ClassDecl); 10571 10572 // Add a context note for diagnostics produced after this point. 10573 Scope.addContextNote(CurrentLocation); 10574 10575 ConstructorUsingShadowDecl *Shadow = 10576 Constructor->getInheritedConstructor().getShadowDecl(); 10577 CXXConstructorDecl *InheritedCtor = 10578 Constructor->getInheritedConstructor().getConstructor(); 10579 10580 // [class.inhctor.init]p1: 10581 // initialization proceeds as if a defaulted default constructor is used to 10582 // initialize the D object and each base class subobject from which the 10583 // constructor was inherited 10584 10585 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 10586 CXXRecordDecl *RD = Shadow->getParent(); 10587 SourceLocation InitLoc = Shadow->getLocation(); 10588 10589 // Build explicit initializers for all base classes from which the 10590 // constructor was inherited. 10591 SmallVector<CXXCtorInitializer*, 8> Inits; 10592 for (bool VBase : {false, true}) { 10593 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 10594 if (B.isVirtual() != VBase) 10595 continue; 10596 10597 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 10598 if (!BaseRD) 10599 continue; 10600 10601 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 10602 if (!BaseCtor.first) 10603 continue; 10604 10605 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 10606 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 10607 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 10608 10609 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 10610 Inits.push_back(new (Context) CXXCtorInitializer( 10611 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 10612 SourceLocation())); 10613 } 10614 } 10615 10616 // We now proceed as if for a defaulted default constructor, with the relevant 10617 // initializers replaced. 10618 10619 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 10620 Constructor->setInvalidDecl(); 10621 return; 10622 } 10623 10624 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 10625 Constructor->markUsed(Context); 10626 10627 if (ASTMutationListener *L = getASTMutationListener()) { 10628 L->CompletedImplicitDefinition(Constructor); 10629 } 10630 10631 DiagnoseUninitializedFields(*this, Constructor); 10632 } 10633 10634 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 10635 // C++ [class.dtor]p2: 10636 // If a class has no user-declared destructor, a destructor is 10637 // declared implicitly. An implicitly-declared destructor is an 10638 // inline public member of its class. 10639 assert(ClassDecl->needsImplicitDestructor()); 10640 10641 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 10642 if (DSM.isAlreadyBeingDeclared()) 10643 return nullptr; 10644 10645 // Create the actual destructor declaration. 10646 CanQualType ClassType 10647 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10648 SourceLocation ClassLoc = ClassDecl->getLocation(); 10649 DeclarationName Name 10650 = Context.DeclarationNames.getCXXDestructorName(ClassType); 10651 DeclarationNameInfo NameInfo(Name, ClassLoc); 10652 CXXDestructorDecl *Destructor 10653 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 10654 QualType(), nullptr, /*isInline=*/true, 10655 /*isImplicitlyDeclared=*/true); 10656 Destructor->setAccess(AS_public); 10657 Destructor->setDefaulted(); 10658 10659 if (getLangOpts().CUDA) { 10660 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 10661 Destructor, 10662 /* ConstRHS */ false, 10663 /* Diagnose */ false); 10664 } 10665 10666 // Build an exception specification pointing back at this destructor. 10667 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 10668 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10669 10670 // We don't need to use SpecialMemberIsTrivial here; triviality for 10671 // destructors is easy to compute. 10672 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 10673 10674 // Note that we have declared this destructor. 10675 ++ASTContext::NumImplicitDestructorsDeclared; 10676 10677 Scope *S = getScopeForContext(ClassDecl); 10678 CheckImplicitSpecialMemberDeclaration(S, Destructor); 10679 10680 // We can't check whether an implicit destructor is deleted before we complete 10681 // the definition of the class, because its validity depends on the alignment 10682 // of the class. We'll check this from ActOnFields once the class is complete. 10683 if (ClassDecl->isCompleteDefinition() && 10684 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 10685 SetDeclDeleted(Destructor, ClassLoc); 10686 10687 // Introduce this destructor into its scope. 10688 if (S) 10689 PushOnScopeChains(Destructor, S, false); 10690 ClassDecl->addDecl(Destructor); 10691 10692 return Destructor; 10693 } 10694 10695 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 10696 CXXDestructorDecl *Destructor) { 10697 assert((Destructor->isDefaulted() && 10698 !Destructor->doesThisDeclarationHaveABody() && 10699 !Destructor->isDeleted()) && 10700 "DefineImplicitDestructor - call it for implicit default dtor"); 10701 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 10702 return; 10703 10704 CXXRecordDecl *ClassDecl = Destructor->getParent(); 10705 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 10706 10707 SynthesizedFunctionScope Scope(*this, Destructor); 10708 10709 // The exception specification is needed because we are defining the 10710 // function. 10711 ResolveExceptionSpec(CurrentLocation, 10712 Destructor->getType()->castAs<FunctionProtoType>()); 10713 MarkVTableUsed(CurrentLocation, ClassDecl); 10714 10715 // Add a context note for diagnostics produced after this point. 10716 Scope.addContextNote(CurrentLocation); 10717 10718 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10719 Destructor->getParent()); 10720 10721 if (CheckDestructor(Destructor)) { 10722 Destructor->setInvalidDecl(); 10723 return; 10724 } 10725 10726 SourceLocation Loc = Destructor->getLocEnd().isValid() 10727 ? Destructor->getLocEnd() 10728 : Destructor->getLocation(); 10729 Destructor->setBody(new (Context) CompoundStmt(Loc)); 10730 Destructor->markUsed(Context); 10731 10732 if (ASTMutationListener *L = getASTMutationListener()) { 10733 L->CompletedImplicitDefinition(Destructor); 10734 } 10735 } 10736 10737 /// \brief Perform any semantic analysis which needs to be delayed until all 10738 /// pending class member declarations have been parsed. 10739 void Sema::ActOnFinishCXXMemberDecls() { 10740 // If the context is an invalid C++ class, just suppress these checks. 10741 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 10742 if (Record->isInvalidDecl()) { 10743 DelayedDefaultedMemberExceptionSpecs.clear(); 10744 DelayedExceptionSpecChecks.clear(); 10745 return; 10746 } 10747 checkForMultipleExportedDefaultConstructors(*this, Record); 10748 } 10749 } 10750 10751 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 10752 referenceDLLExportedClassMethods(); 10753 } 10754 10755 void Sema::referenceDLLExportedClassMethods() { 10756 if (!DelayedDllExportClasses.empty()) { 10757 // Calling ReferenceDllExportedMethods might cause the current function to 10758 // be called again, so use a local copy of DelayedDllExportClasses. 10759 SmallVector<CXXRecordDecl *, 4> WorkList; 10760 std::swap(DelayedDllExportClasses, WorkList); 10761 for (CXXRecordDecl *Class : WorkList) 10762 ReferenceDllExportedMethods(*this, Class); 10763 } 10764 } 10765 10766 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 10767 CXXDestructorDecl *Destructor) { 10768 assert(getLangOpts().CPlusPlus11 && 10769 "adjusting dtor exception specs was introduced in c++11"); 10770 10771 // C++11 [class.dtor]p3: 10772 // A declaration of a destructor that does not have an exception- 10773 // specification is implicitly considered to have the same exception- 10774 // specification as an implicit declaration. 10775 const FunctionProtoType *DtorType = Destructor->getType()-> 10776 getAs<FunctionProtoType>(); 10777 if (DtorType->hasExceptionSpec()) 10778 return; 10779 10780 // Replace the destructor's type, building off the existing one. Fortunately, 10781 // the only thing of interest in the destructor type is its extended info. 10782 // The return and arguments are fixed. 10783 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 10784 EPI.ExceptionSpec.Type = EST_Unevaluated; 10785 EPI.ExceptionSpec.SourceDecl = Destructor; 10786 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10787 10788 // FIXME: If the destructor has a body that could throw, and the newly created 10789 // spec doesn't allow exceptions, we should emit a warning, because this 10790 // change in behavior can break conforming C++03 programs at runtime. 10791 // However, we don't have a body or an exception specification yet, so it 10792 // needs to be done somewhere else. 10793 } 10794 10795 namespace { 10796 /// \brief An abstract base class for all helper classes used in building the 10797 // copy/move operators. These classes serve as factory functions and help us 10798 // avoid using the same Expr* in the AST twice. 10799 class ExprBuilder { 10800 ExprBuilder(const ExprBuilder&) = delete; 10801 ExprBuilder &operator=(const ExprBuilder&) = delete; 10802 10803 protected: 10804 static Expr *assertNotNull(Expr *E) { 10805 assert(E && "Expression construction must not fail."); 10806 return E; 10807 } 10808 10809 public: 10810 ExprBuilder() {} 10811 virtual ~ExprBuilder() {} 10812 10813 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 10814 }; 10815 10816 class RefBuilder: public ExprBuilder { 10817 VarDecl *Var; 10818 QualType VarType; 10819 10820 public: 10821 Expr *build(Sema &S, SourceLocation Loc) const override { 10822 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 10823 } 10824 10825 RefBuilder(VarDecl *Var, QualType VarType) 10826 : Var(Var), VarType(VarType) {} 10827 }; 10828 10829 class ThisBuilder: public ExprBuilder { 10830 public: 10831 Expr *build(Sema &S, SourceLocation Loc) const override { 10832 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 10833 } 10834 }; 10835 10836 class CastBuilder: public ExprBuilder { 10837 const ExprBuilder &Builder; 10838 QualType Type; 10839 ExprValueKind Kind; 10840 const CXXCastPath &Path; 10841 10842 public: 10843 Expr *build(Sema &S, SourceLocation Loc) const override { 10844 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 10845 CK_UncheckedDerivedToBase, Kind, 10846 &Path).get()); 10847 } 10848 10849 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 10850 const CXXCastPath &Path) 10851 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 10852 }; 10853 10854 class DerefBuilder: public ExprBuilder { 10855 const ExprBuilder &Builder; 10856 10857 public: 10858 Expr *build(Sema &S, SourceLocation Loc) const override { 10859 return assertNotNull( 10860 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 10861 } 10862 10863 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10864 }; 10865 10866 class MemberBuilder: public ExprBuilder { 10867 const ExprBuilder &Builder; 10868 QualType Type; 10869 CXXScopeSpec SS; 10870 bool IsArrow; 10871 LookupResult &MemberLookup; 10872 10873 public: 10874 Expr *build(Sema &S, SourceLocation Loc) const override { 10875 return assertNotNull(S.BuildMemberReferenceExpr( 10876 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 10877 nullptr, MemberLookup, nullptr, nullptr).get()); 10878 } 10879 10880 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 10881 LookupResult &MemberLookup) 10882 : Builder(Builder), Type(Type), IsArrow(IsArrow), 10883 MemberLookup(MemberLookup) {} 10884 }; 10885 10886 class MoveCastBuilder: public ExprBuilder { 10887 const ExprBuilder &Builder; 10888 10889 public: 10890 Expr *build(Sema &S, SourceLocation Loc) const override { 10891 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 10892 } 10893 10894 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10895 }; 10896 10897 class LvalueConvBuilder: public ExprBuilder { 10898 const ExprBuilder &Builder; 10899 10900 public: 10901 Expr *build(Sema &S, SourceLocation Loc) const override { 10902 return assertNotNull( 10903 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 10904 } 10905 10906 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10907 }; 10908 10909 class SubscriptBuilder: public ExprBuilder { 10910 const ExprBuilder &Base; 10911 const ExprBuilder &Index; 10912 10913 public: 10914 Expr *build(Sema &S, SourceLocation Loc) const override { 10915 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 10916 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 10917 } 10918 10919 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 10920 : Base(Base), Index(Index) {} 10921 }; 10922 10923 } // end anonymous namespace 10924 10925 /// When generating a defaulted copy or move assignment operator, if a field 10926 /// should be copied with __builtin_memcpy rather than via explicit assignments, 10927 /// do so. This optimization only applies for arrays of scalars, and for arrays 10928 /// of class type where the selected copy/move-assignment operator is trivial. 10929 static StmtResult 10930 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 10931 const ExprBuilder &ToB, const ExprBuilder &FromB) { 10932 // Compute the size of the memory buffer to be copied. 10933 QualType SizeType = S.Context.getSizeType(); 10934 llvm::APInt Size(S.Context.getTypeSize(SizeType), 10935 S.Context.getTypeSizeInChars(T).getQuantity()); 10936 10937 // Take the address of the field references for "from" and "to". We 10938 // directly construct UnaryOperators here because semantic analysis 10939 // does not permit us to take the address of an xvalue. 10940 Expr *From = FromB.build(S, Loc); 10941 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 10942 S.Context.getPointerType(From->getType()), 10943 VK_RValue, OK_Ordinary, Loc); 10944 Expr *To = ToB.build(S, Loc); 10945 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 10946 S.Context.getPointerType(To->getType()), 10947 VK_RValue, OK_Ordinary, Loc); 10948 10949 const Type *E = T->getBaseElementTypeUnsafe(); 10950 bool NeedsCollectableMemCpy = 10951 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 10952 10953 // Create a reference to the __builtin_objc_memmove_collectable function 10954 StringRef MemCpyName = NeedsCollectableMemCpy ? 10955 "__builtin_objc_memmove_collectable" : 10956 "__builtin_memcpy"; 10957 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 10958 Sema::LookupOrdinaryName); 10959 S.LookupName(R, S.TUScope, true); 10960 10961 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 10962 if (!MemCpy) 10963 // Something went horribly wrong earlier, and we will have complained 10964 // about it. 10965 return StmtError(); 10966 10967 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 10968 VK_RValue, Loc, nullptr); 10969 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 10970 10971 Expr *CallArgs[] = { 10972 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 10973 }; 10974 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 10975 Loc, CallArgs, Loc); 10976 10977 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 10978 return Call.getAs<Stmt>(); 10979 } 10980 10981 /// \brief Builds a statement that copies/moves the given entity from \p From to 10982 /// \c To. 10983 /// 10984 /// This routine is used to copy/move the members of a class with an 10985 /// implicitly-declared copy/move assignment operator. When the entities being 10986 /// copied are arrays, this routine builds for loops to copy them. 10987 /// 10988 /// \param S The Sema object used for type-checking. 10989 /// 10990 /// \param Loc The location where the implicit copy/move is being generated. 10991 /// 10992 /// \param T The type of the expressions being copied/moved. Both expressions 10993 /// must have this type. 10994 /// 10995 /// \param To The expression we are copying/moving to. 10996 /// 10997 /// \param From The expression we are copying/moving from. 10998 /// 10999 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 11000 /// Otherwise, it's a non-static member subobject. 11001 /// 11002 /// \param Copying Whether we're copying or moving. 11003 /// 11004 /// \param Depth Internal parameter recording the depth of the recursion. 11005 /// 11006 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11007 /// if a memcpy should be used instead. 11008 static StmtResult 11009 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11010 const ExprBuilder &To, const ExprBuilder &From, 11011 bool CopyingBaseSubobject, bool Copying, 11012 unsigned Depth = 0) { 11013 // C++11 [class.copy]p28: 11014 // Each subobject is assigned in the manner appropriate to its type: 11015 // 11016 // - if the subobject is of class type, as if by a call to operator= with 11017 // the subobject as the object expression and the corresponding 11018 // subobject of x as a single function argument (as if by explicit 11019 // qualification; that is, ignoring any possible virtual overriding 11020 // functions in more derived classes); 11021 // 11022 // C++03 [class.copy]p13: 11023 // - if the subobject is of class type, the copy assignment operator for 11024 // the class is used (as if by explicit qualification; that is, 11025 // ignoring any possible virtual overriding functions in more derived 11026 // classes); 11027 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11028 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11029 11030 // Look for operator=. 11031 DeclarationName Name 11032 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11033 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11034 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11035 11036 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11037 // operator. 11038 if (!S.getLangOpts().CPlusPlus11) { 11039 LookupResult::Filter F = OpLookup.makeFilter(); 11040 while (F.hasNext()) { 11041 NamedDecl *D = F.next(); 11042 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11043 if (Method->isCopyAssignmentOperator() || 11044 (!Copying && Method->isMoveAssignmentOperator())) 11045 continue; 11046 11047 F.erase(); 11048 } 11049 F.done(); 11050 } 11051 11052 // Suppress the protected check (C++ [class.protected]) for each of the 11053 // assignment operators we found. This strange dance is required when 11054 // we're assigning via a base classes's copy-assignment operator. To 11055 // ensure that we're getting the right base class subobject (without 11056 // ambiguities), we need to cast "this" to that subobject type; to 11057 // ensure that we don't go through the virtual call mechanism, we need 11058 // to qualify the operator= name with the base class (see below). However, 11059 // this means that if the base class has a protected copy assignment 11060 // operator, the protected member access check will fail. So, we 11061 // rewrite "protected" access to "public" access in this case, since we 11062 // know by construction that we're calling from a derived class. 11063 if (CopyingBaseSubobject) { 11064 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11065 L != LEnd; ++L) { 11066 if (L.getAccess() == AS_protected) 11067 L.setAccess(AS_public); 11068 } 11069 } 11070 11071 // Create the nested-name-specifier that will be used to qualify the 11072 // reference to operator=; this is required to suppress the virtual 11073 // call mechanism. 11074 CXXScopeSpec SS; 11075 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11076 SS.MakeTrivial(S.Context, 11077 NestedNameSpecifier::Create(S.Context, nullptr, false, 11078 CanonicalT), 11079 Loc); 11080 11081 // Create the reference to operator=. 11082 ExprResult OpEqualRef 11083 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 11084 SS, /*TemplateKWLoc=*/SourceLocation(), 11085 /*FirstQualifierInScope=*/nullptr, 11086 OpLookup, 11087 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11088 /*SuppressQualifierCheck=*/true); 11089 if (OpEqualRef.isInvalid()) 11090 return StmtError(); 11091 11092 // Build the call to the assignment operator. 11093 11094 Expr *FromInst = From.build(S, Loc); 11095 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11096 OpEqualRef.getAs<Expr>(), 11097 Loc, FromInst, Loc); 11098 if (Call.isInvalid()) 11099 return StmtError(); 11100 11101 // If we built a call to a trivial 'operator=' while copying an array, 11102 // bail out. We'll replace the whole shebang with a memcpy. 11103 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11104 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11105 return StmtResult((Stmt*)nullptr); 11106 11107 // Convert to an expression-statement, and clean up any produced 11108 // temporaries. 11109 return S.ActOnExprStmt(Call); 11110 } 11111 11112 // - if the subobject is of scalar type, the built-in assignment 11113 // operator is used. 11114 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11115 if (!ArrayTy) { 11116 ExprResult Assignment = S.CreateBuiltinBinOp( 11117 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11118 if (Assignment.isInvalid()) 11119 return StmtError(); 11120 return S.ActOnExprStmt(Assignment); 11121 } 11122 11123 // - if the subobject is an array, each element is assigned, in the 11124 // manner appropriate to the element type; 11125 11126 // Construct a loop over the array bounds, e.g., 11127 // 11128 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11129 // 11130 // that will copy each of the array elements. 11131 QualType SizeType = S.Context.getSizeType(); 11132 11133 // Create the iteration variable. 11134 IdentifierInfo *IterationVarName = nullptr; 11135 { 11136 SmallString<8> Str; 11137 llvm::raw_svector_ostream OS(Str); 11138 OS << "__i" << Depth; 11139 IterationVarName = &S.Context.Idents.get(OS.str()); 11140 } 11141 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11142 IterationVarName, SizeType, 11143 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11144 SC_None); 11145 11146 // Initialize the iteration variable to zero. 11147 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11148 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11149 11150 // Creates a reference to the iteration variable. 11151 RefBuilder IterationVarRef(IterationVar, SizeType); 11152 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11153 11154 // Create the DeclStmt that holds the iteration variable. 11155 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11156 11157 // Subscript the "from" and "to" expressions with the iteration variable. 11158 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11159 MoveCastBuilder FromIndexMove(FromIndexCopy); 11160 const ExprBuilder *FromIndex; 11161 if (Copying) 11162 FromIndex = &FromIndexCopy; 11163 else 11164 FromIndex = &FromIndexMove; 11165 11166 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11167 11168 // Build the copy/move for an individual element of the array. 11169 StmtResult Copy = 11170 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11171 ToIndex, *FromIndex, CopyingBaseSubobject, 11172 Copying, Depth + 1); 11173 // Bail out if copying fails or if we determined that we should use memcpy. 11174 if (Copy.isInvalid() || !Copy.get()) 11175 return Copy; 11176 11177 // Create the comparison against the array bound. 11178 llvm::APInt Upper 11179 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11180 Expr *Comparison 11181 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11182 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11183 BO_NE, S.Context.BoolTy, 11184 VK_RValue, OK_Ordinary, Loc, FPOptions()); 11185 11186 // Create the pre-increment of the iteration variable. 11187 Expr *Increment 11188 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 11189 SizeType, VK_LValue, OK_Ordinary, Loc); 11190 11191 // Construct the loop that copies all elements of this array. 11192 return S.ActOnForStmt( 11193 Loc, Loc, InitStmt, 11194 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 11195 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 11196 } 11197 11198 static StmtResult 11199 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 11200 const ExprBuilder &To, const ExprBuilder &From, 11201 bool CopyingBaseSubobject, bool Copying) { 11202 // Maybe we should use a memcpy? 11203 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 11204 T.isTriviallyCopyableType(S.Context)) 11205 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11206 11207 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 11208 CopyingBaseSubobject, 11209 Copying, 0)); 11210 11211 // If we ended up picking a trivial assignment operator for an array of a 11212 // non-trivially-copyable class type, just emit a memcpy. 11213 if (!Result.isInvalid() && !Result.get()) 11214 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11215 11216 return Result; 11217 } 11218 11219 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 11220 // Note: The following rules are largely analoguous to the copy 11221 // constructor rules. Note that virtual bases are not taken into account 11222 // for determining the argument type of the operator. Note also that 11223 // operators taking an object instead of a reference are allowed. 11224 assert(ClassDecl->needsImplicitCopyAssignment()); 11225 11226 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 11227 if (DSM.isAlreadyBeingDeclared()) 11228 return nullptr; 11229 11230 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11231 QualType RetType = Context.getLValueReferenceType(ArgType); 11232 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 11233 if (Const) 11234 ArgType = ArgType.withConst(); 11235 ArgType = Context.getLValueReferenceType(ArgType); 11236 11237 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11238 CXXCopyAssignment, 11239 Const); 11240 11241 // An implicitly-declared copy assignment operator is an inline public 11242 // member of its class. 11243 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11244 SourceLocation ClassLoc = ClassDecl->getLocation(); 11245 DeclarationNameInfo NameInfo(Name, ClassLoc); 11246 CXXMethodDecl *CopyAssignment = 11247 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11248 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11249 /*isInline=*/true, Constexpr, SourceLocation()); 11250 CopyAssignment->setAccess(AS_public); 11251 CopyAssignment->setDefaulted(); 11252 CopyAssignment->setImplicit(); 11253 11254 if (getLangOpts().CUDA) { 11255 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 11256 CopyAssignment, 11257 /* ConstRHS */ Const, 11258 /* Diagnose */ false); 11259 } 11260 11261 // Build an exception specification pointing back at this member. 11262 FunctionProtoType::ExtProtoInfo EPI = 11263 getImplicitMethodEPI(*this, CopyAssignment); 11264 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11265 11266 // Add the parameter to the operator. 11267 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 11268 ClassLoc, ClassLoc, 11269 /*Id=*/nullptr, ArgType, 11270 /*TInfo=*/nullptr, SC_None, 11271 nullptr); 11272 CopyAssignment->setParams(FromParam); 11273 11274 CopyAssignment->setTrivial( 11275 ClassDecl->needsOverloadResolutionForCopyAssignment() 11276 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 11277 : ClassDecl->hasTrivialCopyAssignment()); 11278 11279 // Note that we have added this copy-assignment operator. 11280 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 11281 11282 Scope *S = getScopeForContext(ClassDecl); 11283 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 11284 11285 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 11286 SetDeclDeleted(CopyAssignment, ClassLoc); 11287 11288 if (S) 11289 PushOnScopeChains(CopyAssignment, S, false); 11290 ClassDecl->addDecl(CopyAssignment); 11291 11292 return CopyAssignment; 11293 } 11294 11295 /// Diagnose an implicit copy operation for a class which is odr-used, but 11296 /// which is deprecated because the class has a user-declared copy constructor, 11297 /// copy assignment operator, or destructor. 11298 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 11299 assert(CopyOp->isImplicit()); 11300 11301 CXXRecordDecl *RD = CopyOp->getParent(); 11302 CXXMethodDecl *UserDeclaredOperation = nullptr; 11303 11304 // In Microsoft mode, assignment operations don't affect constructors and 11305 // vice versa. 11306 if (RD->hasUserDeclaredDestructor()) { 11307 UserDeclaredOperation = RD->getDestructor(); 11308 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11309 RD->hasUserDeclaredCopyConstructor() && 11310 !S.getLangOpts().MSVCCompat) { 11311 // Find any user-declared copy constructor. 11312 for (auto *I : RD->ctors()) { 11313 if (I->isCopyConstructor()) { 11314 UserDeclaredOperation = I; 11315 break; 11316 } 11317 } 11318 assert(UserDeclaredOperation); 11319 } else if (isa<CXXConstructorDecl>(CopyOp) && 11320 RD->hasUserDeclaredCopyAssignment() && 11321 !S.getLangOpts().MSVCCompat) { 11322 // Find any user-declared move assignment operator. 11323 for (auto *I : RD->methods()) { 11324 if (I->isCopyAssignmentOperator()) { 11325 UserDeclaredOperation = I; 11326 break; 11327 } 11328 } 11329 assert(UserDeclaredOperation); 11330 } 11331 11332 if (UserDeclaredOperation) { 11333 S.Diag(UserDeclaredOperation->getLocation(), 11334 diag::warn_deprecated_copy_operation) 11335 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11336 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11337 } 11338 } 11339 11340 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11341 CXXMethodDecl *CopyAssignOperator) { 11342 assert((CopyAssignOperator->isDefaulted() && 11343 CopyAssignOperator->isOverloadedOperator() && 11344 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11345 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11346 !CopyAssignOperator->isDeleted()) && 11347 "DefineImplicitCopyAssignment called for wrong function"); 11348 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 11349 return; 11350 11351 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11352 if (ClassDecl->isInvalidDecl()) { 11353 CopyAssignOperator->setInvalidDecl(); 11354 return; 11355 } 11356 11357 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11358 11359 // The exception specification is needed because we are defining the 11360 // function. 11361 ResolveExceptionSpec(CurrentLocation, 11362 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11363 11364 // Add a context note for diagnostics produced after this point. 11365 Scope.addContextNote(CurrentLocation); 11366 11367 // C++11 [class.copy]p18: 11368 // The [definition of an implicitly declared copy assignment operator] is 11369 // deprecated if the class has a user-declared copy constructor or a 11370 // user-declared destructor. 11371 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11372 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 11373 11374 // C++0x [class.copy]p30: 11375 // The implicitly-defined or explicitly-defaulted copy assignment operator 11376 // for a non-union class X performs memberwise copy assignment of its 11377 // subobjects. The direct base classes of X are assigned first, in the 11378 // order of their declaration in the base-specifier-list, and then the 11379 // immediate non-static data members of X are assigned, in the order in 11380 // which they were declared in the class definition. 11381 11382 // The statements that form the synthesized function body. 11383 SmallVector<Stmt*, 8> Statements; 11384 11385 // The parameter for the "other" object, which we are copying from. 11386 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 11387 Qualifiers OtherQuals = Other->getType().getQualifiers(); 11388 QualType OtherRefType = Other->getType(); 11389 if (const LValueReferenceType *OtherRef 11390 = OtherRefType->getAs<LValueReferenceType>()) { 11391 OtherRefType = OtherRef->getPointeeType(); 11392 OtherQuals = OtherRefType.getQualifiers(); 11393 } 11394 11395 // Our location for everything implicitly-generated. 11396 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 11397 ? CopyAssignOperator->getLocEnd() 11398 : CopyAssignOperator->getLocation(); 11399 11400 // Builds a DeclRefExpr for the "other" object. 11401 RefBuilder OtherRef(Other, OtherRefType); 11402 11403 // Builds the "this" pointer. 11404 ThisBuilder This; 11405 11406 // Assign base classes. 11407 bool Invalid = false; 11408 for (auto &Base : ClassDecl->bases()) { 11409 // Form the assignment: 11410 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 11411 QualType BaseType = Base.getType().getUnqualifiedType(); 11412 if (!BaseType->isRecordType()) { 11413 Invalid = true; 11414 continue; 11415 } 11416 11417 CXXCastPath BasePath; 11418 BasePath.push_back(&Base); 11419 11420 // Construct the "from" expression, which is an implicit cast to the 11421 // appropriately-qualified base type. 11422 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 11423 VK_LValue, BasePath); 11424 11425 // Dereference "this". 11426 DerefBuilder DerefThis(This); 11427 CastBuilder To(DerefThis, 11428 Context.getCVRQualifiedType( 11429 BaseType, CopyAssignOperator->getTypeQualifiers()), 11430 VK_LValue, BasePath); 11431 11432 // Build the copy. 11433 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 11434 To, From, 11435 /*CopyingBaseSubobject=*/true, 11436 /*Copying=*/true); 11437 if (Copy.isInvalid()) { 11438 CopyAssignOperator->setInvalidDecl(); 11439 return; 11440 } 11441 11442 // Success! Record the copy. 11443 Statements.push_back(Copy.getAs<Expr>()); 11444 } 11445 11446 // Assign non-static members. 11447 for (auto *Field : ClassDecl->fields()) { 11448 // FIXME: We should form some kind of AST representation for the implied 11449 // memcpy in a union copy operation. 11450 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11451 continue; 11452 11453 if (Field->isInvalidDecl()) { 11454 Invalid = true; 11455 continue; 11456 } 11457 11458 // Check for members of reference type; we can't copy those. 11459 if (Field->getType()->isReferenceType()) { 11460 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11461 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11462 Diag(Field->getLocation(), diag::note_declared_at); 11463 Invalid = true; 11464 continue; 11465 } 11466 11467 // Check for members of const-qualified, non-class type. 11468 QualType BaseType = Context.getBaseElementType(Field->getType()); 11469 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11470 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11471 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11472 Diag(Field->getLocation(), diag::note_declared_at); 11473 Invalid = true; 11474 continue; 11475 } 11476 11477 // Suppress assigning zero-width bitfields. 11478 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11479 continue; 11480 11481 QualType FieldType = Field->getType().getNonReferenceType(); 11482 if (FieldType->isIncompleteArrayType()) { 11483 assert(ClassDecl->hasFlexibleArrayMember() && 11484 "Incomplete array type is not valid"); 11485 continue; 11486 } 11487 11488 // Build references to the field in the object we're copying from and to. 11489 CXXScopeSpec SS; // Intentionally empty 11490 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11491 LookupMemberName); 11492 MemberLookup.addDecl(Field); 11493 MemberLookup.resolveKind(); 11494 11495 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 11496 11497 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 11498 11499 // Build the copy of this field. 11500 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 11501 To, From, 11502 /*CopyingBaseSubobject=*/false, 11503 /*Copying=*/true); 11504 if (Copy.isInvalid()) { 11505 CopyAssignOperator->setInvalidDecl(); 11506 return; 11507 } 11508 11509 // Success! Record the copy. 11510 Statements.push_back(Copy.getAs<Stmt>()); 11511 } 11512 11513 if (!Invalid) { 11514 // Add a "return *this;" 11515 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11516 11517 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11518 if (Return.isInvalid()) 11519 Invalid = true; 11520 else 11521 Statements.push_back(Return.getAs<Stmt>()); 11522 } 11523 11524 if (Invalid) { 11525 CopyAssignOperator->setInvalidDecl(); 11526 return; 11527 } 11528 11529 StmtResult Body; 11530 { 11531 CompoundScopeRAII CompoundScope(*this); 11532 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11533 /*isStmtExpr=*/false); 11534 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11535 } 11536 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 11537 CopyAssignOperator->markUsed(Context); 11538 11539 if (ASTMutationListener *L = getASTMutationListener()) { 11540 L->CompletedImplicitDefinition(CopyAssignOperator); 11541 } 11542 } 11543 11544 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 11545 assert(ClassDecl->needsImplicitMoveAssignment()); 11546 11547 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 11548 if (DSM.isAlreadyBeingDeclared()) 11549 return nullptr; 11550 11551 // Note: The following rules are largely analoguous to the move 11552 // constructor rules. 11553 11554 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11555 QualType RetType = Context.getLValueReferenceType(ArgType); 11556 ArgType = Context.getRValueReferenceType(ArgType); 11557 11558 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11559 CXXMoveAssignment, 11560 false); 11561 11562 // An implicitly-declared move assignment operator is an inline public 11563 // member of its class. 11564 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11565 SourceLocation ClassLoc = ClassDecl->getLocation(); 11566 DeclarationNameInfo NameInfo(Name, ClassLoc); 11567 CXXMethodDecl *MoveAssignment = 11568 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11569 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11570 /*isInline=*/true, Constexpr, SourceLocation()); 11571 MoveAssignment->setAccess(AS_public); 11572 MoveAssignment->setDefaulted(); 11573 MoveAssignment->setImplicit(); 11574 11575 if (getLangOpts().CUDA) { 11576 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 11577 MoveAssignment, 11578 /* ConstRHS */ false, 11579 /* Diagnose */ false); 11580 } 11581 11582 // Build an exception specification pointing back at this member. 11583 FunctionProtoType::ExtProtoInfo EPI = 11584 getImplicitMethodEPI(*this, MoveAssignment); 11585 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11586 11587 // Add the parameter to the operator. 11588 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 11589 ClassLoc, ClassLoc, 11590 /*Id=*/nullptr, ArgType, 11591 /*TInfo=*/nullptr, SC_None, 11592 nullptr); 11593 MoveAssignment->setParams(FromParam); 11594 11595 MoveAssignment->setTrivial( 11596 ClassDecl->needsOverloadResolutionForMoveAssignment() 11597 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 11598 : ClassDecl->hasTrivialMoveAssignment()); 11599 11600 // Note that we have added this copy-assignment operator. 11601 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 11602 11603 Scope *S = getScopeForContext(ClassDecl); 11604 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 11605 11606 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 11607 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 11608 SetDeclDeleted(MoveAssignment, ClassLoc); 11609 } 11610 11611 if (S) 11612 PushOnScopeChains(MoveAssignment, S, false); 11613 ClassDecl->addDecl(MoveAssignment); 11614 11615 return MoveAssignment; 11616 } 11617 11618 /// Check if we're implicitly defining a move assignment operator for a class 11619 /// with virtual bases. Such a move assignment might move-assign the virtual 11620 /// base multiple times. 11621 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 11622 SourceLocation CurrentLocation) { 11623 assert(!Class->isDependentContext() && "should not define dependent move"); 11624 11625 // Only a virtual base could get implicitly move-assigned multiple times. 11626 // Only a non-trivial move assignment can observe this. We only want to 11627 // diagnose if we implicitly define an assignment operator that assigns 11628 // two base classes, both of which move-assign the same virtual base. 11629 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 11630 Class->getNumBases() < 2) 11631 return; 11632 11633 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 11634 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 11635 VBaseMap VBases; 11636 11637 for (auto &BI : Class->bases()) { 11638 Worklist.push_back(&BI); 11639 while (!Worklist.empty()) { 11640 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 11641 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 11642 11643 // If the base has no non-trivial move assignment operators, 11644 // we don't care about moves from it. 11645 if (!Base->hasNonTrivialMoveAssignment()) 11646 continue; 11647 11648 // If there's nothing virtual here, skip it. 11649 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 11650 continue; 11651 11652 // If we're not actually going to call a move assignment for this base, 11653 // or the selected move assignment is trivial, skip it. 11654 Sema::SpecialMemberOverloadResult SMOR = 11655 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 11656 /*ConstArg*/false, /*VolatileArg*/false, 11657 /*RValueThis*/true, /*ConstThis*/false, 11658 /*VolatileThis*/false); 11659 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 11660 !SMOR.getMethod()->isMoveAssignmentOperator()) 11661 continue; 11662 11663 if (BaseSpec->isVirtual()) { 11664 // We're going to move-assign this virtual base, and its move 11665 // assignment operator is not trivial. If this can happen for 11666 // multiple distinct direct bases of Class, diagnose it. (If it 11667 // only happens in one base, we'll diagnose it when synthesizing 11668 // that base class's move assignment operator.) 11669 CXXBaseSpecifier *&Existing = 11670 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 11671 .first->second; 11672 if (Existing && Existing != &BI) { 11673 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 11674 << Class << Base; 11675 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 11676 << (Base->getCanonicalDecl() == 11677 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11678 << Base << Existing->getType() << Existing->getSourceRange(); 11679 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 11680 << (Base->getCanonicalDecl() == 11681 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11682 << Base << BI.getType() << BaseSpec->getSourceRange(); 11683 11684 // Only diagnose each vbase once. 11685 Existing = nullptr; 11686 } 11687 } else { 11688 // Only walk over bases that have defaulted move assignment operators. 11689 // We assume that any user-provided move assignment operator handles 11690 // the multiple-moves-of-vbase case itself somehow. 11691 if (!SMOR.getMethod()->isDefaulted()) 11692 continue; 11693 11694 // We're going to move the base classes of Base. Add them to the list. 11695 for (auto &BI : Base->bases()) 11696 Worklist.push_back(&BI); 11697 } 11698 } 11699 } 11700 } 11701 11702 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 11703 CXXMethodDecl *MoveAssignOperator) { 11704 assert((MoveAssignOperator->isDefaulted() && 11705 MoveAssignOperator->isOverloadedOperator() && 11706 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 11707 !MoveAssignOperator->doesThisDeclarationHaveABody() && 11708 !MoveAssignOperator->isDeleted()) && 11709 "DefineImplicitMoveAssignment called for wrong function"); 11710 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 11711 return; 11712 11713 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 11714 if (ClassDecl->isInvalidDecl()) { 11715 MoveAssignOperator->setInvalidDecl(); 11716 return; 11717 } 11718 11719 // C++0x [class.copy]p28: 11720 // The implicitly-defined or move assignment operator for a non-union class 11721 // X performs memberwise move assignment of its subobjects. The direct base 11722 // classes of X are assigned first, in the order of their declaration in the 11723 // base-specifier-list, and then the immediate non-static data members of X 11724 // are assigned, in the order in which they were declared in the class 11725 // definition. 11726 11727 // Issue a warning if our implicit move assignment operator will move 11728 // from a virtual base more than once. 11729 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 11730 11731 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 11732 11733 // The exception specification is needed because we are defining the 11734 // function. 11735 ResolveExceptionSpec(CurrentLocation, 11736 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 11737 11738 // Add a context note for diagnostics produced after this point. 11739 Scope.addContextNote(CurrentLocation); 11740 11741 // The statements that form the synthesized function body. 11742 SmallVector<Stmt*, 8> Statements; 11743 11744 // The parameter for the "other" object, which we are move from. 11745 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 11746 QualType OtherRefType = Other->getType()-> 11747 getAs<RValueReferenceType>()->getPointeeType(); 11748 assert(!OtherRefType.getQualifiers() && 11749 "Bad argument type of defaulted move assignment"); 11750 11751 // Our location for everything implicitly-generated. 11752 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 11753 ? MoveAssignOperator->getLocEnd() 11754 : MoveAssignOperator->getLocation(); 11755 11756 // Builds a reference to the "other" object. 11757 RefBuilder OtherRef(Other, OtherRefType); 11758 // Cast to rvalue. 11759 MoveCastBuilder MoveOther(OtherRef); 11760 11761 // Builds the "this" pointer. 11762 ThisBuilder This; 11763 11764 // Assign base classes. 11765 bool Invalid = false; 11766 for (auto &Base : ClassDecl->bases()) { 11767 // C++11 [class.copy]p28: 11768 // It is unspecified whether subobjects representing virtual base classes 11769 // are assigned more than once by the implicitly-defined copy assignment 11770 // operator. 11771 // FIXME: Do not assign to a vbase that will be assigned by some other base 11772 // class. For a move-assignment, this can result in the vbase being moved 11773 // multiple times. 11774 11775 // Form the assignment: 11776 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 11777 QualType BaseType = Base.getType().getUnqualifiedType(); 11778 if (!BaseType->isRecordType()) { 11779 Invalid = true; 11780 continue; 11781 } 11782 11783 CXXCastPath BasePath; 11784 BasePath.push_back(&Base); 11785 11786 // Construct the "from" expression, which is an implicit cast to the 11787 // appropriately-qualified base type. 11788 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 11789 11790 // Dereference "this". 11791 DerefBuilder DerefThis(This); 11792 11793 // Implicitly cast "this" to the appropriately-qualified base type. 11794 CastBuilder To(DerefThis, 11795 Context.getCVRQualifiedType( 11796 BaseType, MoveAssignOperator->getTypeQualifiers()), 11797 VK_LValue, BasePath); 11798 11799 // Build the move. 11800 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 11801 To, From, 11802 /*CopyingBaseSubobject=*/true, 11803 /*Copying=*/false); 11804 if (Move.isInvalid()) { 11805 MoveAssignOperator->setInvalidDecl(); 11806 return; 11807 } 11808 11809 // Success! Record the move. 11810 Statements.push_back(Move.getAs<Expr>()); 11811 } 11812 11813 // Assign non-static members. 11814 for (auto *Field : ClassDecl->fields()) { 11815 // FIXME: We should form some kind of AST representation for the implied 11816 // memcpy in a union copy operation. 11817 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11818 continue; 11819 11820 if (Field->isInvalidDecl()) { 11821 Invalid = true; 11822 continue; 11823 } 11824 11825 // Check for members of reference type; we can't move those. 11826 if (Field->getType()->isReferenceType()) { 11827 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11828 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11829 Diag(Field->getLocation(), diag::note_declared_at); 11830 Invalid = true; 11831 continue; 11832 } 11833 11834 // Check for members of const-qualified, non-class type. 11835 QualType BaseType = Context.getBaseElementType(Field->getType()); 11836 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11837 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11838 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11839 Diag(Field->getLocation(), diag::note_declared_at); 11840 Invalid = true; 11841 continue; 11842 } 11843 11844 // Suppress assigning zero-width bitfields. 11845 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11846 continue; 11847 11848 QualType FieldType = Field->getType().getNonReferenceType(); 11849 if (FieldType->isIncompleteArrayType()) { 11850 assert(ClassDecl->hasFlexibleArrayMember() && 11851 "Incomplete array type is not valid"); 11852 continue; 11853 } 11854 11855 // Build references to the field in the object we're copying from and to. 11856 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11857 LookupMemberName); 11858 MemberLookup.addDecl(Field); 11859 MemberLookup.resolveKind(); 11860 MemberBuilder From(MoveOther, OtherRefType, 11861 /*IsArrow=*/false, MemberLookup); 11862 MemberBuilder To(This, getCurrentThisType(), 11863 /*IsArrow=*/true, MemberLookup); 11864 11865 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 11866 "Member reference with rvalue base must be rvalue except for reference " 11867 "members, which aren't allowed for move assignment."); 11868 11869 // Build the move of this field. 11870 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 11871 To, From, 11872 /*CopyingBaseSubobject=*/false, 11873 /*Copying=*/false); 11874 if (Move.isInvalid()) { 11875 MoveAssignOperator->setInvalidDecl(); 11876 return; 11877 } 11878 11879 // Success! Record the copy. 11880 Statements.push_back(Move.getAs<Stmt>()); 11881 } 11882 11883 if (!Invalid) { 11884 // Add a "return *this;" 11885 ExprResult ThisObj = 11886 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11887 11888 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11889 if (Return.isInvalid()) 11890 Invalid = true; 11891 else 11892 Statements.push_back(Return.getAs<Stmt>()); 11893 } 11894 11895 if (Invalid) { 11896 MoveAssignOperator->setInvalidDecl(); 11897 return; 11898 } 11899 11900 StmtResult Body; 11901 { 11902 CompoundScopeRAII CompoundScope(*this); 11903 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11904 /*isStmtExpr=*/false); 11905 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11906 } 11907 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 11908 MoveAssignOperator->markUsed(Context); 11909 11910 if (ASTMutationListener *L = getASTMutationListener()) { 11911 L->CompletedImplicitDefinition(MoveAssignOperator); 11912 } 11913 } 11914 11915 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 11916 CXXRecordDecl *ClassDecl) { 11917 // C++ [class.copy]p4: 11918 // If the class definition does not explicitly declare a copy 11919 // constructor, one is declared implicitly. 11920 assert(ClassDecl->needsImplicitCopyConstructor()); 11921 11922 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 11923 if (DSM.isAlreadyBeingDeclared()) 11924 return nullptr; 11925 11926 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11927 QualType ArgType = ClassType; 11928 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 11929 if (Const) 11930 ArgType = ArgType.withConst(); 11931 ArgType = Context.getLValueReferenceType(ArgType); 11932 11933 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11934 CXXCopyConstructor, 11935 Const); 11936 11937 DeclarationName Name 11938 = Context.DeclarationNames.getCXXConstructorName( 11939 Context.getCanonicalType(ClassType)); 11940 SourceLocation ClassLoc = ClassDecl->getLocation(); 11941 DeclarationNameInfo NameInfo(Name, ClassLoc); 11942 11943 // An implicitly-declared copy constructor is an inline public 11944 // member of its class. 11945 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 11946 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 11947 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11948 Constexpr); 11949 CopyConstructor->setAccess(AS_public); 11950 CopyConstructor->setDefaulted(); 11951 11952 if (getLangOpts().CUDA) { 11953 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 11954 CopyConstructor, 11955 /* ConstRHS */ Const, 11956 /* Diagnose */ false); 11957 } 11958 11959 // Build an exception specification pointing back at this member. 11960 FunctionProtoType::ExtProtoInfo EPI = 11961 getImplicitMethodEPI(*this, CopyConstructor); 11962 CopyConstructor->setType( 11963 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 11964 11965 // Add the parameter to the constructor. 11966 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 11967 ClassLoc, ClassLoc, 11968 /*IdentifierInfo=*/nullptr, 11969 ArgType, /*TInfo=*/nullptr, 11970 SC_None, nullptr); 11971 CopyConstructor->setParams(FromParam); 11972 11973 CopyConstructor->setTrivial( 11974 ClassDecl->needsOverloadResolutionForCopyConstructor() 11975 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 11976 : ClassDecl->hasTrivialCopyConstructor()); 11977 11978 // Note that we have declared this constructor. 11979 ++ASTContext::NumImplicitCopyConstructorsDeclared; 11980 11981 Scope *S = getScopeForContext(ClassDecl); 11982 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 11983 11984 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 11985 ClassDecl->setImplicitCopyConstructorIsDeleted(); 11986 SetDeclDeleted(CopyConstructor, ClassLoc); 11987 } 11988 11989 if (S) 11990 PushOnScopeChains(CopyConstructor, S, false); 11991 ClassDecl->addDecl(CopyConstructor); 11992 11993 return CopyConstructor; 11994 } 11995 11996 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 11997 CXXConstructorDecl *CopyConstructor) { 11998 assert((CopyConstructor->isDefaulted() && 11999 CopyConstructor->isCopyConstructor() && 12000 !CopyConstructor->doesThisDeclarationHaveABody() && 12001 !CopyConstructor->isDeleted()) && 12002 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12003 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12004 return; 12005 12006 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12007 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12008 12009 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12010 12011 // The exception specification is needed because we are defining the 12012 // function. 12013 ResolveExceptionSpec(CurrentLocation, 12014 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12015 MarkVTableUsed(CurrentLocation, ClassDecl); 12016 12017 // Add a context note for diagnostics produced after this point. 12018 Scope.addContextNote(CurrentLocation); 12019 12020 // C++11 [class.copy]p7: 12021 // The [definition of an implicitly declared copy constructor] is 12022 // deprecated if the class has a user-declared copy assignment operator 12023 // or a user-declared destructor. 12024 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12025 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12026 12027 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12028 CopyConstructor->setInvalidDecl(); 12029 } else { 12030 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 12031 ? CopyConstructor->getLocEnd() 12032 : CopyConstructor->getLocation(); 12033 Sema::CompoundScopeRAII CompoundScope(*this); 12034 CopyConstructor->setBody( 12035 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12036 CopyConstructor->markUsed(Context); 12037 } 12038 12039 if (ASTMutationListener *L = getASTMutationListener()) { 12040 L->CompletedImplicitDefinition(CopyConstructor); 12041 } 12042 } 12043 12044 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12045 CXXRecordDecl *ClassDecl) { 12046 assert(ClassDecl->needsImplicitMoveConstructor()); 12047 12048 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12049 if (DSM.isAlreadyBeingDeclared()) 12050 return nullptr; 12051 12052 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12053 QualType ArgType = Context.getRValueReferenceType(ClassType); 12054 12055 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12056 CXXMoveConstructor, 12057 false); 12058 12059 DeclarationName Name 12060 = Context.DeclarationNames.getCXXConstructorName( 12061 Context.getCanonicalType(ClassType)); 12062 SourceLocation ClassLoc = ClassDecl->getLocation(); 12063 DeclarationNameInfo NameInfo(Name, ClassLoc); 12064 12065 // C++11 [class.copy]p11: 12066 // An implicitly-declared copy/move constructor is an inline public 12067 // member of its class. 12068 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12069 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12070 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12071 Constexpr); 12072 MoveConstructor->setAccess(AS_public); 12073 MoveConstructor->setDefaulted(); 12074 12075 if (getLangOpts().CUDA) { 12076 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12077 MoveConstructor, 12078 /* ConstRHS */ false, 12079 /* Diagnose */ false); 12080 } 12081 12082 // Build an exception specification pointing back at this member. 12083 FunctionProtoType::ExtProtoInfo EPI = 12084 getImplicitMethodEPI(*this, MoveConstructor); 12085 MoveConstructor->setType( 12086 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12087 12088 // Add the parameter to the constructor. 12089 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12090 ClassLoc, ClassLoc, 12091 /*IdentifierInfo=*/nullptr, 12092 ArgType, /*TInfo=*/nullptr, 12093 SC_None, nullptr); 12094 MoveConstructor->setParams(FromParam); 12095 12096 MoveConstructor->setTrivial( 12097 ClassDecl->needsOverloadResolutionForMoveConstructor() 12098 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12099 : ClassDecl->hasTrivialMoveConstructor()); 12100 12101 // Note that we have declared this constructor. 12102 ++ASTContext::NumImplicitMoveConstructorsDeclared; 12103 12104 Scope *S = getScopeForContext(ClassDecl); 12105 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12106 12107 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12108 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12109 SetDeclDeleted(MoveConstructor, ClassLoc); 12110 } 12111 12112 if (S) 12113 PushOnScopeChains(MoveConstructor, S, false); 12114 ClassDecl->addDecl(MoveConstructor); 12115 12116 return MoveConstructor; 12117 } 12118 12119 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12120 CXXConstructorDecl *MoveConstructor) { 12121 assert((MoveConstructor->isDefaulted() && 12122 MoveConstructor->isMoveConstructor() && 12123 !MoveConstructor->doesThisDeclarationHaveABody() && 12124 !MoveConstructor->isDeleted()) && 12125 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12126 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12127 return; 12128 12129 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12130 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12131 12132 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12133 12134 // The exception specification is needed because we are defining the 12135 // function. 12136 ResolveExceptionSpec(CurrentLocation, 12137 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12138 MarkVTableUsed(CurrentLocation, ClassDecl); 12139 12140 // Add a context note for diagnostics produced after this point. 12141 Scope.addContextNote(CurrentLocation); 12142 12143 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12144 MoveConstructor->setInvalidDecl(); 12145 } else { 12146 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 12147 ? MoveConstructor->getLocEnd() 12148 : MoveConstructor->getLocation(); 12149 Sema::CompoundScopeRAII CompoundScope(*this); 12150 MoveConstructor->setBody(ActOnCompoundStmt( 12151 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12152 MoveConstructor->markUsed(Context); 12153 } 12154 12155 if (ASTMutationListener *L = getASTMutationListener()) { 12156 L->CompletedImplicitDefinition(MoveConstructor); 12157 } 12158 } 12159 12160 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12161 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12162 } 12163 12164 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12165 SourceLocation CurrentLocation, 12166 CXXConversionDecl *Conv) { 12167 SynthesizedFunctionScope Scope(*this, Conv); 12168 12169 CXXRecordDecl *Lambda = Conv->getParent(); 12170 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 12171 // If we are defining a specialization of a conversion to function-ptr 12172 // cache the deduced template arguments for this specialization 12173 // so that we can use them to retrieve the corresponding call-operator 12174 // and static-invoker. 12175 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 12176 12177 // Retrieve the corresponding call-operator specialization. 12178 if (Lambda->isGenericLambda()) { 12179 assert(Conv->isFunctionTemplateSpecialization()); 12180 FunctionTemplateDecl *CallOpTemplate = 12181 CallOp->getDescribedFunctionTemplate(); 12182 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 12183 void *InsertPos = nullptr; 12184 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 12185 DeducedTemplateArgs->asArray(), 12186 InsertPos); 12187 assert(CallOpSpec && 12188 "Conversion operator must have a corresponding call operator"); 12189 CallOp = cast<CXXMethodDecl>(CallOpSpec); 12190 } 12191 12192 // Mark the call operator referenced (and add to pending instantiations 12193 // if necessary). 12194 // For both the conversion and static-invoker template specializations 12195 // we construct their body's in this function, so no need to add them 12196 // to the PendingInstantiations. 12197 MarkFunctionReferenced(CurrentLocation, CallOp); 12198 12199 // Retrieve the static invoker... 12200 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12201 // ... and get the corresponding specialization for a generic lambda. 12202 if (Lambda->isGenericLambda()) { 12203 assert(DeducedTemplateArgs && 12204 "Must have deduced template arguments from Conversion Operator"); 12205 FunctionTemplateDecl *InvokeTemplate = 12206 Invoker->getDescribedFunctionTemplate(); 12207 void *InsertPos = nullptr; 12208 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 12209 DeducedTemplateArgs->asArray(), 12210 InsertPos); 12211 assert(InvokeSpec && 12212 "Must have a corresponding static invoker specialization"); 12213 Invoker = cast<CXXMethodDecl>(InvokeSpec); 12214 } 12215 // Construct the body of the conversion function { return __invoke; }. 12216 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12217 VK_LValue, Conv->getLocation()).get(); 12218 assert(FunctionRef && "Can't refer to __invoke function?"); 12219 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12220 Conv->setBody(new (Context) CompoundStmt(Context, Return, 12221 Conv->getLocation(), 12222 Conv->getLocation())); 12223 12224 Conv->markUsed(Context); 12225 Conv->setReferenced(); 12226 12227 // Fill in the __invoke function with a dummy implementation. IR generation 12228 // will fill in the actual details. 12229 Invoker->markUsed(Context); 12230 Invoker->setReferenced(); 12231 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12232 12233 if (ASTMutationListener *L = getASTMutationListener()) { 12234 L->CompletedImplicitDefinition(Conv); 12235 L->CompletedImplicitDefinition(Invoker); 12236 } 12237 } 12238 12239 12240 12241 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12242 SourceLocation CurrentLocation, 12243 CXXConversionDecl *Conv) 12244 { 12245 assert(!Conv->getParent()->isGenericLambda()); 12246 12247 SynthesizedFunctionScope Scope(*this, Conv); 12248 12249 // Copy-initialize the lambda object as needed to capture it. 12250 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12251 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12252 12253 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12254 Conv->getLocation(), 12255 Conv, DerefThis); 12256 12257 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12258 // behavior. Note that only the general conversion function does this 12259 // (since it's unusable otherwise); in the case where we inline the 12260 // block literal, it has block literal lifetime semantics. 12261 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12262 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12263 CK_CopyAndAutoreleaseBlockObject, 12264 BuildBlock.get(), nullptr, VK_RValue); 12265 12266 if (BuildBlock.isInvalid()) { 12267 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12268 Conv->setInvalidDecl(); 12269 return; 12270 } 12271 12272 // Create the return statement that returns the block from the conversion 12273 // function. 12274 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12275 if (Return.isInvalid()) { 12276 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12277 Conv->setInvalidDecl(); 12278 return; 12279 } 12280 12281 // Set the body of the conversion function. 12282 Stmt *ReturnS = Return.get(); 12283 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 12284 Conv->getLocation(), 12285 Conv->getLocation())); 12286 Conv->markUsed(Context); 12287 12288 // We're done; notify the mutation listener, if any. 12289 if (ASTMutationListener *L = getASTMutationListener()) { 12290 L->CompletedImplicitDefinition(Conv); 12291 } 12292 } 12293 12294 /// \brief Determine whether the given list arguments contains exactly one 12295 /// "real" (non-default) argument. 12296 static bool hasOneRealArgument(MultiExprArg Args) { 12297 switch (Args.size()) { 12298 case 0: 12299 return false; 12300 12301 default: 12302 if (!Args[1]->isDefaultArgument()) 12303 return false; 12304 12305 // fall through 12306 case 1: 12307 return !Args[0]->isDefaultArgument(); 12308 } 12309 12310 return false; 12311 } 12312 12313 ExprResult 12314 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12315 NamedDecl *FoundDecl, 12316 CXXConstructorDecl *Constructor, 12317 MultiExprArg ExprArgs, 12318 bool HadMultipleCandidates, 12319 bool IsListInitialization, 12320 bool IsStdInitListInitialization, 12321 bool RequiresZeroInit, 12322 unsigned ConstructKind, 12323 SourceRange ParenRange) { 12324 bool Elidable = false; 12325 12326 // C++0x [class.copy]p34: 12327 // When certain criteria are met, an implementation is allowed to 12328 // omit the copy/move construction of a class object, even if the 12329 // copy/move constructor and/or destructor for the object have 12330 // side effects. [...] 12331 // - when a temporary class object that has not been bound to a 12332 // reference (12.2) would be copied/moved to a class object 12333 // with the same cv-unqualified type, the copy/move operation 12334 // can be omitted by constructing the temporary object 12335 // directly into the target of the omitted copy/move 12336 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12337 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12338 Expr *SubExpr = ExprArgs[0]; 12339 Elidable = SubExpr->isTemporaryObject( 12340 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12341 } 12342 12343 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12344 FoundDecl, Constructor, 12345 Elidable, ExprArgs, HadMultipleCandidates, 12346 IsListInitialization, 12347 IsStdInitListInitialization, RequiresZeroInit, 12348 ConstructKind, ParenRange); 12349 } 12350 12351 ExprResult 12352 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12353 NamedDecl *FoundDecl, 12354 CXXConstructorDecl *Constructor, 12355 bool Elidable, 12356 MultiExprArg ExprArgs, 12357 bool HadMultipleCandidates, 12358 bool IsListInitialization, 12359 bool IsStdInitListInitialization, 12360 bool RequiresZeroInit, 12361 unsigned ConstructKind, 12362 SourceRange ParenRange) { 12363 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12364 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12365 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12366 return ExprError(); 12367 } 12368 12369 return BuildCXXConstructExpr( 12370 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12371 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12372 RequiresZeroInit, ConstructKind, ParenRange); 12373 } 12374 12375 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12376 /// including handling of its default argument expressions. 12377 ExprResult 12378 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12379 CXXConstructorDecl *Constructor, 12380 bool Elidable, 12381 MultiExprArg ExprArgs, 12382 bool HadMultipleCandidates, 12383 bool IsListInitialization, 12384 bool IsStdInitListInitialization, 12385 bool RequiresZeroInit, 12386 unsigned ConstructKind, 12387 SourceRange ParenRange) { 12388 assert(declaresSameEntity( 12389 Constructor->getParent(), 12390 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 12391 "given constructor for wrong type"); 12392 MarkFunctionReferenced(ConstructLoc, Constructor); 12393 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 12394 return ExprError(); 12395 12396 return CXXConstructExpr::Create( 12397 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 12398 ExprArgs, HadMultipleCandidates, IsListInitialization, 12399 IsStdInitListInitialization, RequiresZeroInit, 12400 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 12401 ParenRange); 12402 } 12403 12404 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 12405 assert(Field->hasInClassInitializer()); 12406 12407 // If we already have the in-class initializer nothing needs to be done. 12408 if (Field->getInClassInitializer()) 12409 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12410 12411 // If we might have already tried and failed to instantiate, don't try again. 12412 if (Field->isInvalidDecl()) 12413 return ExprError(); 12414 12415 // Maybe we haven't instantiated the in-class initializer. Go check the 12416 // pattern FieldDecl to see if it has one. 12417 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 12418 12419 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 12420 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 12421 DeclContext::lookup_result Lookup = 12422 ClassPattern->lookup(Field->getDeclName()); 12423 12424 // Lookup can return at most two results: the pattern for the field, or the 12425 // injected class name of the parent record. No other member can have the 12426 // same name as the field. 12427 // In modules mode, lookup can return multiple results (coming from 12428 // different modules). 12429 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 12430 "more than two lookup results for field name"); 12431 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 12432 if (!Pattern) { 12433 assert(isa<CXXRecordDecl>(Lookup[0]) && 12434 "cannot have other non-field member with same name"); 12435 for (auto L : Lookup) 12436 if (isa<FieldDecl>(L)) { 12437 Pattern = cast<FieldDecl>(L); 12438 break; 12439 } 12440 assert(Pattern && "We must have set the Pattern!"); 12441 } 12442 12443 if (!Pattern->hasInClassInitializer() || 12444 InstantiateInClassInitializer(Loc, Field, Pattern, 12445 getTemplateInstantiationArgs(Field))) { 12446 // Don't diagnose this again. 12447 Field->setInvalidDecl(); 12448 return ExprError(); 12449 } 12450 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12451 } 12452 12453 // DR1351: 12454 // If the brace-or-equal-initializer of a non-static data member 12455 // invokes a defaulted default constructor of its class or of an 12456 // enclosing class in a potentially evaluated subexpression, the 12457 // program is ill-formed. 12458 // 12459 // This resolution is unworkable: the exception specification of the 12460 // default constructor can be needed in an unevaluated context, in 12461 // particular, in the operand of a noexcept-expression, and we can be 12462 // unable to compute an exception specification for an enclosed class. 12463 // 12464 // Any attempt to resolve the exception specification of a defaulted default 12465 // constructor before the initializer is lexically complete will ultimately 12466 // come here at which point we can diagnose it. 12467 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 12468 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 12469 << OutermostClass << Field; 12470 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed); 12471 // Recover by marking the field invalid, unless we're in a SFINAE context. 12472 if (!isSFINAEContext()) 12473 Field->setInvalidDecl(); 12474 return ExprError(); 12475 } 12476 12477 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 12478 if (VD->isInvalidDecl()) return; 12479 12480 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 12481 if (ClassDecl->isInvalidDecl()) return; 12482 if (ClassDecl->hasIrrelevantDestructor()) return; 12483 if (ClassDecl->isDependentContext()) return; 12484 12485 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12486 MarkFunctionReferenced(VD->getLocation(), Destructor); 12487 CheckDestructorAccess(VD->getLocation(), Destructor, 12488 PDiag(diag::err_access_dtor_var) 12489 << VD->getDeclName() 12490 << VD->getType()); 12491 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 12492 12493 if (Destructor->isTrivial()) return; 12494 if (!VD->hasGlobalStorage()) return; 12495 12496 // Emit warning for non-trivial dtor in global scope (a real global, 12497 // class-static, function-static). 12498 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 12499 12500 // TODO: this should be re-enabled for static locals by !CXAAtExit 12501 if (!VD->isStaticLocal()) 12502 Diag(VD->getLocation(), diag::warn_global_destructor); 12503 } 12504 12505 /// \brief Given a constructor and the set of arguments provided for the 12506 /// constructor, convert the arguments and add any required default arguments 12507 /// to form a proper call to this constructor. 12508 /// 12509 /// \returns true if an error occurred, false otherwise. 12510 bool 12511 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 12512 MultiExprArg ArgsPtr, 12513 SourceLocation Loc, 12514 SmallVectorImpl<Expr*> &ConvertedArgs, 12515 bool AllowExplicit, 12516 bool IsListInitialization) { 12517 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 12518 unsigned NumArgs = ArgsPtr.size(); 12519 Expr **Args = ArgsPtr.data(); 12520 12521 const FunctionProtoType *Proto 12522 = Constructor->getType()->getAs<FunctionProtoType>(); 12523 assert(Proto && "Constructor without a prototype?"); 12524 unsigned NumParams = Proto->getNumParams(); 12525 12526 // If too few arguments are available, we'll fill in the rest with defaults. 12527 if (NumArgs < NumParams) 12528 ConvertedArgs.reserve(NumParams); 12529 else 12530 ConvertedArgs.reserve(NumArgs); 12531 12532 VariadicCallType CallType = 12533 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 12534 SmallVector<Expr *, 8> AllArgs; 12535 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 12536 Proto, 0, 12537 llvm::makeArrayRef(Args, NumArgs), 12538 AllArgs, 12539 CallType, AllowExplicit, 12540 IsListInitialization); 12541 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 12542 12543 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 12544 12545 CheckConstructorCall(Constructor, 12546 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 12547 Proto, Loc); 12548 12549 return Invalid; 12550 } 12551 12552 static inline bool 12553 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 12554 const FunctionDecl *FnDecl) { 12555 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 12556 if (isa<NamespaceDecl>(DC)) { 12557 return SemaRef.Diag(FnDecl->getLocation(), 12558 diag::err_operator_new_delete_declared_in_namespace) 12559 << FnDecl->getDeclName(); 12560 } 12561 12562 if (isa<TranslationUnitDecl>(DC) && 12563 FnDecl->getStorageClass() == SC_Static) { 12564 return SemaRef.Diag(FnDecl->getLocation(), 12565 diag::err_operator_new_delete_declared_static) 12566 << FnDecl->getDeclName(); 12567 } 12568 12569 return false; 12570 } 12571 12572 static inline bool 12573 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 12574 CanQualType ExpectedResultType, 12575 CanQualType ExpectedFirstParamType, 12576 unsigned DependentParamTypeDiag, 12577 unsigned InvalidParamTypeDiag) { 12578 QualType ResultType = 12579 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 12580 12581 // Check that the result type is not dependent. 12582 if (ResultType->isDependentType()) 12583 return SemaRef.Diag(FnDecl->getLocation(), 12584 diag::err_operator_new_delete_dependent_result_type) 12585 << FnDecl->getDeclName() << ExpectedResultType; 12586 12587 // Check that the result type is what we expect. 12588 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 12589 return SemaRef.Diag(FnDecl->getLocation(), 12590 diag::err_operator_new_delete_invalid_result_type) 12591 << FnDecl->getDeclName() << ExpectedResultType; 12592 12593 // A function template must have at least 2 parameters. 12594 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 12595 return SemaRef.Diag(FnDecl->getLocation(), 12596 diag::err_operator_new_delete_template_too_few_parameters) 12597 << FnDecl->getDeclName(); 12598 12599 // The function decl must have at least 1 parameter. 12600 if (FnDecl->getNumParams() == 0) 12601 return SemaRef.Diag(FnDecl->getLocation(), 12602 diag::err_operator_new_delete_too_few_parameters) 12603 << FnDecl->getDeclName(); 12604 12605 // Check the first parameter type is not dependent. 12606 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 12607 if (FirstParamType->isDependentType()) 12608 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 12609 << FnDecl->getDeclName() << ExpectedFirstParamType; 12610 12611 // Check that the first parameter type is what we expect. 12612 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 12613 ExpectedFirstParamType) 12614 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 12615 << FnDecl->getDeclName() << ExpectedFirstParamType; 12616 12617 return false; 12618 } 12619 12620 static bool 12621 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 12622 // C++ [basic.stc.dynamic.allocation]p1: 12623 // A program is ill-formed if an allocation function is declared in a 12624 // namespace scope other than global scope or declared static in global 12625 // scope. 12626 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12627 return true; 12628 12629 CanQualType SizeTy = 12630 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 12631 12632 // C++ [basic.stc.dynamic.allocation]p1: 12633 // The return type shall be void*. The first parameter shall have type 12634 // std::size_t. 12635 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 12636 SizeTy, 12637 diag::err_operator_new_dependent_param_type, 12638 diag::err_operator_new_param_type)) 12639 return true; 12640 12641 // C++ [basic.stc.dynamic.allocation]p1: 12642 // The first parameter shall not have an associated default argument. 12643 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 12644 return SemaRef.Diag(FnDecl->getLocation(), 12645 diag::err_operator_new_default_arg) 12646 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 12647 12648 return false; 12649 } 12650 12651 static bool 12652 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 12653 // C++ [basic.stc.dynamic.deallocation]p1: 12654 // A program is ill-formed if deallocation functions are declared in a 12655 // namespace scope other than global scope or declared static in global 12656 // scope. 12657 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12658 return true; 12659 12660 // C++ [basic.stc.dynamic.deallocation]p2: 12661 // Each deallocation function shall return void and its first parameter 12662 // shall be void*. 12663 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 12664 SemaRef.Context.VoidPtrTy, 12665 diag::err_operator_delete_dependent_param_type, 12666 diag::err_operator_delete_param_type)) 12667 return true; 12668 12669 return false; 12670 } 12671 12672 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 12673 /// of this overloaded operator is well-formed. If so, returns false; 12674 /// otherwise, emits appropriate diagnostics and returns true. 12675 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 12676 assert(FnDecl && FnDecl->isOverloadedOperator() && 12677 "Expected an overloaded operator declaration"); 12678 12679 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 12680 12681 // C++ [over.oper]p5: 12682 // The allocation and deallocation functions, operator new, 12683 // operator new[], operator delete and operator delete[], are 12684 // described completely in 3.7.3. The attributes and restrictions 12685 // found in the rest of this subclause do not apply to them unless 12686 // explicitly stated in 3.7.3. 12687 if (Op == OO_Delete || Op == OO_Array_Delete) 12688 return CheckOperatorDeleteDeclaration(*this, FnDecl); 12689 12690 if (Op == OO_New || Op == OO_Array_New) 12691 return CheckOperatorNewDeclaration(*this, FnDecl); 12692 12693 // C++ [over.oper]p6: 12694 // An operator function shall either be a non-static member 12695 // function or be a non-member function and have at least one 12696 // parameter whose type is a class, a reference to a class, an 12697 // enumeration, or a reference to an enumeration. 12698 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 12699 if (MethodDecl->isStatic()) 12700 return Diag(FnDecl->getLocation(), 12701 diag::err_operator_overload_static) << FnDecl->getDeclName(); 12702 } else { 12703 bool ClassOrEnumParam = false; 12704 for (auto Param : FnDecl->parameters()) { 12705 QualType ParamType = Param->getType().getNonReferenceType(); 12706 if (ParamType->isDependentType() || ParamType->isRecordType() || 12707 ParamType->isEnumeralType()) { 12708 ClassOrEnumParam = true; 12709 break; 12710 } 12711 } 12712 12713 if (!ClassOrEnumParam) 12714 return Diag(FnDecl->getLocation(), 12715 diag::err_operator_overload_needs_class_or_enum) 12716 << FnDecl->getDeclName(); 12717 } 12718 12719 // C++ [over.oper]p8: 12720 // An operator function cannot have default arguments (8.3.6), 12721 // except where explicitly stated below. 12722 // 12723 // Only the function-call operator allows default arguments 12724 // (C++ [over.call]p1). 12725 if (Op != OO_Call) { 12726 for (auto Param : FnDecl->parameters()) { 12727 if (Param->hasDefaultArg()) 12728 return Diag(Param->getLocation(), 12729 diag::err_operator_overload_default_arg) 12730 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 12731 } 12732 } 12733 12734 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 12735 { false, false, false } 12736 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 12737 , { Unary, Binary, MemberOnly } 12738 #include "clang/Basic/OperatorKinds.def" 12739 }; 12740 12741 bool CanBeUnaryOperator = OperatorUses[Op][0]; 12742 bool CanBeBinaryOperator = OperatorUses[Op][1]; 12743 bool MustBeMemberOperator = OperatorUses[Op][2]; 12744 12745 // C++ [over.oper]p8: 12746 // [...] Operator functions cannot have more or fewer parameters 12747 // than the number required for the corresponding operator, as 12748 // described in the rest of this subclause. 12749 unsigned NumParams = FnDecl->getNumParams() 12750 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 12751 if (Op != OO_Call && 12752 ((NumParams == 1 && !CanBeUnaryOperator) || 12753 (NumParams == 2 && !CanBeBinaryOperator) || 12754 (NumParams < 1) || (NumParams > 2))) { 12755 // We have the wrong number of parameters. 12756 unsigned ErrorKind; 12757 if (CanBeUnaryOperator && CanBeBinaryOperator) { 12758 ErrorKind = 2; // 2 -> unary or binary. 12759 } else if (CanBeUnaryOperator) { 12760 ErrorKind = 0; // 0 -> unary 12761 } else { 12762 assert(CanBeBinaryOperator && 12763 "All non-call overloaded operators are unary or binary!"); 12764 ErrorKind = 1; // 1 -> binary 12765 } 12766 12767 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 12768 << FnDecl->getDeclName() << NumParams << ErrorKind; 12769 } 12770 12771 // Overloaded operators other than operator() cannot be variadic. 12772 if (Op != OO_Call && 12773 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 12774 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 12775 << FnDecl->getDeclName(); 12776 } 12777 12778 // Some operators must be non-static member functions. 12779 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 12780 return Diag(FnDecl->getLocation(), 12781 diag::err_operator_overload_must_be_member) 12782 << FnDecl->getDeclName(); 12783 } 12784 12785 // C++ [over.inc]p1: 12786 // The user-defined function called operator++ implements the 12787 // prefix and postfix ++ operator. If this function is a member 12788 // function with no parameters, or a non-member function with one 12789 // parameter of class or enumeration type, it defines the prefix 12790 // increment operator ++ for objects of that type. If the function 12791 // is a member function with one parameter (which shall be of type 12792 // int) or a non-member function with two parameters (the second 12793 // of which shall be of type int), it defines the postfix 12794 // increment operator ++ for objects of that type. 12795 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 12796 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 12797 QualType ParamType = LastParam->getType(); 12798 12799 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 12800 !ParamType->isDependentType()) 12801 return Diag(LastParam->getLocation(), 12802 diag::err_operator_overload_post_incdec_must_be_int) 12803 << LastParam->getType() << (Op == OO_MinusMinus); 12804 } 12805 12806 return false; 12807 } 12808 12809 static bool 12810 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 12811 FunctionTemplateDecl *TpDecl) { 12812 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 12813 12814 // Must have one or two template parameters. 12815 if (TemplateParams->size() == 1) { 12816 NonTypeTemplateParmDecl *PmDecl = 12817 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 12818 12819 // The template parameter must be a char parameter pack. 12820 if (PmDecl && PmDecl->isTemplateParameterPack() && 12821 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 12822 return false; 12823 12824 } else if (TemplateParams->size() == 2) { 12825 TemplateTypeParmDecl *PmType = 12826 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 12827 NonTypeTemplateParmDecl *PmArgs = 12828 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 12829 12830 // The second template parameter must be a parameter pack with the 12831 // first template parameter as its type. 12832 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 12833 PmArgs->isTemplateParameterPack()) { 12834 const TemplateTypeParmType *TArgs = 12835 PmArgs->getType()->getAs<TemplateTypeParmType>(); 12836 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 12837 TArgs->getIndex() == PmType->getIndex()) { 12838 if (!SemaRef.inTemplateInstantiation()) 12839 SemaRef.Diag(TpDecl->getLocation(), 12840 diag::ext_string_literal_operator_template); 12841 return false; 12842 } 12843 } 12844 } 12845 12846 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 12847 diag::err_literal_operator_template) 12848 << TpDecl->getTemplateParameters()->getSourceRange(); 12849 return true; 12850 } 12851 12852 /// CheckLiteralOperatorDeclaration - Check whether the declaration 12853 /// of this literal operator function is well-formed. If so, returns 12854 /// false; otherwise, emits appropriate diagnostics and returns true. 12855 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 12856 if (isa<CXXMethodDecl>(FnDecl)) { 12857 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 12858 << FnDecl->getDeclName(); 12859 return true; 12860 } 12861 12862 if (FnDecl->isExternC()) { 12863 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 12864 if (const LinkageSpecDecl *LSD = 12865 FnDecl->getDeclContext()->getExternCContext()) 12866 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 12867 return true; 12868 } 12869 12870 // This might be the definition of a literal operator template. 12871 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 12872 12873 // This might be a specialization of a literal operator template. 12874 if (!TpDecl) 12875 TpDecl = FnDecl->getPrimaryTemplate(); 12876 12877 // template <char...> type operator "" name() and 12878 // template <class T, T...> type operator "" name() are the only valid 12879 // template signatures, and the only valid signatures with no parameters. 12880 if (TpDecl) { 12881 if (FnDecl->param_size() != 0) { 12882 Diag(FnDecl->getLocation(), 12883 diag::err_literal_operator_template_with_params); 12884 return true; 12885 } 12886 12887 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 12888 return true; 12889 12890 } else if (FnDecl->param_size() == 1) { 12891 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 12892 12893 QualType ParamType = Param->getType().getUnqualifiedType(); 12894 12895 // Only unsigned long long int, long double, any character type, and const 12896 // char * are allowed as the only parameters. 12897 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 12898 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 12899 Context.hasSameType(ParamType, Context.CharTy) || 12900 Context.hasSameType(ParamType, Context.WideCharTy) || 12901 Context.hasSameType(ParamType, Context.Char16Ty) || 12902 Context.hasSameType(ParamType, Context.Char32Ty)) { 12903 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 12904 QualType InnerType = Ptr->getPointeeType(); 12905 12906 // Pointer parameter must be a const char *. 12907 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 12908 Context.CharTy) && 12909 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 12910 Diag(Param->getSourceRange().getBegin(), 12911 diag::err_literal_operator_param) 12912 << ParamType << "'const char *'" << Param->getSourceRange(); 12913 return true; 12914 } 12915 12916 } else if (ParamType->isRealFloatingType()) { 12917 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12918 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 12919 return true; 12920 12921 } else if (ParamType->isIntegerType()) { 12922 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12923 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 12924 return true; 12925 12926 } else { 12927 Diag(Param->getSourceRange().getBegin(), 12928 diag::err_literal_operator_invalid_param) 12929 << ParamType << Param->getSourceRange(); 12930 return true; 12931 } 12932 12933 } else if (FnDecl->param_size() == 2) { 12934 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 12935 12936 // First, verify that the first parameter is correct. 12937 12938 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 12939 12940 // Two parameter function must have a pointer to const as a 12941 // first parameter; let's strip those qualifiers. 12942 const PointerType *PT = FirstParamType->getAs<PointerType>(); 12943 12944 if (!PT) { 12945 Diag((*Param)->getSourceRange().getBegin(), 12946 diag::err_literal_operator_param) 12947 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12948 return true; 12949 } 12950 12951 QualType PointeeType = PT->getPointeeType(); 12952 // First parameter must be const 12953 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 12954 Diag((*Param)->getSourceRange().getBegin(), 12955 diag::err_literal_operator_param) 12956 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12957 return true; 12958 } 12959 12960 QualType InnerType = PointeeType.getUnqualifiedType(); 12961 // Only const char *, const wchar_t*, const char16_t*, and const char32_t* 12962 // are allowed as the first parameter to a two-parameter function 12963 if (!(Context.hasSameType(InnerType, Context.CharTy) || 12964 Context.hasSameType(InnerType, Context.WideCharTy) || 12965 Context.hasSameType(InnerType, Context.Char16Ty) || 12966 Context.hasSameType(InnerType, Context.Char32Ty))) { 12967 Diag((*Param)->getSourceRange().getBegin(), 12968 diag::err_literal_operator_param) 12969 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12970 return true; 12971 } 12972 12973 // Move on to the second and final parameter. 12974 ++Param; 12975 12976 // The second parameter must be a std::size_t. 12977 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 12978 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 12979 Diag((*Param)->getSourceRange().getBegin(), 12980 diag::err_literal_operator_param) 12981 << SecondParamType << Context.getSizeType() 12982 << (*Param)->getSourceRange(); 12983 return true; 12984 } 12985 } else { 12986 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 12987 return true; 12988 } 12989 12990 // Parameters are good. 12991 12992 // A parameter-declaration-clause containing a default argument is not 12993 // equivalent to any of the permitted forms. 12994 for (auto Param : FnDecl->parameters()) { 12995 if (Param->hasDefaultArg()) { 12996 Diag(Param->getDefaultArgRange().getBegin(), 12997 diag::err_literal_operator_default_argument) 12998 << Param->getDefaultArgRange(); 12999 break; 13000 } 13001 } 13002 13003 StringRef LiteralName 13004 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13005 if (LiteralName[0] != '_') { 13006 // C++11 [usrlit.suffix]p1: 13007 // Literal suffix identifiers that do not start with an underscore 13008 // are reserved for future standardization. 13009 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13010 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13011 } 13012 13013 return false; 13014 } 13015 13016 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13017 /// linkage specification, including the language and (if present) 13018 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13019 /// language string literal. LBraceLoc, if valid, provides the location of 13020 /// the '{' brace. Otherwise, this linkage specification does not 13021 /// have any braces. 13022 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13023 Expr *LangStr, 13024 SourceLocation LBraceLoc) { 13025 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13026 if (!Lit->isAscii()) { 13027 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13028 << LangStr->getSourceRange(); 13029 return nullptr; 13030 } 13031 13032 StringRef Lang = Lit->getString(); 13033 LinkageSpecDecl::LanguageIDs Language; 13034 if (Lang == "C") 13035 Language = LinkageSpecDecl::lang_c; 13036 else if (Lang == "C++") 13037 Language = LinkageSpecDecl::lang_cxx; 13038 else { 13039 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13040 << LangStr->getSourceRange(); 13041 return nullptr; 13042 } 13043 13044 // FIXME: Add all the various semantics of linkage specifications 13045 13046 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13047 LangStr->getExprLoc(), Language, 13048 LBraceLoc.isValid()); 13049 CurContext->addDecl(D); 13050 PushDeclContext(S, D); 13051 return D; 13052 } 13053 13054 /// ActOnFinishLinkageSpecification - Complete the definition of 13055 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13056 /// valid, it's the position of the closing '}' brace in a linkage 13057 /// specification that uses braces. 13058 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13059 Decl *LinkageSpec, 13060 SourceLocation RBraceLoc) { 13061 if (RBraceLoc.isValid()) { 13062 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13063 LSDecl->setRBraceLoc(RBraceLoc); 13064 } 13065 PopDeclContext(); 13066 return LinkageSpec; 13067 } 13068 13069 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13070 AttributeList *AttrList, 13071 SourceLocation SemiLoc) { 13072 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13073 // Attribute declarations appertain to empty declaration so we handle 13074 // them here. 13075 if (AttrList) 13076 ProcessDeclAttributeList(S, ED, AttrList); 13077 13078 CurContext->addDecl(ED); 13079 return ED; 13080 } 13081 13082 /// \brief Perform semantic analysis for the variable declaration that 13083 /// occurs within a C++ catch clause, returning the newly-created 13084 /// variable. 13085 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13086 TypeSourceInfo *TInfo, 13087 SourceLocation StartLoc, 13088 SourceLocation Loc, 13089 IdentifierInfo *Name) { 13090 bool Invalid = false; 13091 QualType ExDeclType = TInfo->getType(); 13092 13093 // Arrays and functions decay. 13094 if (ExDeclType->isArrayType()) 13095 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13096 else if (ExDeclType->isFunctionType()) 13097 ExDeclType = Context.getPointerType(ExDeclType); 13098 13099 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13100 // The exception-declaration shall not denote a pointer or reference to an 13101 // incomplete type, other than [cv] void*. 13102 // N2844 forbids rvalue references. 13103 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13104 Diag(Loc, diag::err_catch_rvalue_ref); 13105 Invalid = true; 13106 } 13107 13108 if (ExDeclType->isVariablyModifiedType()) { 13109 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13110 Invalid = true; 13111 } 13112 13113 QualType BaseType = ExDeclType; 13114 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13115 unsigned DK = diag::err_catch_incomplete; 13116 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13117 BaseType = Ptr->getPointeeType(); 13118 Mode = 1; 13119 DK = diag::err_catch_incomplete_ptr; 13120 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13121 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13122 BaseType = Ref->getPointeeType(); 13123 Mode = 2; 13124 DK = diag::err_catch_incomplete_ref; 13125 } 13126 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13127 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13128 Invalid = true; 13129 13130 if (!Invalid && !ExDeclType->isDependentType() && 13131 RequireNonAbstractType(Loc, ExDeclType, 13132 diag::err_abstract_type_in_decl, 13133 AbstractVariableType)) 13134 Invalid = true; 13135 13136 // Only the non-fragile NeXT runtime currently supports C++ catches 13137 // of ObjC types, and no runtime supports catching ObjC types by value. 13138 if (!Invalid && getLangOpts().ObjC1) { 13139 QualType T = ExDeclType; 13140 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13141 T = RT->getPointeeType(); 13142 13143 if (T->isObjCObjectType()) { 13144 Diag(Loc, diag::err_objc_object_catch); 13145 Invalid = true; 13146 } else if (T->isObjCObjectPointerType()) { 13147 // FIXME: should this be a test for macosx-fragile specifically? 13148 if (getLangOpts().ObjCRuntime.isFragile()) 13149 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13150 } 13151 } 13152 13153 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13154 ExDeclType, TInfo, SC_None); 13155 ExDecl->setExceptionVariable(true); 13156 13157 // In ARC, infer 'retaining' for variables of retainable type. 13158 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13159 Invalid = true; 13160 13161 if (!Invalid && !ExDeclType->isDependentType()) { 13162 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13163 // Insulate this from anything else we might currently be parsing. 13164 EnterExpressionEvaluationContext scope( 13165 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 13166 13167 // C++ [except.handle]p16: 13168 // The object declared in an exception-declaration or, if the 13169 // exception-declaration does not specify a name, a temporary (12.2) is 13170 // copy-initialized (8.5) from the exception object. [...] 13171 // The object is destroyed when the handler exits, after the destruction 13172 // of any automatic objects initialized within the handler. 13173 // 13174 // We just pretend to initialize the object with itself, then make sure 13175 // it can be destroyed later. 13176 QualType initType = Context.getExceptionObjectType(ExDeclType); 13177 13178 InitializedEntity entity = 13179 InitializedEntity::InitializeVariable(ExDecl); 13180 InitializationKind initKind = 13181 InitializationKind::CreateCopy(Loc, SourceLocation()); 13182 13183 Expr *opaqueValue = 13184 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13185 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13186 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13187 if (result.isInvalid()) 13188 Invalid = true; 13189 else { 13190 // If the constructor used was non-trivial, set this as the 13191 // "initializer". 13192 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13193 if (!construct->getConstructor()->isTrivial()) { 13194 Expr *init = MaybeCreateExprWithCleanups(construct); 13195 ExDecl->setInit(init); 13196 } 13197 13198 // And make sure it's destructable. 13199 FinalizeVarWithDestructor(ExDecl, recordType); 13200 } 13201 } 13202 } 13203 13204 if (Invalid) 13205 ExDecl->setInvalidDecl(); 13206 13207 return ExDecl; 13208 } 13209 13210 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13211 /// handler. 13212 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13213 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13214 bool Invalid = D.isInvalidType(); 13215 13216 // Check for unexpanded parameter packs. 13217 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13218 UPPC_ExceptionType)) { 13219 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13220 D.getIdentifierLoc()); 13221 Invalid = true; 13222 } 13223 13224 IdentifierInfo *II = D.getIdentifier(); 13225 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13226 LookupOrdinaryName, 13227 ForRedeclaration)) { 13228 // The scope should be freshly made just for us. There is just no way 13229 // it contains any previous declaration, except for function parameters in 13230 // a function-try-block's catch statement. 13231 assert(!S->isDeclScope(PrevDecl)); 13232 if (isDeclInScope(PrevDecl, CurContext, S)) { 13233 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13234 << D.getIdentifier(); 13235 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13236 Invalid = true; 13237 } else if (PrevDecl->isTemplateParameter()) 13238 // Maybe we will complain about the shadowed template parameter. 13239 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13240 } 13241 13242 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13243 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13244 << D.getCXXScopeSpec().getRange(); 13245 Invalid = true; 13246 } 13247 13248 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 13249 D.getLocStart(), 13250 D.getIdentifierLoc(), 13251 D.getIdentifier()); 13252 if (Invalid) 13253 ExDecl->setInvalidDecl(); 13254 13255 // Add the exception declaration into this scope. 13256 if (II) 13257 PushOnScopeChains(ExDecl, S); 13258 else 13259 CurContext->addDecl(ExDecl); 13260 13261 ProcessDeclAttributes(S, ExDecl, D); 13262 return ExDecl; 13263 } 13264 13265 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13266 Expr *AssertExpr, 13267 Expr *AssertMessageExpr, 13268 SourceLocation RParenLoc) { 13269 StringLiteral *AssertMessage = 13270 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13271 13272 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13273 return nullptr; 13274 13275 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13276 AssertMessage, RParenLoc, false); 13277 } 13278 13279 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13280 Expr *AssertExpr, 13281 StringLiteral *AssertMessage, 13282 SourceLocation RParenLoc, 13283 bool Failed) { 13284 assert(AssertExpr != nullptr && "Expected non-null condition"); 13285 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13286 !Failed) { 13287 // In a static_assert-declaration, the constant-expression shall be a 13288 // constant expression that can be contextually converted to bool. 13289 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13290 if (Converted.isInvalid()) 13291 Failed = true; 13292 13293 llvm::APSInt Cond; 13294 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13295 diag::err_static_assert_expression_is_not_constant, 13296 /*AllowFold=*/false).isInvalid()) 13297 Failed = true; 13298 13299 if (!Failed && !Cond) { 13300 SmallString<256> MsgBuffer; 13301 llvm::raw_svector_ostream Msg(MsgBuffer); 13302 if (AssertMessage) 13303 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13304 13305 Expr *InnerCond = nullptr; 13306 std::string InnerCondDescription; 13307 std::tie(InnerCond, InnerCondDescription) = 13308 findFailedBooleanCondition(Converted.get(), 13309 /*AllowTopLevelCond=*/false); 13310 if (InnerCond) { 13311 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 13312 << InnerCondDescription << !AssertMessage 13313 << Msg.str() << InnerCond->getSourceRange(); 13314 } else { 13315 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13316 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13317 } 13318 Failed = true; 13319 } 13320 } 13321 13322 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 13323 /*DiscardedValue*/false, 13324 /*IsConstexpr*/true); 13325 if (FullAssertExpr.isInvalid()) 13326 Failed = true; 13327 else 13328 AssertExpr = FullAssertExpr.get(); 13329 13330 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13331 AssertExpr, AssertMessage, RParenLoc, 13332 Failed); 13333 13334 CurContext->addDecl(Decl); 13335 return Decl; 13336 } 13337 13338 /// \brief Perform semantic analysis of the given friend type declaration. 13339 /// 13340 /// \returns A friend declaration that. 13341 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 13342 SourceLocation FriendLoc, 13343 TypeSourceInfo *TSInfo) { 13344 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 13345 13346 QualType T = TSInfo->getType(); 13347 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 13348 13349 // C++03 [class.friend]p2: 13350 // An elaborated-type-specifier shall be used in a friend declaration 13351 // for a class.* 13352 // 13353 // * The class-key of the elaborated-type-specifier is required. 13354 if (!CodeSynthesisContexts.empty()) { 13355 // Do not complain about the form of friend template types during any kind 13356 // of code synthesis. For template instantiation, we will have complained 13357 // when the template was defined. 13358 } else { 13359 if (!T->isElaboratedTypeSpecifier()) { 13360 // If we evaluated the type to a record type, suggest putting 13361 // a tag in front. 13362 if (const RecordType *RT = T->getAs<RecordType>()) { 13363 RecordDecl *RD = RT->getDecl(); 13364 13365 SmallString<16> InsertionText(" "); 13366 InsertionText += RD->getKindName(); 13367 13368 Diag(TypeRange.getBegin(), 13369 getLangOpts().CPlusPlus11 ? 13370 diag::warn_cxx98_compat_unelaborated_friend_type : 13371 diag::ext_unelaborated_friend_type) 13372 << (unsigned) RD->getTagKind() 13373 << T 13374 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 13375 InsertionText); 13376 } else { 13377 Diag(FriendLoc, 13378 getLangOpts().CPlusPlus11 ? 13379 diag::warn_cxx98_compat_nonclass_type_friend : 13380 diag::ext_nonclass_type_friend) 13381 << T 13382 << TypeRange; 13383 } 13384 } else if (T->getAs<EnumType>()) { 13385 Diag(FriendLoc, 13386 getLangOpts().CPlusPlus11 ? 13387 diag::warn_cxx98_compat_enum_friend : 13388 diag::ext_enum_friend) 13389 << T 13390 << TypeRange; 13391 } 13392 13393 // C++11 [class.friend]p3: 13394 // A friend declaration that does not declare a function shall have one 13395 // of the following forms: 13396 // friend elaborated-type-specifier ; 13397 // friend simple-type-specifier ; 13398 // friend typename-specifier ; 13399 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 13400 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 13401 } 13402 13403 // If the type specifier in a friend declaration designates a (possibly 13404 // cv-qualified) class type, that class is declared as a friend; otherwise, 13405 // the friend declaration is ignored. 13406 return FriendDecl::Create(Context, CurContext, 13407 TSInfo->getTypeLoc().getLocStart(), TSInfo, 13408 FriendLoc); 13409 } 13410 13411 /// Handle a friend tag declaration where the scope specifier was 13412 /// templated. 13413 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 13414 unsigned TagSpec, SourceLocation TagLoc, 13415 CXXScopeSpec &SS, 13416 IdentifierInfo *Name, 13417 SourceLocation NameLoc, 13418 AttributeList *Attr, 13419 MultiTemplateParamsArg TempParamLists) { 13420 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13421 13422 bool IsMemberSpecialization = false; 13423 bool Invalid = false; 13424 13425 if (TemplateParameterList *TemplateParams = 13426 MatchTemplateParametersToScopeSpecifier( 13427 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 13428 IsMemberSpecialization, Invalid)) { 13429 if (TemplateParams->size() > 0) { 13430 // This is a declaration of a class template. 13431 if (Invalid) 13432 return nullptr; 13433 13434 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 13435 NameLoc, Attr, TemplateParams, AS_public, 13436 /*ModulePrivateLoc=*/SourceLocation(), 13437 FriendLoc, TempParamLists.size() - 1, 13438 TempParamLists.data()).get(); 13439 } else { 13440 // The "template<>" header is extraneous. 13441 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13442 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13443 IsMemberSpecialization = true; 13444 } 13445 } 13446 13447 if (Invalid) return nullptr; 13448 13449 bool isAllExplicitSpecializations = true; 13450 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 13451 if (TempParamLists[I]->size()) { 13452 isAllExplicitSpecializations = false; 13453 break; 13454 } 13455 } 13456 13457 // FIXME: don't ignore attributes. 13458 13459 // If it's explicit specializations all the way down, just forget 13460 // about the template header and build an appropriate non-templated 13461 // friend. TODO: for source fidelity, remember the headers. 13462 if (isAllExplicitSpecializations) { 13463 if (SS.isEmpty()) { 13464 bool Owned = false; 13465 bool IsDependent = false; 13466 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 13467 Attr, AS_public, 13468 /*ModulePrivateLoc=*/SourceLocation(), 13469 MultiTemplateParamsArg(), Owned, IsDependent, 13470 /*ScopedEnumKWLoc=*/SourceLocation(), 13471 /*ScopedEnumUsesClassTag=*/false, 13472 /*UnderlyingType=*/TypeResult(), 13473 /*IsTypeSpecifier=*/false, 13474 /*IsTemplateParamOrArg=*/false); 13475 } 13476 13477 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 13478 ElaboratedTypeKeyword Keyword 13479 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13480 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 13481 *Name, NameLoc); 13482 if (T.isNull()) 13483 return nullptr; 13484 13485 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13486 if (isa<DependentNameType>(T)) { 13487 DependentNameTypeLoc TL = 13488 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13489 TL.setElaboratedKeywordLoc(TagLoc); 13490 TL.setQualifierLoc(QualifierLoc); 13491 TL.setNameLoc(NameLoc); 13492 } else { 13493 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 13494 TL.setElaboratedKeywordLoc(TagLoc); 13495 TL.setQualifierLoc(QualifierLoc); 13496 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 13497 } 13498 13499 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13500 TSI, FriendLoc, TempParamLists); 13501 Friend->setAccess(AS_public); 13502 CurContext->addDecl(Friend); 13503 return Friend; 13504 } 13505 13506 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 13507 13508 13509 13510 // Handle the case of a templated-scope friend class. e.g. 13511 // template <class T> class A<T>::B; 13512 // FIXME: we don't support these right now. 13513 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 13514 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 13515 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13516 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 13517 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13518 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13519 TL.setElaboratedKeywordLoc(TagLoc); 13520 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 13521 TL.setNameLoc(NameLoc); 13522 13523 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13524 TSI, FriendLoc, TempParamLists); 13525 Friend->setAccess(AS_public); 13526 Friend->setUnsupportedFriend(true); 13527 CurContext->addDecl(Friend); 13528 return Friend; 13529 } 13530 13531 13532 /// Handle a friend type declaration. This works in tandem with 13533 /// ActOnTag. 13534 /// 13535 /// Notes on friend class templates: 13536 /// 13537 /// We generally treat friend class declarations as if they were 13538 /// declaring a class. So, for example, the elaborated type specifier 13539 /// in a friend declaration is required to obey the restrictions of a 13540 /// class-head (i.e. no typedefs in the scope chain), template 13541 /// parameters are required to match up with simple template-ids, &c. 13542 /// However, unlike when declaring a template specialization, it's 13543 /// okay to refer to a template specialization without an empty 13544 /// template parameter declaration, e.g. 13545 /// friend class A<T>::B<unsigned>; 13546 /// We permit this as a special case; if there are any template 13547 /// parameters present at all, require proper matching, i.e. 13548 /// template <> template \<class T> friend class A<int>::B; 13549 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 13550 MultiTemplateParamsArg TempParams) { 13551 SourceLocation Loc = DS.getLocStart(); 13552 13553 assert(DS.isFriendSpecified()); 13554 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13555 13556 // Try to convert the decl specifier to a type. This works for 13557 // friend templates because ActOnTag never produces a ClassTemplateDecl 13558 // for a TUK_Friend. 13559 Declarator TheDeclarator(DS, Declarator::MemberContext); 13560 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 13561 QualType T = TSI->getType(); 13562 if (TheDeclarator.isInvalidType()) 13563 return nullptr; 13564 13565 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 13566 return nullptr; 13567 13568 // This is definitely an error in C++98. It's probably meant to 13569 // be forbidden in C++0x, too, but the specification is just 13570 // poorly written. 13571 // 13572 // The problem is with declarations like the following: 13573 // template <T> friend A<T>::foo; 13574 // where deciding whether a class C is a friend or not now hinges 13575 // on whether there exists an instantiation of A that causes 13576 // 'foo' to equal C. There are restrictions on class-heads 13577 // (which we declare (by fiat) elaborated friend declarations to 13578 // be) that makes this tractable. 13579 // 13580 // FIXME: handle "template <> friend class A<T>;", which 13581 // is possibly well-formed? Who even knows? 13582 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 13583 Diag(Loc, diag::err_tagless_friend_type_template) 13584 << DS.getSourceRange(); 13585 return nullptr; 13586 } 13587 13588 // C++98 [class.friend]p1: A friend of a class is a function 13589 // or class that is not a member of the class . . . 13590 // This is fixed in DR77, which just barely didn't make the C++03 13591 // deadline. It's also a very silly restriction that seriously 13592 // affects inner classes and which nobody else seems to implement; 13593 // thus we never diagnose it, not even in -pedantic. 13594 // 13595 // But note that we could warn about it: it's always useless to 13596 // friend one of your own members (it's not, however, worthless to 13597 // friend a member of an arbitrary specialization of your template). 13598 13599 Decl *D; 13600 if (!TempParams.empty()) 13601 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 13602 TempParams, 13603 TSI, 13604 DS.getFriendSpecLoc()); 13605 else 13606 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 13607 13608 if (!D) 13609 return nullptr; 13610 13611 D->setAccess(AS_public); 13612 CurContext->addDecl(D); 13613 13614 return D; 13615 } 13616 13617 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 13618 MultiTemplateParamsArg TemplateParams) { 13619 const DeclSpec &DS = D.getDeclSpec(); 13620 13621 assert(DS.isFriendSpecified()); 13622 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13623 13624 SourceLocation Loc = D.getIdentifierLoc(); 13625 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13626 13627 // C++ [class.friend]p1 13628 // A friend of a class is a function or class.... 13629 // Note that this sees through typedefs, which is intended. 13630 // It *doesn't* see through dependent types, which is correct 13631 // according to [temp.arg.type]p3: 13632 // If a declaration acquires a function type through a 13633 // type dependent on a template-parameter and this causes 13634 // a declaration that does not use the syntactic form of a 13635 // function declarator to have a function type, the program 13636 // is ill-formed. 13637 if (!TInfo->getType()->isFunctionType()) { 13638 Diag(Loc, diag::err_unexpected_friend); 13639 13640 // It might be worthwhile to try to recover by creating an 13641 // appropriate declaration. 13642 return nullptr; 13643 } 13644 13645 // C++ [namespace.memdef]p3 13646 // - If a friend declaration in a non-local class first declares a 13647 // class or function, the friend class or function is a member 13648 // of the innermost enclosing namespace. 13649 // - The name of the friend is not found by simple name lookup 13650 // until a matching declaration is provided in that namespace 13651 // scope (either before or after the class declaration granting 13652 // friendship). 13653 // - If a friend function is called, its name may be found by the 13654 // name lookup that considers functions from namespaces and 13655 // classes associated with the types of the function arguments. 13656 // - When looking for a prior declaration of a class or a function 13657 // declared as a friend, scopes outside the innermost enclosing 13658 // namespace scope are not considered. 13659 13660 CXXScopeSpec &SS = D.getCXXScopeSpec(); 13661 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 13662 DeclarationName Name = NameInfo.getName(); 13663 assert(Name); 13664 13665 // Check for unexpanded parameter packs. 13666 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 13667 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 13668 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 13669 return nullptr; 13670 13671 // The context we found the declaration in, or in which we should 13672 // create the declaration. 13673 DeclContext *DC; 13674 Scope *DCScope = S; 13675 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 13676 ForRedeclaration); 13677 13678 // There are five cases here. 13679 // - There's no scope specifier and we're in a local class. Only look 13680 // for functions declared in the immediately-enclosing block scope. 13681 // We recover from invalid scope qualifiers as if they just weren't there. 13682 FunctionDecl *FunctionContainingLocalClass = nullptr; 13683 if ((SS.isInvalid() || !SS.isSet()) && 13684 (FunctionContainingLocalClass = 13685 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 13686 // C++11 [class.friend]p11: 13687 // If a friend declaration appears in a local class and the name 13688 // specified is an unqualified name, a prior declaration is 13689 // looked up without considering scopes that are outside the 13690 // innermost enclosing non-class scope. For a friend function 13691 // declaration, if there is no prior declaration, the program is 13692 // ill-formed. 13693 13694 // Find the innermost enclosing non-class scope. This is the block 13695 // scope containing the local class definition (or for a nested class, 13696 // the outer local class). 13697 DCScope = S->getFnParent(); 13698 13699 // Look up the function name in the scope. 13700 Previous.clear(LookupLocalFriendName); 13701 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 13702 13703 if (!Previous.empty()) { 13704 // All possible previous declarations must have the same context: 13705 // either they were declared at block scope or they are members of 13706 // one of the enclosing local classes. 13707 DC = Previous.getRepresentativeDecl()->getDeclContext(); 13708 } else { 13709 // This is ill-formed, but provide the context that we would have 13710 // declared the function in, if we were permitted to, for error recovery. 13711 DC = FunctionContainingLocalClass; 13712 } 13713 adjustContextForLocalExternDecl(DC); 13714 13715 // C++ [class.friend]p6: 13716 // A function can be defined in a friend declaration of a class if and 13717 // only if the class is a non-local class (9.8), the function name is 13718 // unqualified, and the function has namespace scope. 13719 if (D.isFunctionDefinition()) { 13720 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 13721 } 13722 13723 // - There's no scope specifier, in which case we just go to the 13724 // appropriate scope and look for a function or function template 13725 // there as appropriate. 13726 } else if (SS.isInvalid() || !SS.isSet()) { 13727 // C++11 [namespace.memdef]p3: 13728 // If the name in a friend declaration is neither qualified nor 13729 // a template-id and the declaration is a function or an 13730 // elaborated-type-specifier, the lookup to determine whether 13731 // the entity has been previously declared shall not consider 13732 // any scopes outside the innermost enclosing namespace. 13733 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 13734 13735 // Find the appropriate context according to the above. 13736 DC = CurContext; 13737 13738 // Skip class contexts. If someone can cite chapter and verse 13739 // for this behavior, that would be nice --- it's what GCC and 13740 // EDG do, and it seems like a reasonable intent, but the spec 13741 // really only says that checks for unqualified existing 13742 // declarations should stop at the nearest enclosing namespace, 13743 // not that they should only consider the nearest enclosing 13744 // namespace. 13745 while (DC->isRecord()) 13746 DC = DC->getParent(); 13747 13748 DeclContext *LookupDC = DC; 13749 while (LookupDC->isTransparentContext()) 13750 LookupDC = LookupDC->getParent(); 13751 13752 while (true) { 13753 LookupQualifiedName(Previous, LookupDC); 13754 13755 if (!Previous.empty()) { 13756 DC = LookupDC; 13757 break; 13758 } 13759 13760 if (isTemplateId) { 13761 if (isa<TranslationUnitDecl>(LookupDC)) break; 13762 } else { 13763 if (LookupDC->isFileContext()) break; 13764 } 13765 LookupDC = LookupDC->getParent(); 13766 } 13767 13768 DCScope = getScopeForDeclContext(S, DC); 13769 13770 // - There's a non-dependent scope specifier, in which case we 13771 // compute it and do a previous lookup there for a function 13772 // or function template. 13773 } else if (!SS.getScopeRep()->isDependent()) { 13774 DC = computeDeclContext(SS); 13775 if (!DC) return nullptr; 13776 13777 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 13778 13779 LookupQualifiedName(Previous, DC); 13780 13781 // Ignore things found implicitly in the wrong scope. 13782 // TODO: better diagnostics for this case. Suggesting the right 13783 // qualified scope would be nice... 13784 LookupResult::Filter F = Previous.makeFilter(); 13785 while (F.hasNext()) { 13786 NamedDecl *D = F.next(); 13787 if (!DC->InEnclosingNamespaceSetOf( 13788 D->getDeclContext()->getRedeclContext())) 13789 F.erase(); 13790 } 13791 F.done(); 13792 13793 if (Previous.empty()) { 13794 D.setInvalidType(); 13795 Diag(Loc, diag::err_qualified_friend_not_found) 13796 << Name << TInfo->getType(); 13797 return nullptr; 13798 } 13799 13800 // C++ [class.friend]p1: A friend of a class is a function or 13801 // class that is not a member of the class . . . 13802 if (DC->Equals(CurContext)) 13803 Diag(DS.getFriendSpecLoc(), 13804 getLangOpts().CPlusPlus11 ? 13805 diag::warn_cxx98_compat_friend_is_member : 13806 diag::err_friend_is_member); 13807 13808 if (D.isFunctionDefinition()) { 13809 // C++ [class.friend]p6: 13810 // A function can be defined in a friend declaration of a class if and 13811 // only if the class is a non-local class (9.8), the function name is 13812 // unqualified, and the function has namespace scope. 13813 SemaDiagnosticBuilder DB 13814 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 13815 13816 DB << SS.getScopeRep(); 13817 if (DC->isFileContext()) 13818 DB << FixItHint::CreateRemoval(SS.getRange()); 13819 SS.clear(); 13820 } 13821 13822 // - There's a scope specifier that does not match any template 13823 // parameter lists, in which case we use some arbitrary context, 13824 // create a method or method template, and wait for instantiation. 13825 // - There's a scope specifier that does match some template 13826 // parameter lists, which we don't handle right now. 13827 } else { 13828 if (D.isFunctionDefinition()) { 13829 // C++ [class.friend]p6: 13830 // A function can be defined in a friend declaration of a class if and 13831 // only if the class is a non-local class (9.8), the function name is 13832 // unqualified, and the function has namespace scope. 13833 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 13834 << SS.getScopeRep(); 13835 } 13836 13837 DC = CurContext; 13838 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 13839 } 13840 13841 if (!DC->isRecord()) { 13842 int DiagArg = -1; 13843 switch (D.getName().getKind()) { 13844 case UnqualifiedId::IK_ConstructorTemplateId: 13845 case UnqualifiedId::IK_ConstructorName: 13846 DiagArg = 0; 13847 break; 13848 case UnqualifiedId::IK_DestructorName: 13849 DiagArg = 1; 13850 break; 13851 case UnqualifiedId::IK_ConversionFunctionId: 13852 DiagArg = 2; 13853 break; 13854 case UnqualifiedId::IK_DeductionGuideName: 13855 DiagArg = 3; 13856 break; 13857 case UnqualifiedId::IK_Identifier: 13858 case UnqualifiedId::IK_ImplicitSelfParam: 13859 case UnqualifiedId::IK_LiteralOperatorId: 13860 case UnqualifiedId::IK_OperatorFunctionId: 13861 case UnqualifiedId::IK_TemplateId: 13862 break; 13863 } 13864 // This implies that it has to be an operator or function. 13865 if (DiagArg >= 0) { 13866 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 13867 return nullptr; 13868 } 13869 } 13870 13871 // FIXME: This is an egregious hack to cope with cases where the scope stack 13872 // does not contain the declaration context, i.e., in an out-of-line 13873 // definition of a class. 13874 Scope FakeDCScope(S, Scope::DeclScope, Diags); 13875 if (!DCScope) { 13876 FakeDCScope.setEntity(DC); 13877 DCScope = &FakeDCScope; 13878 } 13879 13880 bool AddToScope = true; 13881 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 13882 TemplateParams, AddToScope); 13883 if (!ND) return nullptr; 13884 13885 assert(ND->getLexicalDeclContext() == CurContext); 13886 13887 // If we performed typo correction, we might have added a scope specifier 13888 // and changed the decl context. 13889 DC = ND->getDeclContext(); 13890 13891 // Add the function declaration to the appropriate lookup tables, 13892 // adjusting the redeclarations list as necessary. We don't 13893 // want to do this yet if the friending class is dependent. 13894 // 13895 // Also update the scope-based lookup if the target context's 13896 // lookup context is in lexical scope. 13897 if (!CurContext->isDependentContext()) { 13898 DC = DC->getRedeclContext(); 13899 DC->makeDeclVisibleInContext(ND); 13900 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13901 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 13902 } 13903 13904 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 13905 D.getIdentifierLoc(), ND, 13906 DS.getFriendSpecLoc()); 13907 FrD->setAccess(AS_public); 13908 CurContext->addDecl(FrD); 13909 13910 if (ND->isInvalidDecl()) { 13911 FrD->setInvalidDecl(); 13912 } else { 13913 if (DC->isRecord()) CheckFriendAccess(ND); 13914 13915 FunctionDecl *FD; 13916 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 13917 FD = FTD->getTemplatedDecl(); 13918 else 13919 FD = cast<FunctionDecl>(ND); 13920 13921 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 13922 // default argument expression, that declaration shall be a definition 13923 // and shall be the only declaration of the function or function 13924 // template in the translation unit. 13925 if (functionDeclHasDefaultArgument(FD)) { 13926 // We can't look at FD->getPreviousDecl() because it may not have been set 13927 // if we're in a dependent context. If the function is known to be a 13928 // redeclaration, we will have narrowed Previous down to the right decl. 13929 if (D.isRedeclaration()) { 13930 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 13931 Diag(Previous.getRepresentativeDecl()->getLocation(), 13932 diag::note_previous_declaration); 13933 } else if (!D.isFunctionDefinition()) 13934 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 13935 } 13936 13937 // Mark templated-scope function declarations as unsupported. 13938 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 13939 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 13940 << SS.getScopeRep() << SS.getRange() 13941 << cast<CXXRecordDecl>(CurContext); 13942 FrD->setUnsupportedFriend(true); 13943 } 13944 } 13945 13946 return ND; 13947 } 13948 13949 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 13950 AdjustDeclIfTemplate(Dcl); 13951 13952 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 13953 if (!Fn) { 13954 Diag(DelLoc, diag::err_deleted_non_function); 13955 return; 13956 } 13957 13958 // Deleted function does not have a body. 13959 Fn->setWillHaveBody(false); 13960 13961 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 13962 // Don't consider the implicit declaration we generate for explicit 13963 // specializations. FIXME: Do not generate these implicit declarations. 13964 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 13965 Prev->getPreviousDecl()) && 13966 !Prev->isDefined()) { 13967 Diag(DelLoc, diag::err_deleted_decl_not_first); 13968 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 13969 Prev->isImplicit() ? diag::note_previous_implicit_declaration 13970 : diag::note_previous_declaration); 13971 } 13972 // If the declaration wasn't the first, we delete the function anyway for 13973 // recovery. 13974 Fn = Fn->getCanonicalDecl(); 13975 } 13976 13977 // dllimport/dllexport cannot be deleted. 13978 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 13979 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 13980 Fn->setInvalidDecl(); 13981 } 13982 13983 if (Fn->isDeleted()) 13984 return; 13985 13986 // See if we're deleting a function which is already known to override a 13987 // non-deleted virtual function. 13988 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 13989 bool IssuedDiagnostic = false; 13990 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 13991 E = MD->end_overridden_methods(); 13992 I != E; ++I) { 13993 if (!(*MD->begin_overridden_methods())->isDeleted()) { 13994 if (!IssuedDiagnostic) { 13995 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 13996 IssuedDiagnostic = true; 13997 } 13998 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 13999 } 14000 } 14001 // If this function was implicitly deleted because it was defaulted, 14002 // explain why it was deleted. 14003 if (IssuedDiagnostic && MD->isDefaulted()) 14004 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14005 /*Diagnose*/true); 14006 } 14007 14008 // C++11 [basic.start.main]p3: 14009 // A program that defines main as deleted [...] is ill-formed. 14010 if (Fn->isMain()) 14011 Diag(DelLoc, diag::err_deleted_main); 14012 14013 // C++11 [dcl.fct.def.delete]p4: 14014 // A deleted function is implicitly inline. 14015 Fn->setImplicitlyInline(); 14016 Fn->setDeletedAsWritten(); 14017 } 14018 14019 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14020 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14021 14022 if (MD) { 14023 if (MD->getParent()->isDependentType()) { 14024 MD->setDefaulted(); 14025 MD->setExplicitlyDefaulted(); 14026 return; 14027 } 14028 14029 CXXSpecialMember Member = getSpecialMember(MD); 14030 if (Member == CXXInvalid) { 14031 if (!MD->isInvalidDecl()) 14032 Diag(DefaultLoc, diag::err_default_special_members); 14033 return; 14034 } 14035 14036 MD->setDefaulted(); 14037 MD->setExplicitlyDefaulted(); 14038 14039 // Unset that we will have a body for this function. We might not, 14040 // if it turns out to be trivial, and we don't need this marking now 14041 // that we've marked it as defaulted. 14042 MD->setWillHaveBody(false); 14043 14044 // If this definition appears within the record, do the checking when 14045 // the record is complete. 14046 const FunctionDecl *Primary = MD; 14047 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14048 // Ask the template instantiation pattern that actually had the 14049 // '= default' on it. 14050 Primary = Pattern; 14051 14052 // If the method was defaulted on its first declaration, we will have 14053 // already performed the checking in CheckCompletedCXXClass. Such a 14054 // declaration doesn't trigger an implicit definition. 14055 if (Primary->getCanonicalDecl()->isDefaulted()) 14056 return; 14057 14058 CheckExplicitlyDefaultedSpecialMember(MD); 14059 14060 if (!MD->isInvalidDecl()) 14061 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14062 } else { 14063 Diag(DefaultLoc, diag::err_default_special_members); 14064 } 14065 } 14066 14067 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14068 for (Stmt *SubStmt : S->children()) { 14069 if (!SubStmt) 14070 continue; 14071 if (isa<ReturnStmt>(SubStmt)) 14072 Self.Diag(SubStmt->getLocStart(), 14073 diag::err_return_in_constructor_handler); 14074 if (!isa<Expr>(SubStmt)) 14075 SearchForReturnInStmt(Self, SubStmt); 14076 } 14077 } 14078 14079 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14080 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14081 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14082 SearchForReturnInStmt(*this, Handler); 14083 } 14084 } 14085 14086 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14087 const CXXMethodDecl *Old) { 14088 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 14089 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 14090 14091 if (OldFT->hasExtParameterInfos()) { 14092 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 14093 // A parameter of the overriding method should be annotated with noescape 14094 // if the corresponding parameter of the overridden method is annotated. 14095 if (OldFT->getExtParameterInfo(I).isNoEscape() && 14096 !NewFT->getExtParameterInfo(I).isNoEscape()) { 14097 Diag(New->getParamDecl(I)->getLocation(), 14098 diag::warn_overriding_method_missing_noescape); 14099 Diag(Old->getParamDecl(I)->getLocation(), 14100 diag::note_overridden_marked_noescape); 14101 } 14102 } 14103 14104 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14105 14106 // If the calling conventions match, everything is fine 14107 if (NewCC == OldCC) 14108 return false; 14109 14110 // If the calling conventions mismatch because the new function is static, 14111 // suppress the calling convention mismatch error; the error about static 14112 // function override (err_static_overrides_virtual from 14113 // Sema::CheckFunctionDeclaration) is more clear. 14114 if (New->getStorageClass() == SC_Static) 14115 return false; 14116 14117 Diag(New->getLocation(), 14118 diag::err_conflicting_overriding_cc_attributes) 14119 << New->getDeclName() << New->getType() << Old->getType(); 14120 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14121 return true; 14122 } 14123 14124 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14125 const CXXMethodDecl *Old) { 14126 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14127 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 14128 14129 if (Context.hasSameType(NewTy, OldTy) || 14130 NewTy->isDependentType() || OldTy->isDependentType()) 14131 return false; 14132 14133 // Check if the return types are covariant 14134 QualType NewClassTy, OldClassTy; 14135 14136 /// Both types must be pointers or references to classes. 14137 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 14138 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 14139 NewClassTy = NewPT->getPointeeType(); 14140 OldClassTy = OldPT->getPointeeType(); 14141 } 14142 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 14143 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 14144 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 14145 NewClassTy = NewRT->getPointeeType(); 14146 OldClassTy = OldRT->getPointeeType(); 14147 } 14148 } 14149 } 14150 14151 // The return types aren't either both pointers or references to a class type. 14152 if (NewClassTy.isNull()) { 14153 Diag(New->getLocation(), 14154 diag::err_different_return_type_for_overriding_virtual_function) 14155 << New->getDeclName() << NewTy << OldTy 14156 << New->getReturnTypeSourceRange(); 14157 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14158 << Old->getReturnTypeSourceRange(); 14159 14160 return true; 14161 } 14162 14163 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 14164 // C++14 [class.virtual]p8: 14165 // If the class type in the covariant return type of D::f differs from 14166 // that of B::f, the class type in the return type of D::f shall be 14167 // complete at the point of declaration of D::f or shall be the class 14168 // type D. 14169 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14170 if (!RT->isBeingDefined() && 14171 RequireCompleteType(New->getLocation(), NewClassTy, 14172 diag::err_covariant_return_incomplete, 14173 New->getDeclName())) 14174 return true; 14175 } 14176 14177 // Check if the new class derives from the old class. 14178 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14179 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14180 << New->getDeclName() << NewTy << OldTy 14181 << New->getReturnTypeSourceRange(); 14182 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14183 << Old->getReturnTypeSourceRange(); 14184 return true; 14185 } 14186 14187 // Check if we the conversion from derived to base is valid. 14188 if (CheckDerivedToBaseConversion( 14189 NewClassTy, OldClassTy, 14190 diag::err_covariant_return_inaccessible_base, 14191 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14192 New->getLocation(), New->getReturnTypeSourceRange(), 14193 New->getDeclName(), nullptr)) { 14194 // FIXME: this note won't trigger for delayed access control 14195 // diagnostics, and it's impossible to get an undelayed error 14196 // here from access control during the original parse because 14197 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14198 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14199 << Old->getReturnTypeSourceRange(); 14200 return true; 14201 } 14202 } 14203 14204 // The qualifiers of the return types must be the same. 14205 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14206 Diag(New->getLocation(), 14207 diag::err_covariant_return_type_different_qualifications) 14208 << New->getDeclName() << NewTy << OldTy 14209 << New->getReturnTypeSourceRange(); 14210 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14211 << Old->getReturnTypeSourceRange(); 14212 return true; 14213 } 14214 14215 14216 // The new class type must have the same or less qualifiers as the old type. 14217 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14218 Diag(New->getLocation(), 14219 diag::err_covariant_return_type_class_type_more_qualified) 14220 << New->getDeclName() << NewTy << OldTy 14221 << New->getReturnTypeSourceRange(); 14222 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14223 << Old->getReturnTypeSourceRange(); 14224 return true; 14225 } 14226 14227 return false; 14228 } 14229 14230 /// \brief Mark the given method pure. 14231 /// 14232 /// \param Method the method to be marked pure. 14233 /// 14234 /// \param InitRange the source range that covers the "0" initializer. 14235 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14236 SourceLocation EndLoc = InitRange.getEnd(); 14237 if (EndLoc.isValid()) 14238 Method->setRangeEnd(EndLoc); 14239 14240 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14241 Method->setPure(); 14242 return false; 14243 } 14244 14245 if (!Method->isInvalidDecl()) 14246 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14247 << Method->getDeclName() << InitRange; 14248 return true; 14249 } 14250 14251 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14252 if (D->getFriendObjectKind()) 14253 Diag(D->getLocation(), diag::err_pure_friend); 14254 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14255 CheckPureMethod(M, ZeroLoc); 14256 else 14257 Diag(D->getLocation(), diag::err_illegal_initializer); 14258 } 14259 14260 /// \brief Determine whether the given declaration is a global variable or 14261 /// static data member. 14262 static bool isNonlocalVariable(const Decl *D) { 14263 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14264 return Var->hasGlobalStorage(); 14265 14266 return false; 14267 } 14268 14269 /// Invoked when we are about to parse an initializer for the declaration 14270 /// 'Dcl'. 14271 /// 14272 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14273 /// static data member of class X, names should be looked up in the scope of 14274 /// class X. If the declaration had a scope specifier, a scope will have 14275 /// been created and passed in for this purpose. Otherwise, S will be null. 14276 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14277 // If there is no declaration, there was an error parsing it. 14278 if (!D || D->isInvalidDecl()) 14279 return; 14280 14281 // We will always have a nested name specifier here, but this declaration 14282 // might not be out of line if the specifier names the current namespace: 14283 // extern int n; 14284 // int ::n = 0; 14285 if (S && D->isOutOfLine()) 14286 EnterDeclaratorContext(S, D->getDeclContext()); 14287 14288 // If we are parsing the initializer for a static data member, push a 14289 // new expression evaluation context that is associated with this static 14290 // data member. 14291 if (isNonlocalVariable(D)) 14292 PushExpressionEvaluationContext( 14293 ExpressionEvaluationContext::PotentiallyEvaluated, D); 14294 } 14295 14296 /// Invoked after we are finished parsing an initializer for the declaration D. 14297 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14298 // If there is no declaration, there was an error parsing it. 14299 if (!D || D->isInvalidDecl()) 14300 return; 14301 14302 if (isNonlocalVariable(D)) 14303 PopExpressionEvaluationContext(); 14304 14305 if (S && D->isOutOfLine()) 14306 ExitDeclaratorContext(S); 14307 } 14308 14309 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14310 /// C++ if/switch/while/for statement. 14311 /// e.g: "if (int x = f()) {...}" 14312 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14313 // C++ 6.4p2: 14314 // The declarator shall not specify a function or an array. 14315 // The type-specifier-seq shall not contain typedef and shall not declare a 14316 // new class or enumeration. 14317 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14318 "Parser allowed 'typedef' as storage class of condition decl."); 14319 14320 Decl *Dcl = ActOnDeclarator(S, D); 14321 if (!Dcl) 14322 return true; 14323 14324 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 14325 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 14326 << D.getSourceRange(); 14327 return true; 14328 } 14329 14330 return Dcl; 14331 } 14332 14333 void Sema::LoadExternalVTableUses() { 14334 if (!ExternalSource) 14335 return; 14336 14337 SmallVector<ExternalVTableUse, 4> VTables; 14338 ExternalSource->ReadUsedVTables(VTables); 14339 SmallVector<VTableUse, 4> NewUses; 14340 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 14341 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 14342 = VTablesUsed.find(VTables[I].Record); 14343 // Even if a definition wasn't required before, it may be required now. 14344 if (Pos != VTablesUsed.end()) { 14345 if (!Pos->second && VTables[I].DefinitionRequired) 14346 Pos->second = true; 14347 continue; 14348 } 14349 14350 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 14351 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 14352 } 14353 14354 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 14355 } 14356 14357 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 14358 bool DefinitionRequired) { 14359 // Ignore any vtable uses in unevaluated operands or for classes that do 14360 // not have a vtable. 14361 if (!Class->isDynamicClass() || Class->isDependentContext() || 14362 CurContext->isDependentContext() || isUnevaluatedContext()) 14363 return; 14364 14365 // Try to insert this class into the map. 14366 LoadExternalVTableUses(); 14367 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14368 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 14369 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 14370 if (!Pos.second) { 14371 // If we already had an entry, check to see if we are promoting this vtable 14372 // to require a definition. If so, we need to reappend to the VTableUses 14373 // list, since we may have already processed the first entry. 14374 if (DefinitionRequired && !Pos.first->second) { 14375 Pos.first->second = true; 14376 } else { 14377 // Otherwise, we can early exit. 14378 return; 14379 } 14380 } else { 14381 // The Microsoft ABI requires that we perform the destructor body 14382 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 14383 // the deleting destructor is emitted with the vtable, not with the 14384 // destructor definition as in the Itanium ABI. 14385 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14386 CXXDestructorDecl *DD = Class->getDestructor(); 14387 if (DD && DD->isVirtual() && !DD->isDeleted()) { 14388 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 14389 // If this is an out-of-line declaration, marking it referenced will 14390 // not do anything. Manually call CheckDestructor to look up operator 14391 // delete(). 14392 ContextRAII SavedContext(*this, DD); 14393 CheckDestructor(DD); 14394 } else { 14395 MarkFunctionReferenced(Loc, Class->getDestructor()); 14396 } 14397 } 14398 } 14399 } 14400 14401 // Local classes need to have their virtual members marked 14402 // immediately. For all other classes, we mark their virtual members 14403 // at the end of the translation unit. 14404 if (Class->isLocalClass()) 14405 MarkVirtualMembersReferenced(Loc, Class); 14406 else 14407 VTableUses.push_back(std::make_pair(Class, Loc)); 14408 } 14409 14410 bool Sema::DefineUsedVTables() { 14411 LoadExternalVTableUses(); 14412 if (VTableUses.empty()) 14413 return false; 14414 14415 // Note: The VTableUses vector could grow as a result of marking 14416 // the members of a class as "used", so we check the size each 14417 // time through the loop and prefer indices (which are stable) to 14418 // iterators (which are not). 14419 bool DefinedAnything = false; 14420 for (unsigned I = 0; I != VTableUses.size(); ++I) { 14421 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 14422 if (!Class) 14423 continue; 14424 TemplateSpecializationKind ClassTSK = 14425 Class->getTemplateSpecializationKind(); 14426 14427 SourceLocation Loc = VTableUses[I].second; 14428 14429 bool DefineVTable = true; 14430 14431 // If this class has a key function, but that key function is 14432 // defined in another translation unit, we don't need to emit the 14433 // vtable even though we're using it. 14434 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 14435 if (KeyFunction && !KeyFunction->hasBody()) { 14436 // The key function is in another translation unit. 14437 DefineVTable = false; 14438 TemplateSpecializationKind TSK = 14439 KeyFunction->getTemplateSpecializationKind(); 14440 assert(TSK != TSK_ExplicitInstantiationDefinition && 14441 TSK != TSK_ImplicitInstantiation && 14442 "Instantiations don't have key functions"); 14443 (void)TSK; 14444 } else if (!KeyFunction) { 14445 // If we have a class with no key function that is the subject 14446 // of an explicit instantiation declaration, suppress the 14447 // vtable; it will live with the explicit instantiation 14448 // definition. 14449 bool IsExplicitInstantiationDeclaration = 14450 ClassTSK == TSK_ExplicitInstantiationDeclaration; 14451 for (auto R : Class->redecls()) { 14452 TemplateSpecializationKind TSK 14453 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 14454 if (TSK == TSK_ExplicitInstantiationDeclaration) 14455 IsExplicitInstantiationDeclaration = true; 14456 else if (TSK == TSK_ExplicitInstantiationDefinition) { 14457 IsExplicitInstantiationDeclaration = false; 14458 break; 14459 } 14460 } 14461 14462 if (IsExplicitInstantiationDeclaration) 14463 DefineVTable = false; 14464 } 14465 14466 // The exception specifications for all virtual members may be needed even 14467 // if we are not providing an authoritative form of the vtable in this TU. 14468 // We may choose to emit it available_externally anyway. 14469 if (!DefineVTable) { 14470 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 14471 continue; 14472 } 14473 14474 // Mark all of the virtual members of this class as referenced, so 14475 // that we can build a vtable. Then, tell the AST consumer that a 14476 // vtable for this class is required. 14477 DefinedAnything = true; 14478 MarkVirtualMembersReferenced(Loc, Class); 14479 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14480 if (VTablesUsed[Canonical]) 14481 Consumer.HandleVTable(Class); 14482 14483 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 14484 // no key function or the key function is inlined. Don't warn in C++ ABIs 14485 // that lack key functions, since the user won't be able to make one. 14486 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 14487 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 14488 const FunctionDecl *KeyFunctionDef = nullptr; 14489 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 14490 KeyFunctionDef->isInlined())) { 14491 Diag(Class->getLocation(), 14492 ClassTSK == TSK_ExplicitInstantiationDefinition 14493 ? diag::warn_weak_template_vtable 14494 : diag::warn_weak_vtable) 14495 << Class; 14496 } 14497 } 14498 } 14499 VTableUses.clear(); 14500 14501 return DefinedAnything; 14502 } 14503 14504 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 14505 const CXXRecordDecl *RD) { 14506 for (const auto *I : RD->methods()) 14507 if (I->isVirtual() && !I->isPure()) 14508 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 14509 } 14510 14511 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 14512 const CXXRecordDecl *RD) { 14513 // Mark all functions which will appear in RD's vtable as used. 14514 CXXFinalOverriderMap FinalOverriders; 14515 RD->getFinalOverriders(FinalOverriders); 14516 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 14517 E = FinalOverriders.end(); 14518 I != E; ++I) { 14519 for (OverridingMethods::const_iterator OI = I->second.begin(), 14520 OE = I->second.end(); 14521 OI != OE; ++OI) { 14522 assert(OI->second.size() > 0 && "no final overrider"); 14523 CXXMethodDecl *Overrider = OI->second.front().Method; 14524 14525 // C++ [basic.def.odr]p2: 14526 // [...] A virtual member function is used if it is not pure. [...] 14527 if (!Overrider->isPure()) 14528 MarkFunctionReferenced(Loc, Overrider); 14529 } 14530 } 14531 14532 // Only classes that have virtual bases need a VTT. 14533 if (RD->getNumVBases() == 0) 14534 return; 14535 14536 for (const auto &I : RD->bases()) { 14537 const CXXRecordDecl *Base = 14538 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 14539 if (Base->getNumVBases() == 0) 14540 continue; 14541 MarkVirtualMembersReferenced(Loc, Base); 14542 } 14543 } 14544 14545 /// SetIvarInitializers - This routine builds initialization ASTs for the 14546 /// Objective-C implementation whose ivars need be initialized. 14547 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 14548 if (!getLangOpts().CPlusPlus) 14549 return; 14550 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 14551 SmallVector<ObjCIvarDecl*, 8> ivars; 14552 CollectIvarsToConstructOrDestruct(OID, ivars); 14553 if (ivars.empty()) 14554 return; 14555 SmallVector<CXXCtorInitializer*, 32> AllToInit; 14556 for (unsigned i = 0; i < ivars.size(); i++) { 14557 FieldDecl *Field = ivars[i]; 14558 if (Field->isInvalidDecl()) 14559 continue; 14560 14561 CXXCtorInitializer *Member; 14562 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 14563 InitializationKind InitKind = 14564 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 14565 14566 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 14567 ExprResult MemberInit = 14568 InitSeq.Perform(*this, InitEntity, InitKind, None); 14569 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 14570 // Note, MemberInit could actually come back empty if no initialization 14571 // is required (e.g., because it would call a trivial default constructor) 14572 if (!MemberInit.get() || MemberInit.isInvalid()) 14573 continue; 14574 14575 Member = 14576 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 14577 SourceLocation(), 14578 MemberInit.getAs<Expr>(), 14579 SourceLocation()); 14580 AllToInit.push_back(Member); 14581 14582 // Be sure that the destructor is accessible and is marked as referenced. 14583 if (const RecordType *RecordTy = 14584 Context.getBaseElementType(Field->getType()) 14585 ->getAs<RecordType>()) { 14586 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 14587 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 14588 MarkFunctionReferenced(Field->getLocation(), Destructor); 14589 CheckDestructorAccess(Field->getLocation(), Destructor, 14590 PDiag(diag::err_access_dtor_ivar) 14591 << Context.getBaseElementType(Field->getType())); 14592 } 14593 } 14594 } 14595 ObjCImplementation->setIvarInitializers(Context, 14596 AllToInit.data(), AllToInit.size()); 14597 } 14598 } 14599 14600 static 14601 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 14602 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 14603 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 14604 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 14605 Sema &S) { 14606 if (Ctor->isInvalidDecl()) 14607 return; 14608 14609 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 14610 14611 // Target may not be determinable yet, for instance if this is a dependent 14612 // call in an uninstantiated template. 14613 if (Target) { 14614 const FunctionDecl *FNTarget = nullptr; 14615 (void)Target->hasBody(FNTarget); 14616 Target = const_cast<CXXConstructorDecl*>( 14617 cast_or_null<CXXConstructorDecl>(FNTarget)); 14618 } 14619 14620 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 14621 // Avoid dereferencing a null pointer here. 14622 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 14623 14624 if (!Current.insert(Canonical).second) 14625 return; 14626 14627 // We know that beyond here, we aren't chaining into a cycle. 14628 if (!Target || !Target->isDelegatingConstructor() || 14629 Target->isInvalidDecl() || Valid.count(TCanonical)) { 14630 Valid.insert(Current.begin(), Current.end()); 14631 Current.clear(); 14632 // We've hit a cycle. 14633 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 14634 Current.count(TCanonical)) { 14635 // If we haven't diagnosed this cycle yet, do so now. 14636 if (!Invalid.count(TCanonical)) { 14637 S.Diag((*Ctor->init_begin())->getSourceLocation(), 14638 diag::warn_delegating_ctor_cycle) 14639 << Ctor; 14640 14641 // Don't add a note for a function delegating directly to itself. 14642 if (TCanonical != Canonical) 14643 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 14644 14645 CXXConstructorDecl *C = Target; 14646 while (C->getCanonicalDecl() != Canonical) { 14647 const FunctionDecl *FNTarget = nullptr; 14648 (void)C->getTargetConstructor()->hasBody(FNTarget); 14649 assert(FNTarget && "Ctor cycle through bodiless function"); 14650 14651 C = const_cast<CXXConstructorDecl*>( 14652 cast<CXXConstructorDecl>(FNTarget)); 14653 S.Diag(C->getLocation(), diag::note_which_delegates_to); 14654 } 14655 } 14656 14657 Invalid.insert(Current.begin(), Current.end()); 14658 Current.clear(); 14659 } else { 14660 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 14661 } 14662 } 14663 14664 14665 void Sema::CheckDelegatingCtorCycles() { 14666 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 14667 14668 for (DelegatingCtorDeclsType::iterator 14669 I = DelegatingCtorDecls.begin(ExternalSource), 14670 E = DelegatingCtorDecls.end(); 14671 I != E; ++I) 14672 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 14673 14674 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 14675 CE = Invalid.end(); 14676 CI != CE; ++CI) 14677 (*CI)->setInvalidDecl(); 14678 } 14679 14680 namespace { 14681 /// \brief AST visitor that finds references to the 'this' expression. 14682 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 14683 Sema &S; 14684 14685 public: 14686 explicit FindCXXThisExpr(Sema &S) : S(S) { } 14687 14688 bool VisitCXXThisExpr(CXXThisExpr *E) { 14689 S.Diag(E->getLocation(), diag::err_this_static_member_func) 14690 << E->isImplicit(); 14691 return false; 14692 } 14693 }; 14694 } 14695 14696 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 14697 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14698 if (!TSInfo) 14699 return false; 14700 14701 TypeLoc TL = TSInfo->getTypeLoc(); 14702 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14703 if (!ProtoTL) 14704 return false; 14705 14706 // C++11 [expr.prim.general]p3: 14707 // [The expression this] shall not appear before the optional 14708 // cv-qualifier-seq and it shall not appear within the declaration of a 14709 // static member function (although its type and value category are defined 14710 // within a static member function as they are within a non-static member 14711 // function). [ Note: this is because declaration matching does not occur 14712 // until the complete declarator is known. - end note ] 14713 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14714 FindCXXThisExpr Finder(*this); 14715 14716 // If the return type came after the cv-qualifier-seq, check it now. 14717 if (Proto->hasTrailingReturn() && 14718 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 14719 return true; 14720 14721 // Check the exception specification. 14722 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 14723 return true; 14724 14725 return checkThisInStaticMemberFunctionAttributes(Method); 14726 } 14727 14728 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 14729 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14730 if (!TSInfo) 14731 return false; 14732 14733 TypeLoc TL = TSInfo->getTypeLoc(); 14734 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14735 if (!ProtoTL) 14736 return false; 14737 14738 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14739 FindCXXThisExpr Finder(*this); 14740 14741 switch (Proto->getExceptionSpecType()) { 14742 case EST_Unparsed: 14743 case EST_Uninstantiated: 14744 case EST_Unevaluated: 14745 case EST_BasicNoexcept: 14746 case EST_DynamicNone: 14747 case EST_MSAny: 14748 case EST_None: 14749 break; 14750 14751 case EST_ComputedNoexcept: 14752 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 14753 return true; 14754 LLVM_FALLTHROUGH; 14755 14756 case EST_Dynamic: 14757 for (const auto &E : Proto->exceptions()) { 14758 if (!Finder.TraverseType(E)) 14759 return true; 14760 } 14761 break; 14762 } 14763 14764 return false; 14765 } 14766 14767 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 14768 FindCXXThisExpr Finder(*this); 14769 14770 // Check attributes. 14771 for (const auto *A : Method->attrs()) { 14772 // FIXME: This should be emitted by tblgen. 14773 Expr *Arg = nullptr; 14774 ArrayRef<Expr *> Args; 14775 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 14776 Arg = G->getArg(); 14777 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 14778 Arg = G->getArg(); 14779 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 14780 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 14781 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 14782 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 14783 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 14784 Arg = ETLF->getSuccessValue(); 14785 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 14786 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 14787 Arg = STLF->getSuccessValue(); 14788 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 14789 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 14790 Arg = LR->getArg(); 14791 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 14792 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 14793 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 14794 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14795 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 14796 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14797 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 14798 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14799 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 14800 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14801 14802 if (Arg && !Finder.TraverseStmt(Arg)) 14803 return true; 14804 14805 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 14806 if (!Finder.TraverseStmt(Args[I])) 14807 return true; 14808 } 14809 } 14810 14811 return false; 14812 } 14813 14814 void Sema::checkExceptionSpecification( 14815 bool IsTopLevel, ExceptionSpecificationType EST, 14816 ArrayRef<ParsedType> DynamicExceptions, 14817 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 14818 SmallVectorImpl<QualType> &Exceptions, 14819 FunctionProtoType::ExceptionSpecInfo &ESI) { 14820 Exceptions.clear(); 14821 ESI.Type = EST; 14822 if (EST == EST_Dynamic) { 14823 Exceptions.reserve(DynamicExceptions.size()); 14824 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 14825 // FIXME: Preserve type source info. 14826 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 14827 14828 if (IsTopLevel) { 14829 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 14830 collectUnexpandedParameterPacks(ET, Unexpanded); 14831 if (!Unexpanded.empty()) { 14832 DiagnoseUnexpandedParameterPacks( 14833 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 14834 Unexpanded); 14835 continue; 14836 } 14837 } 14838 14839 // Check that the type is valid for an exception spec, and 14840 // drop it if not. 14841 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 14842 Exceptions.push_back(ET); 14843 } 14844 ESI.Exceptions = Exceptions; 14845 return; 14846 } 14847 14848 if (EST == EST_ComputedNoexcept) { 14849 // If an error occurred, there's no expression here. 14850 if (NoexceptExpr) { 14851 assert((NoexceptExpr->isTypeDependent() || 14852 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 14853 Context.BoolTy) && 14854 "Parser should have made sure that the expression is boolean"); 14855 if (IsTopLevel && NoexceptExpr && 14856 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 14857 ESI.Type = EST_BasicNoexcept; 14858 return; 14859 } 14860 14861 if (!NoexceptExpr->isValueDependent()) 14862 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 14863 diag::err_noexcept_needs_constant_expression, 14864 /*AllowFold*/ false).get(); 14865 ESI.NoexceptExpr = NoexceptExpr; 14866 } 14867 return; 14868 } 14869 } 14870 14871 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 14872 ExceptionSpecificationType EST, 14873 SourceRange SpecificationRange, 14874 ArrayRef<ParsedType> DynamicExceptions, 14875 ArrayRef<SourceRange> DynamicExceptionRanges, 14876 Expr *NoexceptExpr) { 14877 if (!MethodD) 14878 return; 14879 14880 // Dig out the method we're referring to. 14881 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 14882 MethodD = FunTmpl->getTemplatedDecl(); 14883 14884 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 14885 if (!Method) 14886 return; 14887 14888 // Check the exception specification. 14889 llvm::SmallVector<QualType, 4> Exceptions; 14890 FunctionProtoType::ExceptionSpecInfo ESI; 14891 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 14892 DynamicExceptionRanges, NoexceptExpr, Exceptions, 14893 ESI); 14894 14895 // Update the exception specification on the function type. 14896 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 14897 14898 if (Method->isStatic()) 14899 checkThisInStaticMemberFunctionExceptionSpec(Method); 14900 14901 if (Method->isVirtual()) { 14902 // Check overrides, which we previously had to delay. 14903 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 14904 OEnd = Method->end_overridden_methods(); 14905 O != OEnd; ++O) 14906 CheckOverridingFunctionExceptionSpec(Method, *O); 14907 } 14908 } 14909 14910 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 14911 /// 14912 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 14913 SourceLocation DeclStart, 14914 Declarator &D, Expr *BitWidth, 14915 InClassInitStyle InitStyle, 14916 AccessSpecifier AS, 14917 AttributeList *MSPropertyAttr) { 14918 IdentifierInfo *II = D.getIdentifier(); 14919 if (!II) { 14920 Diag(DeclStart, diag::err_anonymous_property); 14921 return nullptr; 14922 } 14923 SourceLocation Loc = D.getIdentifierLoc(); 14924 14925 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14926 QualType T = TInfo->getType(); 14927 if (getLangOpts().CPlusPlus) { 14928 CheckExtraCXXDefaultArguments(D); 14929 14930 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14931 UPPC_DataMemberType)) { 14932 D.setInvalidType(); 14933 T = Context.IntTy; 14934 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14935 } 14936 } 14937 14938 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14939 14940 if (D.getDeclSpec().isInlineSpecified()) 14941 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14942 << getLangOpts().CPlusPlus1z; 14943 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14944 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14945 diag::err_invalid_thread) 14946 << DeclSpec::getSpecifierName(TSCS); 14947 14948 // Check to see if this name was declared as a member previously 14949 NamedDecl *PrevDecl = nullptr; 14950 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 14951 LookupName(Previous, S); 14952 switch (Previous.getResultKind()) { 14953 case LookupResult::Found: 14954 case LookupResult::FoundUnresolvedValue: 14955 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14956 break; 14957 14958 case LookupResult::FoundOverloaded: 14959 PrevDecl = Previous.getRepresentativeDecl(); 14960 break; 14961 14962 case LookupResult::NotFound: 14963 case LookupResult::NotFoundInCurrentInstantiation: 14964 case LookupResult::Ambiguous: 14965 break; 14966 } 14967 14968 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14969 // Maybe we will complain about the shadowed template parameter. 14970 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14971 // Just pretend that we didn't see the previous declaration. 14972 PrevDecl = nullptr; 14973 } 14974 14975 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14976 PrevDecl = nullptr; 14977 14978 SourceLocation TSSL = D.getLocStart(); 14979 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 14980 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 14981 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 14982 ProcessDeclAttributes(TUScope, NewPD, D); 14983 NewPD->setAccess(AS); 14984 14985 if (NewPD->isInvalidDecl()) 14986 Record->setInvalidDecl(); 14987 14988 if (D.getDeclSpec().isModulePrivateSpecified()) 14989 NewPD->setModulePrivate(); 14990 14991 if (NewPD->isInvalidDecl() && PrevDecl) { 14992 // Don't introduce NewFD into scope; there's already something 14993 // with the same name in the same scope. 14994 } else if (II) { 14995 PushOnScopeChains(NewPD, S); 14996 } else 14997 Record->addDecl(NewPD); 14998 14999 return NewPD; 15000 } 15001