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/ComparisonCategories.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/RecordLayout.h" 24 #include "clang/AST/RecursiveASTVisitor.h" 25 #include "clang/AST/StmtVisitor.h" 26 #include "clang/AST/TypeLoc.h" 27 #include "clang/AST/TypeOrdering.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/CXXFieldCollector.h" 33 #include "clang/Sema/DeclSpec.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedTemplate.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "clang/Sema/SemaInternal.h" 40 #include "clang/Sema/Template.h" 41 #include "llvm/ADT/STLExtras.h" 42 #include "llvm/ADT/SmallString.h" 43 #include "llvm/ADT/StringExtras.h" 44 #include <map> 45 #include <set> 46 47 using namespace clang; 48 49 //===----------------------------------------------------------------------===// 50 // CheckDefaultArgumentVisitor 51 //===----------------------------------------------------------------------===// 52 53 namespace { 54 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 55 /// the default argument of a parameter to determine whether it 56 /// contains any ill-formed subexpressions. For example, this will 57 /// diagnose the use of local variables or parameters within the 58 /// default argument expression. 59 class CheckDefaultArgumentVisitor 60 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 61 Expr *DefaultArg; 62 Sema *S; 63 64 public: 65 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 66 : DefaultArg(defarg), S(s) {} 67 68 bool VisitExpr(Expr *Node); 69 bool VisitDeclRefExpr(DeclRefExpr *DRE); 70 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 71 bool VisitLambdaExpr(LambdaExpr *Lambda); 72 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 73 }; 74 75 /// VisitExpr - Visit all of the children of this expression. 76 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 77 bool IsInvalid = false; 78 for (Stmt *SubStmt : Node->children()) 79 IsInvalid |= Visit(SubStmt); 80 return IsInvalid; 81 } 82 83 /// VisitDeclRefExpr - Visit a reference to a declaration, to 84 /// determine whether this declaration can be used in the default 85 /// argument expression. 86 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 87 NamedDecl *Decl = DRE->getDecl(); 88 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 89 // C++ [dcl.fct.default]p9 90 // Default arguments are evaluated each time the function is 91 // called. The order of evaluation of function arguments is 92 // unspecified. Consequently, parameters of a function shall not 93 // be used in default argument expressions, even if they are not 94 // evaluated. Parameters of a function declared before a default 95 // argument expression are in scope and can hide namespace and 96 // class member names. 97 return S->Diag(DRE->getBeginLoc(), 98 diag::err_param_default_argument_references_param) 99 << Param->getDeclName() << DefaultArg->getSourceRange(); 100 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 101 // C++ [dcl.fct.default]p7 102 // Local variables shall not be used in default argument 103 // expressions. 104 if (VDecl->isLocalVarDecl()) 105 return S->Diag(DRE->getBeginLoc(), 106 diag::err_param_default_argument_references_local) 107 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 108 } 109 110 return false; 111 } 112 113 /// VisitCXXThisExpr - Visit a C++ "this" expression. 114 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 115 // C++ [dcl.fct.default]p8: 116 // The keyword this shall not be used in a default argument of a 117 // member function. 118 return S->Diag(ThisE->getBeginLoc(), 119 diag::err_param_default_argument_references_this) 120 << ThisE->getSourceRange(); 121 } 122 123 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 124 bool Invalid = false; 125 for (PseudoObjectExpr::semantics_iterator 126 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 127 Expr *E = *i; 128 129 // Look through bindings. 130 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 131 E = OVE->getSourceExpr(); 132 assert(E && "pseudo-object binding without source expression?"); 133 } 134 135 Invalid |= Visit(E); 136 } 137 return Invalid; 138 } 139 140 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 141 // C++11 [expr.lambda.prim]p13: 142 // A lambda-expression appearing in a default argument shall not 143 // implicitly or explicitly capture any entity. 144 if (Lambda->capture_begin() == Lambda->capture_end()) 145 return false; 146 147 return S->Diag(Lambda->getBeginLoc(), 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 case EST_Unparsed: 175 case EST_Uninstantiated: 176 case EST_Unevaluated: 177 llvm_unreachable("should not see unresolved exception specs here"); 178 179 // If this function can throw any exceptions, make a note of that. 180 case EST_MSAny: 181 case EST_None: 182 // FIXME: Whichever we see last of MSAny and None determines our result. 183 // We should make a consistent, order-independent choice here. 184 ClearExceptions(); 185 ComputedEST = EST; 186 return; 187 case EST_NoexceptFalse: 188 ClearExceptions(); 189 ComputedEST = EST_None; 190 return; 191 // FIXME: If the call to this decl is using any of its default arguments, we 192 // need to search them for potentially-throwing calls. 193 // If this function has a basic noexcept, it doesn't affect the outcome. 194 case EST_BasicNoexcept: 195 case EST_NoexceptTrue: 196 return; 197 // If we're still at noexcept(true) and there's a throw() callee, 198 // change to that specification. 199 case EST_DynamicNone: 200 if (ComputedEST == EST_BasicNoexcept) 201 ComputedEST = EST_DynamicNone; 202 return; 203 case EST_DependentNoexcept: 204 llvm_unreachable( 205 "should not generate implicit declarations for dependent cases"); 206 case EST_Dynamic: 207 break; 208 } 209 assert(EST == EST_Dynamic && "EST case not considered earlier."); 210 assert(ComputedEST != EST_None && 211 "Shouldn't collect exceptions when throw-all is guaranteed."); 212 ComputedEST = EST_Dynamic; 213 // Record the exceptions in this function's exception specification. 214 for (const auto &E : Proto->exceptions()) 215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 216 Exceptions.push_back(E); 217 } 218 219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 220 if (!E || ComputedEST == EST_MSAny) 221 return; 222 223 // FIXME: 224 // 225 // C++0x [except.spec]p14: 226 // [An] implicit exception-specification specifies the type-id T if and 227 // only if T is allowed by the exception-specification of a function directly 228 // invoked by f's implicit definition; f shall allow all exceptions if any 229 // function it directly invokes allows all exceptions, and f shall allow no 230 // exceptions if every function it directly invokes allows no exceptions. 231 // 232 // Note in particular that if an implicit exception-specification is generated 233 // for a function containing a throw-expression, that specification can still 234 // be noexcept(true). 235 // 236 // Note also that 'directly invoked' is not defined in the standard, and there 237 // is no indication that we should only consider potentially-evaluated calls. 238 // 239 // Ultimately we should implement the intent of the standard: the exception 240 // specification should be the set of exceptions which can be thrown by the 241 // implicit definition. For now, we assume that any non-nothrow expression can 242 // throw any exception. 243 244 if (Self->canThrow(E)) 245 ComputedEST = EST_None; 246 } 247 248 bool 249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 250 SourceLocation EqualLoc) { 251 if (RequireCompleteType(Param->getLocation(), Param->getType(), 252 diag::err_typecheck_decl_incomplete_type)) { 253 Param->setInvalidDecl(); 254 return true; 255 } 256 257 // C++ [dcl.fct.default]p5 258 // A default argument expression is implicitly converted (clause 259 // 4) to the parameter type. The default argument expression has 260 // the same semantic constraints as the initializer expression in 261 // a declaration of a variable of the parameter type, using the 262 // copy-initialization semantics (8.5). 263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 264 Param); 265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 266 EqualLoc); 267 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 269 if (Result.isInvalid()) 270 return true; 271 Arg = Result.getAs<Expr>(); 272 273 CheckCompletedExpr(Arg, EqualLoc); 274 Arg = MaybeCreateExprWithCleanups(Arg); 275 276 // Okay: add the default argument to the parameter 277 Param->setDefaultArg(Arg); 278 279 // We have already instantiated this parameter; provide each of the 280 // instantiations with the uninstantiated default argument. 281 UnparsedDefaultArgInstantiationsMap::iterator InstPos 282 = UnparsedDefaultArgInstantiations.find(Param); 283 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 286 287 // We're done tracking this parameter's instantiations. 288 UnparsedDefaultArgInstantiations.erase(InstPos); 289 } 290 291 return false; 292 } 293 294 /// ActOnParamDefaultArgument - Check whether the default argument 295 /// provided for a function parameter is well-formed. If so, attach it 296 /// to the parameter declaration. 297 void 298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 299 Expr *DefaultArg) { 300 if (!param || !DefaultArg) 301 return; 302 303 ParmVarDecl *Param = cast<ParmVarDecl>(param); 304 UnparsedDefaultArgLocs.erase(Param); 305 306 // Default arguments are only permitted in C++ 307 if (!getLangOpts().CPlusPlus) { 308 Diag(EqualLoc, diag::err_param_default_argument) 309 << DefaultArg->getSourceRange(); 310 Param->setInvalidDecl(); 311 return; 312 } 313 314 // Check for unexpanded parameter packs. 315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 316 Param->setInvalidDecl(); 317 return; 318 } 319 320 // C++11 [dcl.fct.default]p3 321 // A default argument expression [...] shall not be specified for a 322 // parameter pack. 323 if (Param->isParameterPack()) { 324 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 325 << DefaultArg->getSourceRange(); 326 return; 327 } 328 329 // Check that the default argument is well-formed 330 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 331 if (DefaultArgChecker.Visit(DefaultArg)) { 332 Param->setInvalidDecl(); 333 return; 334 } 335 336 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 337 } 338 339 /// ActOnParamUnparsedDefaultArgument - We've seen a default 340 /// argument for a function parameter, but we can't parse it yet 341 /// because we're inside a class definition. Note that this default 342 /// argument will be parsed later. 343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 344 SourceLocation EqualLoc, 345 SourceLocation ArgLoc) { 346 if (!param) 347 return; 348 349 ParmVarDecl *Param = cast<ParmVarDecl>(param); 350 Param->setUnparsedDefaultArg(); 351 UnparsedDefaultArgLocs[Param] = ArgLoc; 352 } 353 354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 355 /// the default argument for the parameter param failed. 356 void Sema::ActOnParamDefaultArgumentError(Decl *param, 357 SourceLocation EqualLoc) { 358 if (!param) 359 return; 360 361 ParmVarDecl *Param = cast<ParmVarDecl>(param); 362 Param->setInvalidDecl(); 363 UnparsedDefaultArgLocs.erase(Param); 364 Param->setDefaultArg(new(Context) 365 OpaqueValueExpr(EqualLoc, 366 Param->getType().getNonReferenceType(), 367 VK_RValue)); 368 } 369 370 /// CheckExtraCXXDefaultArguments - Check for any extra default 371 /// arguments in the declarator, which is not a function declaration 372 /// or definition and therefore is not permitted to have default 373 /// arguments. This routine should be invoked for every declarator 374 /// that is not a function declaration or definition. 375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 376 // C++ [dcl.fct.default]p3 377 // A default argument expression shall be specified only in the 378 // parameter-declaration-clause of a function declaration or in a 379 // template-parameter (14.1). It shall not be specified for a 380 // parameter pack. If it is specified in a 381 // parameter-declaration-clause, it shall not occur within a 382 // declarator or abstract-declarator of a parameter-declaration. 383 bool MightBeFunction = D.isFunctionDeclarationContext(); 384 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 385 DeclaratorChunk &chunk = D.getTypeObject(i); 386 if (chunk.Kind == DeclaratorChunk::Function) { 387 if (MightBeFunction) { 388 // This is a function declaration. It can have default arguments, but 389 // keep looking in case its return type is a function type with default 390 // arguments. 391 MightBeFunction = false; 392 continue; 393 } 394 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 395 ++argIdx) { 396 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 397 if (Param->hasUnparsedDefaultArg()) { 398 std::unique_ptr<CachedTokens> Toks = 399 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 400 SourceRange SR; 401 if (Toks->size() > 1) 402 SR = SourceRange((*Toks)[1].getLocation(), 403 Toks->back().getLocation()); 404 else 405 SR = UnparsedDefaultArgLocs[Param]; 406 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 407 << SR; 408 } else if (Param->getDefaultArg()) { 409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 410 << Param->getDefaultArg()->getSourceRange(); 411 Param->setDefaultArg(nullptr); 412 } 413 } 414 } else if (chunk.Kind != DeclaratorChunk::Paren) { 415 MightBeFunction = false; 416 } 417 } 418 } 419 420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 423 if (!PVD->hasDefaultArg()) 424 return false; 425 if (!PVD->hasInheritedDefaultArg()) 426 return true; 427 } 428 return false; 429 } 430 431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 432 /// function, once we already know that they have the same 433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 434 /// error, false otherwise. 435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 436 Scope *S) { 437 bool Invalid = false; 438 439 // The declaration context corresponding to the scope is the semantic 440 // parent, unless this is a local function declaration, in which case 441 // it is that surrounding function. 442 DeclContext *ScopeDC = New->isLocalExternDecl() 443 ? New->getLexicalDeclContext() 444 : New->getDeclContext(); 445 446 // Find the previous declaration for the purpose of default arguments. 447 FunctionDecl *PrevForDefaultArgs = Old; 448 for (/**/; PrevForDefaultArgs; 449 // Don't bother looking back past the latest decl if this is a local 450 // extern declaration; nothing else could work. 451 PrevForDefaultArgs = New->isLocalExternDecl() 452 ? nullptr 453 : PrevForDefaultArgs->getPreviousDecl()) { 454 // Ignore hidden declarations. 455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 456 continue; 457 458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 459 !New->isCXXClassMember()) { 460 // Ignore default arguments of old decl if they are not in 461 // the same scope and this is not an out-of-line definition of 462 // a member function. 463 continue; 464 } 465 466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 467 // If only one of these is a local function declaration, then they are 468 // declared in different scopes, even though isDeclInScope may think 469 // they're in the same scope. (If both are local, the scope check is 470 // sufficient, and if neither is local, then they are in the same scope.) 471 continue; 472 } 473 474 // We found the right previous declaration. 475 break; 476 } 477 478 // C++ [dcl.fct.default]p4: 479 // For non-template functions, default arguments can be added in 480 // later declarations of a function in the same 481 // scope. Declarations in different scopes have completely 482 // distinct sets of default arguments. That is, declarations in 483 // inner scopes do not acquire default arguments from 484 // declarations in outer scopes, and vice versa. In a given 485 // function declaration, all parameters subsequent to a 486 // parameter with a default argument shall have default 487 // arguments supplied in this or previous declarations. A 488 // default argument shall not be redefined by a later 489 // declaration (not even to the same value). 490 // 491 // C++ [dcl.fct.default]p6: 492 // Except for member functions of class templates, the default arguments 493 // in a member function definition that appears outside of the class 494 // definition are added to the set of default arguments provided by the 495 // member function declaration in the class definition. 496 for (unsigned p = 0, NumParams = PrevForDefaultArgs 497 ? PrevForDefaultArgs->getNumParams() 498 : 0; 499 p < NumParams; ++p) { 500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 501 ParmVarDecl *NewParam = New->getParamDecl(p); 502 503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 504 bool NewParamHasDfl = NewParam->hasDefaultArg(); 505 506 if (OldParamHasDfl && NewParamHasDfl) { 507 unsigned DiagDefaultParamID = 508 diag::err_param_default_argument_redefinition; 509 510 // MSVC accepts that default parameters be redefined for member functions 511 // of template class. The new default parameter's value is ignored. 512 Invalid = true; 513 if (getLangOpts().MicrosoftExt) { 514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 515 if (MD && MD->getParent()->getDescribedClassTemplate()) { 516 // Merge the old default argument into the new parameter. 517 NewParam->setHasInheritedDefaultArg(); 518 if (OldParam->hasUninstantiatedDefaultArg()) 519 NewParam->setUninstantiatedDefaultArg( 520 OldParam->getUninstantiatedDefaultArg()); 521 else 522 NewParam->setDefaultArg(OldParam->getInit()); 523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 524 Invalid = false; 525 } 526 } 527 528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 529 // hint here. Alternatively, we could walk the type-source information 530 // for NewParam to find the last source location in the type... but it 531 // isn't worth the effort right now. This is the kind of test case that 532 // is hard to get right: 533 // int f(int); 534 // void g(int (*fp)(int) = f); 535 // void g(int (*fp)(int) = &f); 536 Diag(NewParam->getLocation(), DiagDefaultParamID) 537 << NewParam->getDefaultArgRange(); 538 539 // Look for the function declaration where the default argument was 540 // actually written, which may be a declaration prior to Old. 541 for (auto Older = PrevForDefaultArgs; 542 OldParam->hasInheritedDefaultArg(); /**/) { 543 Older = Older->getPreviousDecl(); 544 OldParam = Older->getParamDecl(p); 545 } 546 547 Diag(OldParam->getLocation(), diag::note_previous_definition) 548 << OldParam->getDefaultArgRange(); 549 } else if (OldParamHasDfl) { 550 // Merge the old default argument into the new parameter unless the new 551 // function is a friend declaration in a template class. In the latter 552 // case the default arguments will be inherited when the friend 553 // declaration will be instantiated. 554 if (New->getFriendObjectKind() == Decl::FOK_None || 555 !New->getLexicalDeclContext()->isDependentContext()) { 556 // It's important to use getInit() here; getDefaultArg() 557 // strips off any top-level ExprWithCleanups. 558 NewParam->setHasInheritedDefaultArg(); 559 if (OldParam->hasUnparsedDefaultArg()) 560 NewParam->setUnparsedDefaultArg(); 561 else if (OldParam->hasUninstantiatedDefaultArg()) 562 NewParam->setUninstantiatedDefaultArg( 563 OldParam->getUninstantiatedDefaultArg()); 564 else 565 NewParam->setDefaultArg(OldParam->getInit()); 566 } 567 } else if (NewParamHasDfl) { 568 if (New->getDescribedFunctionTemplate()) { 569 // Paragraph 4, quoted above, only applies to non-template functions. 570 Diag(NewParam->getLocation(), 571 diag::err_param_default_argument_template_redecl) 572 << NewParam->getDefaultArgRange(); 573 Diag(PrevForDefaultArgs->getLocation(), 574 diag::note_template_prev_declaration) 575 << false; 576 } else if (New->getTemplateSpecializationKind() 577 != TSK_ImplicitInstantiation && 578 New->getTemplateSpecializationKind() != TSK_Undeclared) { 579 // C++ [temp.expr.spec]p21: 580 // Default function arguments shall not be specified in a declaration 581 // or a definition for one of the following explicit specializations: 582 // - the explicit specialization of a function template; 583 // - the explicit specialization of a member function template; 584 // - the explicit specialization of a member function of a class 585 // template where the class template specialization to which the 586 // member function specialization belongs is implicitly 587 // instantiated. 588 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 589 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 590 << New->getDeclName() 591 << NewParam->getDefaultArgRange(); 592 } else if (New->getDeclContext()->isDependentContext()) { 593 // C++ [dcl.fct.default]p6 (DR217): 594 // Default arguments for a member function of a class template shall 595 // be specified on the initial declaration of the member function 596 // within the class template. 597 // 598 // Reading the tea leaves a bit in DR217 and its reference to DR205 599 // leads me to the conclusion that one cannot add default function 600 // arguments for an out-of-line definition of a member function of a 601 // dependent type. 602 int WhichKind = 2; 603 if (CXXRecordDecl *Record 604 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 605 if (Record->getDescribedClassTemplate()) 606 WhichKind = 0; 607 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 608 WhichKind = 1; 609 else 610 WhichKind = 2; 611 } 612 613 Diag(NewParam->getLocation(), 614 diag::err_param_default_argument_member_template_redecl) 615 << WhichKind 616 << NewParam->getDefaultArgRange(); 617 } 618 } 619 } 620 621 // DR1344: If a default argument is added outside a class definition and that 622 // default argument makes the function a special member function, the program 623 // is ill-formed. This can only happen for constructors. 624 if (isa<CXXConstructorDecl>(New) && 625 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 626 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 627 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 628 if (NewSM != OldSM) { 629 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 630 assert(NewParam->hasDefaultArg()); 631 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 632 << NewParam->getDefaultArgRange() << NewSM; 633 Diag(Old->getLocation(), diag::note_previous_declaration); 634 } 635 } 636 637 const FunctionDecl *Def; 638 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 639 // template has a constexpr specifier then all its declarations shall 640 // contain the constexpr specifier. 641 if (New->isConstexpr() != Old->isConstexpr()) { 642 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 643 << New << New->isConstexpr(); 644 Diag(Old->getLocation(), diag::note_previous_declaration); 645 Invalid = true; 646 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 647 Old->isDefined(Def) && 648 // If a friend function is inlined but does not have 'inline' 649 // specifier, it is a definition. Do not report attribute conflict 650 // in this case, redefinition will be diagnosed later. 651 (New->isInlineSpecified() || 652 New->getFriendObjectKind() == Decl::FOK_None)) { 653 // C++11 [dcl.fcn.spec]p4: 654 // If the definition of a function appears in a translation unit before its 655 // first declaration as inline, the program is ill-formed. 656 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 657 Diag(Def->getLocation(), diag::note_previous_definition); 658 Invalid = true; 659 } 660 661 // FIXME: It's not clear what should happen if multiple declarations of a 662 // deduction guide have different explicitness. For now at least we simply 663 // reject any case where the explicitness changes. 664 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New); 665 if (NewGuide && NewGuide->isExplicitSpecified() != 666 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) { 667 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch) 668 << NewGuide->isExplicitSpecified(); 669 Diag(Old->getLocation(), diag::note_previous_declaration); 670 } 671 672 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 673 // argument expression, that declaration shall be a definition and shall be 674 // the only declaration of the function or function template in the 675 // translation unit. 676 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 677 functionDeclHasDefaultArgument(Old)) { 678 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 679 Diag(Old->getLocation(), diag::note_previous_declaration); 680 Invalid = true; 681 } 682 683 return Invalid; 684 } 685 686 NamedDecl * 687 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 688 MultiTemplateParamsArg TemplateParamLists) { 689 assert(D.isDecompositionDeclarator()); 690 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 691 692 // The syntax only allows a decomposition declarator as a simple-declaration, 693 // a for-range-declaration, or a condition in Clang, but we parse it in more 694 // cases than that. 695 if (!D.mayHaveDecompositionDeclarator()) { 696 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 697 << Decomp.getSourceRange(); 698 return nullptr; 699 } 700 701 if (!TemplateParamLists.empty()) { 702 // FIXME: There's no rule against this, but there are also no rules that 703 // would actually make it usable, so we reject it for now. 704 Diag(TemplateParamLists.front()->getTemplateLoc(), 705 diag::err_decomp_decl_template); 706 return nullptr; 707 } 708 709 Diag(Decomp.getLSquareLoc(), 710 !getLangOpts().CPlusPlus17 711 ? diag::ext_decomp_decl 712 : D.getContext() == DeclaratorContext::ConditionContext 713 ? diag::ext_decomp_decl_cond 714 : diag::warn_cxx14_compat_decomp_decl) 715 << Decomp.getSourceRange(); 716 717 // The semantic context is always just the current context. 718 DeclContext *const DC = CurContext; 719 720 // C++1z [dcl.dcl]/8: 721 // The decl-specifier-seq shall contain only the type-specifier auto 722 // and cv-qualifiers. 723 auto &DS = D.getDeclSpec(); 724 { 725 SmallVector<StringRef, 8> BadSpecifiers; 726 SmallVector<SourceLocation, 8> BadSpecifierLocs; 727 if (auto SCS = DS.getStorageClassSpec()) { 728 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 729 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 730 } 731 if (auto TSCS = DS.getThreadStorageClassSpec()) { 732 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 733 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 734 } 735 if (DS.isConstexprSpecified()) { 736 BadSpecifiers.push_back("constexpr"); 737 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 738 } 739 if (DS.isInlineSpecified()) { 740 BadSpecifiers.push_back("inline"); 741 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 742 } 743 if (!BadSpecifiers.empty()) { 744 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 745 Err << (int)BadSpecifiers.size() 746 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 747 // Don't add FixItHints to remove the specifiers; we do still respect 748 // them when building the underlying variable. 749 for (auto Loc : BadSpecifierLocs) 750 Err << SourceRange(Loc, Loc); 751 } 752 // We can't recover from it being declared as a typedef. 753 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 754 return nullptr; 755 } 756 757 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 758 QualType R = TInfo->getType(); 759 760 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 761 UPPC_DeclarationType)) 762 D.setInvalidType(); 763 764 // The syntax only allows a single ref-qualifier prior to the decomposition 765 // declarator. No other declarator chunks are permitted. Also check the type 766 // specifier here. 767 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 768 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 769 (D.getNumTypeObjects() == 1 && 770 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 771 Diag(Decomp.getLSquareLoc(), 772 (D.hasGroupingParens() || 773 (D.getNumTypeObjects() && 774 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 775 ? diag::err_decomp_decl_parens 776 : diag::err_decomp_decl_type) 777 << R; 778 779 // In most cases, there's no actual problem with an explicitly-specified 780 // type, but a function type won't work here, and ActOnVariableDeclarator 781 // shouldn't be called for such a type. 782 if (R->isFunctionType()) 783 D.setInvalidType(); 784 } 785 786 // Build the BindingDecls. 787 SmallVector<BindingDecl*, 8> Bindings; 788 789 // Build the BindingDecls. 790 for (auto &B : D.getDecompositionDeclarator().bindings()) { 791 // Check for name conflicts. 792 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 793 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 794 ForVisibleRedeclaration); 795 LookupName(Previous, S, 796 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 797 798 // It's not permitted to shadow a template parameter name. 799 if (Previous.isSingleResult() && 800 Previous.getFoundDecl()->isTemplateParameter()) { 801 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 802 Previous.getFoundDecl()); 803 Previous.clear(); 804 } 805 806 bool ConsiderLinkage = DC->isFunctionOrMethod() && 807 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 808 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 809 /*AllowInlineNamespace*/false); 810 if (!Previous.empty()) { 811 auto *Old = Previous.getRepresentativeDecl(); 812 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 813 Diag(Old->getLocation(), diag::note_previous_definition); 814 } 815 816 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 817 PushOnScopeChains(BD, S, true); 818 Bindings.push_back(BD); 819 ParsingInitForAutoVars.insert(BD); 820 } 821 822 // There are no prior lookup results for the variable itself, because it 823 // is unnamed. 824 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 825 Decomp.getLSquareLoc()); 826 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 827 ForVisibleRedeclaration); 828 829 // Build the variable that holds the non-decomposed object. 830 bool AddToScope = true; 831 NamedDecl *New = 832 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 833 MultiTemplateParamsArg(), AddToScope, Bindings); 834 if (AddToScope) { 835 S->AddDecl(New); 836 CurContext->addHiddenDecl(New); 837 } 838 839 if (isInOpenMPDeclareTargetContext()) 840 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 841 842 return New; 843 } 844 845 static bool checkSimpleDecomposition( 846 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 847 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 848 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 849 if ((int64_t)Bindings.size() != NumElems) { 850 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 851 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 852 << (NumElems < Bindings.size()); 853 return true; 854 } 855 856 unsigned I = 0; 857 for (auto *B : Bindings) { 858 SourceLocation Loc = B->getLocation(); 859 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 860 if (E.isInvalid()) 861 return true; 862 E = GetInit(Loc, E.get(), I++); 863 if (E.isInvalid()) 864 return true; 865 B->setBinding(ElemType, E.get()); 866 } 867 868 return false; 869 } 870 871 static bool checkArrayLikeDecomposition(Sema &S, 872 ArrayRef<BindingDecl *> Bindings, 873 ValueDecl *Src, QualType DecompType, 874 const llvm::APSInt &NumElems, 875 QualType ElemType) { 876 return checkSimpleDecomposition( 877 S, Bindings, Src, DecompType, NumElems, ElemType, 878 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 879 ExprResult E = S.ActOnIntegerConstant(Loc, I); 880 if (E.isInvalid()) 881 return ExprError(); 882 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 883 }); 884 } 885 886 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 887 ValueDecl *Src, QualType DecompType, 888 const ConstantArrayType *CAT) { 889 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 890 llvm::APSInt(CAT->getSize()), 891 CAT->getElementType()); 892 } 893 894 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 895 ValueDecl *Src, QualType DecompType, 896 const VectorType *VT) { 897 return checkArrayLikeDecomposition( 898 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 899 S.Context.getQualifiedType(VT->getElementType(), 900 DecompType.getQualifiers())); 901 } 902 903 static bool checkComplexDecomposition(Sema &S, 904 ArrayRef<BindingDecl *> Bindings, 905 ValueDecl *Src, QualType DecompType, 906 const ComplexType *CT) { 907 return checkSimpleDecomposition( 908 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 909 S.Context.getQualifiedType(CT->getElementType(), 910 DecompType.getQualifiers()), 911 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 912 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 913 }); 914 } 915 916 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 917 TemplateArgumentListInfo &Args) { 918 SmallString<128> SS; 919 llvm::raw_svector_ostream OS(SS); 920 bool First = true; 921 for (auto &Arg : Args.arguments()) { 922 if (!First) 923 OS << ", "; 924 Arg.getArgument().print(PrintingPolicy, OS); 925 First = false; 926 } 927 return OS.str(); 928 } 929 930 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 931 SourceLocation Loc, StringRef Trait, 932 TemplateArgumentListInfo &Args, 933 unsigned DiagID) { 934 auto DiagnoseMissing = [&] { 935 if (DiagID) 936 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 937 Args); 938 return true; 939 }; 940 941 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 942 NamespaceDecl *Std = S.getStdNamespace(); 943 if (!Std) 944 return DiagnoseMissing(); 945 946 // Look up the trait itself, within namespace std. We can diagnose various 947 // problems with this lookup even if we've been asked to not diagnose a 948 // missing specialization, because this can only fail if the user has been 949 // declaring their own names in namespace std or we don't support the 950 // standard library implementation in use. 951 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 952 Loc, Sema::LookupOrdinaryName); 953 if (!S.LookupQualifiedName(Result, Std)) 954 return DiagnoseMissing(); 955 if (Result.isAmbiguous()) 956 return true; 957 958 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 959 if (!TraitTD) { 960 Result.suppressDiagnostics(); 961 NamedDecl *Found = *Result.begin(); 962 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 963 S.Diag(Found->getLocation(), diag::note_declared_at); 964 return true; 965 } 966 967 // Build the template-id. 968 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 969 if (TraitTy.isNull()) 970 return true; 971 if (!S.isCompleteType(Loc, TraitTy)) { 972 if (DiagID) 973 S.RequireCompleteType( 974 Loc, TraitTy, DiagID, 975 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 976 return true; 977 } 978 979 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 980 assert(RD && "specialization of class template is not a class?"); 981 982 // Look up the member of the trait type. 983 S.LookupQualifiedName(TraitMemberLookup, RD); 984 return TraitMemberLookup.isAmbiguous(); 985 } 986 987 static TemplateArgumentLoc 988 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 989 uint64_t I) { 990 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 991 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 992 } 993 994 static TemplateArgumentLoc 995 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 996 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 997 } 998 999 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1000 1001 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1002 llvm::APSInt &Size) { 1003 EnterExpressionEvaluationContext ContextRAII( 1004 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1005 1006 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1007 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1008 1009 // Form template argument list for tuple_size<T>. 1010 TemplateArgumentListInfo Args(Loc, Loc); 1011 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1012 1013 // If there's no tuple_size specialization, it's not tuple-like. 1014 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0)) 1015 return IsTupleLike::NotTupleLike; 1016 1017 // If we get this far, we've committed to the tuple interpretation, but 1018 // we can still fail if there actually isn't a usable ::value. 1019 1020 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1021 LookupResult &R; 1022 TemplateArgumentListInfo &Args; 1023 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1024 : R(R), Args(Args) {} 1025 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1026 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1027 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1028 } 1029 } Diagnoser(R, Args); 1030 1031 if (R.empty()) { 1032 Diagnoser.diagnoseNotICE(S, Loc, SourceRange()); 1033 return IsTupleLike::Error; 1034 } 1035 1036 ExprResult E = 1037 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1038 if (E.isInvalid()) 1039 return IsTupleLike::Error; 1040 1041 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1042 if (E.isInvalid()) 1043 return IsTupleLike::Error; 1044 1045 return IsTupleLike::TupleLike; 1046 } 1047 1048 /// \return std::tuple_element<I, T>::type. 1049 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1050 unsigned I, QualType T) { 1051 // Form template argument list for tuple_element<I, T>. 1052 TemplateArgumentListInfo Args(Loc, Loc); 1053 Args.addArgument( 1054 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1055 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1056 1057 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1058 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1059 if (lookupStdTypeTraitMember( 1060 S, R, Loc, "tuple_element", Args, 1061 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1062 return QualType(); 1063 1064 auto *TD = R.getAsSingle<TypeDecl>(); 1065 if (!TD) { 1066 R.suppressDiagnostics(); 1067 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1068 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1069 if (!R.empty()) 1070 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1071 return QualType(); 1072 } 1073 1074 return S.Context.getTypeDeclType(TD); 1075 } 1076 1077 namespace { 1078 struct BindingDiagnosticTrap { 1079 Sema &S; 1080 DiagnosticErrorTrap Trap; 1081 BindingDecl *BD; 1082 1083 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1084 : S(S), Trap(S.Diags), BD(BD) {} 1085 ~BindingDiagnosticTrap() { 1086 if (Trap.hasErrorOccurred()) 1087 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1088 } 1089 }; 1090 } 1091 1092 static bool checkTupleLikeDecomposition(Sema &S, 1093 ArrayRef<BindingDecl *> Bindings, 1094 VarDecl *Src, QualType DecompType, 1095 const llvm::APSInt &TupleSize) { 1096 if ((int64_t)Bindings.size() != TupleSize) { 1097 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1098 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1099 << (TupleSize < Bindings.size()); 1100 return true; 1101 } 1102 1103 if (Bindings.empty()) 1104 return false; 1105 1106 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1107 1108 // [dcl.decomp]p3: 1109 // The unqualified-id get is looked up in the scope of E by class member 1110 // access lookup ... 1111 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1112 bool UseMemberGet = false; 1113 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1114 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1115 S.LookupQualifiedName(MemberGet, RD); 1116 if (MemberGet.isAmbiguous()) 1117 return true; 1118 // ... and if that finds at least one declaration that is a function 1119 // template whose first template parameter is a non-type parameter ... 1120 for (NamedDecl *D : MemberGet) { 1121 if (FunctionTemplateDecl *FTD = 1122 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1123 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1124 if (TPL->size() != 0 && 1125 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1126 // ... the initializer is e.get<i>(). 1127 UseMemberGet = true; 1128 break; 1129 } 1130 } 1131 } 1132 S.FilterAcceptableTemplateNames(MemberGet); 1133 } 1134 1135 unsigned I = 0; 1136 for (auto *B : Bindings) { 1137 BindingDiagnosticTrap Trap(S, B); 1138 SourceLocation Loc = B->getLocation(); 1139 1140 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1141 if (E.isInvalid()) 1142 return true; 1143 1144 // e is an lvalue if the type of the entity is an lvalue reference and 1145 // an xvalue otherwise 1146 if (!Src->getType()->isLValueReferenceType()) 1147 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1148 E.get(), nullptr, VK_XValue); 1149 1150 TemplateArgumentListInfo Args(Loc, Loc); 1151 Args.addArgument( 1152 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1153 1154 if (UseMemberGet) { 1155 // if [lookup of member get] finds at least one declaration, the 1156 // initializer is e.get<i-1>(). 1157 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1158 CXXScopeSpec(), SourceLocation(), nullptr, 1159 MemberGet, &Args, nullptr); 1160 if (E.isInvalid()) 1161 return true; 1162 1163 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc); 1164 } else { 1165 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1166 // in the associated namespaces. 1167 Expr *Get = UnresolvedLookupExpr::Create( 1168 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1169 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1170 UnresolvedSetIterator(), UnresolvedSetIterator()); 1171 1172 Expr *Arg = E.get(); 1173 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc); 1174 } 1175 if (E.isInvalid()) 1176 return true; 1177 Expr *Init = E.get(); 1178 1179 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1180 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1181 if (T.isNull()) 1182 return true; 1183 1184 // each vi is a variable of type "reference to T" initialized with the 1185 // initializer, where the reference is an lvalue reference if the 1186 // initializer is an lvalue and an rvalue reference otherwise 1187 QualType RefType = 1188 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1189 if (RefType.isNull()) 1190 return true; 1191 auto *RefVD = VarDecl::Create( 1192 S.Context, Src->getDeclContext(), Loc, Loc, 1193 B->getDeclName().getAsIdentifierInfo(), RefType, 1194 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1195 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1196 RefVD->setTSCSpec(Src->getTSCSpec()); 1197 RefVD->setImplicit(); 1198 if (Src->isInlineSpecified()) 1199 RefVD->setInlineSpecified(); 1200 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1201 1202 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1203 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1204 InitializationSequence Seq(S, Entity, Kind, Init); 1205 E = Seq.Perform(S, Entity, Kind, Init); 1206 if (E.isInvalid()) 1207 return true; 1208 E = S.ActOnFinishFullExpr(E.get(), Loc); 1209 if (E.isInvalid()) 1210 return true; 1211 RefVD->setInit(E.get()); 1212 RefVD->checkInitIsICE(); 1213 1214 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1215 DeclarationNameInfo(B->getDeclName(), Loc), 1216 RefVD); 1217 if (E.isInvalid()) 1218 return true; 1219 1220 B->setBinding(T, E.get()); 1221 I++; 1222 } 1223 1224 return false; 1225 } 1226 1227 /// Find the base class to decompose in a built-in decomposition of a class type. 1228 /// This base class search is, unfortunately, not quite like any other that we 1229 /// perform anywhere else in C++. 1230 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1231 const CXXRecordDecl *RD, 1232 CXXCastPath &BasePath) { 1233 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1234 CXXBasePath &Path) { 1235 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1236 }; 1237 1238 const CXXRecordDecl *ClassWithFields = nullptr; 1239 AccessSpecifier AS = AS_public; 1240 if (RD->hasDirectFields()) 1241 // [dcl.decomp]p4: 1242 // Otherwise, all of E's non-static data members shall be public direct 1243 // members of E ... 1244 ClassWithFields = RD; 1245 else { 1246 // ... or of ... 1247 CXXBasePaths Paths; 1248 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1249 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1250 // If no classes have fields, just decompose RD itself. (This will work 1251 // if and only if zero bindings were provided.) 1252 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1253 } 1254 1255 CXXBasePath *BestPath = nullptr; 1256 for (auto &P : Paths) { 1257 if (!BestPath) 1258 BestPath = &P; 1259 else if (!S.Context.hasSameType(P.back().Base->getType(), 1260 BestPath->back().Base->getType())) { 1261 // ... the same ... 1262 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1263 << false << RD << BestPath->back().Base->getType() 1264 << P.back().Base->getType(); 1265 return DeclAccessPair(); 1266 } else if (P.Access < BestPath->Access) { 1267 BestPath = &P; 1268 } 1269 } 1270 1271 // ... unambiguous ... 1272 QualType BaseType = BestPath->back().Base->getType(); 1273 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1274 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1275 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1276 return DeclAccessPair(); 1277 } 1278 1279 // ... [accessible, implied by other rules] base class of E. 1280 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1281 *BestPath, diag::err_decomp_decl_inaccessible_base); 1282 AS = BestPath->Access; 1283 1284 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1285 S.BuildBasePathArray(Paths, BasePath); 1286 } 1287 1288 // The above search did not check whether the selected class itself has base 1289 // classes with fields, so check that now. 1290 CXXBasePaths Paths; 1291 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1292 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1293 << (ClassWithFields == RD) << RD << ClassWithFields 1294 << Paths.front().back().Base->getType(); 1295 return DeclAccessPair(); 1296 } 1297 1298 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1299 } 1300 1301 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1302 ValueDecl *Src, QualType DecompType, 1303 const CXXRecordDecl *OrigRD) { 1304 CXXCastPath BasePath; 1305 DeclAccessPair BasePair = 1306 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1307 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1308 if (!RD) 1309 return true; 1310 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1311 DecompType.getQualifiers()); 1312 1313 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1314 unsigned NumFields = 1315 std::count_if(RD->field_begin(), RD->field_end(), 1316 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1317 assert(Bindings.size() != NumFields); 1318 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1319 << DecompType << (unsigned)Bindings.size() << NumFields 1320 << (NumFields < Bindings.size()); 1321 return true; 1322 }; 1323 1324 // all of E's non-static data members shall be [...] well-formed 1325 // when named as e.name in the context of the structured binding, 1326 // E shall not have an anonymous union member, ... 1327 unsigned I = 0; 1328 for (auto *FD : RD->fields()) { 1329 if (FD->isUnnamedBitfield()) 1330 continue; 1331 1332 if (FD->isAnonymousStructOrUnion()) { 1333 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1334 << DecompType << FD->getType()->isUnionType(); 1335 S.Diag(FD->getLocation(), diag::note_declared_at); 1336 return true; 1337 } 1338 1339 // We have a real field to bind. 1340 if (I >= Bindings.size()) 1341 return DiagnoseBadNumberOfBindings(); 1342 auto *B = Bindings[I++]; 1343 SourceLocation Loc = B->getLocation(); 1344 1345 // The field must be accessible in the context of the structured binding. 1346 // We already checked that the base class is accessible. 1347 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1348 // const_cast here. 1349 S.CheckStructuredBindingMemberAccess( 1350 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1351 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1352 BasePair.getAccess(), FD->getAccess()))); 1353 1354 // Initialize the binding to Src.FD. 1355 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1356 if (E.isInvalid()) 1357 return true; 1358 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1359 VK_LValue, &BasePath); 1360 if (E.isInvalid()) 1361 return true; 1362 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1363 CXXScopeSpec(), FD, 1364 DeclAccessPair::make(FD, FD->getAccess()), 1365 DeclarationNameInfo(FD->getDeclName(), Loc)); 1366 if (E.isInvalid()) 1367 return true; 1368 1369 // If the type of the member is T, the referenced type is cv T, where cv is 1370 // the cv-qualification of the decomposition expression. 1371 // 1372 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1373 // 'const' to the type of the field. 1374 Qualifiers Q = DecompType.getQualifiers(); 1375 if (FD->isMutable()) 1376 Q.removeConst(); 1377 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1378 } 1379 1380 if (I != Bindings.size()) 1381 return DiagnoseBadNumberOfBindings(); 1382 1383 return false; 1384 } 1385 1386 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1387 QualType DecompType = DD->getType(); 1388 1389 // If the type of the decomposition is dependent, then so is the type of 1390 // each binding. 1391 if (DecompType->isDependentType()) { 1392 for (auto *B : DD->bindings()) 1393 B->setType(Context.DependentTy); 1394 return; 1395 } 1396 1397 DecompType = DecompType.getNonReferenceType(); 1398 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1399 1400 // C++1z [dcl.decomp]/2: 1401 // If E is an array type [...] 1402 // As an extension, we also support decomposition of built-in complex and 1403 // vector types. 1404 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1405 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1406 DD->setInvalidDecl(); 1407 return; 1408 } 1409 if (auto *VT = DecompType->getAs<VectorType>()) { 1410 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1411 DD->setInvalidDecl(); 1412 return; 1413 } 1414 if (auto *CT = DecompType->getAs<ComplexType>()) { 1415 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1416 DD->setInvalidDecl(); 1417 return; 1418 } 1419 1420 // C++1z [dcl.decomp]/3: 1421 // if the expression std::tuple_size<E>::value is a well-formed integral 1422 // constant expression, [...] 1423 llvm::APSInt TupleSize(32); 1424 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1425 case IsTupleLike::Error: 1426 DD->setInvalidDecl(); 1427 return; 1428 1429 case IsTupleLike::TupleLike: 1430 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1431 DD->setInvalidDecl(); 1432 return; 1433 1434 case IsTupleLike::NotTupleLike: 1435 break; 1436 } 1437 1438 // C++1z [dcl.dcl]/8: 1439 // [E shall be of array or non-union class type] 1440 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1441 if (!RD || RD->isUnion()) { 1442 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1443 << DD << !RD << DecompType; 1444 DD->setInvalidDecl(); 1445 return; 1446 } 1447 1448 // C++1z [dcl.decomp]/4: 1449 // all of E's non-static data members shall be [...] direct members of 1450 // E or of the same unambiguous public base class of E, ... 1451 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1452 DD->setInvalidDecl(); 1453 } 1454 1455 /// Merge the exception specifications of two variable declarations. 1456 /// 1457 /// This is called when there's a redeclaration of a VarDecl. The function 1458 /// checks if the redeclaration might have an exception specification and 1459 /// validates compatibility and merges the specs if necessary. 1460 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1461 // Shortcut if exceptions are disabled. 1462 if (!getLangOpts().CXXExceptions) 1463 return; 1464 1465 assert(Context.hasSameType(New->getType(), Old->getType()) && 1466 "Should only be called if types are otherwise the same."); 1467 1468 QualType NewType = New->getType(); 1469 QualType OldType = Old->getType(); 1470 1471 // We're only interested in pointers and references to functions, as well 1472 // as pointers to member functions. 1473 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1474 NewType = R->getPointeeType(); 1475 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1476 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1477 NewType = P->getPointeeType(); 1478 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1479 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1480 NewType = M->getPointeeType(); 1481 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1482 } 1483 1484 if (!NewType->isFunctionProtoType()) 1485 return; 1486 1487 // There's lots of special cases for functions. For function pointers, system 1488 // libraries are hopefully not as broken so that we don't need these 1489 // workarounds. 1490 if (CheckEquivalentExceptionSpec( 1491 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1492 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1493 New->setInvalidDecl(); 1494 } 1495 } 1496 1497 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1498 /// function declaration are well-formed according to C++ 1499 /// [dcl.fct.default]. 1500 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1501 unsigned NumParams = FD->getNumParams(); 1502 unsigned p; 1503 1504 // Find first parameter with a default argument 1505 for (p = 0; p < NumParams; ++p) { 1506 ParmVarDecl *Param = FD->getParamDecl(p); 1507 if (Param->hasDefaultArg()) 1508 break; 1509 } 1510 1511 // C++11 [dcl.fct.default]p4: 1512 // In a given function declaration, each parameter subsequent to a parameter 1513 // with a default argument shall have a default argument supplied in this or 1514 // a previous declaration or shall be a function parameter pack. A default 1515 // argument shall not be redefined by a later declaration (not even to the 1516 // same value). 1517 unsigned LastMissingDefaultArg = 0; 1518 for (; p < NumParams; ++p) { 1519 ParmVarDecl *Param = FD->getParamDecl(p); 1520 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1521 if (Param->isInvalidDecl()) 1522 /* We already complained about this parameter. */; 1523 else if (Param->getIdentifier()) 1524 Diag(Param->getLocation(), 1525 diag::err_param_default_argument_missing_name) 1526 << Param->getIdentifier(); 1527 else 1528 Diag(Param->getLocation(), 1529 diag::err_param_default_argument_missing); 1530 1531 LastMissingDefaultArg = p; 1532 } 1533 } 1534 1535 if (LastMissingDefaultArg > 0) { 1536 // Some default arguments were missing. Clear out all of the 1537 // default arguments up to (and including) the last missing 1538 // default argument, so that we leave the function parameters 1539 // in a semantically valid state. 1540 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1541 ParmVarDecl *Param = FD->getParamDecl(p); 1542 if (Param->hasDefaultArg()) { 1543 Param->setDefaultArg(nullptr); 1544 } 1545 } 1546 } 1547 } 1548 1549 // CheckConstexprParameterTypes - Check whether a function's parameter types 1550 // are all literal types. If so, return true. If not, produce a suitable 1551 // diagnostic and return false. 1552 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1553 const FunctionDecl *FD) { 1554 unsigned ArgIndex = 0; 1555 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1556 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1557 e = FT->param_type_end(); 1558 i != e; ++i, ++ArgIndex) { 1559 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1560 SourceLocation ParamLoc = PD->getLocation(); 1561 if (!(*i)->isDependentType() && 1562 SemaRef.RequireLiteralType(ParamLoc, *i, 1563 diag::err_constexpr_non_literal_param, 1564 ArgIndex+1, PD->getSourceRange(), 1565 isa<CXXConstructorDecl>(FD))) 1566 return false; 1567 } 1568 return true; 1569 } 1570 1571 /// Get diagnostic %select index for tag kind for 1572 /// record diagnostic message. 1573 /// WARNING: Indexes apply to particular diagnostics only! 1574 /// 1575 /// \returns diagnostic %select index. 1576 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1577 switch (Tag) { 1578 case TTK_Struct: return 0; 1579 case TTK_Interface: return 1; 1580 case TTK_Class: return 2; 1581 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1582 } 1583 } 1584 1585 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 1586 // the requirements of a constexpr function definition or a constexpr 1587 // constructor definition. If so, return true. If not, produce appropriate 1588 // diagnostics and return false. 1589 // 1590 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1591 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 1592 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1593 if (MD && MD->isInstance()) { 1594 // C++11 [dcl.constexpr]p4: 1595 // The definition of a constexpr constructor shall satisfy the following 1596 // constraints: 1597 // - the class shall not have any virtual base classes; 1598 const CXXRecordDecl *RD = MD->getParent(); 1599 if (RD->getNumVBases()) { 1600 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1601 << isa<CXXConstructorDecl>(NewFD) 1602 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1603 for (const auto &I : RD->vbases()) 1604 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1605 << I.getSourceRange(); 1606 return false; 1607 } 1608 } 1609 1610 if (!isa<CXXConstructorDecl>(NewFD)) { 1611 // C++11 [dcl.constexpr]p3: 1612 // The definition of a constexpr function shall satisfy the following 1613 // constraints: 1614 // - it shall not be virtual; 1615 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1616 if (Method && Method->isVirtual()) { 1617 Method = Method->getCanonicalDecl(); 1618 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1619 1620 // If it's not obvious why this function is virtual, find an overridden 1621 // function which uses the 'virtual' keyword. 1622 const CXXMethodDecl *WrittenVirtual = Method; 1623 while (!WrittenVirtual->isVirtualAsWritten()) 1624 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1625 if (WrittenVirtual != Method) 1626 Diag(WrittenVirtual->getLocation(), 1627 diag::note_overridden_virtual_function); 1628 return false; 1629 } 1630 1631 // - its return type shall be a literal type; 1632 QualType RT = NewFD->getReturnType(); 1633 if (!RT->isDependentType() && 1634 RequireLiteralType(NewFD->getLocation(), RT, 1635 diag::err_constexpr_non_literal_return)) 1636 return false; 1637 } 1638 1639 // - each of its parameter types shall be a literal type; 1640 if (!CheckConstexprParameterTypes(*this, NewFD)) 1641 return false; 1642 1643 return true; 1644 } 1645 1646 /// Check the given declaration statement is legal within a constexpr function 1647 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1648 /// 1649 /// \return true if the body is OK (maybe only as an extension), false if we 1650 /// have diagnosed a problem. 1651 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1652 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 1653 // C++11 [dcl.constexpr]p3 and p4: 1654 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1655 // contain only 1656 for (const auto *DclIt : DS->decls()) { 1657 switch (DclIt->getKind()) { 1658 case Decl::StaticAssert: 1659 case Decl::Using: 1660 case Decl::UsingShadow: 1661 case Decl::UsingDirective: 1662 case Decl::UnresolvedUsingTypename: 1663 case Decl::UnresolvedUsingValue: 1664 // - static_assert-declarations 1665 // - using-declarations, 1666 // - using-directives, 1667 continue; 1668 1669 case Decl::Typedef: 1670 case Decl::TypeAlias: { 1671 // - typedef declarations and alias-declarations that do not define 1672 // classes or enumerations, 1673 const auto *TN = cast<TypedefNameDecl>(DclIt); 1674 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1675 // Don't allow variably-modified types in constexpr functions. 1676 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1677 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1678 << TL.getSourceRange() << TL.getType() 1679 << isa<CXXConstructorDecl>(Dcl); 1680 return false; 1681 } 1682 continue; 1683 } 1684 1685 case Decl::Enum: 1686 case Decl::CXXRecord: 1687 // C++1y allows types to be defined, not just declared. 1688 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 1689 SemaRef.Diag(DS->getBeginLoc(), 1690 SemaRef.getLangOpts().CPlusPlus14 1691 ? diag::warn_cxx11_compat_constexpr_type_definition 1692 : diag::ext_constexpr_type_definition) 1693 << isa<CXXConstructorDecl>(Dcl); 1694 continue; 1695 1696 case Decl::EnumConstant: 1697 case Decl::IndirectField: 1698 case Decl::ParmVar: 1699 // These can only appear with other declarations which are banned in 1700 // C++11 and permitted in C++1y, so ignore them. 1701 continue; 1702 1703 case Decl::Var: 1704 case Decl::Decomposition: { 1705 // C++1y [dcl.constexpr]p3 allows anything except: 1706 // a definition of a variable of non-literal type or of static or 1707 // thread storage duration or for which no initialization is performed. 1708 const auto *VD = cast<VarDecl>(DclIt); 1709 if (VD->isThisDeclarationADefinition()) { 1710 if (VD->isStaticLocal()) { 1711 SemaRef.Diag(VD->getLocation(), 1712 diag::err_constexpr_local_var_static) 1713 << isa<CXXConstructorDecl>(Dcl) 1714 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1715 return false; 1716 } 1717 if (!VD->getType()->isDependentType() && 1718 SemaRef.RequireLiteralType( 1719 VD->getLocation(), VD->getType(), 1720 diag::err_constexpr_local_var_non_literal_type, 1721 isa<CXXConstructorDecl>(Dcl))) 1722 return false; 1723 if (!VD->getType()->isDependentType() && 1724 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1725 SemaRef.Diag(VD->getLocation(), 1726 diag::err_constexpr_local_var_no_init) 1727 << isa<CXXConstructorDecl>(Dcl); 1728 return false; 1729 } 1730 } 1731 SemaRef.Diag(VD->getLocation(), 1732 SemaRef.getLangOpts().CPlusPlus14 1733 ? diag::warn_cxx11_compat_constexpr_local_var 1734 : diag::ext_constexpr_local_var) 1735 << isa<CXXConstructorDecl>(Dcl); 1736 continue; 1737 } 1738 1739 case Decl::NamespaceAlias: 1740 case Decl::Function: 1741 // These are disallowed in C++11 and permitted in C++1y. Allow them 1742 // everywhere as an extension. 1743 if (!Cxx1yLoc.isValid()) 1744 Cxx1yLoc = DS->getBeginLoc(); 1745 continue; 1746 1747 default: 1748 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1749 << isa<CXXConstructorDecl>(Dcl); 1750 return false; 1751 } 1752 } 1753 1754 return true; 1755 } 1756 1757 /// Check that the given field is initialized within a constexpr constructor. 1758 /// 1759 /// \param Dcl The constexpr constructor being checked. 1760 /// \param Field The field being checked. This may be a member of an anonymous 1761 /// struct or union nested within the class being checked. 1762 /// \param Inits All declarations, including anonymous struct/union members and 1763 /// indirect members, for which any initialization was provided. 1764 /// \param Diagnosed Set to true if an error is produced. 1765 static void CheckConstexprCtorInitializer(Sema &SemaRef, 1766 const FunctionDecl *Dcl, 1767 FieldDecl *Field, 1768 llvm::SmallSet<Decl*, 16> &Inits, 1769 bool &Diagnosed) { 1770 if (Field->isInvalidDecl()) 1771 return; 1772 1773 if (Field->isUnnamedBitfield()) 1774 return; 1775 1776 // Anonymous unions with no variant members and empty anonymous structs do not 1777 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1778 // indirect fields don't need initializing. 1779 if (Field->isAnonymousStructOrUnion() && 1780 (Field->getType()->isUnionType() 1781 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1782 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1783 return; 1784 1785 if (!Inits.count(Field)) { 1786 if (!Diagnosed) { 1787 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1788 Diagnosed = true; 1789 } 1790 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1791 } else if (Field->isAnonymousStructOrUnion()) { 1792 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1793 for (auto *I : RD->fields()) 1794 // If an anonymous union contains an anonymous struct of which any member 1795 // is initialized, all members must be initialized. 1796 if (!RD->isUnion() || Inits.count(I)) 1797 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1798 } 1799 } 1800 1801 /// Check the provided statement is allowed in a constexpr function 1802 /// definition. 1803 static bool 1804 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1805 SmallVectorImpl<SourceLocation> &ReturnStmts, 1806 SourceLocation &Cxx1yLoc) { 1807 // - its function-body shall be [...] a compound-statement that contains only 1808 switch (S->getStmtClass()) { 1809 case Stmt::NullStmtClass: 1810 // - null statements, 1811 return true; 1812 1813 case Stmt::DeclStmtClass: 1814 // - static_assert-declarations 1815 // - using-declarations, 1816 // - using-directives, 1817 // - typedef declarations and alias-declarations that do not define 1818 // classes or enumerations, 1819 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1820 return false; 1821 return true; 1822 1823 case Stmt::ReturnStmtClass: 1824 // - and exactly one return statement; 1825 if (isa<CXXConstructorDecl>(Dcl)) { 1826 // C++1y allows return statements in constexpr constructors. 1827 if (!Cxx1yLoc.isValid()) 1828 Cxx1yLoc = S->getBeginLoc(); 1829 return true; 1830 } 1831 1832 ReturnStmts.push_back(S->getBeginLoc()); 1833 return true; 1834 1835 case Stmt::CompoundStmtClass: { 1836 // C++1y allows compound-statements. 1837 if (!Cxx1yLoc.isValid()) 1838 Cxx1yLoc = S->getBeginLoc(); 1839 1840 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1841 for (auto *BodyIt : CompStmt->body()) { 1842 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1843 Cxx1yLoc)) 1844 return false; 1845 } 1846 return true; 1847 } 1848 1849 case Stmt::AttributedStmtClass: 1850 if (!Cxx1yLoc.isValid()) 1851 Cxx1yLoc = S->getBeginLoc(); 1852 return true; 1853 1854 case Stmt::IfStmtClass: { 1855 // C++1y allows if-statements. 1856 if (!Cxx1yLoc.isValid()) 1857 Cxx1yLoc = S->getBeginLoc(); 1858 1859 IfStmt *If = cast<IfStmt>(S); 1860 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1861 Cxx1yLoc)) 1862 return false; 1863 if (If->getElse() && 1864 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1865 Cxx1yLoc)) 1866 return false; 1867 return true; 1868 } 1869 1870 case Stmt::WhileStmtClass: 1871 case Stmt::DoStmtClass: 1872 case Stmt::ForStmtClass: 1873 case Stmt::CXXForRangeStmtClass: 1874 case Stmt::ContinueStmtClass: 1875 // C++1y allows all of these. We don't allow them as extensions in C++11, 1876 // because they don't make sense without variable mutation. 1877 if (!SemaRef.getLangOpts().CPlusPlus14) 1878 break; 1879 if (!Cxx1yLoc.isValid()) 1880 Cxx1yLoc = S->getBeginLoc(); 1881 for (Stmt *SubStmt : S->children()) 1882 if (SubStmt && 1883 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1884 Cxx1yLoc)) 1885 return false; 1886 return true; 1887 1888 case Stmt::SwitchStmtClass: 1889 case Stmt::CaseStmtClass: 1890 case Stmt::DefaultStmtClass: 1891 case Stmt::BreakStmtClass: 1892 // C++1y allows switch-statements, and since they don't need variable 1893 // mutation, we can reasonably allow them in C++11 as an extension. 1894 if (!Cxx1yLoc.isValid()) 1895 Cxx1yLoc = S->getBeginLoc(); 1896 for (Stmt *SubStmt : S->children()) 1897 if (SubStmt && 1898 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1899 Cxx1yLoc)) 1900 return false; 1901 return true; 1902 1903 default: 1904 if (!isa<Expr>(S)) 1905 break; 1906 1907 // C++1y allows expression-statements. 1908 if (!Cxx1yLoc.isValid()) 1909 Cxx1yLoc = S->getBeginLoc(); 1910 return true; 1911 } 1912 1913 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1914 << isa<CXXConstructorDecl>(Dcl); 1915 return false; 1916 } 1917 1918 /// Check the body for the given constexpr function declaration only contains 1919 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1920 /// 1921 /// \return true if the body is OK, false if we have diagnosed a problem. 1922 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1923 if (isa<CXXTryStmt>(Body)) { 1924 // C++11 [dcl.constexpr]p3: 1925 // The definition of a constexpr function shall satisfy the following 1926 // constraints: [...] 1927 // - its function-body shall be = delete, = default, or a 1928 // compound-statement 1929 // 1930 // C++11 [dcl.constexpr]p4: 1931 // In the definition of a constexpr constructor, [...] 1932 // - its function-body shall not be a function-try-block; 1933 Diag(Body->getBeginLoc(), diag::err_constexpr_function_try_block) 1934 << isa<CXXConstructorDecl>(Dcl); 1935 return false; 1936 } 1937 1938 SmallVector<SourceLocation, 4> ReturnStmts; 1939 1940 // - its function-body shall be [...] a compound-statement that contains only 1941 // [... list of cases ...] 1942 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1943 SourceLocation Cxx1yLoc; 1944 for (auto *BodyIt : CompBody->body()) { 1945 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1946 return false; 1947 } 1948 1949 if (Cxx1yLoc.isValid()) 1950 Diag(Cxx1yLoc, 1951 getLangOpts().CPlusPlus14 1952 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1953 : diag::ext_constexpr_body_invalid_stmt) 1954 << isa<CXXConstructorDecl>(Dcl); 1955 1956 if (const CXXConstructorDecl *Constructor 1957 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1958 const CXXRecordDecl *RD = Constructor->getParent(); 1959 // DR1359: 1960 // - every non-variant non-static data member and base class sub-object 1961 // shall be initialized; 1962 // DR1460: 1963 // - if the class is a union having variant members, exactly one of them 1964 // shall be initialized; 1965 if (RD->isUnion()) { 1966 if (Constructor->getNumCtorInitializers() == 0 && 1967 RD->hasVariantMembers()) { 1968 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1969 return false; 1970 } 1971 } else if (!Constructor->isDependentContext() && 1972 !Constructor->isDelegatingConstructor()) { 1973 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1974 1975 // Skip detailed checking if we have enough initializers, and we would 1976 // allow at most one initializer per member. 1977 bool AnyAnonStructUnionMembers = false; 1978 unsigned Fields = 0; 1979 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1980 E = RD->field_end(); I != E; ++I, ++Fields) { 1981 if (I->isAnonymousStructOrUnion()) { 1982 AnyAnonStructUnionMembers = true; 1983 break; 1984 } 1985 } 1986 // DR1460: 1987 // - if the class is a union-like class, but is not a union, for each of 1988 // its anonymous union members having variant members, exactly one of 1989 // them shall be initialized; 1990 if (AnyAnonStructUnionMembers || 1991 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1992 // Check initialization of non-static data members. Base classes are 1993 // always initialized so do not need to be checked. Dependent bases 1994 // might not have initializers in the member initializer list. 1995 llvm::SmallSet<Decl*, 16> Inits; 1996 for (const auto *I: Constructor->inits()) { 1997 if (FieldDecl *FD = I->getMember()) 1998 Inits.insert(FD); 1999 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2000 Inits.insert(ID->chain_begin(), ID->chain_end()); 2001 } 2002 2003 bool Diagnosed = false; 2004 for (auto *I : RD->fields()) 2005 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 2006 if (Diagnosed) 2007 return false; 2008 } 2009 } 2010 } else { 2011 if (ReturnStmts.empty()) { 2012 // C++1y doesn't require constexpr functions to contain a 'return' 2013 // statement. We still do, unless the return type might be void, because 2014 // otherwise if there's no return statement, the function cannot 2015 // be used in a core constant expression. 2016 bool OK = getLangOpts().CPlusPlus14 && 2017 (Dcl->getReturnType()->isVoidType() || 2018 Dcl->getReturnType()->isDependentType()); 2019 Diag(Dcl->getLocation(), 2020 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2021 : diag::err_constexpr_body_no_return); 2022 if (!OK) 2023 return false; 2024 } else if (ReturnStmts.size() > 1) { 2025 Diag(ReturnStmts.back(), 2026 getLangOpts().CPlusPlus14 2027 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2028 : diag::ext_constexpr_body_multiple_return); 2029 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2030 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 2031 } 2032 } 2033 2034 // C++11 [dcl.constexpr]p5: 2035 // if no function argument values exist such that the function invocation 2036 // substitution would produce a constant expression, the program is 2037 // ill-formed; no diagnostic required. 2038 // C++11 [dcl.constexpr]p3: 2039 // - every constructor call and implicit conversion used in initializing the 2040 // return value shall be one of those allowed in a constant expression. 2041 // C++11 [dcl.constexpr]p4: 2042 // - every constructor involved in initializing non-static data members and 2043 // base class sub-objects shall be a constexpr constructor. 2044 SmallVector<PartialDiagnosticAt, 8> Diags; 2045 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 2046 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 2047 << isa<CXXConstructorDecl>(Dcl); 2048 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2049 Diag(Diags[I].first, Diags[I].second); 2050 // Don't return false here: we allow this for compatibility in 2051 // system headers. 2052 } 2053 2054 return true; 2055 } 2056 2057 /// Get the class that is directly named by the current context. This is the 2058 /// class for which an unqualified-id in this scope could name a constructor 2059 /// or destructor. 2060 /// 2061 /// If the scope specifier denotes a class, this will be that class. 2062 /// If the scope specifier is empty, this will be the class whose 2063 /// member-specification we are currently within. Otherwise, there 2064 /// is no such class. 2065 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2066 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2067 2068 if (SS && SS->isInvalid()) 2069 return nullptr; 2070 2071 if (SS && SS->isNotEmpty()) { 2072 DeclContext *DC = computeDeclContext(*SS, true); 2073 return dyn_cast_or_null<CXXRecordDecl>(DC); 2074 } 2075 2076 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2077 } 2078 2079 /// isCurrentClassName - Determine whether the identifier II is the 2080 /// name of the class type currently being defined. In the case of 2081 /// nested classes, this will only return true if II is the name of 2082 /// the innermost class. 2083 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2084 const CXXScopeSpec *SS) { 2085 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2086 return CurDecl && &II == CurDecl->getIdentifier(); 2087 } 2088 2089 /// Determine whether the identifier II is a typo for the name of 2090 /// the class type currently being defined. If so, update it to the identifier 2091 /// that should have been used. 2092 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2093 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2094 2095 if (!getLangOpts().SpellChecking) 2096 return false; 2097 2098 CXXRecordDecl *CurDecl; 2099 if (SS && SS->isSet() && !SS->isInvalid()) { 2100 DeclContext *DC = computeDeclContext(*SS, true); 2101 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2102 } else 2103 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2104 2105 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2106 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2107 < II->getLength()) { 2108 II = CurDecl->getIdentifier(); 2109 return true; 2110 } 2111 2112 return false; 2113 } 2114 2115 /// Determine whether the given class is a base class of the given 2116 /// class, including looking at dependent bases. 2117 static bool findCircularInheritance(const CXXRecordDecl *Class, 2118 const CXXRecordDecl *Current) { 2119 SmallVector<const CXXRecordDecl*, 8> Queue; 2120 2121 Class = Class->getCanonicalDecl(); 2122 while (true) { 2123 for (const auto &I : Current->bases()) { 2124 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2125 if (!Base) 2126 continue; 2127 2128 Base = Base->getDefinition(); 2129 if (!Base) 2130 continue; 2131 2132 if (Base->getCanonicalDecl() == Class) 2133 return true; 2134 2135 Queue.push_back(Base); 2136 } 2137 2138 if (Queue.empty()) 2139 return false; 2140 2141 Current = Queue.pop_back_val(); 2142 } 2143 2144 return false; 2145 } 2146 2147 /// Check the validity of a C++ base class specifier. 2148 /// 2149 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2150 /// and returns NULL otherwise. 2151 CXXBaseSpecifier * 2152 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2153 SourceRange SpecifierRange, 2154 bool Virtual, AccessSpecifier Access, 2155 TypeSourceInfo *TInfo, 2156 SourceLocation EllipsisLoc) { 2157 QualType BaseType = TInfo->getType(); 2158 2159 // C++ [class.union]p1: 2160 // A union shall not have base classes. 2161 if (Class->isUnion()) { 2162 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2163 << SpecifierRange; 2164 return nullptr; 2165 } 2166 2167 if (EllipsisLoc.isValid() && 2168 !TInfo->getType()->containsUnexpandedParameterPack()) { 2169 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2170 << TInfo->getTypeLoc().getSourceRange(); 2171 EllipsisLoc = SourceLocation(); 2172 } 2173 2174 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2175 2176 if (BaseType->isDependentType()) { 2177 // Make sure that we don't have circular inheritance among our dependent 2178 // bases. For non-dependent bases, the check for completeness below handles 2179 // this. 2180 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2181 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2182 ((BaseDecl = BaseDecl->getDefinition()) && 2183 findCircularInheritance(Class, BaseDecl))) { 2184 Diag(BaseLoc, diag::err_circular_inheritance) 2185 << BaseType << Context.getTypeDeclType(Class); 2186 2187 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2188 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2189 << BaseType; 2190 2191 return nullptr; 2192 } 2193 } 2194 2195 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2196 Class->getTagKind() == TTK_Class, 2197 Access, TInfo, EllipsisLoc); 2198 } 2199 2200 // Base specifiers must be record types. 2201 if (!BaseType->isRecordType()) { 2202 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2203 return nullptr; 2204 } 2205 2206 // C++ [class.union]p1: 2207 // A union shall not be used as a base class. 2208 if (BaseType->isUnionType()) { 2209 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2210 return nullptr; 2211 } 2212 2213 // For the MS ABI, propagate DLL attributes to base class templates. 2214 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2215 if (Attr *ClassAttr = getDLLAttr(Class)) { 2216 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2217 BaseType->getAsCXXRecordDecl())) { 2218 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2219 BaseLoc); 2220 } 2221 } 2222 } 2223 2224 // C++ [class.derived]p2: 2225 // The class-name in a base-specifier shall not be an incompletely 2226 // defined class. 2227 if (RequireCompleteType(BaseLoc, BaseType, 2228 diag::err_incomplete_base_class, SpecifierRange)) { 2229 Class->setInvalidDecl(); 2230 return nullptr; 2231 } 2232 2233 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2234 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2235 assert(BaseDecl && "Record type has no declaration"); 2236 BaseDecl = BaseDecl->getDefinition(); 2237 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2238 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2239 assert(CXXBaseDecl && "Base type is not a C++ type"); 2240 2241 // Microsoft docs say: 2242 // "If a base-class has a code_seg attribute, derived classes must have the 2243 // same attribute." 2244 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2245 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2246 if ((DerivedCSA || BaseCSA) && 2247 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2248 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2249 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2250 << CXXBaseDecl; 2251 return nullptr; 2252 } 2253 2254 // A class which contains a flexible array member is not suitable for use as a 2255 // base class: 2256 // - If the layout determines that a base comes before another base, 2257 // the flexible array member would index into the subsequent base. 2258 // - If the layout determines that base comes before the derived class, 2259 // the flexible array member would index into the derived class. 2260 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2261 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2262 << CXXBaseDecl->getDeclName(); 2263 return nullptr; 2264 } 2265 2266 // C++ [class]p3: 2267 // If a class is marked final and it appears as a base-type-specifier in 2268 // base-clause, the program is ill-formed. 2269 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2270 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2271 << CXXBaseDecl->getDeclName() 2272 << FA->isSpelledAsSealed(); 2273 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2274 << CXXBaseDecl->getDeclName() << FA->getRange(); 2275 return nullptr; 2276 } 2277 2278 if (BaseDecl->isInvalidDecl()) 2279 Class->setInvalidDecl(); 2280 2281 // Create the base specifier. 2282 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2283 Class->getTagKind() == TTK_Class, 2284 Access, TInfo, EllipsisLoc); 2285 } 2286 2287 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2288 /// one entry in the base class list of a class specifier, for 2289 /// example: 2290 /// class foo : public bar, virtual private baz { 2291 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2292 BaseResult 2293 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2294 ParsedAttributes &Attributes, 2295 bool Virtual, AccessSpecifier Access, 2296 ParsedType basetype, SourceLocation BaseLoc, 2297 SourceLocation EllipsisLoc) { 2298 if (!classdecl) 2299 return true; 2300 2301 AdjustDeclIfTemplate(classdecl); 2302 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2303 if (!Class) 2304 return true; 2305 2306 // We haven't yet attached the base specifiers. 2307 Class->setIsParsingBaseSpecifiers(); 2308 2309 // We do not support any C++11 attributes on base-specifiers yet. 2310 // Diagnose any attributes we see. 2311 for (const ParsedAttr &AL : Attributes) { 2312 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2313 continue; 2314 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2315 ? diag::warn_unknown_attribute_ignored 2316 : diag::err_base_specifier_attribute) 2317 << AL.getName(); 2318 } 2319 2320 TypeSourceInfo *TInfo = nullptr; 2321 GetTypeFromParser(basetype, &TInfo); 2322 2323 if (EllipsisLoc.isInvalid() && 2324 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2325 UPPC_BaseType)) 2326 return true; 2327 2328 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2329 Virtual, Access, TInfo, 2330 EllipsisLoc)) 2331 return BaseSpec; 2332 else 2333 Class->setInvalidDecl(); 2334 2335 return true; 2336 } 2337 2338 /// Use small set to collect indirect bases. As this is only used 2339 /// locally, there's no need to abstract the small size parameter. 2340 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2341 2342 /// Recursively add the bases of Type. Don't add Type itself. 2343 static void 2344 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2345 const QualType &Type) 2346 { 2347 // Even though the incoming type is a base, it might not be 2348 // a class -- it could be a template parm, for instance. 2349 if (auto Rec = Type->getAs<RecordType>()) { 2350 auto Decl = Rec->getAsCXXRecordDecl(); 2351 2352 // Iterate over its bases. 2353 for (const auto &BaseSpec : Decl->bases()) { 2354 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2355 .getUnqualifiedType(); 2356 if (Set.insert(Base).second) 2357 // If we've not already seen it, recurse. 2358 NoteIndirectBases(Context, Set, Base); 2359 } 2360 } 2361 } 2362 2363 /// Performs the actual work of attaching the given base class 2364 /// specifiers to a C++ class. 2365 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2366 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2367 if (Bases.empty()) 2368 return false; 2369 2370 // Used to keep track of which base types we have already seen, so 2371 // that we can properly diagnose redundant direct base types. Note 2372 // that the key is always the unqualified canonical type of the base 2373 // class. 2374 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2375 2376 // Used to track indirect bases so we can see if a direct base is 2377 // ambiguous. 2378 IndirectBaseSet IndirectBaseTypes; 2379 2380 // Copy non-redundant base specifiers into permanent storage. 2381 unsigned NumGoodBases = 0; 2382 bool Invalid = false; 2383 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2384 QualType NewBaseType 2385 = Context.getCanonicalType(Bases[idx]->getType()); 2386 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2387 2388 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2389 if (KnownBase) { 2390 // C++ [class.mi]p3: 2391 // A class shall not be specified as a direct base class of a 2392 // derived class more than once. 2393 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2394 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2395 2396 // Delete the duplicate base class specifier; we're going to 2397 // overwrite its pointer later. 2398 Context.Deallocate(Bases[idx]); 2399 2400 Invalid = true; 2401 } else { 2402 // Okay, add this new base class. 2403 KnownBase = Bases[idx]; 2404 Bases[NumGoodBases++] = Bases[idx]; 2405 2406 // Note this base's direct & indirect bases, if there could be ambiguity. 2407 if (Bases.size() > 1) 2408 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2409 2410 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2411 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2412 if (Class->isInterface() && 2413 (!RD->isInterfaceLike() || 2414 KnownBase->getAccessSpecifier() != AS_public)) { 2415 // The Microsoft extension __interface does not permit bases that 2416 // are not themselves public interfaces. 2417 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2418 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2419 << RD->getSourceRange(); 2420 Invalid = true; 2421 } 2422 if (RD->hasAttr<WeakAttr>()) 2423 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2424 } 2425 } 2426 } 2427 2428 // Attach the remaining base class specifiers to the derived class. 2429 Class->setBases(Bases.data(), NumGoodBases); 2430 2431 // Check that the only base classes that are duplicate are virtual. 2432 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2433 // Check whether this direct base is inaccessible due to ambiguity. 2434 QualType BaseType = Bases[idx]->getType(); 2435 2436 // Skip all dependent types in templates being used as base specifiers. 2437 // Checks below assume that the base specifier is a CXXRecord. 2438 if (BaseType->isDependentType()) 2439 continue; 2440 2441 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2442 .getUnqualifiedType(); 2443 2444 if (IndirectBaseTypes.count(CanonicalBase)) { 2445 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2446 /*DetectVirtual=*/true); 2447 bool found 2448 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2449 assert(found); 2450 (void)found; 2451 2452 if (Paths.isAmbiguous(CanonicalBase)) 2453 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2454 << BaseType << getAmbiguousPathsDisplayString(Paths) 2455 << Bases[idx]->getSourceRange(); 2456 else 2457 assert(Bases[idx]->isVirtual()); 2458 } 2459 2460 // Delete the base class specifier, since its data has been copied 2461 // into the CXXRecordDecl. 2462 Context.Deallocate(Bases[idx]); 2463 } 2464 2465 return Invalid; 2466 } 2467 2468 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2469 /// class, after checking whether there are any duplicate base 2470 /// classes. 2471 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2472 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2473 if (!ClassDecl || Bases.empty()) 2474 return; 2475 2476 AdjustDeclIfTemplate(ClassDecl); 2477 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2478 } 2479 2480 /// Determine whether the type \p Derived is a C++ class that is 2481 /// derived from the type \p Base. 2482 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2483 if (!getLangOpts().CPlusPlus) 2484 return false; 2485 2486 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2487 if (!DerivedRD) 2488 return false; 2489 2490 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2491 if (!BaseRD) 2492 return false; 2493 2494 // If either the base or the derived type is invalid, don't try to 2495 // check whether one is derived from the other. 2496 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2497 return false; 2498 2499 // FIXME: In a modules build, do we need the entire path to be visible for us 2500 // to be able to use the inheritance relationship? 2501 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2502 return false; 2503 2504 return DerivedRD->isDerivedFrom(BaseRD); 2505 } 2506 2507 /// Determine whether the type \p Derived is a C++ class that is 2508 /// derived from the type \p Base. 2509 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2510 CXXBasePaths &Paths) { 2511 if (!getLangOpts().CPlusPlus) 2512 return false; 2513 2514 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2515 if (!DerivedRD) 2516 return false; 2517 2518 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2519 if (!BaseRD) 2520 return false; 2521 2522 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2523 return false; 2524 2525 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2526 } 2527 2528 static void BuildBasePathArray(const CXXBasePath &Path, 2529 CXXCastPath &BasePathArray) { 2530 // We first go backward and check if we have a virtual base. 2531 // FIXME: It would be better if CXXBasePath had the base specifier for 2532 // the nearest virtual base. 2533 unsigned Start = 0; 2534 for (unsigned I = Path.size(); I != 0; --I) { 2535 if (Path[I - 1].Base->isVirtual()) { 2536 Start = I - 1; 2537 break; 2538 } 2539 } 2540 2541 // Now add all bases. 2542 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2543 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2544 } 2545 2546 2547 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2548 CXXCastPath &BasePathArray) { 2549 assert(BasePathArray.empty() && "Base path array must be empty!"); 2550 assert(Paths.isRecordingPaths() && "Must record paths!"); 2551 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2552 } 2553 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2554 /// conversion (where Derived and Base are class types) is 2555 /// well-formed, meaning that the conversion is unambiguous (and 2556 /// that all of the base classes are accessible). Returns true 2557 /// and emits a diagnostic if the code is ill-formed, returns false 2558 /// otherwise. Loc is the location where this routine should point to 2559 /// if there is an error, and Range is the source range to highlight 2560 /// if there is an error. 2561 /// 2562 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2563 /// diagnostic for the respective type of error will be suppressed, but the 2564 /// check for ill-formed code will still be performed. 2565 bool 2566 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2567 unsigned InaccessibleBaseID, 2568 unsigned AmbigiousBaseConvID, 2569 SourceLocation Loc, SourceRange Range, 2570 DeclarationName Name, 2571 CXXCastPath *BasePath, 2572 bool IgnoreAccess) { 2573 // First, determine whether the path from Derived to Base is 2574 // ambiguous. This is slightly more expensive than checking whether 2575 // the Derived to Base conversion exists, because here we need to 2576 // explore multiple paths to determine if there is an ambiguity. 2577 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2578 /*DetectVirtual=*/false); 2579 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2580 if (!DerivationOkay) 2581 return true; 2582 2583 const CXXBasePath *Path = nullptr; 2584 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2585 Path = &Paths.front(); 2586 2587 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2588 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2589 // user to access such bases. 2590 if (!Path && getLangOpts().MSVCCompat) { 2591 for (const CXXBasePath &PossiblePath : Paths) { 2592 if (PossiblePath.size() == 1) { 2593 Path = &PossiblePath; 2594 if (AmbigiousBaseConvID) 2595 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2596 << Base << Derived << Range; 2597 break; 2598 } 2599 } 2600 } 2601 2602 if (Path) { 2603 if (!IgnoreAccess) { 2604 // Check that the base class can be accessed. 2605 switch ( 2606 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2607 case AR_inaccessible: 2608 return true; 2609 case AR_accessible: 2610 case AR_dependent: 2611 case AR_delayed: 2612 break; 2613 } 2614 } 2615 2616 // Build a base path if necessary. 2617 if (BasePath) 2618 ::BuildBasePathArray(*Path, *BasePath); 2619 return false; 2620 } 2621 2622 if (AmbigiousBaseConvID) { 2623 // We know that the derived-to-base conversion is ambiguous, and 2624 // we're going to produce a diagnostic. Perform the derived-to-base 2625 // search just one more time to compute all of the possible paths so 2626 // that we can print them out. This is more expensive than any of 2627 // the previous derived-to-base checks we've done, but at this point 2628 // performance isn't as much of an issue. 2629 Paths.clear(); 2630 Paths.setRecordingPaths(true); 2631 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2632 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2633 (void)StillOkay; 2634 2635 // Build up a textual representation of the ambiguous paths, e.g., 2636 // D -> B -> A, that will be used to illustrate the ambiguous 2637 // conversions in the diagnostic. We only print one of the paths 2638 // to each base class subobject. 2639 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2640 2641 Diag(Loc, AmbigiousBaseConvID) 2642 << Derived << Base << PathDisplayStr << Range << Name; 2643 } 2644 return true; 2645 } 2646 2647 bool 2648 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2649 SourceLocation Loc, SourceRange Range, 2650 CXXCastPath *BasePath, 2651 bool IgnoreAccess) { 2652 return CheckDerivedToBaseConversion( 2653 Derived, Base, diag::err_upcast_to_inaccessible_base, 2654 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2655 BasePath, IgnoreAccess); 2656 } 2657 2658 2659 /// Builds a string representing ambiguous paths from a 2660 /// specific derived class to different subobjects of the same base 2661 /// class. 2662 /// 2663 /// This function builds a string that can be used in error messages 2664 /// to show the different paths that one can take through the 2665 /// inheritance hierarchy to go from the derived class to different 2666 /// subobjects of a base class. The result looks something like this: 2667 /// @code 2668 /// struct D -> struct B -> struct A 2669 /// struct D -> struct C -> struct A 2670 /// @endcode 2671 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2672 std::string PathDisplayStr; 2673 std::set<unsigned> DisplayedPaths; 2674 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2675 Path != Paths.end(); ++Path) { 2676 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2677 // We haven't displayed a path to this particular base 2678 // class subobject yet. 2679 PathDisplayStr += "\n "; 2680 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2681 for (CXXBasePath::const_iterator Element = Path->begin(); 2682 Element != Path->end(); ++Element) 2683 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2684 } 2685 } 2686 2687 return PathDisplayStr; 2688 } 2689 2690 //===----------------------------------------------------------------------===// 2691 // C++ class member Handling 2692 //===----------------------------------------------------------------------===// 2693 2694 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2695 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2696 SourceLocation ColonLoc, 2697 const ParsedAttributesView &Attrs) { 2698 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2699 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2700 ASLoc, ColonLoc); 2701 CurContext->addHiddenDecl(ASDecl); 2702 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2703 } 2704 2705 /// CheckOverrideControl - Check C++11 override control semantics. 2706 void Sema::CheckOverrideControl(NamedDecl *D) { 2707 if (D->isInvalidDecl()) 2708 return; 2709 2710 // We only care about "override" and "final" declarations. 2711 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2712 return; 2713 2714 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2715 2716 // We can't check dependent instance methods. 2717 if (MD && MD->isInstance() && 2718 (MD->getParent()->hasAnyDependentBases() || 2719 MD->getType()->isDependentType())) 2720 return; 2721 2722 if (MD && !MD->isVirtual()) { 2723 // If we have a non-virtual method, check if if hides a virtual method. 2724 // (In that case, it's most likely the method has the wrong type.) 2725 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2726 FindHiddenVirtualMethods(MD, OverloadedMethods); 2727 2728 if (!OverloadedMethods.empty()) { 2729 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2730 Diag(OA->getLocation(), 2731 diag::override_keyword_hides_virtual_member_function) 2732 << "override" << (OverloadedMethods.size() > 1); 2733 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2734 Diag(FA->getLocation(), 2735 diag::override_keyword_hides_virtual_member_function) 2736 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2737 << (OverloadedMethods.size() > 1); 2738 } 2739 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2740 MD->setInvalidDecl(); 2741 return; 2742 } 2743 // Fall through into the general case diagnostic. 2744 // FIXME: We might want to attempt typo correction here. 2745 } 2746 2747 if (!MD || !MD->isVirtual()) { 2748 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2749 Diag(OA->getLocation(), 2750 diag::override_keyword_only_allowed_on_virtual_member_functions) 2751 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2752 D->dropAttr<OverrideAttr>(); 2753 } 2754 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2755 Diag(FA->getLocation(), 2756 diag::override_keyword_only_allowed_on_virtual_member_functions) 2757 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2758 << FixItHint::CreateRemoval(FA->getLocation()); 2759 D->dropAttr<FinalAttr>(); 2760 } 2761 return; 2762 } 2763 2764 // C++11 [class.virtual]p5: 2765 // If a function is marked with the virt-specifier override and 2766 // does not override a member function of a base class, the program is 2767 // ill-formed. 2768 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 2769 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2770 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2771 << MD->getDeclName(); 2772 } 2773 2774 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2775 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2776 return; 2777 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2778 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 2779 return; 2780 2781 SourceLocation Loc = MD->getLocation(); 2782 SourceLocation SpellingLoc = Loc; 2783 if (getSourceManager().isMacroArgExpansion(Loc)) 2784 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 2785 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2786 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2787 return; 2788 2789 if (MD->size_overridden_methods() > 0) { 2790 unsigned DiagID = isa<CXXDestructorDecl>(MD) 2791 ? diag::warn_destructor_marked_not_override_overriding 2792 : diag::warn_function_marked_not_override_overriding; 2793 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 2794 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2795 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2796 } 2797 } 2798 2799 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2800 /// function overrides a virtual member function marked 'final', according to 2801 /// C++11 [class.virtual]p4. 2802 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2803 const CXXMethodDecl *Old) { 2804 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2805 if (!FA) 2806 return false; 2807 2808 Diag(New->getLocation(), diag::err_final_function_overridden) 2809 << New->getDeclName() 2810 << FA->isSpelledAsSealed(); 2811 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2812 return true; 2813 } 2814 2815 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2816 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2817 // FIXME: Destruction of ObjC lifetime types has side-effects. 2818 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2819 return !RD->isCompleteDefinition() || 2820 !RD->hasTrivialDefaultConstructor() || 2821 !RD->hasTrivialDestructor(); 2822 return false; 2823 } 2824 2825 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 2826 ParsedAttributesView::const_iterator Itr = 2827 llvm::find_if(list, [](const ParsedAttr &AL) { 2828 return AL.isDeclspecPropertyAttribute(); 2829 }); 2830 if (Itr != list.end()) 2831 return &*Itr; 2832 return nullptr; 2833 } 2834 2835 // Check if there is a field shadowing. 2836 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 2837 DeclarationName FieldName, 2838 const CXXRecordDecl *RD) { 2839 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 2840 return; 2841 2842 // To record a shadowed field in a base 2843 std::map<CXXRecordDecl*, NamedDecl*> Bases; 2844 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 2845 CXXBasePath &Path) { 2846 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 2847 // Record an ambiguous path directly 2848 if (Bases.find(Base) != Bases.end()) 2849 return true; 2850 for (const auto Field : Base->lookup(FieldName)) { 2851 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 2852 Field->getAccess() != AS_private) { 2853 assert(Field->getAccess() != AS_none); 2854 assert(Bases.find(Base) == Bases.end()); 2855 Bases[Base] = Field; 2856 return true; 2857 } 2858 } 2859 return false; 2860 }; 2861 2862 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2863 /*DetectVirtual=*/true); 2864 if (!RD->lookupInBases(FieldShadowed, Paths)) 2865 return; 2866 2867 for (const auto &P : Paths) { 2868 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 2869 auto It = Bases.find(Base); 2870 // Skip duplicated bases 2871 if (It == Bases.end()) 2872 continue; 2873 auto BaseField = It->second; 2874 assert(BaseField->getAccess() != AS_private); 2875 if (AS_none != 2876 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 2877 Diag(Loc, diag::warn_shadow_field) 2878 << FieldName << RD << Base; 2879 Diag(BaseField->getLocation(), diag::note_shadow_field); 2880 Bases.erase(It); 2881 } 2882 } 2883 } 2884 2885 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2886 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2887 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2888 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2889 /// present (but parsing it has been deferred). 2890 NamedDecl * 2891 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2892 MultiTemplateParamsArg TemplateParameterLists, 2893 Expr *BW, const VirtSpecifiers &VS, 2894 InClassInitStyle InitStyle) { 2895 const DeclSpec &DS = D.getDeclSpec(); 2896 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2897 DeclarationName Name = NameInfo.getName(); 2898 SourceLocation Loc = NameInfo.getLoc(); 2899 2900 // For anonymous bitfields, the location should point to the type. 2901 if (Loc.isInvalid()) 2902 Loc = D.getBeginLoc(); 2903 2904 Expr *BitWidth = static_cast<Expr*>(BW); 2905 2906 assert(isa<CXXRecordDecl>(CurContext)); 2907 assert(!DS.isFriendSpecified()); 2908 2909 bool isFunc = D.isDeclarationOfFunction(); 2910 const ParsedAttr *MSPropertyAttr = 2911 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 2912 2913 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2914 // The Microsoft extension __interface only permits public member functions 2915 // and prohibits constructors, destructors, operators, non-public member 2916 // functions, static methods and data members. 2917 unsigned InvalidDecl; 2918 bool ShowDeclName = true; 2919 if (!isFunc && 2920 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 2921 InvalidDecl = 0; 2922 else if (!isFunc) 2923 InvalidDecl = 1; 2924 else if (AS != AS_public) 2925 InvalidDecl = 2; 2926 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2927 InvalidDecl = 3; 2928 else switch (Name.getNameKind()) { 2929 case DeclarationName::CXXConstructorName: 2930 InvalidDecl = 4; 2931 ShowDeclName = false; 2932 break; 2933 2934 case DeclarationName::CXXDestructorName: 2935 InvalidDecl = 5; 2936 ShowDeclName = false; 2937 break; 2938 2939 case DeclarationName::CXXOperatorName: 2940 case DeclarationName::CXXConversionFunctionName: 2941 InvalidDecl = 6; 2942 break; 2943 2944 default: 2945 InvalidDecl = 0; 2946 break; 2947 } 2948 2949 if (InvalidDecl) { 2950 if (ShowDeclName) 2951 Diag(Loc, diag::err_invalid_member_in_interface) 2952 << (InvalidDecl-1) << Name; 2953 else 2954 Diag(Loc, diag::err_invalid_member_in_interface) 2955 << (InvalidDecl-1) << ""; 2956 return nullptr; 2957 } 2958 } 2959 2960 // C++ 9.2p6: A member shall not be declared to have automatic storage 2961 // duration (auto, register) or with the extern storage-class-specifier. 2962 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2963 // data members and cannot be applied to names declared const or static, 2964 // and cannot be applied to reference members. 2965 switch (DS.getStorageClassSpec()) { 2966 case DeclSpec::SCS_unspecified: 2967 case DeclSpec::SCS_typedef: 2968 case DeclSpec::SCS_static: 2969 break; 2970 case DeclSpec::SCS_mutable: 2971 if (isFunc) { 2972 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2973 2974 // FIXME: It would be nicer if the keyword was ignored only for this 2975 // declarator. Otherwise we could get follow-up errors. 2976 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2977 } 2978 break; 2979 default: 2980 Diag(DS.getStorageClassSpecLoc(), 2981 diag::err_storageclass_invalid_for_member); 2982 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2983 break; 2984 } 2985 2986 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2987 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2988 !isFunc); 2989 2990 if (DS.isConstexprSpecified() && isInstField) { 2991 SemaDiagnosticBuilder B = 2992 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2993 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2994 if (InitStyle == ICIS_NoInit) { 2995 B << 0 << 0; 2996 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2997 B << FixItHint::CreateRemoval(ConstexprLoc); 2998 else { 2999 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3000 D.getMutableDeclSpec().ClearConstexprSpec(); 3001 const char *PrevSpec; 3002 unsigned DiagID; 3003 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3004 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3005 (void)Failed; 3006 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3007 } 3008 } else { 3009 B << 1; 3010 const char *PrevSpec; 3011 unsigned DiagID; 3012 if (D.getMutableDeclSpec().SetStorageClassSpec( 3013 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3014 Context.getPrintingPolicy())) { 3015 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3016 "This is the only DeclSpec that should fail to be applied"); 3017 B << 1; 3018 } else { 3019 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3020 isInstField = false; 3021 } 3022 } 3023 } 3024 3025 NamedDecl *Member; 3026 if (isInstField) { 3027 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3028 3029 // Data members must have identifiers for names. 3030 if (!Name.isIdentifier()) { 3031 Diag(Loc, diag::err_bad_variable_name) 3032 << Name; 3033 return nullptr; 3034 } 3035 3036 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3037 3038 // Member field could not be with "template" keyword. 3039 // So TemplateParameterLists should be empty in this case. 3040 if (TemplateParameterLists.size()) { 3041 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3042 if (TemplateParams->size()) { 3043 // There is no such thing as a member field template. 3044 Diag(D.getIdentifierLoc(), diag::err_template_member) 3045 << II 3046 << SourceRange(TemplateParams->getTemplateLoc(), 3047 TemplateParams->getRAngleLoc()); 3048 } else { 3049 // There is an extraneous 'template<>' for this member. 3050 Diag(TemplateParams->getTemplateLoc(), 3051 diag::err_template_member_noparams) 3052 << II 3053 << SourceRange(TemplateParams->getTemplateLoc(), 3054 TemplateParams->getRAngleLoc()); 3055 } 3056 return nullptr; 3057 } 3058 3059 if (SS.isSet() && !SS.isInvalid()) { 3060 // The user provided a superfluous scope specifier inside a class 3061 // definition: 3062 // 3063 // class X { 3064 // int X::member; 3065 // }; 3066 if (DeclContext *DC = computeDeclContext(SS, false)) 3067 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3068 D.getName().getKind() == 3069 UnqualifiedIdKind::IK_TemplateId); 3070 else 3071 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3072 << Name << SS.getRange(); 3073 3074 SS.clear(); 3075 } 3076 3077 if (MSPropertyAttr) { 3078 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3079 BitWidth, InitStyle, AS, *MSPropertyAttr); 3080 if (!Member) 3081 return nullptr; 3082 isInstField = false; 3083 } else { 3084 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3085 BitWidth, InitStyle, AS); 3086 if (!Member) 3087 return nullptr; 3088 } 3089 3090 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3091 } else { 3092 Member = HandleDeclarator(S, D, TemplateParameterLists); 3093 if (!Member) 3094 return nullptr; 3095 3096 // Non-instance-fields can't have a bitfield. 3097 if (BitWidth) { 3098 if (Member->isInvalidDecl()) { 3099 // don't emit another diagnostic. 3100 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3101 // C++ 9.6p3: A bit-field shall not be a static member. 3102 // "static member 'A' cannot be a bit-field" 3103 Diag(Loc, diag::err_static_not_bitfield) 3104 << Name << BitWidth->getSourceRange(); 3105 } else if (isa<TypedefDecl>(Member)) { 3106 // "typedef member 'x' cannot be a bit-field" 3107 Diag(Loc, diag::err_typedef_not_bitfield) 3108 << Name << BitWidth->getSourceRange(); 3109 } else { 3110 // A function typedef ("typedef int f(); f a;"). 3111 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3112 Diag(Loc, diag::err_not_integral_type_bitfield) 3113 << Name << cast<ValueDecl>(Member)->getType() 3114 << BitWidth->getSourceRange(); 3115 } 3116 3117 BitWidth = nullptr; 3118 Member->setInvalidDecl(); 3119 } 3120 3121 NamedDecl *NonTemplateMember = Member; 3122 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3123 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3124 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3125 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3126 3127 Member->setAccess(AS); 3128 3129 // If we have declared a member function template or static data member 3130 // template, set the access of the templated declaration as well. 3131 if (NonTemplateMember != Member) 3132 NonTemplateMember->setAccess(AS); 3133 3134 // C++ [temp.deduct.guide]p3: 3135 // A deduction guide [...] for a member class template [shall be 3136 // declared] with the same access [as the template]. 3137 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3138 auto *TD = DG->getDeducedTemplate(); 3139 if (AS != TD->getAccess()) { 3140 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3141 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3142 << TD->getAccess(); 3143 const AccessSpecDecl *LastAccessSpec = nullptr; 3144 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3145 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3146 LastAccessSpec = AccessSpec; 3147 } 3148 assert(LastAccessSpec && "differing access with no access specifier"); 3149 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3150 << AS; 3151 } 3152 } 3153 } 3154 3155 if (VS.isOverrideSpecified()) 3156 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3157 if (VS.isFinalSpecified()) 3158 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3159 VS.isFinalSpelledSealed())); 3160 3161 if (VS.getLastLocation().isValid()) { 3162 // Update the end location of a method that has a virt-specifiers. 3163 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3164 MD->setRangeEnd(VS.getLastLocation()); 3165 } 3166 3167 CheckOverrideControl(Member); 3168 3169 assert((Name || isInstField) && "No identifier for non-field ?"); 3170 3171 if (isInstField) { 3172 FieldDecl *FD = cast<FieldDecl>(Member); 3173 FieldCollector->Add(FD); 3174 3175 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3176 // Remember all explicit private FieldDecls that have a name, no side 3177 // effects and are not part of a dependent type declaration. 3178 if (!FD->isImplicit() && FD->getDeclName() && 3179 FD->getAccess() == AS_private && 3180 !FD->hasAttr<UnusedAttr>() && 3181 !FD->getParent()->isDependentContext() && 3182 !InitializationHasSideEffects(*FD)) 3183 UnusedPrivateFields.insert(FD); 3184 } 3185 } 3186 3187 return Member; 3188 } 3189 3190 namespace { 3191 class UninitializedFieldVisitor 3192 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3193 Sema &S; 3194 // List of Decls to generate a warning on. Also remove Decls that become 3195 // initialized. 3196 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3197 // List of base classes of the record. Classes are removed after their 3198 // initializers. 3199 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3200 // Vector of decls to be removed from the Decl set prior to visiting the 3201 // nodes. These Decls may have been initialized in the prior initializer. 3202 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3203 // If non-null, add a note to the warning pointing back to the constructor. 3204 const CXXConstructorDecl *Constructor; 3205 // Variables to hold state when processing an initializer list. When 3206 // InitList is true, special case initialization of FieldDecls matching 3207 // InitListFieldDecl. 3208 bool InitList; 3209 FieldDecl *InitListFieldDecl; 3210 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3211 3212 public: 3213 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3214 UninitializedFieldVisitor(Sema &S, 3215 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3216 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3217 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3218 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3219 3220 // Returns true if the use of ME is not an uninitialized use. 3221 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3222 bool CheckReferenceOnly) { 3223 llvm::SmallVector<FieldDecl*, 4> Fields; 3224 bool ReferenceField = false; 3225 while (ME) { 3226 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3227 if (!FD) 3228 return false; 3229 Fields.push_back(FD); 3230 if (FD->getType()->isReferenceType()) 3231 ReferenceField = true; 3232 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3233 } 3234 3235 // Binding a reference to an unintialized field is not an 3236 // uninitialized use. 3237 if (CheckReferenceOnly && !ReferenceField) 3238 return true; 3239 3240 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3241 // Discard the first field since it is the field decl that is being 3242 // initialized. 3243 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3244 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3245 } 3246 3247 for (auto UsedIter = UsedFieldIndex.begin(), 3248 UsedEnd = UsedFieldIndex.end(), 3249 OrigIter = InitFieldIndex.begin(), 3250 OrigEnd = InitFieldIndex.end(); 3251 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3252 if (*UsedIter < *OrigIter) 3253 return true; 3254 if (*UsedIter > *OrigIter) 3255 break; 3256 } 3257 3258 return false; 3259 } 3260 3261 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3262 bool AddressOf) { 3263 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3264 return; 3265 3266 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3267 // or union. 3268 MemberExpr *FieldME = ME; 3269 3270 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3271 3272 Expr *Base = ME; 3273 while (MemberExpr *SubME = 3274 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3275 3276 if (isa<VarDecl>(SubME->getMemberDecl())) 3277 return; 3278 3279 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3280 if (!FD->isAnonymousStructOrUnion()) 3281 FieldME = SubME; 3282 3283 if (!FieldME->getType().isPODType(S.Context)) 3284 AllPODFields = false; 3285 3286 Base = SubME->getBase(); 3287 } 3288 3289 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3290 return; 3291 3292 if (AddressOf && AllPODFields) 3293 return; 3294 3295 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3296 3297 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3298 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3299 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3300 } 3301 3302 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3303 QualType T = BaseCast->getType(); 3304 if (T->isPointerType() && 3305 BaseClasses.count(T->getPointeeType())) { 3306 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3307 << T->getPointeeType() << FoundVD; 3308 } 3309 } 3310 } 3311 3312 if (!Decls.count(FoundVD)) 3313 return; 3314 3315 const bool IsReference = FoundVD->getType()->isReferenceType(); 3316 3317 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3318 // Special checking for initializer lists. 3319 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3320 return; 3321 } 3322 } else { 3323 // Prevent double warnings on use of unbounded references. 3324 if (CheckReferenceOnly && !IsReference) 3325 return; 3326 } 3327 3328 unsigned diag = IsReference 3329 ? diag::warn_reference_field_is_uninit 3330 : diag::warn_field_is_uninit; 3331 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3332 if (Constructor) 3333 S.Diag(Constructor->getLocation(), 3334 diag::note_uninit_in_this_constructor) 3335 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3336 3337 } 3338 3339 void HandleValue(Expr *E, bool AddressOf) { 3340 E = E->IgnoreParens(); 3341 3342 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3343 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3344 AddressOf /*AddressOf*/); 3345 return; 3346 } 3347 3348 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3349 Visit(CO->getCond()); 3350 HandleValue(CO->getTrueExpr(), AddressOf); 3351 HandleValue(CO->getFalseExpr(), AddressOf); 3352 return; 3353 } 3354 3355 if (BinaryConditionalOperator *BCO = 3356 dyn_cast<BinaryConditionalOperator>(E)) { 3357 Visit(BCO->getCond()); 3358 HandleValue(BCO->getFalseExpr(), AddressOf); 3359 return; 3360 } 3361 3362 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3363 HandleValue(OVE->getSourceExpr(), AddressOf); 3364 return; 3365 } 3366 3367 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3368 switch (BO->getOpcode()) { 3369 default: 3370 break; 3371 case(BO_PtrMemD): 3372 case(BO_PtrMemI): 3373 HandleValue(BO->getLHS(), AddressOf); 3374 Visit(BO->getRHS()); 3375 return; 3376 case(BO_Comma): 3377 Visit(BO->getLHS()); 3378 HandleValue(BO->getRHS(), AddressOf); 3379 return; 3380 } 3381 } 3382 3383 Visit(E); 3384 } 3385 3386 void CheckInitListExpr(InitListExpr *ILE) { 3387 InitFieldIndex.push_back(0); 3388 for (auto Child : ILE->children()) { 3389 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3390 CheckInitListExpr(SubList); 3391 } else { 3392 Visit(Child); 3393 } 3394 ++InitFieldIndex.back(); 3395 } 3396 InitFieldIndex.pop_back(); 3397 } 3398 3399 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3400 FieldDecl *Field, const Type *BaseClass) { 3401 // Remove Decls that may have been initialized in the previous 3402 // initializer. 3403 for (ValueDecl* VD : DeclsToRemove) 3404 Decls.erase(VD); 3405 DeclsToRemove.clear(); 3406 3407 Constructor = FieldConstructor; 3408 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3409 3410 if (ILE && Field) { 3411 InitList = true; 3412 InitListFieldDecl = Field; 3413 InitFieldIndex.clear(); 3414 CheckInitListExpr(ILE); 3415 } else { 3416 InitList = false; 3417 Visit(E); 3418 } 3419 3420 if (Field) 3421 Decls.erase(Field); 3422 if (BaseClass) 3423 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3424 } 3425 3426 void VisitMemberExpr(MemberExpr *ME) { 3427 // All uses of unbounded reference fields will warn. 3428 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3429 } 3430 3431 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3432 if (E->getCastKind() == CK_LValueToRValue) { 3433 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3434 return; 3435 } 3436 3437 Inherited::VisitImplicitCastExpr(E); 3438 } 3439 3440 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3441 if (E->getConstructor()->isCopyConstructor()) { 3442 Expr *ArgExpr = E->getArg(0); 3443 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3444 if (ILE->getNumInits() == 1) 3445 ArgExpr = ILE->getInit(0); 3446 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3447 if (ICE->getCastKind() == CK_NoOp) 3448 ArgExpr = ICE->getSubExpr(); 3449 HandleValue(ArgExpr, false /*AddressOf*/); 3450 return; 3451 } 3452 Inherited::VisitCXXConstructExpr(E); 3453 } 3454 3455 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3456 Expr *Callee = E->getCallee(); 3457 if (isa<MemberExpr>(Callee)) { 3458 HandleValue(Callee, false /*AddressOf*/); 3459 for (auto Arg : E->arguments()) 3460 Visit(Arg); 3461 return; 3462 } 3463 3464 Inherited::VisitCXXMemberCallExpr(E); 3465 } 3466 3467 void VisitCallExpr(CallExpr *E) { 3468 // Treat std::move as a use. 3469 if (E->isCallToStdMove()) { 3470 HandleValue(E->getArg(0), /*AddressOf=*/false); 3471 return; 3472 } 3473 3474 Inherited::VisitCallExpr(E); 3475 } 3476 3477 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3478 Expr *Callee = E->getCallee(); 3479 3480 if (isa<UnresolvedLookupExpr>(Callee)) 3481 return Inherited::VisitCXXOperatorCallExpr(E); 3482 3483 Visit(Callee); 3484 for (auto Arg : E->arguments()) 3485 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3486 } 3487 3488 void VisitBinaryOperator(BinaryOperator *E) { 3489 // If a field assignment is detected, remove the field from the 3490 // uninitiailized field set. 3491 if (E->getOpcode() == BO_Assign) 3492 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3493 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3494 if (!FD->getType()->isReferenceType()) 3495 DeclsToRemove.push_back(FD); 3496 3497 if (E->isCompoundAssignmentOp()) { 3498 HandleValue(E->getLHS(), false /*AddressOf*/); 3499 Visit(E->getRHS()); 3500 return; 3501 } 3502 3503 Inherited::VisitBinaryOperator(E); 3504 } 3505 3506 void VisitUnaryOperator(UnaryOperator *E) { 3507 if (E->isIncrementDecrementOp()) { 3508 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3509 return; 3510 } 3511 if (E->getOpcode() == UO_AddrOf) { 3512 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3513 HandleValue(ME->getBase(), true /*AddressOf*/); 3514 return; 3515 } 3516 } 3517 3518 Inherited::VisitUnaryOperator(E); 3519 } 3520 }; 3521 3522 // Diagnose value-uses of fields to initialize themselves, e.g. 3523 // foo(foo) 3524 // where foo is not also a parameter to the constructor. 3525 // Also diagnose across field uninitialized use such as 3526 // x(y), y(x) 3527 // TODO: implement -Wuninitialized and fold this into that framework. 3528 static void DiagnoseUninitializedFields( 3529 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3530 3531 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3532 Constructor->getLocation())) { 3533 return; 3534 } 3535 3536 if (Constructor->isInvalidDecl()) 3537 return; 3538 3539 const CXXRecordDecl *RD = Constructor->getParent(); 3540 3541 if (RD->getDescribedClassTemplate()) 3542 return; 3543 3544 // Holds fields that are uninitialized. 3545 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3546 3547 // At the beginning, all fields are uninitialized. 3548 for (auto *I : RD->decls()) { 3549 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3550 UninitializedFields.insert(FD); 3551 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3552 UninitializedFields.insert(IFD->getAnonField()); 3553 } 3554 } 3555 3556 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3557 for (auto I : RD->bases()) 3558 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3559 3560 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3561 return; 3562 3563 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3564 UninitializedFields, 3565 UninitializedBaseClasses); 3566 3567 for (const auto *FieldInit : Constructor->inits()) { 3568 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3569 break; 3570 3571 Expr *InitExpr = FieldInit->getInit(); 3572 if (!InitExpr) 3573 continue; 3574 3575 if (CXXDefaultInitExpr *Default = 3576 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3577 InitExpr = Default->getExpr(); 3578 if (!InitExpr) 3579 continue; 3580 // In class initializers will point to the constructor. 3581 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3582 FieldInit->getAnyMember(), 3583 FieldInit->getBaseClass()); 3584 } else { 3585 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3586 FieldInit->getAnyMember(), 3587 FieldInit->getBaseClass()); 3588 } 3589 } 3590 } 3591 } // namespace 3592 3593 /// Enter a new C++ default initializer scope. After calling this, the 3594 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3595 /// parsing or instantiating the initializer failed. 3596 void Sema::ActOnStartCXXInClassMemberInitializer() { 3597 // Create a synthetic function scope to represent the call to the constructor 3598 // that notionally surrounds a use of this initializer. 3599 PushFunctionScope(); 3600 } 3601 3602 /// This is invoked after parsing an in-class initializer for a 3603 /// non-static C++ class member, and after instantiating an in-class initializer 3604 /// in a class template. Such actions are deferred until the class is complete. 3605 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3606 SourceLocation InitLoc, 3607 Expr *InitExpr) { 3608 // Pop the notional constructor scope we created earlier. 3609 PopFunctionScopeInfo(nullptr, D); 3610 3611 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3612 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3613 "must set init style when field is created"); 3614 3615 if (!InitExpr) { 3616 D->setInvalidDecl(); 3617 if (FD) 3618 FD->removeInClassInitializer(); 3619 return; 3620 } 3621 3622 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3623 FD->setInvalidDecl(); 3624 FD->removeInClassInitializer(); 3625 return; 3626 } 3627 3628 ExprResult Init = InitExpr; 3629 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3630 InitializedEntity Entity = 3631 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3632 InitializationKind Kind = 3633 FD->getInClassInitStyle() == ICIS_ListInit 3634 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3635 InitExpr->getBeginLoc(), 3636 InitExpr->getEndLoc()) 3637 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3638 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3639 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3640 if (Init.isInvalid()) { 3641 FD->setInvalidDecl(); 3642 return; 3643 } 3644 } 3645 3646 // C++11 [class.base.init]p7: 3647 // The initialization of each base and member constitutes a 3648 // full-expression. 3649 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 3650 if (Init.isInvalid()) { 3651 FD->setInvalidDecl(); 3652 return; 3653 } 3654 3655 InitExpr = Init.get(); 3656 3657 FD->setInClassInitializer(InitExpr); 3658 } 3659 3660 /// Find the direct and/or virtual base specifiers that 3661 /// correspond to the given base type, for use in base initialization 3662 /// within a constructor. 3663 static bool FindBaseInitializer(Sema &SemaRef, 3664 CXXRecordDecl *ClassDecl, 3665 QualType BaseType, 3666 const CXXBaseSpecifier *&DirectBaseSpec, 3667 const CXXBaseSpecifier *&VirtualBaseSpec) { 3668 // First, check for a direct base class. 3669 DirectBaseSpec = nullptr; 3670 for (const auto &Base : ClassDecl->bases()) { 3671 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3672 // We found a direct base of this type. That's what we're 3673 // initializing. 3674 DirectBaseSpec = &Base; 3675 break; 3676 } 3677 } 3678 3679 // Check for a virtual base class. 3680 // FIXME: We might be able to short-circuit this if we know in advance that 3681 // there are no virtual bases. 3682 VirtualBaseSpec = nullptr; 3683 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3684 // We haven't found a base yet; search the class hierarchy for a 3685 // virtual base class. 3686 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3687 /*DetectVirtual=*/false); 3688 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3689 SemaRef.Context.getTypeDeclType(ClassDecl), 3690 BaseType, Paths)) { 3691 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3692 Path != Paths.end(); ++Path) { 3693 if (Path->back().Base->isVirtual()) { 3694 VirtualBaseSpec = Path->back().Base; 3695 break; 3696 } 3697 } 3698 } 3699 } 3700 3701 return DirectBaseSpec || VirtualBaseSpec; 3702 } 3703 3704 /// Handle a C++ member initializer using braced-init-list syntax. 3705 MemInitResult 3706 Sema::ActOnMemInitializer(Decl *ConstructorD, 3707 Scope *S, 3708 CXXScopeSpec &SS, 3709 IdentifierInfo *MemberOrBase, 3710 ParsedType TemplateTypeTy, 3711 const DeclSpec &DS, 3712 SourceLocation IdLoc, 3713 Expr *InitList, 3714 SourceLocation EllipsisLoc) { 3715 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3716 DS, IdLoc, InitList, 3717 EllipsisLoc); 3718 } 3719 3720 /// Handle a C++ member initializer using parentheses syntax. 3721 MemInitResult 3722 Sema::ActOnMemInitializer(Decl *ConstructorD, 3723 Scope *S, 3724 CXXScopeSpec &SS, 3725 IdentifierInfo *MemberOrBase, 3726 ParsedType TemplateTypeTy, 3727 const DeclSpec &DS, 3728 SourceLocation IdLoc, 3729 SourceLocation LParenLoc, 3730 ArrayRef<Expr *> Args, 3731 SourceLocation RParenLoc, 3732 SourceLocation EllipsisLoc) { 3733 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 3734 Args, RParenLoc); 3735 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3736 DS, IdLoc, List, EllipsisLoc); 3737 } 3738 3739 namespace { 3740 3741 // Callback to only accept typo corrections that can be a valid C++ member 3742 // intializer: either a non-static field member or a base class. 3743 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 3744 public: 3745 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3746 : ClassDecl(ClassDecl) {} 3747 3748 bool ValidateCandidate(const TypoCorrection &candidate) override { 3749 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3750 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3751 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3752 return isa<TypeDecl>(ND); 3753 } 3754 return false; 3755 } 3756 3757 private: 3758 CXXRecordDecl *ClassDecl; 3759 }; 3760 3761 } 3762 3763 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 3764 CXXScopeSpec &SS, 3765 ParsedType TemplateTypeTy, 3766 IdentifierInfo *MemberOrBase) { 3767 if (SS.getScopeRep() || TemplateTypeTy) 3768 return nullptr; 3769 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3770 if (Result.empty()) 3771 return nullptr; 3772 ValueDecl *Member; 3773 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3774 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 3775 return Member; 3776 return nullptr; 3777 } 3778 3779 /// Handle a C++ member initializer. 3780 MemInitResult 3781 Sema::BuildMemInitializer(Decl *ConstructorD, 3782 Scope *S, 3783 CXXScopeSpec &SS, 3784 IdentifierInfo *MemberOrBase, 3785 ParsedType TemplateTypeTy, 3786 const DeclSpec &DS, 3787 SourceLocation IdLoc, 3788 Expr *Init, 3789 SourceLocation EllipsisLoc) { 3790 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3791 if (!Res.isUsable()) 3792 return true; 3793 Init = Res.get(); 3794 3795 if (!ConstructorD) 3796 return true; 3797 3798 AdjustDeclIfTemplate(ConstructorD); 3799 3800 CXXConstructorDecl *Constructor 3801 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3802 if (!Constructor) { 3803 // The user wrote a constructor initializer on a function that is 3804 // not a C++ constructor. Ignore the error for now, because we may 3805 // have more member initializers coming; we'll diagnose it just 3806 // once in ActOnMemInitializers. 3807 return true; 3808 } 3809 3810 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3811 3812 // C++ [class.base.init]p2: 3813 // Names in a mem-initializer-id are looked up in the scope of the 3814 // constructor's class and, if not found in that scope, are looked 3815 // up in the scope containing the constructor's definition. 3816 // [Note: if the constructor's class contains a member with the 3817 // same name as a direct or virtual base class of the class, a 3818 // mem-initializer-id naming the member or base class and composed 3819 // of a single identifier refers to the class member. A 3820 // mem-initializer-id for the hidden base class may be specified 3821 // using a qualified name. ] 3822 3823 // Look for a member, first. 3824 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 3825 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 3826 if (EllipsisLoc.isValid()) 3827 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 3828 << MemberOrBase 3829 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 3830 3831 return BuildMemberInitializer(Member, Init, IdLoc); 3832 } 3833 // It didn't name a member, so see if it names a class. 3834 QualType BaseType; 3835 TypeSourceInfo *TInfo = nullptr; 3836 3837 if (TemplateTypeTy) { 3838 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 3839 } else if (DS.getTypeSpecType() == TST_decltype) { 3840 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3841 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 3842 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 3843 return true; 3844 } else { 3845 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 3846 LookupParsedName(R, S, &SS); 3847 3848 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 3849 if (!TyD) { 3850 if (R.isAmbiguous()) return true; 3851 3852 // We don't want access-control diagnostics here. 3853 R.suppressDiagnostics(); 3854 3855 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 3856 bool NotUnknownSpecialization = false; 3857 DeclContext *DC = computeDeclContext(SS, false); 3858 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 3859 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 3860 3861 if (!NotUnknownSpecialization) { 3862 // When the scope specifier can refer to a member of an unknown 3863 // specialization, we take it as a type name. 3864 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 3865 SS.getWithLocInContext(Context), 3866 *MemberOrBase, IdLoc); 3867 if (BaseType.isNull()) 3868 return true; 3869 3870 TInfo = Context.CreateTypeSourceInfo(BaseType); 3871 DependentNameTypeLoc TL = 3872 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 3873 if (!TL.isNull()) { 3874 TL.setNameLoc(IdLoc); 3875 TL.setElaboratedKeywordLoc(SourceLocation()); 3876 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3877 } 3878 3879 R.clear(); 3880 R.setLookupName(MemberOrBase); 3881 } 3882 } 3883 3884 // If no results were found, try to correct typos. 3885 TypoCorrection Corr; 3886 if (R.empty() && BaseType.isNull() && 3887 (Corr = CorrectTypo( 3888 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 3889 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 3890 CTK_ErrorRecovery, ClassDecl))) { 3891 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 3892 // We have found a non-static data member with a similar 3893 // name to what was typed; complain and initialize that 3894 // member. 3895 diagnoseTypo(Corr, 3896 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3897 << MemberOrBase << true); 3898 return BuildMemberInitializer(Member, Init, IdLoc); 3899 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3900 const CXXBaseSpecifier *DirectBaseSpec; 3901 const CXXBaseSpecifier *VirtualBaseSpec; 3902 if (FindBaseInitializer(*this, ClassDecl, 3903 Context.getTypeDeclType(Type), 3904 DirectBaseSpec, VirtualBaseSpec)) { 3905 // We have found a direct or virtual base class with a 3906 // similar name to what was typed; complain and initialize 3907 // that base class. 3908 diagnoseTypo(Corr, 3909 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3910 << MemberOrBase << false, 3911 PDiag() /*Suppress note, we provide our own.*/); 3912 3913 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3914 : VirtualBaseSpec; 3915 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 3916 << BaseSpec->getType() << BaseSpec->getSourceRange(); 3917 3918 TyD = Type; 3919 } 3920 } 3921 } 3922 3923 if (!TyD && BaseType.isNull()) { 3924 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3925 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3926 return true; 3927 } 3928 } 3929 3930 if (BaseType.isNull()) { 3931 BaseType = Context.getTypeDeclType(TyD); 3932 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3933 if (SS.isSet()) { 3934 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3935 BaseType); 3936 TInfo = Context.CreateTypeSourceInfo(BaseType); 3937 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 3938 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 3939 TL.setElaboratedKeywordLoc(SourceLocation()); 3940 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3941 } 3942 } 3943 } 3944 3945 if (!TInfo) 3946 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3947 3948 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3949 } 3950 3951 MemInitResult 3952 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3953 SourceLocation IdLoc) { 3954 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3955 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3956 assert((DirectMember || IndirectMember) && 3957 "Member must be a FieldDecl or IndirectFieldDecl"); 3958 3959 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3960 return true; 3961 3962 if (Member->isInvalidDecl()) 3963 return true; 3964 3965 MultiExprArg Args; 3966 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3967 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3968 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3969 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3970 } else { 3971 // Template instantiation doesn't reconstruct ParenListExprs for us. 3972 Args = Init; 3973 } 3974 3975 SourceRange InitRange = Init->getSourceRange(); 3976 3977 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3978 // Can't check initialization for a member of dependent type or when 3979 // any of the arguments are type-dependent expressions. 3980 DiscardCleanupsInEvaluationContext(); 3981 } else { 3982 bool InitList = false; 3983 if (isa<InitListExpr>(Init)) { 3984 InitList = true; 3985 Args = Init; 3986 } 3987 3988 // Initialize the member. 3989 InitializedEntity MemberEntity = 3990 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3991 : InitializedEntity::InitializeMember(IndirectMember, 3992 nullptr); 3993 InitializationKind Kind = 3994 InitList ? InitializationKind::CreateDirectList( 3995 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 3996 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3997 InitRange.getEnd()); 3998 3999 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4000 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4001 nullptr); 4002 if (MemberInit.isInvalid()) 4003 return true; 4004 4005 // C++11 [class.base.init]p7: 4006 // The initialization of each base and member constitutes a 4007 // full-expression. 4008 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 4009 if (MemberInit.isInvalid()) 4010 return true; 4011 4012 Init = MemberInit.get(); 4013 } 4014 4015 if (DirectMember) { 4016 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4017 InitRange.getBegin(), Init, 4018 InitRange.getEnd()); 4019 } else { 4020 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4021 InitRange.getBegin(), Init, 4022 InitRange.getEnd()); 4023 } 4024 } 4025 4026 MemInitResult 4027 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4028 CXXRecordDecl *ClassDecl) { 4029 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4030 if (!LangOpts.CPlusPlus11) 4031 return Diag(NameLoc, diag::err_delegating_ctor) 4032 << TInfo->getTypeLoc().getLocalSourceRange(); 4033 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4034 4035 bool InitList = true; 4036 MultiExprArg Args = Init; 4037 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4038 InitList = false; 4039 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4040 } 4041 4042 SourceRange InitRange = Init->getSourceRange(); 4043 // Initialize the object. 4044 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4045 QualType(ClassDecl->getTypeForDecl(), 0)); 4046 InitializationKind Kind = 4047 InitList ? InitializationKind::CreateDirectList( 4048 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4049 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4050 InitRange.getEnd()); 4051 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4052 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4053 Args, nullptr); 4054 if (DelegationInit.isInvalid()) 4055 return true; 4056 4057 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4058 "Delegating constructor with no target?"); 4059 4060 // C++11 [class.base.init]p7: 4061 // The initialization of each base and member constitutes a 4062 // full-expression. 4063 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 4064 InitRange.getBegin()); 4065 if (DelegationInit.isInvalid()) 4066 return true; 4067 4068 // If we are in a dependent context, template instantiation will 4069 // perform this type-checking again. Just save the arguments that we 4070 // received in a ParenListExpr. 4071 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4072 // of the information that we have about the base 4073 // initializer. However, deconstructing the ASTs is a dicey process, 4074 // and this approach is far more likely to get the corner cases right. 4075 if (CurContext->isDependentContext()) 4076 DelegationInit = Init; 4077 4078 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4079 DelegationInit.getAs<Expr>(), 4080 InitRange.getEnd()); 4081 } 4082 4083 MemInitResult 4084 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4085 Expr *Init, CXXRecordDecl *ClassDecl, 4086 SourceLocation EllipsisLoc) { 4087 SourceLocation BaseLoc 4088 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4089 4090 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4091 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4092 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4093 4094 // C++ [class.base.init]p2: 4095 // [...] Unless the mem-initializer-id names a nonstatic data 4096 // member of the constructor's class or a direct or virtual base 4097 // of that class, the mem-initializer is ill-formed. A 4098 // mem-initializer-list can initialize a base class using any 4099 // name that denotes that base class type. 4100 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4101 4102 SourceRange InitRange = Init->getSourceRange(); 4103 if (EllipsisLoc.isValid()) { 4104 // This is a pack expansion. 4105 if (!BaseType->containsUnexpandedParameterPack()) { 4106 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4107 << SourceRange(BaseLoc, InitRange.getEnd()); 4108 4109 EllipsisLoc = SourceLocation(); 4110 } 4111 } else { 4112 // Check for any unexpanded parameter packs. 4113 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4114 return true; 4115 4116 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4117 return true; 4118 } 4119 4120 // Check for direct and virtual base classes. 4121 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4122 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4123 if (!Dependent) { 4124 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4125 BaseType)) 4126 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4127 4128 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4129 VirtualBaseSpec); 4130 4131 // C++ [base.class.init]p2: 4132 // Unless the mem-initializer-id names a nonstatic data member of the 4133 // constructor's class or a direct or virtual base of that class, the 4134 // mem-initializer is ill-formed. 4135 if (!DirectBaseSpec && !VirtualBaseSpec) { 4136 // If the class has any dependent bases, then it's possible that 4137 // one of those types will resolve to the same type as 4138 // BaseType. Therefore, just treat this as a dependent base 4139 // class initialization. FIXME: Should we try to check the 4140 // initialization anyway? It seems odd. 4141 if (ClassDecl->hasAnyDependentBases()) 4142 Dependent = true; 4143 else 4144 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4145 << BaseType << Context.getTypeDeclType(ClassDecl) 4146 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4147 } 4148 } 4149 4150 if (Dependent) { 4151 DiscardCleanupsInEvaluationContext(); 4152 4153 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4154 /*IsVirtual=*/false, 4155 InitRange.getBegin(), Init, 4156 InitRange.getEnd(), EllipsisLoc); 4157 } 4158 4159 // C++ [base.class.init]p2: 4160 // If a mem-initializer-id is ambiguous because it designates both 4161 // a direct non-virtual base class and an inherited virtual base 4162 // class, the mem-initializer is ill-formed. 4163 if (DirectBaseSpec && VirtualBaseSpec) 4164 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4165 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4166 4167 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4168 if (!BaseSpec) 4169 BaseSpec = VirtualBaseSpec; 4170 4171 // Initialize the base. 4172 bool InitList = true; 4173 MultiExprArg Args = Init; 4174 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4175 InitList = false; 4176 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4177 } 4178 4179 InitializedEntity BaseEntity = 4180 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4181 InitializationKind Kind = 4182 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4183 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4184 InitRange.getEnd()); 4185 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4186 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4187 if (BaseInit.isInvalid()) 4188 return true; 4189 4190 // C++11 [class.base.init]p7: 4191 // The initialization of each base and member constitutes a 4192 // full-expression. 4193 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 4194 if (BaseInit.isInvalid()) 4195 return true; 4196 4197 // If we are in a dependent context, template instantiation will 4198 // perform this type-checking again. Just save the arguments that we 4199 // received in a ParenListExpr. 4200 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4201 // of the information that we have about the base 4202 // initializer. However, deconstructing the ASTs is a dicey process, 4203 // and this approach is far more likely to get the corner cases right. 4204 if (CurContext->isDependentContext()) 4205 BaseInit = Init; 4206 4207 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4208 BaseSpec->isVirtual(), 4209 InitRange.getBegin(), 4210 BaseInit.getAs<Expr>(), 4211 InitRange.getEnd(), EllipsisLoc); 4212 } 4213 4214 // Create a static_cast\<T&&>(expr). 4215 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4216 if (T.isNull()) T = E->getType(); 4217 QualType TargetType = SemaRef.BuildReferenceType( 4218 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4219 SourceLocation ExprLoc = E->getBeginLoc(); 4220 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4221 TargetType, ExprLoc); 4222 4223 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4224 SourceRange(ExprLoc, ExprLoc), 4225 E->getSourceRange()).get(); 4226 } 4227 4228 /// ImplicitInitializerKind - How an implicit base or member initializer should 4229 /// initialize its base or member. 4230 enum ImplicitInitializerKind { 4231 IIK_Default, 4232 IIK_Copy, 4233 IIK_Move, 4234 IIK_Inherit 4235 }; 4236 4237 static bool 4238 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4239 ImplicitInitializerKind ImplicitInitKind, 4240 CXXBaseSpecifier *BaseSpec, 4241 bool IsInheritedVirtualBase, 4242 CXXCtorInitializer *&CXXBaseInit) { 4243 InitializedEntity InitEntity 4244 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4245 IsInheritedVirtualBase); 4246 4247 ExprResult BaseInit; 4248 4249 switch (ImplicitInitKind) { 4250 case IIK_Inherit: 4251 case IIK_Default: { 4252 InitializationKind InitKind 4253 = InitializationKind::CreateDefault(Constructor->getLocation()); 4254 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4255 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4256 break; 4257 } 4258 4259 case IIK_Move: 4260 case IIK_Copy: { 4261 bool Moving = ImplicitInitKind == IIK_Move; 4262 ParmVarDecl *Param = Constructor->getParamDecl(0); 4263 QualType ParamType = Param->getType().getNonReferenceType(); 4264 4265 Expr *CopyCtorArg = 4266 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4267 SourceLocation(), Param, false, 4268 Constructor->getLocation(), ParamType, 4269 VK_LValue, nullptr); 4270 4271 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4272 4273 // Cast to the base class to avoid ambiguities. 4274 QualType ArgTy = 4275 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4276 ParamType.getQualifiers()); 4277 4278 if (Moving) { 4279 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4280 } 4281 4282 CXXCastPath BasePath; 4283 BasePath.push_back(BaseSpec); 4284 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4285 CK_UncheckedDerivedToBase, 4286 Moving ? VK_XValue : VK_LValue, 4287 &BasePath).get(); 4288 4289 InitializationKind InitKind 4290 = InitializationKind::CreateDirect(Constructor->getLocation(), 4291 SourceLocation(), SourceLocation()); 4292 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4293 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4294 break; 4295 } 4296 } 4297 4298 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4299 if (BaseInit.isInvalid()) 4300 return true; 4301 4302 CXXBaseInit = 4303 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4304 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4305 SourceLocation()), 4306 BaseSpec->isVirtual(), 4307 SourceLocation(), 4308 BaseInit.getAs<Expr>(), 4309 SourceLocation(), 4310 SourceLocation()); 4311 4312 return false; 4313 } 4314 4315 static bool RefersToRValueRef(Expr *MemRef) { 4316 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4317 return Referenced->getType()->isRValueReferenceType(); 4318 } 4319 4320 static bool 4321 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4322 ImplicitInitializerKind ImplicitInitKind, 4323 FieldDecl *Field, IndirectFieldDecl *Indirect, 4324 CXXCtorInitializer *&CXXMemberInit) { 4325 if (Field->isInvalidDecl()) 4326 return true; 4327 4328 SourceLocation Loc = Constructor->getLocation(); 4329 4330 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4331 bool Moving = ImplicitInitKind == IIK_Move; 4332 ParmVarDecl *Param = Constructor->getParamDecl(0); 4333 QualType ParamType = Param->getType().getNonReferenceType(); 4334 4335 // Suppress copying zero-width bitfields. 4336 if (Field->isZeroLengthBitField(SemaRef.Context)) 4337 return false; 4338 4339 Expr *MemberExprBase = 4340 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4341 SourceLocation(), Param, false, 4342 Loc, ParamType, VK_LValue, nullptr); 4343 4344 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4345 4346 if (Moving) { 4347 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4348 } 4349 4350 // Build a reference to this field within the parameter. 4351 CXXScopeSpec SS; 4352 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4353 Sema::LookupMemberName); 4354 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4355 : cast<ValueDecl>(Field), AS_public); 4356 MemberLookup.resolveKind(); 4357 ExprResult CtorArg 4358 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4359 ParamType, Loc, 4360 /*IsArrow=*/false, 4361 SS, 4362 /*TemplateKWLoc=*/SourceLocation(), 4363 /*FirstQualifierInScope=*/nullptr, 4364 MemberLookup, 4365 /*TemplateArgs=*/nullptr, 4366 /*S*/nullptr); 4367 if (CtorArg.isInvalid()) 4368 return true; 4369 4370 // C++11 [class.copy]p15: 4371 // - if a member m has rvalue reference type T&&, it is direct-initialized 4372 // with static_cast<T&&>(x.m); 4373 if (RefersToRValueRef(CtorArg.get())) { 4374 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4375 } 4376 4377 InitializedEntity Entity = 4378 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4379 /*Implicit*/ true) 4380 : InitializedEntity::InitializeMember(Field, nullptr, 4381 /*Implicit*/ true); 4382 4383 // Direct-initialize to use the copy constructor. 4384 InitializationKind InitKind = 4385 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4386 4387 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4388 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4389 ExprResult MemberInit = 4390 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4391 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4392 if (MemberInit.isInvalid()) 4393 return true; 4394 4395 if (Indirect) 4396 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4397 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4398 else 4399 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4400 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4401 return false; 4402 } 4403 4404 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4405 "Unhandled implicit init kind!"); 4406 4407 QualType FieldBaseElementType = 4408 SemaRef.Context.getBaseElementType(Field->getType()); 4409 4410 if (FieldBaseElementType->isRecordType()) { 4411 InitializedEntity InitEntity = 4412 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4413 /*Implicit*/ true) 4414 : InitializedEntity::InitializeMember(Field, nullptr, 4415 /*Implicit*/ true); 4416 InitializationKind InitKind = 4417 InitializationKind::CreateDefault(Loc); 4418 4419 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4420 ExprResult MemberInit = 4421 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4422 4423 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4424 if (MemberInit.isInvalid()) 4425 return true; 4426 4427 if (Indirect) 4428 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4429 Indirect, Loc, 4430 Loc, 4431 MemberInit.get(), 4432 Loc); 4433 else 4434 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4435 Field, Loc, Loc, 4436 MemberInit.get(), 4437 Loc); 4438 return false; 4439 } 4440 4441 if (!Field->getParent()->isUnion()) { 4442 if (FieldBaseElementType->isReferenceType()) { 4443 SemaRef.Diag(Constructor->getLocation(), 4444 diag::err_uninitialized_member_in_ctor) 4445 << (int)Constructor->isImplicit() 4446 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4447 << 0 << Field->getDeclName(); 4448 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4449 return true; 4450 } 4451 4452 if (FieldBaseElementType.isConstQualified()) { 4453 SemaRef.Diag(Constructor->getLocation(), 4454 diag::err_uninitialized_member_in_ctor) 4455 << (int)Constructor->isImplicit() 4456 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4457 << 1 << Field->getDeclName(); 4458 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4459 return true; 4460 } 4461 } 4462 4463 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4464 // ARC and Weak: 4465 // Default-initialize Objective-C pointers to NULL. 4466 CXXMemberInit 4467 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4468 Loc, Loc, 4469 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4470 Loc); 4471 return false; 4472 } 4473 4474 // Nothing to initialize. 4475 CXXMemberInit = nullptr; 4476 return false; 4477 } 4478 4479 namespace { 4480 struct BaseAndFieldInfo { 4481 Sema &S; 4482 CXXConstructorDecl *Ctor; 4483 bool AnyErrorsInInits; 4484 ImplicitInitializerKind IIK; 4485 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4486 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4487 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4488 4489 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4490 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4491 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4492 if (Ctor->getInheritedConstructor()) 4493 IIK = IIK_Inherit; 4494 else if (Generated && Ctor->isCopyConstructor()) 4495 IIK = IIK_Copy; 4496 else if (Generated && Ctor->isMoveConstructor()) 4497 IIK = IIK_Move; 4498 else 4499 IIK = IIK_Default; 4500 } 4501 4502 bool isImplicitCopyOrMove() const { 4503 switch (IIK) { 4504 case IIK_Copy: 4505 case IIK_Move: 4506 return true; 4507 4508 case IIK_Default: 4509 case IIK_Inherit: 4510 return false; 4511 } 4512 4513 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4514 } 4515 4516 bool addFieldInitializer(CXXCtorInitializer *Init) { 4517 AllToInit.push_back(Init); 4518 4519 // Check whether this initializer makes the field "used". 4520 if (Init->getInit()->HasSideEffects(S.Context)) 4521 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4522 4523 return false; 4524 } 4525 4526 bool isInactiveUnionMember(FieldDecl *Field) { 4527 RecordDecl *Record = Field->getParent(); 4528 if (!Record->isUnion()) 4529 return false; 4530 4531 if (FieldDecl *Active = 4532 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4533 return Active != Field->getCanonicalDecl(); 4534 4535 // In an implicit copy or move constructor, ignore any in-class initializer. 4536 if (isImplicitCopyOrMove()) 4537 return true; 4538 4539 // If there's no explicit initialization, the field is active only if it 4540 // has an in-class initializer... 4541 if (Field->hasInClassInitializer()) 4542 return false; 4543 // ... or it's an anonymous struct or union whose class has an in-class 4544 // initializer. 4545 if (!Field->isAnonymousStructOrUnion()) 4546 return true; 4547 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4548 return !FieldRD->hasInClassInitializer(); 4549 } 4550 4551 /// Determine whether the given field is, or is within, a union member 4552 /// that is inactive (because there was an initializer given for a different 4553 /// member of the union, or because the union was not initialized at all). 4554 bool isWithinInactiveUnionMember(FieldDecl *Field, 4555 IndirectFieldDecl *Indirect) { 4556 if (!Indirect) 4557 return isInactiveUnionMember(Field); 4558 4559 for (auto *C : Indirect->chain()) { 4560 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4561 if (Field && isInactiveUnionMember(Field)) 4562 return true; 4563 } 4564 return false; 4565 } 4566 }; 4567 } 4568 4569 /// Determine whether the given type is an incomplete or zero-lenfgth 4570 /// array type. 4571 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4572 if (T->isIncompleteArrayType()) 4573 return true; 4574 4575 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4576 if (!ArrayT->getSize()) 4577 return true; 4578 4579 T = ArrayT->getElementType(); 4580 } 4581 4582 return false; 4583 } 4584 4585 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4586 FieldDecl *Field, 4587 IndirectFieldDecl *Indirect = nullptr) { 4588 if (Field->isInvalidDecl()) 4589 return false; 4590 4591 // Overwhelmingly common case: we have a direct initializer for this field. 4592 if (CXXCtorInitializer *Init = 4593 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4594 return Info.addFieldInitializer(Init); 4595 4596 // C++11 [class.base.init]p8: 4597 // if the entity is a non-static data member that has a 4598 // brace-or-equal-initializer and either 4599 // -- the constructor's class is a union and no other variant member of that 4600 // union is designated by a mem-initializer-id or 4601 // -- the constructor's class is not a union, and, if the entity is a member 4602 // of an anonymous union, no other member of that union is designated by 4603 // a mem-initializer-id, 4604 // the entity is initialized as specified in [dcl.init]. 4605 // 4606 // We also apply the same rules to handle anonymous structs within anonymous 4607 // unions. 4608 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4609 return false; 4610 4611 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4612 ExprResult DIE = 4613 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4614 if (DIE.isInvalid()) 4615 return true; 4616 4617 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4618 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4619 4620 CXXCtorInitializer *Init; 4621 if (Indirect) 4622 Init = new (SemaRef.Context) 4623 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4624 SourceLocation(), DIE.get(), SourceLocation()); 4625 else 4626 Init = new (SemaRef.Context) 4627 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4628 SourceLocation(), DIE.get(), SourceLocation()); 4629 return Info.addFieldInitializer(Init); 4630 } 4631 4632 // Don't initialize incomplete or zero-length arrays. 4633 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4634 return false; 4635 4636 // Don't try to build an implicit initializer if there were semantic 4637 // errors in any of the initializers (and therefore we might be 4638 // missing some that the user actually wrote). 4639 if (Info.AnyErrorsInInits) 4640 return false; 4641 4642 CXXCtorInitializer *Init = nullptr; 4643 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4644 Indirect, Init)) 4645 return true; 4646 4647 if (!Init) 4648 return false; 4649 4650 return Info.addFieldInitializer(Init); 4651 } 4652 4653 bool 4654 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4655 CXXCtorInitializer *Initializer) { 4656 assert(Initializer->isDelegatingInitializer()); 4657 Constructor->setNumCtorInitializers(1); 4658 CXXCtorInitializer **initializer = 4659 new (Context) CXXCtorInitializer*[1]; 4660 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4661 Constructor->setCtorInitializers(initializer); 4662 4663 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4664 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4665 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4666 } 4667 4668 DelegatingCtorDecls.push_back(Constructor); 4669 4670 DiagnoseUninitializedFields(*this, Constructor); 4671 4672 return false; 4673 } 4674 4675 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4676 ArrayRef<CXXCtorInitializer *> Initializers) { 4677 if (Constructor->isDependentContext()) { 4678 // Just store the initializers as written, they will be checked during 4679 // instantiation. 4680 if (!Initializers.empty()) { 4681 Constructor->setNumCtorInitializers(Initializers.size()); 4682 CXXCtorInitializer **baseOrMemberInitializers = 4683 new (Context) CXXCtorInitializer*[Initializers.size()]; 4684 memcpy(baseOrMemberInitializers, Initializers.data(), 4685 Initializers.size() * sizeof(CXXCtorInitializer*)); 4686 Constructor->setCtorInitializers(baseOrMemberInitializers); 4687 } 4688 4689 // Let template instantiation know whether we had errors. 4690 if (AnyErrors) 4691 Constructor->setInvalidDecl(); 4692 4693 return false; 4694 } 4695 4696 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4697 4698 // We need to build the initializer AST according to order of construction 4699 // and not what user specified in the Initializers list. 4700 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4701 if (!ClassDecl) 4702 return true; 4703 4704 bool HadError = false; 4705 4706 for (unsigned i = 0; i < Initializers.size(); i++) { 4707 CXXCtorInitializer *Member = Initializers[i]; 4708 4709 if (Member->isBaseInitializer()) 4710 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4711 else { 4712 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4713 4714 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4715 for (auto *C : F->chain()) { 4716 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4717 if (FD && FD->getParent()->isUnion()) 4718 Info.ActiveUnionMember.insert(std::make_pair( 4719 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4720 } 4721 } else if (FieldDecl *FD = Member->getMember()) { 4722 if (FD->getParent()->isUnion()) 4723 Info.ActiveUnionMember.insert(std::make_pair( 4724 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4725 } 4726 } 4727 } 4728 4729 // Keep track of the direct virtual bases. 4730 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4731 for (auto &I : ClassDecl->bases()) { 4732 if (I.isVirtual()) 4733 DirectVBases.insert(&I); 4734 } 4735 4736 // Push virtual bases before others. 4737 for (auto &VBase : ClassDecl->vbases()) { 4738 if (CXXCtorInitializer *Value 4739 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4740 // [class.base.init]p7, per DR257: 4741 // A mem-initializer where the mem-initializer-id names a virtual base 4742 // class is ignored during execution of a constructor of any class that 4743 // is not the most derived class. 4744 if (ClassDecl->isAbstract()) { 4745 // FIXME: Provide a fixit to remove the base specifier. This requires 4746 // tracking the location of the associated comma for a base specifier. 4747 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4748 << VBase.getType() << ClassDecl; 4749 DiagnoseAbstractType(ClassDecl); 4750 } 4751 4752 Info.AllToInit.push_back(Value); 4753 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4754 // [class.base.init]p8, per DR257: 4755 // If a given [...] base class is not named by a mem-initializer-id 4756 // [...] and the entity is not a virtual base class of an abstract 4757 // class, then [...] the entity is default-initialized. 4758 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4759 CXXCtorInitializer *CXXBaseInit; 4760 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4761 &VBase, IsInheritedVirtualBase, 4762 CXXBaseInit)) { 4763 HadError = true; 4764 continue; 4765 } 4766 4767 Info.AllToInit.push_back(CXXBaseInit); 4768 } 4769 } 4770 4771 // Non-virtual bases. 4772 for (auto &Base : ClassDecl->bases()) { 4773 // Virtuals are in the virtual base list and already constructed. 4774 if (Base.isVirtual()) 4775 continue; 4776 4777 if (CXXCtorInitializer *Value 4778 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4779 Info.AllToInit.push_back(Value); 4780 } else if (!AnyErrors) { 4781 CXXCtorInitializer *CXXBaseInit; 4782 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4783 &Base, /*IsInheritedVirtualBase=*/false, 4784 CXXBaseInit)) { 4785 HadError = true; 4786 continue; 4787 } 4788 4789 Info.AllToInit.push_back(CXXBaseInit); 4790 } 4791 } 4792 4793 // Fields. 4794 for (auto *Mem : ClassDecl->decls()) { 4795 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4796 // C++ [class.bit]p2: 4797 // A declaration for a bit-field that omits the identifier declares an 4798 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4799 // initialized. 4800 if (F->isUnnamedBitfield()) 4801 continue; 4802 4803 // If we're not generating the implicit copy/move constructor, then we'll 4804 // handle anonymous struct/union fields based on their individual 4805 // indirect fields. 4806 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4807 continue; 4808 4809 if (CollectFieldInitializer(*this, Info, F)) 4810 HadError = true; 4811 continue; 4812 } 4813 4814 // Beyond this point, we only consider default initialization. 4815 if (Info.isImplicitCopyOrMove()) 4816 continue; 4817 4818 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4819 if (F->getType()->isIncompleteArrayType()) { 4820 assert(ClassDecl->hasFlexibleArrayMember() && 4821 "Incomplete array type is not valid"); 4822 continue; 4823 } 4824 4825 // Initialize each field of an anonymous struct individually. 4826 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4827 HadError = true; 4828 4829 continue; 4830 } 4831 } 4832 4833 unsigned NumInitializers = Info.AllToInit.size(); 4834 if (NumInitializers > 0) { 4835 Constructor->setNumCtorInitializers(NumInitializers); 4836 CXXCtorInitializer **baseOrMemberInitializers = 4837 new (Context) CXXCtorInitializer*[NumInitializers]; 4838 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4839 NumInitializers * sizeof(CXXCtorInitializer*)); 4840 Constructor->setCtorInitializers(baseOrMemberInitializers); 4841 4842 // Constructors implicitly reference the base and member 4843 // destructors. 4844 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4845 Constructor->getParent()); 4846 } 4847 4848 return HadError; 4849 } 4850 4851 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4852 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4853 const RecordDecl *RD = RT->getDecl(); 4854 if (RD->isAnonymousStructOrUnion()) { 4855 for (auto *Field : RD->fields()) 4856 PopulateKeysForFields(Field, IdealInits); 4857 return; 4858 } 4859 } 4860 IdealInits.push_back(Field->getCanonicalDecl()); 4861 } 4862 4863 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4864 return Context.getCanonicalType(BaseType).getTypePtr(); 4865 } 4866 4867 static const void *GetKeyForMember(ASTContext &Context, 4868 CXXCtorInitializer *Member) { 4869 if (!Member->isAnyMemberInitializer()) 4870 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4871 4872 return Member->getAnyMember()->getCanonicalDecl(); 4873 } 4874 4875 static void DiagnoseBaseOrMemInitializerOrder( 4876 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4877 ArrayRef<CXXCtorInitializer *> Inits) { 4878 if (Constructor->getDeclContext()->isDependentContext()) 4879 return; 4880 4881 // Don't check initializers order unless the warning is enabled at the 4882 // location of at least one initializer. 4883 bool ShouldCheckOrder = false; 4884 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4885 CXXCtorInitializer *Init = Inits[InitIndex]; 4886 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4887 Init->getSourceLocation())) { 4888 ShouldCheckOrder = true; 4889 break; 4890 } 4891 } 4892 if (!ShouldCheckOrder) 4893 return; 4894 4895 // Build the list of bases and members in the order that they'll 4896 // actually be initialized. The explicit initializers should be in 4897 // this same order but may be missing things. 4898 SmallVector<const void*, 32> IdealInitKeys; 4899 4900 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4901 4902 // 1. Virtual bases. 4903 for (const auto &VBase : ClassDecl->vbases()) 4904 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4905 4906 // 2. Non-virtual bases. 4907 for (const auto &Base : ClassDecl->bases()) { 4908 if (Base.isVirtual()) 4909 continue; 4910 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4911 } 4912 4913 // 3. Direct fields. 4914 for (auto *Field : ClassDecl->fields()) { 4915 if (Field->isUnnamedBitfield()) 4916 continue; 4917 4918 PopulateKeysForFields(Field, IdealInitKeys); 4919 } 4920 4921 unsigned NumIdealInits = IdealInitKeys.size(); 4922 unsigned IdealIndex = 0; 4923 4924 CXXCtorInitializer *PrevInit = nullptr; 4925 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4926 CXXCtorInitializer *Init = Inits[InitIndex]; 4927 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4928 4929 // Scan forward to try to find this initializer in the idealized 4930 // initializers list. 4931 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4932 if (InitKey == IdealInitKeys[IdealIndex]) 4933 break; 4934 4935 // If we didn't find this initializer, it must be because we 4936 // scanned past it on a previous iteration. That can only 4937 // happen if we're out of order; emit a warning. 4938 if (IdealIndex == NumIdealInits && PrevInit) { 4939 Sema::SemaDiagnosticBuilder D = 4940 SemaRef.Diag(PrevInit->getSourceLocation(), 4941 diag::warn_initializer_out_of_order); 4942 4943 if (PrevInit->isAnyMemberInitializer()) 4944 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4945 else 4946 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4947 4948 if (Init->isAnyMemberInitializer()) 4949 D << 0 << Init->getAnyMember()->getDeclName(); 4950 else 4951 D << 1 << Init->getTypeSourceInfo()->getType(); 4952 4953 // Move back to the initializer's location in the ideal list. 4954 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4955 if (InitKey == IdealInitKeys[IdealIndex]) 4956 break; 4957 4958 assert(IdealIndex < NumIdealInits && 4959 "initializer not found in initializer list"); 4960 } 4961 4962 PrevInit = Init; 4963 } 4964 } 4965 4966 namespace { 4967 bool CheckRedundantInit(Sema &S, 4968 CXXCtorInitializer *Init, 4969 CXXCtorInitializer *&PrevInit) { 4970 if (!PrevInit) { 4971 PrevInit = Init; 4972 return false; 4973 } 4974 4975 if (FieldDecl *Field = Init->getAnyMember()) 4976 S.Diag(Init->getSourceLocation(), 4977 diag::err_multiple_mem_initialization) 4978 << Field->getDeclName() 4979 << Init->getSourceRange(); 4980 else { 4981 const Type *BaseClass = Init->getBaseClass(); 4982 assert(BaseClass && "neither field nor base"); 4983 S.Diag(Init->getSourceLocation(), 4984 diag::err_multiple_base_initialization) 4985 << QualType(BaseClass, 0) 4986 << Init->getSourceRange(); 4987 } 4988 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4989 << 0 << PrevInit->getSourceRange(); 4990 4991 return true; 4992 } 4993 4994 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4995 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4996 4997 bool CheckRedundantUnionInit(Sema &S, 4998 CXXCtorInitializer *Init, 4999 RedundantUnionMap &Unions) { 5000 FieldDecl *Field = Init->getAnyMember(); 5001 RecordDecl *Parent = Field->getParent(); 5002 NamedDecl *Child = Field; 5003 5004 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5005 if (Parent->isUnion()) { 5006 UnionEntry &En = Unions[Parent]; 5007 if (En.first && En.first != Child) { 5008 S.Diag(Init->getSourceLocation(), 5009 diag::err_multiple_mem_union_initialization) 5010 << Field->getDeclName() 5011 << Init->getSourceRange(); 5012 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5013 << 0 << En.second->getSourceRange(); 5014 return true; 5015 } 5016 if (!En.first) { 5017 En.first = Child; 5018 En.second = Init; 5019 } 5020 if (!Parent->isAnonymousStructOrUnion()) 5021 return false; 5022 } 5023 5024 Child = Parent; 5025 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5026 } 5027 5028 return false; 5029 } 5030 } 5031 5032 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5033 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5034 SourceLocation ColonLoc, 5035 ArrayRef<CXXCtorInitializer*> MemInits, 5036 bool AnyErrors) { 5037 if (!ConstructorDecl) 5038 return; 5039 5040 AdjustDeclIfTemplate(ConstructorDecl); 5041 5042 CXXConstructorDecl *Constructor 5043 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5044 5045 if (!Constructor) { 5046 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5047 return; 5048 } 5049 5050 // Mapping for the duplicate initializers check. 5051 // For member initializers, this is keyed with a FieldDecl*. 5052 // For base initializers, this is keyed with a Type*. 5053 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5054 5055 // Mapping for the inconsistent anonymous-union initializers check. 5056 RedundantUnionMap MemberUnions; 5057 5058 bool HadError = false; 5059 for (unsigned i = 0; i < MemInits.size(); i++) { 5060 CXXCtorInitializer *Init = MemInits[i]; 5061 5062 // Set the source order index. 5063 Init->setSourceOrder(i); 5064 5065 if (Init->isAnyMemberInitializer()) { 5066 const void *Key = GetKeyForMember(Context, Init); 5067 if (CheckRedundantInit(*this, Init, Members[Key]) || 5068 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5069 HadError = true; 5070 } else if (Init->isBaseInitializer()) { 5071 const void *Key = GetKeyForMember(Context, Init); 5072 if (CheckRedundantInit(*this, Init, Members[Key])) 5073 HadError = true; 5074 } else { 5075 assert(Init->isDelegatingInitializer()); 5076 // This must be the only initializer 5077 if (MemInits.size() != 1) { 5078 Diag(Init->getSourceLocation(), 5079 diag::err_delegating_initializer_alone) 5080 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5081 // We will treat this as being the only initializer. 5082 } 5083 SetDelegatingInitializer(Constructor, MemInits[i]); 5084 // Return immediately as the initializer is set. 5085 return; 5086 } 5087 } 5088 5089 if (HadError) 5090 return; 5091 5092 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5093 5094 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5095 5096 DiagnoseUninitializedFields(*this, Constructor); 5097 } 5098 5099 void 5100 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5101 CXXRecordDecl *ClassDecl) { 5102 // Ignore dependent contexts. Also ignore unions, since their members never 5103 // have destructors implicitly called. 5104 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5105 return; 5106 5107 // FIXME: all the access-control diagnostics are positioned on the 5108 // field/base declaration. That's probably good; that said, the 5109 // user might reasonably want to know why the destructor is being 5110 // emitted, and we currently don't say. 5111 5112 // Non-static data members. 5113 for (auto *Field : ClassDecl->fields()) { 5114 if (Field->isInvalidDecl()) 5115 continue; 5116 5117 // Don't destroy incomplete or zero-length arrays. 5118 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5119 continue; 5120 5121 QualType FieldType = Context.getBaseElementType(Field->getType()); 5122 5123 const RecordType* RT = FieldType->getAs<RecordType>(); 5124 if (!RT) 5125 continue; 5126 5127 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5128 if (FieldClassDecl->isInvalidDecl()) 5129 continue; 5130 if (FieldClassDecl->hasIrrelevantDestructor()) 5131 continue; 5132 // The destructor for an implicit anonymous union member is never invoked. 5133 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5134 continue; 5135 5136 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5137 assert(Dtor && "No dtor found for FieldClassDecl!"); 5138 CheckDestructorAccess(Field->getLocation(), Dtor, 5139 PDiag(diag::err_access_dtor_field) 5140 << Field->getDeclName() 5141 << FieldType); 5142 5143 MarkFunctionReferenced(Location, Dtor); 5144 DiagnoseUseOfDecl(Dtor, Location); 5145 } 5146 5147 // We only potentially invoke the destructors of potentially constructed 5148 // subobjects. 5149 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5150 5151 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5152 5153 // Bases. 5154 for (const auto &Base : ClassDecl->bases()) { 5155 // Bases are always records in a well-formed non-dependent class. 5156 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5157 5158 // Remember direct virtual bases. 5159 if (Base.isVirtual()) { 5160 if (!VisitVirtualBases) 5161 continue; 5162 DirectVirtualBases.insert(RT); 5163 } 5164 5165 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5166 // If our base class is invalid, we probably can't get its dtor anyway. 5167 if (BaseClassDecl->isInvalidDecl()) 5168 continue; 5169 if (BaseClassDecl->hasIrrelevantDestructor()) 5170 continue; 5171 5172 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5173 assert(Dtor && "No dtor found for BaseClassDecl!"); 5174 5175 // FIXME: caret should be on the start of the class name 5176 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5177 PDiag(diag::err_access_dtor_base) 5178 << Base.getType() << Base.getSourceRange(), 5179 Context.getTypeDeclType(ClassDecl)); 5180 5181 MarkFunctionReferenced(Location, Dtor); 5182 DiagnoseUseOfDecl(Dtor, Location); 5183 } 5184 5185 if (!VisitVirtualBases) 5186 return; 5187 5188 // Virtual bases. 5189 for (const auto &VBase : ClassDecl->vbases()) { 5190 // Bases are always records in a well-formed non-dependent class. 5191 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5192 5193 // Ignore direct virtual bases. 5194 if (DirectVirtualBases.count(RT)) 5195 continue; 5196 5197 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5198 // If our base class is invalid, we probably can't get its dtor anyway. 5199 if (BaseClassDecl->isInvalidDecl()) 5200 continue; 5201 if (BaseClassDecl->hasIrrelevantDestructor()) 5202 continue; 5203 5204 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5205 assert(Dtor && "No dtor found for BaseClassDecl!"); 5206 if (CheckDestructorAccess( 5207 ClassDecl->getLocation(), Dtor, 5208 PDiag(diag::err_access_dtor_vbase) 5209 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5210 Context.getTypeDeclType(ClassDecl)) == 5211 AR_accessible) { 5212 CheckDerivedToBaseConversion( 5213 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5214 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5215 SourceRange(), DeclarationName(), nullptr); 5216 } 5217 5218 MarkFunctionReferenced(Location, Dtor); 5219 DiagnoseUseOfDecl(Dtor, Location); 5220 } 5221 } 5222 5223 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5224 if (!CDtorDecl) 5225 return; 5226 5227 if (CXXConstructorDecl *Constructor 5228 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5229 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5230 DiagnoseUninitializedFields(*this, Constructor); 5231 } 5232 } 5233 5234 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5235 if (!getLangOpts().CPlusPlus) 5236 return false; 5237 5238 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5239 if (!RD) 5240 return false; 5241 5242 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5243 // class template specialization here, but doing so breaks a lot of code. 5244 5245 // We can't answer whether something is abstract until it has a 5246 // definition. If it's currently being defined, we'll walk back 5247 // over all the declarations when we have a full definition. 5248 const CXXRecordDecl *Def = RD->getDefinition(); 5249 if (!Def || Def->isBeingDefined()) 5250 return false; 5251 5252 return RD->isAbstract(); 5253 } 5254 5255 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5256 TypeDiagnoser &Diagnoser) { 5257 if (!isAbstractType(Loc, T)) 5258 return false; 5259 5260 T = Context.getBaseElementType(T); 5261 Diagnoser.diagnose(*this, Loc, T); 5262 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5263 return true; 5264 } 5265 5266 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5267 // Check if we've already emitted the list of pure virtual functions 5268 // for this class. 5269 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5270 return; 5271 5272 // If the diagnostic is suppressed, don't emit the notes. We're only 5273 // going to emit them once, so try to attach them to a diagnostic we're 5274 // actually going to show. 5275 if (Diags.isLastDiagnosticIgnored()) 5276 return; 5277 5278 CXXFinalOverriderMap FinalOverriders; 5279 RD->getFinalOverriders(FinalOverriders); 5280 5281 // Keep a set of seen pure methods so we won't diagnose the same method 5282 // more than once. 5283 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5284 5285 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5286 MEnd = FinalOverriders.end(); 5287 M != MEnd; 5288 ++M) { 5289 for (OverridingMethods::iterator SO = M->second.begin(), 5290 SOEnd = M->second.end(); 5291 SO != SOEnd; ++SO) { 5292 // C++ [class.abstract]p4: 5293 // A class is abstract if it contains or inherits at least one 5294 // pure virtual function for which the final overrider is pure 5295 // virtual. 5296 5297 // 5298 if (SO->second.size() != 1) 5299 continue; 5300 5301 if (!SO->second.front().Method->isPure()) 5302 continue; 5303 5304 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5305 continue; 5306 5307 Diag(SO->second.front().Method->getLocation(), 5308 diag::note_pure_virtual_function) 5309 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5310 } 5311 } 5312 5313 if (!PureVirtualClassDiagSet) 5314 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5315 PureVirtualClassDiagSet->insert(RD); 5316 } 5317 5318 namespace { 5319 struct AbstractUsageInfo { 5320 Sema &S; 5321 CXXRecordDecl *Record; 5322 CanQualType AbstractType; 5323 bool Invalid; 5324 5325 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5326 : S(S), Record(Record), 5327 AbstractType(S.Context.getCanonicalType( 5328 S.Context.getTypeDeclType(Record))), 5329 Invalid(false) {} 5330 5331 void DiagnoseAbstractType() { 5332 if (Invalid) return; 5333 S.DiagnoseAbstractType(Record); 5334 Invalid = true; 5335 } 5336 5337 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5338 }; 5339 5340 struct CheckAbstractUsage { 5341 AbstractUsageInfo &Info; 5342 const NamedDecl *Ctx; 5343 5344 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5345 : Info(Info), Ctx(Ctx) {} 5346 5347 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5348 switch (TL.getTypeLocClass()) { 5349 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5350 #define TYPELOC(CLASS, PARENT) \ 5351 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5352 #include "clang/AST/TypeLocNodes.def" 5353 } 5354 } 5355 5356 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5357 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5358 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5359 if (!TL.getParam(I)) 5360 continue; 5361 5362 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5363 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5364 } 5365 } 5366 5367 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5368 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5369 } 5370 5371 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5372 // Visit the type parameters from a permissive context. 5373 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5374 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5375 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5376 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5377 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5378 // TODO: other template argument types? 5379 } 5380 } 5381 5382 // Visit pointee types from a permissive context. 5383 #define CheckPolymorphic(Type) \ 5384 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5385 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5386 } 5387 CheckPolymorphic(PointerTypeLoc) 5388 CheckPolymorphic(ReferenceTypeLoc) 5389 CheckPolymorphic(MemberPointerTypeLoc) 5390 CheckPolymorphic(BlockPointerTypeLoc) 5391 CheckPolymorphic(AtomicTypeLoc) 5392 5393 /// Handle all the types we haven't given a more specific 5394 /// implementation for above. 5395 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5396 // Every other kind of type that we haven't called out already 5397 // that has an inner type is either (1) sugar or (2) contains that 5398 // inner type in some way as a subobject. 5399 if (TypeLoc Next = TL.getNextTypeLoc()) 5400 return Visit(Next, Sel); 5401 5402 // If there's no inner type and we're in a permissive context, 5403 // don't diagnose. 5404 if (Sel == Sema::AbstractNone) return; 5405 5406 // Check whether the type matches the abstract type. 5407 QualType T = TL.getType(); 5408 if (T->isArrayType()) { 5409 Sel = Sema::AbstractArrayType; 5410 T = Info.S.Context.getBaseElementType(T); 5411 } 5412 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5413 if (CT != Info.AbstractType) return; 5414 5415 // It matched; do some magic. 5416 if (Sel == Sema::AbstractArrayType) { 5417 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5418 << T << TL.getSourceRange(); 5419 } else { 5420 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5421 << Sel << T << TL.getSourceRange(); 5422 } 5423 Info.DiagnoseAbstractType(); 5424 } 5425 }; 5426 5427 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5428 Sema::AbstractDiagSelID Sel) { 5429 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5430 } 5431 5432 } 5433 5434 /// Check for invalid uses of an abstract type in a method declaration. 5435 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5436 CXXMethodDecl *MD) { 5437 // No need to do the check on definitions, which require that 5438 // the return/param types be complete. 5439 if (MD->doesThisDeclarationHaveABody()) 5440 return; 5441 5442 // For safety's sake, just ignore it if we don't have type source 5443 // information. This should never happen for non-implicit methods, 5444 // but... 5445 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5446 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5447 } 5448 5449 /// Check for invalid uses of an abstract type within a class definition. 5450 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5451 CXXRecordDecl *RD) { 5452 for (auto *D : RD->decls()) { 5453 if (D->isImplicit()) continue; 5454 5455 // Methods and method templates. 5456 if (isa<CXXMethodDecl>(D)) { 5457 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5458 } else if (isa<FunctionTemplateDecl>(D)) { 5459 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5460 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5461 5462 // Fields and static variables. 5463 } else if (isa<FieldDecl>(D)) { 5464 FieldDecl *FD = cast<FieldDecl>(D); 5465 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5466 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5467 } else if (isa<VarDecl>(D)) { 5468 VarDecl *VD = cast<VarDecl>(D); 5469 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5470 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5471 5472 // Nested classes and class templates. 5473 } else if (isa<CXXRecordDecl>(D)) { 5474 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5475 } else if (isa<ClassTemplateDecl>(D)) { 5476 CheckAbstractClassUsage(Info, 5477 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5478 } 5479 } 5480 } 5481 5482 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5483 Attr *ClassAttr = getDLLAttr(Class); 5484 if (!ClassAttr) 5485 return; 5486 5487 assert(ClassAttr->getKind() == attr::DLLExport); 5488 5489 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5490 5491 if (TSK == TSK_ExplicitInstantiationDeclaration) 5492 // Don't go any further if this is just an explicit instantiation 5493 // declaration. 5494 return; 5495 5496 for (Decl *Member : Class->decls()) { 5497 // Defined static variables that are members of an exported base 5498 // class must be marked export too. 5499 auto *VD = dyn_cast<VarDecl>(Member); 5500 if (VD && Member->getAttr<DLLExportAttr>() && 5501 VD->getStorageClass() == SC_Static && 5502 TSK == TSK_ImplicitInstantiation) 5503 S.MarkVariableReferenced(VD->getLocation(), VD); 5504 5505 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5506 if (!MD) 5507 continue; 5508 5509 if (Member->getAttr<DLLExportAttr>()) { 5510 if (MD->isUserProvided()) { 5511 // Instantiate non-default class member functions ... 5512 5513 // .. except for certain kinds of template specializations. 5514 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5515 continue; 5516 5517 S.MarkFunctionReferenced(Class->getLocation(), MD); 5518 5519 // The function will be passed to the consumer when its definition is 5520 // encountered. 5521 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5522 MD->isCopyAssignmentOperator() || 5523 MD->isMoveAssignmentOperator()) { 5524 // Synthesize and instantiate non-trivial implicit methods, explicitly 5525 // defaulted methods, and the copy and move assignment operators. The 5526 // latter are exported even if they are trivial, because the address of 5527 // an operator can be taken and should compare equal across libraries. 5528 DiagnosticErrorTrap Trap(S.Diags); 5529 S.MarkFunctionReferenced(Class->getLocation(), MD); 5530 if (Trap.hasErrorOccurred()) { 5531 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5532 << Class << !S.getLangOpts().CPlusPlus11; 5533 break; 5534 } 5535 5536 // There is no later point when we will see the definition of this 5537 // function, so pass it to the consumer now. 5538 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5539 } 5540 } 5541 } 5542 } 5543 5544 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5545 CXXRecordDecl *Class) { 5546 // Only the MS ABI has default constructor closures, so we don't need to do 5547 // this semantic checking anywhere else. 5548 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5549 return; 5550 5551 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5552 for (Decl *Member : Class->decls()) { 5553 // Look for exported default constructors. 5554 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5555 if (!CD || !CD->isDefaultConstructor()) 5556 continue; 5557 auto *Attr = CD->getAttr<DLLExportAttr>(); 5558 if (!Attr) 5559 continue; 5560 5561 // If the class is non-dependent, mark the default arguments as ODR-used so 5562 // that we can properly codegen the constructor closure. 5563 if (!Class->isDependentContext()) { 5564 for (ParmVarDecl *PD : CD->parameters()) { 5565 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5566 S.DiscardCleanupsInEvaluationContext(); 5567 } 5568 } 5569 5570 if (LastExportedDefaultCtor) { 5571 S.Diag(LastExportedDefaultCtor->getLocation(), 5572 diag::err_attribute_dll_ambiguous_default_ctor) 5573 << Class; 5574 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5575 << CD->getDeclName(); 5576 return; 5577 } 5578 LastExportedDefaultCtor = CD; 5579 } 5580 } 5581 5582 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 5583 // Mark any compiler-generated routines with the implicit code_seg attribute. 5584 for (auto *Method : Class->methods()) { 5585 if (Method->isUserProvided()) 5586 continue; 5587 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 5588 Method->addAttr(A); 5589 } 5590 } 5591 5592 /// Check class-level dllimport/dllexport attribute. 5593 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5594 Attr *ClassAttr = getDLLAttr(Class); 5595 5596 // MSVC inherits DLL attributes to partial class template specializations. 5597 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5598 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5599 if (Attr *TemplateAttr = 5600 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5601 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5602 A->setInherited(true); 5603 ClassAttr = A; 5604 } 5605 } 5606 } 5607 5608 if (!ClassAttr) 5609 return; 5610 5611 if (!Class->isExternallyVisible()) { 5612 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5613 << Class << ClassAttr; 5614 return; 5615 } 5616 5617 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5618 !ClassAttr->isInherited()) { 5619 // Diagnose dll attributes on members of class with dll attribute. 5620 for (Decl *Member : Class->decls()) { 5621 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5622 continue; 5623 InheritableAttr *MemberAttr = getDLLAttr(Member); 5624 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5625 continue; 5626 5627 Diag(MemberAttr->getLocation(), 5628 diag::err_attribute_dll_member_of_dll_class) 5629 << MemberAttr << ClassAttr; 5630 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5631 Member->setInvalidDecl(); 5632 } 5633 } 5634 5635 if (Class->getDescribedClassTemplate()) 5636 // Don't inherit dll attribute until the template is instantiated. 5637 return; 5638 5639 // The class is either imported or exported. 5640 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5641 5642 // Check if this was a dllimport attribute propagated from a derived class to 5643 // a base class template specialization. We don't apply these attributes to 5644 // static data members. 5645 const bool PropagatedImport = 5646 !ClassExported && 5647 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 5648 5649 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5650 5651 // Ignore explicit dllexport on explicit class template instantiation declarations. 5652 if (ClassExported && !ClassAttr->isInherited() && 5653 TSK == TSK_ExplicitInstantiationDeclaration) { 5654 Class->dropAttr<DLLExportAttr>(); 5655 return; 5656 } 5657 5658 // Force declaration of implicit members so they can inherit the attribute. 5659 ForceDeclarationOfImplicitMembers(Class); 5660 5661 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5662 // seem to be true in practice? 5663 5664 for (Decl *Member : Class->decls()) { 5665 VarDecl *VD = dyn_cast<VarDecl>(Member); 5666 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5667 5668 // Only methods and static fields inherit the attributes. 5669 if (!VD && !MD) 5670 continue; 5671 5672 if (MD) { 5673 // Don't process deleted methods. 5674 if (MD->isDeleted()) 5675 continue; 5676 5677 if (MD->isInlined()) { 5678 // MinGW does not import or export inline methods. 5679 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5680 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) 5681 continue; 5682 5683 // MSVC versions before 2015 don't export the move assignment operators 5684 // and move constructor, so don't attempt to import/export them if 5685 // we have a definition. 5686 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5687 if ((MD->isMoveAssignmentOperator() || 5688 (Ctor && Ctor->isMoveConstructor())) && 5689 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5690 continue; 5691 5692 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5693 // operator is exported anyway. 5694 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5695 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5696 continue; 5697 } 5698 } 5699 5700 // Don't apply dllimport attributes to static data members of class template 5701 // instantiations when the attribute is propagated from a derived class. 5702 if (VD && PropagatedImport) 5703 continue; 5704 5705 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5706 continue; 5707 5708 if (!getDLLAttr(Member)) { 5709 auto *NewAttr = 5710 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5711 NewAttr->setInherited(true); 5712 Member->addAttr(NewAttr); 5713 5714 if (MD) { 5715 // Propagate DLLAttr to friend re-declarations of MD that have already 5716 // been constructed. 5717 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 5718 FD = FD->getPreviousDecl()) { 5719 if (FD->getFriendObjectKind() == Decl::FOK_None) 5720 continue; 5721 assert(!getDLLAttr(FD) && 5722 "friend re-decl should not already have a DLLAttr"); 5723 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5724 NewAttr->setInherited(true); 5725 FD->addAttr(NewAttr); 5726 } 5727 } 5728 } 5729 } 5730 5731 if (ClassExported) 5732 DelayedDllExportClasses.push_back(Class); 5733 } 5734 5735 /// Perform propagation of DLL attributes from a derived class to a 5736 /// templated base class for MS compatibility. 5737 void Sema::propagateDLLAttrToBaseClassTemplate( 5738 CXXRecordDecl *Class, Attr *ClassAttr, 5739 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5740 if (getDLLAttr( 5741 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5742 // If the base class template has a DLL attribute, don't try to change it. 5743 return; 5744 } 5745 5746 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5747 if (!getDLLAttr(BaseTemplateSpec) && 5748 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5749 TSK == TSK_ImplicitInstantiation)) { 5750 // The template hasn't been instantiated yet (or it has, but only as an 5751 // explicit instantiation declaration or implicit instantiation, which means 5752 // we haven't codegenned any members yet), so propagate the attribute. 5753 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5754 NewAttr->setInherited(true); 5755 BaseTemplateSpec->addAttr(NewAttr); 5756 5757 // If this was an import, mark that we propagated it from a derived class to 5758 // a base class template specialization. 5759 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 5760 ImportAttr->setPropagatedToBaseTemplate(); 5761 5762 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5763 // needs to be run again to work see the new attribute. Otherwise this will 5764 // get run whenever the template is instantiated. 5765 if (TSK != TSK_Undeclared) 5766 checkClassLevelDLLAttribute(BaseTemplateSpec); 5767 5768 return; 5769 } 5770 5771 if (getDLLAttr(BaseTemplateSpec)) { 5772 // The template has already been specialized or instantiated with an 5773 // attribute, explicitly or through propagation. We should not try to change 5774 // it. 5775 return; 5776 } 5777 5778 // The template was previously instantiated or explicitly specialized without 5779 // a dll attribute, It's too late for us to add an attribute, so warn that 5780 // this is unsupported. 5781 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5782 << BaseTemplateSpec->isExplicitSpecialization(); 5783 Diag(ClassAttr->getLocation(), diag::note_attribute); 5784 if (BaseTemplateSpec->isExplicitSpecialization()) { 5785 Diag(BaseTemplateSpec->getLocation(), 5786 diag::note_template_class_explicit_specialization_was_here) 5787 << BaseTemplateSpec; 5788 } else { 5789 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5790 diag::note_template_class_instantiation_was_here) 5791 << BaseTemplateSpec; 5792 } 5793 } 5794 5795 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5796 SourceLocation DefaultLoc) { 5797 switch (S.getSpecialMember(MD)) { 5798 case Sema::CXXDefaultConstructor: 5799 S.DefineImplicitDefaultConstructor(DefaultLoc, 5800 cast<CXXConstructorDecl>(MD)); 5801 break; 5802 case Sema::CXXCopyConstructor: 5803 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5804 break; 5805 case Sema::CXXCopyAssignment: 5806 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5807 break; 5808 case Sema::CXXDestructor: 5809 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5810 break; 5811 case Sema::CXXMoveConstructor: 5812 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5813 break; 5814 case Sema::CXXMoveAssignment: 5815 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5816 break; 5817 case Sema::CXXInvalid: 5818 llvm_unreachable("Invalid special member."); 5819 } 5820 } 5821 5822 /// Determine whether a type is permitted to be passed or returned in 5823 /// registers, per C++ [class.temporary]p3. 5824 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 5825 TargetInfo::CallingConvKind CCK) { 5826 if (D->isDependentType() || D->isInvalidDecl()) 5827 return false; 5828 5829 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 5830 // The PS4 platform ABI follows the behavior of Clang 3.2. 5831 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 5832 return !D->hasNonTrivialDestructorForCall() && 5833 !D->hasNonTrivialCopyConstructorForCall(); 5834 5835 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 5836 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 5837 bool DtorIsTrivialForCall = false; 5838 5839 // If a class has at least one non-deleted, trivial copy constructor, it 5840 // is passed according to the C ABI. Otherwise, it is passed indirectly. 5841 // 5842 // Note: This permits classes with non-trivial copy or move ctors to be 5843 // passed in registers, so long as they *also* have a trivial copy ctor, 5844 // which is non-conforming. 5845 if (D->needsImplicitCopyConstructor()) { 5846 if (!D->defaultedCopyConstructorIsDeleted()) { 5847 if (D->hasTrivialCopyConstructor()) 5848 CopyCtorIsTrivial = true; 5849 if (D->hasTrivialCopyConstructorForCall()) 5850 CopyCtorIsTrivialForCall = true; 5851 } 5852 } else { 5853 for (const CXXConstructorDecl *CD : D->ctors()) { 5854 if (CD->isCopyConstructor() && !CD->isDeleted()) { 5855 if (CD->isTrivial()) 5856 CopyCtorIsTrivial = true; 5857 if (CD->isTrivialForCall()) 5858 CopyCtorIsTrivialForCall = true; 5859 } 5860 } 5861 } 5862 5863 if (D->needsImplicitDestructor()) { 5864 if (!D->defaultedDestructorIsDeleted() && 5865 D->hasTrivialDestructorForCall()) 5866 DtorIsTrivialForCall = true; 5867 } else if (const auto *DD = D->getDestructor()) { 5868 if (!DD->isDeleted() && DD->isTrivialForCall()) 5869 DtorIsTrivialForCall = true; 5870 } 5871 5872 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 5873 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 5874 return true; 5875 5876 // If a class has a destructor, we'd really like to pass it indirectly 5877 // because it allows us to elide copies. Unfortunately, MSVC makes that 5878 // impossible for small types, which it will pass in a single register or 5879 // stack slot. Most objects with dtors are large-ish, so handle that early. 5880 // We can't call out all large objects as being indirect because there are 5881 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 5882 // how we pass large POD types. 5883 5884 // Note: This permits small classes with nontrivial destructors to be 5885 // passed in registers, which is non-conforming. 5886 if (CopyCtorIsTrivial && 5887 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= 64) 5888 return true; 5889 return false; 5890 } 5891 5892 // Per C++ [class.temporary]p3, the relevant condition is: 5893 // each copy constructor, move constructor, and destructor of X is 5894 // either trivial or deleted, and X has at least one non-deleted copy 5895 // or move constructor 5896 bool HasNonDeletedCopyOrMove = false; 5897 5898 if (D->needsImplicitCopyConstructor() && 5899 !D->defaultedCopyConstructorIsDeleted()) { 5900 if (!D->hasTrivialCopyConstructorForCall()) 5901 return false; 5902 HasNonDeletedCopyOrMove = true; 5903 } 5904 5905 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 5906 !D->defaultedMoveConstructorIsDeleted()) { 5907 if (!D->hasTrivialMoveConstructorForCall()) 5908 return false; 5909 HasNonDeletedCopyOrMove = true; 5910 } 5911 5912 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 5913 !D->hasTrivialDestructorForCall()) 5914 return false; 5915 5916 for (const CXXMethodDecl *MD : D->methods()) { 5917 if (MD->isDeleted()) 5918 continue; 5919 5920 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 5921 if (CD && CD->isCopyOrMoveConstructor()) 5922 HasNonDeletedCopyOrMove = true; 5923 else if (!isa<CXXDestructorDecl>(MD)) 5924 continue; 5925 5926 if (!MD->isTrivialForCall()) 5927 return false; 5928 } 5929 5930 return HasNonDeletedCopyOrMove; 5931 } 5932 5933 /// Perform semantic checks on a class definition that has been 5934 /// completing, introducing implicitly-declared members, checking for 5935 /// abstract types, etc. 5936 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 5937 if (!Record) 5938 return; 5939 5940 if (Record->isAbstract() && !Record->isInvalidDecl()) { 5941 AbstractUsageInfo Info(*this, Record); 5942 CheckAbstractClassUsage(Info, Record); 5943 } 5944 5945 // If this is not an aggregate type and has no user-declared constructor, 5946 // complain about any non-static data members of reference or const scalar 5947 // type, since they will never get initializers. 5948 if (!Record->isInvalidDecl() && !Record->isDependentType() && 5949 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 5950 !Record->isLambda()) { 5951 bool Complained = false; 5952 for (const auto *F : Record->fields()) { 5953 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 5954 continue; 5955 5956 if (F->getType()->isReferenceType() || 5957 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 5958 if (!Complained) { 5959 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 5960 << Record->getTagKind() << Record; 5961 Complained = true; 5962 } 5963 5964 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 5965 << F->getType()->isReferenceType() 5966 << F->getDeclName(); 5967 } 5968 } 5969 } 5970 5971 if (Record->getIdentifier()) { 5972 // C++ [class.mem]p13: 5973 // If T is the name of a class, then each of the following shall have a 5974 // name different from T: 5975 // - every member of every anonymous union that is a member of class T. 5976 // 5977 // C++ [class.mem]p14: 5978 // In addition, if class T has a user-declared constructor (12.1), every 5979 // non-static data member of class T shall have a name different from T. 5980 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 5981 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 5982 ++I) { 5983 NamedDecl *D = (*I)->getUnderlyingDecl(); 5984 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 5985 Record->hasUserDeclaredConstructor()) || 5986 isa<IndirectFieldDecl>(D)) { 5987 Diag((*I)->getLocation(), diag::err_member_name_of_class) 5988 << D->getDeclName(); 5989 break; 5990 } 5991 } 5992 } 5993 5994 // Warn if the class has virtual methods but non-virtual public destructor. 5995 if (Record->isPolymorphic() && !Record->isDependentType()) { 5996 CXXDestructorDecl *dtor = Record->getDestructor(); 5997 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 5998 !Record->hasAttr<FinalAttr>()) 5999 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6000 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6001 } 6002 6003 if (Record->isAbstract()) { 6004 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6005 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6006 << FA->isSpelledAsSealed(); 6007 DiagnoseAbstractType(Record); 6008 } 6009 } 6010 6011 // See if trivial_abi has to be dropped. 6012 if (Record->hasAttr<TrivialABIAttr>()) 6013 checkIllFormedTrivialABIStruct(*Record); 6014 6015 // Set HasTrivialSpecialMemberForCall if the record has attribute 6016 // "trivial_abi". 6017 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6018 6019 if (HasTrivialABI) 6020 Record->setHasTrivialSpecialMemberForCall(); 6021 6022 bool HasMethodWithOverrideControl = false, 6023 HasOverridingMethodWithoutOverrideControl = false; 6024 if (!Record->isDependentType()) { 6025 for (auto *M : Record->methods()) { 6026 // See if a method overloads virtual methods in a base 6027 // class without overriding any. 6028 if (!M->isStatic()) 6029 DiagnoseHiddenVirtualMethods(M); 6030 if (M->hasAttr<OverrideAttr>()) 6031 HasMethodWithOverrideControl = true; 6032 else if (M->size_overridden_methods() > 0) 6033 HasOverridingMethodWithoutOverrideControl = true; 6034 // Check whether the explicitly-defaulted special members are valid. 6035 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 6036 CheckExplicitlyDefaultedSpecialMember(M); 6037 6038 // For an explicitly defaulted or deleted special member, we defer 6039 // determining triviality until the class is complete. That time is now! 6040 CXXSpecialMember CSM = getSpecialMember(M); 6041 if (!M->isImplicit() && !M->isUserProvided()) { 6042 if (CSM != CXXInvalid) { 6043 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6044 // Inform the class that we've finished declaring this member. 6045 Record->finishedDefaultedOrDeletedMember(M); 6046 M->setTrivialForCall( 6047 HasTrivialABI || 6048 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6049 Record->setTrivialForCallFlags(M); 6050 } 6051 } 6052 6053 // Set triviality for the purpose of calls if this is a user-provided 6054 // copy/move constructor or destructor. 6055 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6056 CSM == CXXDestructor) && M->isUserProvided()) { 6057 M->setTrivialForCall(HasTrivialABI); 6058 Record->setTrivialForCallFlags(M); 6059 } 6060 6061 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6062 M->hasAttr<DLLExportAttr>()) { 6063 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6064 M->isTrivial() && 6065 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6066 CSM == CXXDestructor)) 6067 M->dropAttr<DLLExportAttr>(); 6068 6069 if (M->hasAttr<DLLExportAttr>()) { 6070 DefineImplicitSpecialMember(*this, M, M->getLocation()); 6071 ActOnFinishInlineFunctionDef(M); 6072 } 6073 } 6074 } 6075 } 6076 6077 if (HasMethodWithOverrideControl && 6078 HasOverridingMethodWithoutOverrideControl) { 6079 // At least one method has the 'override' control declared. 6080 // Diagnose all other overridden methods which do not have 'override' specified on them. 6081 for (auto *M : Record->methods()) 6082 DiagnoseAbsenceOfOverrideControl(M); 6083 } 6084 6085 // ms_struct is a request to use the same ABI rules as MSVC. Check 6086 // whether this class uses any C++ features that are implemented 6087 // completely differently in MSVC, and if so, emit a diagnostic. 6088 // That diagnostic defaults to an error, but we allow projects to 6089 // map it down to a warning (or ignore it). It's a fairly common 6090 // practice among users of the ms_struct pragma to mass-annotate 6091 // headers, sweeping up a bunch of types that the project doesn't 6092 // really rely on MSVC-compatible layout for. We must therefore 6093 // support "ms_struct except for C++ stuff" as a secondary ABI. 6094 if (Record->isMsStruct(Context) && 6095 (Record->isPolymorphic() || Record->getNumBases())) { 6096 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6097 } 6098 6099 checkClassLevelDLLAttribute(Record); 6100 checkClassLevelCodeSegAttribute(Record); 6101 6102 bool ClangABICompat4 = 6103 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6104 TargetInfo::CallingConvKind CCK = 6105 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6106 bool CanPass = canPassInRegisters(*this, Record, CCK); 6107 6108 // Do not change ArgPassingRestrictions if it has already been set to 6109 // APK_CanNeverPassInRegs. 6110 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6111 Record->setArgPassingRestrictions(CanPass 6112 ? RecordDecl::APK_CanPassInRegs 6113 : RecordDecl::APK_CannotPassInRegs); 6114 6115 // If canPassInRegisters returns true despite the record having a non-trivial 6116 // destructor, the record is destructed in the callee. This happens only when 6117 // the record or one of its subobjects has a field annotated with trivial_abi 6118 // or a field qualified with ObjC __strong/__weak. 6119 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6120 Record->setParamDestroyedInCallee(true); 6121 else if (Record->hasNonTrivialDestructor()) 6122 Record->setParamDestroyedInCallee(CanPass); 6123 6124 if (getLangOpts().ForceEmitVTables) { 6125 // If we want to emit all the vtables, we need to mark it as used. This 6126 // is especially required for cases like vtable assumption loads. 6127 MarkVTableUsed(Record->getInnerLocStart(), Record); 6128 } 6129 } 6130 6131 /// Look up the special member function that would be called by a special 6132 /// member function for a subobject of class type. 6133 /// 6134 /// \param Class The class type of the subobject. 6135 /// \param CSM The kind of special member function. 6136 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6137 /// \param ConstRHS True if this is a copy operation with a const object 6138 /// on its RHS, that is, if the argument to the outer special member 6139 /// function is 'const' and this is not a field marked 'mutable'. 6140 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6141 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6142 unsigned FieldQuals, bool ConstRHS) { 6143 unsigned LHSQuals = 0; 6144 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6145 LHSQuals = FieldQuals; 6146 6147 unsigned RHSQuals = FieldQuals; 6148 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6149 RHSQuals = 0; 6150 else if (ConstRHS) 6151 RHSQuals |= Qualifiers::Const; 6152 6153 return S.LookupSpecialMember(Class, CSM, 6154 RHSQuals & Qualifiers::Const, 6155 RHSQuals & Qualifiers::Volatile, 6156 false, 6157 LHSQuals & Qualifiers::Const, 6158 LHSQuals & Qualifiers::Volatile); 6159 } 6160 6161 class Sema::InheritedConstructorInfo { 6162 Sema &S; 6163 SourceLocation UseLoc; 6164 6165 /// A mapping from the base classes through which the constructor was 6166 /// inherited to the using shadow declaration in that base class (or a null 6167 /// pointer if the constructor was declared in that base class). 6168 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6169 InheritedFromBases; 6170 6171 public: 6172 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6173 ConstructorUsingShadowDecl *Shadow) 6174 : S(S), UseLoc(UseLoc) { 6175 bool DiagnosedMultipleConstructedBases = false; 6176 CXXRecordDecl *ConstructedBase = nullptr; 6177 UsingDecl *ConstructedBaseUsing = nullptr; 6178 6179 // Find the set of such base class subobjects and check that there's a 6180 // unique constructed subobject. 6181 for (auto *D : Shadow->redecls()) { 6182 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6183 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6184 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6185 6186 InheritedFromBases.insert( 6187 std::make_pair(DNominatedBase->getCanonicalDecl(), 6188 DShadow->getNominatedBaseClassShadowDecl())); 6189 if (DShadow->constructsVirtualBase()) 6190 InheritedFromBases.insert( 6191 std::make_pair(DConstructedBase->getCanonicalDecl(), 6192 DShadow->getConstructedBaseClassShadowDecl())); 6193 else 6194 assert(DNominatedBase == DConstructedBase); 6195 6196 // [class.inhctor.init]p2: 6197 // If the constructor was inherited from multiple base class subobjects 6198 // of type B, the program is ill-formed. 6199 if (!ConstructedBase) { 6200 ConstructedBase = DConstructedBase; 6201 ConstructedBaseUsing = D->getUsingDecl(); 6202 } else if (ConstructedBase != DConstructedBase && 6203 !Shadow->isInvalidDecl()) { 6204 if (!DiagnosedMultipleConstructedBases) { 6205 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6206 << Shadow->getTargetDecl(); 6207 S.Diag(ConstructedBaseUsing->getLocation(), 6208 diag::note_ambiguous_inherited_constructor_using) 6209 << ConstructedBase; 6210 DiagnosedMultipleConstructedBases = true; 6211 } 6212 S.Diag(D->getUsingDecl()->getLocation(), 6213 diag::note_ambiguous_inherited_constructor_using) 6214 << DConstructedBase; 6215 } 6216 } 6217 6218 if (DiagnosedMultipleConstructedBases) 6219 Shadow->setInvalidDecl(); 6220 } 6221 6222 /// Find the constructor to use for inherited construction of a base class, 6223 /// and whether that base class constructor inherits the constructor from a 6224 /// virtual base class (in which case it won't actually invoke it). 6225 std::pair<CXXConstructorDecl *, bool> 6226 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6227 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6228 if (It == InheritedFromBases.end()) 6229 return std::make_pair(nullptr, false); 6230 6231 // This is an intermediary class. 6232 if (It->second) 6233 return std::make_pair( 6234 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6235 It->second->constructsVirtualBase()); 6236 6237 // This is the base class from which the constructor was inherited. 6238 return std::make_pair(Ctor, false); 6239 } 6240 }; 6241 6242 /// Is the special member function which would be selected to perform the 6243 /// specified operation on the specified class type a constexpr constructor? 6244 static bool 6245 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6246 Sema::CXXSpecialMember CSM, unsigned Quals, 6247 bool ConstRHS, 6248 CXXConstructorDecl *InheritedCtor = nullptr, 6249 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6250 // If we're inheriting a constructor, see if we need to call it for this base 6251 // class. 6252 if (InheritedCtor) { 6253 assert(CSM == Sema::CXXDefaultConstructor); 6254 auto BaseCtor = 6255 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6256 if (BaseCtor) 6257 return BaseCtor->isConstexpr(); 6258 } 6259 6260 if (CSM == Sema::CXXDefaultConstructor) 6261 return ClassDecl->hasConstexprDefaultConstructor(); 6262 6263 Sema::SpecialMemberOverloadResult SMOR = 6264 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6265 if (!SMOR.getMethod()) 6266 // A constructor we wouldn't select can't be "involved in initializing" 6267 // anything. 6268 return true; 6269 return SMOR.getMethod()->isConstexpr(); 6270 } 6271 6272 /// Determine whether the specified special member function would be constexpr 6273 /// if it were implicitly defined. 6274 static bool defaultedSpecialMemberIsConstexpr( 6275 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6276 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6277 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6278 if (!S.getLangOpts().CPlusPlus11) 6279 return false; 6280 6281 // C++11 [dcl.constexpr]p4: 6282 // In the definition of a constexpr constructor [...] 6283 bool Ctor = true; 6284 switch (CSM) { 6285 case Sema::CXXDefaultConstructor: 6286 if (Inherited) 6287 break; 6288 // Since default constructor lookup is essentially trivial (and cannot 6289 // involve, for instance, template instantiation), we compute whether a 6290 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6291 // 6292 // This is important for performance; we need to know whether the default 6293 // constructor is constexpr to determine whether the type is a literal type. 6294 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6295 6296 case Sema::CXXCopyConstructor: 6297 case Sema::CXXMoveConstructor: 6298 // For copy or move constructors, we need to perform overload resolution. 6299 break; 6300 6301 case Sema::CXXCopyAssignment: 6302 case Sema::CXXMoveAssignment: 6303 if (!S.getLangOpts().CPlusPlus14) 6304 return false; 6305 // In C++1y, we need to perform overload resolution. 6306 Ctor = false; 6307 break; 6308 6309 case Sema::CXXDestructor: 6310 case Sema::CXXInvalid: 6311 return false; 6312 } 6313 6314 // -- if the class is a non-empty union, or for each non-empty anonymous 6315 // union member of a non-union class, exactly one non-static data member 6316 // shall be initialized; [DR1359] 6317 // 6318 // If we squint, this is guaranteed, since exactly one non-static data member 6319 // will be initialized (if the constructor isn't deleted), we just don't know 6320 // which one. 6321 if (Ctor && ClassDecl->isUnion()) 6322 return CSM == Sema::CXXDefaultConstructor 6323 ? ClassDecl->hasInClassInitializer() || 6324 !ClassDecl->hasVariantMembers() 6325 : true; 6326 6327 // -- the class shall not have any virtual base classes; 6328 if (Ctor && ClassDecl->getNumVBases()) 6329 return false; 6330 6331 // C++1y [class.copy]p26: 6332 // -- [the class] is a literal type, and 6333 if (!Ctor && !ClassDecl->isLiteral()) 6334 return false; 6335 6336 // -- every constructor involved in initializing [...] base class 6337 // sub-objects shall be a constexpr constructor; 6338 // -- the assignment operator selected to copy/move each direct base 6339 // class is a constexpr function, and 6340 for (const auto &B : ClassDecl->bases()) { 6341 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6342 if (!BaseType) continue; 6343 6344 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6345 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6346 InheritedCtor, Inherited)) 6347 return false; 6348 } 6349 6350 // -- every constructor involved in initializing non-static data members 6351 // [...] shall be a constexpr constructor; 6352 // -- every non-static data member and base class sub-object shall be 6353 // initialized 6354 // -- for each non-static data member of X that is of class type (or array 6355 // thereof), the assignment operator selected to copy/move that member is 6356 // a constexpr function 6357 for (const auto *F : ClassDecl->fields()) { 6358 if (F->isInvalidDecl()) 6359 continue; 6360 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6361 continue; 6362 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6363 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6364 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6365 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6366 BaseType.getCVRQualifiers(), 6367 ConstArg && !F->isMutable())) 6368 return false; 6369 } else if (CSM == Sema::CXXDefaultConstructor) { 6370 return false; 6371 } 6372 } 6373 6374 // All OK, it's constexpr! 6375 return true; 6376 } 6377 6378 static Sema::ImplicitExceptionSpecification 6379 ComputeDefaultedSpecialMemberExceptionSpec( 6380 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6381 Sema::InheritedConstructorInfo *ICI); 6382 6383 static Sema::ImplicitExceptionSpecification 6384 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6385 auto CSM = S.getSpecialMember(MD); 6386 if (CSM != Sema::CXXInvalid) 6387 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6388 6389 auto *CD = cast<CXXConstructorDecl>(MD); 6390 assert(CD->getInheritedConstructor() && 6391 "only special members have implicit exception specs"); 6392 Sema::InheritedConstructorInfo ICI( 6393 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6394 return ComputeDefaultedSpecialMemberExceptionSpec( 6395 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6396 } 6397 6398 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6399 CXXMethodDecl *MD) { 6400 FunctionProtoType::ExtProtoInfo EPI; 6401 6402 // Build an exception specification pointing back at this member. 6403 EPI.ExceptionSpec.Type = EST_Unevaluated; 6404 EPI.ExceptionSpec.SourceDecl = MD; 6405 6406 // Set the calling convention to the default for C++ instance methods. 6407 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6408 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6409 /*IsCXXMethod=*/true)); 6410 return EPI; 6411 } 6412 6413 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6414 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6415 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6416 return; 6417 6418 // Evaluate the exception specification. 6419 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6420 auto ESI = IES.getExceptionSpec(); 6421 6422 // Update the type of the special member to use it. 6423 UpdateExceptionSpec(MD, ESI); 6424 6425 // A user-provided destructor can be defined outside the class. When that 6426 // happens, be sure to update the exception specification on both 6427 // declarations. 6428 const FunctionProtoType *CanonicalFPT = 6429 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6430 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6431 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6432 } 6433 6434 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6435 CXXRecordDecl *RD = MD->getParent(); 6436 CXXSpecialMember CSM = getSpecialMember(MD); 6437 6438 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6439 "not an explicitly-defaulted special member"); 6440 6441 // Whether this was the first-declared instance of the constructor. 6442 // This affects whether we implicitly add an exception spec and constexpr. 6443 bool First = MD == MD->getCanonicalDecl(); 6444 6445 bool HadError = false; 6446 6447 // C++11 [dcl.fct.def.default]p1: 6448 // A function that is explicitly defaulted shall 6449 // -- be a special member function (checked elsewhere), 6450 // -- have the same type (except for ref-qualifiers, and except that a 6451 // copy operation can take a non-const reference) as an implicit 6452 // declaration, and 6453 // -- not have default arguments. 6454 // C++2a changes the second bullet to instead delete the function if it's 6455 // defaulted on its first declaration, unless it's "an assignment operator, 6456 // and its return type differs or its parameter type is not a reference". 6457 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First; 6458 bool ShouldDeleteForTypeMismatch = false; 6459 unsigned ExpectedParams = 1; 6460 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6461 ExpectedParams = 0; 6462 if (MD->getNumParams() != ExpectedParams) { 6463 // This checks for default arguments: a copy or move constructor with a 6464 // default argument is classified as a default constructor, and assignment 6465 // operations and destructors can't have default arguments. 6466 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6467 << CSM << MD->getSourceRange(); 6468 HadError = true; 6469 } else if (MD->isVariadic()) { 6470 if (DeleteOnTypeMismatch) 6471 ShouldDeleteForTypeMismatch = true; 6472 else { 6473 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6474 << CSM << MD->getSourceRange(); 6475 HadError = true; 6476 } 6477 } 6478 6479 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6480 6481 bool CanHaveConstParam = false; 6482 if (CSM == CXXCopyConstructor) 6483 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6484 else if (CSM == CXXCopyAssignment) 6485 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6486 6487 QualType ReturnType = Context.VoidTy; 6488 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6489 // Check for return type matching. 6490 ReturnType = Type->getReturnType(); 6491 QualType ExpectedReturnType = 6492 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 6493 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6494 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6495 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6496 HadError = true; 6497 } 6498 6499 // A defaulted special member cannot have cv-qualifiers. 6500 if (Type->getTypeQuals()) { 6501 if (DeleteOnTypeMismatch) 6502 ShouldDeleteForTypeMismatch = true; 6503 else { 6504 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6505 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6506 HadError = true; 6507 } 6508 } 6509 } 6510 6511 // Check for parameter type matching. 6512 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6513 bool HasConstParam = false; 6514 if (ExpectedParams && ArgType->isReferenceType()) { 6515 // Argument must be reference to possibly-const T. 6516 QualType ReferentType = ArgType->getPointeeType(); 6517 HasConstParam = ReferentType.isConstQualified(); 6518 6519 if (ReferentType.isVolatileQualified()) { 6520 if (DeleteOnTypeMismatch) 6521 ShouldDeleteForTypeMismatch = true; 6522 else { 6523 Diag(MD->getLocation(), 6524 diag::err_defaulted_special_member_volatile_param) << CSM; 6525 HadError = true; 6526 } 6527 } 6528 6529 if (HasConstParam && !CanHaveConstParam) { 6530 if (DeleteOnTypeMismatch) 6531 ShouldDeleteForTypeMismatch = true; 6532 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6533 Diag(MD->getLocation(), 6534 diag::err_defaulted_special_member_copy_const_param) 6535 << (CSM == CXXCopyAssignment); 6536 // FIXME: Explain why this special member can't be const. 6537 HadError = true; 6538 } else { 6539 Diag(MD->getLocation(), 6540 diag::err_defaulted_special_member_move_const_param) 6541 << (CSM == CXXMoveAssignment); 6542 HadError = true; 6543 } 6544 } 6545 } else if (ExpectedParams) { 6546 // A copy assignment operator can take its argument by value, but a 6547 // defaulted one cannot. 6548 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6549 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6550 HadError = true; 6551 } 6552 6553 // C++11 [dcl.fct.def.default]p2: 6554 // An explicitly-defaulted function may be declared constexpr only if it 6555 // would have been implicitly declared as constexpr, 6556 // Do not apply this rule to members of class templates, since core issue 1358 6557 // makes such functions always instantiate to constexpr functions. For 6558 // functions which cannot be constexpr (for non-constructors in C++11 and for 6559 // destructors in C++1y), this is checked elsewhere. 6560 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6561 HasConstParam); 6562 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6563 : isa<CXXConstructorDecl>(MD)) && 6564 MD->isConstexpr() && !Constexpr && 6565 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6566 Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) << CSM; 6567 // FIXME: Explain why the special member can't be constexpr. 6568 HadError = true; 6569 } 6570 6571 // and may have an explicit exception-specification only if it is compatible 6572 // with the exception-specification on the implicit declaration. 6573 if (Type->hasExceptionSpec()) { 6574 // Delay the check if this is the first declaration of the special member, 6575 // since we may not have parsed some necessary in-class initializers yet. 6576 if (First) { 6577 // If the exception specification needs to be instantiated, do so now, 6578 // before we clobber it with an EST_Unevaluated specification below. 6579 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6580 InstantiateExceptionSpec(MD->getBeginLoc(), MD); 6581 Type = MD->getType()->getAs<FunctionProtoType>(); 6582 } 6583 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6584 } else 6585 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6586 } 6587 6588 // If a function is explicitly defaulted on its first declaration, 6589 if (First) { 6590 // -- it is implicitly considered to be constexpr if the implicit 6591 // definition would be, 6592 MD->setConstexpr(Constexpr); 6593 6594 // -- it is implicitly considered to have the same exception-specification 6595 // as if it had been implicitly declared, 6596 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6597 EPI.ExceptionSpec.Type = EST_Unevaluated; 6598 EPI.ExceptionSpec.SourceDecl = MD; 6599 MD->setType(Context.getFunctionType(ReturnType, 6600 llvm::makeArrayRef(&ArgType, 6601 ExpectedParams), 6602 EPI)); 6603 } 6604 6605 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 6606 if (First) { 6607 SetDeclDeleted(MD, MD->getLocation()); 6608 if (!inTemplateInstantiation() && !HadError) { 6609 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 6610 if (ShouldDeleteForTypeMismatch) { 6611 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 6612 } else { 6613 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6614 } 6615 } 6616 if (ShouldDeleteForTypeMismatch && !HadError) { 6617 Diag(MD->getLocation(), 6618 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 6619 } 6620 } else { 6621 // C++11 [dcl.fct.def.default]p4: 6622 // [For a] user-provided explicitly-defaulted function [...] if such a 6623 // function is implicitly defined as deleted, the program is ill-formed. 6624 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6625 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 6626 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6627 HadError = true; 6628 } 6629 } 6630 6631 if (HadError) 6632 MD->setInvalidDecl(); 6633 } 6634 6635 /// Check whether the exception specification provided for an 6636 /// explicitly-defaulted special member matches the exception specification 6637 /// that would have been generated for an implicit special member, per 6638 /// C++11 [dcl.fct.def.default]p2. 6639 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6640 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6641 // If the exception specification was explicitly specified but hadn't been 6642 // parsed when the method was defaulted, grab it now. 6643 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6644 SpecifiedType = 6645 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6646 6647 // Compute the implicit exception specification. 6648 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6649 /*IsCXXMethod=*/true); 6650 FunctionProtoType::ExtProtoInfo EPI(CC); 6651 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD); 6652 EPI.ExceptionSpec = IES.getExceptionSpec(); 6653 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6654 Context.getFunctionType(Context.VoidTy, None, EPI)); 6655 6656 // Ensure that it matches. 6657 CheckEquivalentExceptionSpec( 6658 PDiag(diag::err_incorrect_defaulted_exception_spec) 6659 << getSpecialMember(MD), PDiag(), 6660 ImplicitType, SourceLocation(), 6661 SpecifiedType, MD->getLocation()); 6662 } 6663 6664 void Sema::CheckDelayedMemberExceptionSpecs() { 6665 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 6666 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 6667 decltype(DelayedDefaultedMemberExceptionSpecs) Defaulted; 6668 6669 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 6670 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 6671 std::swap(Defaulted, DelayedDefaultedMemberExceptionSpecs); 6672 6673 // Perform any deferred checking of exception specifications for virtual 6674 // destructors. 6675 for (auto &Check : Overriding) 6676 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6677 6678 // Perform any deferred checking of exception specifications for befriended 6679 // special members. 6680 for (auto &Check : Equivalent) 6681 CheckEquivalentExceptionSpec(Check.second, Check.first); 6682 6683 // Check that any explicitly-defaulted methods have exception specifications 6684 // compatible with their implicit exception specifications. 6685 for (auto &Spec : Defaulted) 6686 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6687 } 6688 6689 namespace { 6690 /// CRTP base class for visiting operations performed by a special member 6691 /// function (or inherited constructor). 6692 template<typename Derived> 6693 struct SpecialMemberVisitor { 6694 Sema &S; 6695 CXXMethodDecl *MD; 6696 Sema::CXXSpecialMember CSM; 6697 Sema::InheritedConstructorInfo *ICI; 6698 6699 // Properties of the special member, computed for convenience. 6700 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6701 6702 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6703 Sema::InheritedConstructorInfo *ICI) 6704 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6705 switch (CSM) { 6706 case Sema::CXXDefaultConstructor: 6707 case Sema::CXXCopyConstructor: 6708 case Sema::CXXMoveConstructor: 6709 IsConstructor = true; 6710 break; 6711 case Sema::CXXCopyAssignment: 6712 case Sema::CXXMoveAssignment: 6713 IsAssignment = true; 6714 break; 6715 case Sema::CXXDestructor: 6716 break; 6717 case Sema::CXXInvalid: 6718 llvm_unreachable("invalid special member kind"); 6719 } 6720 6721 if (MD->getNumParams()) { 6722 if (const ReferenceType *RT = 6723 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6724 ConstArg = RT->getPointeeType().isConstQualified(); 6725 } 6726 } 6727 6728 Derived &getDerived() { return static_cast<Derived&>(*this); } 6729 6730 /// Is this a "move" special member? 6731 bool isMove() const { 6732 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6733 } 6734 6735 /// Look up the corresponding special member in the given class. 6736 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6737 unsigned Quals, bool IsMutable) { 6738 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6739 ConstArg && !IsMutable); 6740 } 6741 6742 /// Look up the constructor for the specified base class to see if it's 6743 /// overridden due to this being an inherited constructor. 6744 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6745 if (!ICI) 6746 return {}; 6747 assert(CSM == Sema::CXXDefaultConstructor); 6748 auto *BaseCtor = 6749 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6750 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6751 return MD; 6752 return {}; 6753 } 6754 6755 /// A base or member subobject. 6756 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6757 6758 /// Get the location to use for a subobject in diagnostics. 6759 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6760 // FIXME: For an indirect virtual base, the direct base leading to 6761 // the indirect virtual base would be a more useful choice. 6762 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6763 return B->getBaseTypeLoc(); 6764 else 6765 return Subobj.get<FieldDecl*>()->getLocation(); 6766 } 6767 6768 enum BasesToVisit { 6769 /// Visit all non-virtual (direct) bases. 6770 VisitNonVirtualBases, 6771 /// Visit all direct bases, virtual or not. 6772 VisitDirectBases, 6773 /// Visit all non-virtual bases, and all virtual bases if the class 6774 /// is not abstract. 6775 VisitPotentiallyConstructedBases, 6776 /// Visit all direct or virtual bases. 6777 VisitAllBases 6778 }; 6779 6780 // Visit the bases and members of the class. 6781 bool visit(BasesToVisit Bases) { 6782 CXXRecordDecl *RD = MD->getParent(); 6783 6784 if (Bases == VisitPotentiallyConstructedBases) 6785 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6786 6787 for (auto &B : RD->bases()) 6788 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6789 getDerived().visitBase(&B)) 6790 return true; 6791 6792 if (Bases == VisitAllBases) 6793 for (auto &B : RD->vbases()) 6794 if (getDerived().visitBase(&B)) 6795 return true; 6796 6797 for (auto *F : RD->fields()) 6798 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 6799 getDerived().visitField(F)) 6800 return true; 6801 6802 return false; 6803 } 6804 }; 6805 } 6806 6807 namespace { 6808 struct SpecialMemberDeletionInfo 6809 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 6810 bool Diagnose; 6811 6812 SourceLocation Loc; 6813 6814 bool AllFieldsAreConst; 6815 6816 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6817 Sema::CXXSpecialMember CSM, 6818 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6819 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 6820 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 6821 6822 bool inUnion() const { return MD->getParent()->isUnion(); } 6823 6824 Sema::CXXSpecialMember getEffectiveCSM() { 6825 return ICI ? Sema::CXXInvalid : CSM; 6826 } 6827 6828 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 6829 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 6830 6831 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6832 bool shouldDeleteForField(FieldDecl *FD); 6833 bool shouldDeleteForAllConstMembers(); 6834 6835 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6836 unsigned Quals); 6837 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6838 Sema::SpecialMemberOverloadResult SMOR, 6839 bool IsDtorCallInCtor); 6840 6841 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6842 }; 6843 } 6844 6845 /// Is the given special member inaccessible when used on the given 6846 /// sub-object. 6847 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6848 CXXMethodDecl *target) { 6849 /// If we're operating on a base class, the object type is the 6850 /// type of this special member. 6851 QualType objectTy; 6852 AccessSpecifier access = target->getAccess(); 6853 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6854 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6855 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6856 6857 // If we're operating on a field, the object type is the type of the field. 6858 } else { 6859 objectTy = S.Context.getTypeDeclType(target->getParent()); 6860 } 6861 6862 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6863 } 6864 6865 /// Check whether we should delete a special member due to the implicit 6866 /// definition containing a call to a special member of a subobject. 6867 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6868 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 6869 bool IsDtorCallInCtor) { 6870 CXXMethodDecl *Decl = SMOR.getMethod(); 6871 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6872 6873 int DiagKind = -1; 6874 6875 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6876 DiagKind = !Decl ? 0 : 1; 6877 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6878 DiagKind = 2; 6879 else if (!isAccessible(Subobj, Decl)) 6880 DiagKind = 3; 6881 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6882 !Decl->isTrivial()) { 6883 // A member of a union must have a trivial corresponding special member. 6884 // As a weird special case, a destructor call from a union's constructor 6885 // must be accessible and non-deleted, but need not be trivial. Such a 6886 // destructor is never actually called, but is semantically checked as 6887 // if it were. 6888 DiagKind = 4; 6889 } 6890 6891 if (DiagKind == -1) 6892 return false; 6893 6894 if (Diagnose) { 6895 if (Field) { 6896 S.Diag(Field->getLocation(), 6897 diag::note_deleted_special_member_class_subobject) 6898 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6899 << Field << DiagKind << IsDtorCallInCtor; 6900 } else { 6901 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6902 S.Diag(Base->getBeginLoc(), 6903 diag::note_deleted_special_member_class_subobject) 6904 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 6905 << Base->getType() << DiagKind << IsDtorCallInCtor; 6906 } 6907 6908 if (DiagKind == 1) 6909 S.NoteDeletedFunction(Decl); 6910 // FIXME: Explain inaccessibility if DiagKind == 3. 6911 } 6912 6913 return true; 6914 } 6915 6916 /// Check whether we should delete a special member function due to having a 6917 /// direct or virtual base class or non-static data member of class type M. 6918 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6919 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6920 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6921 bool IsMutable = Field && Field->isMutable(); 6922 6923 // C++11 [class.ctor]p5: 6924 // -- any direct or virtual base class, or non-static data member with no 6925 // brace-or-equal-initializer, has class type M (or array thereof) and 6926 // either M has no default constructor or overload resolution as applied 6927 // to M's default constructor results in an ambiguity or in a function 6928 // that is deleted or inaccessible 6929 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6930 // -- a direct or virtual base class B that cannot be copied/moved because 6931 // overload resolution, as applied to B's corresponding special member, 6932 // results in an ambiguity or a function that is deleted or inaccessible 6933 // from the defaulted special member 6934 // C++11 [class.dtor]p5: 6935 // -- any direct or virtual base class [...] has a type with a destructor 6936 // that is deleted or inaccessible 6937 if (!(CSM == Sema::CXXDefaultConstructor && 6938 Field && Field->hasInClassInitializer()) && 6939 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 6940 false)) 6941 return true; 6942 6943 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 6944 // -- any direct or virtual base class or non-static data member has a 6945 // type with a destructor that is deleted or inaccessible 6946 if (IsConstructor) { 6947 Sema::SpecialMemberOverloadResult SMOR = 6948 S.LookupSpecialMember(Class, Sema::CXXDestructor, 6949 false, false, false, false, false); 6950 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 6951 return true; 6952 } 6953 6954 return false; 6955 } 6956 6957 /// Check whether we should delete a special member function due to the class 6958 /// having a particular direct or virtual base class. 6959 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 6960 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 6961 // If program is correct, BaseClass cannot be null, but if it is, the error 6962 // must be reported elsewhere. 6963 if (!BaseClass) 6964 return false; 6965 // If we have an inheriting constructor, check whether we're calling an 6966 // inherited constructor instead of a default constructor. 6967 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 6968 if (auto *BaseCtor = SMOR.getMethod()) { 6969 // Note that we do not check access along this path; other than that, 6970 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 6971 // FIXME: Check that the base has a usable destructor! Sink this into 6972 // shouldDeleteForClassSubobject. 6973 if (BaseCtor->isDeleted() && Diagnose) { 6974 S.Diag(Base->getBeginLoc(), 6975 diag::note_deleted_special_member_class_subobject) 6976 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 6977 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false; 6978 S.NoteDeletedFunction(BaseCtor); 6979 } 6980 return BaseCtor->isDeleted(); 6981 } 6982 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 6983 } 6984 6985 /// Check whether we should delete a special member function due to the class 6986 /// having a particular non-static data member. 6987 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 6988 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 6989 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 6990 6991 if (CSM == Sema::CXXDefaultConstructor) { 6992 // For a default constructor, all references must be initialized in-class 6993 // and, if a union, it must have a non-const member. 6994 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 6995 if (Diagnose) 6996 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6997 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 6998 return true; 6999 } 7000 // C++11 [class.ctor]p5: any non-variant non-static data member of 7001 // const-qualified type (or array thereof) with no 7002 // brace-or-equal-initializer does not have a user-provided default 7003 // constructor. 7004 if (!inUnion() && FieldType.isConstQualified() && 7005 !FD->hasInClassInitializer() && 7006 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 7007 if (Diagnose) 7008 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 7009 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 7010 return true; 7011 } 7012 7013 if (inUnion() && !FieldType.isConstQualified()) 7014 AllFieldsAreConst = false; 7015 } else if (CSM == Sema::CXXCopyConstructor) { 7016 // For a copy constructor, data members must not be of rvalue reference 7017 // type. 7018 if (FieldType->isRValueReferenceType()) { 7019 if (Diagnose) 7020 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 7021 << MD->getParent() << FD << FieldType; 7022 return true; 7023 } 7024 } else if (IsAssignment) { 7025 // For an assignment operator, data members must not be of reference type. 7026 if (FieldType->isReferenceType()) { 7027 if (Diagnose) 7028 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7029 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 7030 return true; 7031 } 7032 if (!FieldRecord && FieldType.isConstQualified()) { 7033 // C++11 [class.copy]p23: 7034 // -- a non-static data member of const non-class type (or array thereof) 7035 if (Diagnose) 7036 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7037 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 7038 return true; 7039 } 7040 } 7041 7042 if (FieldRecord) { 7043 // Some additional restrictions exist on the variant members. 7044 if (!inUnion() && FieldRecord->isUnion() && 7045 FieldRecord->isAnonymousStructOrUnion()) { 7046 bool AllVariantFieldsAreConst = true; 7047 7048 // FIXME: Handle anonymous unions declared within anonymous unions. 7049 for (auto *UI : FieldRecord->fields()) { 7050 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 7051 7052 if (!UnionFieldType.isConstQualified()) 7053 AllVariantFieldsAreConst = false; 7054 7055 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 7056 if (UnionFieldRecord && 7057 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 7058 UnionFieldType.getCVRQualifiers())) 7059 return true; 7060 } 7061 7062 // At least one member in each anonymous union must be non-const 7063 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 7064 !FieldRecord->field_empty()) { 7065 if (Diagnose) 7066 S.Diag(FieldRecord->getLocation(), 7067 diag::note_deleted_default_ctor_all_const) 7068 << !!ICI << MD->getParent() << /*anonymous union*/1; 7069 return true; 7070 } 7071 7072 // Don't check the implicit member of the anonymous union type. 7073 // This is technically non-conformant, but sanity demands it. 7074 return false; 7075 } 7076 7077 if (shouldDeleteForClassSubobject(FieldRecord, FD, 7078 FieldType.getCVRQualifiers())) 7079 return true; 7080 } 7081 7082 return false; 7083 } 7084 7085 /// C++11 [class.ctor] p5: 7086 /// A defaulted default constructor for a class X is defined as deleted if 7087 /// X is a union and all of its variant members are of const-qualified type. 7088 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 7089 // This is a silly definition, because it gives an empty union a deleted 7090 // default constructor. Don't do that. 7091 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 7092 bool AnyFields = false; 7093 for (auto *F : MD->getParent()->fields()) 7094 if ((AnyFields = !F->isUnnamedBitfield())) 7095 break; 7096 if (!AnyFields) 7097 return false; 7098 if (Diagnose) 7099 S.Diag(MD->getParent()->getLocation(), 7100 diag::note_deleted_default_ctor_all_const) 7101 << !!ICI << MD->getParent() << /*not anonymous union*/0; 7102 return true; 7103 } 7104 return false; 7105 } 7106 7107 /// Determine whether a defaulted special member function should be defined as 7108 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 7109 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 7110 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 7111 InheritedConstructorInfo *ICI, 7112 bool Diagnose) { 7113 if (MD->isInvalidDecl()) 7114 return false; 7115 CXXRecordDecl *RD = MD->getParent(); 7116 assert(!RD->isDependentType() && "do deletion after instantiation"); 7117 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 7118 return false; 7119 7120 // C++11 [expr.lambda.prim]p19: 7121 // The closure type associated with a lambda-expression has a 7122 // deleted (8.4.3) default constructor and a deleted copy 7123 // assignment operator. 7124 // C++2a adds back these operators if the lambda has no capture-default. 7125 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 7126 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 7127 if (Diagnose) 7128 Diag(RD->getLocation(), diag::note_lambda_decl); 7129 return true; 7130 } 7131 7132 // For an anonymous struct or union, the copy and assignment special members 7133 // will never be used, so skip the check. For an anonymous union declared at 7134 // namespace scope, the constructor and destructor are used. 7135 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 7136 RD->isAnonymousStructOrUnion()) 7137 return false; 7138 7139 // C++11 [class.copy]p7, p18: 7140 // If the class definition declares a move constructor or move assignment 7141 // operator, an implicitly declared copy constructor or copy assignment 7142 // operator is defined as deleted. 7143 if (MD->isImplicit() && 7144 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 7145 CXXMethodDecl *UserDeclaredMove = nullptr; 7146 7147 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 7148 // deletion of the corresponding copy operation, not both copy operations. 7149 // MSVC 2015 has adopted the standards conforming behavior. 7150 bool DeletesOnlyMatchingCopy = 7151 getLangOpts().MSVCCompat && 7152 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 7153 7154 if (RD->hasUserDeclaredMoveConstructor() && 7155 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 7156 if (!Diagnose) return true; 7157 7158 // Find any user-declared move constructor. 7159 for (auto *I : RD->ctors()) { 7160 if (I->isMoveConstructor()) { 7161 UserDeclaredMove = I; 7162 break; 7163 } 7164 } 7165 assert(UserDeclaredMove); 7166 } else if (RD->hasUserDeclaredMoveAssignment() && 7167 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 7168 if (!Diagnose) return true; 7169 7170 // Find any user-declared move assignment operator. 7171 for (auto *I : RD->methods()) { 7172 if (I->isMoveAssignmentOperator()) { 7173 UserDeclaredMove = I; 7174 break; 7175 } 7176 } 7177 assert(UserDeclaredMove); 7178 } 7179 7180 if (UserDeclaredMove) { 7181 Diag(UserDeclaredMove->getLocation(), 7182 diag::note_deleted_copy_user_declared_move) 7183 << (CSM == CXXCopyAssignment) << RD 7184 << UserDeclaredMove->isMoveAssignmentOperator(); 7185 return true; 7186 } 7187 } 7188 7189 // Do access control from the special member function 7190 ContextRAII MethodContext(*this, MD); 7191 7192 // C++11 [class.dtor]p5: 7193 // -- for a virtual destructor, lookup of the non-array deallocation function 7194 // results in an ambiguity or in a function that is deleted or inaccessible 7195 if (CSM == CXXDestructor && MD->isVirtual()) { 7196 FunctionDecl *OperatorDelete = nullptr; 7197 DeclarationName Name = 7198 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 7199 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 7200 OperatorDelete, /*Diagnose*/false)) { 7201 if (Diagnose) 7202 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 7203 return true; 7204 } 7205 } 7206 7207 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 7208 7209 // Per DR1611, do not consider virtual bases of constructors of abstract 7210 // classes, since we are not going to construct them. 7211 // Per DR1658, do not consider virtual bases of destructors of abstract 7212 // classes either. 7213 // Per DR2180, for assignment operators we only assign (and thus only 7214 // consider) direct bases. 7215 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 7216 : SMI.VisitPotentiallyConstructedBases)) 7217 return true; 7218 7219 if (SMI.shouldDeleteForAllConstMembers()) 7220 return true; 7221 7222 if (getLangOpts().CUDA) { 7223 // We should delete the special member in CUDA mode if target inference 7224 // failed. 7225 // For inherited constructors (non-null ICI), CSM may be passed so that MD 7226 // is treated as certain special member, which may not reflect what special 7227 // member MD really is. However inferCUDATargetForImplicitSpecialMember 7228 // expects CSM to match MD, therefore recalculate CSM. 7229 assert(ICI || CSM == getSpecialMember(MD)); 7230 auto RealCSM = CSM; 7231 if (ICI) 7232 RealCSM = getSpecialMember(MD); 7233 7234 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 7235 SMI.ConstArg, Diagnose); 7236 } 7237 7238 return false; 7239 } 7240 7241 /// Perform lookup for a special member of the specified kind, and determine 7242 /// whether it is trivial. If the triviality can be determined without the 7243 /// lookup, skip it. This is intended for use when determining whether a 7244 /// special member of a containing object is trivial, and thus does not ever 7245 /// perform overload resolution for default constructors. 7246 /// 7247 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 7248 /// member that was most likely to be intended to be trivial, if any. 7249 /// 7250 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 7251 /// determine whether the special member is trivial. 7252 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 7253 Sema::CXXSpecialMember CSM, unsigned Quals, 7254 bool ConstRHS, 7255 Sema::TrivialABIHandling TAH, 7256 CXXMethodDecl **Selected) { 7257 if (Selected) 7258 *Selected = nullptr; 7259 7260 switch (CSM) { 7261 case Sema::CXXInvalid: 7262 llvm_unreachable("not a special member"); 7263 7264 case Sema::CXXDefaultConstructor: 7265 // C++11 [class.ctor]p5: 7266 // A default constructor is trivial if: 7267 // - all the [direct subobjects] have trivial default constructors 7268 // 7269 // Note, no overload resolution is performed in this case. 7270 if (RD->hasTrivialDefaultConstructor()) 7271 return true; 7272 7273 if (Selected) { 7274 // If there's a default constructor which could have been trivial, dig it 7275 // out. Otherwise, if there's any user-provided default constructor, point 7276 // to that as an example of why there's not a trivial one. 7277 CXXConstructorDecl *DefCtor = nullptr; 7278 if (RD->needsImplicitDefaultConstructor()) 7279 S.DeclareImplicitDefaultConstructor(RD); 7280 for (auto *CI : RD->ctors()) { 7281 if (!CI->isDefaultConstructor()) 7282 continue; 7283 DefCtor = CI; 7284 if (!DefCtor->isUserProvided()) 7285 break; 7286 } 7287 7288 *Selected = DefCtor; 7289 } 7290 7291 return false; 7292 7293 case Sema::CXXDestructor: 7294 // C++11 [class.dtor]p5: 7295 // A destructor is trivial if: 7296 // - all the direct [subobjects] have trivial destructors 7297 if (RD->hasTrivialDestructor() || 7298 (TAH == Sema::TAH_ConsiderTrivialABI && 7299 RD->hasTrivialDestructorForCall())) 7300 return true; 7301 7302 if (Selected) { 7303 if (RD->needsImplicitDestructor()) 7304 S.DeclareImplicitDestructor(RD); 7305 *Selected = RD->getDestructor(); 7306 } 7307 7308 return false; 7309 7310 case Sema::CXXCopyConstructor: 7311 // C++11 [class.copy]p12: 7312 // A copy constructor is trivial if: 7313 // - the constructor selected to copy each direct [subobject] is trivial 7314 if (RD->hasTrivialCopyConstructor() || 7315 (TAH == Sema::TAH_ConsiderTrivialABI && 7316 RD->hasTrivialCopyConstructorForCall())) { 7317 if (Quals == Qualifiers::Const) 7318 // We must either select the trivial copy constructor or reach an 7319 // ambiguity; no need to actually perform overload resolution. 7320 return true; 7321 } else if (!Selected) { 7322 return false; 7323 } 7324 // In C++98, we are not supposed to perform overload resolution here, but we 7325 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7326 // cases like B as having a non-trivial copy constructor: 7327 // struct A { template<typename T> A(T&); }; 7328 // struct B { mutable A a; }; 7329 goto NeedOverloadResolution; 7330 7331 case Sema::CXXCopyAssignment: 7332 // C++11 [class.copy]p25: 7333 // A copy assignment operator is trivial if: 7334 // - the assignment operator selected to copy each direct [subobject] is 7335 // trivial 7336 if (RD->hasTrivialCopyAssignment()) { 7337 if (Quals == Qualifiers::Const) 7338 return true; 7339 } else if (!Selected) { 7340 return false; 7341 } 7342 // In C++98, we are not supposed to perform overload resolution here, but we 7343 // treat that as a language defect. 7344 goto NeedOverloadResolution; 7345 7346 case Sema::CXXMoveConstructor: 7347 case Sema::CXXMoveAssignment: 7348 NeedOverloadResolution: 7349 Sema::SpecialMemberOverloadResult SMOR = 7350 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7351 7352 // The standard doesn't describe how to behave if the lookup is ambiguous. 7353 // We treat it as not making the member non-trivial, just like the standard 7354 // mandates for the default constructor. This should rarely matter, because 7355 // the member will also be deleted. 7356 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7357 return true; 7358 7359 if (!SMOR.getMethod()) { 7360 assert(SMOR.getKind() == 7361 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7362 return false; 7363 } 7364 7365 // We deliberately don't check if we found a deleted special member. We're 7366 // not supposed to! 7367 if (Selected) 7368 *Selected = SMOR.getMethod(); 7369 7370 if (TAH == Sema::TAH_ConsiderTrivialABI && 7371 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 7372 return SMOR.getMethod()->isTrivialForCall(); 7373 return SMOR.getMethod()->isTrivial(); 7374 } 7375 7376 llvm_unreachable("unknown special method kind"); 7377 } 7378 7379 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7380 for (auto *CI : RD->ctors()) 7381 if (!CI->isImplicit()) 7382 return CI; 7383 7384 // Look for constructor templates. 7385 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7386 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7387 if (CXXConstructorDecl *CD = 7388 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7389 return CD; 7390 } 7391 7392 return nullptr; 7393 } 7394 7395 /// The kind of subobject we are checking for triviality. The values of this 7396 /// enumeration are used in diagnostics. 7397 enum TrivialSubobjectKind { 7398 /// The subobject is a base class. 7399 TSK_BaseClass, 7400 /// The subobject is a non-static data member. 7401 TSK_Field, 7402 /// The object is actually the complete object. 7403 TSK_CompleteObject 7404 }; 7405 7406 /// Check whether the special member selected for a given type would be trivial. 7407 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7408 QualType SubType, bool ConstRHS, 7409 Sema::CXXSpecialMember CSM, 7410 TrivialSubobjectKind Kind, 7411 Sema::TrivialABIHandling TAH, bool Diagnose) { 7412 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7413 if (!SubRD) 7414 return true; 7415 7416 CXXMethodDecl *Selected; 7417 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7418 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 7419 return true; 7420 7421 if (Diagnose) { 7422 if (ConstRHS) 7423 SubType.addConst(); 7424 7425 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7426 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7427 << Kind << SubType.getUnqualifiedType(); 7428 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7429 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7430 } else if (!Selected) 7431 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7432 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7433 else if (Selected->isUserProvided()) { 7434 if (Kind == TSK_CompleteObject) 7435 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7436 << Kind << SubType.getUnqualifiedType() << CSM; 7437 else { 7438 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7439 << Kind << SubType.getUnqualifiedType() << CSM; 7440 S.Diag(Selected->getLocation(), diag::note_declared_at); 7441 } 7442 } else { 7443 if (Kind != TSK_CompleteObject) 7444 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7445 << Kind << SubType.getUnqualifiedType() << CSM; 7446 7447 // Explain why the defaulted or deleted special member isn't trivial. 7448 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 7449 Diagnose); 7450 } 7451 } 7452 7453 return false; 7454 } 7455 7456 /// Check whether the members of a class type allow a special member to be 7457 /// trivial. 7458 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7459 Sema::CXXSpecialMember CSM, 7460 bool ConstArg, 7461 Sema::TrivialABIHandling TAH, 7462 bool Diagnose) { 7463 for (const auto *FI : RD->fields()) { 7464 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7465 continue; 7466 7467 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7468 7469 // Pretend anonymous struct or union members are members of this class. 7470 if (FI->isAnonymousStructOrUnion()) { 7471 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7472 CSM, ConstArg, TAH, Diagnose)) 7473 return false; 7474 continue; 7475 } 7476 7477 // C++11 [class.ctor]p5: 7478 // A default constructor is trivial if [...] 7479 // -- no non-static data member of its class has a 7480 // brace-or-equal-initializer 7481 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7482 if (Diagnose) 7483 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7484 return false; 7485 } 7486 7487 // Objective C ARC 4.3.5: 7488 // [...] nontrivally ownership-qualified types are [...] not trivially 7489 // default constructible, copy constructible, move constructible, copy 7490 // assignable, move assignable, or destructible [...] 7491 if (FieldType.hasNonTrivialObjCLifetime()) { 7492 if (Diagnose) 7493 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7494 << RD << FieldType.getObjCLifetime(); 7495 return false; 7496 } 7497 7498 bool ConstRHS = ConstArg && !FI->isMutable(); 7499 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7500 CSM, TSK_Field, TAH, Diagnose)) 7501 return false; 7502 } 7503 7504 return true; 7505 } 7506 7507 /// Diagnose why the specified class does not have a trivial special member of 7508 /// the given kind. 7509 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7510 QualType Ty = Context.getRecordType(RD); 7511 7512 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7513 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7514 TSK_CompleteObject, TAH_IgnoreTrivialABI, 7515 /*Diagnose*/true); 7516 } 7517 7518 /// Determine whether a defaulted or deleted special member function is trivial, 7519 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7520 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7521 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7522 TrivialABIHandling TAH, bool Diagnose) { 7523 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7524 7525 CXXRecordDecl *RD = MD->getParent(); 7526 7527 bool ConstArg = false; 7528 7529 // C++11 [class.copy]p12, p25: [DR1593] 7530 // A [special member] is trivial if [...] its parameter-type-list is 7531 // equivalent to the parameter-type-list of an implicit declaration [...] 7532 switch (CSM) { 7533 case CXXDefaultConstructor: 7534 case CXXDestructor: 7535 // Trivial default constructors and destructors cannot have parameters. 7536 break; 7537 7538 case CXXCopyConstructor: 7539 case CXXCopyAssignment: { 7540 // Trivial copy operations always have const, non-volatile parameter types. 7541 ConstArg = true; 7542 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7543 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7544 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7545 if (Diagnose) 7546 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7547 << Param0->getSourceRange() << Param0->getType() 7548 << Context.getLValueReferenceType( 7549 Context.getRecordType(RD).withConst()); 7550 return false; 7551 } 7552 break; 7553 } 7554 7555 case CXXMoveConstructor: 7556 case CXXMoveAssignment: { 7557 // Trivial move operations always have non-cv-qualified parameters. 7558 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7559 const RValueReferenceType *RT = 7560 Param0->getType()->getAs<RValueReferenceType>(); 7561 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7562 if (Diagnose) 7563 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7564 << Param0->getSourceRange() << Param0->getType() 7565 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7566 return false; 7567 } 7568 break; 7569 } 7570 7571 case CXXInvalid: 7572 llvm_unreachable("not a special member"); 7573 } 7574 7575 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7576 if (Diagnose) 7577 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7578 diag::note_nontrivial_default_arg) 7579 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7580 return false; 7581 } 7582 if (MD->isVariadic()) { 7583 if (Diagnose) 7584 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7585 return false; 7586 } 7587 7588 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7589 // A copy/move [constructor or assignment operator] is trivial if 7590 // -- the [member] selected to copy/move each direct base class subobject 7591 // is trivial 7592 // 7593 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7594 // A [default constructor or destructor] is trivial if 7595 // -- all the direct base classes have trivial [default constructors or 7596 // destructors] 7597 for (const auto &BI : RD->bases()) 7598 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 7599 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 7600 return false; 7601 7602 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7603 // A copy/move [constructor or assignment operator] for a class X is 7604 // trivial if 7605 // -- for each non-static data member of X that is of class type (or array 7606 // thereof), the constructor selected to copy/move that member is 7607 // trivial 7608 // 7609 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7610 // A [default constructor or destructor] is trivial if 7611 // -- for all of the non-static data members of its class that are of class 7612 // type (or array thereof), each such class has a trivial [default 7613 // constructor or destructor] 7614 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 7615 return false; 7616 7617 // C++11 [class.dtor]p5: 7618 // A destructor is trivial if [...] 7619 // -- the destructor is not virtual 7620 if (CSM == CXXDestructor && MD->isVirtual()) { 7621 if (Diagnose) 7622 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7623 return false; 7624 } 7625 7626 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7627 // A [special member] for class X is trivial if [...] 7628 // -- class X has no virtual functions and no virtual base classes 7629 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7630 if (!Diagnose) 7631 return false; 7632 7633 if (RD->getNumVBases()) { 7634 // Check for virtual bases. We already know that the corresponding 7635 // member in all bases is trivial, so vbases must all be direct. 7636 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7637 assert(BS.isVirtual()); 7638 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 7639 return false; 7640 } 7641 7642 // Must have a virtual method. 7643 for (const auto *MI : RD->methods()) { 7644 if (MI->isVirtual()) { 7645 SourceLocation MLoc = MI->getBeginLoc(); 7646 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7647 return false; 7648 } 7649 } 7650 7651 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7652 } 7653 7654 // Looks like it's trivial! 7655 return true; 7656 } 7657 7658 namespace { 7659 struct FindHiddenVirtualMethod { 7660 Sema *S; 7661 CXXMethodDecl *Method; 7662 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7663 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7664 7665 private: 7666 /// Check whether any most overriden method from MD in Methods 7667 static bool CheckMostOverridenMethods( 7668 const CXXMethodDecl *MD, 7669 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7670 if (MD->size_overridden_methods() == 0) 7671 return Methods.count(MD->getCanonicalDecl()); 7672 for (const CXXMethodDecl *O : MD->overridden_methods()) 7673 if (CheckMostOverridenMethods(O, Methods)) 7674 return true; 7675 return false; 7676 } 7677 7678 public: 7679 /// Member lookup function that determines whether a given C++ 7680 /// method overloads virtual methods in a base class without overriding any, 7681 /// to be used with CXXRecordDecl::lookupInBases(). 7682 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7683 RecordDecl *BaseRecord = 7684 Specifier->getType()->getAs<RecordType>()->getDecl(); 7685 7686 DeclarationName Name = Method->getDeclName(); 7687 assert(Name.getNameKind() == DeclarationName::Identifier); 7688 7689 bool foundSameNameMethod = false; 7690 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7691 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7692 Path.Decls = Path.Decls.slice(1)) { 7693 NamedDecl *D = Path.Decls.front(); 7694 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7695 MD = MD->getCanonicalDecl(); 7696 foundSameNameMethod = true; 7697 // Interested only in hidden virtual methods. 7698 if (!MD->isVirtual()) 7699 continue; 7700 // If the method we are checking overrides a method from its base 7701 // don't warn about the other overloaded methods. Clang deviates from 7702 // GCC by only diagnosing overloads of inherited virtual functions that 7703 // do not override any other virtual functions in the base. GCC's 7704 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7705 // function from a base class. These cases may be better served by a 7706 // warning (not specific to virtual functions) on call sites when the 7707 // call would select a different function from the base class, were it 7708 // visible. 7709 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7710 if (!S->IsOverload(Method, MD, false)) 7711 return true; 7712 // Collect the overload only if its hidden. 7713 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7714 overloadedMethods.push_back(MD); 7715 } 7716 } 7717 7718 if (foundSameNameMethod) 7719 OverloadedMethods.append(overloadedMethods.begin(), 7720 overloadedMethods.end()); 7721 return foundSameNameMethod; 7722 } 7723 }; 7724 } // end anonymous namespace 7725 7726 /// Add the most overriden methods from MD to Methods 7727 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7728 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7729 if (MD->size_overridden_methods() == 0) 7730 Methods.insert(MD->getCanonicalDecl()); 7731 else 7732 for (const CXXMethodDecl *O : MD->overridden_methods()) 7733 AddMostOverridenMethods(O, Methods); 7734 } 7735 7736 /// Check if a method overloads virtual methods in a base class without 7737 /// overriding any. 7738 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7739 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7740 if (!MD->getDeclName().isIdentifier()) 7741 return; 7742 7743 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7744 /*bool RecordPaths=*/false, 7745 /*bool DetectVirtual=*/false); 7746 FindHiddenVirtualMethod FHVM; 7747 FHVM.Method = MD; 7748 FHVM.S = this; 7749 7750 // Keep the base methods that were overriden or introduced in the subclass 7751 // by 'using' in a set. A base method not in this set is hidden. 7752 CXXRecordDecl *DC = MD->getParent(); 7753 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7754 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7755 NamedDecl *ND = *I; 7756 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7757 ND = shad->getTargetDecl(); 7758 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7759 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7760 } 7761 7762 if (DC->lookupInBases(FHVM, Paths)) 7763 OverloadedMethods = FHVM.OverloadedMethods; 7764 } 7765 7766 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7767 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7768 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7769 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7770 PartialDiagnostic PD = PDiag( 7771 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7772 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7773 Diag(overloadedMD->getLocation(), PD); 7774 } 7775 } 7776 7777 /// Diagnose methods which overload virtual methods in a base class 7778 /// without overriding any. 7779 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7780 if (MD->isInvalidDecl()) 7781 return; 7782 7783 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7784 return; 7785 7786 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7787 FindHiddenVirtualMethods(MD, OverloadedMethods); 7788 if (!OverloadedMethods.empty()) { 7789 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7790 << MD << (OverloadedMethods.size() > 1); 7791 7792 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7793 } 7794 } 7795 7796 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 7797 auto PrintDiagAndRemoveAttr = [&]() { 7798 // No diagnostics if this is a template instantiation. 7799 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) 7800 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 7801 diag::ext_cannot_use_trivial_abi) << &RD; 7802 RD.dropAttr<TrivialABIAttr>(); 7803 }; 7804 7805 // Ill-formed if the struct has virtual functions. 7806 if (RD.isPolymorphic()) { 7807 PrintDiagAndRemoveAttr(); 7808 return; 7809 } 7810 7811 for (const auto &B : RD.bases()) { 7812 // Ill-formed if the base class is non-trivial for the purpose of calls or a 7813 // virtual base. 7814 if ((!B.getType()->isDependentType() && 7815 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || 7816 B.isVirtual()) { 7817 PrintDiagAndRemoveAttr(); 7818 return; 7819 } 7820 } 7821 7822 for (const auto *FD : RD.fields()) { 7823 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 7824 // non-trivial for the purpose of calls. 7825 QualType FT = FD->getType(); 7826 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 7827 PrintDiagAndRemoveAttr(); 7828 return; 7829 } 7830 7831 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 7832 if (!RT->isDependentType() && 7833 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 7834 PrintDiagAndRemoveAttr(); 7835 return; 7836 } 7837 } 7838 } 7839 7840 void Sema::ActOnFinishCXXMemberSpecification( 7841 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 7842 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 7843 if (!TagDecl) 7844 return; 7845 7846 AdjustDeclIfTemplate(TagDecl); 7847 7848 for (const ParsedAttr &AL : AttrList) { 7849 if (AL.getKind() != ParsedAttr::AT_Visibility) 7850 continue; 7851 AL.setInvalid(); 7852 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) 7853 << AL.getName(); 7854 } 7855 7856 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7857 // strict aliasing violation! 7858 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7859 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7860 7861 CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl)); 7862 } 7863 7864 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7865 /// special functions, such as the default constructor, copy 7866 /// constructor, or destructor, to the given C++ class (C++ 7867 /// [special]p1). This routine can only be executed just before the 7868 /// definition of the class is complete. 7869 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7870 if (ClassDecl->needsImplicitDefaultConstructor()) { 7871 ++ASTContext::NumImplicitDefaultConstructors; 7872 7873 if (ClassDecl->hasInheritedConstructor()) 7874 DeclareImplicitDefaultConstructor(ClassDecl); 7875 } 7876 7877 if (ClassDecl->needsImplicitCopyConstructor()) { 7878 ++ASTContext::NumImplicitCopyConstructors; 7879 7880 // If the properties or semantics of the copy constructor couldn't be 7881 // determined while the class was being declared, force a declaration 7882 // of it now. 7883 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7884 ClassDecl->hasInheritedConstructor()) 7885 DeclareImplicitCopyConstructor(ClassDecl); 7886 // For the MS ABI we need to know whether the copy ctor is deleted. A 7887 // prerequisite for deleting the implicit copy ctor is that the class has a 7888 // move ctor or move assignment that is either user-declared or whose 7889 // semantics are inherited from a subobject. FIXME: We should provide a more 7890 // direct way for CodeGen to ask whether the constructor was deleted. 7891 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 7892 (ClassDecl->hasUserDeclaredMoveConstructor() || 7893 ClassDecl->needsOverloadResolutionForMoveConstructor() || 7894 ClassDecl->hasUserDeclaredMoveAssignment() || 7895 ClassDecl->needsOverloadResolutionForMoveAssignment())) 7896 DeclareImplicitCopyConstructor(ClassDecl); 7897 } 7898 7899 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7900 ++ASTContext::NumImplicitMoveConstructors; 7901 7902 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7903 ClassDecl->hasInheritedConstructor()) 7904 DeclareImplicitMoveConstructor(ClassDecl); 7905 } 7906 7907 if (ClassDecl->needsImplicitCopyAssignment()) { 7908 ++ASTContext::NumImplicitCopyAssignmentOperators; 7909 7910 // If we have a dynamic class, then the copy assignment operator may be 7911 // virtual, so we have to declare it immediately. This ensures that, e.g., 7912 // it shows up in the right place in the vtable and that we diagnose 7913 // problems with the implicit exception specification. 7914 if (ClassDecl->isDynamicClass() || 7915 ClassDecl->needsOverloadResolutionForCopyAssignment() || 7916 ClassDecl->hasInheritedAssignment()) 7917 DeclareImplicitCopyAssignment(ClassDecl); 7918 } 7919 7920 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 7921 ++ASTContext::NumImplicitMoveAssignmentOperators; 7922 7923 // Likewise for the move assignment operator. 7924 if (ClassDecl->isDynamicClass() || 7925 ClassDecl->needsOverloadResolutionForMoveAssignment() || 7926 ClassDecl->hasInheritedAssignment()) 7927 DeclareImplicitMoveAssignment(ClassDecl); 7928 } 7929 7930 if (ClassDecl->needsImplicitDestructor()) { 7931 ++ASTContext::NumImplicitDestructors; 7932 7933 // If we have a dynamic class, then the destructor may be virtual, so we 7934 // have to declare the destructor immediately. This ensures that, e.g., it 7935 // shows up in the right place in the vtable and that we diagnose problems 7936 // with the implicit exception specification. 7937 if (ClassDecl->isDynamicClass() || 7938 ClassDecl->needsOverloadResolutionForDestructor()) 7939 DeclareImplicitDestructor(ClassDecl); 7940 } 7941 } 7942 7943 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 7944 if (!D) 7945 return 0; 7946 7947 // The order of template parameters is not important here. All names 7948 // get added to the same scope. 7949 SmallVector<TemplateParameterList *, 4> ParameterLists; 7950 7951 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 7952 D = TD->getTemplatedDecl(); 7953 7954 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 7955 ParameterLists.push_back(PSD->getTemplateParameters()); 7956 7957 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 7958 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 7959 ParameterLists.push_back(DD->getTemplateParameterList(i)); 7960 7961 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7962 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 7963 ParameterLists.push_back(FTD->getTemplateParameters()); 7964 } 7965 } 7966 7967 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 7968 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 7969 ParameterLists.push_back(TD->getTemplateParameterList(i)); 7970 7971 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 7972 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 7973 ParameterLists.push_back(CTD->getTemplateParameters()); 7974 } 7975 } 7976 7977 unsigned Count = 0; 7978 for (TemplateParameterList *Params : ParameterLists) { 7979 if (Params->size() > 0) 7980 // Ignore explicit specializations; they don't contribute to the template 7981 // depth. 7982 ++Count; 7983 for (NamedDecl *Param : *Params) { 7984 if (Param->getDeclName()) { 7985 S->AddDecl(Param); 7986 IdResolver.AddDecl(Param); 7987 } 7988 } 7989 } 7990 7991 return Count; 7992 } 7993 7994 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7995 if (!RecordD) return; 7996 AdjustDeclIfTemplate(RecordD); 7997 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 7998 PushDeclContext(S, Record); 7999 } 8000 8001 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 8002 if (!RecordD) return; 8003 PopDeclContext(); 8004 } 8005 8006 /// This is used to implement the constant expression evaluation part of the 8007 /// attribute enable_if extension. There is nothing in standard C++ which would 8008 /// require reentering parameters. 8009 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 8010 if (!Param) 8011 return; 8012 8013 S->AddDecl(Param); 8014 if (Param->getDeclName()) 8015 IdResolver.AddDecl(Param); 8016 } 8017 8018 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 8019 /// parsing a top-level (non-nested) C++ class, and we are now 8020 /// parsing those parts of the given Method declaration that could 8021 /// not be parsed earlier (C++ [class.mem]p2), such as default 8022 /// arguments. This action should enter the scope of the given 8023 /// Method declaration as if we had just parsed the qualified method 8024 /// name. However, it should not bring the parameters into scope; 8025 /// that will be performed by ActOnDelayedCXXMethodParameter. 8026 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8027 } 8028 8029 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 8030 /// C++ method declaration. We're (re-)introducing the given 8031 /// function parameter into scope for use in parsing later parts of 8032 /// the method declaration. For example, we could see an 8033 /// ActOnParamDefaultArgument event for this parameter. 8034 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 8035 if (!ParamD) 8036 return; 8037 8038 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 8039 8040 // If this parameter has an unparsed default argument, clear it out 8041 // to make way for the parsed default argument. 8042 if (Param->hasUnparsedDefaultArg()) 8043 Param->setDefaultArg(nullptr); 8044 8045 S->AddDecl(Param); 8046 if (Param->getDeclName()) 8047 IdResolver.AddDecl(Param); 8048 } 8049 8050 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 8051 /// processing the delayed method declaration for Method. The method 8052 /// declaration is now considered finished. There may be a separate 8053 /// ActOnStartOfFunctionDef action later (not necessarily 8054 /// immediately!) for this method, if it was also defined inside the 8055 /// class body. 8056 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8057 if (!MethodD) 8058 return; 8059 8060 AdjustDeclIfTemplate(MethodD); 8061 8062 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 8063 8064 // Now that we have our default arguments, check the constructor 8065 // again. It could produce additional diagnostics or affect whether 8066 // the class has implicitly-declared destructors, among other 8067 // things. 8068 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 8069 CheckConstructor(Constructor); 8070 8071 // Check the default arguments, which we may have added. 8072 if (!Method->isInvalidDecl()) 8073 CheckCXXDefaultArguments(Method); 8074 } 8075 8076 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 8077 /// the well-formedness of the constructor declarator @p D with type @p 8078 /// R. If there are any errors in the declarator, this routine will 8079 /// emit diagnostics and set the invalid bit to true. In any case, the type 8080 /// will be updated to reflect a well-formed type for the constructor and 8081 /// returned. 8082 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 8083 StorageClass &SC) { 8084 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8085 8086 // C++ [class.ctor]p3: 8087 // A constructor shall not be virtual (10.3) or static (9.4). A 8088 // constructor can be invoked for a const, volatile or const 8089 // volatile object. A constructor shall not be declared const, 8090 // volatile, or const volatile (9.3.2). 8091 if (isVirtual) { 8092 if (!D.isInvalidType()) 8093 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8094 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 8095 << SourceRange(D.getIdentifierLoc()); 8096 D.setInvalidType(); 8097 } 8098 if (SC == SC_Static) { 8099 if (!D.isInvalidType()) 8100 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8101 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8102 << SourceRange(D.getIdentifierLoc()); 8103 D.setInvalidType(); 8104 SC = SC_None; 8105 } 8106 8107 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8108 diagnoseIgnoredQualifiers( 8109 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 8110 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 8111 D.getDeclSpec().getRestrictSpecLoc(), 8112 D.getDeclSpec().getAtomicSpecLoc()); 8113 D.setInvalidType(); 8114 } 8115 8116 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8117 if (FTI.TypeQuals != 0) { 8118 if (FTI.TypeQuals & Qualifiers::Const) 8119 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 8120 << "const" << SourceRange(D.getIdentifierLoc()); 8121 if (FTI.TypeQuals & Qualifiers::Volatile) 8122 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 8123 << "volatile" << SourceRange(D.getIdentifierLoc()); 8124 if (FTI.TypeQuals & Qualifiers::Restrict) 8125 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 8126 << "restrict" << SourceRange(D.getIdentifierLoc()); 8127 D.setInvalidType(); 8128 } 8129 8130 // C++0x [class.ctor]p4: 8131 // A constructor shall not be declared with a ref-qualifier. 8132 if (FTI.hasRefQualifier()) { 8133 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 8134 << FTI.RefQualifierIsLValueRef 8135 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8136 D.setInvalidType(); 8137 } 8138 8139 // Rebuild the function type "R" without any type qualifiers (in 8140 // case any of the errors above fired) and with "void" as the 8141 // return type, since constructors don't have return types. 8142 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8143 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 8144 return R; 8145 8146 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8147 EPI.TypeQuals = 0; 8148 EPI.RefQualifier = RQ_None; 8149 8150 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 8151 } 8152 8153 /// CheckConstructor - Checks a fully-formed constructor for 8154 /// well-formedness, issuing any diagnostics required. Returns true if 8155 /// the constructor declarator is invalid. 8156 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 8157 CXXRecordDecl *ClassDecl 8158 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 8159 if (!ClassDecl) 8160 return Constructor->setInvalidDecl(); 8161 8162 // C++ [class.copy]p3: 8163 // A declaration of a constructor for a class X is ill-formed if 8164 // its first parameter is of type (optionally cv-qualified) X and 8165 // either there are no other parameters or else all other 8166 // parameters have default arguments. 8167 if (!Constructor->isInvalidDecl() && 8168 ((Constructor->getNumParams() == 1) || 8169 (Constructor->getNumParams() > 1 && 8170 Constructor->getParamDecl(1)->hasDefaultArg())) && 8171 Constructor->getTemplateSpecializationKind() 8172 != TSK_ImplicitInstantiation) { 8173 QualType ParamType = Constructor->getParamDecl(0)->getType(); 8174 QualType ClassTy = Context.getTagDeclType(ClassDecl); 8175 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 8176 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 8177 const char *ConstRef 8178 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 8179 : " const &"; 8180 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 8181 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 8182 8183 // FIXME: Rather that making the constructor invalid, we should endeavor 8184 // to fix the type. 8185 Constructor->setInvalidDecl(); 8186 } 8187 } 8188 } 8189 8190 /// CheckDestructor - Checks a fully-formed destructor definition for 8191 /// well-formedness, issuing any diagnostics required. Returns true 8192 /// on error. 8193 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 8194 CXXRecordDecl *RD = Destructor->getParent(); 8195 8196 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 8197 SourceLocation Loc; 8198 8199 if (!Destructor->isImplicit()) 8200 Loc = Destructor->getLocation(); 8201 else 8202 Loc = RD->getLocation(); 8203 8204 // If we have a virtual destructor, look up the deallocation function 8205 if (FunctionDecl *OperatorDelete = 8206 FindDeallocationFunctionForDestructor(Loc, RD)) { 8207 Expr *ThisArg = nullptr; 8208 8209 // If the notional 'delete this' expression requires a non-trivial 8210 // conversion from 'this' to the type of a destroying operator delete's 8211 // first parameter, perform that conversion now. 8212 if (OperatorDelete->isDestroyingOperatorDelete()) { 8213 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 8214 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 8215 // C++ [class.dtor]p13: 8216 // ... as if for the expression 'delete this' appearing in a 8217 // non-virtual destructor of the destructor's class. 8218 ContextRAII SwitchContext(*this, Destructor); 8219 ExprResult This = 8220 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 8221 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 8222 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 8223 if (This.isInvalid()) { 8224 // FIXME: Register this as a context note so that it comes out 8225 // in the right order. 8226 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 8227 return true; 8228 } 8229 ThisArg = This.get(); 8230 } 8231 } 8232 8233 MarkFunctionReferenced(Loc, OperatorDelete); 8234 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 8235 } 8236 } 8237 8238 return false; 8239 } 8240 8241 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 8242 /// the well-formednes of the destructor declarator @p D with type @p 8243 /// R. If there are any errors in the declarator, this routine will 8244 /// emit diagnostics and set the declarator to invalid. Even if this happens, 8245 /// will be updated to reflect a well-formed type for the destructor and 8246 /// returned. 8247 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 8248 StorageClass& SC) { 8249 // C++ [class.dtor]p1: 8250 // [...] A typedef-name that names a class is a class-name 8251 // (7.1.3); however, a typedef-name that names a class shall not 8252 // be used as the identifier in the declarator for a destructor 8253 // declaration. 8254 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 8255 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 8256 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8257 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 8258 else if (const TemplateSpecializationType *TST = 8259 DeclaratorType->getAs<TemplateSpecializationType>()) 8260 if (TST->isTypeAlias()) 8261 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8262 << DeclaratorType << 1; 8263 8264 // C++ [class.dtor]p2: 8265 // A destructor is used to destroy objects of its class type. A 8266 // destructor takes no parameters, and no return type can be 8267 // specified for it (not even void). The address of a destructor 8268 // shall not be taken. A destructor shall not be static. A 8269 // destructor can be invoked for a const, volatile or const 8270 // volatile object. A destructor shall not be declared const, 8271 // volatile or const volatile (9.3.2). 8272 if (SC == SC_Static) { 8273 if (!D.isInvalidType()) 8274 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 8275 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8276 << SourceRange(D.getIdentifierLoc()) 8277 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8278 8279 SC = SC_None; 8280 } 8281 if (!D.isInvalidType()) { 8282 // Destructors don't have return types, but the parser will 8283 // happily parse something like: 8284 // 8285 // class X { 8286 // float ~X(); 8287 // }; 8288 // 8289 // The return type will be eliminated later. 8290 if (D.getDeclSpec().hasTypeSpecifier()) 8291 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 8292 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8293 << SourceRange(D.getIdentifierLoc()); 8294 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8295 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 8296 SourceLocation(), 8297 D.getDeclSpec().getConstSpecLoc(), 8298 D.getDeclSpec().getVolatileSpecLoc(), 8299 D.getDeclSpec().getRestrictSpecLoc(), 8300 D.getDeclSpec().getAtomicSpecLoc()); 8301 D.setInvalidType(); 8302 } 8303 } 8304 8305 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8306 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 8307 if (FTI.TypeQuals & Qualifiers::Const) 8308 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8309 << "const" << SourceRange(D.getIdentifierLoc()); 8310 if (FTI.TypeQuals & Qualifiers::Volatile) 8311 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8312 << "volatile" << SourceRange(D.getIdentifierLoc()); 8313 if (FTI.TypeQuals & Qualifiers::Restrict) 8314 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8315 << "restrict" << SourceRange(D.getIdentifierLoc()); 8316 D.setInvalidType(); 8317 } 8318 8319 // C++0x [class.dtor]p2: 8320 // A destructor shall not be declared with a ref-qualifier. 8321 if (FTI.hasRefQualifier()) { 8322 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 8323 << FTI.RefQualifierIsLValueRef 8324 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8325 D.setInvalidType(); 8326 } 8327 8328 // Make sure we don't have any parameters. 8329 if (FTIHasNonVoidParameters(FTI)) { 8330 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 8331 8332 // Delete the parameters. 8333 FTI.freeParams(); 8334 D.setInvalidType(); 8335 } 8336 8337 // Make sure the destructor isn't variadic. 8338 if (FTI.isVariadic) { 8339 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8340 D.setInvalidType(); 8341 } 8342 8343 // Rebuild the function type "R" without any type qualifiers or 8344 // parameters (in case any of the errors above fired) and with 8345 // "void" as the return type, since destructors don't have return 8346 // types. 8347 if (!D.isInvalidType()) 8348 return R; 8349 8350 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8351 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8352 EPI.Variadic = false; 8353 EPI.TypeQuals = 0; 8354 EPI.RefQualifier = RQ_None; 8355 return Context.getFunctionType(Context.VoidTy, None, EPI); 8356 } 8357 8358 static void extendLeft(SourceRange &R, SourceRange Before) { 8359 if (Before.isInvalid()) 8360 return; 8361 R.setBegin(Before.getBegin()); 8362 if (R.getEnd().isInvalid()) 8363 R.setEnd(Before.getEnd()); 8364 } 8365 8366 static void extendRight(SourceRange &R, SourceRange After) { 8367 if (After.isInvalid()) 8368 return; 8369 if (R.getBegin().isInvalid()) 8370 R.setBegin(After.getBegin()); 8371 R.setEnd(After.getEnd()); 8372 } 8373 8374 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8375 /// well-formednes of the conversion function declarator @p D with 8376 /// type @p R. If there are any errors in the declarator, this routine 8377 /// will emit diagnostics and return true. Otherwise, it will return 8378 /// false. Either way, the type @p R will be updated to reflect a 8379 /// well-formed type for the conversion operator. 8380 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8381 StorageClass& SC) { 8382 // C++ [class.conv.fct]p1: 8383 // Neither parameter types nor return type can be specified. The 8384 // type of a conversion function (8.3.5) is "function taking no 8385 // parameter returning conversion-type-id." 8386 if (SC == SC_Static) { 8387 if (!D.isInvalidType()) 8388 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8389 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8390 << D.getName().getSourceRange(); 8391 D.setInvalidType(); 8392 SC = SC_None; 8393 } 8394 8395 TypeSourceInfo *ConvTSI = nullptr; 8396 QualType ConvType = 8397 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8398 8399 const DeclSpec &DS = D.getDeclSpec(); 8400 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 8401 // Conversion functions don't have return types, but the parser will 8402 // happily parse something like: 8403 // 8404 // class X { 8405 // float operator bool(); 8406 // }; 8407 // 8408 // The return type will be changed later anyway. 8409 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8410 << SourceRange(DS.getTypeSpecTypeLoc()) 8411 << SourceRange(D.getIdentifierLoc()); 8412 D.setInvalidType(); 8413 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 8414 // It's also plausible that the user writes type qualifiers in the wrong 8415 // place, such as: 8416 // struct S { const operator int(); }; 8417 // FIXME: we could provide a fixit to move the qualifiers onto the 8418 // conversion type. 8419 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 8420 << SourceRange(D.getIdentifierLoc()) << 0; 8421 D.setInvalidType(); 8422 } 8423 8424 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8425 8426 // Make sure we don't have any parameters. 8427 if (Proto->getNumParams() > 0) { 8428 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8429 8430 // Delete the parameters. 8431 D.getFunctionTypeInfo().freeParams(); 8432 D.setInvalidType(); 8433 } else if (Proto->isVariadic()) { 8434 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8435 D.setInvalidType(); 8436 } 8437 8438 // Diagnose "&operator bool()" and other such nonsense. This 8439 // is actually a gcc extension which we don't support. 8440 if (Proto->getReturnType() != ConvType) { 8441 bool NeedsTypedef = false; 8442 SourceRange Before, After; 8443 8444 // Walk the chunks and extract information on them for our diagnostic. 8445 bool PastFunctionChunk = false; 8446 for (auto &Chunk : D.type_objects()) { 8447 switch (Chunk.Kind) { 8448 case DeclaratorChunk::Function: 8449 if (!PastFunctionChunk) { 8450 if (Chunk.Fun.HasTrailingReturnType) { 8451 TypeSourceInfo *TRT = nullptr; 8452 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8453 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8454 } 8455 PastFunctionChunk = true; 8456 break; 8457 } 8458 LLVM_FALLTHROUGH; 8459 case DeclaratorChunk::Array: 8460 NeedsTypedef = true; 8461 extendRight(After, Chunk.getSourceRange()); 8462 break; 8463 8464 case DeclaratorChunk::Pointer: 8465 case DeclaratorChunk::BlockPointer: 8466 case DeclaratorChunk::Reference: 8467 case DeclaratorChunk::MemberPointer: 8468 case DeclaratorChunk::Pipe: 8469 extendLeft(Before, Chunk.getSourceRange()); 8470 break; 8471 8472 case DeclaratorChunk::Paren: 8473 extendLeft(Before, Chunk.Loc); 8474 extendRight(After, Chunk.EndLoc); 8475 break; 8476 } 8477 } 8478 8479 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8480 After.isValid() ? After.getBegin() : 8481 D.getIdentifierLoc(); 8482 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8483 DB << Before << After; 8484 8485 if (!NeedsTypedef) { 8486 DB << /*don't need a typedef*/0; 8487 8488 // If we can provide a correct fix-it hint, do so. 8489 if (After.isInvalid() && ConvTSI) { 8490 SourceLocation InsertLoc = 8491 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 8492 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8493 << FixItHint::CreateInsertionFromRange( 8494 InsertLoc, CharSourceRange::getTokenRange(Before)) 8495 << FixItHint::CreateRemoval(Before); 8496 } 8497 } else if (!Proto->getReturnType()->isDependentType()) { 8498 DB << /*typedef*/1 << Proto->getReturnType(); 8499 } else if (getLangOpts().CPlusPlus11) { 8500 DB << /*alias template*/2 << Proto->getReturnType(); 8501 } else { 8502 DB << /*might not be fixable*/3; 8503 } 8504 8505 // Recover by incorporating the other type chunks into the result type. 8506 // Note, this does *not* change the name of the function. This is compatible 8507 // with the GCC extension: 8508 // struct S { &operator int(); } s; 8509 // int &r = s.operator int(); // ok in GCC 8510 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8511 ConvType = Proto->getReturnType(); 8512 } 8513 8514 // C++ [class.conv.fct]p4: 8515 // The conversion-type-id shall not represent a function type nor 8516 // an array type. 8517 if (ConvType->isArrayType()) { 8518 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8519 ConvType = Context.getPointerType(ConvType); 8520 D.setInvalidType(); 8521 } else if (ConvType->isFunctionType()) { 8522 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8523 ConvType = Context.getPointerType(ConvType); 8524 D.setInvalidType(); 8525 } 8526 8527 // Rebuild the function type "R" without any parameters (in case any 8528 // of the errors above fired) and with the conversion type as the 8529 // return type. 8530 if (D.isInvalidType()) 8531 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8532 8533 // C++0x explicit conversion operators. 8534 if (DS.isExplicitSpecified()) 8535 Diag(DS.getExplicitSpecLoc(), 8536 getLangOpts().CPlusPlus11 8537 ? diag::warn_cxx98_compat_explicit_conversion_functions 8538 : diag::ext_explicit_conversion_functions) 8539 << SourceRange(DS.getExplicitSpecLoc()); 8540 } 8541 8542 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8543 /// the declaration of the given C++ conversion function. This routine 8544 /// is responsible for recording the conversion function in the C++ 8545 /// class, if possible. 8546 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8547 assert(Conversion && "Expected to receive a conversion function declaration"); 8548 8549 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8550 8551 // Make sure we aren't redeclaring the conversion function. 8552 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8553 8554 // C++ [class.conv.fct]p1: 8555 // [...] A conversion function is never used to convert a 8556 // (possibly cv-qualified) object to the (possibly cv-qualified) 8557 // same object type (or a reference to it), to a (possibly 8558 // cv-qualified) base class of that type (or a reference to it), 8559 // or to (possibly cv-qualified) void. 8560 // FIXME: Suppress this warning if the conversion function ends up being a 8561 // virtual function that overrides a virtual function in a base class. 8562 QualType ClassType 8563 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8564 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8565 ConvType = ConvTypeRef->getPointeeType(); 8566 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8567 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8568 /* Suppress diagnostics for instantiations. */; 8569 else if (ConvType->isRecordType()) { 8570 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8571 if (ConvType == ClassType) 8572 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8573 << ClassType; 8574 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8575 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8576 << ClassType << ConvType; 8577 } else if (ConvType->isVoidType()) { 8578 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8579 << ClassType << ConvType; 8580 } 8581 8582 if (FunctionTemplateDecl *ConversionTemplate 8583 = Conversion->getDescribedFunctionTemplate()) 8584 return ConversionTemplate; 8585 8586 return Conversion; 8587 } 8588 8589 namespace { 8590 /// Utility class to accumulate and print a diagnostic listing the invalid 8591 /// specifier(s) on a declaration. 8592 struct BadSpecifierDiagnoser { 8593 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8594 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8595 ~BadSpecifierDiagnoser() { 8596 Diagnostic << Specifiers; 8597 } 8598 8599 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8600 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8601 } 8602 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8603 return check(SpecLoc, 8604 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8605 } 8606 void check(SourceLocation SpecLoc, const char *Spec) { 8607 if (SpecLoc.isInvalid()) return; 8608 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8609 if (!Specifiers.empty()) Specifiers += " "; 8610 Specifiers += Spec; 8611 } 8612 8613 Sema &S; 8614 Sema::SemaDiagnosticBuilder Diagnostic; 8615 std::string Specifiers; 8616 }; 8617 } 8618 8619 /// Check the validity of a declarator that we parsed for a deduction-guide. 8620 /// These aren't actually declarators in the grammar, so we need to check that 8621 /// the user didn't specify any pieces that are not part of the deduction-guide 8622 /// grammar. 8623 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8624 StorageClass &SC) { 8625 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8626 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8627 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8628 8629 // C++ [temp.deduct.guide]p3: 8630 // A deduction-gide shall be declared in the same scope as the 8631 // corresponding class template. 8632 if (!CurContext->getRedeclContext()->Equals( 8633 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8634 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8635 << GuidedTemplateDecl; 8636 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8637 } 8638 8639 auto &DS = D.getMutableDeclSpec(); 8640 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8641 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8642 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8643 DS.isNoreturnSpecified() || DS.isConstexprSpecified()) { 8644 BadSpecifierDiagnoser Diagnoser( 8645 *this, D.getIdentifierLoc(), 8646 diag::err_deduction_guide_invalid_specifier); 8647 8648 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8649 DS.ClearStorageClassSpecs(); 8650 SC = SC_None; 8651 8652 // 'explicit' is permitted. 8653 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8654 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8655 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8656 DS.ClearConstexprSpec(); 8657 8658 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8659 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8660 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8661 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8662 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8663 DS.ClearTypeQualifiers(); 8664 8665 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8666 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8667 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8668 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8669 DS.ClearTypeSpecType(); 8670 } 8671 8672 if (D.isInvalidType()) 8673 return; 8674 8675 // Check the declarator is simple enough. 8676 bool FoundFunction = false; 8677 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8678 if (Chunk.Kind == DeclaratorChunk::Paren) 8679 continue; 8680 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8681 Diag(D.getDeclSpec().getBeginLoc(), 8682 diag::err_deduction_guide_with_complex_decl) 8683 << D.getSourceRange(); 8684 break; 8685 } 8686 if (!Chunk.Fun.hasTrailingReturnType()) { 8687 Diag(D.getName().getBeginLoc(), 8688 diag::err_deduction_guide_no_trailing_return_type); 8689 break; 8690 } 8691 8692 // Check that the return type is written as a specialization of 8693 // the template specified as the deduction-guide's name. 8694 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8695 TypeSourceInfo *TSI = nullptr; 8696 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8697 assert(TSI && "deduction guide has valid type but invalid return type?"); 8698 bool AcceptableReturnType = false; 8699 bool MightInstantiateToSpecialization = false; 8700 if (auto RetTST = 8701 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8702 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8703 bool TemplateMatches = 8704 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8705 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8706 AcceptableReturnType = true; 8707 else { 8708 // This could still instantiate to the right type, unless we know it 8709 // names the wrong class template. 8710 auto *TD = SpecifiedName.getAsTemplateDecl(); 8711 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8712 !TemplateMatches); 8713 } 8714 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8715 MightInstantiateToSpecialization = true; 8716 } 8717 8718 if (!AcceptableReturnType) { 8719 Diag(TSI->getTypeLoc().getBeginLoc(), 8720 diag::err_deduction_guide_bad_trailing_return_type) 8721 << GuidedTemplate << TSI->getType() 8722 << MightInstantiateToSpecialization 8723 << TSI->getTypeLoc().getSourceRange(); 8724 } 8725 8726 // Keep going to check that we don't have any inner declarator pieces (we 8727 // could still have a function returning a pointer to a function). 8728 FoundFunction = true; 8729 } 8730 8731 if (D.isFunctionDefinition()) 8732 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8733 } 8734 8735 //===----------------------------------------------------------------------===// 8736 // Namespace Handling 8737 //===----------------------------------------------------------------------===// 8738 8739 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 8740 /// reopened. 8741 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8742 SourceLocation Loc, 8743 IdentifierInfo *II, bool *IsInline, 8744 NamespaceDecl *PrevNS) { 8745 assert(*IsInline != PrevNS->isInline()); 8746 8747 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8748 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8749 // inline namespaces, with the intention of bringing names into namespace std. 8750 // 8751 // We support this just well enough to get that case working; this is not 8752 // sufficient to support reopening namespaces as inline in general. 8753 if (*IsInline && II && II->getName().startswith("__atomic") && 8754 S.getSourceManager().isInSystemHeader(Loc)) { 8755 // Mark all prior declarations of the namespace as inline. 8756 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8757 NS = NS->getPreviousDecl()) 8758 NS->setInline(*IsInline); 8759 // Patch up the lookup table for the containing namespace. This isn't really 8760 // correct, but it's good enough for this particular case. 8761 for (auto *I : PrevNS->decls()) 8762 if (auto *ND = dyn_cast<NamedDecl>(I)) 8763 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8764 return; 8765 } 8766 8767 if (PrevNS->isInline()) 8768 // The user probably just forgot the 'inline', so suggest that it 8769 // be added back. 8770 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8771 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8772 else 8773 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8774 8775 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8776 *IsInline = PrevNS->isInline(); 8777 } 8778 8779 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8780 /// definition. 8781 Decl *Sema::ActOnStartNamespaceDef( 8782 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 8783 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 8784 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 8785 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8786 // For anonymous namespace, take the location of the left brace. 8787 SourceLocation Loc = II ? IdentLoc : LBrace; 8788 bool IsInline = InlineLoc.isValid(); 8789 bool IsInvalid = false; 8790 bool IsStd = false; 8791 bool AddToKnown = false; 8792 Scope *DeclRegionScope = NamespcScope->getParent(); 8793 8794 NamespaceDecl *PrevNS = nullptr; 8795 if (II) { 8796 // C++ [namespace.def]p2: 8797 // The identifier in an original-namespace-definition shall not 8798 // have been previously defined in the declarative region in 8799 // which the original-namespace-definition appears. The 8800 // identifier in an original-namespace-definition is the name of 8801 // the namespace. Subsequently in that declarative region, it is 8802 // treated as an original-namespace-name. 8803 // 8804 // Since namespace names are unique in their scope, and we don't 8805 // look through using directives, just look for any ordinary names 8806 // as if by qualified name lookup. 8807 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 8808 ForExternalRedeclaration); 8809 LookupQualifiedName(R, CurContext->getRedeclContext()); 8810 NamedDecl *PrevDecl = 8811 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8812 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8813 8814 if (PrevNS) { 8815 // This is an extended namespace definition. 8816 if (IsInline != PrevNS->isInline()) 8817 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8818 &IsInline, PrevNS); 8819 } else if (PrevDecl) { 8820 // This is an invalid name redefinition. 8821 Diag(Loc, diag::err_redefinition_different_kind) 8822 << II; 8823 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8824 IsInvalid = true; 8825 // Continue on to push Namespc as current DeclContext and return it. 8826 } else if (II->isStr("std") && 8827 CurContext->getRedeclContext()->isTranslationUnit()) { 8828 // This is the first "real" definition of the namespace "std", so update 8829 // our cache of the "std" namespace to point at this definition. 8830 PrevNS = getStdNamespace(); 8831 IsStd = true; 8832 AddToKnown = !IsInline; 8833 } else { 8834 // We've seen this namespace for the first time. 8835 AddToKnown = !IsInline; 8836 } 8837 } else { 8838 // Anonymous namespaces. 8839 8840 // Determine whether the parent already has an anonymous namespace. 8841 DeclContext *Parent = CurContext->getRedeclContext(); 8842 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8843 PrevNS = TU->getAnonymousNamespace(); 8844 } else { 8845 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8846 PrevNS = ND->getAnonymousNamespace(); 8847 } 8848 8849 if (PrevNS && IsInline != PrevNS->isInline()) 8850 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8851 &IsInline, PrevNS); 8852 } 8853 8854 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8855 StartLoc, Loc, II, PrevNS); 8856 if (IsInvalid) 8857 Namespc->setInvalidDecl(); 8858 8859 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8860 AddPragmaAttributes(DeclRegionScope, Namespc); 8861 8862 // FIXME: Should we be merging attributes? 8863 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8864 PushNamespaceVisibilityAttr(Attr, Loc); 8865 8866 if (IsStd) 8867 StdNamespace = Namespc; 8868 if (AddToKnown) 8869 KnownNamespaces[Namespc] = false; 8870 8871 if (II) { 8872 PushOnScopeChains(Namespc, DeclRegionScope); 8873 } else { 8874 // Link the anonymous namespace into its parent. 8875 DeclContext *Parent = CurContext->getRedeclContext(); 8876 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8877 TU->setAnonymousNamespace(Namespc); 8878 } else { 8879 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8880 } 8881 8882 CurContext->addDecl(Namespc); 8883 8884 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8885 // behaves as if it were replaced by 8886 // namespace unique { /* empty body */ } 8887 // using namespace unique; 8888 // namespace unique { namespace-body } 8889 // where all occurrences of 'unique' in a translation unit are 8890 // replaced by the same identifier and this identifier differs 8891 // from all other identifiers in the entire program. 8892 8893 // We just create the namespace with an empty name and then add an 8894 // implicit using declaration, just like the standard suggests. 8895 // 8896 // CodeGen enforces the "universally unique" aspect by giving all 8897 // declarations semantically contained within an anonymous 8898 // namespace internal linkage. 8899 8900 if (!PrevNS) { 8901 UD = UsingDirectiveDecl::Create(Context, Parent, 8902 /* 'using' */ LBrace, 8903 /* 'namespace' */ SourceLocation(), 8904 /* qualifier */ NestedNameSpecifierLoc(), 8905 /* identifier */ SourceLocation(), 8906 Namespc, 8907 /* Ancestor */ Parent); 8908 UD->setImplicit(); 8909 Parent->addDecl(UD); 8910 } 8911 } 8912 8913 ActOnDocumentableDecl(Namespc); 8914 8915 // Although we could have an invalid decl (i.e. the namespace name is a 8916 // redefinition), push it as current DeclContext and try to continue parsing. 8917 // FIXME: We should be able to push Namespc here, so that the each DeclContext 8918 // for the namespace has the declarations that showed up in that particular 8919 // namespace definition. 8920 PushDeclContext(NamespcScope, Namespc); 8921 return Namespc; 8922 } 8923 8924 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 8925 /// is a namespace alias, returns the namespace it points to. 8926 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 8927 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 8928 return AD->getNamespace(); 8929 return dyn_cast_or_null<NamespaceDecl>(D); 8930 } 8931 8932 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 8933 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 8934 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 8935 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 8936 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 8937 Namespc->setRBraceLoc(RBrace); 8938 PopDeclContext(); 8939 if (Namespc->hasAttr<VisibilityAttr>()) 8940 PopPragmaVisibility(true, RBrace); 8941 } 8942 8943 CXXRecordDecl *Sema::getStdBadAlloc() const { 8944 return cast_or_null<CXXRecordDecl>( 8945 StdBadAlloc.get(Context.getExternalSource())); 8946 } 8947 8948 EnumDecl *Sema::getStdAlignValT() const { 8949 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 8950 } 8951 8952 NamespaceDecl *Sema::getStdNamespace() const { 8953 return cast_or_null<NamespaceDecl>( 8954 StdNamespace.get(Context.getExternalSource())); 8955 } 8956 8957 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 8958 if (!StdExperimentalNamespaceCache) { 8959 if (auto Std = getStdNamespace()) { 8960 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 8961 SourceLocation(), LookupNamespaceName); 8962 if (!LookupQualifiedName(Result, Std) || 8963 !(StdExperimentalNamespaceCache = 8964 Result.getAsSingle<NamespaceDecl>())) 8965 Result.suppressDiagnostics(); 8966 } 8967 } 8968 return StdExperimentalNamespaceCache; 8969 } 8970 8971 namespace { 8972 8973 enum UnsupportedSTLSelect { 8974 USS_InvalidMember, 8975 USS_MissingMember, 8976 USS_NonTrivial, 8977 USS_Other 8978 }; 8979 8980 struct InvalidSTLDiagnoser { 8981 Sema &S; 8982 SourceLocation Loc; 8983 QualType TyForDiags; 8984 8985 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 8986 const VarDecl *VD = nullptr) { 8987 { 8988 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 8989 << TyForDiags << ((int)Sel); 8990 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 8991 assert(!Name.empty()); 8992 D << Name; 8993 } 8994 } 8995 if (Sel == USS_InvalidMember) { 8996 S.Diag(VD->getLocation(), diag::note_var_declared_here) 8997 << VD << VD->getSourceRange(); 8998 } 8999 return QualType(); 9000 } 9001 }; 9002 } // namespace 9003 9004 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 9005 SourceLocation Loc) { 9006 assert(getLangOpts().CPlusPlus && 9007 "Looking for comparison category type outside of C++."); 9008 9009 // Check if we've already successfully checked the comparison category type 9010 // before. If so, skip checking it again. 9011 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 9012 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) 9013 return Info->getType(); 9014 9015 // If lookup failed 9016 if (!Info) { 9017 std::string NameForDiags = "std::"; 9018 NameForDiags += ComparisonCategories::getCategoryString(Kind); 9019 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 9020 << NameForDiags; 9021 return QualType(); 9022 } 9023 9024 assert(Info->Kind == Kind); 9025 assert(Info->Record); 9026 9027 // Update the Record decl in case we encountered a forward declaration on our 9028 // first pass. FIXME: This is a bit of a hack. 9029 if (Info->Record->hasDefinition()) 9030 Info->Record = Info->Record->getDefinition(); 9031 9032 // Use an elaborated type for diagnostics which has a name containing the 9033 // prepended 'std' namespace but not any inline namespace names. 9034 QualType TyForDiags = [&]() { 9035 auto *NNS = 9036 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 9037 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 9038 }(); 9039 9040 if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type)) 9041 return QualType(); 9042 9043 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags}; 9044 9045 if (!Info->Record->isTriviallyCopyable()) 9046 return UnsupportedSTLError(USS_NonTrivial); 9047 9048 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 9049 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 9050 // Tolerate empty base classes. 9051 if (Base->isEmpty()) 9052 continue; 9053 // Reject STL implementations which have at least one non-empty base. 9054 return UnsupportedSTLError(); 9055 } 9056 9057 // Check that the STL has implemented the types using a single integer field. 9058 // This expectation allows better codegen for builtin operators. We require: 9059 // (1) The class has exactly one field. 9060 // (2) The field is an integral or enumeration type. 9061 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 9062 if (std::distance(FIt, FEnd) != 1 || 9063 !FIt->getType()->isIntegralOrEnumerationType()) { 9064 return UnsupportedSTLError(); 9065 } 9066 9067 // Build each of the require values and store them in Info. 9068 for (ComparisonCategoryResult CCR : 9069 ComparisonCategories::getPossibleResultsForType(Kind)) { 9070 StringRef MemName = ComparisonCategories::getResultString(CCR); 9071 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 9072 9073 if (!ValInfo) 9074 return UnsupportedSTLError(USS_MissingMember, MemName); 9075 9076 VarDecl *VD = ValInfo->VD; 9077 assert(VD && "should not be null!"); 9078 9079 // Attempt to diagnose reasons why the STL definition of this type 9080 // might be foobar, including it failing to be a constant expression. 9081 // TODO Handle more ways the lookup or result can be invalid. 9082 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || 9083 !VD->checkInitIsICE()) 9084 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 9085 9086 // Attempt to evaluate the var decl as a constant expression and extract 9087 // the value of its first field as a ICE. If this fails, the STL 9088 // implementation is not supported. 9089 if (!ValInfo->hasValidIntValue()) 9090 return UnsupportedSTLError(); 9091 9092 MarkVariableReferenced(Loc, VD); 9093 } 9094 9095 // We've successfully built the required types and expressions. Update 9096 // the cache and return the newly cached value. 9097 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 9098 return Info->getType(); 9099 } 9100 9101 /// Retrieve the special "std" namespace, which may require us to 9102 /// implicitly define the namespace. 9103 NamespaceDecl *Sema::getOrCreateStdNamespace() { 9104 if (!StdNamespace) { 9105 // The "std" namespace has not yet been defined, so build one implicitly. 9106 StdNamespace = NamespaceDecl::Create(Context, 9107 Context.getTranslationUnitDecl(), 9108 /*Inline=*/false, 9109 SourceLocation(), SourceLocation(), 9110 &PP.getIdentifierTable().get("std"), 9111 /*PrevDecl=*/nullptr); 9112 getStdNamespace()->setImplicit(true); 9113 } 9114 9115 return getStdNamespace(); 9116 } 9117 9118 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 9119 assert(getLangOpts().CPlusPlus && 9120 "Looking for std::initializer_list outside of C++."); 9121 9122 // We're looking for implicit instantiations of 9123 // template <typename E> class std::initializer_list. 9124 9125 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 9126 return false; 9127 9128 ClassTemplateDecl *Template = nullptr; 9129 const TemplateArgument *Arguments = nullptr; 9130 9131 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9132 9133 ClassTemplateSpecializationDecl *Specialization = 9134 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 9135 if (!Specialization) 9136 return false; 9137 9138 Template = Specialization->getSpecializedTemplate(); 9139 Arguments = Specialization->getTemplateArgs().data(); 9140 } else if (const TemplateSpecializationType *TST = 9141 Ty->getAs<TemplateSpecializationType>()) { 9142 Template = dyn_cast_or_null<ClassTemplateDecl>( 9143 TST->getTemplateName().getAsTemplateDecl()); 9144 Arguments = TST->getArgs(); 9145 } 9146 if (!Template) 9147 return false; 9148 9149 if (!StdInitializerList) { 9150 // Haven't recognized std::initializer_list yet, maybe this is it. 9151 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 9152 if (TemplateClass->getIdentifier() != 9153 &PP.getIdentifierTable().get("initializer_list") || 9154 !getStdNamespace()->InEnclosingNamespaceSetOf( 9155 TemplateClass->getDeclContext())) 9156 return false; 9157 // This is a template called std::initializer_list, but is it the right 9158 // template? 9159 TemplateParameterList *Params = Template->getTemplateParameters(); 9160 if (Params->getMinRequiredArguments() != 1) 9161 return false; 9162 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 9163 return false; 9164 9165 // It's the right template. 9166 StdInitializerList = Template; 9167 } 9168 9169 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 9170 return false; 9171 9172 // This is an instance of std::initializer_list. Find the argument type. 9173 if (Element) 9174 *Element = Arguments[0].getAsType(); 9175 return true; 9176 } 9177 9178 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 9179 NamespaceDecl *Std = S.getStdNamespace(); 9180 if (!Std) { 9181 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9182 return nullptr; 9183 } 9184 9185 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 9186 Loc, Sema::LookupOrdinaryName); 9187 if (!S.LookupQualifiedName(Result, Std)) { 9188 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9189 return nullptr; 9190 } 9191 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 9192 if (!Template) { 9193 Result.suppressDiagnostics(); 9194 // We found something weird. Complain about the first thing we found. 9195 NamedDecl *Found = *Result.begin(); 9196 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 9197 return nullptr; 9198 } 9199 9200 // We found some template called std::initializer_list. Now verify that it's 9201 // correct. 9202 TemplateParameterList *Params = Template->getTemplateParameters(); 9203 if (Params->getMinRequiredArguments() != 1 || 9204 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 9205 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 9206 return nullptr; 9207 } 9208 9209 return Template; 9210 } 9211 9212 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 9213 if (!StdInitializerList) { 9214 StdInitializerList = LookupStdInitializerList(*this, Loc); 9215 if (!StdInitializerList) 9216 return QualType(); 9217 } 9218 9219 TemplateArgumentListInfo Args(Loc, Loc); 9220 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 9221 Context.getTrivialTypeSourceInfo(Element, 9222 Loc))); 9223 return Context.getCanonicalType( 9224 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 9225 } 9226 9227 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 9228 // C++ [dcl.init.list]p2: 9229 // A constructor is an initializer-list constructor if its first parameter 9230 // is of type std::initializer_list<E> or reference to possibly cv-qualified 9231 // std::initializer_list<E> for some type E, and either there are no other 9232 // parameters or else all other parameters have default arguments. 9233 if (Ctor->getNumParams() < 1 || 9234 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 9235 return false; 9236 9237 QualType ArgType = Ctor->getParamDecl(0)->getType(); 9238 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 9239 ArgType = RT->getPointeeType().getUnqualifiedType(); 9240 9241 return isStdInitializerList(ArgType, nullptr); 9242 } 9243 9244 /// Determine whether a using statement is in a context where it will be 9245 /// apply in all contexts. 9246 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 9247 switch (CurContext->getDeclKind()) { 9248 case Decl::TranslationUnit: 9249 return true; 9250 case Decl::LinkageSpec: 9251 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 9252 default: 9253 return false; 9254 } 9255 } 9256 9257 namespace { 9258 9259 // Callback to only accept typo corrections that are namespaces. 9260 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 9261 public: 9262 bool ValidateCandidate(const TypoCorrection &candidate) override { 9263 if (NamedDecl *ND = candidate.getCorrectionDecl()) 9264 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 9265 return false; 9266 } 9267 }; 9268 9269 } 9270 9271 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 9272 CXXScopeSpec &SS, 9273 SourceLocation IdentLoc, 9274 IdentifierInfo *Ident) { 9275 R.clear(); 9276 if (TypoCorrection Corrected = 9277 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 9278 llvm::make_unique<NamespaceValidatorCCC>(), 9279 Sema::CTK_ErrorRecovery)) { 9280 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 9281 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 9282 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 9283 Ident->getName().equals(CorrectedStr); 9284 S.diagnoseTypo(Corrected, 9285 S.PDiag(diag::err_using_directive_member_suggest) 9286 << Ident << DC << DroppedSpecifier << SS.getRange(), 9287 S.PDiag(diag::note_namespace_defined_here)); 9288 } else { 9289 S.diagnoseTypo(Corrected, 9290 S.PDiag(diag::err_using_directive_suggest) << Ident, 9291 S.PDiag(diag::note_namespace_defined_here)); 9292 } 9293 R.addDecl(Corrected.getFoundDecl()); 9294 return true; 9295 } 9296 return false; 9297 } 9298 9299 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 9300 SourceLocation NamespcLoc, CXXScopeSpec &SS, 9301 SourceLocation IdentLoc, 9302 IdentifierInfo *NamespcName, 9303 const ParsedAttributesView &AttrList) { 9304 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9305 assert(NamespcName && "Invalid NamespcName."); 9306 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 9307 9308 // This can only happen along a recovery path. 9309 while (S->isTemplateParamScope()) 9310 S = S->getParent(); 9311 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9312 9313 UsingDirectiveDecl *UDir = nullptr; 9314 NestedNameSpecifier *Qualifier = nullptr; 9315 if (SS.isSet()) 9316 Qualifier = SS.getScopeRep(); 9317 9318 // Lookup namespace name. 9319 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 9320 LookupParsedName(R, S, &SS); 9321 if (R.isAmbiguous()) 9322 return nullptr; 9323 9324 if (R.empty()) { 9325 R.clear(); 9326 // Allow "using namespace std;" or "using namespace ::std;" even if 9327 // "std" hasn't been defined yet, for GCC compatibility. 9328 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 9329 NamespcName->isStr("std")) { 9330 Diag(IdentLoc, diag::ext_using_undefined_std); 9331 R.addDecl(getOrCreateStdNamespace()); 9332 R.resolveKind(); 9333 } 9334 // Otherwise, attempt typo correction. 9335 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 9336 } 9337 9338 if (!R.empty()) { 9339 NamedDecl *Named = R.getRepresentativeDecl(); 9340 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 9341 assert(NS && "expected namespace decl"); 9342 9343 // The use of a nested name specifier may trigger deprecation warnings. 9344 DiagnoseUseOfDecl(Named, IdentLoc); 9345 9346 // C++ [namespace.udir]p1: 9347 // A using-directive specifies that the names in the nominated 9348 // namespace can be used in the scope in which the 9349 // using-directive appears after the using-directive. During 9350 // unqualified name lookup (3.4.1), the names appear as if they 9351 // were declared in the nearest enclosing namespace which 9352 // contains both the using-directive and the nominated 9353 // namespace. [Note: in this context, "contains" means "contains 9354 // directly or indirectly". ] 9355 9356 // Find enclosing context containing both using-directive and 9357 // nominated namespace. 9358 DeclContext *CommonAncestor = NS; 9359 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 9360 CommonAncestor = CommonAncestor->getParent(); 9361 9362 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 9363 SS.getWithLocInContext(Context), 9364 IdentLoc, Named, CommonAncestor); 9365 9366 if (IsUsingDirectiveInToplevelContext(CurContext) && 9367 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 9368 Diag(IdentLoc, diag::warn_using_directive_in_header); 9369 } 9370 9371 PushUsingDirective(S, UDir); 9372 } else { 9373 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 9374 } 9375 9376 if (UDir) 9377 ProcessDeclAttributeList(S, UDir, AttrList); 9378 9379 return UDir; 9380 } 9381 9382 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 9383 // If the scope has an associated entity and the using directive is at 9384 // namespace or translation unit scope, add the UsingDirectiveDecl into 9385 // its lookup structure so qualified name lookup can find it. 9386 DeclContext *Ctx = S->getEntity(); 9387 if (Ctx && !Ctx->isFunctionOrMethod()) 9388 Ctx->addDecl(UDir); 9389 else 9390 // Otherwise, it is at block scope. The using-directives will affect lookup 9391 // only to the end of the scope. 9392 S->PushUsingDirective(UDir); 9393 } 9394 9395 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 9396 SourceLocation UsingLoc, 9397 SourceLocation TypenameLoc, CXXScopeSpec &SS, 9398 UnqualifiedId &Name, 9399 SourceLocation EllipsisLoc, 9400 const ParsedAttributesView &AttrList) { 9401 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9402 9403 if (SS.isEmpty()) { 9404 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 9405 return nullptr; 9406 } 9407 9408 switch (Name.getKind()) { 9409 case UnqualifiedIdKind::IK_ImplicitSelfParam: 9410 case UnqualifiedIdKind::IK_Identifier: 9411 case UnqualifiedIdKind::IK_OperatorFunctionId: 9412 case UnqualifiedIdKind::IK_LiteralOperatorId: 9413 case UnqualifiedIdKind::IK_ConversionFunctionId: 9414 break; 9415 9416 case UnqualifiedIdKind::IK_ConstructorName: 9417 case UnqualifiedIdKind::IK_ConstructorTemplateId: 9418 // C++11 inheriting constructors. 9419 Diag(Name.getBeginLoc(), 9420 getLangOpts().CPlusPlus11 9421 ? diag::warn_cxx98_compat_using_decl_constructor 9422 : diag::err_using_decl_constructor) 9423 << SS.getRange(); 9424 9425 if (getLangOpts().CPlusPlus11) break; 9426 9427 return nullptr; 9428 9429 case UnqualifiedIdKind::IK_DestructorName: 9430 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 9431 return nullptr; 9432 9433 case UnqualifiedIdKind::IK_TemplateId: 9434 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 9435 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 9436 return nullptr; 9437 9438 case UnqualifiedIdKind::IK_DeductionGuideName: 9439 llvm_unreachable("cannot parse qualified deduction guide name"); 9440 } 9441 9442 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 9443 DeclarationName TargetName = TargetNameInfo.getName(); 9444 if (!TargetName) 9445 return nullptr; 9446 9447 // Warn about access declarations. 9448 if (UsingLoc.isInvalid()) { 9449 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 9450 ? diag::err_access_decl 9451 : diag::warn_access_decl_deprecated) 9452 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 9453 } 9454 9455 if (EllipsisLoc.isInvalid()) { 9456 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 9457 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 9458 return nullptr; 9459 } else { 9460 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 9461 !TargetNameInfo.containsUnexpandedParameterPack()) { 9462 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 9463 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 9464 EllipsisLoc = SourceLocation(); 9465 } 9466 } 9467 9468 NamedDecl *UD = 9469 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9470 SS, TargetNameInfo, EllipsisLoc, AttrList, 9471 /*IsInstantiation*/false); 9472 if (UD) 9473 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9474 9475 return UD; 9476 } 9477 9478 /// Determine whether a using declaration considers the given 9479 /// declarations as "equivalent", e.g., if they are redeclarations of 9480 /// the same entity or are both typedefs of the same type. 9481 static bool 9482 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9483 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9484 return true; 9485 9486 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9487 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9488 return Context.hasSameType(TD1->getUnderlyingType(), 9489 TD2->getUnderlyingType()); 9490 9491 return false; 9492 } 9493 9494 9495 /// Determines whether to create a using shadow decl for a particular 9496 /// decl, given the set of decls existing prior to this using lookup. 9497 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9498 const LookupResult &Previous, 9499 UsingShadowDecl *&PrevShadow) { 9500 // Diagnose finding a decl which is not from a base class of the 9501 // current class. We do this now because there are cases where this 9502 // function will silently decide not to build a shadow decl, which 9503 // will pre-empt further diagnostics. 9504 // 9505 // We don't need to do this in C++11 because we do the check once on 9506 // the qualifier. 9507 // 9508 // FIXME: diagnose the following if we care enough: 9509 // struct A { int foo; }; 9510 // struct B : A { using A::foo; }; 9511 // template <class T> struct C : A {}; 9512 // template <class T> struct D : C<T> { using B::foo; } // <--- 9513 // This is invalid (during instantiation) in C++03 because B::foo 9514 // resolves to the using decl in B, which is not a base class of D<T>. 9515 // We can't diagnose it immediately because C<T> is an unknown 9516 // specialization. The UsingShadowDecl in D<T> then points directly 9517 // to A::foo, which will look well-formed when we instantiate. 9518 // The right solution is to not collapse the shadow-decl chain. 9519 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9520 DeclContext *OrigDC = Orig->getDeclContext(); 9521 9522 // Handle enums and anonymous structs. 9523 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9524 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9525 while (OrigRec->isAnonymousStructOrUnion()) 9526 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9527 9528 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9529 if (OrigDC == CurContext) { 9530 Diag(Using->getLocation(), 9531 diag::err_using_decl_nested_name_specifier_is_current_class) 9532 << Using->getQualifierLoc().getSourceRange(); 9533 Diag(Orig->getLocation(), diag::note_using_decl_target); 9534 Using->setInvalidDecl(); 9535 return true; 9536 } 9537 9538 Diag(Using->getQualifierLoc().getBeginLoc(), 9539 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9540 << Using->getQualifier() 9541 << cast<CXXRecordDecl>(CurContext) 9542 << Using->getQualifierLoc().getSourceRange(); 9543 Diag(Orig->getLocation(), diag::note_using_decl_target); 9544 Using->setInvalidDecl(); 9545 return true; 9546 } 9547 } 9548 9549 if (Previous.empty()) return false; 9550 9551 NamedDecl *Target = Orig; 9552 if (isa<UsingShadowDecl>(Target)) 9553 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9554 9555 // If the target happens to be one of the previous declarations, we 9556 // don't have a conflict. 9557 // 9558 // FIXME: but we might be increasing its access, in which case we 9559 // should redeclare it. 9560 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9561 bool FoundEquivalentDecl = false; 9562 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9563 I != E; ++I) { 9564 NamedDecl *D = (*I)->getUnderlyingDecl(); 9565 // We can have UsingDecls in our Previous results because we use the same 9566 // LookupResult for checking whether the UsingDecl itself is a valid 9567 // redeclaration. 9568 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9569 continue; 9570 9571 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 9572 // C++ [class.mem]p19: 9573 // If T is the name of a class, then [every named member other than 9574 // a non-static data member] shall have a name different from T 9575 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 9576 !isa<IndirectFieldDecl>(Target) && 9577 !isa<UnresolvedUsingValueDecl>(Target) && 9578 DiagnoseClassNameShadow( 9579 CurContext, 9580 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 9581 return true; 9582 } 9583 9584 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9585 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9586 PrevShadow = Shadow; 9587 FoundEquivalentDecl = true; 9588 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9589 // We don't conflict with an existing using shadow decl of an equivalent 9590 // declaration, but we're not a redeclaration of it. 9591 FoundEquivalentDecl = true; 9592 } 9593 9594 if (isVisible(D)) 9595 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9596 } 9597 9598 if (FoundEquivalentDecl) 9599 return false; 9600 9601 if (FunctionDecl *FD = Target->getAsFunction()) { 9602 NamedDecl *OldDecl = nullptr; 9603 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9604 /*IsForUsingDecl*/ true)) { 9605 case Ovl_Overload: 9606 return false; 9607 9608 case Ovl_NonFunction: 9609 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9610 break; 9611 9612 // We found a decl with the exact signature. 9613 case Ovl_Match: 9614 // If we're in a record, we want to hide the target, so we 9615 // return true (without a diagnostic) to tell the caller not to 9616 // build a shadow decl. 9617 if (CurContext->isRecord()) 9618 return true; 9619 9620 // If we're not in a record, this is an error. 9621 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9622 break; 9623 } 9624 9625 Diag(Target->getLocation(), diag::note_using_decl_target); 9626 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9627 Using->setInvalidDecl(); 9628 return true; 9629 } 9630 9631 // Target is not a function. 9632 9633 if (isa<TagDecl>(Target)) { 9634 // No conflict between a tag and a non-tag. 9635 if (!Tag) return false; 9636 9637 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9638 Diag(Target->getLocation(), diag::note_using_decl_target); 9639 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9640 Using->setInvalidDecl(); 9641 return true; 9642 } 9643 9644 // No conflict between a tag and a non-tag. 9645 if (!NonTag) return false; 9646 9647 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9648 Diag(Target->getLocation(), diag::note_using_decl_target); 9649 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9650 Using->setInvalidDecl(); 9651 return true; 9652 } 9653 9654 /// Determine whether a direct base class is a virtual base class. 9655 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9656 if (!Derived->getNumVBases()) 9657 return false; 9658 for (auto &B : Derived->bases()) 9659 if (B.getType()->getAsCXXRecordDecl() == Base) 9660 return B.isVirtual(); 9661 llvm_unreachable("not a direct base class"); 9662 } 9663 9664 /// Builds a shadow declaration corresponding to a 'using' declaration. 9665 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9666 UsingDecl *UD, 9667 NamedDecl *Orig, 9668 UsingShadowDecl *PrevDecl) { 9669 // If we resolved to another shadow declaration, just coalesce them. 9670 NamedDecl *Target = Orig; 9671 if (isa<UsingShadowDecl>(Target)) { 9672 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9673 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9674 } 9675 9676 NamedDecl *NonTemplateTarget = Target; 9677 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9678 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9679 9680 UsingShadowDecl *Shadow; 9681 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 9682 bool IsVirtualBase = 9683 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9684 UD->getQualifier()->getAsRecordDecl()); 9685 Shadow = ConstructorUsingShadowDecl::Create( 9686 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9687 } else { 9688 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9689 Target); 9690 } 9691 UD->addShadowDecl(Shadow); 9692 9693 Shadow->setAccess(UD->getAccess()); 9694 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9695 Shadow->setInvalidDecl(); 9696 9697 Shadow->setPreviousDecl(PrevDecl); 9698 9699 if (S) 9700 PushOnScopeChains(Shadow, S); 9701 else 9702 CurContext->addDecl(Shadow); 9703 9704 9705 return Shadow; 9706 } 9707 9708 /// Hides a using shadow declaration. This is required by the current 9709 /// using-decl implementation when a resolvable using declaration in a 9710 /// class is followed by a declaration which would hide or override 9711 /// one or more of the using decl's targets; for example: 9712 /// 9713 /// struct Base { void foo(int); }; 9714 /// struct Derived : Base { 9715 /// using Base::foo; 9716 /// void foo(int); 9717 /// }; 9718 /// 9719 /// The governing language is C++03 [namespace.udecl]p12: 9720 /// 9721 /// When a using-declaration brings names from a base class into a 9722 /// derived class scope, member functions in the derived class 9723 /// override and/or hide member functions with the same name and 9724 /// parameter types in a base class (rather than conflicting). 9725 /// 9726 /// There are two ways to implement this: 9727 /// (1) optimistically create shadow decls when they're not hidden 9728 /// by existing declarations, or 9729 /// (2) don't create any shadow decls (or at least don't make them 9730 /// visible) until we've fully parsed/instantiated the class. 9731 /// The problem with (1) is that we might have to retroactively remove 9732 /// a shadow decl, which requires several O(n) operations because the 9733 /// decl structures are (very reasonably) not designed for removal. 9734 /// (2) avoids this but is very fiddly and phase-dependent. 9735 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9736 if (Shadow->getDeclName().getNameKind() == 9737 DeclarationName::CXXConversionFunctionName) 9738 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9739 9740 // Remove it from the DeclContext... 9741 Shadow->getDeclContext()->removeDecl(Shadow); 9742 9743 // ...and the scope, if applicable... 9744 if (S) { 9745 S->RemoveDecl(Shadow); 9746 IdResolver.RemoveDecl(Shadow); 9747 } 9748 9749 // ...and the using decl. 9750 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9751 9752 // TODO: complain somehow if Shadow was used. It shouldn't 9753 // be possible for this to happen, because...? 9754 } 9755 9756 /// Find the base specifier for a base class with the given type. 9757 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 9758 QualType DesiredBase, 9759 bool &AnyDependentBases) { 9760 // Check whether the named type is a direct base class. 9761 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 9762 for (auto &Base : Derived->bases()) { 9763 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 9764 if (CanonicalDesiredBase == BaseType) 9765 return &Base; 9766 if (BaseType->isDependentType()) 9767 AnyDependentBases = true; 9768 } 9769 return nullptr; 9770 } 9771 9772 namespace { 9773 class UsingValidatorCCC : public CorrectionCandidateCallback { 9774 public: 9775 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 9776 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 9777 : HasTypenameKeyword(HasTypenameKeyword), 9778 IsInstantiation(IsInstantiation), OldNNS(NNS), 9779 RequireMemberOf(RequireMemberOf) {} 9780 9781 bool ValidateCandidate(const TypoCorrection &Candidate) override { 9782 NamedDecl *ND = Candidate.getCorrectionDecl(); 9783 9784 // Keywords are not valid here. 9785 if (!ND || isa<NamespaceDecl>(ND)) 9786 return false; 9787 9788 // Completely unqualified names are invalid for a 'using' declaration. 9789 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 9790 return false; 9791 9792 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 9793 // reject. 9794 9795 if (RequireMemberOf) { 9796 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9797 if (FoundRecord && FoundRecord->isInjectedClassName()) { 9798 // No-one ever wants a using-declaration to name an injected-class-name 9799 // of a base class, unless they're declaring an inheriting constructor. 9800 ASTContext &Ctx = ND->getASTContext(); 9801 if (!Ctx.getLangOpts().CPlusPlus11) 9802 return false; 9803 QualType FoundType = Ctx.getRecordType(FoundRecord); 9804 9805 // Check that the injected-class-name is named as a member of its own 9806 // type; we don't want to suggest 'using Derived::Base;', since that 9807 // means something else. 9808 NestedNameSpecifier *Specifier = 9809 Candidate.WillReplaceSpecifier() 9810 ? Candidate.getCorrectionSpecifier() 9811 : OldNNS; 9812 if (!Specifier->getAsType() || 9813 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 9814 return false; 9815 9816 // Check that this inheriting constructor declaration actually names a 9817 // direct base class of the current class. 9818 bool AnyDependentBases = false; 9819 if (!findDirectBaseWithType(RequireMemberOf, 9820 Ctx.getRecordType(FoundRecord), 9821 AnyDependentBases) && 9822 !AnyDependentBases) 9823 return false; 9824 } else { 9825 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 9826 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 9827 return false; 9828 9829 // FIXME: Check that the base class member is accessible? 9830 } 9831 } else { 9832 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9833 if (FoundRecord && FoundRecord->isInjectedClassName()) 9834 return false; 9835 } 9836 9837 if (isa<TypeDecl>(ND)) 9838 return HasTypenameKeyword || !IsInstantiation; 9839 9840 return !HasTypenameKeyword; 9841 } 9842 9843 private: 9844 bool HasTypenameKeyword; 9845 bool IsInstantiation; 9846 NestedNameSpecifier *OldNNS; 9847 CXXRecordDecl *RequireMemberOf; 9848 }; 9849 } // end anonymous namespace 9850 9851 /// Builds a using declaration. 9852 /// 9853 /// \param IsInstantiation - Whether this call arises from an 9854 /// instantiation of an unresolved using declaration. We treat 9855 /// the lookup differently for these declarations. 9856 NamedDecl *Sema::BuildUsingDeclaration( 9857 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 9858 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 9859 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 9860 const ParsedAttributesView &AttrList, bool IsInstantiation) { 9861 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9862 SourceLocation IdentLoc = NameInfo.getLoc(); 9863 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9864 9865 // FIXME: We ignore attributes for now. 9866 9867 // For an inheriting constructor declaration, the name of the using 9868 // declaration is the name of a constructor in this class, not in the 9869 // base class. 9870 DeclarationNameInfo UsingName = NameInfo; 9871 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9872 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9873 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9874 Context.getCanonicalType(Context.getRecordType(RD)))); 9875 9876 // Do the redeclaration lookup in the current scope. 9877 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9878 ForVisibleRedeclaration); 9879 Previous.setHideTags(false); 9880 if (S) { 9881 LookupName(Previous, S); 9882 9883 // It is really dumb that we have to do this. 9884 LookupResult::Filter F = Previous.makeFilter(); 9885 while (F.hasNext()) { 9886 NamedDecl *D = F.next(); 9887 if (!isDeclInScope(D, CurContext, S)) 9888 F.erase(); 9889 // If we found a local extern declaration that's not ordinarily visible, 9890 // and this declaration is being added to a non-block scope, ignore it. 9891 // We're only checking for scope conflicts here, not also for violations 9892 // of the linkage rules. 9893 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9894 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9895 F.erase(); 9896 } 9897 F.done(); 9898 } else { 9899 assert(IsInstantiation && "no scope in non-instantiation"); 9900 if (CurContext->isRecord()) 9901 LookupQualifiedName(Previous, CurContext); 9902 else { 9903 // No redeclaration check is needed here; in non-member contexts we 9904 // diagnosed all possible conflicts with other using-declarations when 9905 // building the template: 9906 // 9907 // For a dependent non-type using declaration, the only valid case is 9908 // if we instantiate to a single enumerator. We check for conflicts 9909 // between shadow declarations we introduce, and we check in the template 9910 // definition for conflicts between a non-type using declaration and any 9911 // other declaration, which together covers all cases. 9912 // 9913 // A dependent typename using declaration will never successfully 9914 // instantiate, since it will always name a class member, so we reject 9915 // that in the template definition. 9916 } 9917 } 9918 9919 // Check for invalid redeclarations. 9920 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 9921 SS, IdentLoc, Previous)) 9922 return nullptr; 9923 9924 // Check for bad qualifiers. 9925 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 9926 IdentLoc)) 9927 return nullptr; 9928 9929 DeclContext *LookupContext = computeDeclContext(SS); 9930 NamedDecl *D; 9931 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9932 if (!LookupContext || EllipsisLoc.isValid()) { 9933 if (HasTypenameKeyword) { 9934 // FIXME: not all declaration name kinds are legal here 9935 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 9936 UsingLoc, TypenameLoc, 9937 QualifierLoc, 9938 IdentLoc, NameInfo.getName(), 9939 EllipsisLoc); 9940 } else { 9941 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 9942 QualifierLoc, NameInfo, EllipsisLoc); 9943 } 9944 D->setAccess(AS); 9945 CurContext->addDecl(D); 9946 return D; 9947 } 9948 9949 auto Build = [&](bool Invalid) { 9950 UsingDecl *UD = 9951 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 9952 UsingName, HasTypenameKeyword); 9953 UD->setAccess(AS); 9954 CurContext->addDecl(UD); 9955 UD->setInvalidDecl(Invalid); 9956 return UD; 9957 }; 9958 auto BuildInvalid = [&]{ return Build(true); }; 9959 auto BuildValid = [&]{ return Build(false); }; 9960 9961 if (RequireCompleteDeclContext(SS, LookupContext)) 9962 return BuildInvalid(); 9963 9964 // Look up the target name. 9965 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9966 9967 // Unlike most lookups, we don't always want to hide tag 9968 // declarations: tag names are visible through the using declaration 9969 // even if hidden by ordinary names, *except* in a dependent context 9970 // where it's important for the sanity of two-phase lookup. 9971 if (!IsInstantiation) 9972 R.setHideTags(false); 9973 9974 // For the purposes of this lookup, we have a base object type 9975 // equal to that of the current context. 9976 if (CurContext->isRecord()) { 9977 R.setBaseObjectType( 9978 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 9979 } 9980 9981 LookupQualifiedName(R, LookupContext); 9982 9983 // Try to correct typos if possible. If constructor name lookup finds no 9984 // results, that means the named class has no explicit constructors, and we 9985 // suppressed declaring implicit ones (probably because it's dependent or 9986 // invalid). 9987 if (R.empty() && 9988 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 9989 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 9990 // it will believe that glibc provides a ::gets in cases where it does not, 9991 // and will try to pull it into namespace std with a using-declaration. 9992 // Just ignore the using-declaration in that case. 9993 auto *II = NameInfo.getName().getAsIdentifierInfo(); 9994 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 9995 CurContext->isStdNamespace() && 9996 isa<TranslationUnitDecl>(LookupContext) && 9997 getSourceManager().isInSystemHeader(UsingLoc)) 9998 return nullptr; 9999 if (TypoCorrection Corrected = CorrectTypo( 10000 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 10001 llvm::make_unique<UsingValidatorCCC>( 10002 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 10003 dyn_cast<CXXRecordDecl>(CurContext)), 10004 CTK_ErrorRecovery)) { 10005 // We reject candidates where DroppedSpecifier == true, hence the 10006 // literal '0' below. 10007 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 10008 << NameInfo.getName() << LookupContext << 0 10009 << SS.getRange()); 10010 10011 // If we picked a correction with no attached Decl we can't do anything 10012 // useful with it, bail out. 10013 NamedDecl *ND = Corrected.getCorrectionDecl(); 10014 if (!ND) 10015 return BuildInvalid(); 10016 10017 // If we corrected to an inheriting constructor, handle it as one. 10018 auto *RD = dyn_cast<CXXRecordDecl>(ND); 10019 if (RD && RD->isInjectedClassName()) { 10020 // The parent of the injected class name is the class itself. 10021 RD = cast<CXXRecordDecl>(RD->getParent()); 10022 10023 // Fix up the information we'll use to build the using declaration. 10024 if (Corrected.WillReplaceSpecifier()) { 10025 NestedNameSpecifierLocBuilder Builder; 10026 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 10027 QualifierLoc.getSourceRange()); 10028 QualifierLoc = Builder.getWithLocInContext(Context); 10029 } 10030 10031 // In this case, the name we introduce is the name of a derived class 10032 // constructor. 10033 auto *CurClass = cast<CXXRecordDecl>(CurContext); 10034 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 10035 Context.getCanonicalType(Context.getRecordType(CurClass)))); 10036 UsingName.setNamedTypeInfo(nullptr); 10037 for (auto *Ctor : LookupConstructors(RD)) 10038 R.addDecl(Ctor); 10039 R.resolveKind(); 10040 } else { 10041 // FIXME: Pick up all the declarations if we found an overloaded 10042 // function. 10043 UsingName.setName(ND->getDeclName()); 10044 R.addDecl(ND); 10045 } 10046 } else { 10047 Diag(IdentLoc, diag::err_no_member) 10048 << NameInfo.getName() << LookupContext << SS.getRange(); 10049 return BuildInvalid(); 10050 } 10051 } 10052 10053 if (R.isAmbiguous()) 10054 return BuildInvalid(); 10055 10056 if (HasTypenameKeyword) { 10057 // If we asked for a typename and got a non-type decl, error out. 10058 if (!R.getAsSingle<TypeDecl>()) { 10059 Diag(IdentLoc, diag::err_using_typename_non_type); 10060 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10061 Diag((*I)->getUnderlyingDecl()->getLocation(), 10062 diag::note_using_decl_target); 10063 return BuildInvalid(); 10064 } 10065 } else { 10066 // If we asked for a non-typename and we got a type, error out, 10067 // but only if this is an instantiation of an unresolved using 10068 // decl. Otherwise just silently find the type name. 10069 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 10070 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 10071 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 10072 return BuildInvalid(); 10073 } 10074 } 10075 10076 // C++14 [namespace.udecl]p6: 10077 // A using-declaration shall not name a namespace. 10078 if (R.getAsSingle<NamespaceDecl>()) { 10079 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 10080 << SS.getRange(); 10081 return BuildInvalid(); 10082 } 10083 10084 // C++14 [namespace.udecl]p7: 10085 // A using-declaration shall not name a scoped enumerator. 10086 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 10087 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 10088 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 10089 << SS.getRange(); 10090 return BuildInvalid(); 10091 } 10092 } 10093 10094 UsingDecl *UD = BuildValid(); 10095 10096 // Some additional rules apply to inheriting constructors. 10097 if (UsingName.getName().getNameKind() == 10098 DeclarationName::CXXConstructorName) { 10099 // Suppress access diagnostics; the access check is instead performed at the 10100 // point of use for an inheriting constructor. 10101 R.suppressDiagnostics(); 10102 if (CheckInheritingConstructorUsingDecl(UD)) 10103 return UD; 10104 } 10105 10106 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 10107 UsingShadowDecl *PrevDecl = nullptr; 10108 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 10109 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 10110 } 10111 10112 return UD; 10113 } 10114 10115 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 10116 ArrayRef<NamedDecl *> Expansions) { 10117 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 10118 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 10119 isa<UsingPackDecl>(InstantiatedFrom)); 10120 10121 auto *UPD = 10122 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 10123 UPD->setAccess(InstantiatedFrom->getAccess()); 10124 CurContext->addDecl(UPD); 10125 return UPD; 10126 } 10127 10128 /// Additional checks for a using declaration referring to a constructor name. 10129 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 10130 assert(!UD->hasTypename() && "expecting a constructor name"); 10131 10132 const Type *SourceType = UD->getQualifier()->getAsType(); 10133 assert(SourceType && 10134 "Using decl naming constructor doesn't have type in scope spec."); 10135 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 10136 10137 // Check whether the named type is a direct base class. 10138 bool AnyDependentBases = false; 10139 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 10140 AnyDependentBases); 10141 if (!Base && !AnyDependentBases) { 10142 Diag(UD->getUsingLoc(), 10143 diag::err_using_decl_constructor_not_in_direct_base) 10144 << UD->getNameInfo().getSourceRange() 10145 << QualType(SourceType, 0) << TargetClass; 10146 UD->setInvalidDecl(); 10147 return true; 10148 } 10149 10150 if (Base) 10151 Base->setInheritConstructors(); 10152 10153 return false; 10154 } 10155 10156 /// Checks that the given using declaration is not an invalid 10157 /// redeclaration. Note that this is checking only for the using decl 10158 /// itself, not for any ill-formedness among the UsingShadowDecls. 10159 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 10160 bool HasTypenameKeyword, 10161 const CXXScopeSpec &SS, 10162 SourceLocation NameLoc, 10163 const LookupResult &Prev) { 10164 NestedNameSpecifier *Qual = SS.getScopeRep(); 10165 10166 // C++03 [namespace.udecl]p8: 10167 // C++0x [namespace.udecl]p10: 10168 // A using-declaration is a declaration and can therefore be used 10169 // repeatedly where (and only where) multiple declarations are 10170 // allowed. 10171 // 10172 // That's in non-member contexts. 10173 if (!CurContext->getRedeclContext()->isRecord()) { 10174 // A dependent qualifier outside a class can only ever resolve to an 10175 // enumeration type. Therefore it conflicts with any other non-type 10176 // declaration in the same scope. 10177 // FIXME: How should we check for dependent type-type conflicts at block 10178 // scope? 10179 if (Qual->isDependent() && !HasTypenameKeyword) { 10180 for (auto *D : Prev) { 10181 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 10182 bool OldCouldBeEnumerator = 10183 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 10184 Diag(NameLoc, 10185 OldCouldBeEnumerator ? diag::err_redefinition 10186 : diag::err_redefinition_different_kind) 10187 << Prev.getLookupName(); 10188 Diag(D->getLocation(), diag::note_previous_definition); 10189 return true; 10190 } 10191 } 10192 } 10193 return false; 10194 } 10195 10196 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 10197 NamedDecl *D = *I; 10198 10199 bool DTypename; 10200 NestedNameSpecifier *DQual; 10201 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 10202 DTypename = UD->hasTypename(); 10203 DQual = UD->getQualifier(); 10204 } else if (UnresolvedUsingValueDecl *UD 10205 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 10206 DTypename = false; 10207 DQual = UD->getQualifier(); 10208 } else if (UnresolvedUsingTypenameDecl *UD 10209 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 10210 DTypename = true; 10211 DQual = UD->getQualifier(); 10212 } else continue; 10213 10214 // using decls differ if one says 'typename' and the other doesn't. 10215 // FIXME: non-dependent using decls? 10216 if (HasTypenameKeyword != DTypename) continue; 10217 10218 // using decls differ if they name different scopes (but note that 10219 // template instantiation can cause this check to trigger when it 10220 // didn't before instantiation). 10221 if (Context.getCanonicalNestedNameSpecifier(Qual) != 10222 Context.getCanonicalNestedNameSpecifier(DQual)) 10223 continue; 10224 10225 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 10226 Diag(D->getLocation(), diag::note_using_decl) << 1; 10227 return true; 10228 } 10229 10230 return false; 10231 } 10232 10233 10234 /// Checks that the given nested-name qualifier used in a using decl 10235 /// in the current context is appropriately related to the current 10236 /// scope. If an error is found, diagnoses it and returns true. 10237 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 10238 bool HasTypename, 10239 const CXXScopeSpec &SS, 10240 const DeclarationNameInfo &NameInfo, 10241 SourceLocation NameLoc) { 10242 DeclContext *NamedContext = computeDeclContext(SS); 10243 10244 if (!CurContext->isRecord()) { 10245 // C++03 [namespace.udecl]p3: 10246 // C++0x [namespace.udecl]p8: 10247 // A using-declaration for a class member shall be a member-declaration. 10248 10249 // If we weren't able to compute a valid scope, it might validly be a 10250 // dependent class scope or a dependent enumeration unscoped scope. If 10251 // we have a 'typename' keyword, the scope must resolve to a class type. 10252 if ((HasTypename && !NamedContext) || 10253 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 10254 auto *RD = NamedContext 10255 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 10256 : nullptr; 10257 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 10258 RD = nullptr; 10259 10260 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 10261 << SS.getRange(); 10262 10263 // If we have a complete, non-dependent source type, try to suggest a 10264 // way to get the same effect. 10265 if (!RD) 10266 return true; 10267 10268 // Find what this using-declaration was referring to. 10269 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10270 R.setHideTags(false); 10271 R.suppressDiagnostics(); 10272 LookupQualifiedName(R, RD); 10273 10274 if (R.getAsSingle<TypeDecl>()) { 10275 if (getLangOpts().CPlusPlus11) { 10276 // Convert 'using X::Y;' to 'using Y = X::Y;'. 10277 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 10278 << 0 // alias declaration 10279 << FixItHint::CreateInsertion(SS.getBeginLoc(), 10280 NameInfo.getName().getAsString() + 10281 " = "); 10282 } else { 10283 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 10284 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 10285 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 10286 << 1 // typedef declaration 10287 << FixItHint::CreateReplacement(UsingLoc, "typedef") 10288 << FixItHint::CreateInsertion( 10289 InsertLoc, " " + NameInfo.getName().getAsString()); 10290 } 10291 } else if (R.getAsSingle<VarDecl>()) { 10292 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10293 // repeating the type of the static data member here. 10294 FixItHint FixIt; 10295 if (getLangOpts().CPlusPlus11) { 10296 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10297 FixIt = FixItHint::CreateReplacement( 10298 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 10299 } 10300 10301 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10302 << 2 // reference declaration 10303 << FixIt; 10304 } else if (R.getAsSingle<EnumConstantDecl>()) { 10305 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10306 // repeating the type of the enumeration here, and we can't do so if 10307 // the type is anonymous. 10308 FixItHint FixIt; 10309 if (getLangOpts().CPlusPlus11) { 10310 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10311 FixIt = FixItHint::CreateReplacement( 10312 UsingLoc, 10313 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 10314 } 10315 10316 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10317 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 10318 << FixIt; 10319 } 10320 return true; 10321 } 10322 10323 // Otherwise, this might be valid. 10324 return false; 10325 } 10326 10327 // The current scope is a record. 10328 10329 // If the named context is dependent, we can't decide much. 10330 if (!NamedContext) { 10331 // FIXME: in C++0x, we can diagnose if we can prove that the 10332 // nested-name-specifier does not refer to a base class, which is 10333 // still possible in some cases. 10334 10335 // Otherwise we have to conservatively report that things might be 10336 // okay. 10337 return false; 10338 } 10339 10340 if (!NamedContext->isRecord()) { 10341 // Ideally this would point at the last name in the specifier, 10342 // but we don't have that level of source info. 10343 Diag(SS.getRange().getBegin(), 10344 diag::err_using_decl_nested_name_specifier_is_not_class) 10345 << SS.getScopeRep() << SS.getRange(); 10346 return true; 10347 } 10348 10349 if (!NamedContext->isDependentContext() && 10350 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 10351 return true; 10352 10353 if (getLangOpts().CPlusPlus11) { 10354 // C++11 [namespace.udecl]p3: 10355 // In a using-declaration used as a member-declaration, the 10356 // nested-name-specifier shall name a base class of the class 10357 // being defined. 10358 10359 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 10360 cast<CXXRecordDecl>(NamedContext))) { 10361 if (CurContext == NamedContext) { 10362 Diag(NameLoc, 10363 diag::err_using_decl_nested_name_specifier_is_current_class) 10364 << SS.getRange(); 10365 return true; 10366 } 10367 10368 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 10369 Diag(SS.getRange().getBegin(), 10370 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10371 << SS.getScopeRep() 10372 << cast<CXXRecordDecl>(CurContext) 10373 << SS.getRange(); 10374 } 10375 return true; 10376 } 10377 10378 return false; 10379 } 10380 10381 // C++03 [namespace.udecl]p4: 10382 // A using-declaration used as a member-declaration shall refer 10383 // to a member of a base class of the class being defined [etc.]. 10384 10385 // Salient point: SS doesn't have to name a base class as long as 10386 // lookup only finds members from base classes. Therefore we can 10387 // diagnose here only if we can prove that that can't happen, 10388 // i.e. if the class hierarchies provably don't intersect. 10389 10390 // TODO: it would be nice if "definitely valid" results were cached 10391 // in the UsingDecl and UsingShadowDecl so that these checks didn't 10392 // need to be repeated. 10393 10394 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 10395 auto Collect = [&Bases](const CXXRecordDecl *Base) { 10396 Bases.insert(Base); 10397 return true; 10398 }; 10399 10400 // Collect all bases. Return false if we find a dependent base. 10401 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 10402 return false; 10403 10404 // Returns true if the base is dependent or is one of the accumulated base 10405 // classes. 10406 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 10407 return !Bases.count(Base); 10408 }; 10409 10410 // Return false if the class has a dependent base or if it or one 10411 // of its bases is present in the base set of the current context. 10412 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 10413 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 10414 return false; 10415 10416 Diag(SS.getRange().getBegin(), 10417 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10418 << SS.getScopeRep() 10419 << cast<CXXRecordDecl>(CurContext) 10420 << SS.getRange(); 10421 10422 return true; 10423 } 10424 10425 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 10426 MultiTemplateParamsArg TemplateParamLists, 10427 SourceLocation UsingLoc, UnqualifiedId &Name, 10428 const ParsedAttributesView &AttrList, 10429 TypeResult Type, Decl *DeclFromDeclSpec) { 10430 // Skip up to the relevant declaration scope. 10431 while (S->isTemplateParamScope()) 10432 S = S->getParent(); 10433 assert((S->getFlags() & Scope::DeclScope) && 10434 "got alias-declaration outside of declaration scope"); 10435 10436 if (Type.isInvalid()) 10437 return nullptr; 10438 10439 bool Invalid = false; 10440 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 10441 TypeSourceInfo *TInfo = nullptr; 10442 GetTypeFromParser(Type.get(), &TInfo); 10443 10444 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 10445 return nullptr; 10446 10447 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 10448 UPPC_DeclarationType)) { 10449 Invalid = true; 10450 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10451 TInfo->getTypeLoc().getBeginLoc()); 10452 } 10453 10454 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10455 TemplateParamLists.size() 10456 ? forRedeclarationInCurContext() 10457 : ForVisibleRedeclaration); 10458 LookupName(Previous, S); 10459 10460 // Warn about shadowing the name of a template parameter. 10461 if (Previous.isSingleResult() && 10462 Previous.getFoundDecl()->isTemplateParameter()) { 10463 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 10464 Previous.clear(); 10465 } 10466 10467 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 10468 "name in alias declaration must be an identifier"); 10469 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 10470 Name.StartLocation, 10471 Name.Identifier, TInfo); 10472 10473 NewTD->setAccess(AS); 10474 10475 if (Invalid) 10476 NewTD->setInvalidDecl(); 10477 10478 ProcessDeclAttributeList(S, NewTD, AttrList); 10479 AddPragmaAttributes(S, NewTD); 10480 10481 CheckTypedefForVariablyModifiedType(S, NewTD); 10482 Invalid |= NewTD->isInvalidDecl(); 10483 10484 bool Redeclaration = false; 10485 10486 NamedDecl *NewND; 10487 if (TemplateParamLists.size()) { 10488 TypeAliasTemplateDecl *OldDecl = nullptr; 10489 TemplateParameterList *OldTemplateParams = nullptr; 10490 10491 if (TemplateParamLists.size() != 1) { 10492 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10493 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10494 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10495 } 10496 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10497 10498 // Check that we can declare a template here. 10499 if (CheckTemplateDeclScope(S, TemplateParams)) 10500 return nullptr; 10501 10502 // Only consider previous declarations in the same scope. 10503 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10504 /*ExplicitInstantiationOrSpecialization*/false); 10505 if (!Previous.empty()) { 10506 Redeclaration = true; 10507 10508 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10509 if (!OldDecl && !Invalid) { 10510 Diag(UsingLoc, diag::err_redefinition_different_kind) 10511 << Name.Identifier; 10512 10513 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10514 if (OldD->getLocation().isValid()) 10515 Diag(OldD->getLocation(), diag::note_previous_definition); 10516 10517 Invalid = true; 10518 } 10519 10520 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10521 if (TemplateParameterListsAreEqual(TemplateParams, 10522 OldDecl->getTemplateParameters(), 10523 /*Complain=*/true, 10524 TPL_TemplateMatch)) 10525 OldTemplateParams = 10526 OldDecl->getMostRecentDecl()->getTemplateParameters(); 10527 else 10528 Invalid = true; 10529 10530 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10531 if (!Invalid && 10532 !Context.hasSameType(OldTD->getUnderlyingType(), 10533 NewTD->getUnderlyingType())) { 10534 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10535 // but we can't reasonably accept it. 10536 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10537 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10538 if (OldTD->getLocation().isValid()) 10539 Diag(OldTD->getLocation(), diag::note_previous_definition); 10540 Invalid = true; 10541 } 10542 } 10543 } 10544 10545 // Merge any previous default template arguments into our parameters, 10546 // and check the parameter list. 10547 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10548 TPC_TypeAliasTemplate)) 10549 return nullptr; 10550 10551 TypeAliasTemplateDecl *NewDecl = 10552 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10553 Name.Identifier, TemplateParams, 10554 NewTD); 10555 NewTD->setDescribedAliasTemplate(NewDecl); 10556 10557 NewDecl->setAccess(AS); 10558 10559 if (Invalid) 10560 NewDecl->setInvalidDecl(); 10561 else if (OldDecl) { 10562 NewDecl->setPreviousDecl(OldDecl); 10563 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 10564 } 10565 10566 NewND = NewDecl; 10567 } else { 10568 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10569 setTagNameForLinkagePurposes(TD, NewTD); 10570 handleTagNumbering(TD, S); 10571 } 10572 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10573 NewND = NewTD; 10574 } 10575 10576 PushOnScopeChains(NewND, S); 10577 ActOnDocumentableDecl(NewND); 10578 return NewND; 10579 } 10580 10581 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10582 SourceLocation AliasLoc, 10583 IdentifierInfo *Alias, CXXScopeSpec &SS, 10584 SourceLocation IdentLoc, 10585 IdentifierInfo *Ident) { 10586 10587 // Lookup the namespace name. 10588 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10589 LookupParsedName(R, S, &SS); 10590 10591 if (R.isAmbiguous()) 10592 return nullptr; 10593 10594 if (R.empty()) { 10595 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10596 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10597 return nullptr; 10598 } 10599 } 10600 assert(!R.isAmbiguous() && !R.empty()); 10601 NamedDecl *ND = R.getRepresentativeDecl(); 10602 10603 // Check if we have a previous declaration with the same name. 10604 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10605 ForVisibleRedeclaration); 10606 LookupName(PrevR, S); 10607 10608 // Check we're not shadowing a template parameter. 10609 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10610 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10611 PrevR.clear(); 10612 } 10613 10614 // Filter out any other lookup result from an enclosing scope. 10615 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10616 /*AllowInlineNamespace*/false); 10617 10618 // Find the previous declaration and check that we can redeclare it. 10619 NamespaceAliasDecl *Prev = nullptr; 10620 if (PrevR.isSingleResult()) { 10621 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10622 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10623 // We already have an alias with the same name that points to the same 10624 // namespace; check that it matches. 10625 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10626 Prev = AD; 10627 } else if (isVisible(PrevDecl)) { 10628 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10629 << Alias; 10630 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10631 << AD->getNamespace(); 10632 return nullptr; 10633 } 10634 } else if (isVisible(PrevDecl)) { 10635 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10636 ? diag::err_redefinition 10637 : diag::err_redefinition_different_kind; 10638 Diag(AliasLoc, DiagID) << Alias; 10639 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10640 return nullptr; 10641 } 10642 } 10643 10644 // The use of a nested name specifier may trigger deprecation warnings. 10645 DiagnoseUseOfDecl(ND, IdentLoc); 10646 10647 NamespaceAliasDecl *AliasDecl = 10648 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10649 Alias, SS.getWithLocInContext(Context), 10650 IdentLoc, ND); 10651 if (Prev) 10652 AliasDecl->setPreviousDecl(Prev); 10653 10654 PushOnScopeChains(AliasDecl, S); 10655 return AliasDecl; 10656 } 10657 10658 namespace { 10659 struct SpecialMemberExceptionSpecInfo 10660 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10661 SourceLocation Loc; 10662 Sema::ImplicitExceptionSpecification ExceptSpec; 10663 10664 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10665 Sema::CXXSpecialMember CSM, 10666 Sema::InheritedConstructorInfo *ICI, 10667 SourceLocation Loc) 10668 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10669 10670 bool visitBase(CXXBaseSpecifier *Base); 10671 bool visitField(FieldDecl *FD); 10672 10673 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10674 unsigned Quals); 10675 10676 void visitSubobjectCall(Subobject Subobj, 10677 Sema::SpecialMemberOverloadResult SMOR); 10678 }; 10679 } 10680 10681 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10682 auto *RT = Base->getType()->getAs<RecordType>(); 10683 if (!RT) 10684 return false; 10685 10686 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10687 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10688 if (auto *BaseCtor = SMOR.getMethod()) { 10689 visitSubobjectCall(Base, BaseCtor); 10690 return false; 10691 } 10692 10693 visitClassSubobject(BaseClass, Base, 0); 10694 return false; 10695 } 10696 10697 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10698 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10699 Expr *E = FD->getInClassInitializer(); 10700 if (!E) 10701 // FIXME: It's a little wasteful to build and throw away a 10702 // CXXDefaultInitExpr here. 10703 // FIXME: We should have a single context note pointing at Loc, and 10704 // this location should be MD->getLocation() instead, since that's 10705 // the location where we actually use the default init expression. 10706 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10707 if (E) 10708 ExceptSpec.CalledExpr(E); 10709 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10710 ->getAs<RecordType>()) { 10711 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10712 FD->getType().getCVRQualifiers()); 10713 } 10714 return false; 10715 } 10716 10717 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10718 Subobject Subobj, 10719 unsigned Quals) { 10720 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10721 bool IsMutable = Field && Field->isMutable(); 10722 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10723 } 10724 10725 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10726 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10727 // Note, if lookup fails, it doesn't matter what exception specification we 10728 // choose because the special member will be deleted. 10729 if (CXXMethodDecl *MD = SMOR.getMethod()) 10730 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10731 } 10732 10733 namespace { 10734 /// RAII object to register a special member as being currently declared. 10735 struct ComputingExceptionSpec { 10736 Sema &S; 10737 10738 ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc) 10739 : S(S) { 10740 Sema::CodeSynthesisContext Ctx; 10741 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 10742 Ctx.PointOfInstantiation = Loc; 10743 Ctx.Entity = MD; 10744 S.pushCodeSynthesisContext(Ctx); 10745 } 10746 ~ComputingExceptionSpec() { 10747 S.popCodeSynthesisContext(); 10748 } 10749 }; 10750 } 10751 10752 static Sema::ImplicitExceptionSpecification 10753 ComputeDefaultedSpecialMemberExceptionSpec( 10754 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 10755 Sema::InheritedConstructorInfo *ICI) { 10756 ComputingExceptionSpec CES(S, MD, Loc); 10757 10758 CXXRecordDecl *ClassDecl = MD->getParent(); 10759 10760 // C++ [except.spec]p14: 10761 // An implicitly declared special member function (Clause 12) shall have an 10762 // exception-specification. [...] 10763 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 10764 if (ClassDecl->isInvalidDecl()) 10765 return Info.ExceptSpec; 10766 10767 // FIXME: If this diagnostic fires, we're probably missing a check for 10768 // attempting to resolve an exception specification before it's known 10769 // at a higher level. 10770 if (S.RequireCompleteType(MD->getLocation(), 10771 S.Context.getRecordType(ClassDecl), 10772 diag::err_exception_spec_incomplete_type)) 10773 return Info.ExceptSpec; 10774 10775 // C++1z [except.spec]p7: 10776 // [Look for exceptions thrown by] a constructor selected [...] to 10777 // initialize a potentially constructed subobject, 10778 // C++1z [except.spec]p8: 10779 // The exception specification for an implicitly-declared destructor, or a 10780 // destructor without a noexcept-specifier, is potentially-throwing if and 10781 // only if any of the destructors for any of its potentially constructed 10782 // subojects is potentially throwing. 10783 // FIXME: We respect the first rule but ignore the "potentially constructed" 10784 // in the second rule to resolve a core issue (no number yet) that would have 10785 // us reject: 10786 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 10787 // struct B : A {}; 10788 // struct C : B { void f(); }; 10789 // ... due to giving B::~B() a non-throwing exception specification. 10790 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 10791 : Info.VisitAllBases); 10792 10793 return Info.ExceptSpec; 10794 } 10795 10796 namespace { 10797 /// RAII object to register a special member as being currently declared. 10798 struct DeclaringSpecialMember { 10799 Sema &S; 10800 Sema::SpecialMemberDecl D; 10801 Sema::ContextRAII SavedContext; 10802 bool WasAlreadyBeingDeclared; 10803 10804 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 10805 : S(S), D(RD, CSM), SavedContext(S, RD) { 10806 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 10807 if (WasAlreadyBeingDeclared) 10808 // This almost never happens, but if it does, ensure that our cache 10809 // doesn't contain a stale result. 10810 S.SpecialMemberCache.clear(); 10811 else { 10812 // Register a note to be produced if we encounter an error while 10813 // declaring the special member. 10814 Sema::CodeSynthesisContext Ctx; 10815 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 10816 // FIXME: We don't have a location to use here. Using the class's 10817 // location maintains the fiction that we declare all special members 10818 // with the class, but (1) it's not clear that lying about that helps our 10819 // users understand what's going on, and (2) there may be outer contexts 10820 // on the stack (some of which are relevant) and printing them exposes 10821 // our lies. 10822 Ctx.PointOfInstantiation = RD->getLocation(); 10823 Ctx.Entity = RD; 10824 Ctx.SpecialMember = CSM; 10825 S.pushCodeSynthesisContext(Ctx); 10826 } 10827 } 10828 ~DeclaringSpecialMember() { 10829 if (!WasAlreadyBeingDeclared) { 10830 S.SpecialMembersBeingDeclared.erase(D); 10831 S.popCodeSynthesisContext(); 10832 } 10833 } 10834 10835 /// Are we already trying to declare this special member? 10836 bool isAlreadyBeingDeclared() const { 10837 return WasAlreadyBeingDeclared; 10838 } 10839 }; 10840 } 10841 10842 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 10843 // Look up any existing declarations, but don't trigger declaration of all 10844 // implicit special members with this name. 10845 DeclarationName Name = FD->getDeclName(); 10846 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 10847 ForExternalRedeclaration); 10848 for (auto *D : FD->getParent()->lookup(Name)) 10849 if (auto *Acceptable = R.getAcceptableDecl(D)) 10850 R.addDecl(Acceptable); 10851 R.resolveKind(); 10852 R.suppressDiagnostics(); 10853 10854 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 10855 } 10856 10857 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 10858 CXXRecordDecl *ClassDecl) { 10859 // C++ [class.ctor]p5: 10860 // A default constructor for a class X is a constructor of class X 10861 // that can be called without an argument. If there is no 10862 // user-declared constructor for class X, a default constructor is 10863 // implicitly declared. An implicitly-declared default constructor 10864 // is an inline public member of its class. 10865 assert(ClassDecl->needsImplicitDefaultConstructor() && 10866 "Should not build implicit default constructor!"); 10867 10868 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 10869 if (DSM.isAlreadyBeingDeclared()) 10870 return nullptr; 10871 10872 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10873 CXXDefaultConstructor, 10874 false); 10875 10876 // Create the actual constructor declaration. 10877 CanQualType ClassType 10878 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10879 SourceLocation ClassLoc = ClassDecl->getLocation(); 10880 DeclarationName Name 10881 = Context.DeclarationNames.getCXXConstructorName(ClassType); 10882 DeclarationNameInfo NameInfo(Name, ClassLoc); 10883 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 10884 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 10885 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 10886 /*isImplicitlyDeclared=*/true, Constexpr); 10887 DefaultCon->setAccess(AS_public); 10888 DefaultCon->setDefaulted(); 10889 10890 if (getLangOpts().CUDA) { 10891 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 10892 DefaultCon, 10893 /* ConstRHS */ false, 10894 /* Diagnose */ false); 10895 } 10896 10897 // Build an exception specification pointing back at this constructor. 10898 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 10899 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10900 10901 // We don't need to use SpecialMemberIsTrivial here; triviality for default 10902 // constructors is easy to compute. 10903 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 10904 10905 // Note that we have declared this constructor. 10906 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 10907 10908 Scope *S = getScopeForContext(ClassDecl); 10909 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 10910 10911 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 10912 SetDeclDeleted(DefaultCon, ClassLoc); 10913 10914 if (S) 10915 PushOnScopeChains(DefaultCon, S, false); 10916 ClassDecl->addDecl(DefaultCon); 10917 10918 return DefaultCon; 10919 } 10920 10921 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 10922 CXXConstructorDecl *Constructor) { 10923 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 10924 !Constructor->doesThisDeclarationHaveABody() && 10925 !Constructor->isDeleted()) && 10926 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 10927 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10928 return; 10929 10930 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10931 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 10932 10933 SynthesizedFunctionScope Scope(*this, Constructor); 10934 10935 // The exception specification is needed because we are defining the 10936 // function. 10937 ResolveExceptionSpec(CurrentLocation, 10938 Constructor->getType()->castAs<FunctionProtoType>()); 10939 MarkVTableUsed(CurrentLocation, ClassDecl); 10940 10941 // Add a context note for diagnostics produced after this point. 10942 Scope.addContextNote(CurrentLocation); 10943 10944 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 10945 Constructor->setInvalidDecl(); 10946 return; 10947 } 10948 10949 SourceLocation Loc = Constructor->getEndLoc().isValid() 10950 ? Constructor->getEndLoc() 10951 : Constructor->getLocation(); 10952 Constructor->setBody(new (Context) CompoundStmt(Loc)); 10953 Constructor->markUsed(Context); 10954 10955 if (ASTMutationListener *L = getASTMutationListener()) { 10956 L->CompletedImplicitDefinition(Constructor); 10957 } 10958 10959 DiagnoseUninitializedFields(*this, Constructor); 10960 } 10961 10962 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 10963 // Perform any delayed checks on exception specifications. 10964 CheckDelayedMemberExceptionSpecs(); 10965 } 10966 10967 /// Find or create the fake constructor we synthesize to model constructing an 10968 /// object of a derived class via a constructor of a base class. 10969 CXXConstructorDecl * 10970 Sema::findInheritingConstructor(SourceLocation Loc, 10971 CXXConstructorDecl *BaseCtor, 10972 ConstructorUsingShadowDecl *Shadow) { 10973 CXXRecordDecl *Derived = Shadow->getParent(); 10974 SourceLocation UsingLoc = Shadow->getLocation(); 10975 10976 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 10977 // For now we use the name of the base class constructor as a member of the 10978 // derived class to indicate a (fake) inherited constructor name. 10979 DeclarationName Name = BaseCtor->getDeclName(); 10980 10981 // Check to see if we already have a fake constructor for this inherited 10982 // constructor call. 10983 for (NamedDecl *Ctor : Derived->lookup(Name)) 10984 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 10985 ->getInheritedConstructor() 10986 .getConstructor(), 10987 BaseCtor)) 10988 return cast<CXXConstructorDecl>(Ctor); 10989 10990 DeclarationNameInfo NameInfo(Name, UsingLoc); 10991 TypeSourceInfo *TInfo = 10992 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 10993 FunctionProtoTypeLoc ProtoLoc = 10994 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 10995 10996 // Check the inherited constructor is valid and find the list of base classes 10997 // from which it was inherited. 10998 InheritedConstructorInfo ICI(*this, Loc, Shadow); 10999 11000 bool Constexpr = 11001 BaseCtor->isConstexpr() && 11002 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 11003 false, BaseCtor, &ICI); 11004 11005 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 11006 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 11007 BaseCtor->isExplicit(), /*Inline=*/true, 11008 /*ImplicitlyDeclared=*/true, Constexpr, 11009 InheritedConstructor(Shadow, BaseCtor)); 11010 if (Shadow->isInvalidDecl()) 11011 DerivedCtor->setInvalidDecl(); 11012 11013 // Build an unevaluated exception specification for this fake constructor. 11014 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 11015 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11016 EPI.ExceptionSpec.Type = EST_Unevaluated; 11017 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 11018 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 11019 FPT->getParamTypes(), EPI)); 11020 11021 // Build the parameter declarations. 11022 SmallVector<ParmVarDecl *, 16> ParamDecls; 11023 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 11024 TypeSourceInfo *TInfo = 11025 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 11026 ParmVarDecl *PD = ParmVarDecl::Create( 11027 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 11028 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 11029 PD->setScopeInfo(0, I); 11030 PD->setImplicit(); 11031 // Ensure attributes are propagated onto parameters (this matters for 11032 // format, pass_object_size, ...). 11033 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 11034 ParamDecls.push_back(PD); 11035 ProtoLoc.setParam(I, PD); 11036 } 11037 11038 // Set up the new constructor. 11039 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 11040 DerivedCtor->setAccess(BaseCtor->getAccess()); 11041 DerivedCtor->setParams(ParamDecls); 11042 Derived->addDecl(DerivedCtor); 11043 11044 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 11045 SetDeclDeleted(DerivedCtor, UsingLoc); 11046 11047 return DerivedCtor; 11048 } 11049 11050 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 11051 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 11052 Ctor->getInheritedConstructor().getShadowDecl()); 11053 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 11054 /*Diagnose*/true); 11055 } 11056 11057 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 11058 CXXConstructorDecl *Constructor) { 11059 CXXRecordDecl *ClassDecl = Constructor->getParent(); 11060 assert(Constructor->getInheritedConstructor() && 11061 !Constructor->doesThisDeclarationHaveABody() && 11062 !Constructor->isDeleted()); 11063 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 11064 return; 11065 11066 // Initializations are performed "as if by a defaulted default constructor", 11067 // so enter the appropriate scope. 11068 SynthesizedFunctionScope Scope(*this, Constructor); 11069 11070 // The exception specification is needed because we are defining the 11071 // function. 11072 ResolveExceptionSpec(CurrentLocation, 11073 Constructor->getType()->castAs<FunctionProtoType>()); 11074 MarkVTableUsed(CurrentLocation, ClassDecl); 11075 11076 // Add a context note for diagnostics produced after this point. 11077 Scope.addContextNote(CurrentLocation); 11078 11079 ConstructorUsingShadowDecl *Shadow = 11080 Constructor->getInheritedConstructor().getShadowDecl(); 11081 CXXConstructorDecl *InheritedCtor = 11082 Constructor->getInheritedConstructor().getConstructor(); 11083 11084 // [class.inhctor.init]p1: 11085 // initialization proceeds as if a defaulted default constructor is used to 11086 // initialize the D object and each base class subobject from which the 11087 // constructor was inherited 11088 11089 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 11090 CXXRecordDecl *RD = Shadow->getParent(); 11091 SourceLocation InitLoc = Shadow->getLocation(); 11092 11093 // Build explicit initializers for all base classes from which the 11094 // constructor was inherited. 11095 SmallVector<CXXCtorInitializer*, 8> Inits; 11096 for (bool VBase : {false, true}) { 11097 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 11098 if (B.isVirtual() != VBase) 11099 continue; 11100 11101 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 11102 if (!BaseRD) 11103 continue; 11104 11105 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 11106 if (!BaseCtor.first) 11107 continue; 11108 11109 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 11110 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 11111 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 11112 11113 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 11114 Inits.push_back(new (Context) CXXCtorInitializer( 11115 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 11116 SourceLocation())); 11117 } 11118 } 11119 11120 // We now proceed as if for a defaulted default constructor, with the relevant 11121 // initializers replaced. 11122 11123 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 11124 Constructor->setInvalidDecl(); 11125 return; 11126 } 11127 11128 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 11129 Constructor->markUsed(Context); 11130 11131 if (ASTMutationListener *L = getASTMutationListener()) { 11132 L->CompletedImplicitDefinition(Constructor); 11133 } 11134 11135 DiagnoseUninitializedFields(*this, Constructor); 11136 } 11137 11138 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 11139 // C++ [class.dtor]p2: 11140 // If a class has no user-declared destructor, a destructor is 11141 // declared implicitly. An implicitly-declared destructor is an 11142 // inline public member of its class. 11143 assert(ClassDecl->needsImplicitDestructor()); 11144 11145 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 11146 if (DSM.isAlreadyBeingDeclared()) 11147 return nullptr; 11148 11149 // Create the actual destructor declaration. 11150 CanQualType ClassType 11151 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 11152 SourceLocation ClassLoc = ClassDecl->getLocation(); 11153 DeclarationName Name 11154 = Context.DeclarationNames.getCXXDestructorName(ClassType); 11155 DeclarationNameInfo NameInfo(Name, ClassLoc); 11156 CXXDestructorDecl *Destructor 11157 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 11158 QualType(), nullptr, /*isInline=*/true, 11159 /*isImplicitlyDeclared=*/true); 11160 Destructor->setAccess(AS_public); 11161 Destructor->setDefaulted(); 11162 11163 if (getLangOpts().CUDA) { 11164 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 11165 Destructor, 11166 /* ConstRHS */ false, 11167 /* Diagnose */ false); 11168 } 11169 11170 // Build an exception specification pointing back at this destructor. 11171 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 11172 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 11173 11174 // We don't need to use SpecialMemberIsTrivial here; triviality for 11175 // destructors is easy to compute. 11176 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 11177 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 11178 ClassDecl->hasTrivialDestructorForCall()); 11179 11180 // Note that we have declared this destructor. 11181 ++ASTContext::NumImplicitDestructorsDeclared; 11182 11183 Scope *S = getScopeForContext(ClassDecl); 11184 CheckImplicitSpecialMemberDeclaration(S, Destructor); 11185 11186 // We can't check whether an implicit destructor is deleted before we complete 11187 // the definition of the class, because its validity depends on the alignment 11188 // of the class. We'll check this from ActOnFields once the class is complete. 11189 if (ClassDecl->isCompleteDefinition() && 11190 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 11191 SetDeclDeleted(Destructor, ClassLoc); 11192 11193 // Introduce this destructor into its scope. 11194 if (S) 11195 PushOnScopeChains(Destructor, S, false); 11196 ClassDecl->addDecl(Destructor); 11197 11198 return Destructor; 11199 } 11200 11201 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 11202 CXXDestructorDecl *Destructor) { 11203 assert((Destructor->isDefaulted() && 11204 !Destructor->doesThisDeclarationHaveABody() && 11205 !Destructor->isDeleted()) && 11206 "DefineImplicitDestructor - call it for implicit default dtor"); 11207 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 11208 return; 11209 11210 CXXRecordDecl *ClassDecl = Destructor->getParent(); 11211 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 11212 11213 SynthesizedFunctionScope Scope(*this, Destructor); 11214 11215 // The exception specification is needed because we are defining the 11216 // function. 11217 ResolveExceptionSpec(CurrentLocation, 11218 Destructor->getType()->castAs<FunctionProtoType>()); 11219 MarkVTableUsed(CurrentLocation, ClassDecl); 11220 11221 // Add a context note for diagnostics produced after this point. 11222 Scope.addContextNote(CurrentLocation); 11223 11224 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11225 Destructor->getParent()); 11226 11227 if (CheckDestructor(Destructor)) { 11228 Destructor->setInvalidDecl(); 11229 return; 11230 } 11231 11232 SourceLocation Loc = Destructor->getEndLoc().isValid() 11233 ? Destructor->getEndLoc() 11234 : Destructor->getLocation(); 11235 Destructor->setBody(new (Context) CompoundStmt(Loc)); 11236 Destructor->markUsed(Context); 11237 11238 if (ASTMutationListener *L = getASTMutationListener()) { 11239 L->CompletedImplicitDefinition(Destructor); 11240 } 11241 } 11242 11243 /// Perform any semantic analysis which needs to be delayed until all 11244 /// pending class member declarations have been parsed. 11245 void Sema::ActOnFinishCXXMemberDecls() { 11246 // If the context is an invalid C++ class, just suppress these checks. 11247 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 11248 if (Record->isInvalidDecl()) { 11249 DelayedOverridingExceptionSpecChecks.clear(); 11250 DelayedEquivalentExceptionSpecChecks.clear(); 11251 DelayedDefaultedMemberExceptionSpecs.clear(); 11252 return; 11253 } 11254 checkForMultipleExportedDefaultConstructors(*this, Record); 11255 } 11256 } 11257 11258 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 11259 referenceDLLExportedClassMethods(); 11260 } 11261 11262 void Sema::referenceDLLExportedClassMethods() { 11263 if (!DelayedDllExportClasses.empty()) { 11264 // Calling ReferenceDllExportedMembers might cause the current function to 11265 // be called again, so use a local copy of DelayedDllExportClasses. 11266 SmallVector<CXXRecordDecl *, 4> WorkList; 11267 std::swap(DelayedDllExportClasses, WorkList); 11268 for (CXXRecordDecl *Class : WorkList) 11269 ReferenceDllExportedMembers(*this, Class); 11270 } 11271 } 11272 11273 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 11274 assert(getLangOpts().CPlusPlus11 && 11275 "adjusting dtor exception specs was introduced in c++11"); 11276 11277 if (Destructor->isDependentContext()) 11278 return; 11279 11280 // C++11 [class.dtor]p3: 11281 // A declaration of a destructor that does not have an exception- 11282 // specification is implicitly considered to have the same exception- 11283 // specification as an implicit declaration. 11284 const FunctionProtoType *DtorType = Destructor->getType()-> 11285 getAs<FunctionProtoType>(); 11286 if (DtorType->hasExceptionSpec()) 11287 return; 11288 11289 // Replace the destructor's type, building off the existing one. Fortunately, 11290 // the only thing of interest in the destructor type is its extended info. 11291 // The return and arguments are fixed. 11292 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 11293 EPI.ExceptionSpec.Type = EST_Unevaluated; 11294 EPI.ExceptionSpec.SourceDecl = Destructor; 11295 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 11296 11297 // FIXME: If the destructor has a body that could throw, and the newly created 11298 // spec doesn't allow exceptions, we should emit a warning, because this 11299 // change in behavior can break conforming C++03 programs at runtime. 11300 // However, we don't have a body or an exception specification yet, so it 11301 // needs to be done somewhere else. 11302 } 11303 11304 namespace { 11305 /// An abstract base class for all helper classes used in building the 11306 // copy/move operators. These classes serve as factory functions and help us 11307 // avoid using the same Expr* in the AST twice. 11308 class ExprBuilder { 11309 ExprBuilder(const ExprBuilder&) = delete; 11310 ExprBuilder &operator=(const ExprBuilder&) = delete; 11311 11312 protected: 11313 static Expr *assertNotNull(Expr *E) { 11314 assert(E && "Expression construction must not fail."); 11315 return E; 11316 } 11317 11318 public: 11319 ExprBuilder() {} 11320 virtual ~ExprBuilder() {} 11321 11322 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 11323 }; 11324 11325 class RefBuilder: public ExprBuilder { 11326 VarDecl *Var; 11327 QualType VarType; 11328 11329 public: 11330 Expr *build(Sema &S, SourceLocation Loc) const override { 11331 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 11332 } 11333 11334 RefBuilder(VarDecl *Var, QualType VarType) 11335 : Var(Var), VarType(VarType) {} 11336 }; 11337 11338 class ThisBuilder: public ExprBuilder { 11339 public: 11340 Expr *build(Sema &S, SourceLocation Loc) const override { 11341 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 11342 } 11343 }; 11344 11345 class CastBuilder: public ExprBuilder { 11346 const ExprBuilder &Builder; 11347 QualType Type; 11348 ExprValueKind Kind; 11349 const CXXCastPath &Path; 11350 11351 public: 11352 Expr *build(Sema &S, SourceLocation Loc) const override { 11353 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 11354 CK_UncheckedDerivedToBase, Kind, 11355 &Path).get()); 11356 } 11357 11358 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 11359 const CXXCastPath &Path) 11360 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 11361 }; 11362 11363 class DerefBuilder: public ExprBuilder { 11364 const ExprBuilder &Builder; 11365 11366 public: 11367 Expr *build(Sema &S, SourceLocation Loc) const override { 11368 return assertNotNull( 11369 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 11370 } 11371 11372 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11373 }; 11374 11375 class MemberBuilder: public ExprBuilder { 11376 const ExprBuilder &Builder; 11377 QualType Type; 11378 CXXScopeSpec SS; 11379 bool IsArrow; 11380 LookupResult &MemberLookup; 11381 11382 public: 11383 Expr *build(Sema &S, SourceLocation Loc) const override { 11384 return assertNotNull(S.BuildMemberReferenceExpr( 11385 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 11386 nullptr, MemberLookup, nullptr, nullptr).get()); 11387 } 11388 11389 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 11390 LookupResult &MemberLookup) 11391 : Builder(Builder), Type(Type), IsArrow(IsArrow), 11392 MemberLookup(MemberLookup) {} 11393 }; 11394 11395 class MoveCastBuilder: public ExprBuilder { 11396 const ExprBuilder &Builder; 11397 11398 public: 11399 Expr *build(Sema &S, SourceLocation Loc) const override { 11400 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 11401 } 11402 11403 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11404 }; 11405 11406 class LvalueConvBuilder: public ExprBuilder { 11407 const ExprBuilder &Builder; 11408 11409 public: 11410 Expr *build(Sema &S, SourceLocation Loc) const override { 11411 return assertNotNull( 11412 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 11413 } 11414 11415 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11416 }; 11417 11418 class SubscriptBuilder: public ExprBuilder { 11419 const ExprBuilder &Base; 11420 const ExprBuilder &Index; 11421 11422 public: 11423 Expr *build(Sema &S, SourceLocation Loc) const override { 11424 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 11425 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 11426 } 11427 11428 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 11429 : Base(Base), Index(Index) {} 11430 }; 11431 11432 } // end anonymous namespace 11433 11434 /// When generating a defaulted copy or move assignment operator, if a field 11435 /// should be copied with __builtin_memcpy rather than via explicit assignments, 11436 /// do so. This optimization only applies for arrays of scalars, and for arrays 11437 /// of class type where the selected copy/move-assignment operator is trivial. 11438 static StmtResult 11439 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 11440 const ExprBuilder &ToB, const ExprBuilder &FromB) { 11441 // Compute the size of the memory buffer to be copied. 11442 QualType SizeType = S.Context.getSizeType(); 11443 llvm::APInt Size(S.Context.getTypeSize(SizeType), 11444 S.Context.getTypeSizeInChars(T).getQuantity()); 11445 11446 // Take the address of the field references for "from" and "to". We 11447 // directly construct UnaryOperators here because semantic analysis 11448 // does not permit us to take the address of an xvalue. 11449 Expr *From = FromB.build(S, Loc); 11450 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 11451 S.Context.getPointerType(From->getType()), 11452 VK_RValue, OK_Ordinary, Loc, false); 11453 Expr *To = ToB.build(S, Loc); 11454 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 11455 S.Context.getPointerType(To->getType()), 11456 VK_RValue, OK_Ordinary, Loc, false); 11457 11458 const Type *E = T->getBaseElementTypeUnsafe(); 11459 bool NeedsCollectableMemCpy = 11460 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 11461 11462 // Create a reference to the __builtin_objc_memmove_collectable function 11463 StringRef MemCpyName = NeedsCollectableMemCpy ? 11464 "__builtin_objc_memmove_collectable" : 11465 "__builtin_memcpy"; 11466 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 11467 Sema::LookupOrdinaryName); 11468 S.LookupName(R, S.TUScope, true); 11469 11470 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 11471 if (!MemCpy) 11472 // Something went horribly wrong earlier, and we will have complained 11473 // about it. 11474 return StmtError(); 11475 11476 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 11477 VK_RValue, Loc, nullptr); 11478 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 11479 11480 Expr *CallArgs[] = { 11481 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 11482 }; 11483 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 11484 Loc, CallArgs, Loc); 11485 11486 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 11487 return Call.getAs<Stmt>(); 11488 } 11489 11490 /// Builds a statement that copies/moves the given entity from \p From to 11491 /// \c To. 11492 /// 11493 /// This routine is used to copy/move the members of a class with an 11494 /// implicitly-declared copy/move assignment operator. When the entities being 11495 /// copied are arrays, this routine builds for loops to copy them. 11496 /// 11497 /// \param S The Sema object used for type-checking. 11498 /// 11499 /// \param Loc The location where the implicit copy/move is being generated. 11500 /// 11501 /// \param T The type of the expressions being copied/moved. Both expressions 11502 /// must have this type. 11503 /// 11504 /// \param To The expression we are copying/moving to. 11505 /// 11506 /// \param From The expression we are copying/moving from. 11507 /// 11508 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 11509 /// Otherwise, it's a non-static member subobject. 11510 /// 11511 /// \param Copying Whether we're copying or moving. 11512 /// 11513 /// \param Depth Internal parameter recording the depth of the recursion. 11514 /// 11515 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11516 /// if a memcpy should be used instead. 11517 static StmtResult 11518 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11519 const ExprBuilder &To, const ExprBuilder &From, 11520 bool CopyingBaseSubobject, bool Copying, 11521 unsigned Depth = 0) { 11522 // C++11 [class.copy]p28: 11523 // Each subobject is assigned in the manner appropriate to its type: 11524 // 11525 // - if the subobject is of class type, as if by a call to operator= with 11526 // the subobject as the object expression and the corresponding 11527 // subobject of x as a single function argument (as if by explicit 11528 // qualification; that is, ignoring any possible virtual overriding 11529 // functions in more derived classes); 11530 // 11531 // C++03 [class.copy]p13: 11532 // - if the subobject is of class type, the copy assignment operator for 11533 // the class is used (as if by explicit qualification; that is, 11534 // ignoring any possible virtual overriding functions in more derived 11535 // classes); 11536 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11537 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11538 11539 // Look for operator=. 11540 DeclarationName Name 11541 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11542 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11543 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11544 11545 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11546 // operator. 11547 if (!S.getLangOpts().CPlusPlus11) { 11548 LookupResult::Filter F = OpLookup.makeFilter(); 11549 while (F.hasNext()) { 11550 NamedDecl *D = F.next(); 11551 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11552 if (Method->isCopyAssignmentOperator() || 11553 (!Copying && Method->isMoveAssignmentOperator())) 11554 continue; 11555 11556 F.erase(); 11557 } 11558 F.done(); 11559 } 11560 11561 // Suppress the protected check (C++ [class.protected]) for each of the 11562 // assignment operators we found. This strange dance is required when 11563 // we're assigning via a base classes's copy-assignment operator. To 11564 // ensure that we're getting the right base class subobject (without 11565 // ambiguities), we need to cast "this" to that subobject type; to 11566 // ensure that we don't go through the virtual call mechanism, we need 11567 // to qualify the operator= name with the base class (see below). However, 11568 // this means that if the base class has a protected copy assignment 11569 // operator, the protected member access check will fail. So, we 11570 // rewrite "protected" access to "public" access in this case, since we 11571 // know by construction that we're calling from a derived class. 11572 if (CopyingBaseSubobject) { 11573 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11574 L != LEnd; ++L) { 11575 if (L.getAccess() == AS_protected) 11576 L.setAccess(AS_public); 11577 } 11578 } 11579 11580 // Create the nested-name-specifier that will be used to qualify the 11581 // reference to operator=; this is required to suppress the virtual 11582 // call mechanism. 11583 CXXScopeSpec SS; 11584 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11585 SS.MakeTrivial(S.Context, 11586 NestedNameSpecifier::Create(S.Context, nullptr, false, 11587 CanonicalT), 11588 Loc); 11589 11590 // Create the reference to operator=. 11591 ExprResult OpEqualRef 11592 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 11593 SS, /*TemplateKWLoc=*/SourceLocation(), 11594 /*FirstQualifierInScope=*/nullptr, 11595 OpLookup, 11596 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11597 /*SuppressQualifierCheck=*/true); 11598 if (OpEqualRef.isInvalid()) 11599 return StmtError(); 11600 11601 // Build the call to the assignment operator. 11602 11603 Expr *FromInst = From.build(S, Loc); 11604 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11605 OpEqualRef.getAs<Expr>(), 11606 Loc, FromInst, Loc); 11607 if (Call.isInvalid()) 11608 return StmtError(); 11609 11610 // If we built a call to a trivial 'operator=' while copying an array, 11611 // bail out. We'll replace the whole shebang with a memcpy. 11612 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11613 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11614 return StmtResult((Stmt*)nullptr); 11615 11616 // Convert to an expression-statement, and clean up any produced 11617 // temporaries. 11618 return S.ActOnExprStmt(Call); 11619 } 11620 11621 // - if the subobject is of scalar type, the built-in assignment 11622 // operator is used. 11623 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11624 if (!ArrayTy) { 11625 ExprResult Assignment = S.CreateBuiltinBinOp( 11626 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11627 if (Assignment.isInvalid()) 11628 return StmtError(); 11629 return S.ActOnExprStmt(Assignment); 11630 } 11631 11632 // - if the subobject is an array, each element is assigned, in the 11633 // manner appropriate to the element type; 11634 11635 // Construct a loop over the array bounds, e.g., 11636 // 11637 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11638 // 11639 // that will copy each of the array elements. 11640 QualType SizeType = S.Context.getSizeType(); 11641 11642 // Create the iteration variable. 11643 IdentifierInfo *IterationVarName = nullptr; 11644 { 11645 SmallString<8> Str; 11646 llvm::raw_svector_ostream OS(Str); 11647 OS << "__i" << Depth; 11648 IterationVarName = &S.Context.Idents.get(OS.str()); 11649 } 11650 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11651 IterationVarName, SizeType, 11652 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11653 SC_None); 11654 11655 // Initialize the iteration variable to zero. 11656 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11657 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11658 11659 // Creates a reference to the iteration variable. 11660 RefBuilder IterationVarRef(IterationVar, SizeType); 11661 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11662 11663 // Create the DeclStmt that holds the iteration variable. 11664 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11665 11666 // Subscript the "from" and "to" expressions with the iteration variable. 11667 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11668 MoveCastBuilder FromIndexMove(FromIndexCopy); 11669 const ExprBuilder *FromIndex; 11670 if (Copying) 11671 FromIndex = &FromIndexCopy; 11672 else 11673 FromIndex = &FromIndexMove; 11674 11675 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11676 11677 // Build the copy/move for an individual element of the array. 11678 StmtResult Copy = 11679 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11680 ToIndex, *FromIndex, CopyingBaseSubobject, 11681 Copying, Depth + 1); 11682 // Bail out if copying fails or if we determined that we should use memcpy. 11683 if (Copy.isInvalid() || !Copy.get()) 11684 return Copy; 11685 11686 // Create the comparison against the array bound. 11687 llvm::APInt Upper 11688 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11689 Expr *Comparison 11690 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11691 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11692 BO_NE, S.Context.BoolTy, 11693 VK_RValue, OK_Ordinary, Loc, FPOptions()); 11694 11695 // Create the pre-increment of the iteration variable. We can determine 11696 // whether the increment will overflow based on the value of the array 11697 // bound. 11698 Expr *Increment = new (S.Context) 11699 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, 11700 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); 11701 11702 // Construct the loop that copies all elements of this array. 11703 return S.ActOnForStmt( 11704 Loc, Loc, InitStmt, 11705 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 11706 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 11707 } 11708 11709 static StmtResult 11710 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 11711 const ExprBuilder &To, const ExprBuilder &From, 11712 bool CopyingBaseSubobject, bool Copying) { 11713 // Maybe we should use a memcpy? 11714 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 11715 T.isTriviallyCopyableType(S.Context)) 11716 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11717 11718 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 11719 CopyingBaseSubobject, 11720 Copying, 0)); 11721 11722 // If we ended up picking a trivial assignment operator for an array of a 11723 // non-trivially-copyable class type, just emit a memcpy. 11724 if (!Result.isInvalid() && !Result.get()) 11725 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11726 11727 return Result; 11728 } 11729 11730 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 11731 // Note: The following rules are largely analoguous to the copy 11732 // constructor rules. Note that virtual bases are not taken into account 11733 // for determining the argument type of the operator. Note also that 11734 // operators taking an object instead of a reference are allowed. 11735 assert(ClassDecl->needsImplicitCopyAssignment()); 11736 11737 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 11738 if (DSM.isAlreadyBeingDeclared()) 11739 return nullptr; 11740 11741 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11742 QualType RetType = Context.getLValueReferenceType(ArgType); 11743 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 11744 if (Const) 11745 ArgType = ArgType.withConst(); 11746 ArgType = Context.getLValueReferenceType(ArgType); 11747 11748 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11749 CXXCopyAssignment, 11750 Const); 11751 11752 // An implicitly-declared copy assignment operator is an inline public 11753 // member of its class. 11754 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11755 SourceLocation ClassLoc = ClassDecl->getLocation(); 11756 DeclarationNameInfo NameInfo(Name, ClassLoc); 11757 CXXMethodDecl *CopyAssignment = 11758 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11759 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11760 /*isInline=*/true, Constexpr, SourceLocation()); 11761 CopyAssignment->setAccess(AS_public); 11762 CopyAssignment->setDefaulted(); 11763 CopyAssignment->setImplicit(); 11764 11765 if (getLangOpts().CUDA) { 11766 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 11767 CopyAssignment, 11768 /* ConstRHS */ Const, 11769 /* Diagnose */ false); 11770 } 11771 11772 // Build an exception specification pointing back at this member. 11773 FunctionProtoType::ExtProtoInfo EPI = 11774 getImplicitMethodEPI(*this, CopyAssignment); 11775 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11776 11777 // Add the parameter to the operator. 11778 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 11779 ClassLoc, ClassLoc, 11780 /*Id=*/nullptr, ArgType, 11781 /*TInfo=*/nullptr, SC_None, 11782 nullptr); 11783 CopyAssignment->setParams(FromParam); 11784 11785 CopyAssignment->setTrivial( 11786 ClassDecl->needsOverloadResolutionForCopyAssignment() 11787 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 11788 : ClassDecl->hasTrivialCopyAssignment()); 11789 11790 // Note that we have added this copy-assignment operator. 11791 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 11792 11793 Scope *S = getScopeForContext(ClassDecl); 11794 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 11795 11796 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 11797 SetDeclDeleted(CopyAssignment, ClassLoc); 11798 11799 if (S) 11800 PushOnScopeChains(CopyAssignment, S, false); 11801 ClassDecl->addDecl(CopyAssignment); 11802 11803 return CopyAssignment; 11804 } 11805 11806 /// Diagnose an implicit copy operation for a class which is odr-used, but 11807 /// which is deprecated because the class has a user-declared copy constructor, 11808 /// copy assignment operator, or destructor. 11809 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 11810 assert(CopyOp->isImplicit()); 11811 11812 CXXRecordDecl *RD = CopyOp->getParent(); 11813 CXXMethodDecl *UserDeclaredOperation = nullptr; 11814 11815 // In Microsoft mode, assignment operations don't affect constructors and 11816 // vice versa. 11817 if (RD->hasUserDeclaredDestructor()) { 11818 UserDeclaredOperation = RD->getDestructor(); 11819 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11820 RD->hasUserDeclaredCopyConstructor() && 11821 !S.getLangOpts().MSVCCompat) { 11822 // Find any user-declared copy constructor. 11823 for (auto *I : RD->ctors()) { 11824 if (I->isCopyConstructor()) { 11825 UserDeclaredOperation = I; 11826 break; 11827 } 11828 } 11829 assert(UserDeclaredOperation); 11830 } else if (isa<CXXConstructorDecl>(CopyOp) && 11831 RD->hasUserDeclaredCopyAssignment() && 11832 !S.getLangOpts().MSVCCompat) { 11833 // Find any user-declared move assignment operator. 11834 for (auto *I : RD->methods()) { 11835 if (I->isCopyAssignmentOperator()) { 11836 UserDeclaredOperation = I; 11837 break; 11838 } 11839 } 11840 assert(UserDeclaredOperation); 11841 } 11842 11843 if (UserDeclaredOperation) { 11844 S.Diag(UserDeclaredOperation->getLocation(), 11845 diag::warn_deprecated_copy_operation) 11846 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11847 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11848 } 11849 } 11850 11851 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11852 CXXMethodDecl *CopyAssignOperator) { 11853 assert((CopyAssignOperator->isDefaulted() && 11854 CopyAssignOperator->isOverloadedOperator() && 11855 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11856 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11857 !CopyAssignOperator->isDeleted()) && 11858 "DefineImplicitCopyAssignment called for wrong function"); 11859 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 11860 return; 11861 11862 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11863 if (ClassDecl->isInvalidDecl()) { 11864 CopyAssignOperator->setInvalidDecl(); 11865 return; 11866 } 11867 11868 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11869 11870 // The exception specification is needed because we are defining the 11871 // function. 11872 ResolveExceptionSpec(CurrentLocation, 11873 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11874 11875 // Add a context note for diagnostics produced after this point. 11876 Scope.addContextNote(CurrentLocation); 11877 11878 // C++11 [class.copy]p18: 11879 // The [definition of an implicitly declared copy assignment operator] is 11880 // deprecated if the class has a user-declared copy constructor or a 11881 // user-declared destructor. 11882 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11883 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 11884 11885 // C++0x [class.copy]p30: 11886 // The implicitly-defined or explicitly-defaulted copy assignment operator 11887 // for a non-union class X performs memberwise copy assignment of its 11888 // subobjects. The direct base classes of X are assigned first, in the 11889 // order of their declaration in the base-specifier-list, and then the 11890 // immediate non-static data members of X are assigned, in the order in 11891 // which they were declared in the class definition. 11892 11893 // The statements that form the synthesized function body. 11894 SmallVector<Stmt*, 8> Statements; 11895 11896 // The parameter for the "other" object, which we are copying from. 11897 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 11898 Qualifiers OtherQuals = Other->getType().getQualifiers(); 11899 QualType OtherRefType = Other->getType(); 11900 if (const LValueReferenceType *OtherRef 11901 = OtherRefType->getAs<LValueReferenceType>()) { 11902 OtherRefType = OtherRef->getPointeeType(); 11903 OtherQuals = OtherRefType.getQualifiers(); 11904 } 11905 11906 // Our location for everything implicitly-generated. 11907 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 11908 ? CopyAssignOperator->getEndLoc() 11909 : CopyAssignOperator->getLocation(); 11910 11911 // Builds a DeclRefExpr for the "other" object. 11912 RefBuilder OtherRef(Other, OtherRefType); 11913 11914 // Builds the "this" pointer. 11915 ThisBuilder This; 11916 11917 // Assign base classes. 11918 bool Invalid = false; 11919 for (auto &Base : ClassDecl->bases()) { 11920 // Form the assignment: 11921 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 11922 QualType BaseType = Base.getType().getUnqualifiedType(); 11923 if (!BaseType->isRecordType()) { 11924 Invalid = true; 11925 continue; 11926 } 11927 11928 CXXCastPath BasePath; 11929 BasePath.push_back(&Base); 11930 11931 // Construct the "from" expression, which is an implicit cast to the 11932 // appropriately-qualified base type. 11933 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 11934 VK_LValue, BasePath); 11935 11936 // Dereference "this". 11937 DerefBuilder DerefThis(This); 11938 CastBuilder To(DerefThis, 11939 Context.getCVRQualifiedType( 11940 BaseType, CopyAssignOperator->getTypeQualifiers()), 11941 VK_LValue, BasePath); 11942 11943 // Build the copy. 11944 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 11945 To, From, 11946 /*CopyingBaseSubobject=*/true, 11947 /*Copying=*/true); 11948 if (Copy.isInvalid()) { 11949 CopyAssignOperator->setInvalidDecl(); 11950 return; 11951 } 11952 11953 // Success! Record the copy. 11954 Statements.push_back(Copy.getAs<Expr>()); 11955 } 11956 11957 // Assign non-static members. 11958 for (auto *Field : ClassDecl->fields()) { 11959 // FIXME: We should form some kind of AST representation for the implied 11960 // memcpy in a union copy operation. 11961 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11962 continue; 11963 11964 if (Field->isInvalidDecl()) { 11965 Invalid = true; 11966 continue; 11967 } 11968 11969 // Check for members of reference type; we can't copy those. 11970 if (Field->getType()->isReferenceType()) { 11971 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11972 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11973 Diag(Field->getLocation(), diag::note_declared_at); 11974 Invalid = true; 11975 continue; 11976 } 11977 11978 // Check for members of const-qualified, non-class type. 11979 QualType BaseType = Context.getBaseElementType(Field->getType()); 11980 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11981 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11982 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11983 Diag(Field->getLocation(), diag::note_declared_at); 11984 Invalid = true; 11985 continue; 11986 } 11987 11988 // Suppress assigning zero-width bitfields. 11989 if (Field->isZeroLengthBitField(Context)) 11990 continue; 11991 11992 QualType FieldType = Field->getType().getNonReferenceType(); 11993 if (FieldType->isIncompleteArrayType()) { 11994 assert(ClassDecl->hasFlexibleArrayMember() && 11995 "Incomplete array type is not valid"); 11996 continue; 11997 } 11998 11999 // Build references to the field in the object we're copying from and to. 12000 CXXScopeSpec SS; // Intentionally empty 12001 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12002 LookupMemberName); 12003 MemberLookup.addDecl(Field); 12004 MemberLookup.resolveKind(); 12005 12006 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 12007 12008 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 12009 12010 // Build the copy of this field. 12011 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 12012 To, From, 12013 /*CopyingBaseSubobject=*/false, 12014 /*Copying=*/true); 12015 if (Copy.isInvalid()) { 12016 CopyAssignOperator->setInvalidDecl(); 12017 return; 12018 } 12019 12020 // Success! Record the copy. 12021 Statements.push_back(Copy.getAs<Stmt>()); 12022 } 12023 12024 if (!Invalid) { 12025 // Add a "return *this;" 12026 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12027 12028 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12029 if (Return.isInvalid()) 12030 Invalid = true; 12031 else 12032 Statements.push_back(Return.getAs<Stmt>()); 12033 } 12034 12035 if (Invalid) { 12036 CopyAssignOperator->setInvalidDecl(); 12037 return; 12038 } 12039 12040 StmtResult Body; 12041 { 12042 CompoundScopeRAII CompoundScope(*this); 12043 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12044 /*isStmtExpr=*/false); 12045 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12046 } 12047 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 12048 CopyAssignOperator->markUsed(Context); 12049 12050 if (ASTMutationListener *L = getASTMutationListener()) { 12051 L->CompletedImplicitDefinition(CopyAssignOperator); 12052 } 12053 } 12054 12055 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 12056 assert(ClassDecl->needsImplicitMoveAssignment()); 12057 12058 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 12059 if (DSM.isAlreadyBeingDeclared()) 12060 return nullptr; 12061 12062 // Note: The following rules are largely analoguous to the move 12063 // constructor rules. 12064 12065 QualType ArgType = Context.getTypeDeclType(ClassDecl); 12066 QualType RetType = Context.getLValueReferenceType(ArgType); 12067 ArgType = Context.getRValueReferenceType(ArgType); 12068 12069 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12070 CXXMoveAssignment, 12071 false); 12072 12073 // An implicitly-declared move assignment operator is an inline public 12074 // member of its class. 12075 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 12076 SourceLocation ClassLoc = ClassDecl->getLocation(); 12077 DeclarationNameInfo NameInfo(Name, ClassLoc); 12078 CXXMethodDecl *MoveAssignment = 12079 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 12080 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 12081 /*isInline=*/true, Constexpr, SourceLocation()); 12082 MoveAssignment->setAccess(AS_public); 12083 MoveAssignment->setDefaulted(); 12084 MoveAssignment->setImplicit(); 12085 12086 if (getLangOpts().CUDA) { 12087 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 12088 MoveAssignment, 12089 /* ConstRHS */ false, 12090 /* Diagnose */ false); 12091 } 12092 12093 // Build an exception specification pointing back at this member. 12094 FunctionProtoType::ExtProtoInfo EPI = 12095 getImplicitMethodEPI(*this, MoveAssignment); 12096 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 12097 12098 // Add the parameter to the operator. 12099 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 12100 ClassLoc, ClassLoc, 12101 /*Id=*/nullptr, ArgType, 12102 /*TInfo=*/nullptr, SC_None, 12103 nullptr); 12104 MoveAssignment->setParams(FromParam); 12105 12106 MoveAssignment->setTrivial( 12107 ClassDecl->needsOverloadResolutionForMoveAssignment() 12108 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 12109 : ClassDecl->hasTrivialMoveAssignment()); 12110 12111 // Note that we have added this copy-assignment operator. 12112 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 12113 12114 Scope *S = getScopeForContext(ClassDecl); 12115 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 12116 12117 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 12118 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 12119 SetDeclDeleted(MoveAssignment, ClassLoc); 12120 } 12121 12122 if (S) 12123 PushOnScopeChains(MoveAssignment, S, false); 12124 ClassDecl->addDecl(MoveAssignment); 12125 12126 return MoveAssignment; 12127 } 12128 12129 /// Check if we're implicitly defining a move assignment operator for a class 12130 /// with virtual bases. Such a move assignment might move-assign the virtual 12131 /// base multiple times. 12132 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 12133 SourceLocation CurrentLocation) { 12134 assert(!Class->isDependentContext() && "should not define dependent move"); 12135 12136 // Only a virtual base could get implicitly move-assigned multiple times. 12137 // Only a non-trivial move assignment can observe this. We only want to 12138 // diagnose if we implicitly define an assignment operator that assigns 12139 // two base classes, both of which move-assign the same virtual base. 12140 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 12141 Class->getNumBases() < 2) 12142 return; 12143 12144 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 12145 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 12146 VBaseMap VBases; 12147 12148 for (auto &BI : Class->bases()) { 12149 Worklist.push_back(&BI); 12150 while (!Worklist.empty()) { 12151 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 12152 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 12153 12154 // If the base has no non-trivial move assignment operators, 12155 // we don't care about moves from it. 12156 if (!Base->hasNonTrivialMoveAssignment()) 12157 continue; 12158 12159 // If there's nothing virtual here, skip it. 12160 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 12161 continue; 12162 12163 // If we're not actually going to call a move assignment for this base, 12164 // or the selected move assignment is trivial, skip it. 12165 Sema::SpecialMemberOverloadResult SMOR = 12166 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 12167 /*ConstArg*/false, /*VolatileArg*/false, 12168 /*RValueThis*/true, /*ConstThis*/false, 12169 /*VolatileThis*/false); 12170 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 12171 !SMOR.getMethod()->isMoveAssignmentOperator()) 12172 continue; 12173 12174 if (BaseSpec->isVirtual()) { 12175 // We're going to move-assign this virtual base, and its move 12176 // assignment operator is not trivial. If this can happen for 12177 // multiple distinct direct bases of Class, diagnose it. (If it 12178 // only happens in one base, we'll diagnose it when synthesizing 12179 // that base class's move assignment operator.) 12180 CXXBaseSpecifier *&Existing = 12181 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 12182 .first->second; 12183 if (Existing && Existing != &BI) { 12184 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 12185 << Class << Base; 12186 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 12187 << (Base->getCanonicalDecl() == 12188 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12189 << Base << Existing->getType() << Existing->getSourceRange(); 12190 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 12191 << (Base->getCanonicalDecl() == 12192 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12193 << Base << BI.getType() << BaseSpec->getSourceRange(); 12194 12195 // Only diagnose each vbase once. 12196 Existing = nullptr; 12197 } 12198 } else { 12199 // Only walk over bases that have defaulted move assignment operators. 12200 // We assume that any user-provided move assignment operator handles 12201 // the multiple-moves-of-vbase case itself somehow. 12202 if (!SMOR.getMethod()->isDefaulted()) 12203 continue; 12204 12205 // We're going to move the base classes of Base. Add them to the list. 12206 for (auto &BI : Base->bases()) 12207 Worklist.push_back(&BI); 12208 } 12209 } 12210 } 12211 } 12212 12213 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 12214 CXXMethodDecl *MoveAssignOperator) { 12215 assert((MoveAssignOperator->isDefaulted() && 12216 MoveAssignOperator->isOverloadedOperator() && 12217 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 12218 !MoveAssignOperator->doesThisDeclarationHaveABody() && 12219 !MoveAssignOperator->isDeleted()) && 12220 "DefineImplicitMoveAssignment called for wrong function"); 12221 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 12222 return; 12223 12224 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 12225 if (ClassDecl->isInvalidDecl()) { 12226 MoveAssignOperator->setInvalidDecl(); 12227 return; 12228 } 12229 12230 // C++0x [class.copy]p28: 12231 // The implicitly-defined or move assignment operator for a non-union class 12232 // X performs memberwise move assignment of its subobjects. The direct base 12233 // classes of X are assigned first, in the order of their declaration in the 12234 // base-specifier-list, and then the immediate non-static data members of X 12235 // are assigned, in the order in which they were declared in the class 12236 // definition. 12237 12238 // Issue a warning if our implicit move assignment operator will move 12239 // from a virtual base more than once. 12240 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 12241 12242 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 12243 12244 // The exception specification is needed because we are defining the 12245 // function. 12246 ResolveExceptionSpec(CurrentLocation, 12247 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 12248 12249 // Add a context note for diagnostics produced after this point. 12250 Scope.addContextNote(CurrentLocation); 12251 12252 // The statements that form the synthesized function body. 12253 SmallVector<Stmt*, 8> Statements; 12254 12255 // The parameter for the "other" object, which we are move from. 12256 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 12257 QualType OtherRefType = Other->getType()-> 12258 getAs<RValueReferenceType>()->getPointeeType(); 12259 assert(!OtherRefType.getQualifiers() && 12260 "Bad argument type of defaulted move assignment"); 12261 12262 // Our location for everything implicitly-generated. 12263 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 12264 ? MoveAssignOperator->getEndLoc() 12265 : MoveAssignOperator->getLocation(); 12266 12267 // Builds a reference to the "other" object. 12268 RefBuilder OtherRef(Other, OtherRefType); 12269 // Cast to rvalue. 12270 MoveCastBuilder MoveOther(OtherRef); 12271 12272 // Builds the "this" pointer. 12273 ThisBuilder This; 12274 12275 // Assign base classes. 12276 bool Invalid = false; 12277 for (auto &Base : ClassDecl->bases()) { 12278 // C++11 [class.copy]p28: 12279 // It is unspecified whether subobjects representing virtual base classes 12280 // are assigned more than once by the implicitly-defined copy assignment 12281 // operator. 12282 // FIXME: Do not assign to a vbase that will be assigned by some other base 12283 // class. For a move-assignment, this can result in the vbase being moved 12284 // multiple times. 12285 12286 // Form the assignment: 12287 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 12288 QualType BaseType = Base.getType().getUnqualifiedType(); 12289 if (!BaseType->isRecordType()) { 12290 Invalid = true; 12291 continue; 12292 } 12293 12294 CXXCastPath BasePath; 12295 BasePath.push_back(&Base); 12296 12297 // Construct the "from" expression, which is an implicit cast to the 12298 // appropriately-qualified base type. 12299 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 12300 12301 // Dereference "this". 12302 DerefBuilder DerefThis(This); 12303 12304 // Implicitly cast "this" to the appropriately-qualified base type. 12305 CastBuilder To(DerefThis, 12306 Context.getCVRQualifiedType( 12307 BaseType, MoveAssignOperator->getTypeQualifiers()), 12308 VK_LValue, BasePath); 12309 12310 // Build the move. 12311 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 12312 To, From, 12313 /*CopyingBaseSubobject=*/true, 12314 /*Copying=*/false); 12315 if (Move.isInvalid()) { 12316 MoveAssignOperator->setInvalidDecl(); 12317 return; 12318 } 12319 12320 // Success! Record the move. 12321 Statements.push_back(Move.getAs<Expr>()); 12322 } 12323 12324 // Assign non-static members. 12325 for (auto *Field : ClassDecl->fields()) { 12326 // FIXME: We should form some kind of AST representation for the implied 12327 // memcpy in a union copy operation. 12328 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12329 continue; 12330 12331 if (Field->isInvalidDecl()) { 12332 Invalid = true; 12333 continue; 12334 } 12335 12336 // Check for members of reference type; we can't move those. 12337 if (Field->getType()->isReferenceType()) { 12338 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12339 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12340 Diag(Field->getLocation(), diag::note_declared_at); 12341 Invalid = true; 12342 continue; 12343 } 12344 12345 // Check for members of const-qualified, non-class type. 12346 QualType BaseType = Context.getBaseElementType(Field->getType()); 12347 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12348 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12349 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12350 Diag(Field->getLocation(), diag::note_declared_at); 12351 Invalid = true; 12352 continue; 12353 } 12354 12355 // Suppress assigning zero-width bitfields. 12356 if (Field->isZeroLengthBitField(Context)) 12357 continue; 12358 12359 QualType FieldType = Field->getType().getNonReferenceType(); 12360 if (FieldType->isIncompleteArrayType()) { 12361 assert(ClassDecl->hasFlexibleArrayMember() && 12362 "Incomplete array type is not valid"); 12363 continue; 12364 } 12365 12366 // Build references to the field in the object we're copying from and to. 12367 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12368 LookupMemberName); 12369 MemberLookup.addDecl(Field); 12370 MemberLookup.resolveKind(); 12371 MemberBuilder From(MoveOther, OtherRefType, 12372 /*IsArrow=*/false, MemberLookup); 12373 MemberBuilder To(This, getCurrentThisType(), 12374 /*IsArrow=*/true, MemberLookup); 12375 12376 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 12377 "Member reference with rvalue base must be rvalue except for reference " 12378 "members, which aren't allowed for move assignment."); 12379 12380 // Build the move of this field. 12381 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 12382 To, From, 12383 /*CopyingBaseSubobject=*/false, 12384 /*Copying=*/false); 12385 if (Move.isInvalid()) { 12386 MoveAssignOperator->setInvalidDecl(); 12387 return; 12388 } 12389 12390 // Success! Record the copy. 12391 Statements.push_back(Move.getAs<Stmt>()); 12392 } 12393 12394 if (!Invalid) { 12395 // Add a "return *this;" 12396 ExprResult ThisObj = 12397 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12398 12399 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12400 if (Return.isInvalid()) 12401 Invalid = true; 12402 else 12403 Statements.push_back(Return.getAs<Stmt>()); 12404 } 12405 12406 if (Invalid) { 12407 MoveAssignOperator->setInvalidDecl(); 12408 return; 12409 } 12410 12411 StmtResult Body; 12412 { 12413 CompoundScopeRAII CompoundScope(*this); 12414 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12415 /*isStmtExpr=*/false); 12416 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12417 } 12418 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 12419 MoveAssignOperator->markUsed(Context); 12420 12421 if (ASTMutationListener *L = getASTMutationListener()) { 12422 L->CompletedImplicitDefinition(MoveAssignOperator); 12423 } 12424 } 12425 12426 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 12427 CXXRecordDecl *ClassDecl) { 12428 // C++ [class.copy]p4: 12429 // If the class definition does not explicitly declare a copy 12430 // constructor, one is declared implicitly. 12431 assert(ClassDecl->needsImplicitCopyConstructor()); 12432 12433 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 12434 if (DSM.isAlreadyBeingDeclared()) 12435 return nullptr; 12436 12437 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12438 QualType ArgType = ClassType; 12439 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 12440 if (Const) 12441 ArgType = ArgType.withConst(); 12442 ArgType = Context.getLValueReferenceType(ArgType); 12443 12444 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12445 CXXCopyConstructor, 12446 Const); 12447 12448 DeclarationName Name 12449 = Context.DeclarationNames.getCXXConstructorName( 12450 Context.getCanonicalType(ClassType)); 12451 SourceLocation ClassLoc = ClassDecl->getLocation(); 12452 DeclarationNameInfo NameInfo(Name, ClassLoc); 12453 12454 // An implicitly-declared copy constructor is an inline public 12455 // member of its class. 12456 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 12457 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12458 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12459 Constexpr); 12460 CopyConstructor->setAccess(AS_public); 12461 CopyConstructor->setDefaulted(); 12462 12463 if (getLangOpts().CUDA) { 12464 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 12465 CopyConstructor, 12466 /* ConstRHS */ Const, 12467 /* Diagnose */ false); 12468 } 12469 12470 // Build an exception specification pointing back at this member. 12471 FunctionProtoType::ExtProtoInfo EPI = 12472 getImplicitMethodEPI(*this, CopyConstructor); 12473 CopyConstructor->setType( 12474 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12475 12476 // Add the parameter to the constructor. 12477 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 12478 ClassLoc, ClassLoc, 12479 /*IdentifierInfo=*/nullptr, 12480 ArgType, /*TInfo=*/nullptr, 12481 SC_None, nullptr); 12482 CopyConstructor->setParams(FromParam); 12483 12484 CopyConstructor->setTrivial( 12485 ClassDecl->needsOverloadResolutionForCopyConstructor() 12486 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 12487 : ClassDecl->hasTrivialCopyConstructor()); 12488 12489 CopyConstructor->setTrivialForCall( 12490 ClassDecl->hasAttr<TrivialABIAttr>() || 12491 (ClassDecl->needsOverloadResolutionForCopyConstructor() 12492 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 12493 TAH_ConsiderTrivialABI) 12494 : ClassDecl->hasTrivialCopyConstructorForCall())); 12495 12496 // Note that we have declared this constructor. 12497 ++ASTContext::NumImplicitCopyConstructorsDeclared; 12498 12499 Scope *S = getScopeForContext(ClassDecl); 12500 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 12501 12502 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 12503 ClassDecl->setImplicitCopyConstructorIsDeleted(); 12504 SetDeclDeleted(CopyConstructor, ClassLoc); 12505 } 12506 12507 if (S) 12508 PushOnScopeChains(CopyConstructor, S, false); 12509 ClassDecl->addDecl(CopyConstructor); 12510 12511 return CopyConstructor; 12512 } 12513 12514 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 12515 CXXConstructorDecl *CopyConstructor) { 12516 assert((CopyConstructor->isDefaulted() && 12517 CopyConstructor->isCopyConstructor() && 12518 !CopyConstructor->doesThisDeclarationHaveABody() && 12519 !CopyConstructor->isDeleted()) && 12520 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12521 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12522 return; 12523 12524 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12525 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12526 12527 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12528 12529 // The exception specification is needed because we are defining the 12530 // function. 12531 ResolveExceptionSpec(CurrentLocation, 12532 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12533 MarkVTableUsed(CurrentLocation, ClassDecl); 12534 12535 // Add a context note for diagnostics produced after this point. 12536 Scope.addContextNote(CurrentLocation); 12537 12538 // C++11 [class.copy]p7: 12539 // The [definition of an implicitly declared copy constructor] is 12540 // deprecated if the class has a user-declared copy assignment operator 12541 // or a user-declared destructor. 12542 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12543 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12544 12545 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12546 CopyConstructor->setInvalidDecl(); 12547 } else { 12548 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 12549 ? CopyConstructor->getEndLoc() 12550 : CopyConstructor->getLocation(); 12551 Sema::CompoundScopeRAII CompoundScope(*this); 12552 CopyConstructor->setBody( 12553 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12554 CopyConstructor->markUsed(Context); 12555 } 12556 12557 if (ASTMutationListener *L = getASTMutationListener()) { 12558 L->CompletedImplicitDefinition(CopyConstructor); 12559 } 12560 } 12561 12562 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12563 CXXRecordDecl *ClassDecl) { 12564 assert(ClassDecl->needsImplicitMoveConstructor()); 12565 12566 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12567 if (DSM.isAlreadyBeingDeclared()) 12568 return nullptr; 12569 12570 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12571 QualType ArgType = Context.getRValueReferenceType(ClassType); 12572 12573 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12574 CXXMoveConstructor, 12575 false); 12576 12577 DeclarationName Name 12578 = Context.DeclarationNames.getCXXConstructorName( 12579 Context.getCanonicalType(ClassType)); 12580 SourceLocation ClassLoc = ClassDecl->getLocation(); 12581 DeclarationNameInfo NameInfo(Name, ClassLoc); 12582 12583 // C++11 [class.copy]p11: 12584 // An implicitly-declared copy/move constructor is an inline public 12585 // member of its class. 12586 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12587 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12588 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12589 Constexpr); 12590 MoveConstructor->setAccess(AS_public); 12591 MoveConstructor->setDefaulted(); 12592 12593 if (getLangOpts().CUDA) { 12594 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12595 MoveConstructor, 12596 /* ConstRHS */ false, 12597 /* Diagnose */ false); 12598 } 12599 12600 // Build an exception specification pointing back at this member. 12601 FunctionProtoType::ExtProtoInfo EPI = 12602 getImplicitMethodEPI(*this, MoveConstructor); 12603 MoveConstructor->setType( 12604 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12605 12606 // Add the parameter to the constructor. 12607 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12608 ClassLoc, ClassLoc, 12609 /*IdentifierInfo=*/nullptr, 12610 ArgType, /*TInfo=*/nullptr, 12611 SC_None, nullptr); 12612 MoveConstructor->setParams(FromParam); 12613 12614 MoveConstructor->setTrivial( 12615 ClassDecl->needsOverloadResolutionForMoveConstructor() 12616 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12617 : ClassDecl->hasTrivialMoveConstructor()); 12618 12619 MoveConstructor->setTrivialForCall( 12620 ClassDecl->hasAttr<TrivialABIAttr>() || 12621 (ClassDecl->needsOverloadResolutionForMoveConstructor() 12622 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 12623 TAH_ConsiderTrivialABI) 12624 : ClassDecl->hasTrivialMoveConstructorForCall())); 12625 12626 // Note that we have declared this constructor. 12627 ++ASTContext::NumImplicitMoveConstructorsDeclared; 12628 12629 Scope *S = getScopeForContext(ClassDecl); 12630 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12631 12632 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12633 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12634 SetDeclDeleted(MoveConstructor, ClassLoc); 12635 } 12636 12637 if (S) 12638 PushOnScopeChains(MoveConstructor, S, false); 12639 ClassDecl->addDecl(MoveConstructor); 12640 12641 return MoveConstructor; 12642 } 12643 12644 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12645 CXXConstructorDecl *MoveConstructor) { 12646 assert((MoveConstructor->isDefaulted() && 12647 MoveConstructor->isMoveConstructor() && 12648 !MoveConstructor->doesThisDeclarationHaveABody() && 12649 !MoveConstructor->isDeleted()) && 12650 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12651 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12652 return; 12653 12654 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12655 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12656 12657 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12658 12659 // The exception specification is needed because we are defining the 12660 // function. 12661 ResolveExceptionSpec(CurrentLocation, 12662 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12663 MarkVTableUsed(CurrentLocation, ClassDecl); 12664 12665 // Add a context note for diagnostics produced after this point. 12666 Scope.addContextNote(CurrentLocation); 12667 12668 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12669 MoveConstructor->setInvalidDecl(); 12670 } else { 12671 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 12672 ? MoveConstructor->getEndLoc() 12673 : MoveConstructor->getLocation(); 12674 Sema::CompoundScopeRAII CompoundScope(*this); 12675 MoveConstructor->setBody(ActOnCompoundStmt( 12676 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12677 MoveConstructor->markUsed(Context); 12678 } 12679 12680 if (ASTMutationListener *L = getASTMutationListener()) { 12681 L->CompletedImplicitDefinition(MoveConstructor); 12682 } 12683 } 12684 12685 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12686 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12687 } 12688 12689 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12690 SourceLocation CurrentLocation, 12691 CXXConversionDecl *Conv) { 12692 SynthesizedFunctionScope Scope(*this, Conv); 12693 assert(!Conv->getReturnType()->isUndeducedType()); 12694 12695 CXXRecordDecl *Lambda = Conv->getParent(); 12696 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 12697 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12698 12699 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 12700 CallOp = InstantiateFunctionDeclaration( 12701 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12702 if (!CallOp) 12703 return; 12704 12705 Invoker = InstantiateFunctionDeclaration( 12706 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 12707 if (!Invoker) 12708 return; 12709 } 12710 12711 if (CallOp->isInvalidDecl()) 12712 return; 12713 12714 // Mark the call operator referenced (and add to pending instantiations 12715 // if necessary). 12716 // For both the conversion and static-invoker template specializations 12717 // we construct their body's in this function, so no need to add them 12718 // to the PendingInstantiations. 12719 MarkFunctionReferenced(CurrentLocation, CallOp); 12720 12721 // Fill in the __invoke function with a dummy implementation. IR generation 12722 // will fill in the actual details. Update its type in case it contained 12723 // an 'auto'. 12724 Invoker->markUsed(Context); 12725 Invoker->setReferenced(); 12726 Invoker->setType(Conv->getReturnType()->getPointeeType()); 12727 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12728 12729 // Construct the body of the conversion function { return __invoke; }. 12730 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12731 VK_LValue, Conv->getLocation()).get(); 12732 assert(FunctionRef && "Can't refer to __invoke function?"); 12733 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12734 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 12735 Conv->getLocation())); 12736 Conv->markUsed(Context); 12737 Conv->setReferenced(); 12738 12739 if (ASTMutationListener *L = getASTMutationListener()) { 12740 L->CompletedImplicitDefinition(Conv); 12741 L->CompletedImplicitDefinition(Invoker); 12742 } 12743 } 12744 12745 12746 12747 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12748 SourceLocation CurrentLocation, 12749 CXXConversionDecl *Conv) 12750 { 12751 assert(!Conv->getParent()->isGenericLambda()); 12752 12753 SynthesizedFunctionScope Scope(*this, Conv); 12754 12755 // Copy-initialize the lambda object as needed to capture it. 12756 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12757 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12758 12759 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12760 Conv->getLocation(), 12761 Conv, DerefThis); 12762 12763 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12764 // behavior. Note that only the general conversion function does this 12765 // (since it's unusable otherwise); in the case where we inline the 12766 // block literal, it has block literal lifetime semantics. 12767 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12768 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12769 CK_CopyAndAutoreleaseBlockObject, 12770 BuildBlock.get(), nullptr, VK_RValue); 12771 12772 if (BuildBlock.isInvalid()) { 12773 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12774 Conv->setInvalidDecl(); 12775 return; 12776 } 12777 12778 // Create the return statement that returns the block from the conversion 12779 // function. 12780 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12781 if (Return.isInvalid()) { 12782 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12783 Conv->setInvalidDecl(); 12784 return; 12785 } 12786 12787 // Set the body of the conversion function. 12788 Stmt *ReturnS = Return.get(); 12789 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 12790 Conv->getLocation())); 12791 Conv->markUsed(Context); 12792 12793 // We're done; notify the mutation listener, if any. 12794 if (ASTMutationListener *L = getASTMutationListener()) { 12795 L->CompletedImplicitDefinition(Conv); 12796 } 12797 } 12798 12799 /// Determine whether the given list arguments contains exactly one 12800 /// "real" (non-default) argument. 12801 static bool hasOneRealArgument(MultiExprArg Args) { 12802 switch (Args.size()) { 12803 case 0: 12804 return false; 12805 12806 default: 12807 if (!Args[1]->isDefaultArgument()) 12808 return false; 12809 12810 LLVM_FALLTHROUGH; 12811 case 1: 12812 return !Args[0]->isDefaultArgument(); 12813 } 12814 12815 return false; 12816 } 12817 12818 ExprResult 12819 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12820 NamedDecl *FoundDecl, 12821 CXXConstructorDecl *Constructor, 12822 MultiExprArg ExprArgs, 12823 bool HadMultipleCandidates, 12824 bool IsListInitialization, 12825 bool IsStdInitListInitialization, 12826 bool RequiresZeroInit, 12827 unsigned ConstructKind, 12828 SourceRange ParenRange) { 12829 bool Elidable = false; 12830 12831 // C++0x [class.copy]p34: 12832 // When certain criteria are met, an implementation is allowed to 12833 // omit the copy/move construction of a class object, even if the 12834 // copy/move constructor and/or destructor for the object have 12835 // side effects. [...] 12836 // - when a temporary class object that has not been bound to a 12837 // reference (12.2) would be copied/moved to a class object 12838 // with the same cv-unqualified type, the copy/move operation 12839 // can be omitted by constructing the temporary object 12840 // directly into the target of the omitted copy/move 12841 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12842 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12843 Expr *SubExpr = ExprArgs[0]; 12844 Elidable = SubExpr->isTemporaryObject( 12845 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12846 } 12847 12848 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12849 FoundDecl, Constructor, 12850 Elidable, ExprArgs, HadMultipleCandidates, 12851 IsListInitialization, 12852 IsStdInitListInitialization, RequiresZeroInit, 12853 ConstructKind, ParenRange); 12854 } 12855 12856 ExprResult 12857 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12858 NamedDecl *FoundDecl, 12859 CXXConstructorDecl *Constructor, 12860 bool Elidable, 12861 MultiExprArg ExprArgs, 12862 bool HadMultipleCandidates, 12863 bool IsListInitialization, 12864 bool IsStdInitListInitialization, 12865 bool RequiresZeroInit, 12866 unsigned ConstructKind, 12867 SourceRange ParenRange) { 12868 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12869 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12870 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12871 return ExprError(); 12872 } 12873 12874 return BuildCXXConstructExpr( 12875 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12876 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12877 RequiresZeroInit, ConstructKind, ParenRange); 12878 } 12879 12880 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12881 /// including handling of its default argument expressions. 12882 ExprResult 12883 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12884 CXXConstructorDecl *Constructor, 12885 bool Elidable, 12886 MultiExprArg ExprArgs, 12887 bool HadMultipleCandidates, 12888 bool IsListInitialization, 12889 bool IsStdInitListInitialization, 12890 bool RequiresZeroInit, 12891 unsigned ConstructKind, 12892 SourceRange ParenRange) { 12893 assert(declaresSameEntity( 12894 Constructor->getParent(), 12895 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 12896 "given constructor for wrong type"); 12897 MarkFunctionReferenced(ConstructLoc, Constructor); 12898 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 12899 return ExprError(); 12900 12901 return CXXConstructExpr::Create( 12902 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 12903 ExprArgs, HadMultipleCandidates, IsListInitialization, 12904 IsStdInitListInitialization, RequiresZeroInit, 12905 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 12906 ParenRange); 12907 } 12908 12909 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 12910 assert(Field->hasInClassInitializer()); 12911 12912 // If we already have the in-class initializer nothing needs to be done. 12913 if (Field->getInClassInitializer()) 12914 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12915 12916 // If we might have already tried and failed to instantiate, don't try again. 12917 if (Field->isInvalidDecl()) 12918 return ExprError(); 12919 12920 // Maybe we haven't instantiated the in-class initializer. Go check the 12921 // pattern FieldDecl to see if it has one. 12922 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 12923 12924 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 12925 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 12926 DeclContext::lookup_result Lookup = 12927 ClassPattern->lookup(Field->getDeclName()); 12928 12929 // Lookup can return at most two results: the pattern for the field, or the 12930 // injected class name of the parent record. No other member can have the 12931 // same name as the field. 12932 // In modules mode, lookup can return multiple results (coming from 12933 // different modules). 12934 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 12935 "more than two lookup results for field name"); 12936 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 12937 if (!Pattern) { 12938 assert(isa<CXXRecordDecl>(Lookup[0]) && 12939 "cannot have other non-field member with same name"); 12940 for (auto L : Lookup) 12941 if (isa<FieldDecl>(L)) { 12942 Pattern = cast<FieldDecl>(L); 12943 break; 12944 } 12945 assert(Pattern && "We must have set the Pattern!"); 12946 } 12947 12948 if (!Pattern->hasInClassInitializer() || 12949 InstantiateInClassInitializer(Loc, Field, Pattern, 12950 getTemplateInstantiationArgs(Field))) { 12951 // Don't diagnose this again. 12952 Field->setInvalidDecl(); 12953 return ExprError(); 12954 } 12955 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12956 } 12957 12958 // DR1351: 12959 // If the brace-or-equal-initializer of a non-static data member 12960 // invokes a defaulted default constructor of its class or of an 12961 // enclosing class in a potentially evaluated subexpression, the 12962 // program is ill-formed. 12963 // 12964 // This resolution is unworkable: the exception specification of the 12965 // default constructor can be needed in an unevaluated context, in 12966 // particular, in the operand of a noexcept-expression, and we can be 12967 // unable to compute an exception specification for an enclosed class. 12968 // 12969 // Any attempt to resolve the exception specification of a defaulted default 12970 // constructor before the initializer is lexically complete will ultimately 12971 // come here at which point we can diagnose it. 12972 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 12973 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 12974 << OutermostClass << Field; 12975 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); 12976 // Recover by marking the field invalid, unless we're in a SFINAE context. 12977 if (!isSFINAEContext()) 12978 Field->setInvalidDecl(); 12979 return ExprError(); 12980 } 12981 12982 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 12983 if (VD->isInvalidDecl()) return; 12984 12985 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 12986 if (ClassDecl->isInvalidDecl()) return; 12987 if (ClassDecl->hasIrrelevantDestructor()) return; 12988 if (ClassDecl->isDependentContext()) return; 12989 12990 if (VD->isNoDestroy(getASTContext())) 12991 return; 12992 12993 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12994 MarkFunctionReferenced(VD->getLocation(), Destructor); 12995 CheckDestructorAccess(VD->getLocation(), Destructor, 12996 PDiag(diag::err_access_dtor_var) 12997 << VD->getDeclName() 12998 << VD->getType()); 12999 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 13000 13001 if (Destructor->isTrivial()) return; 13002 if (!VD->hasGlobalStorage()) return; 13003 13004 // Emit warning for non-trivial dtor in global scope (a real global, 13005 // class-static, function-static). 13006 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 13007 13008 // TODO: this should be re-enabled for static locals by !CXAAtExit 13009 if (!VD->isStaticLocal()) 13010 Diag(VD->getLocation(), diag::warn_global_destructor); 13011 } 13012 13013 /// Given a constructor and the set of arguments provided for the 13014 /// constructor, convert the arguments and add any required default arguments 13015 /// to form a proper call to this constructor. 13016 /// 13017 /// \returns true if an error occurred, false otherwise. 13018 bool 13019 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 13020 MultiExprArg ArgsPtr, 13021 SourceLocation Loc, 13022 SmallVectorImpl<Expr*> &ConvertedArgs, 13023 bool AllowExplicit, 13024 bool IsListInitialization) { 13025 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 13026 unsigned NumArgs = ArgsPtr.size(); 13027 Expr **Args = ArgsPtr.data(); 13028 13029 const FunctionProtoType *Proto 13030 = Constructor->getType()->getAs<FunctionProtoType>(); 13031 assert(Proto && "Constructor without a prototype?"); 13032 unsigned NumParams = Proto->getNumParams(); 13033 13034 // If too few arguments are available, we'll fill in the rest with defaults. 13035 if (NumArgs < NumParams) 13036 ConvertedArgs.reserve(NumParams); 13037 else 13038 ConvertedArgs.reserve(NumArgs); 13039 13040 VariadicCallType CallType = 13041 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 13042 SmallVector<Expr *, 8> AllArgs; 13043 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 13044 Proto, 0, 13045 llvm::makeArrayRef(Args, NumArgs), 13046 AllArgs, 13047 CallType, AllowExplicit, 13048 IsListInitialization); 13049 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 13050 13051 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 13052 13053 CheckConstructorCall(Constructor, 13054 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 13055 Proto, Loc); 13056 13057 return Invalid; 13058 } 13059 13060 static inline bool 13061 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 13062 const FunctionDecl *FnDecl) { 13063 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 13064 if (isa<NamespaceDecl>(DC)) { 13065 return SemaRef.Diag(FnDecl->getLocation(), 13066 diag::err_operator_new_delete_declared_in_namespace) 13067 << FnDecl->getDeclName(); 13068 } 13069 13070 if (isa<TranslationUnitDecl>(DC) && 13071 FnDecl->getStorageClass() == SC_Static) { 13072 return SemaRef.Diag(FnDecl->getLocation(), 13073 diag::err_operator_new_delete_declared_static) 13074 << FnDecl->getDeclName(); 13075 } 13076 13077 return false; 13078 } 13079 13080 static QualType 13081 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 13082 QualType QTy = PtrTy->getPointeeType(); 13083 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 13084 return SemaRef.Context.getPointerType(QTy); 13085 } 13086 13087 static inline bool 13088 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 13089 CanQualType ExpectedResultType, 13090 CanQualType ExpectedFirstParamType, 13091 unsigned DependentParamTypeDiag, 13092 unsigned InvalidParamTypeDiag) { 13093 QualType ResultType = 13094 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 13095 13096 // Check that the result type is not dependent. 13097 if (ResultType->isDependentType()) 13098 return SemaRef.Diag(FnDecl->getLocation(), 13099 diag::err_operator_new_delete_dependent_result_type) 13100 << FnDecl->getDeclName() << ExpectedResultType; 13101 13102 // OpenCL C++: the operator is valid on any address space. 13103 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13104 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 13105 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13106 } 13107 } 13108 13109 // Check that the result type is what we expect. 13110 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 13111 return SemaRef.Diag(FnDecl->getLocation(), 13112 diag::err_operator_new_delete_invalid_result_type) 13113 << FnDecl->getDeclName() << ExpectedResultType; 13114 13115 // A function template must have at least 2 parameters. 13116 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 13117 return SemaRef.Diag(FnDecl->getLocation(), 13118 diag::err_operator_new_delete_template_too_few_parameters) 13119 << FnDecl->getDeclName(); 13120 13121 // The function decl must have at least 1 parameter. 13122 if (FnDecl->getNumParams() == 0) 13123 return SemaRef.Diag(FnDecl->getLocation(), 13124 diag::err_operator_new_delete_too_few_parameters) 13125 << FnDecl->getDeclName(); 13126 13127 // Check the first parameter type is not dependent. 13128 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 13129 if (FirstParamType->isDependentType()) 13130 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 13131 << FnDecl->getDeclName() << ExpectedFirstParamType; 13132 13133 // Check that the first parameter type is what we expect. 13134 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13135 // OpenCL C++: the operator is valid on any address space. 13136 if (auto *PtrTy = 13137 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 13138 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13139 } 13140 } 13141 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 13142 ExpectedFirstParamType) 13143 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 13144 << FnDecl->getDeclName() << ExpectedFirstParamType; 13145 13146 return false; 13147 } 13148 13149 static bool 13150 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 13151 // C++ [basic.stc.dynamic.allocation]p1: 13152 // A program is ill-formed if an allocation function is declared in a 13153 // namespace scope other than global scope or declared static in global 13154 // scope. 13155 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13156 return true; 13157 13158 CanQualType SizeTy = 13159 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 13160 13161 // C++ [basic.stc.dynamic.allocation]p1: 13162 // The return type shall be void*. The first parameter shall have type 13163 // std::size_t. 13164 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 13165 SizeTy, 13166 diag::err_operator_new_dependent_param_type, 13167 diag::err_operator_new_param_type)) 13168 return true; 13169 13170 // C++ [basic.stc.dynamic.allocation]p1: 13171 // The first parameter shall not have an associated default argument. 13172 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 13173 return SemaRef.Diag(FnDecl->getLocation(), 13174 diag::err_operator_new_default_arg) 13175 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 13176 13177 return false; 13178 } 13179 13180 static bool 13181 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 13182 // C++ [basic.stc.dynamic.deallocation]p1: 13183 // A program is ill-formed if deallocation functions are declared in a 13184 // namespace scope other than global scope or declared static in global 13185 // scope. 13186 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13187 return true; 13188 13189 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 13190 13191 // C++ P0722: 13192 // Within a class C, the first parameter of a destroying operator delete 13193 // shall be of type C *. The first parameter of any other deallocation 13194 // function shall be of type void *. 13195 CanQualType ExpectedFirstParamType = 13196 MD && MD->isDestroyingOperatorDelete() 13197 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 13198 SemaRef.Context.getRecordType(MD->getParent()))) 13199 : SemaRef.Context.VoidPtrTy; 13200 13201 // C++ [basic.stc.dynamic.deallocation]p2: 13202 // Each deallocation function shall return void 13203 if (CheckOperatorNewDeleteTypes( 13204 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 13205 diag::err_operator_delete_dependent_param_type, 13206 diag::err_operator_delete_param_type)) 13207 return true; 13208 13209 // C++ P0722: 13210 // A destroying operator delete shall be a usual deallocation function. 13211 if (MD && !MD->getParent()->isDependentContext() && 13212 MD->isDestroyingOperatorDelete() && 13213 !SemaRef.isUsualDeallocationFunction(MD)) { 13214 SemaRef.Diag(MD->getLocation(), 13215 diag::err_destroying_operator_delete_not_usual); 13216 return true; 13217 } 13218 13219 return false; 13220 } 13221 13222 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 13223 /// of this overloaded operator is well-formed. If so, returns false; 13224 /// otherwise, emits appropriate diagnostics and returns true. 13225 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 13226 assert(FnDecl && FnDecl->isOverloadedOperator() && 13227 "Expected an overloaded operator declaration"); 13228 13229 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 13230 13231 // C++ [over.oper]p5: 13232 // The allocation and deallocation functions, operator new, 13233 // operator new[], operator delete and operator delete[], are 13234 // described completely in 3.7.3. The attributes and restrictions 13235 // found in the rest of this subclause do not apply to them unless 13236 // explicitly stated in 3.7.3. 13237 if (Op == OO_Delete || Op == OO_Array_Delete) 13238 return CheckOperatorDeleteDeclaration(*this, FnDecl); 13239 13240 if (Op == OO_New || Op == OO_Array_New) 13241 return CheckOperatorNewDeclaration(*this, FnDecl); 13242 13243 // C++ [over.oper]p6: 13244 // An operator function shall either be a non-static member 13245 // function or be a non-member function and have at least one 13246 // parameter whose type is a class, a reference to a class, an 13247 // enumeration, or a reference to an enumeration. 13248 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 13249 if (MethodDecl->isStatic()) 13250 return Diag(FnDecl->getLocation(), 13251 diag::err_operator_overload_static) << FnDecl->getDeclName(); 13252 } else { 13253 bool ClassOrEnumParam = false; 13254 for (auto Param : FnDecl->parameters()) { 13255 QualType ParamType = Param->getType().getNonReferenceType(); 13256 if (ParamType->isDependentType() || ParamType->isRecordType() || 13257 ParamType->isEnumeralType()) { 13258 ClassOrEnumParam = true; 13259 break; 13260 } 13261 } 13262 13263 if (!ClassOrEnumParam) 13264 return Diag(FnDecl->getLocation(), 13265 diag::err_operator_overload_needs_class_or_enum) 13266 << FnDecl->getDeclName(); 13267 } 13268 13269 // C++ [over.oper]p8: 13270 // An operator function cannot have default arguments (8.3.6), 13271 // except where explicitly stated below. 13272 // 13273 // Only the function-call operator allows default arguments 13274 // (C++ [over.call]p1). 13275 if (Op != OO_Call) { 13276 for (auto Param : FnDecl->parameters()) { 13277 if (Param->hasDefaultArg()) 13278 return Diag(Param->getLocation(), 13279 diag::err_operator_overload_default_arg) 13280 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 13281 } 13282 } 13283 13284 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 13285 { false, false, false } 13286 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 13287 , { Unary, Binary, MemberOnly } 13288 #include "clang/Basic/OperatorKinds.def" 13289 }; 13290 13291 bool CanBeUnaryOperator = OperatorUses[Op][0]; 13292 bool CanBeBinaryOperator = OperatorUses[Op][1]; 13293 bool MustBeMemberOperator = OperatorUses[Op][2]; 13294 13295 // C++ [over.oper]p8: 13296 // [...] Operator functions cannot have more or fewer parameters 13297 // than the number required for the corresponding operator, as 13298 // described in the rest of this subclause. 13299 unsigned NumParams = FnDecl->getNumParams() 13300 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 13301 if (Op != OO_Call && 13302 ((NumParams == 1 && !CanBeUnaryOperator) || 13303 (NumParams == 2 && !CanBeBinaryOperator) || 13304 (NumParams < 1) || (NumParams > 2))) { 13305 // We have the wrong number of parameters. 13306 unsigned ErrorKind; 13307 if (CanBeUnaryOperator && CanBeBinaryOperator) { 13308 ErrorKind = 2; // 2 -> unary or binary. 13309 } else if (CanBeUnaryOperator) { 13310 ErrorKind = 0; // 0 -> unary 13311 } else { 13312 assert(CanBeBinaryOperator && 13313 "All non-call overloaded operators are unary or binary!"); 13314 ErrorKind = 1; // 1 -> binary 13315 } 13316 13317 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 13318 << FnDecl->getDeclName() << NumParams << ErrorKind; 13319 } 13320 13321 // Overloaded operators other than operator() cannot be variadic. 13322 if (Op != OO_Call && 13323 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 13324 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 13325 << FnDecl->getDeclName(); 13326 } 13327 13328 // Some operators must be non-static member functions. 13329 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 13330 return Diag(FnDecl->getLocation(), 13331 diag::err_operator_overload_must_be_member) 13332 << FnDecl->getDeclName(); 13333 } 13334 13335 // C++ [over.inc]p1: 13336 // The user-defined function called operator++ implements the 13337 // prefix and postfix ++ operator. If this function is a member 13338 // function with no parameters, or a non-member function with one 13339 // parameter of class or enumeration type, it defines the prefix 13340 // increment operator ++ for objects of that type. If the function 13341 // is a member function with one parameter (which shall be of type 13342 // int) or a non-member function with two parameters (the second 13343 // of which shall be of type int), it defines the postfix 13344 // increment operator ++ for objects of that type. 13345 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 13346 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 13347 QualType ParamType = LastParam->getType(); 13348 13349 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 13350 !ParamType->isDependentType()) 13351 return Diag(LastParam->getLocation(), 13352 diag::err_operator_overload_post_incdec_must_be_int) 13353 << LastParam->getType() << (Op == OO_MinusMinus); 13354 } 13355 13356 return false; 13357 } 13358 13359 static bool 13360 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 13361 FunctionTemplateDecl *TpDecl) { 13362 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 13363 13364 // Must have one or two template parameters. 13365 if (TemplateParams->size() == 1) { 13366 NonTypeTemplateParmDecl *PmDecl = 13367 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 13368 13369 // The template parameter must be a char parameter pack. 13370 if (PmDecl && PmDecl->isTemplateParameterPack() && 13371 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 13372 return false; 13373 13374 } else if (TemplateParams->size() == 2) { 13375 TemplateTypeParmDecl *PmType = 13376 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 13377 NonTypeTemplateParmDecl *PmArgs = 13378 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 13379 13380 // The second template parameter must be a parameter pack with the 13381 // first template parameter as its type. 13382 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 13383 PmArgs->isTemplateParameterPack()) { 13384 const TemplateTypeParmType *TArgs = 13385 PmArgs->getType()->getAs<TemplateTypeParmType>(); 13386 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 13387 TArgs->getIndex() == PmType->getIndex()) { 13388 if (!SemaRef.inTemplateInstantiation()) 13389 SemaRef.Diag(TpDecl->getLocation(), 13390 diag::ext_string_literal_operator_template); 13391 return false; 13392 } 13393 } 13394 } 13395 13396 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 13397 diag::err_literal_operator_template) 13398 << TpDecl->getTemplateParameters()->getSourceRange(); 13399 return true; 13400 } 13401 13402 /// CheckLiteralOperatorDeclaration - Check whether the declaration 13403 /// of this literal operator function is well-formed. If so, returns 13404 /// false; otherwise, emits appropriate diagnostics and returns true. 13405 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 13406 if (isa<CXXMethodDecl>(FnDecl)) { 13407 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 13408 << FnDecl->getDeclName(); 13409 return true; 13410 } 13411 13412 if (FnDecl->isExternC()) { 13413 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 13414 if (const LinkageSpecDecl *LSD = 13415 FnDecl->getDeclContext()->getExternCContext()) 13416 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 13417 return true; 13418 } 13419 13420 // This might be the definition of a literal operator template. 13421 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 13422 13423 // This might be a specialization of a literal operator template. 13424 if (!TpDecl) 13425 TpDecl = FnDecl->getPrimaryTemplate(); 13426 13427 // template <char...> type operator "" name() and 13428 // template <class T, T...> type operator "" name() are the only valid 13429 // template signatures, and the only valid signatures with no parameters. 13430 if (TpDecl) { 13431 if (FnDecl->param_size() != 0) { 13432 Diag(FnDecl->getLocation(), 13433 diag::err_literal_operator_template_with_params); 13434 return true; 13435 } 13436 13437 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 13438 return true; 13439 13440 } else if (FnDecl->param_size() == 1) { 13441 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 13442 13443 QualType ParamType = Param->getType().getUnqualifiedType(); 13444 13445 // Only unsigned long long int, long double, any character type, and const 13446 // char * are allowed as the only parameters. 13447 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 13448 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 13449 Context.hasSameType(ParamType, Context.CharTy) || 13450 Context.hasSameType(ParamType, Context.WideCharTy) || 13451 Context.hasSameType(ParamType, Context.Char8Ty) || 13452 Context.hasSameType(ParamType, Context.Char16Ty) || 13453 Context.hasSameType(ParamType, Context.Char32Ty)) { 13454 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 13455 QualType InnerType = Ptr->getPointeeType(); 13456 13457 // Pointer parameter must be a const char *. 13458 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 13459 Context.CharTy) && 13460 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 13461 Diag(Param->getSourceRange().getBegin(), 13462 diag::err_literal_operator_param) 13463 << ParamType << "'const char *'" << Param->getSourceRange(); 13464 return true; 13465 } 13466 13467 } else if (ParamType->isRealFloatingType()) { 13468 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13469 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 13470 return true; 13471 13472 } else if (ParamType->isIntegerType()) { 13473 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13474 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 13475 return true; 13476 13477 } else { 13478 Diag(Param->getSourceRange().getBegin(), 13479 diag::err_literal_operator_invalid_param) 13480 << ParamType << Param->getSourceRange(); 13481 return true; 13482 } 13483 13484 } else if (FnDecl->param_size() == 2) { 13485 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 13486 13487 // First, verify that the first parameter is correct. 13488 13489 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 13490 13491 // Two parameter function must have a pointer to const as a 13492 // first parameter; let's strip those qualifiers. 13493 const PointerType *PT = FirstParamType->getAs<PointerType>(); 13494 13495 if (!PT) { 13496 Diag((*Param)->getSourceRange().getBegin(), 13497 diag::err_literal_operator_param) 13498 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13499 return true; 13500 } 13501 13502 QualType PointeeType = PT->getPointeeType(); 13503 // First parameter must be const 13504 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 13505 Diag((*Param)->getSourceRange().getBegin(), 13506 diag::err_literal_operator_param) 13507 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13508 return true; 13509 } 13510 13511 QualType InnerType = PointeeType.getUnqualifiedType(); 13512 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 13513 // const char32_t* are allowed as the first parameter to a two-parameter 13514 // function 13515 if (!(Context.hasSameType(InnerType, Context.CharTy) || 13516 Context.hasSameType(InnerType, Context.WideCharTy) || 13517 Context.hasSameType(InnerType, Context.Char8Ty) || 13518 Context.hasSameType(InnerType, Context.Char16Ty) || 13519 Context.hasSameType(InnerType, Context.Char32Ty))) { 13520 Diag((*Param)->getSourceRange().getBegin(), 13521 diag::err_literal_operator_param) 13522 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13523 return true; 13524 } 13525 13526 // Move on to the second and final parameter. 13527 ++Param; 13528 13529 // The second parameter must be a std::size_t. 13530 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 13531 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 13532 Diag((*Param)->getSourceRange().getBegin(), 13533 diag::err_literal_operator_param) 13534 << SecondParamType << Context.getSizeType() 13535 << (*Param)->getSourceRange(); 13536 return true; 13537 } 13538 } else { 13539 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 13540 return true; 13541 } 13542 13543 // Parameters are good. 13544 13545 // A parameter-declaration-clause containing a default argument is not 13546 // equivalent to any of the permitted forms. 13547 for (auto Param : FnDecl->parameters()) { 13548 if (Param->hasDefaultArg()) { 13549 Diag(Param->getDefaultArgRange().getBegin(), 13550 diag::err_literal_operator_default_argument) 13551 << Param->getDefaultArgRange(); 13552 break; 13553 } 13554 } 13555 13556 StringRef LiteralName 13557 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13558 if (LiteralName[0] != '_' && 13559 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 13560 // C++11 [usrlit.suffix]p1: 13561 // Literal suffix identifiers that do not start with an underscore 13562 // are reserved for future standardization. 13563 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13564 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13565 } 13566 13567 return false; 13568 } 13569 13570 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13571 /// linkage specification, including the language and (if present) 13572 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13573 /// language string literal. LBraceLoc, if valid, provides the location of 13574 /// the '{' brace. Otherwise, this linkage specification does not 13575 /// have any braces. 13576 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13577 Expr *LangStr, 13578 SourceLocation LBraceLoc) { 13579 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13580 if (!Lit->isAscii()) { 13581 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13582 << LangStr->getSourceRange(); 13583 return nullptr; 13584 } 13585 13586 StringRef Lang = Lit->getString(); 13587 LinkageSpecDecl::LanguageIDs Language; 13588 if (Lang == "C") 13589 Language = LinkageSpecDecl::lang_c; 13590 else if (Lang == "C++") 13591 Language = LinkageSpecDecl::lang_cxx; 13592 else { 13593 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13594 << LangStr->getSourceRange(); 13595 return nullptr; 13596 } 13597 13598 // FIXME: Add all the various semantics of linkage specifications 13599 13600 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13601 LangStr->getExprLoc(), Language, 13602 LBraceLoc.isValid()); 13603 CurContext->addDecl(D); 13604 PushDeclContext(S, D); 13605 return D; 13606 } 13607 13608 /// ActOnFinishLinkageSpecification - Complete the definition of 13609 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13610 /// valid, it's the position of the closing '}' brace in a linkage 13611 /// specification that uses braces. 13612 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13613 Decl *LinkageSpec, 13614 SourceLocation RBraceLoc) { 13615 if (RBraceLoc.isValid()) { 13616 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13617 LSDecl->setRBraceLoc(RBraceLoc); 13618 } 13619 PopDeclContext(); 13620 return LinkageSpec; 13621 } 13622 13623 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13624 const ParsedAttributesView &AttrList, 13625 SourceLocation SemiLoc) { 13626 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13627 // Attribute declarations appertain to empty declaration so we handle 13628 // them here. 13629 ProcessDeclAttributeList(S, ED, AttrList); 13630 13631 CurContext->addDecl(ED); 13632 return ED; 13633 } 13634 13635 /// Perform semantic analysis for the variable declaration that 13636 /// occurs within a C++ catch clause, returning the newly-created 13637 /// variable. 13638 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13639 TypeSourceInfo *TInfo, 13640 SourceLocation StartLoc, 13641 SourceLocation Loc, 13642 IdentifierInfo *Name) { 13643 bool Invalid = false; 13644 QualType ExDeclType = TInfo->getType(); 13645 13646 // Arrays and functions decay. 13647 if (ExDeclType->isArrayType()) 13648 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13649 else if (ExDeclType->isFunctionType()) 13650 ExDeclType = Context.getPointerType(ExDeclType); 13651 13652 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13653 // The exception-declaration shall not denote a pointer or reference to an 13654 // incomplete type, other than [cv] void*. 13655 // N2844 forbids rvalue references. 13656 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13657 Diag(Loc, diag::err_catch_rvalue_ref); 13658 Invalid = true; 13659 } 13660 13661 if (ExDeclType->isVariablyModifiedType()) { 13662 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13663 Invalid = true; 13664 } 13665 13666 QualType BaseType = ExDeclType; 13667 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13668 unsigned DK = diag::err_catch_incomplete; 13669 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13670 BaseType = Ptr->getPointeeType(); 13671 Mode = 1; 13672 DK = diag::err_catch_incomplete_ptr; 13673 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13674 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13675 BaseType = Ref->getPointeeType(); 13676 Mode = 2; 13677 DK = diag::err_catch_incomplete_ref; 13678 } 13679 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13680 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13681 Invalid = true; 13682 13683 if (!Invalid && !ExDeclType->isDependentType() && 13684 RequireNonAbstractType(Loc, ExDeclType, 13685 diag::err_abstract_type_in_decl, 13686 AbstractVariableType)) 13687 Invalid = true; 13688 13689 // Only the non-fragile NeXT runtime currently supports C++ catches 13690 // of ObjC types, and no runtime supports catching ObjC types by value. 13691 if (!Invalid && getLangOpts().ObjC1) { 13692 QualType T = ExDeclType; 13693 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13694 T = RT->getPointeeType(); 13695 13696 if (T->isObjCObjectType()) { 13697 Diag(Loc, diag::err_objc_object_catch); 13698 Invalid = true; 13699 } else if (T->isObjCObjectPointerType()) { 13700 // FIXME: should this be a test for macosx-fragile specifically? 13701 if (getLangOpts().ObjCRuntime.isFragile()) 13702 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13703 } 13704 } 13705 13706 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13707 ExDeclType, TInfo, SC_None); 13708 ExDecl->setExceptionVariable(true); 13709 13710 // In ARC, infer 'retaining' for variables of retainable type. 13711 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13712 Invalid = true; 13713 13714 if (!Invalid && !ExDeclType->isDependentType()) { 13715 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13716 // Insulate this from anything else we might currently be parsing. 13717 EnterExpressionEvaluationContext scope( 13718 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 13719 13720 // C++ [except.handle]p16: 13721 // The object declared in an exception-declaration or, if the 13722 // exception-declaration does not specify a name, a temporary (12.2) is 13723 // copy-initialized (8.5) from the exception object. [...] 13724 // The object is destroyed when the handler exits, after the destruction 13725 // of any automatic objects initialized within the handler. 13726 // 13727 // We just pretend to initialize the object with itself, then make sure 13728 // it can be destroyed later. 13729 QualType initType = Context.getExceptionObjectType(ExDeclType); 13730 13731 InitializedEntity entity = 13732 InitializedEntity::InitializeVariable(ExDecl); 13733 InitializationKind initKind = 13734 InitializationKind::CreateCopy(Loc, SourceLocation()); 13735 13736 Expr *opaqueValue = 13737 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13738 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13739 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13740 if (result.isInvalid()) 13741 Invalid = true; 13742 else { 13743 // If the constructor used was non-trivial, set this as the 13744 // "initializer". 13745 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13746 if (!construct->getConstructor()->isTrivial()) { 13747 Expr *init = MaybeCreateExprWithCleanups(construct); 13748 ExDecl->setInit(init); 13749 } 13750 13751 // And make sure it's destructable. 13752 FinalizeVarWithDestructor(ExDecl, recordType); 13753 } 13754 } 13755 } 13756 13757 if (Invalid) 13758 ExDecl->setInvalidDecl(); 13759 13760 return ExDecl; 13761 } 13762 13763 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13764 /// handler. 13765 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13766 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13767 bool Invalid = D.isInvalidType(); 13768 13769 // Check for unexpanded parameter packs. 13770 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13771 UPPC_ExceptionType)) { 13772 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13773 D.getIdentifierLoc()); 13774 Invalid = true; 13775 } 13776 13777 IdentifierInfo *II = D.getIdentifier(); 13778 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13779 LookupOrdinaryName, 13780 ForVisibleRedeclaration)) { 13781 // The scope should be freshly made just for us. There is just no way 13782 // it contains any previous declaration, except for function parameters in 13783 // a function-try-block's catch statement. 13784 assert(!S->isDeclScope(PrevDecl)); 13785 if (isDeclInScope(PrevDecl, CurContext, S)) { 13786 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13787 << D.getIdentifier(); 13788 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13789 Invalid = true; 13790 } else if (PrevDecl->isTemplateParameter()) 13791 // Maybe we will complain about the shadowed template parameter. 13792 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13793 } 13794 13795 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13796 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13797 << D.getCXXScopeSpec().getRange(); 13798 Invalid = true; 13799 } 13800 13801 VarDecl *ExDecl = BuildExceptionDeclaration( 13802 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 13803 if (Invalid) 13804 ExDecl->setInvalidDecl(); 13805 13806 // Add the exception declaration into this scope. 13807 if (II) 13808 PushOnScopeChains(ExDecl, S); 13809 else 13810 CurContext->addDecl(ExDecl); 13811 13812 ProcessDeclAttributes(S, ExDecl, D); 13813 return ExDecl; 13814 } 13815 13816 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13817 Expr *AssertExpr, 13818 Expr *AssertMessageExpr, 13819 SourceLocation RParenLoc) { 13820 StringLiteral *AssertMessage = 13821 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13822 13823 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13824 return nullptr; 13825 13826 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13827 AssertMessage, RParenLoc, false); 13828 } 13829 13830 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13831 Expr *AssertExpr, 13832 StringLiteral *AssertMessage, 13833 SourceLocation RParenLoc, 13834 bool Failed) { 13835 assert(AssertExpr != nullptr && "Expected non-null condition"); 13836 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13837 !Failed) { 13838 // In a static_assert-declaration, the constant-expression shall be a 13839 // constant expression that can be contextually converted to bool. 13840 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13841 if (Converted.isInvalid()) 13842 Failed = true; 13843 13844 llvm::APSInt Cond; 13845 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13846 diag::err_static_assert_expression_is_not_constant, 13847 /*AllowFold=*/false).isInvalid()) 13848 Failed = true; 13849 13850 if (!Failed && !Cond) { 13851 SmallString<256> MsgBuffer; 13852 llvm::raw_svector_ostream Msg(MsgBuffer); 13853 if (AssertMessage) 13854 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13855 13856 Expr *InnerCond = nullptr; 13857 std::string InnerCondDescription; 13858 std::tie(InnerCond, InnerCondDescription) = 13859 findFailedBooleanCondition(Converted.get(), 13860 /*AllowTopLevelCond=*/false); 13861 if (InnerCond) { 13862 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 13863 << InnerCondDescription << !AssertMessage 13864 << Msg.str() << InnerCond->getSourceRange(); 13865 } else { 13866 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13867 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13868 } 13869 Failed = true; 13870 } 13871 } 13872 13873 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 13874 /*DiscardedValue*/false, 13875 /*IsConstexpr*/true); 13876 if (FullAssertExpr.isInvalid()) 13877 Failed = true; 13878 else 13879 AssertExpr = FullAssertExpr.get(); 13880 13881 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13882 AssertExpr, AssertMessage, RParenLoc, 13883 Failed); 13884 13885 CurContext->addDecl(Decl); 13886 return Decl; 13887 } 13888 13889 /// Perform semantic analysis of the given friend type declaration. 13890 /// 13891 /// \returns A friend declaration that. 13892 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 13893 SourceLocation FriendLoc, 13894 TypeSourceInfo *TSInfo) { 13895 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 13896 13897 QualType T = TSInfo->getType(); 13898 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 13899 13900 // C++03 [class.friend]p2: 13901 // An elaborated-type-specifier shall be used in a friend declaration 13902 // for a class.* 13903 // 13904 // * The class-key of the elaborated-type-specifier is required. 13905 if (!CodeSynthesisContexts.empty()) { 13906 // Do not complain about the form of friend template types during any kind 13907 // of code synthesis. For template instantiation, we will have complained 13908 // when the template was defined. 13909 } else { 13910 if (!T->isElaboratedTypeSpecifier()) { 13911 // If we evaluated the type to a record type, suggest putting 13912 // a tag in front. 13913 if (const RecordType *RT = T->getAs<RecordType>()) { 13914 RecordDecl *RD = RT->getDecl(); 13915 13916 SmallString<16> InsertionText(" "); 13917 InsertionText += RD->getKindName(); 13918 13919 Diag(TypeRange.getBegin(), 13920 getLangOpts().CPlusPlus11 ? 13921 diag::warn_cxx98_compat_unelaborated_friend_type : 13922 diag::ext_unelaborated_friend_type) 13923 << (unsigned) RD->getTagKind() 13924 << T 13925 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 13926 InsertionText); 13927 } else { 13928 Diag(FriendLoc, 13929 getLangOpts().CPlusPlus11 ? 13930 diag::warn_cxx98_compat_nonclass_type_friend : 13931 diag::ext_nonclass_type_friend) 13932 << T 13933 << TypeRange; 13934 } 13935 } else if (T->getAs<EnumType>()) { 13936 Diag(FriendLoc, 13937 getLangOpts().CPlusPlus11 ? 13938 diag::warn_cxx98_compat_enum_friend : 13939 diag::ext_enum_friend) 13940 << T 13941 << TypeRange; 13942 } 13943 13944 // C++11 [class.friend]p3: 13945 // A friend declaration that does not declare a function shall have one 13946 // of the following forms: 13947 // friend elaborated-type-specifier ; 13948 // friend simple-type-specifier ; 13949 // friend typename-specifier ; 13950 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 13951 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 13952 } 13953 13954 // If the type specifier in a friend declaration designates a (possibly 13955 // cv-qualified) class type, that class is declared as a friend; otherwise, 13956 // the friend declaration is ignored. 13957 return FriendDecl::Create(Context, CurContext, 13958 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 13959 FriendLoc); 13960 } 13961 13962 /// Handle a friend tag declaration where the scope specifier was 13963 /// templated. 13964 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 13965 unsigned TagSpec, SourceLocation TagLoc, 13966 CXXScopeSpec &SS, IdentifierInfo *Name, 13967 SourceLocation NameLoc, 13968 const ParsedAttributesView &Attr, 13969 MultiTemplateParamsArg TempParamLists) { 13970 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13971 13972 bool IsMemberSpecialization = false; 13973 bool Invalid = false; 13974 13975 if (TemplateParameterList *TemplateParams = 13976 MatchTemplateParametersToScopeSpecifier( 13977 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 13978 IsMemberSpecialization, Invalid)) { 13979 if (TemplateParams->size() > 0) { 13980 // This is a declaration of a class template. 13981 if (Invalid) 13982 return nullptr; 13983 13984 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 13985 NameLoc, Attr, TemplateParams, AS_public, 13986 /*ModulePrivateLoc=*/SourceLocation(), 13987 FriendLoc, TempParamLists.size() - 1, 13988 TempParamLists.data()).get(); 13989 } else { 13990 // The "template<>" header is extraneous. 13991 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13992 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13993 IsMemberSpecialization = true; 13994 } 13995 } 13996 13997 if (Invalid) return nullptr; 13998 13999 bool isAllExplicitSpecializations = true; 14000 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 14001 if (TempParamLists[I]->size()) { 14002 isAllExplicitSpecializations = false; 14003 break; 14004 } 14005 } 14006 14007 // FIXME: don't ignore attributes. 14008 14009 // If it's explicit specializations all the way down, just forget 14010 // about the template header and build an appropriate non-templated 14011 // friend. TODO: for source fidelity, remember the headers. 14012 if (isAllExplicitSpecializations) { 14013 if (SS.isEmpty()) { 14014 bool Owned = false; 14015 bool IsDependent = false; 14016 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 14017 Attr, AS_public, 14018 /*ModulePrivateLoc=*/SourceLocation(), 14019 MultiTemplateParamsArg(), Owned, IsDependent, 14020 /*ScopedEnumKWLoc=*/SourceLocation(), 14021 /*ScopedEnumUsesClassTag=*/false, 14022 /*UnderlyingType=*/TypeResult(), 14023 /*IsTypeSpecifier=*/false, 14024 /*IsTemplateParamOrArg=*/false); 14025 } 14026 14027 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 14028 ElaboratedTypeKeyword Keyword 14029 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14030 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 14031 *Name, NameLoc); 14032 if (T.isNull()) 14033 return nullptr; 14034 14035 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14036 if (isa<DependentNameType>(T)) { 14037 DependentNameTypeLoc TL = 14038 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14039 TL.setElaboratedKeywordLoc(TagLoc); 14040 TL.setQualifierLoc(QualifierLoc); 14041 TL.setNameLoc(NameLoc); 14042 } else { 14043 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 14044 TL.setElaboratedKeywordLoc(TagLoc); 14045 TL.setQualifierLoc(QualifierLoc); 14046 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 14047 } 14048 14049 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14050 TSI, FriendLoc, TempParamLists); 14051 Friend->setAccess(AS_public); 14052 CurContext->addDecl(Friend); 14053 return Friend; 14054 } 14055 14056 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 14057 14058 14059 14060 // Handle the case of a templated-scope friend class. e.g. 14061 // template <class T> class A<T>::B; 14062 // FIXME: we don't support these right now. 14063 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 14064 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 14065 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14066 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 14067 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14068 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14069 TL.setElaboratedKeywordLoc(TagLoc); 14070 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 14071 TL.setNameLoc(NameLoc); 14072 14073 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14074 TSI, FriendLoc, TempParamLists); 14075 Friend->setAccess(AS_public); 14076 Friend->setUnsupportedFriend(true); 14077 CurContext->addDecl(Friend); 14078 return Friend; 14079 } 14080 14081 /// Handle a friend type declaration. This works in tandem with 14082 /// ActOnTag. 14083 /// 14084 /// Notes on friend class templates: 14085 /// 14086 /// We generally treat friend class declarations as if they were 14087 /// declaring a class. So, for example, the elaborated type specifier 14088 /// in a friend declaration is required to obey the restrictions of a 14089 /// class-head (i.e. no typedefs in the scope chain), template 14090 /// parameters are required to match up with simple template-ids, &c. 14091 /// However, unlike when declaring a template specialization, it's 14092 /// okay to refer to a template specialization without an empty 14093 /// template parameter declaration, e.g. 14094 /// friend class A<T>::B<unsigned>; 14095 /// We permit this as a special case; if there are any template 14096 /// parameters present at all, require proper matching, i.e. 14097 /// template <> template \<class T> friend class A<int>::B; 14098 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 14099 MultiTemplateParamsArg TempParams) { 14100 SourceLocation Loc = DS.getBeginLoc(); 14101 14102 assert(DS.isFriendSpecified()); 14103 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14104 14105 // C++ [class.friend]p3: 14106 // A friend declaration that does not declare a function shall have one of 14107 // the following forms: 14108 // friend elaborated-type-specifier ; 14109 // friend simple-type-specifier ; 14110 // friend typename-specifier ; 14111 // 14112 // Any declaration with a type qualifier does not have that form. (It's 14113 // legal to specify a qualified type as a friend, you just can't write the 14114 // keywords.) 14115 if (DS.getTypeQualifiers()) { 14116 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 14117 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 14118 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 14119 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 14120 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 14121 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 14122 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 14123 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 14124 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 14125 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 14126 } 14127 14128 // Try to convert the decl specifier to a type. This works for 14129 // friend templates because ActOnTag never produces a ClassTemplateDecl 14130 // for a TUK_Friend. 14131 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 14132 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 14133 QualType T = TSI->getType(); 14134 if (TheDeclarator.isInvalidType()) 14135 return nullptr; 14136 14137 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 14138 return nullptr; 14139 14140 // This is definitely an error in C++98. It's probably meant to 14141 // be forbidden in C++0x, too, but the specification is just 14142 // poorly written. 14143 // 14144 // The problem is with declarations like the following: 14145 // template <T> friend A<T>::foo; 14146 // where deciding whether a class C is a friend or not now hinges 14147 // on whether there exists an instantiation of A that causes 14148 // 'foo' to equal C. There are restrictions on class-heads 14149 // (which we declare (by fiat) elaborated friend declarations to 14150 // be) that makes this tractable. 14151 // 14152 // FIXME: handle "template <> friend class A<T>;", which 14153 // is possibly well-formed? Who even knows? 14154 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 14155 Diag(Loc, diag::err_tagless_friend_type_template) 14156 << DS.getSourceRange(); 14157 return nullptr; 14158 } 14159 14160 // C++98 [class.friend]p1: A friend of a class is a function 14161 // or class that is not a member of the class . . . 14162 // This is fixed in DR77, which just barely didn't make the C++03 14163 // deadline. It's also a very silly restriction that seriously 14164 // affects inner classes and which nobody else seems to implement; 14165 // thus we never diagnose it, not even in -pedantic. 14166 // 14167 // But note that we could warn about it: it's always useless to 14168 // friend one of your own members (it's not, however, worthless to 14169 // friend a member of an arbitrary specialization of your template). 14170 14171 Decl *D; 14172 if (!TempParams.empty()) 14173 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 14174 TempParams, 14175 TSI, 14176 DS.getFriendSpecLoc()); 14177 else 14178 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 14179 14180 if (!D) 14181 return nullptr; 14182 14183 D->setAccess(AS_public); 14184 CurContext->addDecl(D); 14185 14186 return D; 14187 } 14188 14189 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 14190 MultiTemplateParamsArg TemplateParams) { 14191 const DeclSpec &DS = D.getDeclSpec(); 14192 14193 assert(DS.isFriendSpecified()); 14194 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14195 14196 SourceLocation Loc = D.getIdentifierLoc(); 14197 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14198 14199 // C++ [class.friend]p1 14200 // A friend of a class is a function or class.... 14201 // Note that this sees through typedefs, which is intended. 14202 // It *doesn't* see through dependent types, which is correct 14203 // according to [temp.arg.type]p3: 14204 // If a declaration acquires a function type through a 14205 // type dependent on a template-parameter and this causes 14206 // a declaration that does not use the syntactic form of a 14207 // function declarator to have a function type, the program 14208 // is ill-formed. 14209 if (!TInfo->getType()->isFunctionType()) { 14210 Diag(Loc, diag::err_unexpected_friend); 14211 14212 // It might be worthwhile to try to recover by creating an 14213 // appropriate declaration. 14214 return nullptr; 14215 } 14216 14217 // C++ [namespace.memdef]p3 14218 // - If a friend declaration in a non-local class first declares a 14219 // class or function, the friend class or function is a member 14220 // of the innermost enclosing namespace. 14221 // - The name of the friend is not found by simple name lookup 14222 // until a matching declaration is provided in that namespace 14223 // scope (either before or after the class declaration granting 14224 // friendship). 14225 // - If a friend function is called, its name may be found by the 14226 // name lookup that considers functions from namespaces and 14227 // classes associated with the types of the function arguments. 14228 // - When looking for a prior declaration of a class or a function 14229 // declared as a friend, scopes outside the innermost enclosing 14230 // namespace scope are not considered. 14231 14232 CXXScopeSpec &SS = D.getCXXScopeSpec(); 14233 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 14234 DeclarationName Name = NameInfo.getName(); 14235 assert(Name); 14236 14237 // Check for unexpanded parameter packs. 14238 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 14239 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 14240 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 14241 return nullptr; 14242 14243 // The context we found the declaration in, or in which we should 14244 // create the declaration. 14245 DeclContext *DC; 14246 Scope *DCScope = S; 14247 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 14248 ForExternalRedeclaration); 14249 14250 // There are five cases here. 14251 // - There's no scope specifier and we're in a local class. Only look 14252 // for functions declared in the immediately-enclosing block scope. 14253 // We recover from invalid scope qualifiers as if they just weren't there. 14254 FunctionDecl *FunctionContainingLocalClass = nullptr; 14255 if ((SS.isInvalid() || !SS.isSet()) && 14256 (FunctionContainingLocalClass = 14257 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 14258 // C++11 [class.friend]p11: 14259 // If a friend declaration appears in a local class and the name 14260 // specified is an unqualified name, a prior declaration is 14261 // looked up without considering scopes that are outside the 14262 // innermost enclosing non-class scope. For a friend function 14263 // declaration, if there is no prior declaration, the program is 14264 // ill-formed. 14265 14266 // Find the innermost enclosing non-class scope. This is the block 14267 // scope containing the local class definition (or for a nested class, 14268 // the outer local class). 14269 DCScope = S->getFnParent(); 14270 14271 // Look up the function name in the scope. 14272 Previous.clear(LookupLocalFriendName); 14273 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 14274 14275 if (!Previous.empty()) { 14276 // All possible previous declarations must have the same context: 14277 // either they were declared at block scope or they are members of 14278 // one of the enclosing local classes. 14279 DC = Previous.getRepresentativeDecl()->getDeclContext(); 14280 } else { 14281 // This is ill-formed, but provide the context that we would have 14282 // declared the function in, if we were permitted to, for error recovery. 14283 DC = FunctionContainingLocalClass; 14284 } 14285 adjustContextForLocalExternDecl(DC); 14286 14287 // C++ [class.friend]p6: 14288 // A function can be defined in a friend declaration of a class if and 14289 // only if the class is a non-local class (9.8), the function name is 14290 // unqualified, and the function has namespace scope. 14291 if (D.isFunctionDefinition()) { 14292 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 14293 } 14294 14295 // - There's no scope specifier, in which case we just go to the 14296 // appropriate scope and look for a function or function template 14297 // there as appropriate. 14298 } else if (SS.isInvalid() || !SS.isSet()) { 14299 // C++11 [namespace.memdef]p3: 14300 // If the name in a friend declaration is neither qualified nor 14301 // a template-id and the declaration is a function or an 14302 // elaborated-type-specifier, the lookup to determine whether 14303 // the entity has been previously declared shall not consider 14304 // any scopes outside the innermost enclosing namespace. 14305 bool isTemplateId = 14306 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 14307 14308 // Find the appropriate context according to the above. 14309 DC = CurContext; 14310 14311 // Skip class contexts. If someone can cite chapter and verse 14312 // for this behavior, that would be nice --- it's what GCC and 14313 // EDG do, and it seems like a reasonable intent, but the spec 14314 // really only says that checks for unqualified existing 14315 // declarations should stop at the nearest enclosing namespace, 14316 // not that they should only consider the nearest enclosing 14317 // namespace. 14318 while (DC->isRecord()) 14319 DC = DC->getParent(); 14320 14321 DeclContext *LookupDC = DC; 14322 while (LookupDC->isTransparentContext()) 14323 LookupDC = LookupDC->getParent(); 14324 14325 while (true) { 14326 LookupQualifiedName(Previous, LookupDC); 14327 14328 if (!Previous.empty()) { 14329 DC = LookupDC; 14330 break; 14331 } 14332 14333 if (isTemplateId) { 14334 if (isa<TranslationUnitDecl>(LookupDC)) break; 14335 } else { 14336 if (LookupDC->isFileContext()) break; 14337 } 14338 LookupDC = LookupDC->getParent(); 14339 } 14340 14341 DCScope = getScopeForDeclContext(S, DC); 14342 14343 // - There's a non-dependent scope specifier, in which case we 14344 // compute it and do a previous lookup there for a function 14345 // or function template. 14346 } else if (!SS.getScopeRep()->isDependent()) { 14347 DC = computeDeclContext(SS); 14348 if (!DC) return nullptr; 14349 14350 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 14351 14352 LookupQualifiedName(Previous, DC); 14353 14354 // Ignore things found implicitly in the wrong scope. 14355 // TODO: better diagnostics for this case. Suggesting the right 14356 // qualified scope would be nice... 14357 LookupResult::Filter F = Previous.makeFilter(); 14358 while (F.hasNext()) { 14359 NamedDecl *D = F.next(); 14360 if (!DC->InEnclosingNamespaceSetOf( 14361 D->getDeclContext()->getRedeclContext())) 14362 F.erase(); 14363 } 14364 F.done(); 14365 14366 if (Previous.empty()) { 14367 D.setInvalidType(); 14368 Diag(Loc, diag::err_qualified_friend_not_found) 14369 << Name << TInfo->getType(); 14370 return nullptr; 14371 } 14372 14373 // C++ [class.friend]p1: A friend of a class is a function or 14374 // class that is not a member of the class . . . 14375 if (DC->Equals(CurContext)) 14376 Diag(DS.getFriendSpecLoc(), 14377 getLangOpts().CPlusPlus11 ? 14378 diag::warn_cxx98_compat_friend_is_member : 14379 diag::err_friend_is_member); 14380 14381 if (D.isFunctionDefinition()) { 14382 // C++ [class.friend]p6: 14383 // A function can be defined in a friend declaration of a class if and 14384 // only if the class is a non-local class (9.8), the function name is 14385 // unqualified, and the function has namespace scope. 14386 SemaDiagnosticBuilder DB 14387 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 14388 14389 DB << SS.getScopeRep(); 14390 if (DC->isFileContext()) 14391 DB << FixItHint::CreateRemoval(SS.getRange()); 14392 SS.clear(); 14393 } 14394 14395 // - There's a scope specifier that does not match any template 14396 // parameter lists, in which case we use some arbitrary context, 14397 // create a method or method template, and wait for instantiation. 14398 // - There's a scope specifier that does match some template 14399 // parameter lists, which we don't handle right now. 14400 } else { 14401 if (D.isFunctionDefinition()) { 14402 // C++ [class.friend]p6: 14403 // A function can be defined in a friend declaration of a class if and 14404 // only if the class is a non-local class (9.8), the function name is 14405 // unqualified, and the function has namespace scope. 14406 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 14407 << SS.getScopeRep(); 14408 } 14409 14410 DC = CurContext; 14411 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 14412 } 14413 14414 if (!DC->isRecord()) { 14415 int DiagArg = -1; 14416 switch (D.getName().getKind()) { 14417 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14418 case UnqualifiedIdKind::IK_ConstructorName: 14419 DiagArg = 0; 14420 break; 14421 case UnqualifiedIdKind::IK_DestructorName: 14422 DiagArg = 1; 14423 break; 14424 case UnqualifiedIdKind::IK_ConversionFunctionId: 14425 DiagArg = 2; 14426 break; 14427 case UnqualifiedIdKind::IK_DeductionGuideName: 14428 DiagArg = 3; 14429 break; 14430 case UnqualifiedIdKind::IK_Identifier: 14431 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14432 case UnqualifiedIdKind::IK_LiteralOperatorId: 14433 case UnqualifiedIdKind::IK_OperatorFunctionId: 14434 case UnqualifiedIdKind::IK_TemplateId: 14435 break; 14436 } 14437 // This implies that it has to be an operator or function. 14438 if (DiagArg >= 0) { 14439 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 14440 return nullptr; 14441 } 14442 } 14443 14444 // FIXME: This is an egregious hack to cope with cases where the scope stack 14445 // does not contain the declaration context, i.e., in an out-of-line 14446 // definition of a class. 14447 Scope FakeDCScope(S, Scope::DeclScope, Diags); 14448 if (!DCScope) { 14449 FakeDCScope.setEntity(DC); 14450 DCScope = &FakeDCScope; 14451 } 14452 14453 bool AddToScope = true; 14454 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 14455 TemplateParams, AddToScope); 14456 if (!ND) return nullptr; 14457 14458 assert(ND->getLexicalDeclContext() == CurContext); 14459 14460 // If we performed typo correction, we might have added a scope specifier 14461 // and changed the decl context. 14462 DC = ND->getDeclContext(); 14463 14464 // Add the function declaration to the appropriate lookup tables, 14465 // adjusting the redeclarations list as necessary. We don't 14466 // want to do this yet if the friending class is dependent. 14467 // 14468 // Also update the scope-based lookup if the target context's 14469 // lookup context is in lexical scope. 14470 if (!CurContext->isDependentContext()) { 14471 DC = DC->getRedeclContext(); 14472 DC->makeDeclVisibleInContext(ND); 14473 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14474 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 14475 } 14476 14477 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 14478 D.getIdentifierLoc(), ND, 14479 DS.getFriendSpecLoc()); 14480 FrD->setAccess(AS_public); 14481 CurContext->addDecl(FrD); 14482 14483 if (ND->isInvalidDecl()) { 14484 FrD->setInvalidDecl(); 14485 } else { 14486 if (DC->isRecord()) CheckFriendAccess(ND); 14487 14488 FunctionDecl *FD; 14489 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 14490 FD = FTD->getTemplatedDecl(); 14491 else 14492 FD = cast<FunctionDecl>(ND); 14493 14494 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 14495 // default argument expression, that declaration shall be a definition 14496 // and shall be the only declaration of the function or function 14497 // template in the translation unit. 14498 if (functionDeclHasDefaultArgument(FD)) { 14499 // We can't look at FD->getPreviousDecl() because it may not have been set 14500 // if we're in a dependent context. If the function is known to be a 14501 // redeclaration, we will have narrowed Previous down to the right decl. 14502 if (D.isRedeclaration()) { 14503 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 14504 Diag(Previous.getRepresentativeDecl()->getLocation(), 14505 diag::note_previous_declaration); 14506 } else if (!D.isFunctionDefinition()) 14507 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 14508 } 14509 14510 // Mark templated-scope function declarations as unsupported. 14511 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 14512 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 14513 << SS.getScopeRep() << SS.getRange() 14514 << cast<CXXRecordDecl>(CurContext); 14515 FrD->setUnsupportedFriend(true); 14516 } 14517 } 14518 14519 return ND; 14520 } 14521 14522 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 14523 AdjustDeclIfTemplate(Dcl); 14524 14525 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 14526 if (!Fn) { 14527 Diag(DelLoc, diag::err_deleted_non_function); 14528 return; 14529 } 14530 14531 // Deleted function does not have a body. 14532 Fn->setWillHaveBody(false); 14533 14534 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 14535 // Don't consider the implicit declaration we generate for explicit 14536 // specializations. FIXME: Do not generate these implicit declarations. 14537 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 14538 Prev->getPreviousDecl()) && 14539 !Prev->isDefined()) { 14540 Diag(DelLoc, diag::err_deleted_decl_not_first); 14541 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 14542 Prev->isImplicit() ? diag::note_previous_implicit_declaration 14543 : diag::note_previous_declaration); 14544 } 14545 // If the declaration wasn't the first, we delete the function anyway for 14546 // recovery. 14547 Fn = Fn->getCanonicalDecl(); 14548 } 14549 14550 // dllimport/dllexport cannot be deleted. 14551 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 14552 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 14553 Fn->setInvalidDecl(); 14554 } 14555 14556 if (Fn->isDeleted()) 14557 return; 14558 14559 // See if we're deleting a function which is already known to override a 14560 // non-deleted virtual function. 14561 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 14562 bool IssuedDiagnostic = false; 14563 for (const CXXMethodDecl *O : MD->overridden_methods()) { 14564 if (!(*MD->begin_overridden_methods())->isDeleted()) { 14565 if (!IssuedDiagnostic) { 14566 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 14567 IssuedDiagnostic = true; 14568 } 14569 Diag(O->getLocation(), diag::note_overridden_virtual_function); 14570 } 14571 } 14572 // If this function was implicitly deleted because it was defaulted, 14573 // explain why it was deleted. 14574 if (IssuedDiagnostic && MD->isDefaulted()) 14575 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14576 /*Diagnose*/true); 14577 } 14578 14579 // C++11 [basic.start.main]p3: 14580 // A program that defines main as deleted [...] is ill-formed. 14581 if (Fn->isMain()) 14582 Diag(DelLoc, diag::err_deleted_main); 14583 14584 // C++11 [dcl.fct.def.delete]p4: 14585 // A deleted function is implicitly inline. 14586 Fn->setImplicitlyInline(); 14587 Fn->setDeletedAsWritten(); 14588 } 14589 14590 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14591 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14592 14593 if (MD) { 14594 if (MD->getParent()->isDependentType()) { 14595 MD->setDefaulted(); 14596 MD->setExplicitlyDefaulted(); 14597 return; 14598 } 14599 14600 CXXSpecialMember Member = getSpecialMember(MD); 14601 if (Member == CXXInvalid) { 14602 if (!MD->isInvalidDecl()) 14603 Diag(DefaultLoc, diag::err_default_special_members); 14604 return; 14605 } 14606 14607 MD->setDefaulted(); 14608 MD->setExplicitlyDefaulted(); 14609 14610 // Unset that we will have a body for this function. We might not, 14611 // if it turns out to be trivial, and we don't need this marking now 14612 // that we've marked it as defaulted. 14613 MD->setWillHaveBody(false); 14614 14615 // If this definition appears within the record, do the checking when 14616 // the record is complete. 14617 const FunctionDecl *Primary = MD; 14618 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14619 // Ask the template instantiation pattern that actually had the 14620 // '= default' on it. 14621 Primary = Pattern; 14622 14623 // If the method was defaulted on its first declaration, we will have 14624 // already performed the checking in CheckCompletedCXXClass. Such a 14625 // declaration doesn't trigger an implicit definition. 14626 if (Primary->getCanonicalDecl()->isDefaulted()) 14627 return; 14628 14629 CheckExplicitlyDefaultedSpecialMember(MD); 14630 14631 if (!MD->isInvalidDecl()) 14632 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14633 } else { 14634 Diag(DefaultLoc, diag::err_default_special_members); 14635 } 14636 } 14637 14638 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14639 for (Stmt *SubStmt : S->children()) { 14640 if (!SubStmt) 14641 continue; 14642 if (isa<ReturnStmt>(SubStmt)) 14643 Self.Diag(SubStmt->getBeginLoc(), 14644 diag::err_return_in_constructor_handler); 14645 if (!isa<Expr>(SubStmt)) 14646 SearchForReturnInStmt(Self, SubStmt); 14647 } 14648 } 14649 14650 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14651 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14652 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14653 SearchForReturnInStmt(*this, Handler); 14654 } 14655 } 14656 14657 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14658 const CXXMethodDecl *Old) { 14659 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 14660 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 14661 14662 if (OldFT->hasExtParameterInfos()) { 14663 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 14664 // A parameter of the overriding method should be annotated with noescape 14665 // if the corresponding parameter of the overridden method is annotated. 14666 if (OldFT->getExtParameterInfo(I).isNoEscape() && 14667 !NewFT->getExtParameterInfo(I).isNoEscape()) { 14668 Diag(New->getParamDecl(I)->getLocation(), 14669 diag::warn_overriding_method_missing_noescape); 14670 Diag(Old->getParamDecl(I)->getLocation(), 14671 diag::note_overridden_marked_noescape); 14672 } 14673 } 14674 14675 // Virtual overrides must have the same code_seg. 14676 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 14677 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 14678 if ((NewCSA || OldCSA) && 14679 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 14680 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 14681 Diag(Old->getLocation(), diag::note_previous_declaration); 14682 return true; 14683 } 14684 14685 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14686 14687 // If the calling conventions match, everything is fine 14688 if (NewCC == OldCC) 14689 return false; 14690 14691 // If the calling conventions mismatch because the new function is static, 14692 // suppress the calling convention mismatch error; the error about static 14693 // function override (err_static_overrides_virtual from 14694 // Sema::CheckFunctionDeclaration) is more clear. 14695 if (New->getStorageClass() == SC_Static) 14696 return false; 14697 14698 Diag(New->getLocation(), 14699 diag::err_conflicting_overriding_cc_attributes) 14700 << New->getDeclName() << New->getType() << Old->getType(); 14701 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14702 return true; 14703 } 14704 14705 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14706 const CXXMethodDecl *Old) { 14707 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14708 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 14709 14710 if (Context.hasSameType(NewTy, OldTy) || 14711 NewTy->isDependentType() || OldTy->isDependentType()) 14712 return false; 14713 14714 // Check if the return types are covariant 14715 QualType NewClassTy, OldClassTy; 14716 14717 /// Both types must be pointers or references to classes. 14718 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 14719 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 14720 NewClassTy = NewPT->getPointeeType(); 14721 OldClassTy = OldPT->getPointeeType(); 14722 } 14723 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 14724 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 14725 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 14726 NewClassTy = NewRT->getPointeeType(); 14727 OldClassTy = OldRT->getPointeeType(); 14728 } 14729 } 14730 } 14731 14732 // The return types aren't either both pointers or references to a class type. 14733 if (NewClassTy.isNull()) { 14734 Diag(New->getLocation(), 14735 diag::err_different_return_type_for_overriding_virtual_function) 14736 << New->getDeclName() << NewTy << OldTy 14737 << New->getReturnTypeSourceRange(); 14738 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14739 << Old->getReturnTypeSourceRange(); 14740 14741 return true; 14742 } 14743 14744 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 14745 // C++14 [class.virtual]p8: 14746 // If the class type in the covariant return type of D::f differs from 14747 // that of B::f, the class type in the return type of D::f shall be 14748 // complete at the point of declaration of D::f or shall be the class 14749 // type D. 14750 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14751 if (!RT->isBeingDefined() && 14752 RequireCompleteType(New->getLocation(), NewClassTy, 14753 diag::err_covariant_return_incomplete, 14754 New->getDeclName())) 14755 return true; 14756 } 14757 14758 // Check if the new class derives from the old class. 14759 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14760 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14761 << New->getDeclName() << NewTy << OldTy 14762 << New->getReturnTypeSourceRange(); 14763 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14764 << Old->getReturnTypeSourceRange(); 14765 return true; 14766 } 14767 14768 // Check if we the conversion from derived to base is valid. 14769 if (CheckDerivedToBaseConversion( 14770 NewClassTy, OldClassTy, 14771 diag::err_covariant_return_inaccessible_base, 14772 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14773 New->getLocation(), New->getReturnTypeSourceRange(), 14774 New->getDeclName(), nullptr)) { 14775 // FIXME: this note won't trigger for delayed access control 14776 // diagnostics, and it's impossible to get an undelayed error 14777 // here from access control during the original parse because 14778 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14779 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14780 << Old->getReturnTypeSourceRange(); 14781 return true; 14782 } 14783 } 14784 14785 // The qualifiers of the return types must be the same. 14786 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14787 Diag(New->getLocation(), 14788 diag::err_covariant_return_type_different_qualifications) 14789 << New->getDeclName() << NewTy << OldTy 14790 << New->getReturnTypeSourceRange(); 14791 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14792 << Old->getReturnTypeSourceRange(); 14793 return true; 14794 } 14795 14796 14797 // The new class type must have the same or less qualifiers as the old type. 14798 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14799 Diag(New->getLocation(), 14800 diag::err_covariant_return_type_class_type_more_qualified) 14801 << New->getDeclName() << NewTy << OldTy 14802 << New->getReturnTypeSourceRange(); 14803 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14804 << Old->getReturnTypeSourceRange(); 14805 return true; 14806 } 14807 14808 return false; 14809 } 14810 14811 /// Mark the given method pure. 14812 /// 14813 /// \param Method the method to be marked pure. 14814 /// 14815 /// \param InitRange the source range that covers the "0" initializer. 14816 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14817 SourceLocation EndLoc = InitRange.getEnd(); 14818 if (EndLoc.isValid()) 14819 Method->setRangeEnd(EndLoc); 14820 14821 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14822 Method->setPure(); 14823 return false; 14824 } 14825 14826 if (!Method->isInvalidDecl()) 14827 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14828 << Method->getDeclName() << InitRange; 14829 return true; 14830 } 14831 14832 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14833 if (D->getFriendObjectKind()) 14834 Diag(D->getLocation(), diag::err_pure_friend); 14835 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14836 CheckPureMethod(M, ZeroLoc); 14837 else 14838 Diag(D->getLocation(), diag::err_illegal_initializer); 14839 } 14840 14841 /// Determine whether the given declaration is a global variable or 14842 /// static data member. 14843 static bool isNonlocalVariable(const Decl *D) { 14844 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14845 return Var->hasGlobalStorage(); 14846 14847 return false; 14848 } 14849 14850 /// Invoked when we are about to parse an initializer for the declaration 14851 /// 'Dcl'. 14852 /// 14853 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14854 /// static data member of class X, names should be looked up in the scope of 14855 /// class X. If the declaration had a scope specifier, a scope will have 14856 /// been created and passed in for this purpose. Otherwise, S will be null. 14857 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14858 // If there is no declaration, there was an error parsing it. 14859 if (!D || D->isInvalidDecl()) 14860 return; 14861 14862 // We will always have a nested name specifier here, but this declaration 14863 // might not be out of line if the specifier names the current namespace: 14864 // extern int n; 14865 // int ::n = 0; 14866 if (S && D->isOutOfLine()) 14867 EnterDeclaratorContext(S, D->getDeclContext()); 14868 14869 // If we are parsing the initializer for a static data member, push a 14870 // new expression evaluation context that is associated with this static 14871 // data member. 14872 if (isNonlocalVariable(D)) 14873 PushExpressionEvaluationContext( 14874 ExpressionEvaluationContext::PotentiallyEvaluated, D); 14875 } 14876 14877 /// Invoked after we are finished parsing an initializer for the declaration D. 14878 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14879 // If there is no declaration, there was an error parsing it. 14880 if (!D || D->isInvalidDecl()) 14881 return; 14882 14883 if (isNonlocalVariable(D)) 14884 PopExpressionEvaluationContext(); 14885 14886 if (S && D->isOutOfLine()) 14887 ExitDeclaratorContext(S); 14888 } 14889 14890 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14891 /// C++ if/switch/while/for statement. 14892 /// e.g: "if (int x = f()) {...}" 14893 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14894 // C++ 6.4p2: 14895 // The declarator shall not specify a function or an array. 14896 // The type-specifier-seq shall not contain typedef and shall not declare a 14897 // new class or enumeration. 14898 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14899 "Parser allowed 'typedef' as storage class of condition decl."); 14900 14901 Decl *Dcl = ActOnDeclarator(S, D); 14902 if (!Dcl) 14903 return true; 14904 14905 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 14906 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 14907 << D.getSourceRange(); 14908 return true; 14909 } 14910 14911 return Dcl; 14912 } 14913 14914 void Sema::LoadExternalVTableUses() { 14915 if (!ExternalSource) 14916 return; 14917 14918 SmallVector<ExternalVTableUse, 4> VTables; 14919 ExternalSource->ReadUsedVTables(VTables); 14920 SmallVector<VTableUse, 4> NewUses; 14921 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 14922 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 14923 = VTablesUsed.find(VTables[I].Record); 14924 // Even if a definition wasn't required before, it may be required now. 14925 if (Pos != VTablesUsed.end()) { 14926 if (!Pos->second && VTables[I].DefinitionRequired) 14927 Pos->second = true; 14928 continue; 14929 } 14930 14931 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 14932 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 14933 } 14934 14935 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 14936 } 14937 14938 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 14939 bool DefinitionRequired) { 14940 // Ignore any vtable uses in unevaluated operands or for classes that do 14941 // not have a vtable. 14942 if (!Class->isDynamicClass() || Class->isDependentContext() || 14943 CurContext->isDependentContext() || isUnevaluatedContext()) 14944 return; 14945 // Do not mark as used if compiling for the device outside of the target 14946 // region. 14947 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 14948 !isInOpenMPDeclareTargetContext() && 14949 !isInOpenMPTargetExecutionDirective()) 14950 return; 14951 14952 // Try to insert this class into the map. 14953 LoadExternalVTableUses(); 14954 Class = Class->getCanonicalDecl(); 14955 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 14956 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 14957 if (!Pos.second) { 14958 // If we already had an entry, check to see if we are promoting this vtable 14959 // to require a definition. If so, we need to reappend to the VTableUses 14960 // list, since we may have already processed the first entry. 14961 if (DefinitionRequired && !Pos.first->second) { 14962 Pos.first->second = true; 14963 } else { 14964 // Otherwise, we can early exit. 14965 return; 14966 } 14967 } else { 14968 // The Microsoft ABI requires that we perform the destructor body 14969 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 14970 // the deleting destructor is emitted with the vtable, not with the 14971 // destructor definition as in the Itanium ABI. 14972 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14973 CXXDestructorDecl *DD = Class->getDestructor(); 14974 if (DD && DD->isVirtual() && !DD->isDeleted()) { 14975 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 14976 // If this is an out-of-line declaration, marking it referenced will 14977 // not do anything. Manually call CheckDestructor to look up operator 14978 // delete(). 14979 ContextRAII SavedContext(*this, DD); 14980 CheckDestructor(DD); 14981 } else { 14982 MarkFunctionReferenced(Loc, Class->getDestructor()); 14983 } 14984 } 14985 } 14986 } 14987 14988 // Local classes need to have their virtual members marked 14989 // immediately. For all other classes, we mark their virtual members 14990 // at the end of the translation unit. 14991 if (Class->isLocalClass()) 14992 MarkVirtualMembersReferenced(Loc, Class); 14993 else 14994 VTableUses.push_back(std::make_pair(Class, Loc)); 14995 } 14996 14997 bool Sema::DefineUsedVTables() { 14998 LoadExternalVTableUses(); 14999 if (VTableUses.empty()) 15000 return false; 15001 15002 // Note: The VTableUses vector could grow as a result of marking 15003 // the members of a class as "used", so we check the size each 15004 // time through the loop and prefer indices (which are stable) to 15005 // iterators (which are not). 15006 bool DefinedAnything = false; 15007 for (unsigned I = 0; I != VTableUses.size(); ++I) { 15008 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 15009 if (!Class) 15010 continue; 15011 TemplateSpecializationKind ClassTSK = 15012 Class->getTemplateSpecializationKind(); 15013 15014 SourceLocation Loc = VTableUses[I].second; 15015 15016 bool DefineVTable = true; 15017 15018 // If this class has a key function, but that key function is 15019 // defined in another translation unit, we don't need to emit the 15020 // vtable even though we're using it. 15021 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 15022 if (KeyFunction && !KeyFunction->hasBody()) { 15023 // The key function is in another translation unit. 15024 DefineVTable = false; 15025 TemplateSpecializationKind TSK = 15026 KeyFunction->getTemplateSpecializationKind(); 15027 assert(TSK != TSK_ExplicitInstantiationDefinition && 15028 TSK != TSK_ImplicitInstantiation && 15029 "Instantiations don't have key functions"); 15030 (void)TSK; 15031 } else if (!KeyFunction) { 15032 // If we have a class with no key function that is the subject 15033 // of an explicit instantiation declaration, suppress the 15034 // vtable; it will live with the explicit instantiation 15035 // definition. 15036 bool IsExplicitInstantiationDeclaration = 15037 ClassTSK == TSK_ExplicitInstantiationDeclaration; 15038 for (auto R : Class->redecls()) { 15039 TemplateSpecializationKind TSK 15040 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 15041 if (TSK == TSK_ExplicitInstantiationDeclaration) 15042 IsExplicitInstantiationDeclaration = true; 15043 else if (TSK == TSK_ExplicitInstantiationDefinition) { 15044 IsExplicitInstantiationDeclaration = false; 15045 break; 15046 } 15047 } 15048 15049 if (IsExplicitInstantiationDeclaration) 15050 DefineVTable = false; 15051 } 15052 15053 // The exception specifications for all virtual members may be needed even 15054 // if we are not providing an authoritative form of the vtable in this TU. 15055 // We may choose to emit it available_externally anyway. 15056 if (!DefineVTable) { 15057 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 15058 continue; 15059 } 15060 15061 // Mark all of the virtual members of this class as referenced, so 15062 // that we can build a vtable. Then, tell the AST consumer that a 15063 // vtable for this class is required. 15064 DefinedAnything = true; 15065 MarkVirtualMembersReferenced(Loc, Class); 15066 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 15067 if (VTablesUsed[Canonical]) 15068 Consumer.HandleVTable(Class); 15069 15070 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 15071 // no key function or the key function is inlined. Don't warn in C++ ABIs 15072 // that lack key functions, since the user won't be able to make one. 15073 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 15074 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 15075 const FunctionDecl *KeyFunctionDef = nullptr; 15076 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 15077 KeyFunctionDef->isInlined())) { 15078 Diag(Class->getLocation(), 15079 ClassTSK == TSK_ExplicitInstantiationDefinition 15080 ? diag::warn_weak_template_vtable 15081 : diag::warn_weak_vtable) 15082 << Class; 15083 } 15084 } 15085 } 15086 VTableUses.clear(); 15087 15088 return DefinedAnything; 15089 } 15090 15091 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 15092 const CXXRecordDecl *RD) { 15093 for (const auto *I : RD->methods()) 15094 if (I->isVirtual() && !I->isPure()) 15095 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 15096 } 15097 15098 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 15099 const CXXRecordDecl *RD) { 15100 // Mark all functions which will appear in RD's vtable as used. 15101 CXXFinalOverriderMap FinalOverriders; 15102 RD->getFinalOverriders(FinalOverriders); 15103 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 15104 E = FinalOverriders.end(); 15105 I != E; ++I) { 15106 for (OverridingMethods::const_iterator OI = I->second.begin(), 15107 OE = I->second.end(); 15108 OI != OE; ++OI) { 15109 assert(OI->second.size() > 0 && "no final overrider"); 15110 CXXMethodDecl *Overrider = OI->second.front().Method; 15111 15112 // C++ [basic.def.odr]p2: 15113 // [...] A virtual member function is used if it is not pure. [...] 15114 if (!Overrider->isPure()) 15115 MarkFunctionReferenced(Loc, Overrider); 15116 } 15117 } 15118 15119 // Only classes that have virtual bases need a VTT. 15120 if (RD->getNumVBases() == 0) 15121 return; 15122 15123 for (const auto &I : RD->bases()) { 15124 const CXXRecordDecl *Base = 15125 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 15126 if (Base->getNumVBases() == 0) 15127 continue; 15128 MarkVirtualMembersReferenced(Loc, Base); 15129 } 15130 } 15131 15132 /// SetIvarInitializers - This routine builds initialization ASTs for the 15133 /// Objective-C implementation whose ivars need be initialized. 15134 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 15135 if (!getLangOpts().CPlusPlus) 15136 return; 15137 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 15138 SmallVector<ObjCIvarDecl*, 8> ivars; 15139 CollectIvarsToConstructOrDestruct(OID, ivars); 15140 if (ivars.empty()) 15141 return; 15142 SmallVector<CXXCtorInitializer*, 32> AllToInit; 15143 for (unsigned i = 0; i < ivars.size(); i++) { 15144 FieldDecl *Field = ivars[i]; 15145 if (Field->isInvalidDecl()) 15146 continue; 15147 15148 CXXCtorInitializer *Member; 15149 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 15150 InitializationKind InitKind = 15151 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 15152 15153 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 15154 ExprResult MemberInit = 15155 InitSeq.Perform(*this, InitEntity, InitKind, None); 15156 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 15157 // Note, MemberInit could actually come back empty if no initialization 15158 // is required (e.g., because it would call a trivial default constructor) 15159 if (!MemberInit.get() || MemberInit.isInvalid()) 15160 continue; 15161 15162 Member = 15163 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 15164 SourceLocation(), 15165 MemberInit.getAs<Expr>(), 15166 SourceLocation()); 15167 AllToInit.push_back(Member); 15168 15169 // Be sure that the destructor is accessible and is marked as referenced. 15170 if (const RecordType *RecordTy = 15171 Context.getBaseElementType(Field->getType()) 15172 ->getAs<RecordType>()) { 15173 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 15174 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 15175 MarkFunctionReferenced(Field->getLocation(), Destructor); 15176 CheckDestructorAccess(Field->getLocation(), Destructor, 15177 PDiag(diag::err_access_dtor_ivar) 15178 << Context.getBaseElementType(Field->getType())); 15179 } 15180 } 15181 } 15182 ObjCImplementation->setIvarInitializers(Context, 15183 AllToInit.data(), AllToInit.size()); 15184 } 15185 } 15186 15187 static 15188 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 15189 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 15190 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 15191 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 15192 Sema &S) { 15193 if (Ctor->isInvalidDecl()) 15194 return; 15195 15196 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 15197 15198 // Target may not be determinable yet, for instance if this is a dependent 15199 // call in an uninstantiated template. 15200 if (Target) { 15201 const FunctionDecl *FNTarget = nullptr; 15202 (void)Target->hasBody(FNTarget); 15203 Target = const_cast<CXXConstructorDecl*>( 15204 cast_or_null<CXXConstructorDecl>(FNTarget)); 15205 } 15206 15207 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 15208 // Avoid dereferencing a null pointer here. 15209 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 15210 15211 if (!Current.insert(Canonical).second) 15212 return; 15213 15214 // We know that beyond here, we aren't chaining into a cycle. 15215 if (!Target || !Target->isDelegatingConstructor() || 15216 Target->isInvalidDecl() || Valid.count(TCanonical)) { 15217 Valid.insert(Current.begin(), Current.end()); 15218 Current.clear(); 15219 // We've hit a cycle. 15220 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 15221 Current.count(TCanonical)) { 15222 // If we haven't diagnosed this cycle yet, do so now. 15223 if (!Invalid.count(TCanonical)) { 15224 S.Diag((*Ctor->init_begin())->getSourceLocation(), 15225 diag::warn_delegating_ctor_cycle) 15226 << Ctor; 15227 15228 // Don't add a note for a function delegating directly to itself. 15229 if (TCanonical != Canonical) 15230 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 15231 15232 CXXConstructorDecl *C = Target; 15233 while (C->getCanonicalDecl() != Canonical) { 15234 const FunctionDecl *FNTarget = nullptr; 15235 (void)C->getTargetConstructor()->hasBody(FNTarget); 15236 assert(FNTarget && "Ctor cycle through bodiless function"); 15237 15238 C = const_cast<CXXConstructorDecl*>( 15239 cast<CXXConstructorDecl>(FNTarget)); 15240 S.Diag(C->getLocation(), diag::note_which_delegates_to); 15241 } 15242 } 15243 15244 Invalid.insert(Current.begin(), Current.end()); 15245 Current.clear(); 15246 } else { 15247 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 15248 } 15249 } 15250 15251 15252 void Sema::CheckDelegatingCtorCycles() { 15253 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 15254 15255 for (DelegatingCtorDeclsType::iterator 15256 I = DelegatingCtorDecls.begin(ExternalSource), 15257 E = DelegatingCtorDecls.end(); 15258 I != E; ++I) 15259 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 15260 15261 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 15262 (*CI)->setInvalidDecl(); 15263 } 15264 15265 namespace { 15266 /// AST visitor that finds references to the 'this' expression. 15267 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 15268 Sema &S; 15269 15270 public: 15271 explicit FindCXXThisExpr(Sema &S) : S(S) { } 15272 15273 bool VisitCXXThisExpr(CXXThisExpr *E) { 15274 S.Diag(E->getLocation(), diag::err_this_static_member_func) 15275 << E->isImplicit(); 15276 return false; 15277 } 15278 }; 15279 } 15280 15281 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 15282 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15283 if (!TSInfo) 15284 return false; 15285 15286 TypeLoc TL = TSInfo->getTypeLoc(); 15287 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15288 if (!ProtoTL) 15289 return false; 15290 15291 // C++11 [expr.prim.general]p3: 15292 // [The expression this] shall not appear before the optional 15293 // cv-qualifier-seq and it shall not appear within the declaration of a 15294 // static member function (although its type and value category are defined 15295 // within a static member function as they are within a non-static member 15296 // function). [ Note: this is because declaration matching does not occur 15297 // until the complete declarator is known. - end note ] 15298 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15299 FindCXXThisExpr Finder(*this); 15300 15301 // If the return type came after the cv-qualifier-seq, check it now. 15302 if (Proto->hasTrailingReturn() && 15303 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 15304 return true; 15305 15306 // Check the exception specification. 15307 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 15308 return true; 15309 15310 return checkThisInStaticMemberFunctionAttributes(Method); 15311 } 15312 15313 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 15314 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15315 if (!TSInfo) 15316 return false; 15317 15318 TypeLoc TL = TSInfo->getTypeLoc(); 15319 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15320 if (!ProtoTL) 15321 return false; 15322 15323 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15324 FindCXXThisExpr Finder(*this); 15325 15326 switch (Proto->getExceptionSpecType()) { 15327 case EST_Unparsed: 15328 case EST_Uninstantiated: 15329 case EST_Unevaluated: 15330 case EST_BasicNoexcept: 15331 case EST_DynamicNone: 15332 case EST_MSAny: 15333 case EST_None: 15334 break; 15335 15336 case EST_DependentNoexcept: 15337 case EST_NoexceptFalse: 15338 case EST_NoexceptTrue: 15339 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 15340 return true; 15341 LLVM_FALLTHROUGH; 15342 15343 case EST_Dynamic: 15344 for (const auto &E : Proto->exceptions()) { 15345 if (!Finder.TraverseType(E)) 15346 return true; 15347 } 15348 break; 15349 } 15350 15351 return false; 15352 } 15353 15354 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 15355 FindCXXThisExpr Finder(*this); 15356 15357 // Check attributes. 15358 for (const auto *A : Method->attrs()) { 15359 // FIXME: This should be emitted by tblgen. 15360 Expr *Arg = nullptr; 15361 ArrayRef<Expr *> Args; 15362 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 15363 Arg = G->getArg(); 15364 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 15365 Arg = G->getArg(); 15366 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 15367 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 15368 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 15369 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 15370 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 15371 Arg = ETLF->getSuccessValue(); 15372 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 15373 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 15374 Arg = STLF->getSuccessValue(); 15375 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 15376 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 15377 Arg = LR->getArg(); 15378 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 15379 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 15380 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 15381 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15382 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 15383 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15384 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 15385 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15386 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 15387 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15388 15389 if (Arg && !Finder.TraverseStmt(Arg)) 15390 return true; 15391 15392 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 15393 if (!Finder.TraverseStmt(Args[I])) 15394 return true; 15395 } 15396 } 15397 15398 return false; 15399 } 15400 15401 void Sema::checkExceptionSpecification( 15402 bool IsTopLevel, ExceptionSpecificationType EST, 15403 ArrayRef<ParsedType> DynamicExceptions, 15404 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 15405 SmallVectorImpl<QualType> &Exceptions, 15406 FunctionProtoType::ExceptionSpecInfo &ESI) { 15407 Exceptions.clear(); 15408 ESI.Type = EST; 15409 if (EST == EST_Dynamic) { 15410 Exceptions.reserve(DynamicExceptions.size()); 15411 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 15412 // FIXME: Preserve type source info. 15413 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 15414 15415 if (IsTopLevel) { 15416 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 15417 collectUnexpandedParameterPacks(ET, Unexpanded); 15418 if (!Unexpanded.empty()) { 15419 DiagnoseUnexpandedParameterPacks( 15420 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 15421 Unexpanded); 15422 continue; 15423 } 15424 } 15425 15426 // Check that the type is valid for an exception spec, and 15427 // drop it if not. 15428 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 15429 Exceptions.push_back(ET); 15430 } 15431 ESI.Exceptions = Exceptions; 15432 return; 15433 } 15434 15435 if (isComputedNoexcept(EST)) { 15436 assert((NoexceptExpr->isTypeDependent() || 15437 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 15438 Context.BoolTy) && 15439 "Parser should have made sure that the expression is boolean"); 15440 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 15441 ESI.Type = EST_BasicNoexcept; 15442 return; 15443 } 15444 15445 ESI.NoexceptExpr = NoexceptExpr; 15446 return; 15447 } 15448 } 15449 15450 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 15451 ExceptionSpecificationType EST, 15452 SourceRange SpecificationRange, 15453 ArrayRef<ParsedType> DynamicExceptions, 15454 ArrayRef<SourceRange> DynamicExceptionRanges, 15455 Expr *NoexceptExpr) { 15456 if (!MethodD) 15457 return; 15458 15459 // Dig out the method we're referring to. 15460 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 15461 MethodD = FunTmpl->getTemplatedDecl(); 15462 15463 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 15464 if (!Method) 15465 return; 15466 15467 // Check the exception specification. 15468 llvm::SmallVector<QualType, 4> Exceptions; 15469 FunctionProtoType::ExceptionSpecInfo ESI; 15470 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 15471 DynamicExceptionRanges, NoexceptExpr, Exceptions, 15472 ESI); 15473 15474 // Update the exception specification on the function type. 15475 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 15476 15477 if (Method->isStatic()) 15478 checkThisInStaticMemberFunctionExceptionSpec(Method); 15479 15480 if (Method->isVirtual()) { 15481 // Check overrides, which we previously had to delay. 15482 for (const CXXMethodDecl *O : Method->overridden_methods()) 15483 CheckOverridingFunctionExceptionSpec(Method, O); 15484 } 15485 } 15486 15487 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 15488 /// 15489 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 15490 SourceLocation DeclStart, Declarator &D, 15491 Expr *BitWidth, 15492 InClassInitStyle InitStyle, 15493 AccessSpecifier AS, 15494 const ParsedAttr &MSPropertyAttr) { 15495 IdentifierInfo *II = D.getIdentifier(); 15496 if (!II) { 15497 Diag(DeclStart, diag::err_anonymous_property); 15498 return nullptr; 15499 } 15500 SourceLocation Loc = D.getIdentifierLoc(); 15501 15502 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15503 QualType T = TInfo->getType(); 15504 if (getLangOpts().CPlusPlus) { 15505 CheckExtraCXXDefaultArguments(D); 15506 15507 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15508 UPPC_DataMemberType)) { 15509 D.setInvalidType(); 15510 T = Context.IntTy; 15511 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15512 } 15513 } 15514 15515 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15516 15517 if (D.getDeclSpec().isInlineSpecified()) 15518 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15519 << getLangOpts().CPlusPlus17; 15520 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15521 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15522 diag::err_invalid_thread) 15523 << DeclSpec::getSpecifierName(TSCS); 15524 15525 // Check to see if this name was declared as a member previously 15526 NamedDecl *PrevDecl = nullptr; 15527 LookupResult Previous(*this, II, Loc, LookupMemberName, 15528 ForVisibleRedeclaration); 15529 LookupName(Previous, S); 15530 switch (Previous.getResultKind()) { 15531 case LookupResult::Found: 15532 case LookupResult::FoundUnresolvedValue: 15533 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15534 break; 15535 15536 case LookupResult::FoundOverloaded: 15537 PrevDecl = Previous.getRepresentativeDecl(); 15538 break; 15539 15540 case LookupResult::NotFound: 15541 case LookupResult::NotFoundInCurrentInstantiation: 15542 case LookupResult::Ambiguous: 15543 break; 15544 } 15545 15546 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15547 // Maybe we will complain about the shadowed template parameter. 15548 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15549 // Just pretend that we didn't see the previous declaration. 15550 PrevDecl = nullptr; 15551 } 15552 15553 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15554 PrevDecl = nullptr; 15555 15556 SourceLocation TSSL = D.getBeginLoc(); 15557 MSPropertyDecl *NewPD = 15558 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 15559 MSPropertyAttr.getPropertyDataGetter(), 15560 MSPropertyAttr.getPropertyDataSetter()); 15561 ProcessDeclAttributes(TUScope, NewPD, D); 15562 NewPD->setAccess(AS); 15563 15564 if (NewPD->isInvalidDecl()) 15565 Record->setInvalidDecl(); 15566 15567 if (D.getDeclSpec().isModulePrivateSpecified()) 15568 NewPD->setModulePrivate(); 15569 15570 if (NewPD->isInvalidDecl() && PrevDecl) { 15571 // Don't introduce NewFD into scope; there's already something 15572 // with the same name in the same scope. 15573 } else if (II) { 15574 PushOnScopeChains(NewPD, S); 15575 } else 15576 Record->addDecl(NewPD); 15577 15578 return NewPD; 15579 } 15580