1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for C++ declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/RecursiveASTVisitor.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeLoc.h" 26 #include "clang/AST/TypeOrdering.h" 27 #include "clang/Basic/PartialDiagnostic.h" 28 #include "clang/Basic/TargetInfo.h" 29 #include "clang/Lex/LiteralSupport.h" 30 #include "clang/Lex/Preprocessor.h" 31 #include "clang/Sema/CXXFieldCollector.h" 32 #include "clang/Sema/DeclSpec.h" 33 #include "clang/Sema/Initialization.h" 34 #include "clang/Sema/Lookup.h" 35 #include "clang/Sema/ParsedTemplate.h" 36 #include "clang/Sema/Scope.h" 37 #include "clang/Sema/ScopeInfo.h" 38 #include "clang/Sema/SemaInternal.h" 39 #include "clang/Sema/Template.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/SmallString.h" 42 #include "llvm/ADT/StringExtras.h" 43 #include <map> 44 #include <set> 45 46 using namespace clang; 47 48 //===----------------------------------------------------------------------===// 49 // CheckDefaultArgumentVisitor 50 //===----------------------------------------------------------------------===// 51 52 namespace { 53 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 54 /// the default argument of a parameter to determine whether it 55 /// contains any ill-formed subexpressions. For example, this will 56 /// diagnose the use of local variables or parameters within the 57 /// default argument expression. 58 class CheckDefaultArgumentVisitor 59 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 60 Expr *DefaultArg; 61 Sema *S; 62 63 public: 64 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 65 : DefaultArg(defarg), S(s) {} 66 67 bool VisitExpr(Expr *Node); 68 bool VisitDeclRefExpr(DeclRefExpr *DRE); 69 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 70 bool VisitLambdaExpr(LambdaExpr *Lambda); 71 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 72 }; 73 74 /// VisitExpr - Visit all of the children of this expression. 75 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 76 bool IsInvalid = false; 77 for (Stmt *SubStmt : Node->children()) 78 IsInvalid |= Visit(SubStmt); 79 return IsInvalid; 80 } 81 82 /// VisitDeclRefExpr - Visit a reference to a declaration, to 83 /// determine whether this declaration can be used in the default 84 /// argument expression. 85 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 86 NamedDecl *Decl = DRE->getDecl(); 87 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 88 // C++ [dcl.fct.default]p9 89 // Default arguments are evaluated each time the function is 90 // called. The order of evaluation of function arguments is 91 // unspecified. Consequently, parameters of a function shall not 92 // be used in default argument expressions, even if they are not 93 // evaluated. Parameters of a function declared before a default 94 // argument expression are in scope and can hide namespace and 95 // class member names. 96 return S->Diag(DRE->getLocStart(), 97 diag::err_param_default_argument_references_param) 98 << Param->getDeclName() << DefaultArg->getSourceRange(); 99 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 100 // C++ [dcl.fct.default]p7 101 // Local variables shall not be used in default argument 102 // expressions. 103 if (VDecl->isLocalVarDecl()) 104 return S->Diag(DRE->getLocStart(), 105 diag::err_param_default_argument_references_local) 106 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 107 } 108 109 return false; 110 } 111 112 /// VisitCXXThisExpr - Visit a C++ "this" expression. 113 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 114 // C++ [dcl.fct.default]p8: 115 // The keyword this shall not be used in a default argument of a 116 // member function. 117 return S->Diag(ThisE->getLocStart(), 118 diag::err_param_default_argument_references_this) 119 << ThisE->getSourceRange(); 120 } 121 122 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 123 bool Invalid = false; 124 for (PseudoObjectExpr::semantics_iterator 125 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 126 Expr *E = *i; 127 128 // Look through bindings. 129 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 130 E = OVE->getSourceExpr(); 131 assert(E && "pseudo-object binding without source expression?"); 132 } 133 134 Invalid |= Visit(E); 135 } 136 return Invalid; 137 } 138 139 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 140 // C++11 [expr.lambda.prim]p13: 141 // A lambda-expression appearing in a default argument shall not 142 // implicitly or explicitly capture any entity. 143 if (Lambda->capture_begin() == Lambda->capture_end()) 144 return false; 145 146 return S->Diag(Lambda->getLocStart(), 147 diag::err_lambda_capture_default_arg); 148 } 149 } 150 151 void 152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 153 const CXXMethodDecl *Method) { 154 // If we have an MSAny spec already, don't bother. 155 if (!Method || ComputedEST == EST_MSAny) 156 return; 157 158 const FunctionProtoType *Proto 159 = Method->getType()->getAs<FunctionProtoType>(); 160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 161 if (!Proto) 162 return; 163 164 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 165 166 // If we have a throw-all spec at this point, ignore the function. 167 if (ComputedEST == EST_None) 168 return; 169 170 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 171 EST = EST_BasicNoexcept; 172 173 switch(EST) { 174 // If this function can throw any exceptions, make a note of that. 175 case EST_MSAny: 176 case EST_None: 177 ClearExceptions(); 178 ComputedEST = EST; 179 return; 180 // FIXME: If the call to this decl is using any of its default arguments, we 181 // need to search them for potentially-throwing calls. 182 // If this function has a basic noexcept, it doesn't affect the outcome. 183 case EST_BasicNoexcept: 184 return; 185 // If we're still at noexcept(true) and there's a nothrow() callee, 186 // change to that specification. 187 case EST_DynamicNone: 188 if (ComputedEST == EST_BasicNoexcept) 189 ComputedEST = EST_DynamicNone; 190 return; 191 // Check out noexcept specs. 192 case EST_ComputedNoexcept: 193 { 194 FunctionProtoType::NoexceptResult NR = 195 Proto->getNoexceptSpec(Self->Context); 196 assert(NR != FunctionProtoType::NR_NoNoexcept && 197 "Must have noexcept result for EST_ComputedNoexcept."); 198 assert(NR != FunctionProtoType::NR_Dependent && 199 "Should not generate implicit declarations for dependent cases, " 200 "and don't know how to handle them anyway."); 201 // noexcept(false) -> no spec on the new function 202 if (NR == FunctionProtoType::NR_Throw) { 203 ClearExceptions(); 204 ComputedEST = EST_None; 205 } 206 // noexcept(true) won't change anything either. 207 return; 208 } 209 default: 210 break; 211 } 212 assert(EST == EST_Dynamic && "EST case not considered earlier."); 213 assert(ComputedEST != EST_None && 214 "Shouldn't collect exceptions when throw-all is guaranteed."); 215 ComputedEST = EST_Dynamic; 216 // Record the exceptions in this function's exception specification. 217 for (const auto &E : Proto->exceptions()) 218 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 219 Exceptions.push_back(E); 220 } 221 222 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 223 if (!E || ComputedEST == EST_MSAny) 224 return; 225 226 // FIXME: 227 // 228 // C++0x [except.spec]p14: 229 // [An] implicit exception-specification specifies the type-id T if and 230 // only if T is allowed by the exception-specification of a function directly 231 // invoked by f's implicit definition; f shall allow all exceptions if any 232 // function it directly invokes allows all exceptions, and f shall allow no 233 // exceptions if every function it directly invokes allows no exceptions. 234 // 235 // Note in particular that if an implicit exception-specification is generated 236 // for a function containing a throw-expression, that specification can still 237 // be noexcept(true). 238 // 239 // Note also that 'directly invoked' is not defined in the standard, and there 240 // is no indication that we should only consider potentially-evaluated calls. 241 // 242 // Ultimately we should implement the intent of the standard: the exception 243 // specification should be the set of exceptions which can be thrown by the 244 // implicit definition. For now, we assume that any non-nothrow expression can 245 // throw any exception. 246 247 if (Self->canThrow(E)) 248 ComputedEST = EST_None; 249 } 250 251 bool 252 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 253 SourceLocation EqualLoc) { 254 if (RequireCompleteType(Param->getLocation(), Param->getType(), 255 diag::err_typecheck_decl_incomplete_type)) { 256 Param->setInvalidDecl(); 257 return true; 258 } 259 260 // C++ [dcl.fct.default]p5 261 // A default argument expression is implicitly converted (clause 262 // 4) to the parameter type. The default argument expression has 263 // the same semantic constraints as the initializer expression in 264 // a declaration of a variable of the parameter type, using the 265 // copy-initialization semantics (8.5). 266 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 267 Param); 268 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 269 EqualLoc); 270 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 271 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 272 if (Result.isInvalid()) 273 return true; 274 Arg = Result.getAs<Expr>(); 275 276 CheckCompletedExpr(Arg, EqualLoc); 277 Arg = MaybeCreateExprWithCleanups(Arg); 278 279 // Okay: add the default argument to the parameter 280 Param->setDefaultArg(Arg); 281 282 // We have already instantiated this parameter; provide each of the 283 // instantiations with the uninstantiated default argument. 284 UnparsedDefaultArgInstantiationsMap::iterator InstPos 285 = UnparsedDefaultArgInstantiations.find(Param); 286 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 287 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 288 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 289 290 // We're done tracking this parameter's instantiations. 291 UnparsedDefaultArgInstantiations.erase(InstPos); 292 } 293 294 return false; 295 } 296 297 /// ActOnParamDefaultArgument - Check whether the default argument 298 /// provided for a function parameter is well-formed. If so, attach it 299 /// to the parameter declaration. 300 void 301 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 302 Expr *DefaultArg) { 303 if (!param || !DefaultArg) 304 return; 305 306 ParmVarDecl *Param = cast<ParmVarDecl>(param); 307 UnparsedDefaultArgLocs.erase(Param); 308 309 // Default arguments are only permitted in C++ 310 if (!getLangOpts().CPlusPlus) { 311 Diag(EqualLoc, diag::err_param_default_argument) 312 << DefaultArg->getSourceRange(); 313 Param->setInvalidDecl(); 314 return; 315 } 316 317 // Check for unexpanded parameter packs. 318 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 319 Param->setInvalidDecl(); 320 return; 321 } 322 323 // C++11 [dcl.fct.default]p3 324 // A default argument expression [...] shall not be specified for a 325 // parameter pack. 326 if (Param->isParameterPack()) { 327 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 328 << DefaultArg->getSourceRange(); 329 return; 330 } 331 332 // Check that the default argument is well-formed 333 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 334 if (DefaultArgChecker.Visit(DefaultArg)) { 335 Param->setInvalidDecl(); 336 return; 337 } 338 339 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 340 } 341 342 /// ActOnParamUnparsedDefaultArgument - We've seen a default 343 /// argument for a function parameter, but we can't parse it yet 344 /// because we're inside a class definition. Note that this default 345 /// argument will be parsed later. 346 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 347 SourceLocation EqualLoc, 348 SourceLocation ArgLoc) { 349 if (!param) 350 return; 351 352 ParmVarDecl *Param = cast<ParmVarDecl>(param); 353 Param->setUnparsedDefaultArg(); 354 UnparsedDefaultArgLocs[Param] = ArgLoc; 355 } 356 357 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 358 /// the default argument for the parameter param failed. 359 void Sema::ActOnParamDefaultArgumentError(Decl *param, 360 SourceLocation EqualLoc) { 361 if (!param) 362 return; 363 364 ParmVarDecl *Param = cast<ParmVarDecl>(param); 365 Param->setInvalidDecl(); 366 UnparsedDefaultArgLocs.erase(Param); 367 Param->setDefaultArg(new(Context) 368 OpaqueValueExpr(EqualLoc, 369 Param->getType().getNonReferenceType(), 370 VK_RValue)); 371 } 372 373 /// CheckExtraCXXDefaultArguments - Check for any extra default 374 /// arguments in the declarator, which is not a function declaration 375 /// or definition and therefore is not permitted to have default 376 /// arguments. This routine should be invoked for every declarator 377 /// that is not a function declaration or definition. 378 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 379 // C++ [dcl.fct.default]p3 380 // A default argument expression shall be specified only in the 381 // parameter-declaration-clause of a function declaration or in a 382 // template-parameter (14.1). It shall not be specified for a 383 // parameter pack. If it is specified in a 384 // parameter-declaration-clause, it shall not occur within a 385 // declarator or abstract-declarator of a parameter-declaration. 386 bool MightBeFunction = D.isFunctionDeclarationContext(); 387 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 388 DeclaratorChunk &chunk = D.getTypeObject(i); 389 if (chunk.Kind == DeclaratorChunk::Function) { 390 if (MightBeFunction) { 391 // This is a function declaration. It can have default arguments, but 392 // keep looking in case its return type is a function type with default 393 // arguments. 394 MightBeFunction = false; 395 continue; 396 } 397 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 398 ++argIdx) { 399 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 400 if (Param->hasUnparsedDefaultArg()) { 401 std::unique_ptr<CachedTokens> Toks = 402 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 403 SourceRange SR; 404 if (Toks->size() > 1) 405 SR = SourceRange((*Toks)[1].getLocation(), 406 Toks->back().getLocation()); 407 else 408 SR = UnparsedDefaultArgLocs[Param]; 409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 410 << SR; 411 } else if (Param->getDefaultArg()) { 412 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 413 << Param->getDefaultArg()->getSourceRange(); 414 Param->setDefaultArg(nullptr); 415 } 416 } 417 } else if (chunk.Kind != DeclaratorChunk::Paren) { 418 MightBeFunction = false; 419 } 420 } 421 } 422 423 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 424 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 425 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 426 if (!PVD->hasDefaultArg()) 427 return false; 428 if (!PVD->hasInheritedDefaultArg()) 429 return true; 430 } 431 return false; 432 } 433 434 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 435 /// function, once we already know that they have the same 436 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 437 /// error, false otherwise. 438 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 439 Scope *S) { 440 bool Invalid = false; 441 442 // The declaration context corresponding to the scope is the semantic 443 // parent, unless this is a local function declaration, in which case 444 // it is that surrounding function. 445 DeclContext *ScopeDC = New->isLocalExternDecl() 446 ? New->getLexicalDeclContext() 447 : New->getDeclContext(); 448 449 // Find the previous declaration for the purpose of default arguments. 450 FunctionDecl *PrevForDefaultArgs = Old; 451 for (/**/; PrevForDefaultArgs; 452 // Don't bother looking back past the latest decl if this is a local 453 // extern declaration; nothing else could work. 454 PrevForDefaultArgs = New->isLocalExternDecl() 455 ? nullptr 456 : PrevForDefaultArgs->getPreviousDecl()) { 457 // Ignore hidden declarations. 458 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 459 continue; 460 461 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 462 !New->isCXXClassMember()) { 463 // Ignore default arguments of old decl if they are not in 464 // the same scope and this is not an out-of-line definition of 465 // a member function. 466 continue; 467 } 468 469 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 470 // If only one of these is a local function declaration, then they are 471 // declared in different scopes, even though isDeclInScope may think 472 // they're in the same scope. (If both are local, the scope check is 473 // sufficient, and if neither is local, then they are in the same scope.) 474 continue; 475 } 476 477 // We found the right previous declaration. 478 break; 479 } 480 481 // C++ [dcl.fct.default]p4: 482 // For non-template functions, default arguments can be added in 483 // later declarations of a function in the same 484 // scope. Declarations in different scopes have completely 485 // distinct sets of default arguments. That is, declarations in 486 // inner scopes do not acquire default arguments from 487 // declarations in outer scopes, and vice versa. In a given 488 // function declaration, all parameters subsequent to a 489 // parameter with a default argument shall have default 490 // arguments supplied in this or previous declarations. A 491 // default argument shall not be redefined by a later 492 // declaration (not even to the same value). 493 // 494 // C++ [dcl.fct.default]p6: 495 // Except for member functions of class templates, the default arguments 496 // in a member function definition that appears outside of the class 497 // definition are added to the set of default arguments provided by the 498 // member function declaration in the class definition. 499 for (unsigned p = 0, NumParams = PrevForDefaultArgs 500 ? PrevForDefaultArgs->getNumParams() 501 : 0; 502 p < NumParams; ++p) { 503 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 504 ParmVarDecl *NewParam = New->getParamDecl(p); 505 506 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 507 bool NewParamHasDfl = NewParam->hasDefaultArg(); 508 509 if (OldParamHasDfl && NewParamHasDfl) { 510 unsigned DiagDefaultParamID = 511 diag::err_param_default_argument_redefinition; 512 513 // MSVC accepts that default parameters be redefined for member functions 514 // of template class. The new default parameter's value is ignored. 515 Invalid = true; 516 if (getLangOpts().MicrosoftExt) { 517 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 518 if (MD && MD->getParent()->getDescribedClassTemplate()) { 519 // Merge the old default argument into the new parameter. 520 NewParam->setHasInheritedDefaultArg(); 521 if (OldParam->hasUninstantiatedDefaultArg()) 522 NewParam->setUninstantiatedDefaultArg( 523 OldParam->getUninstantiatedDefaultArg()); 524 else 525 NewParam->setDefaultArg(OldParam->getInit()); 526 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 527 Invalid = false; 528 } 529 } 530 531 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 532 // hint here. Alternatively, we could walk the type-source information 533 // for NewParam to find the last source location in the type... but it 534 // isn't worth the effort right now. This is the kind of test case that 535 // is hard to get right: 536 // int f(int); 537 // void g(int (*fp)(int) = f); 538 // void g(int (*fp)(int) = &f); 539 Diag(NewParam->getLocation(), DiagDefaultParamID) 540 << NewParam->getDefaultArgRange(); 541 542 // Look for the function declaration where the default argument was 543 // actually written, which may be a declaration prior to Old. 544 for (auto Older = PrevForDefaultArgs; 545 OldParam->hasInheritedDefaultArg(); /**/) { 546 Older = Older->getPreviousDecl(); 547 OldParam = Older->getParamDecl(p); 548 } 549 550 Diag(OldParam->getLocation(), diag::note_previous_definition) 551 << OldParam->getDefaultArgRange(); 552 } else if (OldParamHasDfl) { 553 // Merge the old default argument into the new parameter unless the new 554 // function is a friend declaration in a template class. In the latter 555 // case the default arguments will be inherited when the friend 556 // declaration will be instantiated. 557 if (New->getFriendObjectKind() == Decl::FOK_None || 558 !New->getLexicalDeclContext()->isDependentContext()) { 559 // It's important to use getInit() here; getDefaultArg() 560 // strips off any top-level ExprWithCleanups. 561 NewParam->setHasInheritedDefaultArg(); 562 if (OldParam->hasUnparsedDefaultArg()) 563 NewParam->setUnparsedDefaultArg(); 564 else if (OldParam->hasUninstantiatedDefaultArg()) 565 NewParam->setUninstantiatedDefaultArg( 566 OldParam->getUninstantiatedDefaultArg()); 567 else 568 NewParam->setDefaultArg(OldParam->getInit()); 569 } 570 } else if (NewParamHasDfl) { 571 if (New->getDescribedFunctionTemplate()) { 572 // Paragraph 4, quoted above, only applies to non-template functions. 573 Diag(NewParam->getLocation(), 574 diag::err_param_default_argument_template_redecl) 575 << NewParam->getDefaultArgRange(); 576 Diag(PrevForDefaultArgs->getLocation(), 577 diag::note_template_prev_declaration) 578 << false; 579 } else if (New->getTemplateSpecializationKind() 580 != TSK_ImplicitInstantiation && 581 New->getTemplateSpecializationKind() != TSK_Undeclared) { 582 // C++ [temp.expr.spec]p21: 583 // Default function arguments shall not be specified in a declaration 584 // or a definition for one of the following explicit specializations: 585 // - the explicit specialization of a function template; 586 // - the explicit specialization of a member function template; 587 // - the explicit specialization of a member function of a class 588 // template where the class template specialization to which the 589 // member function specialization belongs is implicitly 590 // instantiated. 591 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 592 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 593 << New->getDeclName() 594 << NewParam->getDefaultArgRange(); 595 } else if (New->getDeclContext()->isDependentContext()) { 596 // C++ [dcl.fct.default]p6 (DR217): 597 // Default arguments for a member function of a class template shall 598 // be specified on the initial declaration of the member function 599 // within the class template. 600 // 601 // Reading the tea leaves a bit in DR217 and its reference to DR205 602 // leads me to the conclusion that one cannot add default function 603 // arguments for an out-of-line definition of a member function of a 604 // dependent type. 605 int WhichKind = 2; 606 if (CXXRecordDecl *Record 607 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 608 if (Record->getDescribedClassTemplate()) 609 WhichKind = 0; 610 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 611 WhichKind = 1; 612 else 613 WhichKind = 2; 614 } 615 616 Diag(NewParam->getLocation(), 617 diag::err_param_default_argument_member_template_redecl) 618 << WhichKind 619 << NewParam->getDefaultArgRange(); 620 } 621 } 622 } 623 624 // DR1344: If a default argument is added outside a class definition and that 625 // default argument makes the function a special member function, the program 626 // is ill-formed. This can only happen for constructors. 627 if (isa<CXXConstructorDecl>(New) && 628 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 629 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 630 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 631 if (NewSM != OldSM) { 632 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 633 assert(NewParam->hasDefaultArg()); 634 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 635 << NewParam->getDefaultArgRange() << NewSM; 636 Diag(Old->getLocation(), diag::note_previous_declaration); 637 } 638 } 639 640 const FunctionDecl *Def; 641 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 642 // template has a constexpr specifier then all its declarations shall 643 // contain the constexpr specifier. 644 if (New->isConstexpr() != Old->isConstexpr()) { 645 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 646 << New << New->isConstexpr(); 647 Diag(Old->getLocation(), diag::note_previous_declaration); 648 Invalid = true; 649 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 650 Old->isDefined(Def) && 651 // If a friend function is inlined but does not have 'inline' 652 // specifier, it is a definition. Do not report attribute conflict 653 // in this case, redefinition will be diagnosed later. 654 (New->isInlineSpecified() || 655 New->getFriendObjectKind() == Decl::FOK_None)) { 656 // C++11 [dcl.fcn.spec]p4: 657 // If the definition of a function appears in a translation unit before its 658 // first declaration as inline, the program is ill-formed. 659 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 660 Diag(Def->getLocation(), diag::note_previous_definition); 661 Invalid = true; 662 } 663 664 // FIXME: It's not clear what should happen if multiple declarations of a 665 // deduction guide have different explicitness. For now at least we simply 666 // reject any case where the explicitness changes. 667 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New); 668 if (NewGuide && NewGuide->isExplicitSpecified() != 669 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) { 670 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch) 671 << NewGuide->isExplicitSpecified(); 672 Diag(Old->getLocation(), diag::note_previous_declaration); 673 } 674 675 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 676 // argument expression, that declaration shall be a definition and shall be 677 // the only declaration of the function or function template in the 678 // translation unit. 679 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 680 functionDeclHasDefaultArgument(Old)) { 681 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 682 Diag(Old->getLocation(), diag::note_previous_declaration); 683 Invalid = true; 684 } 685 686 return Invalid; 687 } 688 689 NamedDecl * 690 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 691 MultiTemplateParamsArg TemplateParamLists) { 692 assert(D.isDecompositionDeclarator()); 693 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 694 695 // The syntax only allows a decomposition declarator as a simple-declaration, 696 // a for-range-declaration, or a condition in Clang, but we parse it in more 697 // cases than that. 698 if (!D.mayHaveDecompositionDeclarator()) { 699 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 700 << Decomp.getSourceRange(); 701 return nullptr; 702 } 703 704 if (!TemplateParamLists.empty()) { 705 // FIXME: There's no rule against this, but there are also no rules that 706 // would actually make it usable, so we reject it for now. 707 Diag(TemplateParamLists.front()->getTemplateLoc(), 708 diag::err_decomp_decl_template); 709 return nullptr; 710 } 711 712 Diag(Decomp.getLSquareLoc(), 713 !getLangOpts().CPlusPlus17 714 ? diag::ext_decomp_decl 715 : D.getContext() == Declarator::ConditionContext 716 ? diag::ext_decomp_decl_cond 717 : diag::warn_cxx14_compat_decomp_decl) 718 << Decomp.getSourceRange(); 719 720 // The semantic context is always just the current context. 721 DeclContext *const DC = CurContext; 722 723 // C++1z [dcl.dcl]/8: 724 // The decl-specifier-seq shall contain only the type-specifier auto 725 // and cv-qualifiers. 726 auto &DS = D.getDeclSpec(); 727 { 728 SmallVector<StringRef, 8> BadSpecifiers; 729 SmallVector<SourceLocation, 8> BadSpecifierLocs; 730 if (auto SCS = DS.getStorageClassSpec()) { 731 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 732 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 733 } 734 if (auto TSCS = DS.getThreadStorageClassSpec()) { 735 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 736 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 737 } 738 if (DS.isConstexprSpecified()) { 739 BadSpecifiers.push_back("constexpr"); 740 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 741 } 742 if (DS.isInlineSpecified()) { 743 BadSpecifiers.push_back("inline"); 744 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 745 } 746 if (!BadSpecifiers.empty()) { 747 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 748 Err << (int)BadSpecifiers.size() 749 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 750 // Don't add FixItHints to remove the specifiers; we do still respect 751 // them when building the underlying variable. 752 for (auto Loc : BadSpecifierLocs) 753 Err << SourceRange(Loc, Loc); 754 } 755 // We can't recover from it being declared as a typedef. 756 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 757 return nullptr; 758 } 759 760 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 761 QualType R = TInfo->getType(); 762 763 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 764 UPPC_DeclarationType)) 765 D.setInvalidType(); 766 767 // The syntax only allows a single ref-qualifier prior to the decomposition 768 // declarator. No other declarator chunks are permitted. Also check the type 769 // specifier here. 770 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 771 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 772 (D.getNumTypeObjects() == 1 && 773 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 774 Diag(Decomp.getLSquareLoc(), 775 (D.hasGroupingParens() || 776 (D.getNumTypeObjects() && 777 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 778 ? diag::err_decomp_decl_parens 779 : diag::err_decomp_decl_type) 780 << R; 781 782 // In most cases, there's no actual problem with an explicitly-specified 783 // type, but a function type won't work here, and ActOnVariableDeclarator 784 // shouldn't be called for such a type. 785 if (R->isFunctionType()) 786 D.setInvalidType(); 787 } 788 789 // Build the BindingDecls. 790 SmallVector<BindingDecl*, 8> Bindings; 791 792 // Build the BindingDecls. 793 for (auto &B : D.getDecompositionDeclarator().bindings()) { 794 // Check for name conflicts. 795 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 796 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 797 ForVisibleRedeclaration); 798 LookupName(Previous, S, 799 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 800 801 // It's not permitted to shadow a template parameter name. 802 if (Previous.isSingleResult() && 803 Previous.getFoundDecl()->isTemplateParameter()) { 804 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 805 Previous.getFoundDecl()); 806 Previous.clear(); 807 } 808 809 bool ConsiderLinkage = DC->isFunctionOrMethod() && 810 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 811 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 812 /*AllowInlineNamespace*/false); 813 if (!Previous.empty()) { 814 auto *Old = Previous.getRepresentativeDecl(); 815 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 816 Diag(Old->getLocation(), diag::note_previous_definition); 817 } 818 819 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 820 PushOnScopeChains(BD, S, true); 821 Bindings.push_back(BD); 822 ParsingInitForAutoVars.insert(BD); 823 } 824 825 // There are no prior lookup results for the variable itself, because it 826 // is unnamed. 827 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 828 Decomp.getLSquareLoc()); 829 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 830 ForVisibleRedeclaration); 831 832 // Build the variable that holds the non-decomposed object. 833 bool AddToScope = true; 834 NamedDecl *New = 835 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 836 MultiTemplateParamsArg(), AddToScope, Bindings); 837 if (AddToScope) { 838 S->AddDecl(New); 839 CurContext->addHiddenDecl(New); 840 } 841 842 if (isInOpenMPDeclareTargetContext()) 843 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 844 845 return New; 846 } 847 848 static bool checkSimpleDecomposition( 849 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 850 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 851 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 852 if ((int64_t)Bindings.size() != NumElems) { 853 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 854 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 855 << (NumElems < Bindings.size()); 856 return true; 857 } 858 859 unsigned I = 0; 860 for (auto *B : Bindings) { 861 SourceLocation Loc = B->getLocation(); 862 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 863 if (E.isInvalid()) 864 return true; 865 E = GetInit(Loc, E.get(), I++); 866 if (E.isInvalid()) 867 return true; 868 B->setBinding(ElemType, E.get()); 869 } 870 871 return false; 872 } 873 874 static bool checkArrayLikeDecomposition(Sema &S, 875 ArrayRef<BindingDecl *> Bindings, 876 ValueDecl *Src, QualType DecompType, 877 const llvm::APSInt &NumElems, 878 QualType ElemType) { 879 return checkSimpleDecomposition( 880 S, Bindings, Src, DecompType, NumElems, ElemType, 881 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 882 ExprResult E = S.ActOnIntegerConstant(Loc, I); 883 if (E.isInvalid()) 884 return ExprError(); 885 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 886 }); 887 } 888 889 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 890 ValueDecl *Src, QualType DecompType, 891 const ConstantArrayType *CAT) { 892 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 893 llvm::APSInt(CAT->getSize()), 894 CAT->getElementType()); 895 } 896 897 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 898 ValueDecl *Src, QualType DecompType, 899 const VectorType *VT) { 900 return checkArrayLikeDecomposition( 901 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 902 S.Context.getQualifiedType(VT->getElementType(), 903 DecompType.getQualifiers())); 904 } 905 906 static bool checkComplexDecomposition(Sema &S, 907 ArrayRef<BindingDecl *> Bindings, 908 ValueDecl *Src, QualType DecompType, 909 const ComplexType *CT) { 910 return checkSimpleDecomposition( 911 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 912 S.Context.getQualifiedType(CT->getElementType(), 913 DecompType.getQualifiers()), 914 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 915 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 916 }); 917 } 918 919 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 920 TemplateArgumentListInfo &Args) { 921 SmallString<128> SS; 922 llvm::raw_svector_ostream OS(SS); 923 bool First = true; 924 for (auto &Arg : Args.arguments()) { 925 if (!First) 926 OS << ", "; 927 Arg.getArgument().print(PrintingPolicy, OS); 928 First = false; 929 } 930 return OS.str(); 931 } 932 933 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 934 SourceLocation Loc, StringRef Trait, 935 TemplateArgumentListInfo &Args, 936 unsigned DiagID) { 937 auto DiagnoseMissing = [&] { 938 if (DiagID) 939 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 940 Args); 941 return true; 942 }; 943 944 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 945 NamespaceDecl *Std = S.getStdNamespace(); 946 if (!Std) 947 return DiagnoseMissing(); 948 949 // Look up the trait itself, within namespace std. We can diagnose various 950 // problems with this lookup even if we've been asked to not diagnose a 951 // missing specialization, because this can only fail if the user has been 952 // declaring their own names in namespace std or we don't support the 953 // standard library implementation in use. 954 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 955 Loc, Sema::LookupOrdinaryName); 956 if (!S.LookupQualifiedName(Result, Std)) 957 return DiagnoseMissing(); 958 if (Result.isAmbiguous()) 959 return true; 960 961 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 962 if (!TraitTD) { 963 Result.suppressDiagnostics(); 964 NamedDecl *Found = *Result.begin(); 965 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 966 S.Diag(Found->getLocation(), diag::note_declared_at); 967 return true; 968 } 969 970 // Build the template-id. 971 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 972 if (TraitTy.isNull()) 973 return true; 974 if (!S.isCompleteType(Loc, TraitTy)) { 975 if (DiagID) 976 S.RequireCompleteType( 977 Loc, TraitTy, DiagID, 978 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 979 return true; 980 } 981 982 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 983 assert(RD && "specialization of class template is not a class?"); 984 985 // Look up the member of the trait type. 986 S.LookupQualifiedName(TraitMemberLookup, RD); 987 return TraitMemberLookup.isAmbiguous(); 988 } 989 990 static TemplateArgumentLoc 991 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 992 uint64_t I) { 993 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 994 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 995 } 996 997 static TemplateArgumentLoc 998 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 999 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1000 } 1001 1002 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1003 1004 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1005 llvm::APSInt &Size) { 1006 EnterExpressionEvaluationContext ContextRAII( 1007 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1008 1009 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1010 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1011 1012 // Form template argument list for tuple_size<T>. 1013 TemplateArgumentListInfo Args(Loc, Loc); 1014 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1015 1016 // If there's no tuple_size specialization, it's not tuple-like. 1017 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0)) 1018 return IsTupleLike::NotTupleLike; 1019 1020 // If we get this far, we've committed to the tuple interpretation, but 1021 // we can still fail if there actually isn't a usable ::value. 1022 1023 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1024 LookupResult &R; 1025 TemplateArgumentListInfo &Args; 1026 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1027 : R(R), Args(Args) {} 1028 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1029 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1030 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1031 } 1032 } Diagnoser(R, Args); 1033 1034 if (R.empty()) { 1035 Diagnoser.diagnoseNotICE(S, Loc, SourceRange()); 1036 return IsTupleLike::Error; 1037 } 1038 1039 ExprResult E = 1040 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1041 if (E.isInvalid()) 1042 return IsTupleLike::Error; 1043 1044 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1045 if (E.isInvalid()) 1046 return IsTupleLike::Error; 1047 1048 return IsTupleLike::TupleLike; 1049 } 1050 1051 /// \return std::tuple_element<I, T>::type. 1052 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1053 unsigned I, QualType T) { 1054 // Form template argument list for tuple_element<I, T>. 1055 TemplateArgumentListInfo Args(Loc, Loc); 1056 Args.addArgument( 1057 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1058 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1059 1060 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1061 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1062 if (lookupStdTypeTraitMember( 1063 S, R, Loc, "tuple_element", Args, 1064 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1065 return QualType(); 1066 1067 auto *TD = R.getAsSingle<TypeDecl>(); 1068 if (!TD) { 1069 R.suppressDiagnostics(); 1070 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1071 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1072 if (!R.empty()) 1073 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1074 return QualType(); 1075 } 1076 1077 return S.Context.getTypeDeclType(TD); 1078 } 1079 1080 namespace { 1081 struct BindingDiagnosticTrap { 1082 Sema &S; 1083 DiagnosticErrorTrap Trap; 1084 BindingDecl *BD; 1085 1086 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1087 : S(S), Trap(S.Diags), BD(BD) {} 1088 ~BindingDiagnosticTrap() { 1089 if (Trap.hasErrorOccurred()) 1090 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1091 } 1092 }; 1093 } 1094 1095 static bool checkTupleLikeDecomposition(Sema &S, 1096 ArrayRef<BindingDecl *> Bindings, 1097 VarDecl *Src, QualType DecompType, 1098 const llvm::APSInt &TupleSize) { 1099 if ((int64_t)Bindings.size() != TupleSize) { 1100 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1101 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1102 << (TupleSize < Bindings.size()); 1103 return true; 1104 } 1105 1106 if (Bindings.empty()) 1107 return false; 1108 1109 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1110 1111 // [dcl.decomp]p3: 1112 // The unqualified-id get is looked up in the scope of E by class member 1113 // access lookup 1114 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1115 bool UseMemberGet = false; 1116 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1117 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1118 S.LookupQualifiedName(MemberGet, RD); 1119 if (MemberGet.isAmbiguous()) 1120 return true; 1121 UseMemberGet = !MemberGet.empty(); 1122 S.FilterAcceptableTemplateNames(MemberGet); 1123 } 1124 1125 unsigned I = 0; 1126 for (auto *B : Bindings) { 1127 BindingDiagnosticTrap Trap(S, B); 1128 SourceLocation Loc = B->getLocation(); 1129 1130 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1131 if (E.isInvalid()) 1132 return true; 1133 1134 // e is an lvalue if the type of the entity is an lvalue reference and 1135 // an xvalue otherwise 1136 if (!Src->getType()->isLValueReferenceType()) 1137 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1138 E.get(), nullptr, VK_XValue); 1139 1140 TemplateArgumentListInfo Args(Loc, Loc); 1141 Args.addArgument( 1142 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1143 1144 if (UseMemberGet) { 1145 // if [lookup of member get] finds at least one declaration, the 1146 // initializer is e.get<i-1>(). 1147 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1148 CXXScopeSpec(), SourceLocation(), nullptr, 1149 MemberGet, &Args, nullptr); 1150 if (E.isInvalid()) 1151 return true; 1152 1153 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc); 1154 } else { 1155 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1156 // in the associated namespaces. 1157 Expr *Get = UnresolvedLookupExpr::Create( 1158 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1159 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1160 UnresolvedSetIterator(), UnresolvedSetIterator()); 1161 1162 Expr *Arg = E.get(); 1163 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc); 1164 } 1165 if (E.isInvalid()) 1166 return true; 1167 Expr *Init = E.get(); 1168 1169 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1170 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1171 if (T.isNull()) 1172 return true; 1173 1174 // each vi is a variable of type "reference to T" initialized with the 1175 // initializer, where the reference is an lvalue reference if the 1176 // initializer is an lvalue and an rvalue reference otherwise 1177 QualType RefType = 1178 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1179 if (RefType.isNull()) 1180 return true; 1181 auto *RefVD = VarDecl::Create( 1182 S.Context, Src->getDeclContext(), Loc, Loc, 1183 B->getDeclName().getAsIdentifierInfo(), RefType, 1184 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1185 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1186 RefVD->setTSCSpec(Src->getTSCSpec()); 1187 RefVD->setImplicit(); 1188 if (Src->isInlineSpecified()) 1189 RefVD->setInlineSpecified(); 1190 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1191 1192 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1193 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1194 InitializationSequence Seq(S, Entity, Kind, Init); 1195 E = Seq.Perform(S, Entity, Kind, Init); 1196 if (E.isInvalid()) 1197 return true; 1198 E = S.ActOnFinishFullExpr(E.get(), Loc); 1199 if (E.isInvalid()) 1200 return true; 1201 RefVD->setInit(E.get()); 1202 RefVD->checkInitIsICE(); 1203 1204 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1205 DeclarationNameInfo(B->getDeclName(), Loc), 1206 RefVD); 1207 if (E.isInvalid()) 1208 return true; 1209 1210 B->setBinding(T, E.get()); 1211 I++; 1212 } 1213 1214 return false; 1215 } 1216 1217 /// Find the base class to decompose in a built-in decomposition of a class type. 1218 /// This base class search is, unfortunately, not quite like any other that we 1219 /// perform anywhere else in C++. 1220 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S, 1221 SourceLocation Loc, 1222 const CXXRecordDecl *RD, 1223 CXXCastPath &BasePath) { 1224 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1225 CXXBasePath &Path) { 1226 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1227 }; 1228 1229 const CXXRecordDecl *ClassWithFields = nullptr; 1230 if (RD->hasDirectFields()) 1231 // [dcl.decomp]p4: 1232 // Otherwise, all of E's non-static data members shall be public direct 1233 // members of E ... 1234 ClassWithFields = RD; 1235 else { 1236 // ... or of ... 1237 CXXBasePaths Paths; 1238 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1239 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1240 // If no classes have fields, just decompose RD itself. (This will work 1241 // if and only if zero bindings were provided.) 1242 return RD; 1243 } 1244 1245 CXXBasePath *BestPath = nullptr; 1246 for (auto &P : Paths) { 1247 if (!BestPath) 1248 BestPath = &P; 1249 else if (!S.Context.hasSameType(P.back().Base->getType(), 1250 BestPath->back().Base->getType())) { 1251 // ... the same ... 1252 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1253 << false << RD << BestPath->back().Base->getType() 1254 << P.back().Base->getType(); 1255 return nullptr; 1256 } else if (P.Access < BestPath->Access) { 1257 BestPath = &P; 1258 } 1259 } 1260 1261 // ... unambiguous ... 1262 QualType BaseType = BestPath->back().Base->getType(); 1263 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1264 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1265 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1266 return nullptr; 1267 } 1268 1269 // ... public base class of E. 1270 if (BestPath->Access != AS_public) { 1271 S.Diag(Loc, diag::err_decomp_decl_non_public_base) 1272 << RD << BaseType; 1273 for (auto &BS : *BestPath) { 1274 if (BS.Base->getAccessSpecifier() != AS_public) { 1275 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path) 1276 << (BS.Base->getAccessSpecifier() == AS_protected) 1277 << (BS.Base->getAccessSpecifierAsWritten() == AS_none); 1278 break; 1279 } 1280 } 1281 return nullptr; 1282 } 1283 1284 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1285 S.BuildBasePathArray(Paths, BasePath); 1286 } 1287 1288 // The above search did not check whether the selected class itself has base 1289 // classes with fields, so check that now. 1290 CXXBasePaths Paths; 1291 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1292 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1293 << (ClassWithFields == RD) << RD << ClassWithFields 1294 << Paths.front().back().Base->getType(); 1295 return nullptr; 1296 } 1297 1298 return ClassWithFields; 1299 } 1300 1301 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1302 ValueDecl *Src, QualType DecompType, 1303 const CXXRecordDecl *RD) { 1304 CXXCastPath BasePath; 1305 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath); 1306 if (!RD) 1307 return true; 1308 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1309 DecompType.getQualifiers()); 1310 1311 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1312 unsigned NumFields = 1313 std::count_if(RD->field_begin(), RD->field_end(), 1314 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1315 assert(Bindings.size() != NumFields); 1316 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1317 << DecompType << (unsigned)Bindings.size() << NumFields 1318 << (NumFields < Bindings.size()); 1319 return true; 1320 }; 1321 1322 // all of E's non-static data members shall be public [...] members, 1323 // E shall not have an anonymous union member, ... 1324 unsigned I = 0; 1325 for (auto *FD : RD->fields()) { 1326 if (FD->isUnnamedBitfield()) 1327 continue; 1328 1329 if (FD->isAnonymousStructOrUnion()) { 1330 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1331 << DecompType << FD->getType()->isUnionType(); 1332 S.Diag(FD->getLocation(), diag::note_declared_at); 1333 return true; 1334 } 1335 1336 // We have a real field to bind. 1337 if (I >= Bindings.size()) 1338 return DiagnoseBadNumberOfBindings(); 1339 auto *B = Bindings[I++]; 1340 1341 SourceLocation Loc = B->getLocation(); 1342 if (FD->getAccess() != AS_public) { 1343 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType; 1344 1345 // Determine whether the access specifier was explicit. 1346 bool Implicit = true; 1347 for (const auto *D : RD->decls()) { 1348 if (declaresSameEntity(D, FD)) 1349 break; 1350 if (isa<AccessSpecDecl>(D)) { 1351 Implicit = false; 1352 break; 1353 } 1354 } 1355 1356 S.Diag(FD->getLocation(), diag::note_access_natural) 1357 << (FD->getAccess() == AS_protected) << Implicit; 1358 return true; 1359 } 1360 1361 // Initialize the binding to Src.FD. 1362 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1363 if (E.isInvalid()) 1364 return true; 1365 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1366 VK_LValue, &BasePath); 1367 if (E.isInvalid()) 1368 return true; 1369 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1370 CXXScopeSpec(), FD, 1371 DeclAccessPair::make(FD, FD->getAccess()), 1372 DeclarationNameInfo(FD->getDeclName(), Loc)); 1373 if (E.isInvalid()) 1374 return true; 1375 1376 // If the type of the member is T, the referenced type is cv T, where cv is 1377 // the cv-qualification of the decomposition expression. 1378 // 1379 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1380 // 'const' to the type of the field. 1381 Qualifiers Q = DecompType.getQualifiers(); 1382 if (FD->isMutable()) 1383 Q.removeConst(); 1384 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1385 } 1386 1387 if (I != Bindings.size()) 1388 return DiagnoseBadNumberOfBindings(); 1389 1390 return false; 1391 } 1392 1393 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1394 QualType DecompType = DD->getType(); 1395 1396 // If the type of the decomposition is dependent, then so is the type of 1397 // each binding. 1398 if (DecompType->isDependentType()) { 1399 for (auto *B : DD->bindings()) 1400 B->setType(Context.DependentTy); 1401 return; 1402 } 1403 1404 DecompType = DecompType.getNonReferenceType(); 1405 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1406 1407 // C++1z [dcl.decomp]/2: 1408 // If E is an array type [...] 1409 // As an extension, we also support decomposition of built-in complex and 1410 // vector types. 1411 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1412 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1413 DD->setInvalidDecl(); 1414 return; 1415 } 1416 if (auto *VT = DecompType->getAs<VectorType>()) { 1417 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1418 DD->setInvalidDecl(); 1419 return; 1420 } 1421 if (auto *CT = DecompType->getAs<ComplexType>()) { 1422 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1423 DD->setInvalidDecl(); 1424 return; 1425 } 1426 1427 // C++1z [dcl.decomp]/3: 1428 // if the expression std::tuple_size<E>::value is a well-formed integral 1429 // constant expression, [...] 1430 llvm::APSInt TupleSize(32); 1431 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1432 case IsTupleLike::Error: 1433 DD->setInvalidDecl(); 1434 return; 1435 1436 case IsTupleLike::TupleLike: 1437 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1438 DD->setInvalidDecl(); 1439 return; 1440 1441 case IsTupleLike::NotTupleLike: 1442 break; 1443 } 1444 1445 // C++1z [dcl.dcl]/8: 1446 // [E shall be of array or non-union class type] 1447 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1448 if (!RD || RD->isUnion()) { 1449 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1450 << DD << !RD << DecompType; 1451 DD->setInvalidDecl(); 1452 return; 1453 } 1454 1455 // C++1z [dcl.decomp]/4: 1456 // all of E's non-static data members shall be [...] direct members of 1457 // E or of the same unambiguous public base class of E, ... 1458 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1459 DD->setInvalidDecl(); 1460 } 1461 1462 /// \brief Merge the exception specifications of two variable declarations. 1463 /// 1464 /// This is called when there's a redeclaration of a VarDecl. The function 1465 /// checks if the redeclaration might have an exception specification and 1466 /// validates compatibility and merges the specs if necessary. 1467 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1468 // Shortcut if exceptions are disabled. 1469 if (!getLangOpts().CXXExceptions) 1470 return; 1471 1472 assert(Context.hasSameType(New->getType(), Old->getType()) && 1473 "Should only be called if types are otherwise the same."); 1474 1475 QualType NewType = New->getType(); 1476 QualType OldType = Old->getType(); 1477 1478 // We're only interested in pointers and references to functions, as well 1479 // as pointers to member functions. 1480 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1481 NewType = R->getPointeeType(); 1482 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1483 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1484 NewType = P->getPointeeType(); 1485 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1486 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1487 NewType = M->getPointeeType(); 1488 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1489 } 1490 1491 if (!NewType->isFunctionProtoType()) 1492 return; 1493 1494 // There's lots of special cases for functions. For function pointers, system 1495 // libraries are hopefully not as broken so that we don't need these 1496 // workarounds. 1497 if (CheckEquivalentExceptionSpec( 1498 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1499 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1500 New->setInvalidDecl(); 1501 } 1502 } 1503 1504 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1505 /// function declaration are well-formed according to C++ 1506 /// [dcl.fct.default]. 1507 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1508 unsigned NumParams = FD->getNumParams(); 1509 unsigned p; 1510 1511 // Find first parameter with a default argument 1512 for (p = 0; p < NumParams; ++p) { 1513 ParmVarDecl *Param = FD->getParamDecl(p); 1514 if (Param->hasDefaultArg()) 1515 break; 1516 } 1517 1518 // C++11 [dcl.fct.default]p4: 1519 // In a given function declaration, each parameter subsequent to a parameter 1520 // with a default argument shall have a default argument supplied in this or 1521 // a previous declaration or shall be a function parameter pack. A default 1522 // argument shall not be redefined by a later declaration (not even to the 1523 // same value). 1524 unsigned LastMissingDefaultArg = 0; 1525 for (; p < NumParams; ++p) { 1526 ParmVarDecl *Param = FD->getParamDecl(p); 1527 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1528 if (Param->isInvalidDecl()) 1529 /* We already complained about this parameter. */; 1530 else if (Param->getIdentifier()) 1531 Diag(Param->getLocation(), 1532 diag::err_param_default_argument_missing_name) 1533 << Param->getIdentifier(); 1534 else 1535 Diag(Param->getLocation(), 1536 diag::err_param_default_argument_missing); 1537 1538 LastMissingDefaultArg = p; 1539 } 1540 } 1541 1542 if (LastMissingDefaultArg > 0) { 1543 // Some default arguments were missing. Clear out all of the 1544 // default arguments up to (and including) the last missing 1545 // default argument, so that we leave the function parameters 1546 // in a semantically valid state. 1547 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1548 ParmVarDecl *Param = FD->getParamDecl(p); 1549 if (Param->hasDefaultArg()) { 1550 Param->setDefaultArg(nullptr); 1551 } 1552 } 1553 } 1554 } 1555 1556 // CheckConstexprParameterTypes - Check whether a function's parameter types 1557 // are all literal types. If so, return true. If not, produce a suitable 1558 // diagnostic and return false. 1559 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1560 const FunctionDecl *FD) { 1561 unsigned ArgIndex = 0; 1562 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1563 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1564 e = FT->param_type_end(); 1565 i != e; ++i, ++ArgIndex) { 1566 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1567 SourceLocation ParamLoc = PD->getLocation(); 1568 if (!(*i)->isDependentType() && 1569 SemaRef.RequireLiteralType(ParamLoc, *i, 1570 diag::err_constexpr_non_literal_param, 1571 ArgIndex+1, PD->getSourceRange(), 1572 isa<CXXConstructorDecl>(FD))) 1573 return false; 1574 } 1575 return true; 1576 } 1577 1578 /// \brief Get diagnostic %select index for tag kind for 1579 /// record diagnostic message. 1580 /// WARNING: Indexes apply to particular diagnostics only! 1581 /// 1582 /// \returns diagnostic %select index. 1583 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1584 switch (Tag) { 1585 case TTK_Struct: return 0; 1586 case TTK_Interface: return 1; 1587 case TTK_Class: return 2; 1588 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1589 } 1590 } 1591 1592 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 1593 // the requirements of a constexpr function definition or a constexpr 1594 // constructor definition. If so, return true. If not, produce appropriate 1595 // diagnostics and return false. 1596 // 1597 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1598 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 1599 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1600 if (MD && MD->isInstance()) { 1601 // C++11 [dcl.constexpr]p4: 1602 // The definition of a constexpr constructor shall satisfy the following 1603 // constraints: 1604 // - the class shall not have any virtual base classes; 1605 const CXXRecordDecl *RD = MD->getParent(); 1606 if (RD->getNumVBases()) { 1607 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1608 << isa<CXXConstructorDecl>(NewFD) 1609 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1610 for (const auto &I : RD->vbases()) 1611 Diag(I.getLocStart(), 1612 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 1613 return false; 1614 } 1615 } 1616 1617 if (!isa<CXXConstructorDecl>(NewFD)) { 1618 // C++11 [dcl.constexpr]p3: 1619 // The definition of a constexpr function shall satisfy the following 1620 // constraints: 1621 // - it shall not be virtual; 1622 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1623 if (Method && Method->isVirtual()) { 1624 Method = Method->getCanonicalDecl(); 1625 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1626 1627 // If it's not obvious why this function is virtual, find an overridden 1628 // function which uses the 'virtual' keyword. 1629 const CXXMethodDecl *WrittenVirtual = Method; 1630 while (!WrittenVirtual->isVirtualAsWritten()) 1631 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1632 if (WrittenVirtual != Method) 1633 Diag(WrittenVirtual->getLocation(), 1634 diag::note_overridden_virtual_function); 1635 return false; 1636 } 1637 1638 // - its return type shall be a literal type; 1639 QualType RT = NewFD->getReturnType(); 1640 if (!RT->isDependentType() && 1641 RequireLiteralType(NewFD->getLocation(), RT, 1642 diag::err_constexpr_non_literal_return)) 1643 return false; 1644 } 1645 1646 // - each of its parameter types shall be a literal type; 1647 if (!CheckConstexprParameterTypes(*this, NewFD)) 1648 return false; 1649 1650 return true; 1651 } 1652 1653 /// Check the given declaration statement is legal within a constexpr function 1654 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1655 /// 1656 /// \return true if the body is OK (maybe only as an extension), false if we 1657 /// have diagnosed a problem. 1658 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1659 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 1660 // C++11 [dcl.constexpr]p3 and p4: 1661 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1662 // contain only 1663 for (const auto *DclIt : DS->decls()) { 1664 switch (DclIt->getKind()) { 1665 case Decl::StaticAssert: 1666 case Decl::Using: 1667 case Decl::UsingShadow: 1668 case Decl::UsingDirective: 1669 case Decl::UnresolvedUsingTypename: 1670 case Decl::UnresolvedUsingValue: 1671 // - static_assert-declarations 1672 // - using-declarations, 1673 // - using-directives, 1674 continue; 1675 1676 case Decl::Typedef: 1677 case Decl::TypeAlias: { 1678 // - typedef declarations and alias-declarations that do not define 1679 // classes or enumerations, 1680 const auto *TN = cast<TypedefNameDecl>(DclIt); 1681 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1682 // Don't allow variably-modified types in constexpr functions. 1683 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1684 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1685 << TL.getSourceRange() << TL.getType() 1686 << isa<CXXConstructorDecl>(Dcl); 1687 return false; 1688 } 1689 continue; 1690 } 1691 1692 case Decl::Enum: 1693 case Decl::CXXRecord: 1694 // C++1y allows types to be defined, not just declared. 1695 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 1696 SemaRef.Diag(DS->getLocStart(), 1697 SemaRef.getLangOpts().CPlusPlus14 1698 ? diag::warn_cxx11_compat_constexpr_type_definition 1699 : diag::ext_constexpr_type_definition) 1700 << isa<CXXConstructorDecl>(Dcl); 1701 continue; 1702 1703 case Decl::EnumConstant: 1704 case Decl::IndirectField: 1705 case Decl::ParmVar: 1706 // These can only appear with other declarations which are banned in 1707 // C++11 and permitted in C++1y, so ignore them. 1708 continue; 1709 1710 case Decl::Var: 1711 case Decl::Decomposition: { 1712 // C++1y [dcl.constexpr]p3 allows anything except: 1713 // a definition of a variable of non-literal type or of static or 1714 // thread storage duration or for which no initialization is performed. 1715 const auto *VD = cast<VarDecl>(DclIt); 1716 if (VD->isThisDeclarationADefinition()) { 1717 if (VD->isStaticLocal()) { 1718 SemaRef.Diag(VD->getLocation(), 1719 diag::err_constexpr_local_var_static) 1720 << isa<CXXConstructorDecl>(Dcl) 1721 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1722 return false; 1723 } 1724 if (!VD->getType()->isDependentType() && 1725 SemaRef.RequireLiteralType( 1726 VD->getLocation(), VD->getType(), 1727 diag::err_constexpr_local_var_non_literal_type, 1728 isa<CXXConstructorDecl>(Dcl))) 1729 return false; 1730 if (!VD->getType()->isDependentType() && 1731 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1732 SemaRef.Diag(VD->getLocation(), 1733 diag::err_constexpr_local_var_no_init) 1734 << isa<CXXConstructorDecl>(Dcl); 1735 return false; 1736 } 1737 } 1738 SemaRef.Diag(VD->getLocation(), 1739 SemaRef.getLangOpts().CPlusPlus14 1740 ? diag::warn_cxx11_compat_constexpr_local_var 1741 : diag::ext_constexpr_local_var) 1742 << isa<CXXConstructorDecl>(Dcl); 1743 continue; 1744 } 1745 1746 case Decl::NamespaceAlias: 1747 case Decl::Function: 1748 // These are disallowed in C++11 and permitted in C++1y. Allow them 1749 // everywhere as an extension. 1750 if (!Cxx1yLoc.isValid()) 1751 Cxx1yLoc = DS->getLocStart(); 1752 continue; 1753 1754 default: 1755 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1756 << isa<CXXConstructorDecl>(Dcl); 1757 return false; 1758 } 1759 } 1760 1761 return true; 1762 } 1763 1764 /// Check that the given field is initialized within a constexpr constructor. 1765 /// 1766 /// \param Dcl The constexpr constructor being checked. 1767 /// \param Field The field being checked. This may be a member of an anonymous 1768 /// struct or union nested within the class being checked. 1769 /// \param Inits All declarations, including anonymous struct/union members and 1770 /// indirect members, for which any initialization was provided. 1771 /// \param Diagnosed Set to true if an error is produced. 1772 static void CheckConstexprCtorInitializer(Sema &SemaRef, 1773 const FunctionDecl *Dcl, 1774 FieldDecl *Field, 1775 llvm::SmallSet<Decl*, 16> &Inits, 1776 bool &Diagnosed) { 1777 if (Field->isInvalidDecl()) 1778 return; 1779 1780 if (Field->isUnnamedBitfield()) 1781 return; 1782 1783 // Anonymous unions with no variant members and empty anonymous structs do not 1784 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1785 // indirect fields don't need initializing. 1786 if (Field->isAnonymousStructOrUnion() && 1787 (Field->getType()->isUnionType() 1788 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1789 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1790 return; 1791 1792 if (!Inits.count(Field)) { 1793 if (!Diagnosed) { 1794 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1795 Diagnosed = true; 1796 } 1797 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1798 } else if (Field->isAnonymousStructOrUnion()) { 1799 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1800 for (auto *I : RD->fields()) 1801 // If an anonymous union contains an anonymous struct of which any member 1802 // is initialized, all members must be initialized. 1803 if (!RD->isUnion() || Inits.count(I)) 1804 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1805 } 1806 } 1807 1808 /// Check the provided statement is allowed in a constexpr function 1809 /// definition. 1810 static bool 1811 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1812 SmallVectorImpl<SourceLocation> &ReturnStmts, 1813 SourceLocation &Cxx1yLoc) { 1814 // - its function-body shall be [...] a compound-statement that contains only 1815 switch (S->getStmtClass()) { 1816 case Stmt::NullStmtClass: 1817 // - null statements, 1818 return true; 1819 1820 case Stmt::DeclStmtClass: 1821 // - static_assert-declarations 1822 // - using-declarations, 1823 // - using-directives, 1824 // - typedef declarations and alias-declarations that do not define 1825 // classes or enumerations, 1826 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1827 return false; 1828 return true; 1829 1830 case Stmt::ReturnStmtClass: 1831 // - and exactly one return statement; 1832 if (isa<CXXConstructorDecl>(Dcl)) { 1833 // C++1y allows return statements in constexpr constructors. 1834 if (!Cxx1yLoc.isValid()) 1835 Cxx1yLoc = S->getLocStart(); 1836 return true; 1837 } 1838 1839 ReturnStmts.push_back(S->getLocStart()); 1840 return true; 1841 1842 case Stmt::CompoundStmtClass: { 1843 // C++1y allows compound-statements. 1844 if (!Cxx1yLoc.isValid()) 1845 Cxx1yLoc = S->getLocStart(); 1846 1847 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1848 for (auto *BodyIt : CompStmt->body()) { 1849 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1850 Cxx1yLoc)) 1851 return false; 1852 } 1853 return true; 1854 } 1855 1856 case Stmt::AttributedStmtClass: 1857 if (!Cxx1yLoc.isValid()) 1858 Cxx1yLoc = S->getLocStart(); 1859 return true; 1860 1861 case Stmt::IfStmtClass: { 1862 // C++1y allows if-statements. 1863 if (!Cxx1yLoc.isValid()) 1864 Cxx1yLoc = S->getLocStart(); 1865 1866 IfStmt *If = cast<IfStmt>(S); 1867 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1868 Cxx1yLoc)) 1869 return false; 1870 if (If->getElse() && 1871 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1872 Cxx1yLoc)) 1873 return false; 1874 return true; 1875 } 1876 1877 case Stmt::WhileStmtClass: 1878 case Stmt::DoStmtClass: 1879 case Stmt::ForStmtClass: 1880 case Stmt::CXXForRangeStmtClass: 1881 case Stmt::ContinueStmtClass: 1882 // C++1y allows all of these. We don't allow them as extensions in C++11, 1883 // because they don't make sense without variable mutation. 1884 if (!SemaRef.getLangOpts().CPlusPlus14) 1885 break; 1886 if (!Cxx1yLoc.isValid()) 1887 Cxx1yLoc = S->getLocStart(); 1888 for (Stmt *SubStmt : S->children()) 1889 if (SubStmt && 1890 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1891 Cxx1yLoc)) 1892 return false; 1893 return true; 1894 1895 case Stmt::SwitchStmtClass: 1896 case Stmt::CaseStmtClass: 1897 case Stmt::DefaultStmtClass: 1898 case Stmt::BreakStmtClass: 1899 // C++1y allows switch-statements, and since they don't need variable 1900 // mutation, we can reasonably allow them in C++11 as an extension. 1901 if (!Cxx1yLoc.isValid()) 1902 Cxx1yLoc = S->getLocStart(); 1903 for (Stmt *SubStmt : S->children()) 1904 if (SubStmt && 1905 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1906 Cxx1yLoc)) 1907 return false; 1908 return true; 1909 1910 default: 1911 if (!isa<Expr>(S)) 1912 break; 1913 1914 // C++1y allows expression-statements. 1915 if (!Cxx1yLoc.isValid()) 1916 Cxx1yLoc = S->getLocStart(); 1917 return true; 1918 } 1919 1920 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1921 << isa<CXXConstructorDecl>(Dcl); 1922 return false; 1923 } 1924 1925 /// Check the body for the given constexpr function declaration only contains 1926 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1927 /// 1928 /// \return true if the body is OK, false if we have diagnosed a problem. 1929 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1930 if (isa<CXXTryStmt>(Body)) { 1931 // C++11 [dcl.constexpr]p3: 1932 // The definition of a constexpr function shall satisfy the following 1933 // constraints: [...] 1934 // - its function-body shall be = delete, = default, or a 1935 // compound-statement 1936 // 1937 // C++11 [dcl.constexpr]p4: 1938 // In the definition of a constexpr constructor, [...] 1939 // - its function-body shall not be a function-try-block; 1940 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1941 << isa<CXXConstructorDecl>(Dcl); 1942 return false; 1943 } 1944 1945 SmallVector<SourceLocation, 4> ReturnStmts; 1946 1947 // - its function-body shall be [...] a compound-statement that contains only 1948 // [... list of cases ...] 1949 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1950 SourceLocation Cxx1yLoc; 1951 for (auto *BodyIt : CompBody->body()) { 1952 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1953 return false; 1954 } 1955 1956 if (Cxx1yLoc.isValid()) 1957 Diag(Cxx1yLoc, 1958 getLangOpts().CPlusPlus14 1959 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1960 : diag::ext_constexpr_body_invalid_stmt) 1961 << isa<CXXConstructorDecl>(Dcl); 1962 1963 if (const CXXConstructorDecl *Constructor 1964 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1965 const CXXRecordDecl *RD = Constructor->getParent(); 1966 // DR1359: 1967 // - every non-variant non-static data member and base class sub-object 1968 // shall be initialized; 1969 // DR1460: 1970 // - if the class is a union having variant members, exactly one of them 1971 // shall be initialized; 1972 if (RD->isUnion()) { 1973 if (Constructor->getNumCtorInitializers() == 0 && 1974 RD->hasVariantMembers()) { 1975 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1976 return false; 1977 } 1978 } else if (!Constructor->isDependentContext() && 1979 !Constructor->isDelegatingConstructor()) { 1980 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1981 1982 // Skip detailed checking if we have enough initializers, and we would 1983 // allow at most one initializer per member. 1984 bool AnyAnonStructUnionMembers = false; 1985 unsigned Fields = 0; 1986 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1987 E = RD->field_end(); I != E; ++I, ++Fields) { 1988 if (I->isAnonymousStructOrUnion()) { 1989 AnyAnonStructUnionMembers = true; 1990 break; 1991 } 1992 } 1993 // DR1460: 1994 // - if the class is a union-like class, but is not a union, for each of 1995 // its anonymous union members having variant members, exactly one of 1996 // them shall be initialized; 1997 if (AnyAnonStructUnionMembers || 1998 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1999 // Check initialization of non-static data members. Base classes are 2000 // always initialized so do not need to be checked. Dependent bases 2001 // might not have initializers in the member initializer list. 2002 llvm::SmallSet<Decl*, 16> Inits; 2003 for (const auto *I: Constructor->inits()) { 2004 if (FieldDecl *FD = I->getMember()) 2005 Inits.insert(FD); 2006 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2007 Inits.insert(ID->chain_begin(), ID->chain_end()); 2008 } 2009 2010 bool Diagnosed = false; 2011 for (auto *I : RD->fields()) 2012 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 2013 if (Diagnosed) 2014 return false; 2015 } 2016 } 2017 } else { 2018 if (ReturnStmts.empty()) { 2019 // C++1y doesn't require constexpr functions to contain a 'return' 2020 // statement. We still do, unless the return type might be void, because 2021 // otherwise if there's no return statement, the function cannot 2022 // be used in a core constant expression. 2023 bool OK = getLangOpts().CPlusPlus14 && 2024 (Dcl->getReturnType()->isVoidType() || 2025 Dcl->getReturnType()->isDependentType()); 2026 Diag(Dcl->getLocation(), 2027 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2028 : diag::err_constexpr_body_no_return); 2029 if (!OK) 2030 return false; 2031 } else if (ReturnStmts.size() > 1) { 2032 Diag(ReturnStmts.back(), 2033 getLangOpts().CPlusPlus14 2034 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2035 : diag::ext_constexpr_body_multiple_return); 2036 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2037 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 2038 } 2039 } 2040 2041 // C++11 [dcl.constexpr]p5: 2042 // if no function argument values exist such that the function invocation 2043 // substitution would produce a constant expression, the program is 2044 // ill-formed; no diagnostic required. 2045 // C++11 [dcl.constexpr]p3: 2046 // - every constructor call and implicit conversion used in initializing the 2047 // return value shall be one of those allowed in a constant expression. 2048 // C++11 [dcl.constexpr]p4: 2049 // - every constructor involved in initializing non-static data members and 2050 // base class sub-objects shall be a constexpr constructor. 2051 SmallVector<PartialDiagnosticAt, 8> Diags; 2052 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 2053 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 2054 << isa<CXXConstructorDecl>(Dcl); 2055 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2056 Diag(Diags[I].first, Diags[I].second); 2057 // Don't return false here: we allow this for compatibility in 2058 // system headers. 2059 } 2060 2061 return true; 2062 } 2063 2064 /// isCurrentClassName - Determine whether the identifier II is the 2065 /// name of the class type currently being defined. In the case of 2066 /// nested classes, this will only return true if II is the name of 2067 /// the innermost class. 2068 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 2069 const CXXScopeSpec *SS) { 2070 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2071 2072 CXXRecordDecl *CurDecl; 2073 if (SS && SS->isSet() && !SS->isInvalid()) { 2074 DeclContext *DC = computeDeclContext(*SS, true); 2075 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2076 } else 2077 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2078 2079 if (CurDecl && CurDecl->getIdentifier()) 2080 return &II == CurDecl->getIdentifier(); 2081 return false; 2082 } 2083 2084 /// \brief Determine whether the identifier II is a typo for the name of 2085 /// the class type currently being defined. If so, update it to the identifier 2086 /// that should have been used. 2087 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2088 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2089 2090 if (!getLangOpts().SpellChecking) 2091 return false; 2092 2093 CXXRecordDecl *CurDecl; 2094 if (SS && SS->isSet() && !SS->isInvalid()) { 2095 DeclContext *DC = computeDeclContext(*SS, true); 2096 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2097 } else 2098 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2099 2100 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2101 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2102 < II->getLength()) { 2103 II = CurDecl->getIdentifier(); 2104 return true; 2105 } 2106 2107 return false; 2108 } 2109 2110 /// \brief Determine whether the given class is a base class of the given 2111 /// class, including looking at dependent bases. 2112 static bool findCircularInheritance(const CXXRecordDecl *Class, 2113 const CXXRecordDecl *Current) { 2114 SmallVector<const CXXRecordDecl*, 8> Queue; 2115 2116 Class = Class->getCanonicalDecl(); 2117 while (true) { 2118 for (const auto &I : Current->bases()) { 2119 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2120 if (!Base) 2121 continue; 2122 2123 Base = Base->getDefinition(); 2124 if (!Base) 2125 continue; 2126 2127 if (Base->getCanonicalDecl() == Class) 2128 return true; 2129 2130 Queue.push_back(Base); 2131 } 2132 2133 if (Queue.empty()) 2134 return false; 2135 2136 Current = Queue.pop_back_val(); 2137 } 2138 2139 return false; 2140 } 2141 2142 /// \brief Check the validity of a C++ base class specifier. 2143 /// 2144 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2145 /// and returns NULL otherwise. 2146 CXXBaseSpecifier * 2147 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2148 SourceRange SpecifierRange, 2149 bool Virtual, AccessSpecifier Access, 2150 TypeSourceInfo *TInfo, 2151 SourceLocation EllipsisLoc) { 2152 QualType BaseType = TInfo->getType(); 2153 2154 // C++ [class.union]p1: 2155 // A union shall not have base classes. 2156 if (Class->isUnion()) { 2157 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2158 << SpecifierRange; 2159 return nullptr; 2160 } 2161 2162 if (EllipsisLoc.isValid() && 2163 !TInfo->getType()->containsUnexpandedParameterPack()) { 2164 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2165 << TInfo->getTypeLoc().getSourceRange(); 2166 EllipsisLoc = SourceLocation(); 2167 } 2168 2169 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2170 2171 if (BaseType->isDependentType()) { 2172 // Make sure that we don't have circular inheritance among our dependent 2173 // bases. For non-dependent bases, the check for completeness below handles 2174 // this. 2175 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2176 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2177 ((BaseDecl = BaseDecl->getDefinition()) && 2178 findCircularInheritance(Class, BaseDecl))) { 2179 Diag(BaseLoc, diag::err_circular_inheritance) 2180 << BaseType << Context.getTypeDeclType(Class); 2181 2182 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2183 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2184 << BaseType; 2185 2186 return nullptr; 2187 } 2188 } 2189 2190 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2191 Class->getTagKind() == TTK_Class, 2192 Access, TInfo, EllipsisLoc); 2193 } 2194 2195 // Base specifiers must be record types. 2196 if (!BaseType->isRecordType()) { 2197 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2198 return nullptr; 2199 } 2200 2201 // C++ [class.union]p1: 2202 // A union shall not be used as a base class. 2203 if (BaseType->isUnionType()) { 2204 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2205 return nullptr; 2206 } 2207 2208 // For the MS ABI, propagate DLL attributes to base class templates. 2209 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2210 if (Attr *ClassAttr = getDLLAttr(Class)) { 2211 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2212 BaseType->getAsCXXRecordDecl())) { 2213 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2214 BaseLoc); 2215 } 2216 } 2217 } 2218 2219 // C++ [class.derived]p2: 2220 // The class-name in a base-specifier shall not be an incompletely 2221 // defined class. 2222 if (RequireCompleteType(BaseLoc, BaseType, 2223 diag::err_incomplete_base_class, SpecifierRange)) { 2224 Class->setInvalidDecl(); 2225 return nullptr; 2226 } 2227 2228 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2229 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2230 assert(BaseDecl && "Record type has no declaration"); 2231 BaseDecl = BaseDecl->getDefinition(); 2232 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2233 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2234 assert(CXXBaseDecl && "Base type is not a C++ type"); 2235 2236 // A class which contains a flexible array member is not suitable for use as a 2237 // base class: 2238 // - If the layout determines that a base comes before another base, 2239 // the flexible array member would index into the subsequent base. 2240 // - If the layout determines that base comes before the derived class, 2241 // the flexible array member would index into the derived class. 2242 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2243 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2244 << CXXBaseDecl->getDeclName(); 2245 return nullptr; 2246 } 2247 2248 // C++ [class]p3: 2249 // If a class is marked final and it appears as a base-type-specifier in 2250 // base-clause, the program is ill-formed. 2251 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2252 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2253 << CXXBaseDecl->getDeclName() 2254 << FA->isSpelledAsSealed(); 2255 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2256 << CXXBaseDecl->getDeclName() << FA->getRange(); 2257 return nullptr; 2258 } 2259 2260 if (BaseDecl->isInvalidDecl()) 2261 Class->setInvalidDecl(); 2262 2263 // Create the base specifier. 2264 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2265 Class->getTagKind() == TTK_Class, 2266 Access, TInfo, EllipsisLoc); 2267 } 2268 2269 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2270 /// one entry in the base class list of a class specifier, for 2271 /// example: 2272 /// class foo : public bar, virtual private baz { 2273 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2274 BaseResult 2275 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2276 ParsedAttributes &Attributes, 2277 bool Virtual, AccessSpecifier Access, 2278 ParsedType basetype, SourceLocation BaseLoc, 2279 SourceLocation EllipsisLoc) { 2280 if (!classdecl) 2281 return true; 2282 2283 AdjustDeclIfTemplate(classdecl); 2284 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2285 if (!Class) 2286 return true; 2287 2288 // We haven't yet attached the base specifiers. 2289 Class->setIsParsingBaseSpecifiers(); 2290 2291 // We do not support any C++11 attributes on base-specifiers yet. 2292 // Diagnose any attributes we see. 2293 if (!Attributes.empty()) { 2294 for (AttributeList *Attr = Attributes.getList(); Attr; 2295 Attr = Attr->getNext()) { 2296 if (Attr->isInvalid() || 2297 Attr->getKind() == AttributeList::IgnoredAttribute) 2298 continue; 2299 Diag(Attr->getLoc(), 2300 Attr->getKind() == AttributeList::UnknownAttribute 2301 ? diag::warn_unknown_attribute_ignored 2302 : diag::err_base_specifier_attribute) 2303 << Attr->getName(); 2304 } 2305 } 2306 2307 TypeSourceInfo *TInfo = nullptr; 2308 GetTypeFromParser(basetype, &TInfo); 2309 2310 if (EllipsisLoc.isInvalid() && 2311 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2312 UPPC_BaseType)) 2313 return true; 2314 2315 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2316 Virtual, Access, TInfo, 2317 EllipsisLoc)) 2318 return BaseSpec; 2319 else 2320 Class->setInvalidDecl(); 2321 2322 return true; 2323 } 2324 2325 /// Use small set to collect indirect bases. As this is only used 2326 /// locally, there's no need to abstract the small size parameter. 2327 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2328 2329 /// \brief Recursively add the bases of Type. Don't add Type itself. 2330 static void 2331 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2332 const QualType &Type) 2333 { 2334 // Even though the incoming type is a base, it might not be 2335 // a class -- it could be a template parm, for instance. 2336 if (auto Rec = Type->getAs<RecordType>()) { 2337 auto Decl = Rec->getAsCXXRecordDecl(); 2338 2339 // Iterate over its bases. 2340 for (const auto &BaseSpec : Decl->bases()) { 2341 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2342 .getUnqualifiedType(); 2343 if (Set.insert(Base).second) 2344 // If we've not already seen it, recurse. 2345 NoteIndirectBases(Context, Set, Base); 2346 } 2347 } 2348 } 2349 2350 /// \brief Performs the actual work of attaching the given base class 2351 /// specifiers to a C++ class. 2352 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2353 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2354 if (Bases.empty()) 2355 return false; 2356 2357 // Used to keep track of which base types we have already seen, so 2358 // that we can properly diagnose redundant direct base types. Note 2359 // that the key is always the unqualified canonical type of the base 2360 // class. 2361 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2362 2363 // Used to track indirect bases so we can see if a direct base is 2364 // ambiguous. 2365 IndirectBaseSet IndirectBaseTypes; 2366 2367 // Copy non-redundant base specifiers into permanent storage. 2368 unsigned NumGoodBases = 0; 2369 bool Invalid = false; 2370 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2371 QualType NewBaseType 2372 = Context.getCanonicalType(Bases[idx]->getType()); 2373 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2374 2375 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2376 if (KnownBase) { 2377 // C++ [class.mi]p3: 2378 // A class shall not be specified as a direct base class of a 2379 // derived class more than once. 2380 Diag(Bases[idx]->getLocStart(), 2381 diag::err_duplicate_base_class) 2382 << KnownBase->getType() 2383 << Bases[idx]->getSourceRange(); 2384 2385 // Delete the duplicate base class specifier; we're going to 2386 // overwrite its pointer later. 2387 Context.Deallocate(Bases[idx]); 2388 2389 Invalid = true; 2390 } else { 2391 // Okay, add this new base class. 2392 KnownBase = Bases[idx]; 2393 Bases[NumGoodBases++] = Bases[idx]; 2394 2395 // Note this base's direct & indirect bases, if there could be ambiguity. 2396 if (Bases.size() > 1) 2397 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2398 2399 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2400 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2401 if (Class->isInterface() && 2402 (!RD->isInterfaceLike() || 2403 KnownBase->getAccessSpecifier() != AS_public)) { 2404 // The Microsoft extension __interface does not permit bases that 2405 // are not themselves public interfaces. 2406 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 2407 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 2408 << RD->getSourceRange(); 2409 Invalid = true; 2410 } 2411 if (RD->hasAttr<WeakAttr>()) 2412 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2413 } 2414 } 2415 } 2416 2417 // Attach the remaining base class specifiers to the derived class. 2418 Class->setBases(Bases.data(), NumGoodBases); 2419 2420 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2421 // Check whether this direct base is inaccessible due to ambiguity. 2422 QualType BaseType = Bases[idx]->getType(); 2423 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2424 .getUnqualifiedType(); 2425 2426 if (IndirectBaseTypes.count(CanonicalBase)) { 2427 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2428 /*DetectVirtual=*/true); 2429 bool found 2430 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2431 assert(found); 2432 (void)found; 2433 2434 if (Paths.isAmbiguous(CanonicalBase)) 2435 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 2436 << BaseType << getAmbiguousPathsDisplayString(Paths) 2437 << Bases[idx]->getSourceRange(); 2438 else 2439 assert(Bases[idx]->isVirtual()); 2440 } 2441 2442 // Delete the base class specifier, since its data has been copied 2443 // into the CXXRecordDecl. 2444 Context.Deallocate(Bases[idx]); 2445 } 2446 2447 return Invalid; 2448 } 2449 2450 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2451 /// class, after checking whether there are any duplicate base 2452 /// classes. 2453 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2454 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2455 if (!ClassDecl || Bases.empty()) 2456 return; 2457 2458 AdjustDeclIfTemplate(ClassDecl); 2459 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2460 } 2461 2462 /// \brief Determine whether the type \p Derived is a C++ class that is 2463 /// derived from the type \p Base. 2464 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2465 if (!getLangOpts().CPlusPlus) 2466 return false; 2467 2468 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2469 if (!DerivedRD) 2470 return false; 2471 2472 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2473 if (!BaseRD) 2474 return false; 2475 2476 // If either the base or the derived type is invalid, don't try to 2477 // check whether one is derived from the other. 2478 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2479 return false; 2480 2481 // FIXME: In a modules build, do we need the entire path to be visible for us 2482 // to be able to use the inheritance relationship? 2483 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2484 return false; 2485 2486 return DerivedRD->isDerivedFrom(BaseRD); 2487 } 2488 2489 /// \brief Determine whether the type \p Derived is a C++ class that is 2490 /// derived from the type \p Base. 2491 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2492 CXXBasePaths &Paths) { 2493 if (!getLangOpts().CPlusPlus) 2494 return false; 2495 2496 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2497 if (!DerivedRD) 2498 return false; 2499 2500 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2501 if (!BaseRD) 2502 return false; 2503 2504 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2505 return false; 2506 2507 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2508 } 2509 2510 static void BuildBasePathArray(const CXXBasePath &Path, 2511 CXXCastPath &BasePathArray) { 2512 // We first go backward and check if we have a virtual base. 2513 // FIXME: It would be better if CXXBasePath had the base specifier for 2514 // the nearest virtual base. 2515 unsigned Start = 0; 2516 for (unsigned I = Path.size(); I != 0; --I) { 2517 if (Path[I - 1].Base->isVirtual()) { 2518 Start = I - 1; 2519 break; 2520 } 2521 } 2522 2523 // Now add all bases. 2524 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2525 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2526 } 2527 2528 2529 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2530 CXXCastPath &BasePathArray) { 2531 assert(BasePathArray.empty() && "Base path array must be empty!"); 2532 assert(Paths.isRecordingPaths() && "Must record paths!"); 2533 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2534 } 2535 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2536 /// conversion (where Derived and Base are class types) is 2537 /// well-formed, meaning that the conversion is unambiguous (and 2538 /// that all of the base classes are accessible). Returns true 2539 /// and emits a diagnostic if the code is ill-formed, returns false 2540 /// otherwise. Loc is the location where this routine should point to 2541 /// if there is an error, and Range is the source range to highlight 2542 /// if there is an error. 2543 /// 2544 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2545 /// diagnostic for the respective type of error will be suppressed, but the 2546 /// check for ill-formed code will still be performed. 2547 bool 2548 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2549 unsigned InaccessibleBaseID, 2550 unsigned AmbigiousBaseConvID, 2551 SourceLocation Loc, SourceRange Range, 2552 DeclarationName Name, 2553 CXXCastPath *BasePath, 2554 bool IgnoreAccess) { 2555 // First, determine whether the path from Derived to Base is 2556 // ambiguous. This is slightly more expensive than checking whether 2557 // the Derived to Base conversion exists, because here we need to 2558 // explore multiple paths to determine if there is an ambiguity. 2559 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2560 /*DetectVirtual=*/false); 2561 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2562 if (!DerivationOkay) 2563 return true; 2564 2565 const CXXBasePath *Path = nullptr; 2566 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2567 Path = &Paths.front(); 2568 2569 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2570 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2571 // user to access such bases. 2572 if (!Path && getLangOpts().MSVCCompat) { 2573 for (const CXXBasePath &PossiblePath : Paths) { 2574 if (PossiblePath.size() == 1) { 2575 Path = &PossiblePath; 2576 if (AmbigiousBaseConvID) 2577 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2578 << Base << Derived << Range; 2579 break; 2580 } 2581 } 2582 } 2583 2584 if (Path) { 2585 if (!IgnoreAccess) { 2586 // Check that the base class can be accessed. 2587 switch ( 2588 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2589 case AR_inaccessible: 2590 return true; 2591 case AR_accessible: 2592 case AR_dependent: 2593 case AR_delayed: 2594 break; 2595 } 2596 } 2597 2598 // Build a base path if necessary. 2599 if (BasePath) 2600 ::BuildBasePathArray(*Path, *BasePath); 2601 return false; 2602 } 2603 2604 if (AmbigiousBaseConvID) { 2605 // We know that the derived-to-base conversion is ambiguous, and 2606 // we're going to produce a diagnostic. Perform the derived-to-base 2607 // search just one more time to compute all of the possible paths so 2608 // that we can print them out. This is more expensive than any of 2609 // the previous derived-to-base checks we've done, but at this point 2610 // performance isn't as much of an issue. 2611 Paths.clear(); 2612 Paths.setRecordingPaths(true); 2613 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2614 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2615 (void)StillOkay; 2616 2617 // Build up a textual representation of the ambiguous paths, e.g., 2618 // D -> B -> A, that will be used to illustrate the ambiguous 2619 // conversions in the diagnostic. We only print one of the paths 2620 // to each base class subobject. 2621 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2622 2623 Diag(Loc, AmbigiousBaseConvID) 2624 << Derived << Base << PathDisplayStr << Range << Name; 2625 } 2626 return true; 2627 } 2628 2629 bool 2630 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2631 SourceLocation Loc, SourceRange Range, 2632 CXXCastPath *BasePath, 2633 bool IgnoreAccess) { 2634 return CheckDerivedToBaseConversion( 2635 Derived, Base, diag::err_upcast_to_inaccessible_base, 2636 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2637 BasePath, IgnoreAccess); 2638 } 2639 2640 2641 /// @brief Builds a string representing ambiguous paths from a 2642 /// specific derived class to different subobjects of the same base 2643 /// class. 2644 /// 2645 /// This function builds a string that can be used in error messages 2646 /// to show the different paths that one can take through the 2647 /// inheritance hierarchy to go from the derived class to different 2648 /// subobjects of a base class. The result looks something like this: 2649 /// @code 2650 /// struct D -> struct B -> struct A 2651 /// struct D -> struct C -> struct A 2652 /// @endcode 2653 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2654 std::string PathDisplayStr; 2655 std::set<unsigned> DisplayedPaths; 2656 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2657 Path != Paths.end(); ++Path) { 2658 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2659 // We haven't displayed a path to this particular base 2660 // class subobject yet. 2661 PathDisplayStr += "\n "; 2662 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2663 for (CXXBasePath::const_iterator Element = Path->begin(); 2664 Element != Path->end(); ++Element) 2665 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2666 } 2667 } 2668 2669 return PathDisplayStr; 2670 } 2671 2672 //===----------------------------------------------------------------------===// 2673 // C++ class member Handling 2674 //===----------------------------------------------------------------------===// 2675 2676 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2677 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 2678 SourceLocation ASLoc, 2679 SourceLocation ColonLoc, 2680 AttributeList *Attrs) { 2681 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2682 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2683 ASLoc, ColonLoc); 2684 CurContext->addHiddenDecl(ASDecl); 2685 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2686 } 2687 2688 /// CheckOverrideControl - Check C++11 override control semantics. 2689 void Sema::CheckOverrideControl(NamedDecl *D) { 2690 if (D->isInvalidDecl()) 2691 return; 2692 2693 // We only care about "override" and "final" declarations. 2694 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2695 return; 2696 2697 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2698 2699 // We can't check dependent instance methods. 2700 if (MD && MD->isInstance() && 2701 (MD->getParent()->hasAnyDependentBases() || 2702 MD->getType()->isDependentType())) 2703 return; 2704 2705 if (MD && !MD->isVirtual()) { 2706 // If we have a non-virtual method, check if if hides a virtual method. 2707 // (In that case, it's most likely the method has the wrong type.) 2708 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2709 FindHiddenVirtualMethods(MD, OverloadedMethods); 2710 2711 if (!OverloadedMethods.empty()) { 2712 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2713 Diag(OA->getLocation(), 2714 diag::override_keyword_hides_virtual_member_function) 2715 << "override" << (OverloadedMethods.size() > 1); 2716 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2717 Diag(FA->getLocation(), 2718 diag::override_keyword_hides_virtual_member_function) 2719 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2720 << (OverloadedMethods.size() > 1); 2721 } 2722 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2723 MD->setInvalidDecl(); 2724 return; 2725 } 2726 // Fall through into the general case diagnostic. 2727 // FIXME: We might want to attempt typo correction here. 2728 } 2729 2730 if (!MD || !MD->isVirtual()) { 2731 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2732 Diag(OA->getLocation(), 2733 diag::override_keyword_only_allowed_on_virtual_member_functions) 2734 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2735 D->dropAttr<OverrideAttr>(); 2736 } 2737 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2738 Diag(FA->getLocation(), 2739 diag::override_keyword_only_allowed_on_virtual_member_functions) 2740 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2741 << FixItHint::CreateRemoval(FA->getLocation()); 2742 D->dropAttr<FinalAttr>(); 2743 } 2744 return; 2745 } 2746 2747 // C++11 [class.virtual]p5: 2748 // If a function is marked with the virt-specifier override and 2749 // does not override a member function of a base class, the program is 2750 // ill-formed. 2751 bool HasOverriddenMethods = 2752 MD->begin_overridden_methods() != MD->end_overridden_methods(); 2753 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2754 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2755 << MD->getDeclName(); 2756 } 2757 2758 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2759 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2760 return; 2761 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2762 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 2763 return; 2764 2765 SourceLocation Loc = MD->getLocation(); 2766 SourceLocation SpellingLoc = Loc; 2767 if (getSourceManager().isMacroArgExpansion(Loc)) 2768 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 2769 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2770 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2771 return; 2772 2773 if (MD->size_overridden_methods() > 0) { 2774 unsigned DiagID = isa<CXXDestructorDecl>(MD) 2775 ? diag::warn_destructor_marked_not_override_overriding 2776 : diag::warn_function_marked_not_override_overriding; 2777 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 2778 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2779 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2780 } 2781 } 2782 2783 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2784 /// function overrides a virtual member function marked 'final', according to 2785 /// C++11 [class.virtual]p4. 2786 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2787 const CXXMethodDecl *Old) { 2788 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2789 if (!FA) 2790 return false; 2791 2792 Diag(New->getLocation(), diag::err_final_function_overridden) 2793 << New->getDeclName() 2794 << FA->isSpelledAsSealed(); 2795 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2796 return true; 2797 } 2798 2799 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2800 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2801 // FIXME: Destruction of ObjC lifetime types has side-effects. 2802 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2803 return !RD->isCompleteDefinition() || 2804 !RD->hasTrivialDefaultConstructor() || 2805 !RD->hasTrivialDestructor(); 2806 return false; 2807 } 2808 2809 static AttributeList *getMSPropertyAttr(AttributeList *list) { 2810 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 2811 if (it->isDeclspecPropertyAttribute()) 2812 return it; 2813 return nullptr; 2814 } 2815 2816 // Check if there is a field shadowing. 2817 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 2818 DeclarationName FieldName, 2819 const CXXRecordDecl *RD) { 2820 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 2821 return; 2822 2823 // To record a shadowed field in a base 2824 std::map<CXXRecordDecl*, NamedDecl*> Bases; 2825 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 2826 CXXBasePath &Path) { 2827 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 2828 // Record an ambiguous path directly 2829 if (Bases.find(Base) != Bases.end()) 2830 return true; 2831 for (const auto Field : Base->lookup(FieldName)) { 2832 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 2833 Field->getAccess() != AS_private) { 2834 assert(Field->getAccess() != AS_none); 2835 assert(Bases.find(Base) == Bases.end()); 2836 Bases[Base] = Field; 2837 return true; 2838 } 2839 } 2840 return false; 2841 }; 2842 2843 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2844 /*DetectVirtual=*/true); 2845 if (!RD->lookupInBases(FieldShadowed, Paths)) 2846 return; 2847 2848 for (const auto &P : Paths) { 2849 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 2850 auto It = Bases.find(Base); 2851 // Skip duplicated bases 2852 if (It == Bases.end()) 2853 continue; 2854 auto BaseField = It->second; 2855 assert(BaseField->getAccess() != AS_private); 2856 if (AS_none != 2857 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 2858 Diag(Loc, diag::warn_shadow_field) 2859 << FieldName.getAsString() << RD->getName() << Base->getName(); 2860 Diag(BaseField->getLocation(), diag::note_shadow_field); 2861 Bases.erase(It); 2862 } 2863 } 2864 } 2865 2866 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2867 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2868 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2869 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2870 /// present (but parsing it has been deferred). 2871 NamedDecl * 2872 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2873 MultiTemplateParamsArg TemplateParameterLists, 2874 Expr *BW, const VirtSpecifiers &VS, 2875 InClassInitStyle InitStyle) { 2876 const DeclSpec &DS = D.getDeclSpec(); 2877 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2878 DeclarationName Name = NameInfo.getName(); 2879 SourceLocation Loc = NameInfo.getLoc(); 2880 2881 // For anonymous bitfields, the location should point to the type. 2882 if (Loc.isInvalid()) 2883 Loc = D.getLocStart(); 2884 2885 Expr *BitWidth = static_cast<Expr*>(BW); 2886 2887 assert(isa<CXXRecordDecl>(CurContext)); 2888 assert(!DS.isFriendSpecified()); 2889 2890 bool isFunc = D.isDeclarationOfFunction(); 2891 AttributeList *MSPropertyAttr = 2892 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2893 2894 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2895 // The Microsoft extension __interface only permits public member functions 2896 // and prohibits constructors, destructors, operators, non-public member 2897 // functions, static methods and data members. 2898 unsigned InvalidDecl; 2899 bool ShowDeclName = true; 2900 if (!isFunc && 2901 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 2902 InvalidDecl = 0; 2903 else if (!isFunc) 2904 InvalidDecl = 1; 2905 else if (AS != AS_public) 2906 InvalidDecl = 2; 2907 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2908 InvalidDecl = 3; 2909 else switch (Name.getNameKind()) { 2910 case DeclarationName::CXXConstructorName: 2911 InvalidDecl = 4; 2912 ShowDeclName = false; 2913 break; 2914 2915 case DeclarationName::CXXDestructorName: 2916 InvalidDecl = 5; 2917 ShowDeclName = false; 2918 break; 2919 2920 case DeclarationName::CXXOperatorName: 2921 case DeclarationName::CXXConversionFunctionName: 2922 InvalidDecl = 6; 2923 break; 2924 2925 default: 2926 InvalidDecl = 0; 2927 break; 2928 } 2929 2930 if (InvalidDecl) { 2931 if (ShowDeclName) 2932 Diag(Loc, diag::err_invalid_member_in_interface) 2933 << (InvalidDecl-1) << Name; 2934 else 2935 Diag(Loc, diag::err_invalid_member_in_interface) 2936 << (InvalidDecl-1) << ""; 2937 return nullptr; 2938 } 2939 } 2940 2941 // C++ 9.2p6: A member shall not be declared to have automatic storage 2942 // duration (auto, register) or with the extern storage-class-specifier. 2943 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2944 // data members and cannot be applied to names declared const or static, 2945 // and cannot be applied to reference members. 2946 switch (DS.getStorageClassSpec()) { 2947 case DeclSpec::SCS_unspecified: 2948 case DeclSpec::SCS_typedef: 2949 case DeclSpec::SCS_static: 2950 break; 2951 case DeclSpec::SCS_mutable: 2952 if (isFunc) { 2953 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2954 2955 // FIXME: It would be nicer if the keyword was ignored only for this 2956 // declarator. Otherwise we could get follow-up errors. 2957 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2958 } 2959 break; 2960 default: 2961 Diag(DS.getStorageClassSpecLoc(), 2962 diag::err_storageclass_invalid_for_member); 2963 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2964 break; 2965 } 2966 2967 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2968 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2969 !isFunc); 2970 2971 if (DS.isConstexprSpecified() && isInstField) { 2972 SemaDiagnosticBuilder B = 2973 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2974 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2975 if (InitStyle == ICIS_NoInit) { 2976 B << 0 << 0; 2977 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2978 B << FixItHint::CreateRemoval(ConstexprLoc); 2979 else { 2980 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2981 D.getMutableDeclSpec().ClearConstexprSpec(); 2982 const char *PrevSpec; 2983 unsigned DiagID; 2984 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2985 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2986 (void)Failed; 2987 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2988 } 2989 } else { 2990 B << 1; 2991 const char *PrevSpec; 2992 unsigned DiagID; 2993 if (D.getMutableDeclSpec().SetStorageClassSpec( 2994 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2995 Context.getPrintingPolicy())) { 2996 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2997 "This is the only DeclSpec that should fail to be applied"); 2998 B << 1; 2999 } else { 3000 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3001 isInstField = false; 3002 } 3003 } 3004 } 3005 3006 NamedDecl *Member; 3007 if (isInstField) { 3008 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3009 3010 // Data members must have identifiers for names. 3011 if (!Name.isIdentifier()) { 3012 Diag(Loc, diag::err_bad_variable_name) 3013 << Name; 3014 return nullptr; 3015 } 3016 3017 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3018 3019 // Member field could not be with "template" keyword. 3020 // So TemplateParameterLists should be empty in this case. 3021 if (TemplateParameterLists.size()) { 3022 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3023 if (TemplateParams->size()) { 3024 // There is no such thing as a member field template. 3025 Diag(D.getIdentifierLoc(), diag::err_template_member) 3026 << II 3027 << SourceRange(TemplateParams->getTemplateLoc(), 3028 TemplateParams->getRAngleLoc()); 3029 } else { 3030 // There is an extraneous 'template<>' for this member. 3031 Diag(TemplateParams->getTemplateLoc(), 3032 diag::err_template_member_noparams) 3033 << II 3034 << SourceRange(TemplateParams->getTemplateLoc(), 3035 TemplateParams->getRAngleLoc()); 3036 } 3037 return nullptr; 3038 } 3039 3040 if (SS.isSet() && !SS.isInvalid()) { 3041 // The user provided a superfluous scope specifier inside a class 3042 // definition: 3043 // 3044 // class X { 3045 // int X::member; 3046 // }; 3047 if (DeclContext *DC = computeDeclContext(SS, false)) 3048 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 3049 else 3050 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3051 << Name << SS.getRange(); 3052 3053 SS.clear(); 3054 } 3055 3056 if (MSPropertyAttr) { 3057 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3058 BitWidth, InitStyle, AS, MSPropertyAttr); 3059 if (!Member) 3060 return nullptr; 3061 isInstField = false; 3062 } else { 3063 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3064 BitWidth, InitStyle, AS); 3065 if (!Member) 3066 return nullptr; 3067 } 3068 3069 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3070 } else { 3071 Member = HandleDeclarator(S, D, TemplateParameterLists); 3072 if (!Member) 3073 return nullptr; 3074 3075 // Non-instance-fields can't have a bitfield. 3076 if (BitWidth) { 3077 if (Member->isInvalidDecl()) { 3078 // don't emit another diagnostic. 3079 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3080 // C++ 9.6p3: A bit-field shall not be a static member. 3081 // "static member 'A' cannot be a bit-field" 3082 Diag(Loc, diag::err_static_not_bitfield) 3083 << Name << BitWidth->getSourceRange(); 3084 } else if (isa<TypedefDecl>(Member)) { 3085 // "typedef member 'x' cannot be a bit-field" 3086 Diag(Loc, diag::err_typedef_not_bitfield) 3087 << Name << BitWidth->getSourceRange(); 3088 } else { 3089 // A function typedef ("typedef int f(); f a;"). 3090 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3091 Diag(Loc, diag::err_not_integral_type_bitfield) 3092 << Name << cast<ValueDecl>(Member)->getType() 3093 << BitWidth->getSourceRange(); 3094 } 3095 3096 BitWidth = nullptr; 3097 Member->setInvalidDecl(); 3098 } 3099 3100 Member->setAccess(AS); 3101 3102 // If we have declared a member function template or static data member 3103 // template, set the access of the templated declaration as well. 3104 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3105 FunTmpl->getTemplatedDecl()->setAccess(AS); 3106 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3107 VarTmpl->getTemplatedDecl()->setAccess(AS); 3108 } 3109 3110 if (VS.isOverrideSpecified()) 3111 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3112 if (VS.isFinalSpecified()) 3113 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3114 VS.isFinalSpelledSealed())); 3115 3116 if (VS.getLastLocation().isValid()) { 3117 // Update the end location of a method that has a virt-specifiers. 3118 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3119 MD->setRangeEnd(VS.getLastLocation()); 3120 } 3121 3122 CheckOverrideControl(Member); 3123 3124 assert((Name || isInstField) && "No identifier for non-field ?"); 3125 3126 if (isInstField) { 3127 FieldDecl *FD = cast<FieldDecl>(Member); 3128 FieldCollector->Add(FD); 3129 3130 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3131 // Remember all explicit private FieldDecls that have a name, no side 3132 // effects and are not part of a dependent type declaration. 3133 if (!FD->isImplicit() && FD->getDeclName() && 3134 FD->getAccess() == AS_private && 3135 !FD->hasAttr<UnusedAttr>() && 3136 !FD->getParent()->isDependentContext() && 3137 !InitializationHasSideEffects(*FD)) 3138 UnusedPrivateFields.insert(FD); 3139 } 3140 } 3141 3142 return Member; 3143 } 3144 3145 namespace { 3146 class UninitializedFieldVisitor 3147 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3148 Sema &S; 3149 // List of Decls to generate a warning on. Also remove Decls that become 3150 // initialized. 3151 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3152 // List of base classes of the record. Classes are removed after their 3153 // initializers. 3154 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3155 // Vector of decls to be removed from the Decl set prior to visiting the 3156 // nodes. These Decls may have been initialized in the prior initializer. 3157 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3158 // If non-null, add a note to the warning pointing back to the constructor. 3159 const CXXConstructorDecl *Constructor; 3160 // Variables to hold state when processing an initializer list. When 3161 // InitList is true, special case initialization of FieldDecls matching 3162 // InitListFieldDecl. 3163 bool InitList; 3164 FieldDecl *InitListFieldDecl; 3165 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3166 3167 public: 3168 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3169 UninitializedFieldVisitor(Sema &S, 3170 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3171 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3172 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3173 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3174 3175 // Returns true if the use of ME is not an uninitialized use. 3176 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3177 bool CheckReferenceOnly) { 3178 llvm::SmallVector<FieldDecl*, 4> Fields; 3179 bool ReferenceField = false; 3180 while (ME) { 3181 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3182 if (!FD) 3183 return false; 3184 Fields.push_back(FD); 3185 if (FD->getType()->isReferenceType()) 3186 ReferenceField = true; 3187 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3188 } 3189 3190 // Binding a reference to an unintialized field is not an 3191 // uninitialized use. 3192 if (CheckReferenceOnly && !ReferenceField) 3193 return true; 3194 3195 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3196 // Discard the first field since it is the field decl that is being 3197 // initialized. 3198 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3199 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3200 } 3201 3202 for (auto UsedIter = UsedFieldIndex.begin(), 3203 UsedEnd = UsedFieldIndex.end(), 3204 OrigIter = InitFieldIndex.begin(), 3205 OrigEnd = InitFieldIndex.end(); 3206 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3207 if (*UsedIter < *OrigIter) 3208 return true; 3209 if (*UsedIter > *OrigIter) 3210 break; 3211 } 3212 3213 return false; 3214 } 3215 3216 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3217 bool AddressOf) { 3218 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3219 return; 3220 3221 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3222 // or union. 3223 MemberExpr *FieldME = ME; 3224 3225 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3226 3227 Expr *Base = ME; 3228 while (MemberExpr *SubME = 3229 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3230 3231 if (isa<VarDecl>(SubME->getMemberDecl())) 3232 return; 3233 3234 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3235 if (!FD->isAnonymousStructOrUnion()) 3236 FieldME = SubME; 3237 3238 if (!FieldME->getType().isPODType(S.Context)) 3239 AllPODFields = false; 3240 3241 Base = SubME->getBase(); 3242 } 3243 3244 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3245 return; 3246 3247 if (AddressOf && AllPODFields) 3248 return; 3249 3250 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3251 3252 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3253 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3254 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3255 } 3256 3257 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3258 QualType T = BaseCast->getType(); 3259 if (T->isPointerType() && 3260 BaseClasses.count(T->getPointeeType())) { 3261 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3262 << T->getPointeeType() << FoundVD; 3263 } 3264 } 3265 } 3266 3267 if (!Decls.count(FoundVD)) 3268 return; 3269 3270 const bool IsReference = FoundVD->getType()->isReferenceType(); 3271 3272 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3273 // Special checking for initializer lists. 3274 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3275 return; 3276 } 3277 } else { 3278 // Prevent double warnings on use of unbounded references. 3279 if (CheckReferenceOnly && !IsReference) 3280 return; 3281 } 3282 3283 unsigned diag = IsReference 3284 ? diag::warn_reference_field_is_uninit 3285 : diag::warn_field_is_uninit; 3286 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3287 if (Constructor) 3288 S.Diag(Constructor->getLocation(), 3289 diag::note_uninit_in_this_constructor) 3290 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3291 3292 } 3293 3294 void HandleValue(Expr *E, bool AddressOf) { 3295 E = E->IgnoreParens(); 3296 3297 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3298 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3299 AddressOf /*AddressOf*/); 3300 return; 3301 } 3302 3303 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3304 Visit(CO->getCond()); 3305 HandleValue(CO->getTrueExpr(), AddressOf); 3306 HandleValue(CO->getFalseExpr(), AddressOf); 3307 return; 3308 } 3309 3310 if (BinaryConditionalOperator *BCO = 3311 dyn_cast<BinaryConditionalOperator>(E)) { 3312 Visit(BCO->getCond()); 3313 HandleValue(BCO->getFalseExpr(), AddressOf); 3314 return; 3315 } 3316 3317 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3318 HandleValue(OVE->getSourceExpr(), AddressOf); 3319 return; 3320 } 3321 3322 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3323 switch (BO->getOpcode()) { 3324 default: 3325 break; 3326 case(BO_PtrMemD): 3327 case(BO_PtrMemI): 3328 HandleValue(BO->getLHS(), AddressOf); 3329 Visit(BO->getRHS()); 3330 return; 3331 case(BO_Comma): 3332 Visit(BO->getLHS()); 3333 HandleValue(BO->getRHS(), AddressOf); 3334 return; 3335 } 3336 } 3337 3338 Visit(E); 3339 } 3340 3341 void CheckInitListExpr(InitListExpr *ILE) { 3342 InitFieldIndex.push_back(0); 3343 for (auto Child : ILE->children()) { 3344 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3345 CheckInitListExpr(SubList); 3346 } else { 3347 Visit(Child); 3348 } 3349 ++InitFieldIndex.back(); 3350 } 3351 InitFieldIndex.pop_back(); 3352 } 3353 3354 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3355 FieldDecl *Field, const Type *BaseClass) { 3356 // Remove Decls that may have been initialized in the previous 3357 // initializer. 3358 for (ValueDecl* VD : DeclsToRemove) 3359 Decls.erase(VD); 3360 DeclsToRemove.clear(); 3361 3362 Constructor = FieldConstructor; 3363 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3364 3365 if (ILE && Field) { 3366 InitList = true; 3367 InitListFieldDecl = Field; 3368 InitFieldIndex.clear(); 3369 CheckInitListExpr(ILE); 3370 } else { 3371 InitList = false; 3372 Visit(E); 3373 } 3374 3375 if (Field) 3376 Decls.erase(Field); 3377 if (BaseClass) 3378 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3379 } 3380 3381 void VisitMemberExpr(MemberExpr *ME) { 3382 // All uses of unbounded reference fields will warn. 3383 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3384 } 3385 3386 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3387 if (E->getCastKind() == CK_LValueToRValue) { 3388 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3389 return; 3390 } 3391 3392 Inherited::VisitImplicitCastExpr(E); 3393 } 3394 3395 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3396 if (E->getConstructor()->isCopyConstructor()) { 3397 Expr *ArgExpr = E->getArg(0); 3398 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3399 if (ILE->getNumInits() == 1) 3400 ArgExpr = ILE->getInit(0); 3401 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3402 if (ICE->getCastKind() == CK_NoOp) 3403 ArgExpr = ICE->getSubExpr(); 3404 HandleValue(ArgExpr, false /*AddressOf*/); 3405 return; 3406 } 3407 Inherited::VisitCXXConstructExpr(E); 3408 } 3409 3410 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3411 Expr *Callee = E->getCallee(); 3412 if (isa<MemberExpr>(Callee)) { 3413 HandleValue(Callee, false /*AddressOf*/); 3414 for (auto Arg : E->arguments()) 3415 Visit(Arg); 3416 return; 3417 } 3418 3419 Inherited::VisitCXXMemberCallExpr(E); 3420 } 3421 3422 void VisitCallExpr(CallExpr *E) { 3423 // Treat std::move as a use. 3424 if (E->isCallToStdMove()) { 3425 HandleValue(E->getArg(0), /*AddressOf=*/false); 3426 return; 3427 } 3428 3429 Inherited::VisitCallExpr(E); 3430 } 3431 3432 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3433 Expr *Callee = E->getCallee(); 3434 3435 if (isa<UnresolvedLookupExpr>(Callee)) 3436 return Inherited::VisitCXXOperatorCallExpr(E); 3437 3438 Visit(Callee); 3439 for (auto Arg : E->arguments()) 3440 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3441 } 3442 3443 void VisitBinaryOperator(BinaryOperator *E) { 3444 // If a field assignment is detected, remove the field from the 3445 // uninitiailized field set. 3446 if (E->getOpcode() == BO_Assign) 3447 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3448 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3449 if (!FD->getType()->isReferenceType()) 3450 DeclsToRemove.push_back(FD); 3451 3452 if (E->isCompoundAssignmentOp()) { 3453 HandleValue(E->getLHS(), false /*AddressOf*/); 3454 Visit(E->getRHS()); 3455 return; 3456 } 3457 3458 Inherited::VisitBinaryOperator(E); 3459 } 3460 3461 void VisitUnaryOperator(UnaryOperator *E) { 3462 if (E->isIncrementDecrementOp()) { 3463 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3464 return; 3465 } 3466 if (E->getOpcode() == UO_AddrOf) { 3467 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3468 HandleValue(ME->getBase(), true /*AddressOf*/); 3469 return; 3470 } 3471 } 3472 3473 Inherited::VisitUnaryOperator(E); 3474 } 3475 }; 3476 3477 // Diagnose value-uses of fields to initialize themselves, e.g. 3478 // foo(foo) 3479 // where foo is not also a parameter to the constructor. 3480 // Also diagnose across field uninitialized use such as 3481 // x(y), y(x) 3482 // TODO: implement -Wuninitialized and fold this into that framework. 3483 static void DiagnoseUninitializedFields( 3484 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3485 3486 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3487 Constructor->getLocation())) { 3488 return; 3489 } 3490 3491 if (Constructor->isInvalidDecl()) 3492 return; 3493 3494 const CXXRecordDecl *RD = Constructor->getParent(); 3495 3496 if (RD->getDescribedClassTemplate()) 3497 return; 3498 3499 // Holds fields that are uninitialized. 3500 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3501 3502 // At the beginning, all fields are uninitialized. 3503 for (auto *I : RD->decls()) { 3504 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3505 UninitializedFields.insert(FD); 3506 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3507 UninitializedFields.insert(IFD->getAnonField()); 3508 } 3509 } 3510 3511 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3512 for (auto I : RD->bases()) 3513 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3514 3515 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3516 return; 3517 3518 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3519 UninitializedFields, 3520 UninitializedBaseClasses); 3521 3522 for (const auto *FieldInit : Constructor->inits()) { 3523 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3524 break; 3525 3526 Expr *InitExpr = FieldInit->getInit(); 3527 if (!InitExpr) 3528 continue; 3529 3530 if (CXXDefaultInitExpr *Default = 3531 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3532 InitExpr = Default->getExpr(); 3533 if (!InitExpr) 3534 continue; 3535 // In class initializers will point to the constructor. 3536 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3537 FieldInit->getAnyMember(), 3538 FieldInit->getBaseClass()); 3539 } else { 3540 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3541 FieldInit->getAnyMember(), 3542 FieldInit->getBaseClass()); 3543 } 3544 } 3545 } 3546 } // namespace 3547 3548 /// \brief Enter a new C++ default initializer scope. After calling this, the 3549 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3550 /// parsing or instantiating the initializer failed. 3551 void Sema::ActOnStartCXXInClassMemberInitializer() { 3552 // Create a synthetic function scope to represent the call to the constructor 3553 // that notionally surrounds a use of this initializer. 3554 PushFunctionScope(); 3555 } 3556 3557 /// \brief This is invoked after parsing an in-class initializer for a 3558 /// non-static C++ class member, and after instantiating an in-class initializer 3559 /// in a class template. Such actions are deferred until the class is complete. 3560 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3561 SourceLocation InitLoc, 3562 Expr *InitExpr) { 3563 // Pop the notional constructor scope we created earlier. 3564 PopFunctionScopeInfo(nullptr, D); 3565 3566 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3567 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3568 "must set init style when field is created"); 3569 3570 if (!InitExpr) { 3571 D->setInvalidDecl(); 3572 if (FD) 3573 FD->removeInClassInitializer(); 3574 return; 3575 } 3576 3577 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3578 FD->setInvalidDecl(); 3579 FD->removeInClassInitializer(); 3580 return; 3581 } 3582 3583 ExprResult Init = InitExpr; 3584 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3585 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 3586 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 3587 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 3588 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 3589 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3590 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3591 if (Init.isInvalid()) { 3592 FD->setInvalidDecl(); 3593 return; 3594 } 3595 } 3596 3597 // C++11 [class.base.init]p7: 3598 // The initialization of each base and member constitutes a 3599 // full-expression. 3600 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 3601 if (Init.isInvalid()) { 3602 FD->setInvalidDecl(); 3603 return; 3604 } 3605 3606 InitExpr = Init.get(); 3607 3608 FD->setInClassInitializer(InitExpr); 3609 } 3610 3611 /// \brief Find the direct and/or virtual base specifiers that 3612 /// correspond to the given base type, for use in base initialization 3613 /// within a constructor. 3614 static bool FindBaseInitializer(Sema &SemaRef, 3615 CXXRecordDecl *ClassDecl, 3616 QualType BaseType, 3617 const CXXBaseSpecifier *&DirectBaseSpec, 3618 const CXXBaseSpecifier *&VirtualBaseSpec) { 3619 // First, check for a direct base class. 3620 DirectBaseSpec = nullptr; 3621 for (const auto &Base : ClassDecl->bases()) { 3622 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3623 // We found a direct base of this type. That's what we're 3624 // initializing. 3625 DirectBaseSpec = &Base; 3626 break; 3627 } 3628 } 3629 3630 // Check for a virtual base class. 3631 // FIXME: We might be able to short-circuit this if we know in advance that 3632 // there are no virtual bases. 3633 VirtualBaseSpec = nullptr; 3634 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3635 // We haven't found a base yet; search the class hierarchy for a 3636 // virtual base class. 3637 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3638 /*DetectVirtual=*/false); 3639 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3640 SemaRef.Context.getTypeDeclType(ClassDecl), 3641 BaseType, Paths)) { 3642 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3643 Path != Paths.end(); ++Path) { 3644 if (Path->back().Base->isVirtual()) { 3645 VirtualBaseSpec = Path->back().Base; 3646 break; 3647 } 3648 } 3649 } 3650 } 3651 3652 return DirectBaseSpec || VirtualBaseSpec; 3653 } 3654 3655 /// \brief Handle a C++ member initializer using braced-init-list syntax. 3656 MemInitResult 3657 Sema::ActOnMemInitializer(Decl *ConstructorD, 3658 Scope *S, 3659 CXXScopeSpec &SS, 3660 IdentifierInfo *MemberOrBase, 3661 ParsedType TemplateTypeTy, 3662 const DeclSpec &DS, 3663 SourceLocation IdLoc, 3664 Expr *InitList, 3665 SourceLocation EllipsisLoc) { 3666 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3667 DS, IdLoc, InitList, 3668 EllipsisLoc); 3669 } 3670 3671 /// \brief Handle a C++ member initializer using parentheses syntax. 3672 MemInitResult 3673 Sema::ActOnMemInitializer(Decl *ConstructorD, 3674 Scope *S, 3675 CXXScopeSpec &SS, 3676 IdentifierInfo *MemberOrBase, 3677 ParsedType TemplateTypeTy, 3678 const DeclSpec &DS, 3679 SourceLocation IdLoc, 3680 SourceLocation LParenLoc, 3681 ArrayRef<Expr *> Args, 3682 SourceLocation RParenLoc, 3683 SourceLocation EllipsisLoc) { 3684 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 3685 Args, RParenLoc); 3686 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3687 DS, IdLoc, List, EllipsisLoc); 3688 } 3689 3690 namespace { 3691 3692 // Callback to only accept typo corrections that can be a valid C++ member 3693 // intializer: either a non-static field member or a base class. 3694 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 3695 public: 3696 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3697 : ClassDecl(ClassDecl) {} 3698 3699 bool ValidateCandidate(const TypoCorrection &candidate) override { 3700 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3701 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3702 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3703 return isa<TypeDecl>(ND); 3704 } 3705 return false; 3706 } 3707 3708 private: 3709 CXXRecordDecl *ClassDecl; 3710 }; 3711 3712 } 3713 3714 /// \brief Handle a C++ member initializer. 3715 MemInitResult 3716 Sema::BuildMemInitializer(Decl *ConstructorD, 3717 Scope *S, 3718 CXXScopeSpec &SS, 3719 IdentifierInfo *MemberOrBase, 3720 ParsedType TemplateTypeTy, 3721 const DeclSpec &DS, 3722 SourceLocation IdLoc, 3723 Expr *Init, 3724 SourceLocation EllipsisLoc) { 3725 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3726 if (!Res.isUsable()) 3727 return true; 3728 Init = Res.get(); 3729 3730 if (!ConstructorD) 3731 return true; 3732 3733 AdjustDeclIfTemplate(ConstructorD); 3734 3735 CXXConstructorDecl *Constructor 3736 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3737 if (!Constructor) { 3738 // The user wrote a constructor initializer on a function that is 3739 // not a C++ constructor. Ignore the error for now, because we may 3740 // have more member initializers coming; we'll diagnose it just 3741 // once in ActOnMemInitializers. 3742 return true; 3743 } 3744 3745 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3746 3747 // C++ [class.base.init]p2: 3748 // Names in a mem-initializer-id are looked up in the scope of the 3749 // constructor's class and, if not found in that scope, are looked 3750 // up in the scope containing the constructor's definition. 3751 // [Note: if the constructor's class contains a member with the 3752 // same name as a direct or virtual base class of the class, a 3753 // mem-initializer-id naming the member or base class and composed 3754 // of a single identifier refers to the class member. A 3755 // mem-initializer-id for the hidden base class may be specified 3756 // using a qualified name. ] 3757 if (!SS.getScopeRep() && !TemplateTypeTy) { 3758 // Look for a member, first. 3759 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3760 if (!Result.empty()) { 3761 ValueDecl *Member; 3762 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3763 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 3764 if (EllipsisLoc.isValid()) 3765 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 3766 << MemberOrBase 3767 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 3768 3769 return BuildMemberInitializer(Member, Init, IdLoc); 3770 } 3771 } 3772 } 3773 // It didn't name a member, so see if it names a class. 3774 QualType BaseType; 3775 TypeSourceInfo *TInfo = nullptr; 3776 3777 if (TemplateTypeTy) { 3778 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 3779 } else if (DS.getTypeSpecType() == TST_decltype) { 3780 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3781 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 3782 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 3783 return true; 3784 } else { 3785 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 3786 LookupParsedName(R, S, &SS); 3787 3788 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 3789 if (!TyD) { 3790 if (R.isAmbiguous()) return true; 3791 3792 // We don't want access-control diagnostics here. 3793 R.suppressDiagnostics(); 3794 3795 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 3796 bool NotUnknownSpecialization = false; 3797 DeclContext *DC = computeDeclContext(SS, false); 3798 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 3799 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 3800 3801 if (!NotUnknownSpecialization) { 3802 // When the scope specifier can refer to a member of an unknown 3803 // specialization, we take it as a type name. 3804 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 3805 SS.getWithLocInContext(Context), 3806 *MemberOrBase, IdLoc); 3807 if (BaseType.isNull()) 3808 return true; 3809 3810 TInfo = Context.CreateTypeSourceInfo(BaseType); 3811 DependentNameTypeLoc TL = 3812 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 3813 if (!TL.isNull()) { 3814 TL.setNameLoc(IdLoc); 3815 TL.setElaboratedKeywordLoc(SourceLocation()); 3816 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3817 } 3818 3819 R.clear(); 3820 R.setLookupName(MemberOrBase); 3821 } 3822 } 3823 3824 // If no results were found, try to correct typos. 3825 TypoCorrection Corr; 3826 if (R.empty() && BaseType.isNull() && 3827 (Corr = CorrectTypo( 3828 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 3829 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 3830 CTK_ErrorRecovery, ClassDecl))) { 3831 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 3832 // We have found a non-static data member with a similar 3833 // name to what was typed; complain and initialize that 3834 // member. 3835 diagnoseTypo(Corr, 3836 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3837 << MemberOrBase << true); 3838 return BuildMemberInitializer(Member, Init, IdLoc); 3839 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3840 const CXXBaseSpecifier *DirectBaseSpec; 3841 const CXXBaseSpecifier *VirtualBaseSpec; 3842 if (FindBaseInitializer(*this, ClassDecl, 3843 Context.getTypeDeclType(Type), 3844 DirectBaseSpec, VirtualBaseSpec)) { 3845 // We have found a direct or virtual base class with a 3846 // similar name to what was typed; complain and initialize 3847 // that base class. 3848 diagnoseTypo(Corr, 3849 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3850 << MemberOrBase << false, 3851 PDiag() /*Suppress note, we provide our own.*/); 3852 3853 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3854 : VirtualBaseSpec; 3855 Diag(BaseSpec->getLocStart(), 3856 diag::note_base_class_specified_here) 3857 << BaseSpec->getType() 3858 << BaseSpec->getSourceRange(); 3859 3860 TyD = Type; 3861 } 3862 } 3863 } 3864 3865 if (!TyD && BaseType.isNull()) { 3866 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3867 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3868 return true; 3869 } 3870 } 3871 3872 if (BaseType.isNull()) { 3873 BaseType = Context.getTypeDeclType(TyD); 3874 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3875 if (SS.isSet()) { 3876 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3877 BaseType); 3878 TInfo = Context.CreateTypeSourceInfo(BaseType); 3879 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 3880 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 3881 TL.setElaboratedKeywordLoc(SourceLocation()); 3882 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3883 } 3884 } 3885 } 3886 3887 if (!TInfo) 3888 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3889 3890 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3891 } 3892 3893 /// Checks a member initializer expression for cases where reference (or 3894 /// pointer) members are bound to by-value parameters (or their addresses). 3895 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 3896 Expr *Init, 3897 SourceLocation IdLoc) { 3898 QualType MemberTy = Member->getType(); 3899 3900 // We only handle pointers and references currently. 3901 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3902 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3903 return; 3904 3905 const bool IsPointer = MemberTy->isPointerType(); 3906 if (IsPointer) { 3907 if (const UnaryOperator *Op 3908 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3909 // The only case we're worried about with pointers requires taking the 3910 // address. 3911 if (Op->getOpcode() != UO_AddrOf) 3912 return; 3913 3914 Init = Op->getSubExpr(); 3915 } else { 3916 // We only handle address-of expression initializers for pointers. 3917 return; 3918 } 3919 } 3920 3921 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3922 // We only warn when referring to a non-reference parameter declaration. 3923 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3924 if (!Parameter || Parameter->getType()->isReferenceType()) 3925 return; 3926 3927 S.Diag(Init->getExprLoc(), 3928 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3929 : diag::warn_bind_ref_member_to_parameter) 3930 << Member << Parameter << Init->getSourceRange(); 3931 } else { 3932 // Other initializers are fine. 3933 return; 3934 } 3935 3936 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3937 << (unsigned)IsPointer; 3938 } 3939 3940 MemInitResult 3941 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3942 SourceLocation IdLoc) { 3943 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3944 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3945 assert((DirectMember || IndirectMember) && 3946 "Member must be a FieldDecl or IndirectFieldDecl"); 3947 3948 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3949 return true; 3950 3951 if (Member->isInvalidDecl()) 3952 return true; 3953 3954 MultiExprArg Args; 3955 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3956 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3957 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3958 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3959 } else { 3960 // Template instantiation doesn't reconstruct ParenListExprs for us. 3961 Args = Init; 3962 } 3963 3964 SourceRange InitRange = Init->getSourceRange(); 3965 3966 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3967 // Can't check initialization for a member of dependent type or when 3968 // any of the arguments are type-dependent expressions. 3969 DiscardCleanupsInEvaluationContext(); 3970 } else { 3971 bool InitList = false; 3972 if (isa<InitListExpr>(Init)) { 3973 InitList = true; 3974 Args = Init; 3975 } 3976 3977 // Initialize the member. 3978 InitializedEntity MemberEntity = 3979 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3980 : InitializedEntity::InitializeMember(IndirectMember, 3981 nullptr); 3982 InitializationKind Kind = 3983 InitList ? InitializationKind::CreateDirectList(IdLoc) 3984 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3985 InitRange.getEnd()); 3986 3987 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3988 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3989 nullptr); 3990 if (MemberInit.isInvalid()) 3991 return true; 3992 3993 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3994 3995 // C++11 [class.base.init]p7: 3996 // The initialization of each base and member constitutes a 3997 // full-expression. 3998 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3999 if (MemberInit.isInvalid()) 4000 return true; 4001 4002 Init = MemberInit.get(); 4003 } 4004 4005 if (DirectMember) { 4006 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4007 InitRange.getBegin(), Init, 4008 InitRange.getEnd()); 4009 } else { 4010 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4011 InitRange.getBegin(), Init, 4012 InitRange.getEnd()); 4013 } 4014 } 4015 4016 MemInitResult 4017 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4018 CXXRecordDecl *ClassDecl) { 4019 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4020 if (!LangOpts.CPlusPlus11) 4021 return Diag(NameLoc, diag::err_delegating_ctor) 4022 << TInfo->getTypeLoc().getLocalSourceRange(); 4023 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4024 4025 bool InitList = true; 4026 MultiExprArg Args = Init; 4027 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4028 InitList = false; 4029 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4030 } 4031 4032 SourceRange InitRange = Init->getSourceRange(); 4033 // Initialize the object. 4034 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4035 QualType(ClassDecl->getTypeForDecl(), 0)); 4036 InitializationKind Kind = 4037 InitList ? InitializationKind::CreateDirectList(NameLoc) 4038 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4039 InitRange.getEnd()); 4040 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4041 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4042 Args, nullptr); 4043 if (DelegationInit.isInvalid()) 4044 return true; 4045 4046 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4047 "Delegating constructor with no target?"); 4048 4049 // C++11 [class.base.init]p7: 4050 // The initialization of each base and member constitutes a 4051 // full-expression. 4052 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 4053 InitRange.getBegin()); 4054 if (DelegationInit.isInvalid()) 4055 return true; 4056 4057 // If we are in a dependent context, template instantiation will 4058 // perform this type-checking again. Just save the arguments that we 4059 // received in a ParenListExpr. 4060 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4061 // of the information that we have about the base 4062 // initializer. However, deconstructing the ASTs is a dicey process, 4063 // and this approach is far more likely to get the corner cases right. 4064 if (CurContext->isDependentContext()) 4065 DelegationInit = Init; 4066 4067 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4068 DelegationInit.getAs<Expr>(), 4069 InitRange.getEnd()); 4070 } 4071 4072 MemInitResult 4073 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4074 Expr *Init, CXXRecordDecl *ClassDecl, 4075 SourceLocation EllipsisLoc) { 4076 SourceLocation BaseLoc 4077 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4078 4079 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4080 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4081 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4082 4083 // C++ [class.base.init]p2: 4084 // [...] Unless the mem-initializer-id names a nonstatic data 4085 // member of the constructor's class or a direct or virtual base 4086 // of that class, the mem-initializer is ill-formed. A 4087 // mem-initializer-list can initialize a base class using any 4088 // name that denotes that base class type. 4089 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4090 4091 SourceRange InitRange = Init->getSourceRange(); 4092 if (EllipsisLoc.isValid()) { 4093 // This is a pack expansion. 4094 if (!BaseType->containsUnexpandedParameterPack()) { 4095 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4096 << SourceRange(BaseLoc, InitRange.getEnd()); 4097 4098 EllipsisLoc = SourceLocation(); 4099 } 4100 } else { 4101 // Check for any unexpanded parameter packs. 4102 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4103 return true; 4104 4105 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4106 return true; 4107 } 4108 4109 // Check for direct and virtual base classes. 4110 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4111 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4112 if (!Dependent) { 4113 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4114 BaseType)) 4115 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4116 4117 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4118 VirtualBaseSpec); 4119 4120 // C++ [base.class.init]p2: 4121 // Unless the mem-initializer-id names a nonstatic data member of the 4122 // constructor's class or a direct or virtual base of that class, the 4123 // mem-initializer is ill-formed. 4124 if (!DirectBaseSpec && !VirtualBaseSpec) { 4125 // If the class has any dependent bases, then it's possible that 4126 // one of those types will resolve to the same type as 4127 // BaseType. Therefore, just treat this as a dependent base 4128 // class initialization. FIXME: Should we try to check the 4129 // initialization anyway? It seems odd. 4130 if (ClassDecl->hasAnyDependentBases()) 4131 Dependent = true; 4132 else 4133 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4134 << BaseType << Context.getTypeDeclType(ClassDecl) 4135 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4136 } 4137 } 4138 4139 if (Dependent) { 4140 DiscardCleanupsInEvaluationContext(); 4141 4142 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4143 /*IsVirtual=*/false, 4144 InitRange.getBegin(), Init, 4145 InitRange.getEnd(), EllipsisLoc); 4146 } 4147 4148 // C++ [base.class.init]p2: 4149 // If a mem-initializer-id is ambiguous because it designates both 4150 // a direct non-virtual base class and an inherited virtual base 4151 // class, the mem-initializer is ill-formed. 4152 if (DirectBaseSpec && VirtualBaseSpec) 4153 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4154 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4155 4156 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4157 if (!BaseSpec) 4158 BaseSpec = VirtualBaseSpec; 4159 4160 // Initialize the base. 4161 bool InitList = true; 4162 MultiExprArg Args = Init; 4163 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4164 InitList = false; 4165 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4166 } 4167 4168 InitializedEntity BaseEntity = 4169 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4170 InitializationKind Kind = 4171 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4172 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4173 InitRange.getEnd()); 4174 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4175 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4176 if (BaseInit.isInvalid()) 4177 return true; 4178 4179 // C++11 [class.base.init]p7: 4180 // The initialization of each base and member constitutes a 4181 // full-expression. 4182 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 4183 if (BaseInit.isInvalid()) 4184 return true; 4185 4186 // If we are in a dependent context, template instantiation will 4187 // perform this type-checking again. Just save the arguments that we 4188 // received in a ParenListExpr. 4189 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4190 // of the information that we have about the base 4191 // initializer. However, deconstructing the ASTs is a dicey process, 4192 // and this approach is far more likely to get the corner cases right. 4193 if (CurContext->isDependentContext()) 4194 BaseInit = Init; 4195 4196 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4197 BaseSpec->isVirtual(), 4198 InitRange.getBegin(), 4199 BaseInit.getAs<Expr>(), 4200 InitRange.getEnd(), EllipsisLoc); 4201 } 4202 4203 // Create a static_cast\<T&&>(expr). 4204 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4205 if (T.isNull()) T = E->getType(); 4206 QualType TargetType = SemaRef.BuildReferenceType( 4207 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4208 SourceLocation ExprLoc = E->getLocStart(); 4209 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4210 TargetType, ExprLoc); 4211 4212 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4213 SourceRange(ExprLoc, ExprLoc), 4214 E->getSourceRange()).get(); 4215 } 4216 4217 /// ImplicitInitializerKind - How an implicit base or member initializer should 4218 /// initialize its base or member. 4219 enum ImplicitInitializerKind { 4220 IIK_Default, 4221 IIK_Copy, 4222 IIK_Move, 4223 IIK_Inherit 4224 }; 4225 4226 static bool 4227 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4228 ImplicitInitializerKind ImplicitInitKind, 4229 CXXBaseSpecifier *BaseSpec, 4230 bool IsInheritedVirtualBase, 4231 CXXCtorInitializer *&CXXBaseInit) { 4232 InitializedEntity InitEntity 4233 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4234 IsInheritedVirtualBase); 4235 4236 ExprResult BaseInit; 4237 4238 switch (ImplicitInitKind) { 4239 case IIK_Inherit: 4240 case IIK_Default: { 4241 InitializationKind InitKind 4242 = InitializationKind::CreateDefault(Constructor->getLocation()); 4243 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4244 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4245 break; 4246 } 4247 4248 case IIK_Move: 4249 case IIK_Copy: { 4250 bool Moving = ImplicitInitKind == IIK_Move; 4251 ParmVarDecl *Param = Constructor->getParamDecl(0); 4252 QualType ParamType = Param->getType().getNonReferenceType(); 4253 4254 Expr *CopyCtorArg = 4255 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4256 SourceLocation(), Param, false, 4257 Constructor->getLocation(), ParamType, 4258 VK_LValue, nullptr); 4259 4260 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4261 4262 // Cast to the base class to avoid ambiguities. 4263 QualType ArgTy = 4264 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4265 ParamType.getQualifiers()); 4266 4267 if (Moving) { 4268 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4269 } 4270 4271 CXXCastPath BasePath; 4272 BasePath.push_back(BaseSpec); 4273 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4274 CK_UncheckedDerivedToBase, 4275 Moving ? VK_XValue : VK_LValue, 4276 &BasePath).get(); 4277 4278 InitializationKind InitKind 4279 = InitializationKind::CreateDirect(Constructor->getLocation(), 4280 SourceLocation(), SourceLocation()); 4281 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4282 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4283 break; 4284 } 4285 } 4286 4287 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4288 if (BaseInit.isInvalid()) 4289 return true; 4290 4291 CXXBaseInit = 4292 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4293 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4294 SourceLocation()), 4295 BaseSpec->isVirtual(), 4296 SourceLocation(), 4297 BaseInit.getAs<Expr>(), 4298 SourceLocation(), 4299 SourceLocation()); 4300 4301 return false; 4302 } 4303 4304 static bool RefersToRValueRef(Expr *MemRef) { 4305 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4306 return Referenced->getType()->isRValueReferenceType(); 4307 } 4308 4309 static bool 4310 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4311 ImplicitInitializerKind ImplicitInitKind, 4312 FieldDecl *Field, IndirectFieldDecl *Indirect, 4313 CXXCtorInitializer *&CXXMemberInit) { 4314 if (Field->isInvalidDecl()) 4315 return true; 4316 4317 SourceLocation Loc = Constructor->getLocation(); 4318 4319 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4320 bool Moving = ImplicitInitKind == IIK_Move; 4321 ParmVarDecl *Param = Constructor->getParamDecl(0); 4322 QualType ParamType = Param->getType().getNonReferenceType(); 4323 4324 // Suppress copying zero-width bitfields. 4325 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 4326 return false; 4327 4328 Expr *MemberExprBase = 4329 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4330 SourceLocation(), Param, false, 4331 Loc, ParamType, VK_LValue, nullptr); 4332 4333 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4334 4335 if (Moving) { 4336 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4337 } 4338 4339 // Build a reference to this field within the parameter. 4340 CXXScopeSpec SS; 4341 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4342 Sema::LookupMemberName); 4343 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4344 : cast<ValueDecl>(Field), AS_public); 4345 MemberLookup.resolveKind(); 4346 ExprResult CtorArg 4347 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4348 ParamType, Loc, 4349 /*IsArrow=*/false, 4350 SS, 4351 /*TemplateKWLoc=*/SourceLocation(), 4352 /*FirstQualifierInScope=*/nullptr, 4353 MemberLookup, 4354 /*TemplateArgs=*/nullptr, 4355 /*S*/nullptr); 4356 if (CtorArg.isInvalid()) 4357 return true; 4358 4359 // C++11 [class.copy]p15: 4360 // - if a member m has rvalue reference type T&&, it is direct-initialized 4361 // with static_cast<T&&>(x.m); 4362 if (RefersToRValueRef(CtorArg.get())) { 4363 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4364 } 4365 4366 InitializedEntity Entity = 4367 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4368 /*Implicit*/ true) 4369 : InitializedEntity::InitializeMember(Field, nullptr, 4370 /*Implicit*/ true); 4371 4372 // Direct-initialize to use the copy constructor. 4373 InitializationKind InitKind = 4374 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4375 4376 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4377 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4378 ExprResult MemberInit = 4379 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4380 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4381 if (MemberInit.isInvalid()) 4382 return true; 4383 4384 if (Indirect) 4385 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4386 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4387 else 4388 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4389 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4390 return false; 4391 } 4392 4393 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4394 "Unhandled implicit init kind!"); 4395 4396 QualType FieldBaseElementType = 4397 SemaRef.Context.getBaseElementType(Field->getType()); 4398 4399 if (FieldBaseElementType->isRecordType()) { 4400 InitializedEntity InitEntity = 4401 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4402 /*Implicit*/ true) 4403 : InitializedEntity::InitializeMember(Field, nullptr, 4404 /*Implicit*/ true); 4405 InitializationKind InitKind = 4406 InitializationKind::CreateDefault(Loc); 4407 4408 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4409 ExprResult MemberInit = 4410 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4411 4412 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4413 if (MemberInit.isInvalid()) 4414 return true; 4415 4416 if (Indirect) 4417 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4418 Indirect, Loc, 4419 Loc, 4420 MemberInit.get(), 4421 Loc); 4422 else 4423 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4424 Field, Loc, Loc, 4425 MemberInit.get(), 4426 Loc); 4427 return false; 4428 } 4429 4430 if (!Field->getParent()->isUnion()) { 4431 if (FieldBaseElementType->isReferenceType()) { 4432 SemaRef.Diag(Constructor->getLocation(), 4433 diag::err_uninitialized_member_in_ctor) 4434 << (int)Constructor->isImplicit() 4435 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4436 << 0 << Field->getDeclName(); 4437 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4438 return true; 4439 } 4440 4441 if (FieldBaseElementType.isConstQualified()) { 4442 SemaRef.Diag(Constructor->getLocation(), 4443 diag::err_uninitialized_member_in_ctor) 4444 << (int)Constructor->isImplicit() 4445 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4446 << 1 << Field->getDeclName(); 4447 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4448 return true; 4449 } 4450 } 4451 4452 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4453 // ARC and Weak: 4454 // Default-initialize Objective-C pointers to NULL. 4455 CXXMemberInit 4456 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4457 Loc, Loc, 4458 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4459 Loc); 4460 return false; 4461 } 4462 4463 // Nothing to initialize. 4464 CXXMemberInit = nullptr; 4465 return false; 4466 } 4467 4468 namespace { 4469 struct BaseAndFieldInfo { 4470 Sema &S; 4471 CXXConstructorDecl *Ctor; 4472 bool AnyErrorsInInits; 4473 ImplicitInitializerKind IIK; 4474 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4475 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4476 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4477 4478 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4479 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4480 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4481 if (Ctor->getInheritedConstructor()) 4482 IIK = IIK_Inherit; 4483 else if (Generated && Ctor->isCopyConstructor()) 4484 IIK = IIK_Copy; 4485 else if (Generated && Ctor->isMoveConstructor()) 4486 IIK = IIK_Move; 4487 else 4488 IIK = IIK_Default; 4489 } 4490 4491 bool isImplicitCopyOrMove() const { 4492 switch (IIK) { 4493 case IIK_Copy: 4494 case IIK_Move: 4495 return true; 4496 4497 case IIK_Default: 4498 case IIK_Inherit: 4499 return false; 4500 } 4501 4502 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4503 } 4504 4505 bool addFieldInitializer(CXXCtorInitializer *Init) { 4506 AllToInit.push_back(Init); 4507 4508 // Check whether this initializer makes the field "used". 4509 if (Init->getInit()->HasSideEffects(S.Context)) 4510 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4511 4512 return false; 4513 } 4514 4515 bool isInactiveUnionMember(FieldDecl *Field) { 4516 RecordDecl *Record = Field->getParent(); 4517 if (!Record->isUnion()) 4518 return false; 4519 4520 if (FieldDecl *Active = 4521 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4522 return Active != Field->getCanonicalDecl(); 4523 4524 // In an implicit copy or move constructor, ignore any in-class initializer. 4525 if (isImplicitCopyOrMove()) 4526 return true; 4527 4528 // If there's no explicit initialization, the field is active only if it 4529 // has an in-class initializer... 4530 if (Field->hasInClassInitializer()) 4531 return false; 4532 // ... or it's an anonymous struct or union whose class has an in-class 4533 // initializer. 4534 if (!Field->isAnonymousStructOrUnion()) 4535 return true; 4536 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4537 return !FieldRD->hasInClassInitializer(); 4538 } 4539 4540 /// \brief Determine whether the given field is, or is within, a union member 4541 /// that is inactive (because there was an initializer given for a different 4542 /// member of the union, or because the union was not initialized at all). 4543 bool isWithinInactiveUnionMember(FieldDecl *Field, 4544 IndirectFieldDecl *Indirect) { 4545 if (!Indirect) 4546 return isInactiveUnionMember(Field); 4547 4548 for (auto *C : Indirect->chain()) { 4549 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4550 if (Field && isInactiveUnionMember(Field)) 4551 return true; 4552 } 4553 return false; 4554 } 4555 }; 4556 } 4557 4558 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 4559 /// array type. 4560 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4561 if (T->isIncompleteArrayType()) 4562 return true; 4563 4564 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4565 if (!ArrayT->getSize()) 4566 return true; 4567 4568 T = ArrayT->getElementType(); 4569 } 4570 4571 return false; 4572 } 4573 4574 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4575 FieldDecl *Field, 4576 IndirectFieldDecl *Indirect = nullptr) { 4577 if (Field->isInvalidDecl()) 4578 return false; 4579 4580 // Overwhelmingly common case: we have a direct initializer for this field. 4581 if (CXXCtorInitializer *Init = 4582 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4583 return Info.addFieldInitializer(Init); 4584 4585 // C++11 [class.base.init]p8: 4586 // if the entity is a non-static data member that has a 4587 // brace-or-equal-initializer and either 4588 // -- the constructor's class is a union and no other variant member of that 4589 // union is designated by a mem-initializer-id or 4590 // -- the constructor's class is not a union, and, if the entity is a member 4591 // of an anonymous union, no other member of that union is designated by 4592 // a mem-initializer-id, 4593 // the entity is initialized as specified in [dcl.init]. 4594 // 4595 // We also apply the same rules to handle anonymous structs within anonymous 4596 // unions. 4597 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4598 return false; 4599 4600 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4601 ExprResult DIE = 4602 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4603 if (DIE.isInvalid()) 4604 return true; 4605 CXXCtorInitializer *Init; 4606 if (Indirect) 4607 Init = new (SemaRef.Context) 4608 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4609 SourceLocation(), DIE.get(), SourceLocation()); 4610 else 4611 Init = new (SemaRef.Context) 4612 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4613 SourceLocation(), DIE.get(), SourceLocation()); 4614 return Info.addFieldInitializer(Init); 4615 } 4616 4617 // Don't initialize incomplete or zero-length arrays. 4618 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4619 return false; 4620 4621 // Don't try to build an implicit initializer if there were semantic 4622 // errors in any of the initializers (and therefore we might be 4623 // missing some that the user actually wrote). 4624 if (Info.AnyErrorsInInits) 4625 return false; 4626 4627 CXXCtorInitializer *Init = nullptr; 4628 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4629 Indirect, Init)) 4630 return true; 4631 4632 if (!Init) 4633 return false; 4634 4635 return Info.addFieldInitializer(Init); 4636 } 4637 4638 bool 4639 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4640 CXXCtorInitializer *Initializer) { 4641 assert(Initializer->isDelegatingInitializer()); 4642 Constructor->setNumCtorInitializers(1); 4643 CXXCtorInitializer **initializer = 4644 new (Context) CXXCtorInitializer*[1]; 4645 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4646 Constructor->setCtorInitializers(initializer); 4647 4648 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4649 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4650 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4651 } 4652 4653 DelegatingCtorDecls.push_back(Constructor); 4654 4655 DiagnoseUninitializedFields(*this, Constructor); 4656 4657 return false; 4658 } 4659 4660 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4661 ArrayRef<CXXCtorInitializer *> Initializers) { 4662 if (Constructor->isDependentContext()) { 4663 // Just store the initializers as written, they will be checked during 4664 // instantiation. 4665 if (!Initializers.empty()) { 4666 Constructor->setNumCtorInitializers(Initializers.size()); 4667 CXXCtorInitializer **baseOrMemberInitializers = 4668 new (Context) CXXCtorInitializer*[Initializers.size()]; 4669 memcpy(baseOrMemberInitializers, Initializers.data(), 4670 Initializers.size() * sizeof(CXXCtorInitializer*)); 4671 Constructor->setCtorInitializers(baseOrMemberInitializers); 4672 } 4673 4674 // Let template instantiation know whether we had errors. 4675 if (AnyErrors) 4676 Constructor->setInvalidDecl(); 4677 4678 return false; 4679 } 4680 4681 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4682 4683 // We need to build the initializer AST according to order of construction 4684 // and not what user specified in the Initializers list. 4685 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4686 if (!ClassDecl) 4687 return true; 4688 4689 bool HadError = false; 4690 4691 for (unsigned i = 0; i < Initializers.size(); i++) { 4692 CXXCtorInitializer *Member = Initializers[i]; 4693 4694 if (Member->isBaseInitializer()) 4695 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4696 else { 4697 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4698 4699 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4700 for (auto *C : F->chain()) { 4701 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4702 if (FD && FD->getParent()->isUnion()) 4703 Info.ActiveUnionMember.insert(std::make_pair( 4704 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4705 } 4706 } else if (FieldDecl *FD = Member->getMember()) { 4707 if (FD->getParent()->isUnion()) 4708 Info.ActiveUnionMember.insert(std::make_pair( 4709 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4710 } 4711 } 4712 } 4713 4714 // Keep track of the direct virtual bases. 4715 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4716 for (auto &I : ClassDecl->bases()) { 4717 if (I.isVirtual()) 4718 DirectVBases.insert(&I); 4719 } 4720 4721 // Push virtual bases before others. 4722 for (auto &VBase : ClassDecl->vbases()) { 4723 if (CXXCtorInitializer *Value 4724 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4725 // [class.base.init]p7, per DR257: 4726 // A mem-initializer where the mem-initializer-id names a virtual base 4727 // class is ignored during execution of a constructor of any class that 4728 // is not the most derived class. 4729 if (ClassDecl->isAbstract()) { 4730 // FIXME: Provide a fixit to remove the base specifier. This requires 4731 // tracking the location of the associated comma for a base specifier. 4732 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4733 << VBase.getType() << ClassDecl; 4734 DiagnoseAbstractType(ClassDecl); 4735 } 4736 4737 Info.AllToInit.push_back(Value); 4738 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4739 // [class.base.init]p8, per DR257: 4740 // If a given [...] base class is not named by a mem-initializer-id 4741 // [...] and the entity is not a virtual base class of an abstract 4742 // class, then [...] the entity is default-initialized. 4743 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4744 CXXCtorInitializer *CXXBaseInit; 4745 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4746 &VBase, IsInheritedVirtualBase, 4747 CXXBaseInit)) { 4748 HadError = true; 4749 continue; 4750 } 4751 4752 Info.AllToInit.push_back(CXXBaseInit); 4753 } 4754 } 4755 4756 // Non-virtual bases. 4757 for (auto &Base : ClassDecl->bases()) { 4758 // Virtuals are in the virtual base list and already constructed. 4759 if (Base.isVirtual()) 4760 continue; 4761 4762 if (CXXCtorInitializer *Value 4763 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4764 Info.AllToInit.push_back(Value); 4765 } else if (!AnyErrors) { 4766 CXXCtorInitializer *CXXBaseInit; 4767 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4768 &Base, /*IsInheritedVirtualBase=*/false, 4769 CXXBaseInit)) { 4770 HadError = true; 4771 continue; 4772 } 4773 4774 Info.AllToInit.push_back(CXXBaseInit); 4775 } 4776 } 4777 4778 // Fields. 4779 for (auto *Mem : ClassDecl->decls()) { 4780 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4781 // C++ [class.bit]p2: 4782 // A declaration for a bit-field that omits the identifier declares an 4783 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4784 // initialized. 4785 if (F->isUnnamedBitfield()) 4786 continue; 4787 4788 // If we're not generating the implicit copy/move constructor, then we'll 4789 // handle anonymous struct/union fields based on their individual 4790 // indirect fields. 4791 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4792 continue; 4793 4794 if (CollectFieldInitializer(*this, Info, F)) 4795 HadError = true; 4796 continue; 4797 } 4798 4799 // Beyond this point, we only consider default initialization. 4800 if (Info.isImplicitCopyOrMove()) 4801 continue; 4802 4803 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4804 if (F->getType()->isIncompleteArrayType()) { 4805 assert(ClassDecl->hasFlexibleArrayMember() && 4806 "Incomplete array type is not valid"); 4807 continue; 4808 } 4809 4810 // Initialize each field of an anonymous struct individually. 4811 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4812 HadError = true; 4813 4814 continue; 4815 } 4816 } 4817 4818 unsigned NumInitializers = Info.AllToInit.size(); 4819 if (NumInitializers > 0) { 4820 Constructor->setNumCtorInitializers(NumInitializers); 4821 CXXCtorInitializer **baseOrMemberInitializers = 4822 new (Context) CXXCtorInitializer*[NumInitializers]; 4823 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4824 NumInitializers * sizeof(CXXCtorInitializer*)); 4825 Constructor->setCtorInitializers(baseOrMemberInitializers); 4826 4827 // Constructors implicitly reference the base and member 4828 // destructors. 4829 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4830 Constructor->getParent()); 4831 } 4832 4833 return HadError; 4834 } 4835 4836 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4837 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4838 const RecordDecl *RD = RT->getDecl(); 4839 if (RD->isAnonymousStructOrUnion()) { 4840 for (auto *Field : RD->fields()) 4841 PopulateKeysForFields(Field, IdealInits); 4842 return; 4843 } 4844 } 4845 IdealInits.push_back(Field->getCanonicalDecl()); 4846 } 4847 4848 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4849 return Context.getCanonicalType(BaseType).getTypePtr(); 4850 } 4851 4852 static const void *GetKeyForMember(ASTContext &Context, 4853 CXXCtorInitializer *Member) { 4854 if (!Member->isAnyMemberInitializer()) 4855 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4856 4857 return Member->getAnyMember()->getCanonicalDecl(); 4858 } 4859 4860 static void DiagnoseBaseOrMemInitializerOrder( 4861 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4862 ArrayRef<CXXCtorInitializer *> Inits) { 4863 if (Constructor->getDeclContext()->isDependentContext()) 4864 return; 4865 4866 // Don't check initializers order unless the warning is enabled at the 4867 // location of at least one initializer. 4868 bool ShouldCheckOrder = false; 4869 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4870 CXXCtorInitializer *Init = Inits[InitIndex]; 4871 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4872 Init->getSourceLocation())) { 4873 ShouldCheckOrder = true; 4874 break; 4875 } 4876 } 4877 if (!ShouldCheckOrder) 4878 return; 4879 4880 // Build the list of bases and members in the order that they'll 4881 // actually be initialized. The explicit initializers should be in 4882 // this same order but may be missing things. 4883 SmallVector<const void*, 32> IdealInitKeys; 4884 4885 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4886 4887 // 1. Virtual bases. 4888 for (const auto &VBase : ClassDecl->vbases()) 4889 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4890 4891 // 2. Non-virtual bases. 4892 for (const auto &Base : ClassDecl->bases()) { 4893 if (Base.isVirtual()) 4894 continue; 4895 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4896 } 4897 4898 // 3. Direct fields. 4899 for (auto *Field : ClassDecl->fields()) { 4900 if (Field->isUnnamedBitfield()) 4901 continue; 4902 4903 PopulateKeysForFields(Field, IdealInitKeys); 4904 } 4905 4906 unsigned NumIdealInits = IdealInitKeys.size(); 4907 unsigned IdealIndex = 0; 4908 4909 CXXCtorInitializer *PrevInit = nullptr; 4910 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4911 CXXCtorInitializer *Init = Inits[InitIndex]; 4912 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4913 4914 // Scan forward to try to find this initializer in the idealized 4915 // initializers list. 4916 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4917 if (InitKey == IdealInitKeys[IdealIndex]) 4918 break; 4919 4920 // If we didn't find this initializer, it must be because we 4921 // scanned past it on a previous iteration. That can only 4922 // happen if we're out of order; emit a warning. 4923 if (IdealIndex == NumIdealInits && PrevInit) { 4924 Sema::SemaDiagnosticBuilder D = 4925 SemaRef.Diag(PrevInit->getSourceLocation(), 4926 diag::warn_initializer_out_of_order); 4927 4928 if (PrevInit->isAnyMemberInitializer()) 4929 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4930 else 4931 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4932 4933 if (Init->isAnyMemberInitializer()) 4934 D << 0 << Init->getAnyMember()->getDeclName(); 4935 else 4936 D << 1 << Init->getTypeSourceInfo()->getType(); 4937 4938 // Move back to the initializer's location in the ideal list. 4939 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4940 if (InitKey == IdealInitKeys[IdealIndex]) 4941 break; 4942 4943 assert(IdealIndex < NumIdealInits && 4944 "initializer not found in initializer list"); 4945 } 4946 4947 PrevInit = Init; 4948 } 4949 } 4950 4951 namespace { 4952 bool CheckRedundantInit(Sema &S, 4953 CXXCtorInitializer *Init, 4954 CXXCtorInitializer *&PrevInit) { 4955 if (!PrevInit) { 4956 PrevInit = Init; 4957 return false; 4958 } 4959 4960 if (FieldDecl *Field = Init->getAnyMember()) 4961 S.Diag(Init->getSourceLocation(), 4962 diag::err_multiple_mem_initialization) 4963 << Field->getDeclName() 4964 << Init->getSourceRange(); 4965 else { 4966 const Type *BaseClass = Init->getBaseClass(); 4967 assert(BaseClass && "neither field nor base"); 4968 S.Diag(Init->getSourceLocation(), 4969 diag::err_multiple_base_initialization) 4970 << QualType(BaseClass, 0) 4971 << Init->getSourceRange(); 4972 } 4973 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4974 << 0 << PrevInit->getSourceRange(); 4975 4976 return true; 4977 } 4978 4979 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4980 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4981 4982 bool CheckRedundantUnionInit(Sema &S, 4983 CXXCtorInitializer *Init, 4984 RedundantUnionMap &Unions) { 4985 FieldDecl *Field = Init->getAnyMember(); 4986 RecordDecl *Parent = Field->getParent(); 4987 NamedDecl *Child = Field; 4988 4989 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4990 if (Parent->isUnion()) { 4991 UnionEntry &En = Unions[Parent]; 4992 if (En.first && En.first != Child) { 4993 S.Diag(Init->getSourceLocation(), 4994 diag::err_multiple_mem_union_initialization) 4995 << Field->getDeclName() 4996 << Init->getSourceRange(); 4997 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4998 << 0 << En.second->getSourceRange(); 4999 return true; 5000 } 5001 if (!En.first) { 5002 En.first = Child; 5003 En.second = Init; 5004 } 5005 if (!Parent->isAnonymousStructOrUnion()) 5006 return false; 5007 } 5008 5009 Child = Parent; 5010 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5011 } 5012 5013 return false; 5014 } 5015 } 5016 5017 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5018 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5019 SourceLocation ColonLoc, 5020 ArrayRef<CXXCtorInitializer*> MemInits, 5021 bool AnyErrors) { 5022 if (!ConstructorDecl) 5023 return; 5024 5025 AdjustDeclIfTemplate(ConstructorDecl); 5026 5027 CXXConstructorDecl *Constructor 5028 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5029 5030 if (!Constructor) { 5031 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5032 return; 5033 } 5034 5035 // Mapping for the duplicate initializers check. 5036 // For member initializers, this is keyed with a FieldDecl*. 5037 // For base initializers, this is keyed with a Type*. 5038 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5039 5040 // Mapping for the inconsistent anonymous-union initializers check. 5041 RedundantUnionMap MemberUnions; 5042 5043 bool HadError = false; 5044 for (unsigned i = 0; i < MemInits.size(); i++) { 5045 CXXCtorInitializer *Init = MemInits[i]; 5046 5047 // Set the source order index. 5048 Init->setSourceOrder(i); 5049 5050 if (Init->isAnyMemberInitializer()) { 5051 const void *Key = GetKeyForMember(Context, Init); 5052 if (CheckRedundantInit(*this, Init, Members[Key]) || 5053 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5054 HadError = true; 5055 } else if (Init->isBaseInitializer()) { 5056 const void *Key = GetKeyForMember(Context, Init); 5057 if (CheckRedundantInit(*this, Init, Members[Key])) 5058 HadError = true; 5059 } else { 5060 assert(Init->isDelegatingInitializer()); 5061 // This must be the only initializer 5062 if (MemInits.size() != 1) { 5063 Diag(Init->getSourceLocation(), 5064 diag::err_delegating_initializer_alone) 5065 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5066 // We will treat this as being the only initializer. 5067 } 5068 SetDelegatingInitializer(Constructor, MemInits[i]); 5069 // Return immediately as the initializer is set. 5070 return; 5071 } 5072 } 5073 5074 if (HadError) 5075 return; 5076 5077 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5078 5079 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5080 5081 DiagnoseUninitializedFields(*this, Constructor); 5082 } 5083 5084 void 5085 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5086 CXXRecordDecl *ClassDecl) { 5087 // Ignore dependent contexts. Also ignore unions, since their members never 5088 // have destructors implicitly called. 5089 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5090 return; 5091 5092 // FIXME: all the access-control diagnostics are positioned on the 5093 // field/base declaration. That's probably good; that said, the 5094 // user might reasonably want to know why the destructor is being 5095 // emitted, and we currently don't say. 5096 5097 // Non-static data members. 5098 for (auto *Field : ClassDecl->fields()) { 5099 if (Field->isInvalidDecl()) 5100 continue; 5101 5102 // Don't destroy incomplete or zero-length arrays. 5103 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5104 continue; 5105 5106 QualType FieldType = Context.getBaseElementType(Field->getType()); 5107 5108 const RecordType* RT = FieldType->getAs<RecordType>(); 5109 if (!RT) 5110 continue; 5111 5112 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5113 if (FieldClassDecl->isInvalidDecl()) 5114 continue; 5115 if (FieldClassDecl->hasIrrelevantDestructor()) 5116 continue; 5117 // The destructor for an implicit anonymous union member is never invoked. 5118 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5119 continue; 5120 5121 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5122 assert(Dtor && "No dtor found for FieldClassDecl!"); 5123 CheckDestructorAccess(Field->getLocation(), Dtor, 5124 PDiag(diag::err_access_dtor_field) 5125 << Field->getDeclName() 5126 << FieldType); 5127 5128 MarkFunctionReferenced(Location, Dtor); 5129 DiagnoseUseOfDecl(Dtor, Location); 5130 } 5131 5132 // We only potentially invoke the destructors of potentially constructed 5133 // subobjects. 5134 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5135 5136 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5137 5138 // Bases. 5139 for (const auto &Base : ClassDecl->bases()) { 5140 // Bases are always records in a well-formed non-dependent class. 5141 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5142 5143 // Remember direct virtual bases. 5144 if (Base.isVirtual()) { 5145 if (!VisitVirtualBases) 5146 continue; 5147 DirectVirtualBases.insert(RT); 5148 } 5149 5150 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5151 // If our base class is invalid, we probably can't get its dtor anyway. 5152 if (BaseClassDecl->isInvalidDecl()) 5153 continue; 5154 if (BaseClassDecl->hasIrrelevantDestructor()) 5155 continue; 5156 5157 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5158 assert(Dtor && "No dtor found for BaseClassDecl!"); 5159 5160 // FIXME: caret should be on the start of the class name 5161 CheckDestructorAccess(Base.getLocStart(), Dtor, 5162 PDiag(diag::err_access_dtor_base) 5163 << Base.getType() 5164 << Base.getSourceRange(), 5165 Context.getTypeDeclType(ClassDecl)); 5166 5167 MarkFunctionReferenced(Location, Dtor); 5168 DiagnoseUseOfDecl(Dtor, Location); 5169 } 5170 5171 if (!VisitVirtualBases) 5172 return; 5173 5174 // Virtual bases. 5175 for (const auto &VBase : ClassDecl->vbases()) { 5176 // Bases are always records in a well-formed non-dependent class. 5177 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5178 5179 // Ignore direct virtual bases. 5180 if (DirectVirtualBases.count(RT)) 5181 continue; 5182 5183 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5184 // If our base class is invalid, we probably can't get its dtor anyway. 5185 if (BaseClassDecl->isInvalidDecl()) 5186 continue; 5187 if (BaseClassDecl->hasIrrelevantDestructor()) 5188 continue; 5189 5190 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5191 assert(Dtor && "No dtor found for BaseClassDecl!"); 5192 if (CheckDestructorAccess( 5193 ClassDecl->getLocation(), Dtor, 5194 PDiag(diag::err_access_dtor_vbase) 5195 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5196 Context.getTypeDeclType(ClassDecl)) == 5197 AR_accessible) { 5198 CheckDerivedToBaseConversion( 5199 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5200 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5201 SourceRange(), DeclarationName(), nullptr); 5202 } 5203 5204 MarkFunctionReferenced(Location, Dtor); 5205 DiagnoseUseOfDecl(Dtor, Location); 5206 } 5207 } 5208 5209 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5210 if (!CDtorDecl) 5211 return; 5212 5213 if (CXXConstructorDecl *Constructor 5214 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5215 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5216 DiagnoseUninitializedFields(*this, Constructor); 5217 } 5218 } 5219 5220 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5221 if (!getLangOpts().CPlusPlus) 5222 return false; 5223 5224 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5225 if (!RD) 5226 return false; 5227 5228 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5229 // class template specialization here, but doing so breaks a lot of code. 5230 5231 // We can't answer whether something is abstract until it has a 5232 // definition. If it's currently being defined, we'll walk back 5233 // over all the declarations when we have a full definition. 5234 const CXXRecordDecl *Def = RD->getDefinition(); 5235 if (!Def || Def->isBeingDefined()) 5236 return false; 5237 5238 return RD->isAbstract(); 5239 } 5240 5241 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5242 TypeDiagnoser &Diagnoser) { 5243 if (!isAbstractType(Loc, T)) 5244 return false; 5245 5246 T = Context.getBaseElementType(T); 5247 Diagnoser.diagnose(*this, Loc, T); 5248 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5249 return true; 5250 } 5251 5252 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5253 // Check if we've already emitted the list of pure virtual functions 5254 // for this class. 5255 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5256 return; 5257 5258 // If the diagnostic is suppressed, don't emit the notes. We're only 5259 // going to emit them once, so try to attach them to a diagnostic we're 5260 // actually going to show. 5261 if (Diags.isLastDiagnosticIgnored()) 5262 return; 5263 5264 CXXFinalOverriderMap FinalOverriders; 5265 RD->getFinalOverriders(FinalOverriders); 5266 5267 // Keep a set of seen pure methods so we won't diagnose the same method 5268 // more than once. 5269 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5270 5271 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5272 MEnd = FinalOverriders.end(); 5273 M != MEnd; 5274 ++M) { 5275 for (OverridingMethods::iterator SO = M->second.begin(), 5276 SOEnd = M->second.end(); 5277 SO != SOEnd; ++SO) { 5278 // C++ [class.abstract]p4: 5279 // A class is abstract if it contains or inherits at least one 5280 // pure virtual function for which the final overrider is pure 5281 // virtual. 5282 5283 // 5284 if (SO->second.size() != 1) 5285 continue; 5286 5287 if (!SO->second.front().Method->isPure()) 5288 continue; 5289 5290 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5291 continue; 5292 5293 Diag(SO->second.front().Method->getLocation(), 5294 diag::note_pure_virtual_function) 5295 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5296 } 5297 } 5298 5299 if (!PureVirtualClassDiagSet) 5300 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5301 PureVirtualClassDiagSet->insert(RD); 5302 } 5303 5304 namespace { 5305 struct AbstractUsageInfo { 5306 Sema &S; 5307 CXXRecordDecl *Record; 5308 CanQualType AbstractType; 5309 bool Invalid; 5310 5311 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5312 : S(S), Record(Record), 5313 AbstractType(S.Context.getCanonicalType( 5314 S.Context.getTypeDeclType(Record))), 5315 Invalid(false) {} 5316 5317 void DiagnoseAbstractType() { 5318 if (Invalid) return; 5319 S.DiagnoseAbstractType(Record); 5320 Invalid = true; 5321 } 5322 5323 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5324 }; 5325 5326 struct CheckAbstractUsage { 5327 AbstractUsageInfo &Info; 5328 const NamedDecl *Ctx; 5329 5330 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5331 : Info(Info), Ctx(Ctx) {} 5332 5333 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5334 switch (TL.getTypeLocClass()) { 5335 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5336 #define TYPELOC(CLASS, PARENT) \ 5337 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5338 #include "clang/AST/TypeLocNodes.def" 5339 } 5340 } 5341 5342 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5343 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5344 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5345 if (!TL.getParam(I)) 5346 continue; 5347 5348 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5349 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5350 } 5351 } 5352 5353 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5354 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5355 } 5356 5357 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5358 // Visit the type parameters from a permissive context. 5359 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5360 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5361 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5362 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5363 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5364 // TODO: other template argument types? 5365 } 5366 } 5367 5368 // Visit pointee types from a permissive context. 5369 #define CheckPolymorphic(Type) \ 5370 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5371 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5372 } 5373 CheckPolymorphic(PointerTypeLoc) 5374 CheckPolymorphic(ReferenceTypeLoc) 5375 CheckPolymorphic(MemberPointerTypeLoc) 5376 CheckPolymorphic(BlockPointerTypeLoc) 5377 CheckPolymorphic(AtomicTypeLoc) 5378 5379 /// Handle all the types we haven't given a more specific 5380 /// implementation for above. 5381 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5382 // Every other kind of type that we haven't called out already 5383 // that has an inner type is either (1) sugar or (2) contains that 5384 // inner type in some way as a subobject. 5385 if (TypeLoc Next = TL.getNextTypeLoc()) 5386 return Visit(Next, Sel); 5387 5388 // If there's no inner type and we're in a permissive context, 5389 // don't diagnose. 5390 if (Sel == Sema::AbstractNone) return; 5391 5392 // Check whether the type matches the abstract type. 5393 QualType T = TL.getType(); 5394 if (T->isArrayType()) { 5395 Sel = Sema::AbstractArrayType; 5396 T = Info.S.Context.getBaseElementType(T); 5397 } 5398 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5399 if (CT != Info.AbstractType) return; 5400 5401 // It matched; do some magic. 5402 if (Sel == Sema::AbstractArrayType) { 5403 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5404 << T << TL.getSourceRange(); 5405 } else { 5406 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5407 << Sel << T << TL.getSourceRange(); 5408 } 5409 Info.DiagnoseAbstractType(); 5410 } 5411 }; 5412 5413 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5414 Sema::AbstractDiagSelID Sel) { 5415 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5416 } 5417 5418 } 5419 5420 /// Check for invalid uses of an abstract type in a method declaration. 5421 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5422 CXXMethodDecl *MD) { 5423 // No need to do the check on definitions, which require that 5424 // the return/param types be complete. 5425 if (MD->doesThisDeclarationHaveABody()) 5426 return; 5427 5428 // For safety's sake, just ignore it if we don't have type source 5429 // information. This should never happen for non-implicit methods, 5430 // but... 5431 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5432 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5433 } 5434 5435 /// Check for invalid uses of an abstract type within a class definition. 5436 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5437 CXXRecordDecl *RD) { 5438 for (auto *D : RD->decls()) { 5439 if (D->isImplicit()) continue; 5440 5441 // Methods and method templates. 5442 if (isa<CXXMethodDecl>(D)) { 5443 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5444 } else if (isa<FunctionTemplateDecl>(D)) { 5445 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5446 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5447 5448 // Fields and static variables. 5449 } else if (isa<FieldDecl>(D)) { 5450 FieldDecl *FD = cast<FieldDecl>(D); 5451 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5452 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5453 } else if (isa<VarDecl>(D)) { 5454 VarDecl *VD = cast<VarDecl>(D); 5455 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5456 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5457 5458 // Nested classes and class templates. 5459 } else if (isa<CXXRecordDecl>(D)) { 5460 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5461 } else if (isa<ClassTemplateDecl>(D)) { 5462 CheckAbstractClassUsage(Info, 5463 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5464 } 5465 } 5466 } 5467 5468 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) { 5469 Attr *ClassAttr = getDLLAttr(Class); 5470 if (!ClassAttr) 5471 return; 5472 5473 assert(ClassAttr->getKind() == attr::DLLExport); 5474 5475 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5476 5477 if (TSK == TSK_ExplicitInstantiationDeclaration) 5478 // Don't go any further if this is just an explicit instantiation 5479 // declaration. 5480 return; 5481 5482 for (Decl *Member : Class->decls()) { 5483 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5484 if (!MD) 5485 continue; 5486 5487 if (Member->getAttr<DLLExportAttr>()) { 5488 if (MD->isUserProvided()) { 5489 // Instantiate non-default class member functions ... 5490 5491 // .. except for certain kinds of template specializations. 5492 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5493 continue; 5494 5495 S.MarkFunctionReferenced(Class->getLocation(), MD); 5496 5497 // The function will be passed to the consumer when its definition is 5498 // encountered. 5499 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5500 MD->isCopyAssignmentOperator() || 5501 MD->isMoveAssignmentOperator()) { 5502 // Synthesize and instantiate non-trivial implicit methods, explicitly 5503 // defaulted methods, and the copy and move assignment operators. The 5504 // latter are exported even if they are trivial, because the address of 5505 // an operator can be taken and should compare equal across libraries. 5506 DiagnosticErrorTrap Trap(S.Diags); 5507 S.MarkFunctionReferenced(Class->getLocation(), MD); 5508 if (Trap.hasErrorOccurred()) { 5509 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5510 << Class->getName() << !S.getLangOpts().CPlusPlus11; 5511 break; 5512 } 5513 5514 // There is no later point when we will see the definition of this 5515 // function, so pass it to the consumer now. 5516 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5517 } 5518 } 5519 } 5520 } 5521 5522 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5523 CXXRecordDecl *Class) { 5524 // Only the MS ABI has default constructor closures, so we don't need to do 5525 // this semantic checking anywhere else. 5526 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5527 return; 5528 5529 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5530 for (Decl *Member : Class->decls()) { 5531 // Look for exported default constructors. 5532 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5533 if (!CD || !CD->isDefaultConstructor()) 5534 continue; 5535 auto *Attr = CD->getAttr<DLLExportAttr>(); 5536 if (!Attr) 5537 continue; 5538 5539 // If the class is non-dependent, mark the default arguments as ODR-used so 5540 // that we can properly codegen the constructor closure. 5541 if (!Class->isDependentContext()) { 5542 for (ParmVarDecl *PD : CD->parameters()) { 5543 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5544 S.DiscardCleanupsInEvaluationContext(); 5545 } 5546 } 5547 5548 if (LastExportedDefaultCtor) { 5549 S.Diag(LastExportedDefaultCtor->getLocation(), 5550 diag::err_attribute_dll_ambiguous_default_ctor) 5551 << Class; 5552 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5553 << CD->getDeclName(); 5554 return; 5555 } 5556 LastExportedDefaultCtor = CD; 5557 } 5558 } 5559 5560 /// \brief Check class-level dllimport/dllexport attribute. 5561 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5562 Attr *ClassAttr = getDLLAttr(Class); 5563 5564 // MSVC inherits DLL attributes to partial class template specializations. 5565 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5566 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5567 if (Attr *TemplateAttr = 5568 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5569 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5570 A->setInherited(true); 5571 ClassAttr = A; 5572 } 5573 } 5574 } 5575 5576 if (!ClassAttr) 5577 return; 5578 5579 if (!Class->isExternallyVisible()) { 5580 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5581 << Class << ClassAttr; 5582 return; 5583 } 5584 5585 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5586 !ClassAttr->isInherited()) { 5587 // Diagnose dll attributes on members of class with dll attribute. 5588 for (Decl *Member : Class->decls()) { 5589 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5590 continue; 5591 InheritableAttr *MemberAttr = getDLLAttr(Member); 5592 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5593 continue; 5594 5595 Diag(MemberAttr->getLocation(), 5596 diag::err_attribute_dll_member_of_dll_class) 5597 << MemberAttr << ClassAttr; 5598 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5599 Member->setInvalidDecl(); 5600 } 5601 } 5602 5603 if (Class->getDescribedClassTemplate()) 5604 // Don't inherit dll attribute until the template is instantiated. 5605 return; 5606 5607 // The class is either imported or exported. 5608 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5609 5610 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5611 5612 // Ignore explicit dllexport on explicit class template instantiation declarations. 5613 if (ClassExported && !ClassAttr->isInherited() && 5614 TSK == TSK_ExplicitInstantiationDeclaration) { 5615 Class->dropAttr<DLLExportAttr>(); 5616 return; 5617 } 5618 5619 // Force declaration of implicit members so they can inherit the attribute. 5620 ForceDeclarationOfImplicitMembers(Class); 5621 5622 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5623 // seem to be true in practice? 5624 5625 for (Decl *Member : Class->decls()) { 5626 VarDecl *VD = dyn_cast<VarDecl>(Member); 5627 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5628 5629 // Only methods and static fields inherit the attributes. 5630 if (!VD && !MD) 5631 continue; 5632 5633 if (MD) { 5634 // Don't process deleted methods. 5635 if (MD->isDeleted()) 5636 continue; 5637 5638 if (MD->isInlined()) { 5639 // MinGW does not import or export inline methods. 5640 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5641 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) 5642 continue; 5643 5644 // MSVC versions before 2015 don't export the move assignment operators 5645 // and move constructor, so don't attempt to import/export them if 5646 // we have a definition. 5647 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5648 if ((MD->isMoveAssignmentOperator() || 5649 (Ctor && Ctor->isMoveConstructor())) && 5650 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5651 continue; 5652 5653 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5654 // operator is exported anyway. 5655 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5656 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5657 continue; 5658 } 5659 } 5660 5661 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5662 continue; 5663 5664 if (!getDLLAttr(Member)) { 5665 auto *NewAttr = 5666 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5667 NewAttr->setInherited(true); 5668 Member->addAttr(NewAttr); 5669 } 5670 } 5671 5672 if (ClassExported) 5673 DelayedDllExportClasses.push_back(Class); 5674 } 5675 5676 /// \brief Perform propagation of DLL attributes from a derived class to a 5677 /// templated base class for MS compatibility. 5678 void Sema::propagateDLLAttrToBaseClassTemplate( 5679 CXXRecordDecl *Class, Attr *ClassAttr, 5680 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5681 if (getDLLAttr( 5682 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5683 // If the base class template has a DLL attribute, don't try to change it. 5684 return; 5685 } 5686 5687 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5688 if (!getDLLAttr(BaseTemplateSpec) && 5689 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5690 TSK == TSK_ImplicitInstantiation)) { 5691 // The template hasn't been instantiated yet (or it has, but only as an 5692 // explicit instantiation declaration or implicit instantiation, which means 5693 // we haven't codegenned any members yet), so propagate the attribute. 5694 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5695 NewAttr->setInherited(true); 5696 BaseTemplateSpec->addAttr(NewAttr); 5697 5698 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5699 // needs to be run again to work see the new attribute. Otherwise this will 5700 // get run whenever the template is instantiated. 5701 if (TSK != TSK_Undeclared) 5702 checkClassLevelDLLAttribute(BaseTemplateSpec); 5703 5704 return; 5705 } 5706 5707 if (getDLLAttr(BaseTemplateSpec)) { 5708 // The template has already been specialized or instantiated with an 5709 // attribute, explicitly or through propagation. We should not try to change 5710 // it. 5711 return; 5712 } 5713 5714 // The template was previously instantiated or explicitly specialized without 5715 // a dll attribute, It's too late for us to add an attribute, so warn that 5716 // this is unsupported. 5717 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5718 << BaseTemplateSpec->isExplicitSpecialization(); 5719 Diag(ClassAttr->getLocation(), diag::note_attribute); 5720 if (BaseTemplateSpec->isExplicitSpecialization()) { 5721 Diag(BaseTemplateSpec->getLocation(), 5722 diag::note_template_class_explicit_specialization_was_here) 5723 << BaseTemplateSpec; 5724 } else { 5725 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5726 diag::note_template_class_instantiation_was_here) 5727 << BaseTemplateSpec; 5728 } 5729 } 5730 5731 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5732 SourceLocation DefaultLoc) { 5733 switch (S.getSpecialMember(MD)) { 5734 case Sema::CXXDefaultConstructor: 5735 S.DefineImplicitDefaultConstructor(DefaultLoc, 5736 cast<CXXConstructorDecl>(MD)); 5737 break; 5738 case Sema::CXXCopyConstructor: 5739 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5740 break; 5741 case Sema::CXXCopyAssignment: 5742 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5743 break; 5744 case Sema::CXXDestructor: 5745 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5746 break; 5747 case Sema::CXXMoveConstructor: 5748 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5749 break; 5750 case Sema::CXXMoveAssignment: 5751 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5752 break; 5753 case Sema::CXXInvalid: 5754 llvm_unreachable("Invalid special member."); 5755 } 5756 } 5757 5758 /// Determine whether a type is permitted to be passed or returned in 5759 /// registers, per C++ [class.temporary]p3. 5760 static bool computeCanPassInRegisters(Sema &S, CXXRecordDecl *D) { 5761 if (D->isDependentType() || D->isInvalidDecl()) 5762 return false; 5763 5764 // Per C++ [class.temporary]p3, the relevant condition is: 5765 // each copy constructor, move constructor, and destructor of X is 5766 // either trivial or deleted, and X has at least one non-deleted copy 5767 // or move constructor 5768 bool HasNonDeletedCopyOrMove = false; 5769 5770 if (D->needsImplicitCopyConstructor() && 5771 !D->defaultedCopyConstructorIsDeleted()) { 5772 if (!D->hasTrivialCopyConstructor()) 5773 return false; 5774 HasNonDeletedCopyOrMove = true; 5775 } 5776 5777 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 5778 !D->defaultedMoveConstructorIsDeleted()) { 5779 if (!D->hasTrivialMoveConstructor()) 5780 return false; 5781 HasNonDeletedCopyOrMove = true; 5782 } 5783 5784 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 5785 !D->hasTrivialDestructor()) 5786 return false; 5787 5788 for (const CXXMethodDecl *MD : D->methods()) { 5789 if (MD->isDeleted()) 5790 continue; 5791 5792 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 5793 if (CD && CD->isCopyOrMoveConstructor()) 5794 HasNonDeletedCopyOrMove = true; 5795 else if (!isa<CXXDestructorDecl>(MD)) 5796 continue; 5797 5798 if (!MD->isTrivial()) 5799 return false; 5800 } 5801 5802 return HasNonDeletedCopyOrMove; 5803 } 5804 5805 /// \brief Perform semantic checks on a class definition that has been 5806 /// completing, introducing implicitly-declared members, checking for 5807 /// abstract types, etc. 5808 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 5809 if (!Record) 5810 return; 5811 5812 if (Record->isAbstract() && !Record->isInvalidDecl()) { 5813 AbstractUsageInfo Info(*this, Record); 5814 CheckAbstractClassUsage(Info, Record); 5815 } 5816 5817 // If this is not an aggregate type and has no user-declared constructor, 5818 // complain about any non-static data members of reference or const scalar 5819 // type, since they will never get initializers. 5820 if (!Record->isInvalidDecl() && !Record->isDependentType() && 5821 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 5822 !Record->isLambda()) { 5823 bool Complained = false; 5824 for (const auto *F : Record->fields()) { 5825 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 5826 continue; 5827 5828 if (F->getType()->isReferenceType() || 5829 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 5830 if (!Complained) { 5831 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 5832 << Record->getTagKind() << Record; 5833 Complained = true; 5834 } 5835 5836 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 5837 << F->getType()->isReferenceType() 5838 << F->getDeclName(); 5839 } 5840 } 5841 } 5842 5843 if (Record->getIdentifier()) { 5844 // C++ [class.mem]p13: 5845 // If T is the name of a class, then each of the following shall have a 5846 // name different from T: 5847 // - every member of every anonymous union that is a member of class T. 5848 // 5849 // C++ [class.mem]p14: 5850 // In addition, if class T has a user-declared constructor (12.1), every 5851 // non-static data member of class T shall have a name different from T. 5852 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 5853 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 5854 ++I) { 5855 NamedDecl *D = *I; 5856 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 5857 isa<IndirectFieldDecl>(D)) { 5858 Diag(D->getLocation(), diag::err_member_name_of_class) 5859 << D->getDeclName(); 5860 break; 5861 } 5862 } 5863 } 5864 5865 // Warn if the class has virtual methods but non-virtual public destructor. 5866 if (Record->isPolymorphic() && !Record->isDependentType()) { 5867 CXXDestructorDecl *dtor = Record->getDestructor(); 5868 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 5869 !Record->hasAttr<FinalAttr>()) 5870 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 5871 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 5872 } 5873 5874 if (Record->isAbstract()) { 5875 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 5876 Diag(Record->getLocation(), diag::warn_abstract_final_class) 5877 << FA->isSpelledAsSealed(); 5878 DiagnoseAbstractType(Record); 5879 } 5880 } 5881 5882 bool HasMethodWithOverrideControl = false, 5883 HasOverridingMethodWithoutOverrideControl = false; 5884 if (!Record->isDependentType()) { 5885 for (auto *M : Record->methods()) { 5886 // See if a method overloads virtual methods in a base 5887 // class without overriding any. 5888 if (!M->isStatic()) 5889 DiagnoseHiddenVirtualMethods(M); 5890 if (M->hasAttr<OverrideAttr>()) 5891 HasMethodWithOverrideControl = true; 5892 else if (M->size_overridden_methods() > 0) 5893 HasOverridingMethodWithoutOverrideControl = true; 5894 // Check whether the explicitly-defaulted special members are valid. 5895 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 5896 CheckExplicitlyDefaultedSpecialMember(M); 5897 5898 // For an explicitly defaulted or deleted special member, we defer 5899 // determining triviality until the class is complete. That time is now! 5900 CXXSpecialMember CSM = getSpecialMember(M); 5901 if (!M->isImplicit() && !M->isUserProvided()) { 5902 if (CSM != CXXInvalid) { 5903 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 5904 5905 // Inform the class that we've finished declaring this member. 5906 Record->finishedDefaultedOrDeletedMember(M); 5907 } 5908 } 5909 5910 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 5911 M->hasAttr<DLLExportAttr>()) { 5912 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5913 M->isTrivial() && 5914 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 5915 CSM == CXXDestructor)) 5916 M->dropAttr<DLLExportAttr>(); 5917 5918 if (M->hasAttr<DLLExportAttr>()) { 5919 DefineImplicitSpecialMember(*this, M, M->getLocation()); 5920 ActOnFinishInlineFunctionDef(M); 5921 } 5922 } 5923 } 5924 } 5925 5926 if (HasMethodWithOverrideControl && 5927 HasOverridingMethodWithoutOverrideControl) { 5928 // At least one method has the 'override' control declared. 5929 // Diagnose all other overridden methods which do not have 'override' specified on them. 5930 for (auto *M : Record->methods()) 5931 DiagnoseAbsenceOfOverrideControl(M); 5932 } 5933 5934 // ms_struct is a request to use the same ABI rules as MSVC. Check 5935 // whether this class uses any C++ features that are implemented 5936 // completely differently in MSVC, and if so, emit a diagnostic. 5937 // That diagnostic defaults to an error, but we allow projects to 5938 // map it down to a warning (or ignore it). It's a fairly common 5939 // practice among users of the ms_struct pragma to mass-annotate 5940 // headers, sweeping up a bunch of types that the project doesn't 5941 // really rely on MSVC-compatible layout for. We must therefore 5942 // support "ms_struct except for C++ stuff" as a secondary ABI. 5943 if (Record->isMsStruct(Context) && 5944 (Record->isPolymorphic() || Record->getNumBases())) { 5945 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 5946 } 5947 5948 checkClassLevelDLLAttribute(Record); 5949 5950 Record->setCanPassInRegisters(computeCanPassInRegisters(*this, Record)); 5951 } 5952 5953 /// Look up the special member function that would be called by a special 5954 /// member function for a subobject of class type. 5955 /// 5956 /// \param Class The class type of the subobject. 5957 /// \param CSM The kind of special member function. 5958 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 5959 /// \param ConstRHS True if this is a copy operation with a const object 5960 /// on its RHS, that is, if the argument to the outer special member 5961 /// function is 'const' and this is not a field marked 'mutable'. 5962 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 5963 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 5964 unsigned FieldQuals, bool ConstRHS) { 5965 unsigned LHSQuals = 0; 5966 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 5967 LHSQuals = FieldQuals; 5968 5969 unsigned RHSQuals = FieldQuals; 5970 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 5971 RHSQuals = 0; 5972 else if (ConstRHS) 5973 RHSQuals |= Qualifiers::Const; 5974 5975 return S.LookupSpecialMember(Class, CSM, 5976 RHSQuals & Qualifiers::Const, 5977 RHSQuals & Qualifiers::Volatile, 5978 false, 5979 LHSQuals & Qualifiers::Const, 5980 LHSQuals & Qualifiers::Volatile); 5981 } 5982 5983 class Sema::InheritedConstructorInfo { 5984 Sema &S; 5985 SourceLocation UseLoc; 5986 5987 /// A mapping from the base classes through which the constructor was 5988 /// inherited to the using shadow declaration in that base class (or a null 5989 /// pointer if the constructor was declared in that base class). 5990 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 5991 InheritedFromBases; 5992 5993 public: 5994 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 5995 ConstructorUsingShadowDecl *Shadow) 5996 : S(S), UseLoc(UseLoc) { 5997 bool DiagnosedMultipleConstructedBases = false; 5998 CXXRecordDecl *ConstructedBase = nullptr; 5999 UsingDecl *ConstructedBaseUsing = nullptr; 6000 6001 // Find the set of such base class subobjects and check that there's a 6002 // unique constructed subobject. 6003 for (auto *D : Shadow->redecls()) { 6004 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6005 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6006 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6007 6008 InheritedFromBases.insert( 6009 std::make_pair(DNominatedBase->getCanonicalDecl(), 6010 DShadow->getNominatedBaseClassShadowDecl())); 6011 if (DShadow->constructsVirtualBase()) 6012 InheritedFromBases.insert( 6013 std::make_pair(DConstructedBase->getCanonicalDecl(), 6014 DShadow->getConstructedBaseClassShadowDecl())); 6015 else 6016 assert(DNominatedBase == DConstructedBase); 6017 6018 // [class.inhctor.init]p2: 6019 // If the constructor was inherited from multiple base class subobjects 6020 // of type B, the program is ill-formed. 6021 if (!ConstructedBase) { 6022 ConstructedBase = DConstructedBase; 6023 ConstructedBaseUsing = D->getUsingDecl(); 6024 } else if (ConstructedBase != DConstructedBase && 6025 !Shadow->isInvalidDecl()) { 6026 if (!DiagnosedMultipleConstructedBases) { 6027 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6028 << Shadow->getTargetDecl(); 6029 S.Diag(ConstructedBaseUsing->getLocation(), 6030 diag::note_ambiguous_inherited_constructor_using) 6031 << ConstructedBase; 6032 DiagnosedMultipleConstructedBases = true; 6033 } 6034 S.Diag(D->getUsingDecl()->getLocation(), 6035 diag::note_ambiguous_inherited_constructor_using) 6036 << DConstructedBase; 6037 } 6038 } 6039 6040 if (DiagnosedMultipleConstructedBases) 6041 Shadow->setInvalidDecl(); 6042 } 6043 6044 /// Find the constructor to use for inherited construction of a base class, 6045 /// and whether that base class constructor inherits the constructor from a 6046 /// virtual base class (in which case it won't actually invoke it). 6047 std::pair<CXXConstructorDecl *, bool> 6048 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6049 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6050 if (It == InheritedFromBases.end()) 6051 return std::make_pair(nullptr, false); 6052 6053 // This is an intermediary class. 6054 if (It->second) 6055 return std::make_pair( 6056 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6057 It->second->constructsVirtualBase()); 6058 6059 // This is the base class from which the constructor was inherited. 6060 return std::make_pair(Ctor, false); 6061 } 6062 }; 6063 6064 /// Is the special member function which would be selected to perform the 6065 /// specified operation on the specified class type a constexpr constructor? 6066 static bool 6067 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6068 Sema::CXXSpecialMember CSM, unsigned Quals, 6069 bool ConstRHS, 6070 CXXConstructorDecl *InheritedCtor = nullptr, 6071 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6072 // If we're inheriting a constructor, see if we need to call it for this base 6073 // class. 6074 if (InheritedCtor) { 6075 assert(CSM == Sema::CXXDefaultConstructor); 6076 auto BaseCtor = 6077 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6078 if (BaseCtor) 6079 return BaseCtor->isConstexpr(); 6080 } 6081 6082 if (CSM == Sema::CXXDefaultConstructor) 6083 return ClassDecl->hasConstexprDefaultConstructor(); 6084 6085 Sema::SpecialMemberOverloadResult SMOR = 6086 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6087 if (!SMOR.getMethod()) 6088 // A constructor we wouldn't select can't be "involved in initializing" 6089 // anything. 6090 return true; 6091 return SMOR.getMethod()->isConstexpr(); 6092 } 6093 6094 /// Determine whether the specified special member function would be constexpr 6095 /// if it were implicitly defined. 6096 static bool defaultedSpecialMemberIsConstexpr( 6097 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6098 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6099 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6100 if (!S.getLangOpts().CPlusPlus11) 6101 return false; 6102 6103 // C++11 [dcl.constexpr]p4: 6104 // In the definition of a constexpr constructor [...] 6105 bool Ctor = true; 6106 switch (CSM) { 6107 case Sema::CXXDefaultConstructor: 6108 if (Inherited) 6109 break; 6110 // Since default constructor lookup is essentially trivial (and cannot 6111 // involve, for instance, template instantiation), we compute whether a 6112 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6113 // 6114 // This is important for performance; we need to know whether the default 6115 // constructor is constexpr to determine whether the type is a literal type. 6116 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6117 6118 case Sema::CXXCopyConstructor: 6119 case Sema::CXXMoveConstructor: 6120 // For copy or move constructors, we need to perform overload resolution. 6121 break; 6122 6123 case Sema::CXXCopyAssignment: 6124 case Sema::CXXMoveAssignment: 6125 if (!S.getLangOpts().CPlusPlus14) 6126 return false; 6127 // In C++1y, we need to perform overload resolution. 6128 Ctor = false; 6129 break; 6130 6131 case Sema::CXXDestructor: 6132 case Sema::CXXInvalid: 6133 return false; 6134 } 6135 6136 // -- if the class is a non-empty union, or for each non-empty anonymous 6137 // union member of a non-union class, exactly one non-static data member 6138 // shall be initialized; [DR1359] 6139 // 6140 // If we squint, this is guaranteed, since exactly one non-static data member 6141 // will be initialized (if the constructor isn't deleted), we just don't know 6142 // which one. 6143 if (Ctor && ClassDecl->isUnion()) 6144 return CSM == Sema::CXXDefaultConstructor 6145 ? ClassDecl->hasInClassInitializer() || 6146 !ClassDecl->hasVariantMembers() 6147 : true; 6148 6149 // -- the class shall not have any virtual base classes; 6150 if (Ctor && ClassDecl->getNumVBases()) 6151 return false; 6152 6153 // C++1y [class.copy]p26: 6154 // -- [the class] is a literal type, and 6155 if (!Ctor && !ClassDecl->isLiteral()) 6156 return false; 6157 6158 // -- every constructor involved in initializing [...] base class 6159 // sub-objects shall be a constexpr constructor; 6160 // -- the assignment operator selected to copy/move each direct base 6161 // class is a constexpr function, and 6162 for (const auto &B : ClassDecl->bases()) { 6163 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6164 if (!BaseType) continue; 6165 6166 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6167 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6168 InheritedCtor, Inherited)) 6169 return false; 6170 } 6171 6172 // -- every constructor involved in initializing non-static data members 6173 // [...] shall be a constexpr constructor; 6174 // -- every non-static data member and base class sub-object shall be 6175 // initialized 6176 // -- for each non-static data member of X that is of class type (or array 6177 // thereof), the assignment operator selected to copy/move that member is 6178 // a constexpr function 6179 for (const auto *F : ClassDecl->fields()) { 6180 if (F->isInvalidDecl()) 6181 continue; 6182 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6183 continue; 6184 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6185 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6186 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6187 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6188 BaseType.getCVRQualifiers(), 6189 ConstArg && !F->isMutable())) 6190 return false; 6191 } else if (CSM == Sema::CXXDefaultConstructor) { 6192 return false; 6193 } 6194 } 6195 6196 // All OK, it's constexpr! 6197 return true; 6198 } 6199 6200 static Sema::ImplicitExceptionSpecification 6201 ComputeDefaultedSpecialMemberExceptionSpec( 6202 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6203 Sema::InheritedConstructorInfo *ICI); 6204 6205 static Sema::ImplicitExceptionSpecification 6206 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6207 auto CSM = S.getSpecialMember(MD); 6208 if (CSM != Sema::CXXInvalid) 6209 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6210 6211 auto *CD = cast<CXXConstructorDecl>(MD); 6212 assert(CD->getInheritedConstructor() && 6213 "only special members have implicit exception specs"); 6214 Sema::InheritedConstructorInfo ICI( 6215 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6216 return ComputeDefaultedSpecialMemberExceptionSpec( 6217 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6218 } 6219 6220 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6221 CXXMethodDecl *MD) { 6222 FunctionProtoType::ExtProtoInfo EPI; 6223 6224 // Build an exception specification pointing back at this member. 6225 EPI.ExceptionSpec.Type = EST_Unevaluated; 6226 EPI.ExceptionSpec.SourceDecl = MD; 6227 6228 // Set the calling convention to the default for C++ instance methods. 6229 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6230 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6231 /*IsCXXMethod=*/true)); 6232 return EPI; 6233 } 6234 6235 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6236 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6237 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6238 return; 6239 6240 // Evaluate the exception specification. 6241 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6242 auto ESI = IES.getExceptionSpec(); 6243 6244 // Update the type of the special member to use it. 6245 UpdateExceptionSpec(MD, ESI); 6246 6247 // A user-provided destructor can be defined outside the class. When that 6248 // happens, be sure to update the exception specification on both 6249 // declarations. 6250 const FunctionProtoType *CanonicalFPT = 6251 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6252 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6253 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6254 } 6255 6256 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6257 CXXRecordDecl *RD = MD->getParent(); 6258 CXXSpecialMember CSM = getSpecialMember(MD); 6259 6260 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6261 "not an explicitly-defaulted special member"); 6262 6263 // Whether this was the first-declared instance of the constructor. 6264 // This affects whether we implicitly add an exception spec and constexpr. 6265 bool First = MD == MD->getCanonicalDecl(); 6266 6267 bool HadError = false; 6268 6269 // C++11 [dcl.fct.def.default]p1: 6270 // A function that is explicitly defaulted shall 6271 // -- be a special member function (checked elsewhere), 6272 // -- have the same type (except for ref-qualifiers, and except that a 6273 // copy operation can take a non-const reference) as an implicit 6274 // declaration, and 6275 // -- not have default arguments. 6276 unsigned ExpectedParams = 1; 6277 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6278 ExpectedParams = 0; 6279 if (MD->getNumParams() != ExpectedParams) { 6280 // This also checks for default arguments: a copy or move constructor with a 6281 // default argument is classified as a default constructor, and assignment 6282 // operations and destructors can't have default arguments. 6283 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6284 << CSM << MD->getSourceRange(); 6285 HadError = true; 6286 } else if (MD->isVariadic()) { 6287 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6288 << CSM << MD->getSourceRange(); 6289 HadError = true; 6290 } 6291 6292 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6293 6294 bool CanHaveConstParam = false; 6295 if (CSM == CXXCopyConstructor) 6296 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6297 else if (CSM == CXXCopyAssignment) 6298 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6299 6300 QualType ReturnType = Context.VoidTy; 6301 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6302 // Check for return type matching. 6303 ReturnType = Type->getReturnType(); 6304 QualType ExpectedReturnType = 6305 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 6306 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6307 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6308 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6309 HadError = true; 6310 } 6311 6312 // A defaulted special member cannot have cv-qualifiers. 6313 if (Type->getTypeQuals()) { 6314 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6315 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6316 HadError = true; 6317 } 6318 } 6319 6320 // Check for parameter type matching. 6321 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6322 bool HasConstParam = false; 6323 if (ExpectedParams && ArgType->isReferenceType()) { 6324 // Argument must be reference to possibly-const T. 6325 QualType ReferentType = ArgType->getPointeeType(); 6326 HasConstParam = ReferentType.isConstQualified(); 6327 6328 if (ReferentType.isVolatileQualified()) { 6329 Diag(MD->getLocation(), 6330 diag::err_defaulted_special_member_volatile_param) << CSM; 6331 HadError = true; 6332 } 6333 6334 if (HasConstParam && !CanHaveConstParam) { 6335 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6336 Diag(MD->getLocation(), 6337 diag::err_defaulted_special_member_copy_const_param) 6338 << (CSM == CXXCopyAssignment); 6339 // FIXME: Explain why this special member can't be const. 6340 } else { 6341 Diag(MD->getLocation(), 6342 diag::err_defaulted_special_member_move_const_param) 6343 << (CSM == CXXMoveAssignment); 6344 } 6345 HadError = true; 6346 } 6347 } else if (ExpectedParams) { 6348 // A copy assignment operator can take its argument by value, but a 6349 // defaulted one cannot. 6350 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6351 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6352 HadError = true; 6353 } 6354 6355 // C++11 [dcl.fct.def.default]p2: 6356 // An explicitly-defaulted function may be declared constexpr only if it 6357 // would have been implicitly declared as constexpr, 6358 // Do not apply this rule to members of class templates, since core issue 1358 6359 // makes such functions always instantiate to constexpr functions. For 6360 // functions which cannot be constexpr (for non-constructors in C++11 and for 6361 // destructors in C++1y), this is checked elsewhere. 6362 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6363 HasConstParam); 6364 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6365 : isa<CXXConstructorDecl>(MD)) && 6366 MD->isConstexpr() && !Constexpr && 6367 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6368 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 6369 // FIXME: Explain why the special member can't be constexpr. 6370 HadError = true; 6371 } 6372 6373 // and may have an explicit exception-specification only if it is compatible 6374 // with the exception-specification on the implicit declaration. 6375 if (Type->hasExceptionSpec()) { 6376 // Delay the check if this is the first declaration of the special member, 6377 // since we may not have parsed some necessary in-class initializers yet. 6378 if (First) { 6379 // If the exception specification needs to be instantiated, do so now, 6380 // before we clobber it with an EST_Unevaluated specification below. 6381 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6382 InstantiateExceptionSpec(MD->getLocStart(), MD); 6383 Type = MD->getType()->getAs<FunctionProtoType>(); 6384 } 6385 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6386 } else 6387 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6388 } 6389 6390 // If a function is explicitly defaulted on its first declaration, 6391 if (First) { 6392 // -- it is implicitly considered to be constexpr if the implicit 6393 // definition would be, 6394 MD->setConstexpr(Constexpr); 6395 6396 // -- it is implicitly considered to have the same exception-specification 6397 // as if it had been implicitly declared, 6398 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6399 EPI.ExceptionSpec.Type = EST_Unevaluated; 6400 EPI.ExceptionSpec.SourceDecl = MD; 6401 MD->setType(Context.getFunctionType(ReturnType, 6402 llvm::makeArrayRef(&ArgType, 6403 ExpectedParams), 6404 EPI)); 6405 } 6406 6407 if (ShouldDeleteSpecialMember(MD, CSM)) { 6408 if (First) { 6409 SetDeclDeleted(MD, MD->getLocation()); 6410 } else { 6411 // C++11 [dcl.fct.def.default]p4: 6412 // [For a] user-provided explicitly-defaulted function [...] if such a 6413 // function is implicitly defined as deleted, the program is ill-formed. 6414 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6415 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6416 HadError = true; 6417 } 6418 } 6419 6420 if (HadError) 6421 MD->setInvalidDecl(); 6422 } 6423 6424 /// Check whether the exception specification provided for an 6425 /// explicitly-defaulted special member matches the exception specification 6426 /// that would have been generated for an implicit special member, per 6427 /// C++11 [dcl.fct.def.default]p2. 6428 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6429 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6430 // If the exception specification was explicitly specified but hadn't been 6431 // parsed when the method was defaulted, grab it now. 6432 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6433 SpecifiedType = 6434 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6435 6436 // Compute the implicit exception specification. 6437 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6438 /*IsCXXMethod=*/true); 6439 FunctionProtoType::ExtProtoInfo EPI(CC); 6440 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD); 6441 EPI.ExceptionSpec = IES.getExceptionSpec(); 6442 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6443 Context.getFunctionType(Context.VoidTy, None, EPI)); 6444 6445 // Ensure that it matches. 6446 CheckEquivalentExceptionSpec( 6447 PDiag(diag::err_incorrect_defaulted_exception_spec) 6448 << getSpecialMember(MD), PDiag(), 6449 ImplicitType, SourceLocation(), 6450 SpecifiedType, MD->getLocation()); 6451 } 6452 6453 void Sema::CheckDelayedMemberExceptionSpecs() { 6454 decltype(DelayedExceptionSpecChecks) Checks; 6455 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 6456 6457 std::swap(Checks, DelayedExceptionSpecChecks); 6458 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 6459 6460 // Perform any deferred checking of exception specifications for virtual 6461 // destructors. 6462 for (auto &Check : Checks) 6463 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6464 6465 // Check that any explicitly-defaulted methods have exception specifications 6466 // compatible with their implicit exception specifications. 6467 for (auto &Spec : Specs) 6468 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6469 } 6470 6471 namespace { 6472 /// CRTP base class for visiting operations performed by a special member 6473 /// function (or inherited constructor). 6474 template<typename Derived> 6475 struct SpecialMemberVisitor { 6476 Sema &S; 6477 CXXMethodDecl *MD; 6478 Sema::CXXSpecialMember CSM; 6479 Sema::InheritedConstructorInfo *ICI; 6480 6481 // Properties of the special member, computed for convenience. 6482 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6483 6484 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6485 Sema::InheritedConstructorInfo *ICI) 6486 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6487 switch (CSM) { 6488 case Sema::CXXDefaultConstructor: 6489 case Sema::CXXCopyConstructor: 6490 case Sema::CXXMoveConstructor: 6491 IsConstructor = true; 6492 break; 6493 case Sema::CXXCopyAssignment: 6494 case Sema::CXXMoveAssignment: 6495 IsAssignment = true; 6496 break; 6497 case Sema::CXXDestructor: 6498 break; 6499 case Sema::CXXInvalid: 6500 llvm_unreachable("invalid special member kind"); 6501 } 6502 6503 if (MD->getNumParams()) { 6504 if (const ReferenceType *RT = 6505 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6506 ConstArg = RT->getPointeeType().isConstQualified(); 6507 } 6508 } 6509 6510 Derived &getDerived() { return static_cast<Derived&>(*this); } 6511 6512 /// Is this a "move" special member? 6513 bool isMove() const { 6514 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6515 } 6516 6517 /// Look up the corresponding special member in the given class. 6518 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6519 unsigned Quals, bool IsMutable) { 6520 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6521 ConstArg && !IsMutable); 6522 } 6523 6524 /// Look up the constructor for the specified base class to see if it's 6525 /// overridden due to this being an inherited constructor. 6526 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6527 if (!ICI) 6528 return {}; 6529 assert(CSM == Sema::CXXDefaultConstructor); 6530 auto *BaseCtor = 6531 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6532 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6533 return MD; 6534 return {}; 6535 } 6536 6537 /// A base or member subobject. 6538 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6539 6540 /// Get the location to use for a subobject in diagnostics. 6541 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6542 // FIXME: For an indirect virtual base, the direct base leading to 6543 // the indirect virtual base would be a more useful choice. 6544 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6545 return B->getBaseTypeLoc(); 6546 else 6547 return Subobj.get<FieldDecl*>()->getLocation(); 6548 } 6549 6550 enum BasesToVisit { 6551 /// Visit all non-virtual (direct) bases. 6552 VisitNonVirtualBases, 6553 /// Visit all direct bases, virtual or not. 6554 VisitDirectBases, 6555 /// Visit all non-virtual bases, and all virtual bases if the class 6556 /// is not abstract. 6557 VisitPotentiallyConstructedBases, 6558 /// Visit all direct or virtual bases. 6559 VisitAllBases 6560 }; 6561 6562 // Visit the bases and members of the class. 6563 bool visit(BasesToVisit Bases) { 6564 CXXRecordDecl *RD = MD->getParent(); 6565 6566 if (Bases == VisitPotentiallyConstructedBases) 6567 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6568 6569 for (auto &B : RD->bases()) 6570 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6571 getDerived().visitBase(&B)) 6572 return true; 6573 6574 if (Bases == VisitAllBases) 6575 for (auto &B : RD->vbases()) 6576 if (getDerived().visitBase(&B)) 6577 return true; 6578 6579 for (auto *F : RD->fields()) 6580 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 6581 getDerived().visitField(F)) 6582 return true; 6583 6584 return false; 6585 } 6586 }; 6587 } 6588 6589 namespace { 6590 struct SpecialMemberDeletionInfo 6591 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 6592 bool Diagnose; 6593 6594 SourceLocation Loc; 6595 6596 bool AllFieldsAreConst; 6597 6598 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6599 Sema::CXXSpecialMember CSM, 6600 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6601 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 6602 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 6603 6604 bool inUnion() const { return MD->getParent()->isUnion(); } 6605 6606 Sema::CXXSpecialMember getEffectiveCSM() { 6607 return ICI ? Sema::CXXInvalid : CSM; 6608 } 6609 6610 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 6611 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 6612 6613 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6614 bool shouldDeleteForField(FieldDecl *FD); 6615 bool shouldDeleteForAllConstMembers(); 6616 6617 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6618 unsigned Quals); 6619 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6620 Sema::SpecialMemberOverloadResult SMOR, 6621 bool IsDtorCallInCtor); 6622 6623 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6624 }; 6625 } 6626 6627 /// Is the given special member inaccessible when used on the given 6628 /// sub-object. 6629 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6630 CXXMethodDecl *target) { 6631 /// If we're operating on a base class, the object type is the 6632 /// type of this special member. 6633 QualType objectTy; 6634 AccessSpecifier access = target->getAccess(); 6635 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6636 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6637 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6638 6639 // If we're operating on a field, the object type is the type of the field. 6640 } else { 6641 objectTy = S.Context.getTypeDeclType(target->getParent()); 6642 } 6643 6644 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6645 } 6646 6647 /// Check whether we should delete a special member due to the implicit 6648 /// definition containing a call to a special member of a subobject. 6649 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6650 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 6651 bool IsDtorCallInCtor) { 6652 CXXMethodDecl *Decl = SMOR.getMethod(); 6653 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6654 6655 int DiagKind = -1; 6656 6657 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6658 DiagKind = !Decl ? 0 : 1; 6659 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6660 DiagKind = 2; 6661 else if (!isAccessible(Subobj, Decl)) 6662 DiagKind = 3; 6663 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6664 !Decl->isTrivial()) { 6665 // A member of a union must have a trivial corresponding special member. 6666 // As a weird special case, a destructor call from a union's constructor 6667 // must be accessible and non-deleted, but need not be trivial. Such a 6668 // destructor is never actually called, but is semantically checked as 6669 // if it were. 6670 DiagKind = 4; 6671 } 6672 6673 if (DiagKind == -1) 6674 return false; 6675 6676 if (Diagnose) { 6677 if (Field) { 6678 S.Diag(Field->getLocation(), 6679 diag::note_deleted_special_member_class_subobject) 6680 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6681 << Field << DiagKind << IsDtorCallInCtor; 6682 } else { 6683 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6684 S.Diag(Base->getLocStart(), 6685 diag::note_deleted_special_member_class_subobject) 6686 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6687 << Base->getType() << DiagKind << IsDtorCallInCtor; 6688 } 6689 6690 if (DiagKind == 1) 6691 S.NoteDeletedFunction(Decl); 6692 // FIXME: Explain inaccessibility if DiagKind == 3. 6693 } 6694 6695 return true; 6696 } 6697 6698 /// Check whether we should delete a special member function due to having a 6699 /// direct or virtual base class or non-static data member of class type M. 6700 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6701 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6702 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6703 bool IsMutable = Field && Field->isMutable(); 6704 6705 // C++11 [class.ctor]p5: 6706 // -- any direct or virtual base class, or non-static data member with no 6707 // brace-or-equal-initializer, has class type M (or array thereof) and 6708 // either M has no default constructor or overload resolution as applied 6709 // to M's default constructor results in an ambiguity or in a function 6710 // that is deleted or inaccessible 6711 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6712 // -- a direct or virtual base class B that cannot be copied/moved because 6713 // overload resolution, as applied to B's corresponding special member, 6714 // results in an ambiguity or a function that is deleted or inaccessible 6715 // from the defaulted special member 6716 // C++11 [class.dtor]p5: 6717 // -- any direct or virtual base class [...] has a type with a destructor 6718 // that is deleted or inaccessible 6719 if (!(CSM == Sema::CXXDefaultConstructor && 6720 Field && Field->hasInClassInitializer()) && 6721 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 6722 false)) 6723 return true; 6724 6725 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 6726 // -- any direct or virtual base class or non-static data member has a 6727 // type with a destructor that is deleted or inaccessible 6728 if (IsConstructor) { 6729 Sema::SpecialMemberOverloadResult SMOR = 6730 S.LookupSpecialMember(Class, Sema::CXXDestructor, 6731 false, false, false, false, false); 6732 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 6733 return true; 6734 } 6735 6736 return false; 6737 } 6738 6739 /// Check whether we should delete a special member function due to the class 6740 /// having a particular direct or virtual base class. 6741 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 6742 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 6743 // If program is correct, BaseClass cannot be null, but if it is, the error 6744 // must be reported elsewhere. 6745 if (!BaseClass) 6746 return false; 6747 // If we have an inheriting constructor, check whether we're calling an 6748 // inherited constructor instead of a default constructor. 6749 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 6750 if (auto *BaseCtor = SMOR.getMethod()) { 6751 // Note that we do not check access along this path; other than that, 6752 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 6753 // FIXME: Check that the base has a usable destructor! Sink this into 6754 // shouldDeleteForClassSubobject. 6755 if (BaseCtor->isDeleted() && Diagnose) { 6756 S.Diag(Base->getLocStart(), 6757 diag::note_deleted_special_member_class_subobject) 6758 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6759 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false; 6760 S.NoteDeletedFunction(BaseCtor); 6761 } 6762 return BaseCtor->isDeleted(); 6763 } 6764 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 6765 } 6766 6767 /// Check whether we should delete a special member function due to the class 6768 /// having a particular non-static data member. 6769 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 6770 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 6771 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 6772 6773 if (CSM == Sema::CXXDefaultConstructor) { 6774 // For a default constructor, all references must be initialized in-class 6775 // and, if a union, it must have a non-const member. 6776 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 6777 if (Diagnose) 6778 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6779 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 6780 return true; 6781 } 6782 // C++11 [class.ctor]p5: any non-variant non-static data member of 6783 // const-qualified type (or array thereof) with no 6784 // brace-or-equal-initializer does not have a user-provided default 6785 // constructor. 6786 if (!inUnion() && FieldType.isConstQualified() && 6787 !FD->hasInClassInitializer() && 6788 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 6789 if (Diagnose) 6790 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6791 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 6792 return true; 6793 } 6794 6795 if (inUnion() && !FieldType.isConstQualified()) 6796 AllFieldsAreConst = false; 6797 } else if (CSM == Sema::CXXCopyConstructor) { 6798 // For a copy constructor, data members must not be of rvalue reference 6799 // type. 6800 if (FieldType->isRValueReferenceType()) { 6801 if (Diagnose) 6802 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 6803 << MD->getParent() << FD << FieldType; 6804 return true; 6805 } 6806 } else if (IsAssignment) { 6807 // For an assignment operator, data members must not be of reference type. 6808 if (FieldType->isReferenceType()) { 6809 if (Diagnose) 6810 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6811 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 6812 return true; 6813 } 6814 if (!FieldRecord && FieldType.isConstQualified()) { 6815 // C++11 [class.copy]p23: 6816 // -- a non-static data member of const non-class type (or array thereof) 6817 if (Diagnose) 6818 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6819 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 6820 return true; 6821 } 6822 } 6823 6824 if (FieldRecord) { 6825 // Some additional restrictions exist on the variant members. 6826 if (!inUnion() && FieldRecord->isUnion() && 6827 FieldRecord->isAnonymousStructOrUnion()) { 6828 bool AllVariantFieldsAreConst = true; 6829 6830 // FIXME: Handle anonymous unions declared within anonymous unions. 6831 for (auto *UI : FieldRecord->fields()) { 6832 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 6833 6834 if (!UnionFieldType.isConstQualified()) 6835 AllVariantFieldsAreConst = false; 6836 6837 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 6838 if (UnionFieldRecord && 6839 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 6840 UnionFieldType.getCVRQualifiers())) 6841 return true; 6842 } 6843 6844 // At least one member in each anonymous union must be non-const 6845 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 6846 !FieldRecord->field_empty()) { 6847 if (Diagnose) 6848 S.Diag(FieldRecord->getLocation(), 6849 diag::note_deleted_default_ctor_all_const) 6850 << !!ICI << MD->getParent() << /*anonymous union*/1; 6851 return true; 6852 } 6853 6854 // Don't check the implicit member of the anonymous union type. 6855 // This is technically non-conformant, but sanity demands it. 6856 return false; 6857 } 6858 6859 if (shouldDeleteForClassSubobject(FieldRecord, FD, 6860 FieldType.getCVRQualifiers())) 6861 return true; 6862 } 6863 6864 return false; 6865 } 6866 6867 /// C++11 [class.ctor] p5: 6868 /// A defaulted default constructor for a class X is defined as deleted if 6869 /// X is a union and all of its variant members are of const-qualified type. 6870 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 6871 // This is a silly definition, because it gives an empty union a deleted 6872 // default constructor. Don't do that. 6873 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 6874 bool AnyFields = false; 6875 for (auto *F : MD->getParent()->fields()) 6876 if ((AnyFields = !F->isUnnamedBitfield())) 6877 break; 6878 if (!AnyFields) 6879 return false; 6880 if (Diagnose) 6881 S.Diag(MD->getParent()->getLocation(), 6882 diag::note_deleted_default_ctor_all_const) 6883 << !!ICI << MD->getParent() << /*not anonymous union*/0; 6884 return true; 6885 } 6886 return false; 6887 } 6888 6889 /// Determine whether a defaulted special member function should be defined as 6890 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 6891 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 6892 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 6893 InheritedConstructorInfo *ICI, 6894 bool Diagnose) { 6895 if (MD->isInvalidDecl()) 6896 return false; 6897 CXXRecordDecl *RD = MD->getParent(); 6898 assert(!RD->isDependentType() && "do deletion after instantiation"); 6899 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 6900 return false; 6901 6902 // C++11 [expr.lambda.prim]p19: 6903 // The closure type associated with a lambda-expression has a 6904 // deleted (8.4.3) default constructor and a deleted copy 6905 // assignment operator. 6906 if (RD->isLambda() && 6907 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 6908 if (Diagnose) 6909 Diag(RD->getLocation(), diag::note_lambda_decl); 6910 return true; 6911 } 6912 6913 // For an anonymous struct or union, the copy and assignment special members 6914 // will never be used, so skip the check. For an anonymous union declared at 6915 // namespace scope, the constructor and destructor are used. 6916 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 6917 RD->isAnonymousStructOrUnion()) 6918 return false; 6919 6920 // C++11 [class.copy]p7, p18: 6921 // If the class definition declares a move constructor or move assignment 6922 // operator, an implicitly declared copy constructor or copy assignment 6923 // operator is defined as deleted. 6924 if (MD->isImplicit() && 6925 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 6926 CXXMethodDecl *UserDeclaredMove = nullptr; 6927 6928 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 6929 // deletion of the corresponding copy operation, not both copy operations. 6930 // MSVC 2015 has adopted the standards conforming behavior. 6931 bool DeletesOnlyMatchingCopy = 6932 getLangOpts().MSVCCompat && 6933 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 6934 6935 if (RD->hasUserDeclaredMoveConstructor() && 6936 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 6937 if (!Diagnose) return true; 6938 6939 // Find any user-declared move constructor. 6940 for (auto *I : RD->ctors()) { 6941 if (I->isMoveConstructor()) { 6942 UserDeclaredMove = I; 6943 break; 6944 } 6945 } 6946 assert(UserDeclaredMove); 6947 } else if (RD->hasUserDeclaredMoveAssignment() && 6948 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 6949 if (!Diagnose) return true; 6950 6951 // Find any user-declared move assignment operator. 6952 for (auto *I : RD->methods()) { 6953 if (I->isMoveAssignmentOperator()) { 6954 UserDeclaredMove = I; 6955 break; 6956 } 6957 } 6958 assert(UserDeclaredMove); 6959 } 6960 6961 if (UserDeclaredMove) { 6962 Diag(UserDeclaredMove->getLocation(), 6963 diag::note_deleted_copy_user_declared_move) 6964 << (CSM == CXXCopyAssignment) << RD 6965 << UserDeclaredMove->isMoveAssignmentOperator(); 6966 return true; 6967 } 6968 } 6969 6970 // Do access control from the special member function 6971 ContextRAII MethodContext(*this, MD); 6972 6973 // C++11 [class.dtor]p5: 6974 // -- for a virtual destructor, lookup of the non-array deallocation function 6975 // results in an ambiguity or in a function that is deleted or inaccessible 6976 if (CSM == CXXDestructor && MD->isVirtual()) { 6977 FunctionDecl *OperatorDelete = nullptr; 6978 DeclarationName Name = 6979 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6980 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 6981 OperatorDelete, /*Diagnose*/false)) { 6982 if (Diagnose) 6983 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 6984 return true; 6985 } 6986 } 6987 6988 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 6989 6990 // Per DR1611, do not consider virtual bases of constructors of abstract 6991 // classes, since we are not going to construct them. 6992 // Per DR1658, do not consider virtual bases of destructors of abstract 6993 // classes either. 6994 // Per DR2180, for assignment operators we only assign (and thus only 6995 // consider) direct bases. 6996 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 6997 : SMI.VisitPotentiallyConstructedBases)) 6998 return true; 6999 7000 if (SMI.shouldDeleteForAllConstMembers()) 7001 return true; 7002 7003 if (getLangOpts().CUDA) { 7004 // We should delete the special member in CUDA mode if target inference 7005 // failed. 7006 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 7007 Diagnose); 7008 } 7009 7010 return false; 7011 } 7012 7013 /// Perform lookup for a special member of the specified kind, and determine 7014 /// whether it is trivial. If the triviality can be determined without the 7015 /// lookup, skip it. This is intended for use when determining whether a 7016 /// special member of a containing object is trivial, and thus does not ever 7017 /// perform overload resolution for default constructors. 7018 /// 7019 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 7020 /// member that was most likely to be intended to be trivial, if any. 7021 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 7022 Sema::CXXSpecialMember CSM, unsigned Quals, 7023 bool ConstRHS, CXXMethodDecl **Selected) { 7024 if (Selected) 7025 *Selected = nullptr; 7026 7027 switch (CSM) { 7028 case Sema::CXXInvalid: 7029 llvm_unreachable("not a special member"); 7030 7031 case Sema::CXXDefaultConstructor: 7032 // C++11 [class.ctor]p5: 7033 // A default constructor is trivial if: 7034 // - all the [direct subobjects] have trivial default constructors 7035 // 7036 // Note, no overload resolution is performed in this case. 7037 if (RD->hasTrivialDefaultConstructor()) 7038 return true; 7039 7040 if (Selected) { 7041 // If there's a default constructor which could have been trivial, dig it 7042 // out. Otherwise, if there's any user-provided default constructor, point 7043 // to that as an example of why there's not a trivial one. 7044 CXXConstructorDecl *DefCtor = nullptr; 7045 if (RD->needsImplicitDefaultConstructor()) 7046 S.DeclareImplicitDefaultConstructor(RD); 7047 for (auto *CI : RD->ctors()) { 7048 if (!CI->isDefaultConstructor()) 7049 continue; 7050 DefCtor = CI; 7051 if (!DefCtor->isUserProvided()) 7052 break; 7053 } 7054 7055 *Selected = DefCtor; 7056 } 7057 7058 return false; 7059 7060 case Sema::CXXDestructor: 7061 // C++11 [class.dtor]p5: 7062 // A destructor is trivial if: 7063 // - all the direct [subobjects] have trivial destructors 7064 if (RD->hasTrivialDestructor()) 7065 return true; 7066 7067 if (Selected) { 7068 if (RD->needsImplicitDestructor()) 7069 S.DeclareImplicitDestructor(RD); 7070 *Selected = RD->getDestructor(); 7071 } 7072 7073 return false; 7074 7075 case Sema::CXXCopyConstructor: 7076 // C++11 [class.copy]p12: 7077 // A copy constructor is trivial if: 7078 // - the constructor selected to copy each direct [subobject] is trivial 7079 if (RD->hasTrivialCopyConstructor()) { 7080 if (Quals == Qualifiers::Const) 7081 // We must either select the trivial copy constructor or reach an 7082 // ambiguity; no need to actually perform overload resolution. 7083 return true; 7084 } else if (!Selected) { 7085 return false; 7086 } 7087 // In C++98, we are not supposed to perform overload resolution here, but we 7088 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7089 // cases like B as having a non-trivial copy constructor: 7090 // struct A { template<typename T> A(T&); }; 7091 // struct B { mutable A a; }; 7092 goto NeedOverloadResolution; 7093 7094 case Sema::CXXCopyAssignment: 7095 // C++11 [class.copy]p25: 7096 // A copy assignment operator is trivial if: 7097 // - the assignment operator selected to copy each direct [subobject] is 7098 // trivial 7099 if (RD->hasTrivialCopyAssignment()) { 7100 if (Quals == Qualifiers::Const) 7101 return true; 7102 } else if (!Selected) { 7103 return false; 7104 } 7105 // In C++98, we are not supposed to perform overload resolution here, but we 7106 // treat that as a language defect. 7107 goto NeedOverloadResolution; 7108 7109 case Sema::CXXMoveConstructor: 7110 case Sema::CXXMoveAssignment: 7111 NeedOverloadResolution: 7112 Sema::SpecialMemberOverloadResult SMOR = 7113 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7114 7115 // The standard doesn't describe how to behave if the lookup is ambiguous. 7116 // We treat it as not making the member non-trivial, just like the standard 7117 // mandates for the default constructor. This should rarely matter, because 7118 // the member will also be deleted. 7119 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7120 return true; 7121 7122 if (!SMOR.getMethod()) { 7123 assert(SMOR.getKind() == 7124 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7125 return false; 7126 } 7127 7128 // We deliberately don't check if we found a deleted special member. We're 7129 // not supposed to! 7130 if (Selected) 7131 *Selected = SMOR.getMethod(); 7132 return SMOR.getMethod()->isTrivial(); 7133 } 7134 7135 llvm_unreachable("unknown special method kind"); 7136 } 7137 7138 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7139 for (auto *CI : RD->ctors()) 7140 if (!CI->isImplicit()) 7141 return CI; 7142 7143 // Look for constructor templates. 7144 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7145 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7146 if (CXXConstructorDecl *CD = 7147 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7148 return CD; 7149 } 7150 7151 return nullptr; 7152 } 7153 7154 /// The kind of subobject we are checking for triviality. The values of this 7155 /// enumeration are used in diagnostics. 7156 enum TrivialSubobjectKind { 7157 /// The subobject is a base class. 7158 TSK_BaseClass, 7159 /// The subobject is a non-static data member. 7160 TSK_Field, 7161 /// The object is actually the complete object. 7162 TSK_CompleteObject 7163 }; 7164 7165 /// Check whether the special member selected for a given type would be trivial. 7166 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7167 QualType SubType, bool ConstRHS, 7168 Sema::CXXSpecialMember CSM, 7169 TrivialSubobjectKind Kind, 7170 bool Diagnose) { 7171 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7172 if (!SubRD) 7173 return true; 7174 7175 CXXMethodDecl *Selected; 7176 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7177 ConstRHS, Diagnose ? &Selected : nullptr)) 7178 return true; 7179 7180 if (Diagnose) { 7181 if (ConstRHS) 7182 SubType.addConst(); 7183 7184 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7185 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7186 << Kind << SubType.getUnqualifiedType(); 7187 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7188 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7189 } else if (!Selected) 7190 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7191 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7192 else if (Selected->isUserProvided()) { 7193 if (Kind == TSK_CompleteObject) 7194 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7195 << Kind << SubType.getUnqualifiedType() << CSM; 7196 else { 7197 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7198 << Kind << SubType.getUnqualifiedType() << CSM; 7199 S.Diag(Selected->getLocation(), diag::note_declared_at); 7200 } 7201 } else { 7202 if (Kind != TSK_CompleteObject) 7203 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7204 << Kind << SubType.getUnqualifiedType() << CSM; 7205 7206 // Explain why the defaulted or deleted special member isn't trivial. 7207 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 7208 } 7209 } 7210 7211 return false; 7212 } 7213 7214 /// Check whether the members of a class type allow a special member to be 7215 /// trivial. 7216 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7217 Sema::CXXSpecialMember CSM, 7218 bool ConstArg, bool Diagnose) { 7219 for (const auto *FI : RD->fields()) { 7220 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7221 continue; 7222 7223 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7224 7225 // Pretend anonymous struct or union members are members of this class. 7226 if (FI->isAnonymousStructOrUnion()) { 7227 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7228 CSM, ConstArg, Diagnose)) 7229 return false; 7230 continue; 7231 } 7232 7233 // C++11 [class.ctor]p5: 7234 // A default constructor is trivial if [...] 7235 // -- no non-static data member of its class has a 7236 // brace-or-equal-initializer 7237 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7238 if (Diagnose) 7239 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7240 return false; 7241 } 7242 7243 // Objective C ARC 4.3.5: 7244 // [...] nontrivally ownership-qualified types are [...] not trivially 7245 // default constructible, copy constructible, move constructible, copy 7246 // assignable, move assignable, or destructible [...] 7247 if (FieldType.hasNonTrivialObjCLifetime()) { 7248 if (Diagnose) 7249 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7250 << RD << FieldType.getObjCLifetime(); 7251 return false; 7252 } 7253 7254 bool ConstRHS = ConstArg && !FI->isMutable(); 7255 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7256 CSM, TSK_Field, Diagnose)) 7257 return false; 7258 } 7259 7260 return true; 7261 } 7262 7263 /// Diagnose why the specified class does not have a trivial special member of 7264 /// the given kind. 7265 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7266 QualType Ty = Context.getRecordType(RD); 7267 7268 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7269 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7270 TSK_CompleteObject, /*Diagnose*/true); 7271 } 7272 7273 /// Determine whether a defaulted or deleted special member function is trivial, 7274 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7275 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7276 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7277 bool Diagnose) { 7278 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7279 7280 CXXRecordDecl *RD = MD->getParent(); 7281 7282 bool ConstArg = false; 7283 7284 // C++11 [class.copy]p12, p25: [DR1593] 7285 // A [special member] is trivial if [...] its parameter-type-list is 7286 // equivalent to the parameter-type-list of an implicit declaration [...] 7287 switch (CSM) { 7288 case CXXDefaultConstructor: 7289 case CXXDestructor: 7290 // Trivial default constructors and destructors cannot have parameters. 7291 break; 7292 7293 case CXXCopyConstructor: 7294 case CXXCopyAssignment: { 7295 // Trivial copy operations always have const, non-volatile parameter types. 7296 ConstArg = true; 7297 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7298 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7299 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7300 if (Diagnose) 7301 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7302 << Param0->getSourceRange() << Param0->getType() 7303 << Context.getLValueReferenceType( 7304 Context.getRecordType(RD).withConst()); 7305 return false; 7306 } 7307 break; 7308 } 7309 7310 case CXXMoveConstructor: 7311 case CXXMoveAssignment: { 7312 // Trivial move operations always have non-cv-qualified parameters. 7313 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7314 const RValueReferenceType *RT = 7315 Param0->getType()->getAs<RValueReferenceType>(); 7316 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7317 if (Diagnose) 7318 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7319 << Param0->getSourceRange() << Param0->getType() 7320 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7321 return false; 7322 } 7323 break; 7324 } 7325 7326 case CXXInvalid: 7327 llvm_unreachable("not a special member"); 7328 } 7329 7330 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7331 if (Diagnose) 7332 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7333 diag::note_nontrivial_default_arg) 7334 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7335 return false; 7336 } 7337 if (MD->isVariadic()) { 7338 if (Diagnose) 7339 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7340 return false; 7341 } 7342 7343 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7344 // A copy/move [constructor or assignment operator] is trivial if 7345 // -- the [member] selected to copy/move each direct base class subobject 7346 // is trivial 7347 // 7348 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7349 // A [default constructor or destructor] is trivial if 7350 // -- all the direct base classes have trivial [default constructors or 7351 // destructors] 7352 for (const auto &BI : RD->bases()) 7353 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 7354 ConstArg, CSM, TSK_BaseClass, Diagnose)) 7355 return false; 7356 7357 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7358 // A copy/move [constructor or assignment operator] for a class X is 7359 // trivial if 7360 // -- for each non-static data member of X that is of class type (or array 7361 // thereof), the constructor selected to copy/move that member is 7362 // trivial 7363 // 7364 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7365 // A [default constructor or destructor] is trivial if 7366 // -- for all of the non-static data members of its class that are of class 7367 // type (or array thereof), each such class has a trivial [default 7368 // constructor or destructor] 7369 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 7370 return false; 7371 7372 // C++11 [class.dtor]p5: 7373 // A destructor is trivial if [...] 7374 // -- the destructor is not virtual 7375 if (CSM == CXXDestructor && MD->isVirtual()) { 7376 if (Diagnose) 7377 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7378 return false; 7379 } 7380 7381 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7382 // A [special member] for class X is trivial if [...] 7383 // -- class X has no virtual functions and no virtual base classes 7384 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7385 if (!Diagnose) 7386 return false; 7387 7388 if (RD->getNumVBases()) { 7389 // Check for virtual bases. We already know that the corresponding 7390 // member in all bases is trivial, so vbases must all be direct. 7391 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7392 assert(BS.isVirtual()); 7393 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 7394 return false; 7395 } 7396 7397 // Must have a virtual method. 7398 for (const auto *MI : RD->methods()) { 7399 if (MI->isVirtual()) { 7400 SourceLocation MLoc = MI->getLocStart(); 7401 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7402 return false; 7403 } 7404 } 7405 7406 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7407 } 7408 7409 // Looks like it's trivial! 7410 return true; 7411 } 7412 7413 namespace { 7414 struct FindHiddenVirtualMethod { 7415 Sema *S; 7416 CXXMethodDecl *Method; 7417 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7418 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7419 7420 private: 7421 /// Check whether any most overriden method from MD in Methods 7422 static bool CheckMostOverridenMethods( 7423 const CXXMethodDecl *MD, 7424 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7425 if (MD->size_overridden_methods() == 0) 7426 return Methods.count(MD->getCanonicalDecl()); 7427 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7428 E = MD->end_overridden_methods(); 7429 I != E; ++I) 7430 if (CheckMostOverridenMethods(*I, Methods)) 7431 return true; 7432 return false; 7433 } 7434 7435 public: 7436 /// Member lookup function that determines whether a given C++ 7437 /// method overloads virtual methods in a base class without overriding any, 7438 /// to be used with CXXRecordDecl::lookupInBases(). 7439 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7440 RecordDecl *BaseRecord = 7441 Specifier->getType()->getAs<RecordType>()->getDecl(); 7442 7443 DeclarationName Name = Method->getDeclName(); 7444 assert(Name.getNameKind() == DeclarationName::Identifier); 7445 7446 bool foundSameNameMethod = false; 7447 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7448 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7449 Path.Decls = Path.Decls.slice(1)) { 7450 NamedDecl *D = Path.Decls.front(); 7451 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7452 MD = MD->getCanonicalDecl(); 7453 foundSameNameMethod = true; 7454 // Interested only in hidden virtual methods. 7455 if (!MD->isVirtual()) 7456 continue; 7457 // If the method we are checking overrides a method from its base 7458 // don't warn about the other overloaded methods. Clang deviates from 7459 // GCC by only diagnosing overloads of inherited virtual functions that 7460 // do not override any other virtual functions in the base. GCC's 7461 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7462 // function from a base class. These cases may be better served by a 7463 // warning (not specific to virtual functions) on call sites when the 7464 // call would select a different function from the base class, were it 7465 // visible. 7466 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7467 if (!S->IsOverload(Method, MD, false)) 7468 return true; 7469 // Collect the overload only if its hidden. 7470 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7471 overloadedMethods.push_back(MD); 7472 } 7473 } 7474 7475 if (foundSameNameMethod) 7476 OverloadedMethods.append(overloadedMethods.begin(), 7477 overloadedMethods.end()); 7478 return foundSameNameMethod; 7479 } 7480 }; 7481 } // end anonymous namespace 7482 7483 /// \brief Add the most overriden methods from MD to Methods 7484 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7485 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7486 if (MD->size_overridden_methods() == 0) 7487 Methods.insert(MD->getCanonicalDecl()); 7488 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7489 E = MD->end_overridden_methods(); 7490 I != E; ++I) 7491 AddMostOverridenMethods(*I, Methods); 7492 } 7493 7494 /// \brief Check if a method overloads virtual methods in a base class without 7495 /// overriding any. 7496 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7497 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7498 if (!MD->getDeclName().isIdentifier()) 7499 return; 7500 7501 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7502 /*bool RecordPaths=*/false, 7503 /*bool DetectVirtual=*/false); 7504 FindHiddenVirtualMethod FHVM; 7505 FHVM.Method = MD; 7506 FHVM.S = this; 7507 7508 // Keep the base methods that were overriden or introduced in the subclass 7509 // by 'using' in a set. A base method not in this set is hidden. 7510 CXXRecordDecl *DC = MD->getParent(); 7511 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7512 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7513 NamedDecl *ND = *I; 7514 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7515 ND = shad->getTargetDecl(); 7516 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7517 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7518 } 7519 7520 if (DC->lookupInBases(FHVM, Paths)) 7521 OverloadedMethods = FHVM.OverloadedMethods; 7522 } 7523 7524 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7525 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7526 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7527 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7528 PartialDiagnostic PD = PDiag( 7529 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7530 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7531 Diag(overloadedMD->getLocation(), PD); 7532 } 7533 } 7534 7535 /// \brief Diagnose methods which overload virtual methods in a base class 7536 /// without overriding any. 7537 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7538 if (MD->isInvalidDecl()) 7539 return; 7540 7541 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7542 return; 7543 7544 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7545 FindHiddenVirtualMethods(MD, OverloadedMethods); 7546 if (!OverloadedMethods.empty()) { 7547 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7548 << MD << (OverloadedMethods.size() > 1); 7549 7550 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7551 } 7552 } 7553 7554 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 7555 Decl *TagDecl, 7556 SourceLocation LBrac, 7557 SourceLocation RBrac, 7558 AttributeList *AttrList) { 7559 if (!TagDecl) 7560 return; 7561 7562 AdjustDeclIfTemplate(TagDecl); 7563 7564 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 7565 if (l->getKind() != AttributeList::AT_Visibility) 7566 continue; 7567 l->setInvalid(); 7568 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 7569 l->getName(); 7570 } 7571 7572 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7573 // strict aliasing violation! 7574 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7575 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7576 7577 CheckCompletedCXXClass(dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 7578 } 7579 7580 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7581 /// special functions, such as the default constructor, copy 7582 /// constructor, or destructor, to the given C++ class (C++ 7583 /// [special]p1). This routine can only be executed just before the 7584 /// definition of the class is complete. 7585 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7586 if (ClassDecl->needsImplicitDefaultConstructor()) { 7587 ++ASTContext::NumImplicitDefaultConstructors; 7588 7589 if (ClassDecl->hasInheritedConstructor()) 7590 DeclareImplicitDefaultConstructor(ClassDecl); 7591 } 7592 7593 if (ClassDecl->needsImplicitCopyConstructor()) { 7594 ++ASTContext::NumImplicitCopyConstructors; 7595 7596 // If the properties or semantics of the copy constructor couldn't be 7597 // determined while the class was being declared, force a declaration 7598 // of it now. 7599 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7600 ClassDecl->hasInheritedConstructor()) 7601 DeclareImplicitCopyConstructor(ClassDecl); 7602 // For the MS ABI we need to know whether the copy ctor is deleted. A 7603 // prerequisite for deleting the implicit copy ctor is that the class has a 7604 // move ctor or move assignment that is either user-declared or whose 7605 // semantics are inherited from a subobject. FIXME: We should provide a more 7606 // direct way for CodeGen to ask whether the constructor was deleted. 7607 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 7608 (ClassDecl->hasUserDeclaredMoveConstructor() || 7609 ClassDecl->needsOverloadResolutionForMoveConstructor() || 7610 ClassDecl->hasUserDeclaredMoveAssignment() || 7611 ClassDecl->needsOverloadResolutionForMoveAssignment())) 7612 DeclareImplicitCopyConstructor(ClassDecl); 7613 } 7614 7615 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7616 ++ASTContext::NumImplicitMoveConstructors; 7617 7618 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7619 ClassDecl->hasInheritedConstructor()) 7620 DeclareImplicitMoveConstructor(ClassDecl); 7621 } 7622 7623 if (ClassDecl->needsImplicitCopyAssignment()) { 7624 ++ASTContext::NumImplicitCopyAssignmentOperators; 7625 7626 // If we have a dynamic class, then the copy assignment operator may be 7627 // virtual, so we have to declare it immediately. This ensures that, e.g., 7628 // it shows up in the right place in the vtable and that we diagnose 7629 // problems with the implicit exception specification. 7630 if (ClassDecl->isDynamicClass() || 7631 ClassDecl->needsOverloadResolutionForCopyAssignment() || 7632 ClassDecl->hasInheritedAssignment()) 7633 DeclareImplicitCopyAssignment(ClassDecl); 7634 } 7635 7636 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 7637 ++ASTContext::NumImplicitMoveAssignmentOperators; 7638 7639 // Likewise for the move assignment operator. 7640 if (ClassDecl->isDynamicClass() || 7641 ClassDecl->needsOverloadResolutionForMoveAssignment() || 7642 ClassDecl->hasInheritedAssignment()) 7643 DeclareImplicitMoveAssignment(ClassDecl); 7644 } 7645 7646 if (ClassDecl->needsImplicitDestructor()) { 7647 ++ASTContext::NumImplicitDestructors; 7648 7649 // If we have a dynamic class, then the destructor may be virtual, so we 7650 // have to declare the destructor immediately. This ensures that, e.g., it 7651 // shows up in the right place in the vtable and that we diagnose problems 7652 // with the implicit exception specification. 7653 if (ClassDecl->isDynamicClass() || 7654 ClassDecl->needsOverloadResolutionForDestructor()) 7655 DeclareImplicitDestructor(ClassDecl); 7656 } 7657 } 7658 7659 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 7660 if (!D) 7661 return 0; 7662 7663 // The order of template parameters is not important here. All names 7664 // get added to the same scope. 7665 SmallVector<TemplateParameterList *, 4> ParameterLists; 7666 7667 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 7668 D = TD->getTemplatedDecl(); 7669 7670 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 7671 ParameterLists.push_back(PSD->getTemplateParameters()); 7672 7673 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 7674 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 7675 ParameterLists.push_back(DD->getTemplateParameterList(i)); 7676 7677 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7678 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 7679 ParameterLists.push_back(FTD->getTemplateParameters()); 7680 } 7681 } 7682 7683 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 7684 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 7685 ParameterLists.push_back(TD->getTemplateParameterList(i)); 7686 7687 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 7688 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 7689 ParameterLists.push_back(CTD->getTemplateParameters()); 7690 } 7691 } 7692 7693 unsigned Count = 0; 7694 for (TemplateParameterList *Params : ParameterLists) { 7695 if (Params->size() > 0) 7696 // Ignore explicit specializations; they don't contribute to the template 7697 // depth. 7698 ++Count; 7699 for (NamedDecl *Param : *Params) { 7700 if (Param->getDeclName()) { 7701 S->AddDecl(Param); 7702 IdResolver.AddDecl(Param); 7703 } 7704 } 7705 } 7706 7707 return Count; 7708 } 7709 7710 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7711 if (!RecordD) return; 7712 AdjustDeclIfTemplate(RecordD); 7713 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 7714 PushDeclContext(S, Record); 7715 } 7716 7717 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7718 if (!RecordD) return; 7719 PopDeclContext(); 7720 } 7721 7722 /// This is used to implement the constant expression evaluation part of the 7723 /// attribute enable_if extension. There is nothing in standard C++ which would 7724 /// require reentering parameters. 7725 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 7726 if (!Param) 7727 return; 7728 7729 S->AddDecl(Param); 7730 if (Param->getDeclName()) 7731 IdResolver.AddDecl(Param); 7732 } 7733 7734 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 7735 /// parsing a top-level (non-nested) C++ class, and we are now 7736 /// parsing those parts of the given Method declaration that could 7737 /// not be parsed earlier (C++ [class.mem]p2), such as default 7738 /// arguments. This action should enter the scope of the given 7739 /// Method declaration as if we had just parsed the qualified method 7740 /// name. However, it should not bring the parameters into scope; 7741 /// that will be performed by ActOnDelayedCXXMethodParameter. 7742 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7743 } 7744 7745 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 7746 /// C++ method declaration. We're (re-)introducing the given 7747 /// function parameter into scope for use in parsing later parts of 7748 /// the method declaration. For example, we could see an 7749 /// ActOnParamDefaultArgument event for this parameter. 7750 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 7751 if (!ParamD) 7752 return; 7753 7754 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 7755 7756 // If this parameter has an unparsed default argument, clear it out 7757 // to make way for the parsed default argument. 7758 if (Param->hasUnparsedDefaultArg()) 7759 Param->setDefaultArg(nullptr); 7760 7761 S->AddDecl(Param); 7762 if (Param->getDeclName()) 7763 IdResolver.AddDecl(Param); 7764 } 7765 7766 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 7767 /// processing the delayed method declaration for Method. The method 7768 /// declaration is now considered finished. There may be a separate 7769 /// ActOnStartOfFunctionDef action later (not necessarily 7770 /// immediately!) for this method, if it was also defined inside the 7771 /// class body. 7772 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7773 if (!MethodD) 7774 return; 7775 7776 AdjustDeclIfTemplate(MethodD); 7777 7778 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 7779 7780 // Now that we have our default arguments, check the constructor 7781 // again. It could produce additional diagnostics or affect whether 7782 // the class has implicitly-declared destructors, among other 7783 // things. 7784 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 7785 CheckConstructor(Constructor); 7786 7787 // Check the default arguments, which we may have added. 7788 if (!Method->isInvalidDecl()) 7789 CheckCXXDefaultArguments(Method); 7790 } 7791 7792 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 7793 /// the well-formedness of the constructor declarator @p D with type @p 7794 /// R. If there are any errors in the declarator, this routine will 7795 /// emit diagnostics and set the invalid bit to true. In any case, the type 7796 /// will be updated to reflect a well-formed type for the constructor and 7797 /// returned. 7798 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 7799 StorageClass &SC) { 7800 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7801 7802 // C++ [class.ctor]p3: 7803 // A constructor shall not be virtual (10.3) or static (9.4). A 7804 // constructor can be invoked for a const, volatile or const 7805 // volatile object. A constructor shall not be declared const, 7806 // volatile, or const volatile (9.3.2). 7807 if (isVirtual) { 7808 if (!D.isInvalidType()) 7809 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7810 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 7811 << SourceRange(D.getIdentifierLoc()); 7812 D.setInvalidType(); 7813 } 7814 if (SC == SC_Static) { 7815 if (!D.isInvalidType()) 7816 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7817 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7818 << SourceRange(D.getIdentifierLoc()); 7819 D.setInvalidType(); 7820 SC = SC_None; 7821 } 7822 7823 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7824 diagnoseIgnoredQualifiers( 7825 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 7826 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 7827 D.getDeclSpec().getRestrictSpecLoc(), 7828 D.getDeclSpec().getAtomicSpecLoc()); 7829 D.setInvalidType(); 7830 } 7831 7832 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7833 if (FTI.TypeQuals != 0) { 7834 if (FTI.TypeQuals & Qualifiers::Const) 7835 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7836 << "const" << SourceRange(D.getIdentifierLoc()); 7837 if (FTI.TypeQuals & Qualifiers::Volatile) 7838 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7839 << "volatile" << SourceRange(D.getIdentifierLoc()); 7840 if (FTI.TypeQuals & Qualifiers::Restrict) 7841 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7842 << "restrict" << SourceRange(D.getIdentifierLoc()); 7843 D.setInvalidType(); 7844 } 7845 7846 // C++0x [class.ctor]p4: 7847 // A constructor shall not be declared with a ref-qualifier. 7848 if (FTI.hasRefQualifier()) { 7849 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 7850 << FTI.RefQualifierIsLValueRef 7851 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7852 D.setInvalidType(); 7853 } 7854 7855 // Rebuild the function type "R" without any type qualifiers (in 7856 // case any of the errors above fired) and with "void" as the 7857 // return type, since constructors don't have return types. 7858 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7859 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 7860 return R; 7861 7862 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 7863 EPI.TypeQuals = 0; 7864 EPI.RefQualifier = RQ_None; 7865 7866 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 7867 } 7868 7869 /// CheckConstructor - Checks a fully-formed constructor for 7870 /// well-formedness, issuing any diagnostics required. Returns true if 7871 /// the constructor declarator is invalid. 7872 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 7873 CXXRecordDecl *ClassDecl 7874 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 7875 if (!ClassDecl) 7876 return Constructor->setInvalidDecl(); 7877 7878 // C++ [class.copy]p3: 7879 // A declaration of a constructor for a class X is ill-formed if 7880 // its first parameter is of type (optionally cv-qualified) X and 7881 // either there are no other parameters or else all other 7882 // parameters have default arguments. 7883 if (!Constructor->isInvalidDecl() && 7884 ((Constructor->getNumParams() == 1) || 7885 (Constructor->getNumParams() > 1 && 7886 Constructor->getParamDecl(1)->hasDefaultArg())) && 7887 Constructor->getTemplateSpecializationKind() 7888 != TSK_ImplicitInstantiation) { 7889 QualType ParamType = Constructor->getParamDecl(0)->getType(); 7890 QualType ClassTy = Context.getTagDeclType(ClassDecl); 7891 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 7892 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 7893 const char *ConstRef 7894 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 7895 : " const &"; 7896 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 7897 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 7898 7899 // FIXME: Rather that making the constructor invalid, we should endeavor 7900 // to fix the type. 7901 Constructor->setInvalidDecl(); 7902 } 7903 } 7904 } 7905 7906 /// CheckDestructor - Checks a fully-formed destructor definition for 7907 /// well-formedness, issuing any diagnostics required. Returns true 7908 /// on error. 7909 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 7910 CXXRecordDecl *RD = Destructor->getParent(); 7911 7912 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 7913 SourceLocation Loc; 7914 7915 if (!Destructor->isImplicit()) 7916 Loc = Destructor->getLocation(); 7917 else 7918 Loc = RD->getLocation(); 7919 7920 // If we have a virtual destructor, look up the deallocation function 7921 if (FunctionDecl *OperatorDelete = 7922 FindDeallocationFunctionForDestructor(Loc, RD)) { 7923 Expr *ThisArg = nullptr; 7924 7925 // If the notional 'delete this' expression requires a non-trivial 7926 // conversion from 'this' to the type of a destroying operator delete's 7927 // first parameter, perform that conversion now. 7928 if (OperatorDelete->isDestroyingOperatorDelete()) { 7929 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 7930 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 7931 // C++ [class.dtor]p13: 7932 // ... as if for the expression 'delete this' appearing in a 7933 // non-virtual destructor of the destructor's class. 7934 ContextRAII SwitchContext(*this, Destructor); 7935 ExprResult This = 7936 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 7937 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 7938 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 7939 if (This.isInvalid()) { 7940 // FIXME: Register this as a context note so that it comes out 7941 // in the right order. 7942 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 7943 return true; 7944 } 7945 ThisArg = This.get(); 7946 } 7947 } 7948 7949 MarkFunctionReferenced(Loc, OperatorDelete); 7950 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 7951 } 7952 } 7953 7954 return false; 7955 } 7956 7957 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 7958 /// the well-formednes of the destructor declarator @p D with type @p 7959 /// R. If there are any errors in the declarator, this routine will 7960 /// emit diagnostics and set the declarator to invalid. Even if this happens, 7961 /// will be updated to reflect a well-formed type for the destructor and 7962 /// returned. 7963 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 7964 StorageClass& SC) { 7965 // C++ [class.dtor]p1: 7966 // [...] A typedef-name that names a class is a class-name 7967 // (7.1.3); however, a typedef-name that names a class shall not 7968 // be used as the identifier in the declarator for a destructor 7969 // declaration. 7970 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 7971 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 7972 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7973 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 7974 else if (const TemplateSpecializationType *TST = 7975 DeclaratorType->getAs<TemplateSpecializationType>()) 7976 if (TST->isTypeAlias()) 7977 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7978 << DeclaratorType << 1; 7979 7980 // C++ [class.dtor]p2: 7981 // A destructor is used to destroy objects of its class type. A 7982 // destructor takes no parameters, and no return type can be 7983 // specified for it (not even void). The address of a destructor 7984 // shall not be taken. A destructor shall not be static. A 7985 // destructor can be invoked for a const, volatile or const 7986 // volatile object. A destructor shall not be declared const, 7987 // volatile or const volatile (9.3.2). 7988 if (SC == SC_Static) { 7989 if (!D.isInvalidType()) 7990 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 7991 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7992 << SourceRange(D.getIdentifierLoc()) 7993 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7994 7995 SC = SC_None; 7996 } 7997 if (!D.isInvalidType()) { 7998 // Destructors don't have return types, but the parser will 7999 // happily parse something like: 8000 // 8001 // class X { 8002 // float ~X(); 8003 // }; 8004 // 8005 // The return type will be eliminated later. 8006 if (D.getDeclSpec().hasTypeSpecifier()) 8007 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 8008 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8009 << SourceRange(D.getIdentifierLoc()); 8010 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8011 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 8012 SourceLocation(), 8013 D.getDeclSpec().getConstSpecLoc(), 8014 D.getDeclSpec().getVolatileSpecLoc(), 8015 D.getDeclSpec().getRestrictSpecLoc(), 8016 D.getDeclSpec().getAtomicSpecLoc()); 8017 D.setInvalidType(); 8018 } 8019 } 8020 8021 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8022 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 8023 if (FTI.TypeQuals & Qualifiers::Const) 8024 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8025 << "const" << SourceRange(D.getIdentifierLoc()); 8026 if (FTI.TypeQuals & Qualifiers::Volatile) 8027 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8028 << "volatile" << SourceRange(D.getIdentifierLoc()); 8029 if (FTI.TypeQuals & Qualifiers::Restrict) 8030 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 8031 << "restrict" << SourceRange(D.getIdentifierLoc()); 8032 D.setInvalidType(); 8033 } 8034 8035 // C++0x [class.dtor]p2: 8036 // A destructor shall not be declared with a ref-qualifier. 8037 if (FTI.hasRefQualifier()) { 8038 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 8039 << FTI.RefQualifierIsLValueRef 8040 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8041 D.setInvalidType(); 8042 } 8043 8044 // Make sure we don't have any parameters. 8045 if (FTIHasNonVoidParameters(FTI)) { 8046 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 8047 8048 // Delete the parameters. 8049 FTI.freeParams(); 8050 D.setInvalidType(); 8051 } 8052 8053 // Make sure the destructor isn't variadic. 8054 if (FTI.isVariadic) { 8055 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8056 D.setInvalidType(); 8057 } 8058 8059 // Rebuild the function type "R" without any type qualifiers or 8060 // parameters (in case any of the errors above fired) and with 8061 // "void" as the return type, since destructors don't have return 8062 // types. 8063 if (!D.isInvalidType()) 8064 return R; 8065 8066 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8067 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8068 EPI.Variadic = false; 8069 EPI.TypeQuals = 0; 8070 EPI.RefQualifier = RQ_None; 8071 return Context.getFunctionType(Context.VoidTy, None, EPI); 8072 } 8073 8074 static void extendLeft(SourceRange &R, SourceRange Before) { 8075 if (Before.isInvalid()) 8076 return; 8077 R.setBegin(Before.getBegin()); 8078 if (R.getEnd().isInvalid()) 8079 R.setEnd(Before.getEnd()); 8080 } 8081 8082 static void extendRight(SourceRange &R, SourceRange After) { 8083 if (After.isInvalid()) 8084 return; 8085 if (R.getBegin().isInvalid()) 8086 R.setBegin(After.getBegin()); 8087 R.setEnd(After.getEnd()); 8088 } 8089 8090 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8091 /// well-formednes of the conversion function declarator @p D with 8092 /// type @p R. If there are any errors in the declarator, this routine 8093 /// will emit diagnostics and return true. Otherwise, it will return 8094 /// false. Either way, the type @p R will be updated to reflect a 8095 /// well-formed type for the conversion operator. 8096 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8097 StorageClass& SC) { 8098 // C++ [class.conv.fct]p1: 8099 // Neither parameter types nor return type can be specified. The 8100 // type of a conversion function (8.3.5) is "function taking no 8101 // parameter returning conversion-type-id." 8102 if (SC == SC_Static) { 8103 if (!D.isInvalidType()) 8104 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8105 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8106 << D.getName().getSourceRange(); 8107 D.setInvalidType(); 8108 SC = SC_None; 8109 } 8110 8111 TypeSourceInfo *ConvTSI = nullptr; 8112 QualType ConvType = 8113 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8114 8115 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 8116 // Conversion functions don't have return types, but the parser will 8117 // happily parse something like: 8118 // 8119 // class X { 8120 // float operator bool(); 8121 // }; 8122 // 8123 // The return type will be changed later anyway. 8124 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8125 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8126 << SourceRange(D.getIdentifierLoc()); 8127 D.setInvalidType(); 8128 } 8129 8130 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8131 8132 // Make sure we don't have any parameters. 8133 if (Proto->getNumParams() > 0) { 8134 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8135 8136 // Delete the parameters. 8137 D.getFunctionTypeInfo().freeParams(); 8138 D.setInvalidType(); 8139 } else if (Proto->isVariadic()) { 8140 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8141 D.setInvalidType(); 8142 } 8143 8144 // Diagnose "&operator bool()" and other such nonsense. This 8145 // is actually a gcc extension which we don't support. 8146 if (Proto->getReturnType() != ConvType) { 8147 bool NeedsTypedef = false; 8148 SourceRange Before, After; 8149 8150 // Walk the chunks and extract information on them for our diagnostic. 8151 bool PastFunctionChunk = false; 8152 for (auto &Chunk : D.type_objects()) { 8153 switch (Chunk.Kind) { 8154 case DeclaratorChunk::Function: 8155 if (!PastFunctionChunk) { 8156 if (Chunk.Fun.HasTrailingReturnType) { 8157 TypeSourceInfo *TRT = nullptr; 8158 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8159 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8160 } 8161 PastFunctionChunk = true; 8162 break; 8163 } 8164 // Fall through. 8165 case DeclaratorChunk::Array: 8166 NeedsTypedef = true; 8167 extendRight(After, Chunk.getSourceRange()); 8168 break; 8169 8170 case DeclaratorChunk::Pointer: 8171 case DeclaratorChunk::BlockPointer: 8172 case DeclaratorChunk::Reference: 8173 case DeclaratorChunk::MemberPointer: 8174 case DeclaratorChunk::Pipe: 8175 extendLeft(Before, Chunk.getSourceRange()); 8176 break; 8177 8178 case DeclaratorChunk::Paren: 8179 extendLeft(Before, Chunk.Loc); 8180 extendRight(After, Chunk.EndLoc); 8181 break; 8182 } 8183 } 8184 8185 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8186 After.isValid() ? After.getBegin() : 8187 D.getIdentifierLoc(); 8188 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8189 DB << Before << After; 8190 8191 if (!NeedsTypedef) { 8192 DB << /*don't need a typedef*/0; 8193 8194 // If we can provide a correct fix-it hint, do so. 8195 if (After.isInvalid() && ConvTSI) { 8196 SourceLocation InsertLoc = 8197 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 8198 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8199 << FixItHint::CreateInsertionFromRange( 8200 InsertLoc, CharSourceRange::getTokenRange(Before)) 8201 << FixItHint::CreateRemoval(Before); 8202 } 8203 } else if (!Proto->getReturnType()->isDependentType()) { 8204 DB << /*typedef*/1 << Proto->getReturnType(); 8205 } else if (getLangOpts().CPlusPlus11) { 8206 DB << /*alias template*/2 << Proto->getReturnType(); 8207 } else { 8208 DB << /*might not be fixable*/3; 8209 } 8210 8211 // Recover by incorporating the other type chunks into the result type. 8212 // Note, this does *not* change the name of the function. This is compatible 8213 // with the GCC extension: 8214 // struct S { &operator int(); } s; 8215 // int &r = s.operator int(); // ok in GCC 8216 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8217 ConvType = Proto->getReturnType(); 8218 } 8219 8220 // C++ [class.conv.fct]p4: 8221 // The conversion-type-id shall not represent a function type nor 8222 // an array type. 8223 if (ConvType->isArrayType()) { 8224 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8225 ConvType = Context.getPointerType(ConvType); 8226 D.setInvalidType(); 8227 } else if (ConvType->isFunctionType()) { 8228 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8229 ConvType = Context.getPointerType(ConvType); 8230 D.setInvalidType(); 8231 } 8232 8233 // Rebuild the function type "R" without any parameters (in case any 8234 // of the errors above fired) and with the conversion type as the 8235 // return type. 8236 if (D.isInvalidType()) 8237 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8238 8239 // C++0x explicit conversion operators. 8240 if (D.getDeclSpec().isExplicitSpecified()) 8241 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8242 getLangOpts().CPlusPlus11 ? 8243 diag::warn_cxx98_compat_explicit_conversion_functions : 8244 diag::ext_explicit_conversion_functions) 8245 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 8246 } 8247 8248 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8249 /// the declaration of the given C++ conversion function. This routine 8250 /// is responsible for recording the conversion function in the C++ 8251 /// class, if possible. 8252 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8253 assert(Conversion && "Expected to receive a conversion function declaration"); 8254 8255 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8256 8257 // Make sure we aren't redeclaring the conversion function. 8258 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8259 8260 // C++ [class.conv.fct]p1: 8261 // [...] A conversion function is never used to convert a 8262 // (possibly cv-qualified) object to the (possibly cv-qualified) 8263 // same object type (or a reference to it), to a (possibly 8264 // cv-qualified) base class of that type (or a reference to it), 8265 // or to (possibly cv-qualified) void. 8266 // FIXME: Suppress this warning if the conversion function ends up being a 8267 // virtual function that overrides a virtual function in a base class. 8268 QualType ClassType 8269 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8270 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8271 ConvType = ConvTypeRef->getPointeeType(); 8272 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8273 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8274 /* Suppress diagnostics for instantiations. */; 8275 else if (ConvType->isRecordType()) { 8276 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8277 if (ConvType == ClassType) 8278 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8279 << ClassType; 8280 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8281 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8282 << ClassType << ConvType; 8283 } else if (ConvType->isVoidType()) { 8284 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8285 << ClassType << ConvType; 8286 } 8287 8288 if (FunctionTemplateDecl *ConversionTemplate 8289 = Conversion->getDescribedFunctionTemplate()) 8290 return ConversionTemplate; 8291 8292 return Conversion; 8293 } 8294 8295 namespace { 8296 /// Utility class to accumulate and print a diagnostic listing the invalid 8297 /// specifier(s) on a declaration. 8298 struct BadSpecifierDiagnoser { 8299 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8300 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8301 ~BadSpecifierDiagnoser() { 8302 Diagnostic << Specifiers; 8303 } 8304 8305 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8306 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8307 } 8308 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8309 return check(SpecLoc, 8310 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8311 } 8312 void check(SourceLocation SpecLoc, const char *Spec) { 8313 if (SpecLoc.isInvalid()) return; 8314 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8315 if (!Specifiers.empty()) Specifiers += " "; 8316 Specifiers += Spec; 8317 } 8318 8319 Sema &S; 8320 Sema::SemaDiagnosticBuilder Diagnostic; 8321 std::string Specifiers; 8322 }; 8323 } 8324 8325 /// Check the validity of a declarator that we parsed for a deduction-guide. 8326 /// These aren't actually declarators in the grammar, so we need to check that 8327 /// the user didn't specify any pieces that are not part of the deduction-guide 8328 /// grammar. 8329 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8330 StorageClass &SC) { 8331 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8332 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8333 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8334 8335 // C++ [temp.deduct.guide]p3: 8336 // A deduction-gide shall be declared in the same scope as the 8337 // corresponding class template. 8338 if (!CurContext->getRedeclContext()->Equals( 8339 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8340 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8341 << GuidedTemplateDecl; 8342 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8343 } 8344 8345 auto &DS = D.getMutableDeclSpec(); 8346 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8347 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8348 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8349 DS.isNoreturnSpecified() || DS.isConstexprSpecified()) { 8350 BadSpecifierDiagnoser Diagnoser( 8351 *this, D.getIdentifierLoc(), 8352 diag::err_deduction_guide_invalid_specifier); 8353 8354 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8355 DS.ClearStorageClassSpecs(); 8356 SC = SC_None; 8357 8358 // 'explicit' is permitted. 8359 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8360 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8361 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8362 DS.ClearConstexprSpec(); 8363 8364 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8365 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8366 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8367 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8368 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8369 DS.ClearTypeQualifiers(); 8370 8371 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8372 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8373 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8374 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8375 DS.ClearTypeSpecType(); 8376 } 8377 8378 if (D.isInvalidType()) 8379 return; 8380 8381 // Check the declarator is simple enough. 8382 bool FoundFunction = false; 8383 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8384 if (Chunk.Kind == DeclaratorChunk::Paren) 8385 continue; 8386 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8387 Diag(D.getDeclSpec().getLocStart(), 8388 diag::err_deduction_guide_with_complex_decl) 8389 << D.getSourceRange(); 8390 break; 8391 } 8392 if (!Chunk.Fun.hasTrailingReturnType()) { 8393 Diag(D.getName().getLocStart(), 8394 diag::err_deduction_guide_no_trailing_return_type); 8395 break; 8396 } 8397 8398 // Check that the return type is written as a specialization of 8399 // the template specified as the deduction-guide's name. 8400 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8401 TypeSourceInfo *TSI = nullptr; 8402 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8403 assert(TSI && "deduction guide has valid type but invalid return type?"); 8404 bool AcceptableReturnType = false; 8405 bool MightInstantiateToSpecialization = false; 8406 if (auto RetTST = 8407 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8408 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8409 bool TemplateMatches = 8410 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8411 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8412 AcceptableReturnType = true; 8413 else { 8414 // This could still instantiate to the right type, unless we know it 8415 // names the wrong class template. 8416 auto *TD = SpecifiedName.getAsTemplateDecl(); 8417 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8418 !TemplateMatches); 8419 } 8420 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8421 MightInstantiateToSpecialization = true; 8422 } 8423 8424 if (!AcceptableReturnType) { 8425 Diag(TSI->getTypeLoc().getLocStart(), 8426 diag::err_deduction_guide_bad_trailing_return_type) 8427 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization 8428 << TSI->getTypeLoc().getSourceRange(); 8429 } 8430 8431 // Keep going to check that we don't have any inner declarator pieces (we 8432 // could still have a function returning a pointer to a function). 8433 FoundFunction = true; 8434 } 8435 8436 if (D.isFunctionDefinition()) 8437 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8438 } 8439 8440 //===----------------------------------------------------------------------===// 8441 // Namespace Handling 8442 //===----------------------------------------------------------------------===// 8443 8444 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 8445 /// reopened. 8446 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8447 SourceLocation Loc, 8448 IdentifierInfo *II, bool *IsInline, 8449 NamespaceDecl *PrevNS) { 8450 assert(*IsInline != PrevNS->isInline()); 8451 8452 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8453 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8454 // inline namespaces, with the intention of bringing names into namespace std. 8455 // 8456 // We support this just well enough to get that case working; this is not 8457 // sufficient to support reopening namespaces as inline in general. 8458 if (*IsInline && II && II->getName().startswith("__atomic") && 8459 S.getSourceManager().isInSystemHeader(Loc)) { 8460 // Mark all prior declarations of the namespace as inline. 8461 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8462 NS = NS->getPreviousDecl()) 8463 NS->setInline(*IsInline); 8464 // Patch up the lookup table for the containing namespace. This isn't really 8465 // correct, but it's good enough for this particular case. 8466 for (auto *I : PrevNS->decls()) 8467 if (auto *ND = dyn_cast<NamedDecl>(I)) 8468 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8469 return; 8470 } 8471 8472 if (PrevNS->isInline()) 8473 // The user probably just forgot the 'inline', so suggest that it 8474 // be added back. 8475 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8476 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8477 else 8478 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8479 8480 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8481 *IsInline = PrevNS->isInline(); 8482 } 8483 8484 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8485 /// definition. 8486 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 8487 SourceLocation InlineLoc, 8488 SourceLocation NamespaceLoc, 8489 SourceLocation IdentLoc, 8490 IdentifierInfo *II, 8491 SourceLocation LBrace, 8492 AttributeList *AttrList, 8493 UsingDirectiveDecl *&UD) { 8494 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8495 // For anonymous namespace, take the location of the left brace. 8496 SourceLocation Loc = II ? IdentLoc : LBrace; 8497 bool IsInline = InlineLoc.isValid(); 8498 bool IsInvalid = false; 8499 bool IsStd = false; 8500 bool AddToKnown = false; 8501 Scope *DeclRegionScope = NamespcScope->getParent(); 8502 8503 NamespaceDecl *PrevNS = nullptr; 8504 if (II) { 8505 // C++ [namespace.def]p2: 8506 // The identifier in an original-namespace-definition shall not 8507 // have been previously defined in the declarative region in 8508 // which the original-namespace-definition appears. The 8509 // identifier in an original-namespace-definition is the name of 8510 // the namespace. Subsequently in that declarative region, it is 8511 // treated as an original-namespace-name. 8512 // 8513 // Since namespace names are unique in their scope, and we don't 8514 // look through using directives, just look for any ordinary names 8515 // as if by qualified name lookup. 8516 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 8517 ForExternalRedeclaration); 8518 LookupQualifiedName(R, CurContext->getRedeclContext()); 8519 NamedDecl *PrevDecl = 8520 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8521 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8522 8523 if (PrevNS) { 8524 // This is an extended namespace definition. 8525 if (IsInline != PrevNS->isInline()) 8526 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8527 &IsInline, PrevNS); 8528 } else if (PrevDecl) { 8529 // This is an invalid name redefinition. 8530 Diag(Loc, diag::err_redefinition_different_kind) 8531 << II; 8532 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8533 IsInvalid = true; 8534 // Continue on to push Namespc as current DeclContext and return it. 8535 } else if (II->isStr("std") && 8536 CurContext->getRedeclContext()->isTranslationUnit()) { 8537 // This is the first "real" definition of the namespace "std", so update 8538 // our cache of the "std" namespace to point at this definition. 8539 PrevNS = getStdNamespace(); 8540 IsStd = true; 8541 AddToKnown = !IsInline; 8542 } else { 8543 // We've seen this namespace for the first time. 8544 AddToKnown = !IsInline; 8545 } 8546 } else { 8547 // Anonymous namespaces. 8548 8549 // Determine whether the parent already has an anonymous namespace. 8550 DeclContext *Parent = CurContext->getRedeclContext(); 8551 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8552 PrevNS = TU->getAnonymousNamespace(); 8553 } else { 8554 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8555 PrevNS = ND->getAnonymousNamespace(); 8556 } 8557 8558 if (PrevNS && IsInline != PrevNS->isInline()) 8559 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8560 &IsInline, PrevNS); 8561 } 8562 8563 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8564 StartLoc, Loc, II, PrevNS); 8565 if (IsInvalid) 8566 Namespc->setInvalidDecl(); 8567 8568 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8569 AddPragmaAttributes(DeclRegionScope, Namespc); 8570 8571 // FIXME: Should we be merging attributes? 8572 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8573 PushNamespaceVisibilityAttr(Attr, Loc); 8574 8575 if (IsStd) 8576 StdNamespace = Namespc; 8577 if (AddToKnown) 8578 KnownNamespaces[Namespc] = false; 8579 8580 if (II) { 8581 PushOnScopeChains(Namespc, DeclRegionScope); 8582 } else { 8583 // Link the anonymous namespace into its parent. 8584 DeclContext *Parent = CurContext->getRedeclContext(); 8585 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8586 TU->setAnonymousNamespace(Namespc); 8587 } else { 8588 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8589 } 8590 8591 CurContext->addDecl(Namespc); 8592 8593 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8594 // behaves as if it were replaced by 8595 // namespace unique { /* empty body */ } 8596 // using namespace unique; 8597 // namespace unique { namespace-body } 8598 // where all occurrences of 'unique' in a translation unit are 8599 // replaced by the same identifier and this identifier differs 8600 // from all other identifiers in the entire program. 8601 8602 // We just create the namespace with an empty name and then add an 8603 // implicit using declaration, just like the standard suggests. 8604 // 8605 // CodeGen enforces the "universally unique" aspect by giving all 8606 // declarations semantically contained within an anonymous 8607 // namespace internal linkage. 8608 8609 if (!PrevNS) { 8610 UD = UsingDirectiveDecl::Create(Context, Parent, 8611 /* 'using' */ LBrace, 8612 /* 'namespace' */ SourceLocation(), 8613 /* qualifier */ NestedNameSpecifierLoc(), 8614 /* identifier */ SourceLocation(), 8615 Namespc, 8616 /* Ancestor */ Parent); 8617 UD->setImplicit(); 8618 Parent->addDecl(UD); 8619 } 8620 } 8621 8622 ActOnDocumentableDecl(Namespc); 8623 8624 // Although we could have an invalid decl (i.e. the namespace name is a 8625 // redefinition), push it as current DeclContext and try to continue parsing. 8626 // FIXME: We should be able to push Namespc here, so that the each DeclContext 8627 // for the namespace has the declarations that showed up in that particular 8628 // namespace definition. 8629 PushDeclContext(NamespcScope, Namespc); 8630 return Namespc; 8631 } 8632 8633 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 8634 /// is a namespace alias, returns the namespace it points to. 8635 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 8636 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 8637 return AD->getNamespace(); 8638 return dyn_cast_or_null<NamespaceDecl>(D); 8639 } 8640 8641 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 8642 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 8643 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 8644 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 8645 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 8646 Namespc->setRBraceLoc(RBrace); 8647 PopDeclContext(); 8648 if (Namespc->hasAttr<VisibilityAttr>()) 8649 PopPragmaVisibility(true, RBrace); 8650 } 8651 8652 CXXRecordDecl *Sema::getStdBadAlloc() const { 8653 return cast_or_null<CXXRecordDecl>( 8654 StdBadAlloc.get(Context.getExternalSource())); 8655 } 8656 8657 EnumDecl *Sema::getStdAlignValT() const { 8658 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 8659 } 8660 8661 NamespaceDecl *Sema::getStdNamespace() const { 8662 return cast_or_null<NamespaceDecl>( 8663 StdNamespace.get(Context.getExternalSource())); 8664 } 8665 8666 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 8667 if (!StdExperimentalNamespaceCache) { 8668 if (auto Std = getStdNamespace()) { 8669 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 8670 SourceLocation(), LookupNamespaceName); 8671 if (!LookupQualifiedName(Result, Std) || 8672 !(StdExperimentalNamespaceCache = 8673 Result.getAsSingle<NamespaceDecl>())) 8674 Result.suppressDiagnostics(); 8675 } 8676 } 8677 return StdExperimentalNamespaceCache; 8678 } 8679 8680 /// \brief Retrieve the special "std" namespace, which may require us to 8681 /// implicitly define the namespace. 8682 NamespaceDecl *Sema::getOrCreateStdNamespace() { 8683 if (!StdNamespace) { 8684 // The "std" namespace has not yet been defined, so build one implicitly. 8685 StdNamespace = NamespaceDecl::Create(Context, 8686 Context.getTranslationUnitDecl(), 8687 /*Inline=*/false, 8688 SourceLocation(), SourceLocation(), 8689 &PP.getIdentifierTable().get("std"), 8690 /*PrevDecl=*/nullptr); 8691 getStdNamespace()->setImplicit(true); 8692 } 8693 8694 return getStdNamespace(); 8695 } 8696 8697 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 8698 assert(getLangOpts().CPlusPlus && 8699 "Looking for std::initializer_list outside of C++."); 8700 8701 // We're looking for implicit instantiations of 8702 // template <typename E> class std::initializer_list. 8703 8704 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 8705 return false; 8706 8707 ClassTemplateDecl *Template = nullptr; 8708 const TemplateArgument *Arguments = nullptr; 8709 8710 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8711 8712 ClassTemplateSpecializationDecl *Specialization = 8713 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 8714 if (!Specialization) 8715 return false; 8716 8717 Template = Specialization->getSpecializedTemplate(); 8718 Arguments = Specialization->getTemplateArgs().data(); 8719 } else if (const TemplateSpecializationType *TST = 8720 Ty->getAs<TemplateSpecializationType>()) { 8721 Template = dyn_cast_or_null<ClassTemplateDecl>( 8722 TST->getTemplateName().getAsTemplateDecl()); 8723 Arguments = TST->getArgs(); 8724 } 8725 if (!Template) 8726 return false; 8727 8728 if (!StdInitializerList) { 8729 // Haven't recognized std::initializer_list yet, maybe this is it. 8730 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 8731 if (TemplateClass->getIdentifier() != 8732 &PP.getIdentifierTable().get("initializer_list") || 8733 !getStdNamespace()->InEnclosingNamespaceSetOf( 8734 TemplateClass->getDeclContext())) 8735 return false; 8736 // This is a template called std::initializer_list, but is it the right 8737 // template? 8738 TemplateParameterList *Params = Template->getTemplateParameters(); 8739 if (Params->getMinRequiredArguments() != 1) 8740 return false; 8741 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 8742 return false; 8743 8744 // It's the right template. 8745 StdInitializerList = Template; 8746 } 8747 8748 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 8749 return false; 8750 8751 // This is an instance of std::initializer_list. Find the argument type. 8752 if (Element) 8753 *Element = Arguments[0].getAsType(); 8754 return true; 8755 } 8756 8757 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 8758 NamespaceDecl *Std = S.getStdNamespace(); 8759 if (!Std) { 8760 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8761 return nullptr; 8762 } 8763 8764 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 8765 Loc, Sema::LookupOrdinaryName); 8766 if (!S.LookupQualifiedName(Result, Std)) { 8767 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8768 return nullptr; 8769 } 8770 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 8771 if (!Template) { 8772 Result.suppressDiagnostics(); 8773 // We found something weird. Complain about the first thing we found. 8774 NamedDecl *Found = *Result.begin(); 8775 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 8776 return nullptr; 8777 } 8778 8779 // We found some template called std::initializer_list. Now verify that it's 8780 // correct. 8781 TemplateParameterList *Params = Template->getTemplateParameters(); 8782 if (Params->getMinRequiredArguments() != 1 || 8783 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 8784 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 8785 return nullptr; 8786 } 8787 8788 return Template; 8789 } 8790 8791 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 8792 if (!StdInitializerList) { 8793 StdInitializerList = LookupStdInitializerList(*this, Loc); 8794 if (!StdInitializerList) 8795 return QualType(); 8796 } 8797 8798 TemplateArgumentListInfo Args(Loc, Loc); 8799 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 8800 Context.getTrivialTypeSourceInfo(Element, 8801 Loc))); 8802 return Context.getCanonicalType( 8803 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 8804 } 8805 8806 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 8807 // C++ [dcl.init.list]p2: 8808 // A constructor is an initializer-list constructor if its first parameter 8809 // is of type std::initializer_list<E> or reference to possibly cv-qualified 8810 // std::initializer_list<E> for some type E, and either there are no other 8811 // parameters or else all other parameters have default arguments. 8812 if (Ctor->getNumParams() < 1 || 8813 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 8814 return false; 8815 8816 QualType ArgType = Ctor->getParamDecl(0)->getType(); 8817 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 8818 ArgType = RT->getPointeeType().getUnqualifiedType(); 8819 8820 return isStdInitializerList(ArgType, nullptr); 8821 } 8822 8823 /// \brief Determine whether a using statement is in a context where it will be 8824 /// apply in all contexts. 8825 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 8826 switch (CurContext->getDeclKind()) { 8827 case Decl::TranslationUnit: 8828 return true; 8829 case Decl::LinkageSpec: 8830 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 8831 default: 8832 return false; 8833 } 8834 } 8835 8836 namespace { 8837 8838 // Callback to only accept typo corrections that are namespaces. 8839 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 8840 public: 8841 bool ValidateCandidate(const TypoCorrection &candidate) override { 8842 if (NamedDecl *ND = candidate.getCorrectionDecl()) 8843 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 8844 return false; 8845 } 8846 }; 8847 8848 } 8849 8850 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 8851 CXXScopeSpec &SS, 8852 SourceLocation IdentLoc, 8853 IdentifierInfo *Ident) { 8854 R.clear(); 8855 if (TypoCorrection Corrected = 8856 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 8857 llvm::make_unique<NamespaceValidatorCCC>(), 8858 Sema::CTK_ErrorRecovery)) { 8859 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 8860 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 8861 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 8862 Ident->getName().equals(CorrectedStr); 8863 S.diagnoseTypo(Corrected, 8864 S.PDiag(diag::err_using_directive_member_suggest) 8865 << Ident << DC << DroppedSpecifier << SS.getRange(), 8866 S.PDiag(diag::note_namespace_defined_here)); 8867 } else { 8868 S.diagnoseTypo(Corrected, 8869 S.PDiag(diag::err_using_directive_suggest) << Ident, 8870 S.PDiag(diag::note_namespace_defined_here)); 8871 } 8872 R.addDecl(Corrected.getFoundDecl()); 8873 return true; 8874 } 8875 return false; 8876 } 8877 8878 Decl *Sema::ActOnUsingDirective(Scope *S, 8879 SourceLocation UsingLoc, 8880 SourceLocation NamespcLoc, 8881 CXXScopeSpec &SS, 8882 SourceLocation IdentLoc, 8883 IdentifierInfo *NamespcName, 8884 AttributeList *AttrList) { 8885 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8886 assert(NamespcName && "Invalid NamespcName."); 8887 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 8888 8889 // This can only happen along a recovery path. 8890 while (S->isTemplateParamScope()) 8891 S = S->getParent(); 8892 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8893 8894 UsingDirectiveDecl *UDir = nullptr; 8895 NestedNameSpecifier *Qualifier = nullptr; 8896 if (SS.isSet()) 8897 Qualifier = SS.getScopeRep(); 8898 8899 // Lookup namespace name. 8900 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 8901 LookupParsedName(R, S, &SS); 8902 if (R.isAmbiguous()) 8903 return nullptr; 8904 8905 if (R.empty()) { 8906 R.clear(); 8907 // Allow "using namespace std;" or "using namespace ::std;" even if 8908 // "std" hasn't been defined yet, for GCC compatibility. 8909 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 8910 NamespcName->isStr("std")) { 8911 Diag(IdentLoc, diag::ext_using_undefined_std); 8912 R.addDecl(getOrCreateStdNamespace()); 8913 R.resolveKind(); 8914 } 8915 // Otherwise, attempt typo correction. 8916 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 8917 } 8918 8919 if (!R.empty()) { 8920 NamedDecl *Named = R.getRepresentativeDecl(); 8921 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 8922 assert(NS && "expected namespace decl"); 8923 8924 // The use of a nested name specifier may trigger deprecation warnings. 8925 DiagnoseUseOfDecl(Named, IdentLoc); 8926 8927 // C++ [namespace.udir]p1: 8928 // A using-directive specifies that the names in the nominated 8929 // namespace can be used in the scope in which the 8930 // using-directive appears after the using-directive. During 8931 // unqualified name lookup (3.4.1), the names appear as if they 8932 // were declared in the nearest enclosing namespace which 8933 // contains both the using-directive and the nominated 8934 // namespace. [Note: in this context, "contains" means "contains 8935 // directly or indirectly". ] 8936 8937 // Find enclosing context containing both using-directive and 8938 // nominated namespace. 8939 DeclContext *CommonAncestor = cast<DeclContext>(NS); 8940 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 8941 CommonAncestor = CommonAncestor->getParent(); 8942 8943 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 8944 SS.getWithLocInContext(Context), 8945 IdentLoc, Named, CommonAncestor); 8946 8947 if (IsUsingDirectiveInToplevelContext(CurContext) && 8948 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 8949 Diag(IdentLoc, diag::warn_using_directive_in_header); 8950 } 8951 8952 PushUsingDirective(S, UDir); 8953 } else { 8954 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8955 } 8956 8957 if (UDir) 8958 ProcessDeclAttributeList(S, UDir, AttrList); 8959 8960 return UDir; 8961 } 8962 8963 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 8964 // If the scope has an associated entity and the using directive is at 8965 // namespace or translation unit scope, add the UsingDirectiveDecl into 8966 // its lookup structure so qualified name lookup can find it. 8967 DeclContext *Ctx = S->getEntity(); 8968 if (Ctx && !Ctx->isFunctionOrMethod()) 8969 Ctx->addDecl(UDir); 8970 else 8971 // Otherwise, it is at block scope. The using-directives will affect lookup 8972 // only to the end of the scope. 8973 S->PushUsingDirective(UDir); 8974 } 8975 8976 8977 Decl *Sema::ActOnUsingDeclaration(Scope *S, 8978 AccessSpecifier AS, 8979 SourceLocation UsingLoc, 8980 SourceLocation TypenameLoc, 8981 CXXScopeSpec &SS, 8982 UnqualifiedId &Name, 8983 SourceLocation EllipsisLoc, 8984 AttributeList *AttrList) { 8985 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8986 8987 if (SS.isEmpty()) { 8988 Diag(Name.getLocStart(), diag::err_using_requires_qualname); 8989 return nullptr; 8990 } 8991 8992 switch (Name.getKind()) { 8993 case UnqualifiedId::IK_ImplicitSelfParam: 8994 case UnqualifiedId::IK_Identifier: 8995 case UnqualifiedId::IK_OperatorFunctionId: 8996 case UnqualifiedId::IK_LiteralOperatorId: 8997 case UnqualifiedId::IK_ConversionFunctionId: 8998 break; 8999 9000 case UnqualifiedId::IK_ConstructorName: 9001 case UnqualifiedId::IK_ConstructorTemplateId: 9002 // C++11 inheriting constructors. 9003 Diag(Name.getLocStart(), 9004 getLangOpts().CPlusPlus11 ? 9005 diag::warn_cxx98_compat_using_decl_constructor : 9006 diag::err_using_decl_constructor) 9007 << SS.getRange(); 9008 9009 if (getLangOpts().CPlusPlus11) break; 9010 9011 return nullptr; 9012 9013 case UnqualifiedId::IK_DestructorName: 9014 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 9015 << SS.getRange(); 9016 return nullptr; 9017 9018 case UnqualifiedId::IK_TemplateId: 9019 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 9020 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 9021 return nullptr; 9022 9023 case UnqualifiedId::IK_DeductionGuideName: 9024 llvm_unreachable("cannot parse qualified deduction guide name"); 9025 } 9026 9027 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 9028 DeclarationName TargetName = TargetNameInfo.getName(); 9029 if (!TargetName) 9030 return nullptr; 9031 9032 // Warn about access declarations. 9033 if (UsingLoc.isInvalid()) { 9034 Diag(Name.getLocStart(), 9035 getLangOpts().CPlusPlus11 ? diag::err_access_decl 9036 : diag::warn_access_decl_deprecated) 9037 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 9038 } 9039 9040 if (EllipsisLoc.isInvalid()) { 9041 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 9042 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 9043 return nullptr; 9044 } else { 9045 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 9046 !TargetNameInfo.containsUnexpandedParameterPack()) { 9047 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 9048 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 9049 EllipsisLoc = SourceLocation(); 9050 } 9051 } 9052 9053 NamedDecl *UD = 9054 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9055 SS, TargetNameInfo, EllipsisLoc, AttrList, 9056 /*IsInstantiation*/false); 9057 if (UD) 9058 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9059 9060 return UD; 9061 } 9062 9063 /// \brief Determine whether a using declaration considers the given 9064 /// declarations as "equivalent", e.g., if they are redeclarations of 9065 /// the same entity or are both typedefs of the same type. 9066 static bool 9067 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9068 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9069 return true; 9070 9071 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9072 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9073 return Context.hasSameType(TD1->getUnderlyingType(), 9074 TD2->getUnderlyingType()); 9075 9076 return false; 9077 } 9078 9079 9080 /// Determines whether to create a using shadow decl for a particular 9081 /// decl, given the set of decls existing prior to this using lookup. 9082 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9083 const LookupResult &Previous, 9084 UsingShadowDecl *&PrevShadow) { 9085 // Diagnose finding a decl which is not from a base class of the 9086 // current class. We do this now because there are cases where this 9087 // function will silently decide not to build a shadow decl, which 9088 // will pre-empt further diagnostics. 9089 // 9090 // We don't need to do this in C++11 because we do the check once on 9091 // the qualifier. 9092 // 9093 // FIXME: diagnose the following if we care enough: 9094 // struct A { int foo; }; 9095 // struct B : A { using A::foo; }; 9096 // template <class T> struct C : A {}; 9097 // template <class T> struct D : C<T> { using B::foo; } // <--- 9098 // This is invalid (during instantiation) in C++03 because B::foo 9099 // resolves to the using decl in B, which is not a base class of D<T>. 9100 // We can't diagnose it immediately because C<T> is an unknown 9101 // specialization. The UsingShadowDecl in D<T> then points directly 9102 // to A::foo, which will look well-formed when we instantiate. 9103 // The right solution is to not collapse the shadow-decl chain. 9104 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9105 DeclContext *OrigDC = Orig->getDeclContext(); 9106 9107 // Handle enums and anonymous structs. 9108 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9109 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9110 while (OrigRec->isAnonymousStructOrUnion()) 9111 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9112 9113 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9114 if (OrigDC == CurContext) { 9115 Diag(Using->getLocation(), 9116 diag::err_using_decl_nested_name_specifier_is_current_class) 9117 << Using->getQualifierLoc().getSourceRange(); 9118 Diag(Orig->getLocation(), diag::note_using_decl_target); 9119 Using->setInvalidDecl(); 9120 return true; 9121 } 9122 9123 Diag(Using->getQualifierLoc().getBeginLoc(), 9124 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9125 << Using->getQualifier() 9126 << cast<CXXRecordDecl>(CurContext) 9127 << Using->getQualifierLoc().getSourceRange(); 9128 Diag(Orig->getLocation(), diag::note_using_decl_target); 9129 Using->setInvalidDecl(); 9130 return true; 9131 } 9132 } 9133 9134 if (Previous.empty()) return false; 9135 9136 NamedDecl *Target = Orig; 9137 if (isa<UsingShadowDecl>(Target)) 9138 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9139 9140 // If the target happens to be one of the previous declarations, we 9141 // don't have a conflict. 9142 // 9143 // FIXME: but we might be increasing its access, in which case we 9144 // should redeclare it. 9145 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9146 bool FoundEquivalentDecl = false; 9147 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9148 I != E; ++I) { 9149 NamedDecl *D = (*I)->getUnderlyingDecl(); 9150 // We can have UsingDecls in our Previous results because we use the same 9151 // LookupResult for checking whether the UsingDecl itself is a valid 9152 // redeclaration. 9153 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9154 continue; 9155 9156 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9157 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9158 PrevShadow = Shadow; 9159 FoundEquivalentDecl = true; 9160 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9161 // We don't conflict with an existing using shadow decl of an equivalent 9162 // declaration, but we're not a redeclaration of it. 9163 FoundEquivalentDecl = true; 9164 } 9165 9166 if (isVisible(D)) 9167 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9168 } 9169 9170 if (FoundEquivalentDecl) 9171 return false; 9172 9173 if (FunctionDecl *FD = Target->getAsFunction()) { 9174 NamedDecl *OldDecl = nullptr; 9175 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9176 /*IsForUsingDecl*/ true)) { 9177 case Ovl_Overload: 9178 return false; 9179 9180 case Ovl_NonFunction: 9181 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9182 break; 9183 9184 // We found a decl with the exact signature. 9185 case Ovl_Match: 9186 // If we're in a record, we want to hide the target, so we 9187 // return true (without a diagnostic) to tell the caller not to 9188 // build a shadow decl. 9189 if (CurContext->isRecord()) 9190 return true; 9191 9192 // If we're not in a record, this is an error. 9193 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9194 break; 9195 } 9196 9197 Diag(Target->getLocation(), diag::note_using_decl_target); 9198 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9199 Using->setInvalidDecl(); 9200 return true; 9201 } 9202 9203 // Target is not a function. 9204 9205 if (isa<TagDecl>(Target)) { 9206 // No conflict between a tag and a non-tag. 9207 if (!Tag) return false; 9208 9209 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9210 Diag(Target->getLocation(), diag::note_using_decl_target); 9211 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9212 Using->setInvalidDecl(); 9213 return true; 9214 } 9215 9216 // No conflict between a tag and a non-tag. 9217 if (!NonTag) return false; 9218 9219 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9220 Diag(Target->getLocation(), diag::note_using_decl_target); 9221 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9222 Using->setInvalidDecl(); 9223 return true; 9224 } 9225 9226 /// Determine whether a direct base class is a virtual base class. 9227 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9228 if (!Derived->getNumVBases()) 9229 return false; 9230 for (auto &B : Derived->bases()) 9231 if (B.getType()->getAsCXXRecordDecl() == Base) 9232 return B.isVirtual(); 9233 llvm_unreachable("not a direct base class"); 9234 } 9235 9236 /// Builds a shadow declaration corresponding to a 'using' declaration. 9237 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9238 UsingDecl *UD, 9239 NamedDecl *Orig, 9240 UsingShadowDecl *PrevDecl) { 9241 // If we resolved to another shadow declaration, just coalesce them. 9242 NamedDecl *Target = Orig; 9243 if (isa<UsingShadowDecl>(Target)) { 9244 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9245 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9246 } 9247 9248 NamedDecl *NonTemplateTarget = Target; 9249 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9250 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9251 9252 UsingShadowDecl *Shadow; 9253 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 9254 bool IsVirtualBase = 9255 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9256 UD->getQualifier()->getAsRecordDecl()); 9257 Shadow = ConstructorUsingShadowDecl::Create( 9258 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9259 } else { 9260 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9261 Target); 9262 } 9263 UD->addShadowDecl(Shadow); 9264 9265 Shadow->setAccess(UD->getAccess()); 9266 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9267 Shadow->setInvalidDecl(); 9268 9269 Shadow->setPreviousDecl(PrevDecl); 9270 9271 if (S) 9272 PushOnScopeChains(Shadow, S); 9273 else 9274 CurContext->addDecl(Shadow); 9275 9276 9277 return Shadow; 9278 } 9279 9280 /// Hides a using shadow declaration. This is required by the current 9281 /// using-decl implementation when a resolvable using declaration in a 9282 /// class is followed by a declaration which would hide or override 9283 /// one or more of the using decl's targets; for example: 9284 /// 9285 /// struct Base { void foo(int); }; 9286 /// struct Derived : Base { 9287 /// using Base::foo; 9288 /// void foo(int); 9289 /// }; 9290 /// 9291 /// The governing language is C++03 [namespace.udecl]p12: 9292 /// 9293 /// When a using-declaration brings names from a base class into a 9294 /// derived class scope, member functions in the derived class 9295 /// override and/or hide member functions with the same name and 9296 /// parameter types in a base class (rather than conflicting). 9297 /// 9298 /// There are two ways to implement this: 9299 /// (1) optimistically create shadow decls when they're not hidden 9300 /// by existing declarations, or 9301 /// (2) don't create any shadow decls (or at least don't make them 9302 /// visible) until we've fully parsed/instantiated the class. 9303 /// The problem with (1) is that we might have to retroactively remove 9304 /// a shadow decl, which requires several O(n) operations because the 9305 /// decl structures are (very reasonably) not designed for removal. 9306 /// (2) avoids this but is very fiddly and phase-dependent. 9307 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9308 if (Shadow->getDeclName().getNameKind() == 9309 DeclarationName::CXXConversionFunctionName) 9310 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9311 9312 // Remove it from the DeclContext... 9313 Shadow->getDeclContext()->removeDecl(Shadow); 9314 9315 // ...and the scope, if applicable... 9316 if (S) { 9317 S->RemoveDecl(Shadow); 9318 IdResolver.RemoveDecl(Shadow); 9319 } 9320 9321 // ...and the using decl. 9322 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9323 9324 // TODO: complain somehow if Shadow was used. It shouldn't 9325 // be possible for this to happen, because...? 9326 } 9327 9328 /// Find the base specifier for a base class with the given type. 9329 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 9330 QualType DesiredBase, 9331 bool &AnyDependentBases) { 9332 // Check whether the named type is a direct base class. 9333 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 9334 for (auto &Base : Derived->bases()) { 9335 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 9336 if (CanonicalDesiredBase == BaseType) 9337 return &Base; 9338 if (BaseType->isDependentType()) 9339 AnyDependentBases = true; 9340 } 9341 return nullptr; 9342 } 9343 9344 namespace { 9345 class UsingValidatorCCC : public CorrectionCandidateCallback { 9346 public: 9347 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 9348 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 9349 : HasTypenameKeyword(HasTypenameKeyword), 9350 IsInstantiation(IsInstantiation), OldNNS(NNS), 9351 RequireMemberOf(RequireMemberOf) {} 9352 9353 bool ValidateCandidate(const TypoCorrection &Candidate) override { 9354 NamedDecl *ND = Candidate.getCorrectionDecl(); 9355 9356 // Keywords are not valid here. 9357 if (!ND || isa<NamespaceDecl>(ND)) 9358 return false; 9359 9360 // Completely unqualified names are invalid for a 'using' declaration. 9361 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 9362 return false; 9363 9364 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 9365 // reject. 9366 9367 if (RequireMemberOf) { 9368 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9369 if (FoundRecord && FoundRecord->isInjectedClassName()) { 9370 // No-one ever wants a using-declaration to name an injected-class-name 9371 // of a base class, unless they're declaring an inheriting constructor. 9372 ASTContext &Ctx = ND->getASTContext(); 9373 if (!Ctx.getLangOpts().CPlusPlus11) 9374 return false; 9375 QualType FoundType = Ctx.getRecordType(FoundRecord); 9376 9377 // Check that the injected-class-name is named as a member of its own 9378 // type; we don't want to suggest 'using Derived::Base;', since that 9379 // means something else. 9380 NestedNameSpecifier *Specifier = 9381 Candidate.WillReplaceSpecifier() 9382 ? Candidate.getCorrectionSpecifier() 9383 : OldNNS; 9384 if (!Specifier->getAsType() || 9385 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 9386 return false; 9387 9388 // Check that this inheriting constructor declaration actually names a 9389 // direct base class of the current class. 9390 bool AnyDependentBases = false; 9391 if (!findDirectBaseWithType(RequireMemberOf, 9392 Ctx.getRecordType(FoundRecord), 9393 AnyDependentBases) && 9394 !AnyDependentBases) 9395 return false; 9396 } else { 9397 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 9398 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 9399 return false; 9400 9401 // FIXME: Check that the base class member is accessible? 9402 } 9403 } else { 9404 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9405 if (FoundRecord && FoundRecord->isInjectedClassName()) 9406 return false; 9407 } 9408 9409 if (isa<TypeDecl>(ND)) 9410 return HasTypenameKeyword || !IsInstantiation; 9411 9412 return !HasTypenameKeyword; 9413 } 9414 9415 private: 9416 bool HasTypenameKeyword; 9417 bool IsInstantiation; 9418 NestedNameSpecifier *OldNNS; 9419 CXXRecordDecl *RequireMemberOf; 9420 }; 9421 } // end anonymous namespace 9422 9423 /// Builds a using declaration. 9424 /// 9425 /// \param IsInstantiation - Whether this call arises from an 9426 /// instantiation of an unresolved using declaration. We treat 9427 /// the lookup differently for these declarations. 9428 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 9429 SourceLocation UsingLoc, 9430 bool HasTypenameKeyword, 9431 SourceLocation TypenameLoc, 9432 CXXScopeSpec &SS, 9433 DeclarationNameInfo NameInfo, 9434 SourceLocation EllipsisLoc, 9435 AttributeList *AttrList, 9436 bool IsInstantiation) { 9437 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9438 SourceLocation IdentLoc = NameInfo.getLoc(); 9439 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9440 9441 // FIXME: We ignore attributes for now. 9442 9443 // For an inheriting constructor declaration, the name of the using 9444 // declaration is the name of a constructor in this class, not in the 9445 // base class. 9446 DeclarationNameInfo UsingName = NameInfo; 9447 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9448 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9449 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9450 Context.getCanonicalType(Context.getRecordType(RD)))); 9451 9452 // Do the redeclaration lookup in the current scope. 9453 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9454 ForVisibleRedeclaration); 9455 Previous.setHideTags(false); 9456 if (S) { 9457 LookupName(Previous, S); 9458 9459 // It is really dumb that we have to do this. 9460 LookupResult::Filter F = Previous.makeFilter(); 9461 while (F.hasNext()) { 9462 NamedDecl *D = F.next(); 9463 if (!isDeclInScope(D, CurContext, S)) 9464 F.erase(); 9465 // If we found a local extern declaration that's not ordinarily visible, 9466 // and this declaration is being added to a non-block scope, ignore it. 9467 // We're only checking for scope conflicts here, not also for violations 9468 // of the linkage rules. 9469 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9470 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9471 F.erase(); 9472 } 9473 F.done(); 9474 } else { 9475 assert(IsInstantiation && "no scope in non-instantiation"); 9476 if (CurContext->isRecord()) 9477 LookupQualifiedName(Previous, CurContext); 9478 else { 9479 // No redeclaration check is needed here; in non-member contexts we 9480 // diagnosed all possible conflicts with other using-declarations when 9481 // building the template: 9482 // 9483 // For a dependent non-type using declaration, the only valid case is 9484 // if we instantiate to a single enumerator. We check for conflicts 9485 // between shadow declarations we introduce, and we check in the template 9486 // definition for conflicts between a non-type using declaration and any 9487 // other declaration, which together covers all cases. 9488 // 9489 // A dependent typename using declaration will never successfully 9490 // instantiate, since it will always name a class member, so we reject 9491 // that in the template definition. 9492 } 9493 } 9494 9495 // Check for invalid redeclarations. 9496 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 9497 SS, IdentLoc, Previous)) 9498 return nullptr; 9499 9500 // Check for bad qualifiers. 9501 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 9502 IdentLoc)) 9503 return nullptr; 9504 9505 DeclContext *LookupContext = computeDeclContext(SS); 9506 NamedDecl *D; 9507 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9508 if (!LookupContext || EllipsisLoc.isValid()) { 9509 if (HasTypenameKeyword) { 9510 // FIXME: not all declaration name kinds are legal here 9511 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 9512 UsingLoc, TypenameLoc, 9513 QualifierLoc, 9514 IdentLoc, NameInfo.getName(), 9515 EllipsisLoc); 9516 } else { 9517 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 9518 QualifierLoc, NameInfo, EllipsisLoc); 9519 } 9520 D->setAccess(AS); 9521 CurContext->addDecl(D); 9522 return D; 9523 } 9524 9525 auto Build = [&](bool Invalid) { 9526 UsingDecl *UD = 9527 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 9528 UsingName, HasTypenameKeyword); 9529 UD->setAccess(AS); 9530 CurContext->addDecl(UD); 9531 UD->setInvalidDecl(Invalid); 9532 return UD; 9533 }; 9534 auto BuildInvalid = [&]{ return Build(true); }; 9535 auto BuildValid = [&]{ return Build(false); }; 9536 9537 if (RequireCompleteDeclContext(SS, LookupContext)) 9538 return BuildInvalid(); 9539 9540 // Look up the target name. 9541 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9542 9543 // Unlike most lookups, we don't always want to hide tag 9544 // declarations: tag names are visible through the using declaration 9545 // even if hidden by ordinary names, *except* in a dependent context 9546 // where it's important for the sanity of two-phase lookup. 9547 if (!IsInstantiation) 9548 R.setHideTags(false); 9549 9550 // For the purposes of this lookup, we have a base object type 9551 // equal to that of the current context. 9552 if (CurContext->isRecord()) { 9553 R.setBaseObjectType( 9554 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 9555 } 9556 9557 LookupQualifiedName(R, LookupContext); 9558 9559 // Try to correct typos if possible. If constructor name lookup finds no 9560 // results, that means the named class has no explicit constructors, and we 9561 // suppressed declaring implicit ones (probably because it's dependent or 9562 // invalid). 9563 if (R.empty() && 9564 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 9565 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 9566 // it will believe that glibc provides a ::gets in cases where it does not, 9567 // and will try to pull it into namespace std with a using-declaration. 9568 // Just ignore the using-declaration in that case. 9569 auto *II = NameInfo.getName().getAsIdentifierInfo(); 9570 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 9571 CurContext->isStdNamespace() && 9572 isa<TranslationUnitDecl>(LookupContext) && 9573 getSourceManager().isInSystemHeader(UsingLoc)) 9574 return nullptr; 9575 if (TypoCorrection Corrected = CorrectTypo( 9576 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 9577 llvm::make_unique<UsingValidatorCCC>( 9578 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 9579 dyn_cast<CXXRecordDecl>(CurContext)), 9580 CTK_ErrorRecovery)) { 9581 // We reject candidates where DroppedSpecifier == true, hence the 9582 // literal '0' below. 9583 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 9584 << NameInfo.getName() << LookupContext << 0 9585 << SS.getRange()); 9586 9587 // If we picked a correction with no attached Decl we can't do anything 9588 // useful with it, bail out. 9589 NamedDecl *ND = Corrected.getCorrectionDecl(); 9590 if (!ND) 9591 return BuildInvalid(); 9592 9593 // If we corrected to an inheriting constructor, handle it as one. 9594 auto *RD = dyn_cast<CXXRecordDecl>(ND); 9595 if (RD && RD->isInjectedClassName()) { 9596 // The parent of the injected class name is the class itself. 9597 RD = cast<CXXRecordDecl>(RD->getParent()); 9598 9599 // Fix up the information we'll use to build the using declaration. 9600 if (Corrected.WillReplaceSpecifier()) { 9601 NestedNameSpecifierLocBuilder Builder; 9602 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 9603 QualifierLoc.getSourceRange()); 9604 QualifierLoc = Builder.getWithLocInContext(Context); 9605 } 9606 9607 // In this case, the name we introduce is the name of a derived class 9608 // constructor. 9609 auto *CurClass = cast<CXXRecordDecl>(CurContext); 9610 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9611 Context.getCanonicalType(Context.getRecordType(CurClass)))); 9612 UsingName.setNamedTypeInfo(nullptr); 9613 for (auto *Ctor : LookupConstructors(RD)) 9614 R.addDecl(Ctor); 9615 R.resolveKind(); 9616 } else { 9617 // FIXME: Pick up all the declarations if we found an overloaded 9618 // function. 9619 UsingName.setName(ND->getDeclName()); 9620 R.addDecl(ND); 9621 } 9622 } else { 9623 Diag(IdentLoc, diag::err_no_member) 9624 << NameInfo.getName() << LookupContext << SS.getRange(); 9625 return BuildInvalid(); 9626 } 9627 } 9628 9629 if (R.isAmbiguous()) 9630 return BuildInvalid(); 9631 9632 if (HasTypenameKeyword) { 9633 // If we asked for a typename and got a non-type decl, error out. 9634 if (!R.getAsSingle<TypeDecl>()) { 9635 Diag(IdentLoc, diag::err_using_typename_non_type); 9636 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9637 Diag((*I)->getUnderlyingDecl()->getLocation(), 9638 diag::note_using_decl_target); 9639 return BuildInvalid(); 9640 } 9641 } else { 9642 // If we asked for a non-typename and we got a type, error out, 9643 // but only if this is an instantiation of an unresolved using 9644 // decl. Otherwise just silently find the type name. 9645 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 9646 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 9647 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 9648 return BuildInvalid(); 9649 } 9650 } 9651 9652 // C++14 [namespace.udecl]p6: 9653 // A using-declaration shall not name a namespace. 9654 if (R.getAsSingle<NamespaceDecl>()) { 9655 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 9656 << SS.getRange(); 9657 return BuildInvalid(); 9658 } 9659 9660 // C++14 [namespace.udecl]p7: 9661 // A using-declaration shall not name a scoped enumerator. 9662 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 9663 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 9664 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 9665 << SS.getRange(); 9666 return BuildInvalid(); 9667 } 9668 } 9669 9670 UsingDecl *UD = BuildValid(); 9671 9672 // Some additional rules apply to inheriting constructors. 9673 if (UsingName.getName().getNameKind() == 9674 DeclarationName::CXXConstructorName) { 9675 // Suppress access diagnostics; the access check is instead performed at the 9676 // point of use for an inheriting constructor. 9677 R.suppressDiagnostics(); 9678 if (CheckInheritingConstructorUsingDecl(UD)) 9679 return UD; 9680 } 9681 9682 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9683 UsingShadowDecl *PrevDecl = nullptr; 9684 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 9685 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 9686 } 9687 9688 return UD; 9689 } 9690 9691 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 9692 ArrayRef<NamedDecl *> Expansions) { 9693 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 9694 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 9695 isa<UsingPackDecl>(InstantiatedFrom)); 9696 9697 auto *UPD = 9698 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 9699 UPD->setAccess(InstantiatedFrom->getAccess()); 9700 CurContext->addDecl(UPD); 9701 return UPD; 9702 } 9703 9704 /// Additional checks for a using declaration referring to a constructor name. 9705 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 9706 assert(!UD->hasTypename() && "expecting a constructor name"); 9707 9708 const Type *SourceType = UD->getQualifier()->getAsType(); 9709 assert(SourceType && 9710 "Using decl naming constructor doesn't have type in scope spec."); 9711 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 9712 9713 // Check whether the named type is a direct base class. 9714 bool AnyDependentBases = false; 9715 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 9716 AnyDependentBases); 9717 if (!Base && !AnyDependentBases) { 9718 Diag(UD->getUsingLoc(), 9719 diag::err_using_decl_constructor_not_in_direct_base) 9720 << UD->getNameInfo().getSourceRange() 9721 << QualType(SourceType, 0) << TargetClass; 9722 UD->setInvalidDecl(); 9723 return true; 9724 } 9725 9726 if (Base) 9727 Base->setInheritConstructors(); 9728 9729 return false; 9730 } 9731 9732 /// Checks that the given using declaration is not an invalid 9733 /// redeclaration. Note that this is checking only for the using decl 9734 /// itself, not for any ill-formedness among the UsingShadowDecls. 9735 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 9736 bool HasTypenameKeyword, 9737 const CXXScopeSpec &SS, 9738 SourceLocation NameLoc, 9739 const LookupResult &Prev) { 9740 NestedNameSpecifier *Qual = SS.getScopeRep(); 9741 9742 // C++03 [namespace.udecl]p8: 9743 // C++0x [namespace.udecl]p10: 9744 // A using-declaration is a declaration and can therefore be used 9745 // repeatedly where (and only where) multiple declarations are 9746 // allowed. 9747 // 9748 // That's in non-member contexts. 9749 if (!CurContext->getRedeclContext()->isRecord()) { 9750 // A dependent qualifier outside a class can only ever resolve to an 9751 // enumeration type. Therefore it conflicts with any other non-type 9752 // declaration in the same scope. 9753 // FIXME: How should we check for dependent type-type conflicts at block 9754 // scope? 9755 if (Qual->isDependent() && !HasTypenameKeyword) { 9756 for (auto *D : Prev) { 9757 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 9758 bool OldCouldBeEnumerator = 9759 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 9760 Diag(NameLoc, 9761 OldCouldBeEnumerator ? diag::err_redefinition 9762 : diag::err_redefinition_different_kind) 9763 << Prev.getLookupName(); 9764 Diag(D->getLocation(), diag::note_previous_definition); 9765 return true; 9766 } 9767 } 9768 } 9769 return false; 9770 } 9771 9772 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 9773 NamedDecl *D = *I; 9774 9775 bool DTypename; 9776 NestedNameSpecifier *DQual; 9777 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 9778 DTypename = UD->hasTypename(); 9779 DQual = UD->getQualifier(); 9780 } else if (UnresolvedUsingValueDecl *UD 9781 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 9782 DTypename = false; 9783 DQual = UD->getQualifier(); 9784 } else if (UnresolvedUsingTypenameDecl *UD 9785 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 9786 DTypename = true; 9787 DQual = UD->getQualifier(); 9788 } else continue; 9789 9790 // using decls differ if one says 'typename' and the other doesn't. 9791 // FIXME: non-dependent using decls? 9792 if (HasTypenameKeyword != DTypename) continue; 9793 9794 // using decls differ if they name different scopes (but note that 9795 // template instantiation can cause this check to trigger when it 9796 // didn't before instantiation). 9797 if (Context.getCanonicalNestedNameSpecifier(Qual) != 9798 Context.getCanonicalNestedNameSpecifier(DQual)) 9799 continue; 9800 9801 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 9802 Diag(D->getLocation(), diag::note_using_decl) << 1; 9803 return true; 9804 } 9805 9806 return false; 9807 } 9808 9809 9810 /// Checks that the given nested-name qualifier used in a using decl 9811 /// in the current context is appropriately related to the current 9812 /// scope. If an error is found, diagnoses it and returns true. 9813 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 9814 bool HasTypename, 9815 const CXXScopeSpec &SS, 9816 const DeclarationNameInfo &NameInfo, 9817 SourceLocation NameLoc) { 9818 DeclContext *NamedContext = computeDeclContext(SS); 9819 9820 if (!CurContext->isRecord()) { 9821 // C++03 [namespace.udecl]p3: 9822 // C++0x [namespace.udecl]p8: 9823 // A using-declaration for a class member shall be a member-declaration. 9824 9825 // If we weren't able to compute a valid scope, it might validly be a 9826 // dependent class scope or a dependent enumeration unscoped scope. If 9827 // we have a 'typename' keyword, the scope must resolve to a class type. 9828 if ((HasTypename && !NamedContext) || 9829 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 9830 auto *RD = NamedContext 9831 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 9832 : nullptr; 9833 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 9834 RD = nullptr; 9835 9836 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 9837 << SS.getRange(); 9838 9839 // If we have a complete, non-dependent source type, try to suggest a 9840 // way to get the same effect. 9841 if (!RD) 9842 return true; 9843 9844 // Find what this using-declaration was referring to. 9845 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9846 R.setHideTags(false); 9847 R.suppressDiagnostics(); 9848 LookupQualifiedName(R, RD); 9849 9850 if (R.getAsSingle<TypeDecl>()) { 9851 if (getLangOpts().CPlusPlus11) { 9852 // Convert 'using X::Y;' to 'using Y = X::Y;'. 9853 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 9854 << 0 // alias declaration 9855 << FixItHint::CreateInsertion(SS.getBeginLoc(), 9856 NameInfo.getName().getAsString() + 9857 " = "); 9858 } else { 9859 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 9860 SourceLocation InsertLoc = 9861 getLocForEndOfToken(NameInfo.getLocEnd()); 9862 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 9863 << 1 // typedef declaration 9864 << FixItHint::CreateReplacement(UsingLoc, "typedef") 9865 << FixItHint::CreateInsertion( 9866 InsertLoc, " " + NameInfo.getName().getAsString()); 9867 } 9868 } else if (R.getAsSingle<VarDecl>()) { 9869 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9870 // repeating the type of the static data member here. 9871 FixItHint FixIt; 9872 if (getLangOpts().CPlusPlus11) { 9873 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9874 FixIt = FixItHint::CreateReplacement( 9875 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 9876 } 9877 9878 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9879 << 2 // reference declaration 9880 << FixIt; 9881 } else if (R.getAsSingle<EnumConstantDecl>()) { 9882 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9883 // repeating the type of the enumeration here, and we can't do so if 9884 // the type is anonymous. 9885 FixItHint FixIt; 9886 if (getLangOpts().CPlusPlus11) { 9887 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9888 FixIt = FixItHint::CreateReplacement( 9889 UsingLoc, 9890 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 9891 } 9892 9893 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9894 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 9895 << FixIt; 9896 } 9897 return true; 9898 } 9899 9900 // Otherwise, this might be valid. 9901 return false; 9902 } 9903 9904 // The current scope is a record. 9905 9906 // If the named context is dependent, we can't decide much. 9907 if (!NamedContext) { 9908 // FIXME: in C++0x, we can diagnose if we can prove that the 9909 // nested-name-specifier does not refer to a base class, which is 9910 // still possible in some cases. 9911 9912 // Otherwise we have to conservatively report that things might be 9913 // okay. 9914 return false; 9915 } 9916 9917 if (!NamedContext->isRecord()) { 9918 // Ideally this would point at the last name in the specifier, 9919 // but we don't have that level of source info. 9920 Diag(SS.getRange().getBegin(), 9921 diag::err_using_decl_nested_name_specifier_is_not_class) 9922 << SS.getScopeRep() << SS.getRange(); 9923 return true; 9924 } 9925 9926 if (!NamedContext->isDependentContext() && 9927 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 9928 return true; 9929 9930 if (getLangOpts().CPlusPlus11) { 9931 // C++11 [namespace.udecl]p3: 9932 // In a using-declaration used as a member-declaration, the 9933 // nested-name-specifier shall name a base class of the class 9934 // being defined. 9935 9936 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 9937 cast<CXXRecordDecl>(NamedContext))) { 9938 if (CurContext == NamedContext) { 9939 Diag(NameLoc, 9940 diag::err_using_decl_nested_name_specifier_is_current_class) 9941 << SS.getRange(); 9942 return true; 9943 } 9944 9945 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 9946 Diag(SS.getRange().getBegin(), 9947 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9948 << SS.getScopeRep() 9949 << cast<CXXRecordDecl>(CurContext) 9950 << SS.getRange(); 9951 } 9952 return true; 9953 } 9954 9955 return false; 9956 } 9957 9958 // C++03 [namespace.udecl]p4: 9959 // A using-declaration used as a member-declaration shall refer 9960 // to a member of a base class of the class being defined [etc.]. 9961 9962 // Salient point: SS doesn't have to name a base class as long as 9963 // lookup only finds members from base classes. Therefore we can 9964 // diagnose here only if we can prove that that can't happen, 9965 // i.e. if the class hierarchies provably don't intersect. 9966 9967 // TODO: it would be nice if "definitely valid" results were cached 9968 // in the UsingDecl and UsingShadowDecl so that these checks didn't 9969 // need to be repeated. 9970 9971 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 9972 auto Collect = [&Bases](const CXXRecordDecl *Base) { 9973 Bases.insert(Base); 9974 return true; 9975 }; 9976 9977 // Collect all bases. Return false if we find a dependent base. 9978 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 9979 return false; 9980 9981 // Returns true if the base is dependent or is one of the accumulated base 9982 // classes. 9983 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 9984 return !Bases.count(Base); 9985 }; 9986 9987 // Return false if the class has a dependent base or if it or one 9988 // of its bases is present in the base set of the current context. 9989 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 9990 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 9991 return false; 9992 9993 Diag(SS.getRange().getBegin(), 9994 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9995 << SS.getScopeRep() 9996 << cast<CXXRecordDecl>(CurContext) 9997 << SS.getRange(); 9998 9999 return true; 10000 } 10001 10002 Decl *Sema::ActOnAliasDeclaration(Scope *S, 10003 AccessSpecifier AS, 10004 MultiTemplateParamsArg TemplateParamLists, 10005 SourceLocation UsingLoc, 10006 UnqualifiedId &Name, 10007 AttributeList *AttrList, 10008 TypeResult Type, 10009 Decl *DeclFromDeclSpec) { 10010 // Skip up to the relevant declaration scope. 10011 while (S->isTemplateParamScope()) 10012 S = S->getParent(); 10013 assert((S->getFlags() & Scope::DeclScope) && 10014 "got alias-declaration outside of declaration scope"); 10015 10016 if (Type.isInvalid()) 10017 return nullptr; 10018 10019 bool Invalid = false; 10020 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 10021 TypeSourceInfo *TInfo = nullptr; 10022 GetTypeFromParser(Type.get(), &TInfo); 10023 10024 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 10025 return nullptr; 10026 10027 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 10028 UPPC_DeclarationType)) { 10029 Invalid = true; 10030 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10031 TInfo->getTypeLoc().getBeginLoc()); 10032 } 10033 10034 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10035 TemplateParamLists.size() 10036 ? forRedeclarationInCurContext() 10037 : ForVisibleRedeclaration); 10038 LookupName(Previous, S); 10039 10040 // Warn about shadowing the name of a template parameter. 10041 if (Previous.isSingleResult() && 10042 Previous.getFoundDecl()->isTemplateParameter()) { 10043 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 10044 Previous.clear(); 10045 } 10046 10047 assert(Name.Kind == UnqualifiedId::IK_Identifier && 10048 "name in alias declaration must be an identifier"); 10049 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 10050 Name.StartLocation, 10051 Name.Identifier, TInfo); 10052 10053 NewTD->setAccess(AS); 10054 10055 if (Invalid) 10056 NewTD->setInvalidDecl(); 10057 10058 ProcessDeclAttributeList(S, NewTD, AttrList); 10059 AddPragmaAttributes(S, NewTD); 10060 10061 CheckTypedefForVariablyModifiedType(S, NewTD); 10062 Invalid |= NewTD->isInvalidDecl(); 10063 10064 bool Redeclaration = false; 10065 10066 NamedDecl *NewND; 10067 if (TemplateParamLists.size()) { 10068 TypeAliasTemplateDecl *OldDecl = nullptr; 10069 TemplateParameterList *OldTemplateParams = nullptr; 10070 10071 if (TemplateParamLists.size() != 1) { 10072 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10073 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10074 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10075 } 10076 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10077 10078 // Check that we can declare a template here. 10079 if (CheckTemplateDeclScope(S, TemplateParams)) 10080 return nullptr; 10081 10082 // Only consider previous declarations in the same scope. 10083 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10084 /*ExplicitInstantiationOrSpecialization*/false); 10085 if (!Previous.empty()) { 10086 Redeclaration = true; 10087 10088 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10089 if (!OldDecl && !Invalid) { 10090 Diag(UsingLoc, diag::err_redefinition_different_kind) 10091 << Name.Identifier; 10092 10093 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10094 if (OldD->getLocation().isValid()) 10095 Diag(OldD->getLocation(), diag::note_previous_definition); 10096 10097 Invalid = true; 10098 } 10099 10100 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10101 if (TemplateParameterListsAreEqual(TemplateParams, 10102 OldDecl->getTemplateParameters(), 10103 /*Complain=*/true, 10104 TPL_TemplateMatch)) 10105 OldTemplateParams = OldDecl->getTemplateParameters(); 10106 else 10107 Invalid = true; 10108 10109 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10110 if (!Invalid && 10111 !Context.hasSameType(OldTD->getUnderlyingType(), 10112 NewTD->getUnderlyingType())) { 10113 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10114 // but we can't reasonably accept it. 10115 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10116 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10117 if (OldTD->getLocation().isValid()) 10118 Diag(OldTD->getLocation(), diag::note_previous_definition); 10119 Invalid = true; 10120 } 10121 } 10122 } 10123 10124 // Merge any previous default template arguments into our parameters, 10125 // and check the parameter list. 10126 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10127 TPC_TypeAliasTemplate)) 10128 return nullptr; 10129 10130 TypeAliasTemplateDecl *NewDecl = 10131 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10132 Name.Identifier, TemplateParams, 10133 NewTD); 10134 NewTD->setDescribedAliasTemplate(NewDecl); 10135 10136 NewDecl->setAccess(AS); 10137 10138 if (Invalid) 10139 NewDecl->setInvalidDecl(); 10140 else if (OldDecl) { 10141 NewDecl->setPreviousDecl(OldDecl); 10142 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 10143 } 10144 10145 NewND = NewDecl; 10146 } else { 10147 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10148 setTagNameForLinkagePurposes(TD, NewTD); 10149 handleTagNumbering(TD, S); 10150 } 10151 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10152 NewND = NewTD; 10153 } 10154 10155 PushOnScopeChains(NewND, S); 10156 ActOnDocumentableDecl(NewND); 10157 return NewND; 10158 } 10159 10160 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10161 SourceLocation AliasLoc, 10162 IdentifierInfo *Alias, CXXScopeSpec &SS, 10163 SourceLocation IdentLoc, 10164 IdentifierInfo *Ident) { 10165 10166 // Lookup the namespace name. 10167 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10168 LookupParsedName(R, S, &SS); 10169 10170 if (R.isAmbiguous()) 10171 return nullptr; 10172 10173 if (R.empty()) { 10174 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10175 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10176 return nullptr; 10177 } 10178 } 10179 assert(!R.isAmbiguous() && !R.empty()); 10180 NamedDecl *ND = R.getRepresentativeDecl(); 10181 10182 // Check if we have a previous declaration with the same name. 10183 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10184 ForVisibleRedeclaration); 10185 LookupName(PrevR, S); 10186 10187 // Check we're not shadowing a template parameter. 10188 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10189 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10190 PrevR.clear(); 10191 } 10192 10193 // Filter out any other lookup result from an enclosing scope. 10194 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10195 /*AllowInlineNamespace*/false); 10196 10197 // Find the previous declaration and check that we can redeclare it. 10198 NamespaceAliasDecl *Prev = nullptr; 10199 if (PrevR.isSingleResult()) { 10200 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10201 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10202 // We already have an alias with the same name that points to the same 10203 // namespace; check that it matches. 10204 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10205 Prev = AD; 10206 } else if (isVisible(PrevDecl)) { 10207 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10208 << Alias; 10209 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10210 << AD->getNamespace(); 10211 return nullptr; 10212 } 10213 } else if (isVisible(PrevDecl)) { 10214 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10215 ? diag::err_redefinition 10216 : diag::err_redefinition_different_kind; 10217 Diag(AliasLoc, DiagID) << Alias; 10218 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10219 return nullptr; 10220 } 10221 } 10222 10223 // The use of a nested name specifier may trigger deprecation warnings. 10224 DiagnoseUseOfDecl(ND, IdentLoc); 10225 10226 NamespaceAliasDecl *AliasDecl = 10227 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10228 Alias, SS.getWithLocInContext(Context), 10229 IdentLoc, ND); 10230 if (Prev) 10231 AliasDecl->setPreviousDecl(Prev); 10232 10233 PushOnScopeChains(AliasDecl, S); 10234 return AliasDecl; 10235 } 10236 10237 namespace { 10238 struct SpecialMemberExceptionSpecInfo 10239 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10240 SourceLocation Loc; 10241 Sema::ImplicitExceptionSpecification ExceptSpec; 10242 10243 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10244 Sema::CXXSpecialMember CSM, 10245 Sema::InheritedConstructorInfo *ICI, 10246 SourceLocation Loc) 10247 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10248 10249 bool visitBase(CXXBaseSpecifier *Base); 10250 bool visitField(FieldDecl *FD); 10251 10252 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10253 unsigned Quals); 10254 10255 void visitSubobjectCall(Subobject Subobj, 10256 Sema::SpecialMemberOverloadResult SMOR); 10257 }; 10258 } 10259 10260 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10261 auto *RT = Base->getType()->getAs<RecordType>(); 10262 if (!RT) 10263 return false; 10264 10265 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10266 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10267 if (auto *BaseCtor = SMOR.getMethod()) { 10268 visitSubobjectCall(Base, BaseCtor); 10269 return false; 10270 } 10271 10272 visitClassSubobject(BaseClass, Base, 0); 10273 return false; 10274 } 10275 10276 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10277 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10278 Expr *E = FD->getInClassInitializer(); 10279 if (!E) 10280 // FIXME: It's a little wasteful to build and throw away a 10281 // CXXDefaultInitExpr here. 10282 // FIXME: We should have a single context note pointing at Loc, and 10283 // this location should be MD->getLocation() instead, since that's 10284 // the location where we actually use the default init expression. 10285 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10286 if (E) 10287 ExceptSpec.CalledExpr(E); 10288 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10289 ->getAs<RecordType>()) { 10290 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10291 FD->getType().getCVRQualifiers()); 10292 } 10293 return false; 10294 } 10295 10296 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10297 Subobject Subobj, 10298 unsigned Quals) { 10299 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10300 bool IsMutable = Field && Field->isMutable(); 10301 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10302 } 10303 10304 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10305 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10306 // Note, if lookup fails, it doesn't matter what exception specification we 10307 // choose because the special member will be deleted. 10308 if (CXXMethodDecl *MD = SMOR.getMethod()) 10309 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10310 } 10311 10312 static Sema::ImplicitExceptionSpecification 10313 ComputeDefaultedSpecialMemberExceptionSpec( 10314 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 10315 Sema::InheritedConstructorInfo *ICI) { 10316 CXXRecordDecl *ClassDecl = MD->getParent(); 10317 10318 // C++ [except.spec]p14: 10319 // An implicitly declared special member function (Clause 12) shall have an 10320 // exception-specification. [...] 10321 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc); 10322 if (ClassDecl->isInvalidDecl()) 10323 return Info.ExceptSpec; 10324 10325 // C++1z [except.spec]p7: 10326 // [Look for exceptions thrown by] a constructor selected [...] to 10327 // initialize a potentially constructed subobject, 10328 // C++1z [except.spec]p8: 10329 // The exception specification for an implicitly-declared destructor, or a 10330 // destructor without a noexcept-specifier, is potentially-throwing if and 10331 // only if any of the destructors for any of its potentially constructed 10332 // subojects is potentially throwing. 10333 // FIXME: We respect the first rule but ignore the "potentially constructed" 10334 // in the second rule to resolve a core issue (no number yet) that would have 10335 // us reject: 10336 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 10337 // struct B : A {}; 10338 // struct C : B { void f(); }; 10339 // ... due to giving B::~B() a non-throwing exception specification. 10340 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 10341 : Info.VisitAllBases); 10342 10343 return Info.ExceptSpec; 10344 } 10345 10346 namespace { 10347 /// RAII object to register a special member as being currently declared. 10348 struct DeclaringSpecialMember { 10349 Sema &S; 10350 Sema::SpecialMemberDecl D; 10351 Sema::ContextRAII SavedContext; 10352 bool WasAlreadyBeingDeclared; 10353 10354 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 10355 : S(S), D(RD, CSM), SavedContext(S, RD) { 10356 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 10357 if (WasAlreadyBeingDeclared) 10358 // This almost never happens, but if it does, ensure that our cache 10359 // doesn't contain a stale result. 10360 S.SpecialMemberCache.clear(); 10361 else { 10362 // Register a note to be produced if we encounter an error while 10363 // declaring the special member. 10364 Sema::CodeSynthesisContext Ctx; 10365 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 10366 // FIXME: We don't have a location to use here. Using the class's 10367 // location maintains the fiction that we declare all special members 10368 // with the class, but (1) it's not clear that lying about that helps our 10369 // users understand what's going on, and (2) there may be outer contexts 10370 // on the stack (some of which are relevant) and printing them exposes 10371 // our lies. 10372 Ctx.PointOfInstantiation = RD->getLocation(); 10373 Ctx.Entity = RD; 10374 Ctx.SpecialMember = CSM; 10375 S.pushCodeSynthesisContext(Ctx); 10376 } 10377 } 10378 ~DeclaringSpecialMember() { 10379 if (!WasAlreadyBeingDeclared) { 10380 S.SpecialMembersBeingDeclared.erase(D); 10381 S.popCodeSynthesisContext(); 10382 } 10383 } 10384 10385 /// \brief Are we already trying to declare this special member? 10386 bool isAlreadyBeingDeclared() const { 10387 return WasAlreadyBeingDeclared; 10388 } 10389 }; 10390 } 10391 10392 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 10393 // Look up any existing declarations, but don't trigger declaration of all 10394 // implicit special members with this name. 10395 DeclarationName Name = FD->getDeclName(); 10396 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 10397 ForExternalRedeclaration); 10398 for (auto *D : FD->getParent()->lookup(Name)) 10399 if (auto *Acceptable = R.getAcceptableDecl(D)) 10400 R.addDecl(Acceptable); 10401 R.resolveKind(); 10402 R.suppressDiagnostics(); 10403 10404 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 10405 } 10406 10407 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 10408 CXXRecordDecl *ClassDecl) { 10409 // C++ [class.ctor]p5: 10410 // A default constructor for a class X is a constructor of class X 10411 // that can be called without an argument. If there is no 10412 // user-declared constructor for class X, a default constructor is 10413 // implicitly declared. An implicitly-declared default constructor 10414 // is an inline public member of its class. 10415 assert(ClassDecl->needsImplicitDefaultConstructor() && 10416 "Should not build implicit default constructor!"); 10417 10418 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 10419 if (DSM.isAlreadyBeingDeclared()) 10420 return nullptr; 10421 10422 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10423 CXXDefaultConstructor, 10424 false); 10425 10426 // Create the actual constructor declaration. 10427 CanQualType ClassType 10428 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10429 SourceLocation ClassLoc = ClassDecl->getLocation(); 10430 DeclarationName Name 10431 = Context.DeclarationNames.getCXXConstructorName(ClassType); 10432 DeclarationNameInfo NameInfo(Name, ClassLoc); 10433 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 10434 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 10435 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 10436 /*isImplicitlyDeclared=*/true, Constexpr); 10437 DefaultCon->setAccess(AS_public); 10438 DefaultCon->setDefaulted(); 10439 10440 if (getLangOpts().CUDA) { 10441 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 10442 DefaultCon, 10443 /* ConstRHS */ false, 10444 /* Diagnose */ false); 10445 } 10446 10447 // Build an exception specification pointing back at this constructor. 10448 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 10449 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10450 10451 // We don't need to use SpecialMemberIsTrivial here; triviality for default 10452 // constructors is easy to compute. 10453 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 10454 10455 // Note that we have declared this constructor. 10456 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 10457 10458 Scope *S = getScopeForContext(ClassDecl); 10459 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 10460 10461 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 10462 SetDeclDeleted(DefaultCon, ClassLoc); 10463 10464 if (S) 10465 PushOnScopeChains(DefaultCon, S, false); 10466 ClassDecl->addDecl(DefaultCon); 10467 10468 return DefaultCon; 10469 } 10470 10471 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 10472 CXXConstructorDecl *Constructor) { 10473 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 10474 !Constructor->doesThisDeclarationHaveABody() && 10475 !Constructor->isDeleted()) && 10476 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 10477 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10478 return; 10479 10480 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10481 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 10482 10483 SynthesizedFunctionScope Scope(*this, Constructor); 10484 10485 // The exception specification is needed because we are defining the 10486 // function. 10487 ResolveExceptionSpec(CurrentLocation, 10488 Constructor->getType()->castAs<FunctionProtoType>()); 10489 MarkVTableUsed(CurrentLocation, ClassDecl); 10490 10491 // Add a context note for diagnostics produced after this point. 10492 Scope.addContextNote(CurrentLocation); 10493 10494 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 10495 Constructor->setInvalidDecl(); 10496 return; 10497 } 10498 10499 SourceLocation Loc = Constructor->getLocEnd().isValid() 10500 ? Constructor->getLocEnd() 10501 : Constructor->getLocation(); 10502 Constructor->setBody(new (Context) CompoundStmt(Loc)); 10503 Constructor->markUsed(Context); 10504 10505 if (ASTMutationListener *L = getASTMutationListener()) { 10506 L->CompletedImplicitDefinition(Constructor); 10507 } 10508 10509 DiagnoseUninitializedFields(*this, Constructor); 10510 } 10511 10512 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 10513 // Perform any delayed checks on exception specifications. 10514 CheckDelayedMemberExceptionSpecs(); 10515 } 10516 10517 /// Find or create the fake constructor we synthesize to model constructing an 10518 /// object of a derived class via a constructor of a base class. 10519 CXXConstructorDecl * 10520 Sema::findInheritingConstructor(SourceLocation Loc, 10521 CXXConstructorDecl *BaseCtor, 10522 ConstructorUsingShadowDecl *Shadow) { 10523 CXXRecordDecl *Derived = Shadow->getParent(); 10524 SourceLocation UsingLoc = Shadow->getLocation(); 10525 10526 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 10527 // For now we use the name of the base class constructor as a member of the 10528 // derived class to indicate a (fake) inherited constructor name. 10529 DeclarationName Name = BaseCtor->getDeclName(); 10530 10531 // Check to see if we already have a fake constructor for this inherited 10532 // constructor call. 10533 for (NamedDecl *Ctor : Derived->lookup(Name)) 10534 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 10535 ->getInheritedConstructor() 10536 .getConstructor(), 10537 BaseCtor)) 10538 return cast<CXXConstructorDecl>(Ctor); 10539 10540 DeclarationNameInfo NameInfo(Name, UsingLoc); 10541 TypeSourceInfo *TInfo = 10542 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 10543 FunctionProtoTypeLoc ProtoLoc = 10544 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 10545 10546 // Check the inherited constructor is valid and find the list of base classes 10547 // from which it was inherited. 10548 InheritedConstructorInfo ICI(*this, Loc, Shadow); 10549 10550 bool Constexpr = 10551 BaseCtor->isConstexpr() && 10552 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 10553 false, BaseCtor, &ICI); 10554 10555 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 10556 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 10557 BaseCtor->isExplicit(), /*Inline=*/true, 10558 /*ImplicitlyDeclared=*/true, Constexpr, 10559 InheritedConstructor(Shadow, BaseCtor)); 10560 if (Shadow->isInvalidDecl()) 10561 DerivedCtor->setInvalidDecl(); 10562 10563 // Build an unevaluated exception specification for this fake constructor. 10564 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 10565 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10566 EPI.ExceptionSpec.Type = EST_Unevaluated; 10567 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 10568 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 10569 FPT->getParamTypes(), EPI)); 10570 10571 // Build the parameter declarations. 10572 SmallVector<ParmVarDecl *, 16> ParamDecls; 10573 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 10574 TypeSourceInfo *TInfo = 10575 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 10576 ParmVarDecl *PD = ParmVarDecl::Create( 10577 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 10578 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 10579 PD->setScopeInfo(0, I); 10580 PD->setImplicit(); 10581 // Ensure attributes are propagated onto parameters (this matters for 10582 // format, pass_object_size, ...). 10583 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 10584 ParamDecls.push_back(PD); 10585 ProtoLoc.setParam(I, PD); 10586 } 10587 10588 // Set up the new constructor. 10589 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 10590 DerivedCtor->setAccess(BaseCtor->getAccess()); 10591 DerivedCtor->setParams(ParamDecls); 10592 Derived->addDecl(DerivedCtor); 10593 10594 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 10595 SetDeclDeleted(DerivedCtor, UsingLoc); 10596 10597 return DerivedCtor; 10598 } 10599 10600 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 10601 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 10602 Ctor->getInheritedConstructor().getShadowDecl()); 10603 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 10604 /*Diagnose*/true); 10605 } 10606 10607 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 10608 CXXConstructorDecl *Constructor) { 10609 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10610 assert(Constructor->getInheritedConstructor() && 10611 !Constructor->doesThisDeclarationHaveABody() && 10612 !Constructor->isDeleted()); 10613 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10614 return; 10615 10616 // Initializations are performed "as if by a defaulted default constructor", 10617 // so enter the appropriate scope. 10618 SynthesizedFunctionScope Scope(*this, Constructor); 10619 10620 // The exception specification is needed because we are defining the 10621 // function. 10622 ResolveExceptionSpec(CurrentLocation, 10623 Constructor->getType()->castAs<FunctionProtoType>()); 10624 MarkVTableUsed(CurrentLocation, ClassDecl); 10625 10626 // Add a context note for diagnostics produced after this point. 10627 Scope.addContextNote(CurrentLocation); 10628 10629 ConstructorUsingShadowDecl *Shadow = 10630 Constructor->getInheritedConstructor().getShadowDecl(); 10631 CXXConstructorDecl *InheritedCtor = 10632 Constructor->getInheritedConstructor().getConstructor(); 10633 10634 // [class.inhctor.init]p1: 10635 // initialization proceeds as if a defaulted default constructor is used to 10636 // initialize the D object and each base class subobject from which the 10637 // constructor was inherited 10638 10639 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 10640 CXXRecordDecl *RD = Shadow->getParent(); 10641 SourceLocation InitLoc = Shadow->getLocation(); 10642 10643 // Build explicit initializers for all base classes from which the 10644 // constructor was inherited. 10645 SmallVector<CXXCtorInitializer*, 8> Inits; 10646 for (bool VBase : {false, true}) { 10647 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 10648 if (B.isVirtual() != VBase) 10649 continue; 10650 10651 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 10652 if (!BaseRD) 10653 continue; 10654 10655 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 10656 if (!BaseCtor.first) 10657 continue; 10658 10659 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 10660 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 10661 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 10662 10663 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 10664 Inits.push_back(new (Context) CXXCtorInitializer( 10665 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 10666 SourceLocation())); 10667 } 10668 } 10669 10670 // We now proceed as if for a defaulted default constructor, with the relevant 10671 // initializers replaced. 10672 10673 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 10674 Constructor->setInvalidDecl(); 10675 return; 10676 } 10677 10678 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 10679 Constructor->markUsed(Context); 10680 10681 if (ASTMutationListener *L = getASTMutationListener()) { 10682 L->CompletedImplicitDefinition(Constructor); 10683 } 10684 10685 DiagnoseUninitializedFields(*this, Constructor); 10686 } 10687 10688 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 10689 // C++ [class.dtor]p2: 10690 // If a class has no user-declared destructor, a destructor is 10691 // declared implicitly. An implicitly-declared destructor is an 10692 // inline public member of its class. 10693 assert(ClassDecl->needsImplicitDestructor()); 10694 10695 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 10696 if (DSM.isAlreadyBeingDeclared()) 10697 return nullptr; 10698 10699 // Create the actual destructor declaration. 10700 CanQualType ClassType 10701 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10702 SourceLocation ClassLoc = ClassDecl->getLocation(); 10703 DeclarationName Name 10704 = Context.DeclarationNames.getCXXDestructorName(ClassType); 10705 DeclarationNameInfo NameInfo(Name, ClassLoc); 10706 CXXDestructorDecl *Destructor 10707 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 10708 QualType(), nullptr, /*isInline=*/true, 10709 /*isImplicitlyDeclared=*/true); 10710 Destructor->setAccess(AS_public); 10711 Destructor->setDefaulted(); 10712 10713 if (getLangOpts().CUDA) { 10714 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 10715 Destructor, 10716 /* ConstRHS */ false, 10717 /* Diagnose */ false); 10718 } 10719 10720 // Build an exception specification pointing back at this destructor. 10721 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 10722 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10723 10724 // We don't need to use SpecialMemberIsTrivial here; triviality for 10725 // destructors is easy to compute. 10726 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 10727 10728 // Note that we have declared this destructor. 10729 ++ASTContext::NumImplicitDestructorsDeclared; 10730 10731 Scope *S = getScopeForContext(ClassDecl); 10732 CheckImplicitSpecialMemberDeclaration(S, Destructor); 10733 10734 // We can't check whether an implicit destructor is deleted before we complete 10735 // the definition of the class, because its validity depends on the alignment 10736 // of the class. We'll check this from ActOnFields once the class is complete. 10737 if (ClassDecl->isCompleteDefinition() && 10738 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 10739 SetDeclDeleted(Destructor, ClassLoc); 10740 10741 // Introduce this destructor into its scope. 10742 if (S) 10743 PushOnScopeChains(Destructor, S, false); 10744 ClassDecl->addDecl(Destructor); 10745 10746 return Destructor; 10747 } 10748 10749 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 10750 CXXDestructorDecl *Destructor) { 10751 assert((Destructor->isDefaulted() && 10752 !Destructor->doesThisDeclarationHaveABody() && 10753 !Destructor->isDeleted()) && 10754 "DefineImplicitDestructor - call it for implicit default dtor"); 10755 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 10756 return; 10757 10758 CXXRecordDecl *ClassDecl = Destructor->getParent(); 10759 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 10760 10761 SynthesizedFunctionScope Scope(*this, Destructor); 10762 10763 // The exception specification is needed because we are defining the 10764 // function. 10765 ResolveExceptionSpec(CurrentLocation, 10766 Destructor->getType()->castAs<FunctionProtoType>()); 10767 MarkVTableUsed(CurrentLocation, ClassDecl); 10768 10769 // Add a context note for diagnostics produced after this point. 10770 Scope.addContextNote(CurrentLocation); 10771 10772 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10773 Destructor->getParent()); 10774 10775 if (CheckDestructor(Destructor)) { 10776 Destructor->setInvalidDecl(); 10777 return; 10778 } 10779 10780 SourceLocation Loc = Destructor->getLocEnd().isValid() 10781 ? Destructor->getLocEnd() 10782 : Destructor->getLocation(); 10783 Destructor->setBody(new (Context) CompoundStmt(Loc)); 10784 Destructor->markUsed(Context); 10785 10786 if (ASTMutationListener *L = getASTMutationListener()) { 10787 L->CompletedImplicitDefinition(Destructor); 10788 } 10789 } 10790 10791 /// \brief Perform any semantic analysis which needs to be delayed until all 10792 /// pending class member declarations have been parsed. 10793 void Sema::ActOnFinishCXXMemberDecls() { 10794 // If the context is an invalid C++ class, just suppress these checks. 10795 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 10796 if (Record->isInvalidDecl()) { 10797 DelayedDefaultedMemberExceptionSpecs.clear(); 10798 DelayedExceptionSpecChecks.clear(); 10799 return; 10800 } 10801 checkForMultipleExportedDefaultConstructors(*this, Record); 10802 } 10803 } 10804 10805 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 10806 referenceDLLExportedClassMethods(); 10807 } 10808 10809 void Sema::referenceDLLExportedClassMethods() { 10810 if (!DelayedDllExportClasses.empty()) { 10811 // Calling ReferenceDllExportedMethods might cause the current function to 10812 // be called again, so use a local copy of DelayedDllExportClasses. 10813 SmallVector<CXXRecordDecl *, 4> WorkList; 10814 std::swap(DelayedDllExportClasses, WorkList); 10815 for (CXXRecordDecl *Class : WorkList) 10816 ReferenceDllExportedMethods(*this, Class); 10817 } 10818 } 10819 10820 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 10821 CXXDestructorDecl *Destructor) { 10822 assert(getLangOpts().CPlusPlus11 && 10823 "adjusting dtor exception specs was introduced in c++11"); 10824 10825 // C++11 [class.dtor]p3: 10826 // A declaration of a destructor that does not have an exception- 10827 // specification is implicitly considered to have the same exception- 10828 // specification as an implicit declaration. 10829 const FunctionProtoType *DtorType = Destructor->getType()-> 10830 getAs<FunctionProtoType>(); 10831 if (DtorType->hasExceptionSpec()) 10832 return; 10833 10834 // Replace the destructor's type, building off the existing one. Fortunately, 10835 // the only thing of interest in the destructor type is its extended info. 10836 // The return and arguments are fixed. 10837 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 10838 EPI.ExceptionSpec.Type = EST_Unevaluated; 10839 EPI.ExceptionSpec.SourceDecl = Destructor; 10840 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10841 10842 // FIXME: If the destructor has a body that could throw, and the newly created 10843 // spec doesn't allow exceptions, we should emit a warning, because this 10844 // change in behavior can break conforming C++03 programs at runtime. 10845 // However, we don't have a body or an exception specification yet, so it 10846 // needs to be done somewhere else. 10847 } 10848 10849 namespace { 10850 /// \brief An abstract base class for all helper classes used in building the 10851 // copy/move operators. These classes serve as factory functions and help us 10852 // avoid using the same Expr* in the AST twice. 10853 class ExprBuilder { 10854 ExprBuilder(const ExprBuilder&) = delete; 10855 ExprBuilder &operator=(const ExprBuilder&) = delete; 10856 10857 protected: 10858 static Expr *assertNotNull(Expr *E) { 10859 assert(E && "Expression construction must not fail."); 10860 return E; 10861 } 10862 10863 public: 10864 ExprBuilder() {} 10865 virtual ~ExprBuilder() {} 10866 10867 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 10868 }; 10869 10870 class RefBuilder: public ExprBuilder { 10871 VarDecl *Var; 10872 QualType VarType; 10873 10874 public: 10875 Expr *build(Sema &S, SourceLocation Loc) const override { 10876 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 10877 } 10878 10879 RefBuilder(VarDecl *Var, QualType VarType) 10880 : Var(Var), VarType(VarType) {} 10881 }; 10882 10883 class ThisBuilder: public ExprBuilder { 10884 public: 10885 Expr *build(Sema &S, SourceLocation Loc) const override { 10886 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 10887 } 10888 }; 10889 10890 class CastBuilder: public ExprBuilder { 10891 const ExprBuilder &Builder; 10892 QualType Type; 10893 ExprValueKind Kind; 10894 const CXXCastPath &Path; 10895 10896 public: 10897 Expr *build(Sema &S, SourceLocation Loc) const override { 10898 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 10899 CK_UncheckedDerivedToBase, Kind, 10900 &Path).get()); 10901 } 10902 10903 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 10904 const CXXCastPath &Path) 10905 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 10906 }; 10907 10908 class DerefBuilder: public ExprBuilder { 10909 const ExprBuilder &Builder; 10910 10911 public: 10912 Expr *build(Sema &S, SourceLocation Loc) const override { 10913 return assertNotNull( 10914 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 10915 } 10916 10917 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10918 }; 10919 10920 class MemberBuilder: public ExprBuilder { 10921 const ExprBuilder &Builder; 10922 QualType Type; 10923 CXXScopeSpec SS; 10924 bool IsArrow; 10925 LookupResult &MemberLookup; 10926 10927 public: 10928 Expr *build(Sema &S, SourceLocation Loc) const override { 10929 return assertNotNull(S.BuildMemberReferenceExpr( 10930 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 10931 nullptr, MemberLookup, nullptr, nullptr).get()); 10932 } 10933 10934 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 10935 LookupResult &MemberLookup) 10936 : Builder(Builder), Type(Type), IsArrow(IsArrow), 10937 MemberLookup(MemberLookup) {} 10938 }; 10939 10940 class MoveCastBuilder: public ExprBuilder { 10941 const ExprBuilder &Builder; 10942 10943 public: 10944 Expr *build(Sema &S, SourceLocation Loc) const override { 10945 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 10946 } 10947 10948 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10949 }; 10950 10951 class LvalueConvBuilder: public ExprBuilder { 10952 const ExprBuilder &Builder; 10953 10954 public: 10955 Expr *build(Sema &S, SourceLocation Loc) const override { 10956 return assertNotNull( 10957 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 10958 } 10959 10960 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10961 }; 10962 10963 class SubscriptBuilder: public ExprBuilder { 10964 const ExprBuilder &Base; 10965 const ExprBuilder &Index; 10966 10967 public: 10968 Expr *build(Sema &S, SourceLocation Loc) const override { 10969 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 10970 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 10971 } 10972 10973 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 10974 : Base(Base), Index(Index) {} 10975 }; 10976 10977 } // end anonymous namespace 10978 10979 /// When generating a defaulted copy or move assignment operator, if a field 10980 /// should be copied with __builtin_memcpy rather than via explicit assignments, 10981 /// do so. This optimization only applies for arrays of scalars, and for arrays 10982 /// of class type where the selected copy/move-assignment operator is trivial. 10983 static StmtResult 10984 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 10985 const ExprBuilder &ToB, const ExprBuilder &FromB) { 10986 // Compute the size of the memory buffer to be copied. 10987 QualType SizeType = S.Context.getSizeType(); 10988 llvm::APInt Size(S.Context.getTypeSize(SizeType), 10989 S.Context.getTypeSizeInChars(T).getQuantity()); 10990 10991 // Take the address of the field references for "from" and "to". We 10992 // directly construct UnaryOperators here because semantic analysis 10993 // does not permit us to take the address of an xvalue. 10994 Expr *From = FromB.build(S, Loc); 10995 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 10996 S.Context.getPointerType(From->getType()), 10997 VK_RValue, OK_Ordinary, Loc); 10998 Expr *To = ToB.build(S, Loc); 10999 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 11000 S.Context.getPointerType(To->getType()), 11001 VK_RValue, OK_Ordinary, Loc); 11002 11003 const Type *E = T->getBaseElementTypeUnsafe(); 11004 bool NeedsCollectableMemCpy = 11005 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 11006 11007 // Create a reference to the __builtin_objc_memmove_collectable function 11008 StringRef MemCpyName = NeedsCollectableMemCpy ? 11009 "__builtin_objc_memmove_collectable" : 11010 "__builtin_memcpy"; 11011 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 11012 Sema::LookupOrdinaryName); 11013 S.LookupName(R, S.TUScope, true); 11014 11015 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 11016 if (!MemCpy) 11017 // Something went horribly wrong earlier, and we will have complained 11018 // about it. 11019 return StmtError(); 11020 11021 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 11022 VK_RValue, Loc, nullptr); 11023 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 11024 11025 Expr *CallArgs[] = { 11026 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 11027 }; 11028 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 11029 Loc, CallArgs, Loc); 11030 11031 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 11032 return Call.getAs<Stmt>(); 11033 } 11034 11035 /// \brief Builds a statement that copies/moves the given entity from \p From to 11036 /// \c To. 11037 /// 11038 /// This routine is used to copy/move the members of a class with an 11039 /// implicitly-declared copy/move assignment operator. When the entities being 11040 /// copied are arrays, this routine builds for loops to copy them. 11041 /// 11042 /// \param S The Sema object used for type-checking. 11043 /// 11044 /// \param Loc The location where the implicit copy/move is being generated. 11045 /// 11046 /// \param T The type of the expressions being copied/moved. Both expressions 11047 /// must have this type. 11048 /// 11049 /// \param To The expression we are copying/moving to. 11050 /// 11051 /// \param From The expression we are copying/moving from. 11052 /// 11053 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 11054 /// Otherwise, it's a non-static member subobject. 11055 /// 11056 /// \param Copying Whether we're copying or moving. 11057 /// 11058 /// \param Depth Internal parameter recording the depth of the recursion. 11059 /// 11060 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11061 /// if a memcpy should be used instead. 11062 static StmtResult 11063 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11064 const ExprBuilder &To, const ExprBuilder &From, 11065 bool CopyingBaseSubobject, bool Copying, 11066 unsigned Depth = 0) { 11067 // C++11 [class.copy]p28: 11068 // Each subobject is assigned in the manner appropriate to its type: 11069 // 11070 // - if the subobject is of class type, as if by a call to operator= with 11071 // the subobject as the object expression and the corresponding 11072 // subobject of x as a single function argument (as if by explicit 11073 // qualification; that is, ignoring any possible virtual overriding 11074 // functions in more derived classes); 11075 // 11076 // C++03 [class.copy]p13: 11077 // - if the subobject is of class type, the copy assignment operator for 11078 // the class is used (as if by explicit qualification; that is, 11079 // ignoring any possible virtual overriding functions in more derived 11080 // classes); 11081 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11082 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11083 11084 // Look for operator=. 11085 DeclarationName Name 11086 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11087 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11088 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11089 11090 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11091 // operator. 11092 if (!S.getLangOpts().CPlusPlus11) { 11093 LookupResult::Filter F = OpLookup.makeFilter(); 11094 while (F.hasNext()) { 11095 NamedDecl *D = F.next(); 11096 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11097 if (Method->isCopyAssignmentOperator() || 11098 (!Copying && Method->isMoveAssignmentOperator())) 11099 continue; 11100 11101 F.erase(); 11102 } 11103 F.done(); 11104 } 11105 11106 // Suppress the protected check (C++ [class.protected]) for each of the 11107 // assignment operators we found. This strange dance is required when 11108 // we're assigning via a base classes's copy-assignment operator. To 11109 // ensure that we're getting the right base class subobject (without 11110 // ambiguities), we need to cast "this" to that subobject type; to 11111 // ensure that we don't go through the virtual call mechanism, we need 11112 // to qualify the operator= name with the base class (see below). However, 11113 // this means that if the base class has a protected copy assignment 11114 // operator, the protected member access check will fail. So, we 11115 // rewrite "protected" access to "public" access in this case, since we 11116 // know by construction that we're calling from a derived class. 11117 if (CopyingBaseSubobject) { 11118 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11119 L != LEnd; ++L) { 11120 if (L.getAccess() == AS_protected) 11121 L.setAccess(AS_public); 11122 } 11123 } 11124 11125 // Create the nested-name-specifier that will be used to qualify the 11126 // reference to operator=; this is required to suppress the virtual 11127 // call mechanism. 11128 CXXScopeSpec SS; 11129 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11130 SS.MakeTrivial(S.Context, 11131 NestedNameSpecifier::Create(S.Context, nullptr, false, 11132 CanonicalT), 11133 Loc); 11134 11135 // Create the reference to operator=. 11136 ExprResult OpEqualRef 11137 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 11138 SS, /*TemplateKWLoc=*/SourceLocation(), 11139 /*FirstQualifierInScope=*/nullptr, 11140 OpLookup, 11141 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11142 /*SuppressQualifierCheck=*/true); 11143 if (OpEqualRef.isInvalid()) 11144 return StmtError(); 11145 11146 // Build the call to the assignment operator. 11147 11148 Expr *FromInst = From.build(S, Loc); 11149 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11150 OpEqualRef.getAs<Expr>(), 11151 Loc, FromInst, Loc); 11152 if (Call.isInvalid()) 11153 return StmtError(); 11154 11155 // If we built a call to a trivial 'operator=' while copying an array, 11156 // bail out. We'll replace the whole shebang with a memcpy. 11157 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11158 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11159 return StmtResult((Stmt*)nullptr); 11160 11161 // Convert to an expression-statement, and clean up any produced 11162 // temporaries. 11163 return S.ActOnExprStmt(Call); 11164 } 11165 11166 // - if the subobject is of scalar type, the built-in assignment 11167 // operator is used. 11168 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11169 if (!ArrayTy) { 11170 ExprResult Assignment = S.CreateBuiltinBinOp( 11171 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11172 if (Assignment.isInvalid()) 11173 return StmtError(); 11174 return S.ActOnExprStmt(Assignment); 11175 } 11176 11177 // - if the subobject is an array, each element is assigned, in the 11178 // manner appropriate to the element type; 11179 11180 // Construct a loop over the array bounds, e.g., 11181 // 11182 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11183 // 11184 // that will copy each of the array elements. 11185 QualType SizeType = S.Context.getSizeType(); 11186 11187 // Create the iteration variable. 11188 IdentifierInfo *IterationVarName = nullptr; 11189 { 11190 SmallString<8> Str; 11191 llvm::raw_svector_ostream OS(Str); 11192 OS << "__i" << Depth; 11193 IterationVarName = &S.Context.Idents.get(OS.str()); 11194 } 11195 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11196 IterationVarName, SizeType, 11197 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11198 SC_None); 11199 11200 // Initialize the iteration variable to zero. 11201 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11202 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11203 11204 // Creates a reference to the iteration variable. 11205 RefBuilder IterationVarRef(IterationVar, SizeType); 11206 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11207 11208 // Create the DeclStmt that holds the iteration variable. 11209 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11210 11211 // Subscript the "from" and "to" expressions with the iteration variable. 11212 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11213 MoveCastBuilder FromIndexMove(FromIndexCopy); 11214 const ExprBuilder *FromIndex; 11215 if (Copying) 11216 FromIndex = &FromIndexCopy; 11217 else 11218 FromIndex = &FromIndexMove; 11219 11220 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11221 11222 // Build the copy/move for an individual element of the array. 11223 StmtResult Copy = 11224 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11225 ToIndex, *FromIndex, CopyingBaseSubobject, 11226 Copying, Depth + 1); 11227 // Bail out if copying fails or if we determined that we should use memcpy. 11228 if (Copy.isInvalid() || !Copy.get()) 11229 return Copy; 11230 11231 // Create the comparison against the array bound. 11232 llvm::APInt Upper 11233 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11234 Expr *Comparison 11235 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11236 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11237 BO_NE, S.Context.BoolTy, 11238 VK_RValue, OK_Ordinary, Loc, FPOptions()); 11239 11240 // Create the pre-increment of the iteration variable. 11241 Expr *Increment 11242 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 11243 SizeType, VK_LValue, OK_Ordinary, Loc); 11244 11245 // Construct the loop that copies all elements of this array. 11246 return S.ActOnForStmt( 11247 Loc, Loc, InitStmt, 11248 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 11249 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 11250 } 11251 11252 static StmtResult 11253 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 11254 const ExprBuilder &To, const ExprBuilder &From, 11255 bool CopyingBaseSubobject, bool Copying) { 11256 // Maybe we should use a memcpy? 11257 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 11258 T.isTriviallyCopyableType(S.Context)) 11259 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11260 11261 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 11262 CopyingBaseSubobject, 11263 Copying, 0)); 11264 11265 // If we ended up picking a trivial assignment operator for an array of a 11266 // non-trivially-copyable class type, just emit a memcpy. 11267 if (!Result.isInvalid() && !Result.get()) 11268 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11269 11270 return Result; 11271 } 11272 11273 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 11274 // Note: The following rules are largely analoguous to the copy 11275 // constructor rules. Note that virtual bases are not taken into account 11276 // for determining the argument type of the operator. Note also that 11277 // operators taking an object instead of a reference are allowed. 11278 assert(ClassDecl->needsImplicitCopyAssignment()); 11279 11280 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 11281 if (DSM.isAlreadyBeingDeclared()) 11282 return nullptr; 11283 11284 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11285 QualType RetType = Context.getLValueReferenceType(ArgType); 11286 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 11287 if (Const) 11288 ArgType = ArgType.withConst(); 11289 ArgType = Context.getLValueReferenceType(ArgType); 11290 11291 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11292 CXXCopyAssignment, 11293 Const); 11294 11295 // An implicitly-declared copy assignment operator is an inline public 11296 // member of its class. 11297 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11298 SourceLocation ClassLoc = ClassDecl->getLocation(); 11299 DeclarationNameInfo NameInfo(Name, ClassLoc); 11300 CXXMethodDecl *CopyAssignment = 11301 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11302 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11303 /*isInline=*/true, Constexpr, SourceLocation()); 11304 CopyAssignment->setAccess(AS_public); 11305 CopyAssignment->setDefaulted(); 11306 CopyAssignment->setImplicit(); 11307 11308 if (getLangOpts().CUDA) { 11309 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 11310 CopyAssignment, 11311 /* ConstRHS */ Const, 11312 /* Diagnose */ false); 11313 } 11314 11315 // Build an exception specification pointing back at this member. 11316 FunctionProtoType::ExtProtoInfo EPI = 11317 getImplicitMethodEPI(*this, CopyAssignment); 11318 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11319 11320 // Add the parameter to the operator. 11321 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 11322 ClassLoc, ClassLoc, 11323 /*Id=*/nullptr, ArgType, 11324 /*TInfo=*/nullptr, SC_None, 11325 nullptr); 11326 CopyAssignment->setParams(FromParam); 11327 11328 CopyAssignment->setTrivial( 11329 ClassDecl->needsOverloadResolutionForCopyAssignment() 11330 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 11331 : ClassDecl->hasTrivialCopyAssignment()); 11332 11333 // Note that we have added this copy-assignment operator. 11334 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 11335 11336 Scope *S = getScopeForContext(ClassDecl); 11337 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 11338 11339 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 11340 SetDeclDeleted(CopyAssignment, ClassLoc); 11341 11342 if (S) 11343 PushOnScopeChains(CopyAssignment, S, false); 11344 ClassDecl->addDecl(CopyAssignment); 11345 11346 return CopyAssignment; 11347 } 11348 11349 /// Diagnose an implicit copy operation for a class which is odr-used, but 11350 /// which is deprecated because the class has a user-declared copy constructor, 11351 /// copy assignment operator, or destructor. 11352 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 11353 assert(CopyOp->isImplicit()); 11354 11355 CXXRecordDecl *RD = CopyOp->getParent(); 11356 CXXMethodDecl *UserDeclaredOperation = nullptr; 11357 11358 // In Microsoft mode, assignment operations don't affect constructors and 11359 // vice versa. 11360 if (RD->hasUserDeclaredDestructor()) { 11361 UserDeclaredOperation = RD->getDestructor(); 11362 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11363 RD->hasUserDeclaredCopyConstructor() && 11364 !S.getLangOpts().MSVCCompat) { 11365 // Find any user-declared copy constructor. 11366 for (auto *I : RD->ctors()) { 11367 if (I->isCopyConstructor()) { 11368 UserDeclaredOperation = I; 11369 break; 11370 } 11371 } 11372 assert(UserDeclaredOperation); 11373 } else if (isa<CXXConstructorDecl>(CopyOp) && 11374 RD->hasUserDeclaredCopyAssignment() && 11375 !S.getLangOpts().MSVCCompat) { 11376 // Find any user-declared move assignment operator. 11377 for (auto *I : RD->methods()) { 11378 if (I->isCopyAssignmentOperator()) { 11379 UserDeclaredOperation = I; 11380 break; 11381 } 11382 } 11383 assert(UserDeclaredOperation); 11384 } 11385 11386 if (UserDeclaredOperation) { 11387 S.Diag(UserDeclaredOperation->getLocation(), 11388 diag::warn_deprecated_copy_operation) 11389 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11390 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11391 } 11392 } 11393 11394 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11395 CXXMethodDecl *CopyAssignOperator) { 11396 assert((CopyAssignOperator->isDefaulted() && 11397 CopyAssignOperator->isOverloadedOperator() && 11398 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11399 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11400 !CopyAssignOperator->isDeleted()) && 11401 "DefineImplicitCopyAssignment called for wrong function"); 11402 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 11403 return; 11404 11405 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11406 if (ClassDecl->isInvalidDecl()) { 11407 CopyAssignOperator->setInvalidDecl(); 11408 return; 11409 } 11410 11411 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11412 11413 // The exception specification is needed because we are defining the 11414 // function. 11415 ResolveExceptionSpec(CurrentLocation, 11416 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11417 11418 // Add a context note for diagnostics produced after this point. 11419 Scope.addContextNote(CurrentLocation); 11420 11421 // C++11 [class.copy]p18: 11422 // The [definition of an implicitly declared copy assignment operator] is 11423 // deprecated if the class has a user-declared copy constructor or a 11424 // user-declared destructor. 11425 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11426 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 11427 11428 // C++0x [class.copy]p30: 11429 // The implicitly-defined or explicitly-defaulted copy assignment operator 11430 // for a non-union class X performs memberwise copy assignment of its 11431 // subobjects. The direct base classes of X are assigned first, in the 11432 // order of their declaration in the base-specifier-list, and then the 11433 // immediate non-static data members of X are assigned, in the order in 11434 // which they were declared in the class definition. 11435 11436 // The statements that form the synthesized function body. 11437 SmallVector<Stmt*, 8> Statements; 11438 11439 // The parameter for the "other" object, which we are copying from. 11440 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 11441 Qualifiers OtherQuals = Other->getType().getQualifiers(); 11442 QualType OtherRefType = Other->getType(); 11443 if (const LValueReferenceType *OtherRef 11444 = OtherRefType->getAs<LValueReferenceType>()) { 11445 OtherRefType = OtherRef->getPointeeType(); 11446 OtherQuals = OtherRefType.getQualifiers(); 11447 } 11448 11449 // Our location for everything implicitly-generated. 11450 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 11451 ? CopyAssignOperator->getLocEnd() 11452 : CopyAssignOperator->getLocation(); 11453 11454 // Builds a DeclRefExpr for the "other" object. 11455 RefBuilder OtherRef(Other, OtherRefType); 11456 11457 // Builds the "this" pointer. 11458 ThisBuilder This; 11459 11460 // Assign base classes. 11461 bool Invalid = false; 11462 for (auto &Base : ClassDecl->bases()) { 11463 // Form the assignment: 11464 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 11465 QualType BaseType = Base.getType().getUnqualifiedType(); 11466 if (!BaseType->isRecordType()) { 11467 Invalid = true; 11468 continue; 11469 } 11470 11471 CXXCastPath BasePath; 11472 BasePath.push_back(&Base); 11473 11474 // Construct the "from" expression, which is an implicit cast to the 11475 // appropriately-qualified base type. 11476 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 11477 VK_LValue, BasePath); 11478 11479 // Dereference "this". 11480 DerefBuilder DerefThis(This); 11481 CastBuilder To(DerefThis, 11482 Context.getCVRQualifiedType( 11483 BaseType, CopyAssignOperator->getTypeQualifiers()), 11484 VK_LValue, BasePath); 11485 11486 // Build the copy. 11487 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 11488 To, From, 11489 /*CopyingBaseSubobject=*/true, 11490 /*Copying=*/true); 11491 if (Copy.isInvalid()) { 11492 CopyAssignOperator->setInvalidDecl(); 11493 return; 11494 } 11495 11496 // Success! Record the copy. 11497 Statements.push_back(Copy.getAs<Expr>()); 11498 } 11499 11500 // Assign non-static members. 11501 for (auto *Field : ClassDecl->fields()) { 11502 // FIXME: We should form some kind of AST representation for the implied 11503 // memcpy in a union copy operation. 11504 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11505 continue; 11506 11507 if (Field->isInvalidDecl()) { 11508 Invalid = true; 11509 continue; 11510 } 11511 11512 // Check for members of reference type; we can't copy those. 11513 if (Field->getType()->isReferenceType()) { 11514 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11515 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11516 Diag(Field->getLocation(), diag::note_declared_at); 11517 Invalid = true; 11518 continue; 11519 } 11520 11521 // Check for members of const-qualified, non-class type. 11522 QualType BaseType = Context.getBaseElementType(Field->getType()); 11523 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11524 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11525 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11526 Diag(Field->getLocation(), diag::note_declared_at); 11527 Invalid = true; 11528 continue; 11529 } 11530 11531 // Suppress assigning zero-width bitfields. 11532 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11533 continue; 11534 11535 QualType FieldType = Field->getType().getNonReferenceType(); 11536 if (FieldType->isIncompleteArrayType()) { 11537 assert(ClassDecl->hasFlexibleArrayMember() && 11538 "Incomplete array type is not valid"); 11539 continue; 11540 } 11541 11542 // Build references to the field in the object we're copying from and to. 11543 CXXScopeSpec SS; // Intentionally empty 11544 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11545 LookupMemberName); 11546 MemberLookup.addDecl(Field); 11547 MemberLookup.resolveKind(); 11548 11549 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 11550 11551 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 11552 11553 // Build the copy of this field. 11554 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 11555 To, From, 11556 /*CopyingBaseSubobject=*/false, 11557 /*Copying=*/true); 11558 if (Copy.isInvalid()) { 11559 CopyAssignOperator->setInvalidDecl(); 11560 return; 11561 } 11562 11563 // Success! Record the copy. 11564 Statements.push_back(Copy.getAs<Stmt>()); 11565 } 11566 11567 if (!Invalid) { 11568 // Add a "return *this;" 11569 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11570 11571 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11572 if (Return.isInvalid()) 11573 Invalid = true; 11574 else 11575 Statements.push_back(Return.getAs<Stmt>()); 11576 } 11577 11578 if (Invalid) { 11579 CopyAssignOperator->setInvalidDecl(); 11580 return; 11581 } 11582 11583 StmtResult Body; 11584 { 11585 CompoundScopeRAII CompoundScope(*this); 11586 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11587 /*isStmtExpr=*/false); 11588 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11589 } 11590 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 11591 CopyAssignOperator->markUsed(Context); 11592 11593 if (ASTMutationListener *L = getASTMutationListener()) { 11594 L->CompletedImplicitDefinition(CopyAssignOperator); 11595 } 11596 } 11597 11598 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 11599 assert(ClassDecl->needsImplicitMoveAssignment()); 11600 11601 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 11602 if (DSM.isAlreadyBeingDeclared()) 11603 return nullptr; 11604 11605 // Note: The following rules are largely analoguous to the move 11606 // constructor rules. 11607 11608 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11609 QualType RetType = Context.getLValueReferenceType(ArgType); 11610 ArgType = Context.getRValueReferenceType(ArgType); 11611 11612 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11613 CXXMoveAssignment, 11614 false); 11615 11616 // An implicitly-declared move assignment operator is an inline public 11617 // member of its class. 11618 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11619 SourceLocation ClassLoc = ClassDecl->getLocation(); 11620 DeclarationNameInfo NameInfo(Name, ClassLoc); 11621 CXXMethodDecl *MoveAssignment = 11622 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11623 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11624 /*isInline=*/true, Constexpr, SourceLocation()); 11625 MoveAssignment->setAccess(AS_public); 11626 MoveAssignment->setDefaulted(); 11627 MoveAssignment->setImplicit(); 11628 11629 if (getLangOpts().CUDA) { 11630 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 11631 MoveAssignment, 11632 /* ConstRHS */ false, 11633 /* Diagnose */ false); 11634 } 11635 11636 // Build an exception specification pointing back at this member. 11637 FunctionProtoType::ExtProtoInfo EPI = 11638 getImplicitMethodEPI(*this, MoveAssignment); 11639 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11640 11641 // Add the parameter to the operator. 11642 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 11643 ClassLoc, ClassLoc, 11644 /*Id=*/nullptr, ArgType, 11645 /*TInfo=*/nullptr, SC_None, 11646 nullptr); 11647 MoveAssignment->setParams(FromParam); 11648 11649 MoveAssignment->setTrivial( 11650 ClassDecl->needsOverloadResolutionForMoveAssignment() 11651 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 11652 : ClassDecl->hasTrivialMoveAssignment()); 11653 11654 // Note that we have added this copy-assignment operator. 11655 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 11656 11657 Scope *S = getScopeForContext(ClassDecl); 11658 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 11659 11660 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 11661 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 11662 SetDeclDeleted(MoveAssignment, ClassLoc); 11663 } 11664 11665 if (S) 11666 PushOnScopeChains(MoveAssignment, S, false); 11667 ClassDecl->addDecl(MoveAssignment); 11668 11669 return MoveAssignment; 11670 } 11671 11672 /// Check if we're implicitly defining a move assignment operator for a class 11673 /// with virtual bases. Such a move assignment might move-assign the virtual 11674 /// base multiple times. 11675 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 11676 SourceLocation CurrentLocation) { 11677 assert(!Class->isDependentContext() && "should not define dependent move"); 11678 11679 // Only a virtual base could get implicitly move-assigned multiple times. 11680 // Only a non-trivial move assignment can observe this. We only want to 11681 // diagnose if we implicitly define an assignment operator that assigns 11682 // two base classes, both of which move-assign the same virtual base. 11683 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 11684 Class->getNumBases() < 2) 11685 return; 11686 11687 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 11688 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 11689 VBaseMap VBases; 11690 11691 for (auto &BI : Class->bases()) { 11692 Worklist.push_back(&BI); 11693 while (!Worklist.empty()) { 11694 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 11695 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 11696 11697 // If the base has no non-trivial move assignment operators, 11698 // we don't care about moves from it. 11699 if (!Base->hasNonTrivialMoveAssignment()) 11700 continue; 11701 11702 // If there's nothing virtual here, skip it. 11703 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 11704 continue; 11705 11706 // If we're not actually going to call a move assignment for this base, 11707 // or the selected move assignment is trivial, skip it. 11708 Sema::SpecialMemberOverloadResult SMOR = 11709 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 11710 /*ConstArg*/false, /*VolatileArg*/false, 11711 /*RValueThis*/true, /*ConstThis*/false, 11712 /*VolatileThis*/false); 11713 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 11714 !SMOR.getMethod()->isMoveAssignmentOperator()) 11715 continue; 11716 11717 if (BaseSpec->isVirtual()) { 11718 // We're going to move-assign this virtual base, and its move 11719 // assignment operator is not trivial. If this can happen for 11720 // multiple distinct direct bases of Class, diagnose it. (If it 11721 // only happens in one base, we'll diagnose it when synthesizing 11722 // that base class's move assignment operator.) 11723 CXXBaseSpecifier *&Existing = 11724 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 11725 .first->second; 11726 if (Existing && Existing != &BI) { 11727 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 11728 << Class << Base; 11729 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 11730 << (Base->getCanonicalDecl() == 11731 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11732 << Base << Existing->getType() << Existing->getSourceRange(); 11733 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 11734 << (Base->getCanonicalDecl() == 11735 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11736 << Base << BI.getType() << BaseSpec->getSourceRange(); 11737 11738 // Only diagnose each vbase once. 11739 Existing = nullptr; 11740 } 11741 } else { 11742 // Only walk over bases that have defaulted move assignment operators. 11743 // We assume that any user-provided move assignment operator handles 11744 // the multiple-moves-of-vbase case itself somehow. 11745 if (!SMOR.getMethod()->isDefaulted()) 11746 continue; 11747 11748 // We're going to move the base classes of Base. Add them to the list. 11749 for (auto &BI : Base->bases()) 11750 Worklist.push_back(&BI); 11751 } 11752 } 11753 } 11754 } 11755 11756 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 11757 CXXMethodDecl *MoveAssignOperator) { 11758 assert((MoveAssignOperator->isDefaulted() && 11759 MoveAssignOperator->isOverloadedOperator() && 11760 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 11761 !MoveAssignOperator->doesThisDeclarationHaveABody() && 11762 !MoveAssignOperator->isDeleted()) && 11763 "DefineImplicitMoveAssignment called for wrong function"); 11764 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 11765 return; 11766 11767 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 11768 if (ClassDecl->isInvalidDecl()) { 11769 MoveAssignOperator->setInvalidDecl(); 11770 return; 11771 } 11772 11773 // C++0x [class.copy]p28: 11774 // The implicitly-defined or move assignment operator for a non-union class 11775 // X performs memberwise move assignment of its subobjects. The direct base 11776 // classes of X are assigned first, in the order of their declaration in the 11777 // base-specifier-list, and then the immediate non-static data members of X 11778 // are assigned, in the order in which they were declared in the class 11779 // definition. 11780 11781 // Issue a warning if our implicit move assignment operator will move 11782 // from a virtual base more than once. 11783 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 11784 11785 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 11786 11787 // The exception specification is needed because we are defining the 11788 // function. 11789 ResolveExceptionSpec(CurrentLocation, 11790 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 11791 11792 // Add a context note for diagnostics produced after this point. 11793 Scope.addContextNote(CurrentLocation); 11794 11795 // The statements that form the synthesized function body. 11796 SmallVector<Stmt*, 8> Statements; 11797 11798 // The parameter for the "other" object, which we are move from. 11799 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 11800 QualType OtherRefType = Other->getType()-> 11801 getAs<RValueReferenceType>()->getPointeeType(); 11802 assert(!OtherRefType.getQualifiers() && 11803 "Bad argument type of defaulted move assignment"); 11804 11805 // Our location for everything implicitly-generated. 11806 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 11807 ? MoveAssignOperator->getLocEnd() 11808 : MoveAssignOperator->getLocation(); 11809 11810 // Builds a reference to the "other" object. 11811 RefBuilder OtherRef(Other, OtherRefType); 11812 // Cast to rvalue. 11813 MoveCastBuilder MoveOther(OtherRef); 11814 11815 // Builds the "this" pointer. 11816 ThisBuilder This; 11817 11818 // Assign base classes. 11819 bool Invalid = false; 11820 for (auto &Base : ClassDecl->bases()) { 11821 // C++11 [class.copy]p28: 11822 // It is unspecified whether subobjects representing virtual base classes 11823 // are assigned more than once by the implicitly-defined copy assignment 11824 // operator. 11825 // FIXME: Do not assign to a vbase that will be assigned by some other base 11826 // class. For a move-assignment, this can result in the vbase being moved 11827 // multiple times. 11828 11829 // Form the assignment: 11830 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 11831 QualType BaseType = Base.getType().getUnqualifiedType(); 11832 if (!BaseType->isRecordType()) { 11833 Invalid = true; 11834 continue; 11835 } 11836 11837 CXXCastPath BasePath; 11838 BasePath.push_back(&Base); 11839 11840 // Construct the "from" expression, which is an implicit cast to the 11841 // appropriately-qualified base type. 11842 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 11843 11844 // Dereference "this". 11845 DerefBuilder DerefThis(This); 11846 11847 // Implicitly cast "this" to the appropriately-qualified base type. 11848 CastBuilder To(DerefThis, 11849 Context.getCVRQualifiedType( 11850 BaseType, MoveAssignOperator->getTypeQualifiers()), 11851 VK_LValue, BasePath); 11852 11853 // Build the move. 11854 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 11855 To, From, 11856 /*CopyingBaseSubobject=*/true, 11857 /*Copying=*/false); 11858 if (Move.isInvalid()) { 11859 MoveAssignOperator->setInvalidDecl(); 11860 return; 11861 } 11862 11863 // Success! Record the move. 11864 Statements.push_back(Move.getAs<Expr>()); 11865 } 11866 11867 // Assign non-static members. 11868 for (auto *Field : ClassDecl->fields()) { 11869 // FIXME: We should form some kind of AST representation for the implied 11870 // memcpy in a union copy operation. 11871 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11872 continue; 11873 11874 if (Field->isInvalidDecl()) { 11875 Invalid = true; 11876 continue; 11877 } 11878 11879 // Check for members of reference type; we can't move those. 11880 if (Field->getType()->isReferenceType()) { 11881 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11882 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11883 Diag(Field->getLocation(), diag::note_declared_at); 11884 Invalid = true; 11885 continue; 11886 } 11887 11888 // Check for members of const-qualified, non-class type. 11889 QualType BaseType = Context.getBaseElementType(Field->getType()); 11890 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11891 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11892 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11893 Diag(Field->getLocation(), diag::note_declared_at); 11894 Invalid = true; 11895 continue; 11896 } 11897 11898 // Suppress assigning zero-width bitfields. 11899 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11900 continue; 11901 11902 QualType FieldType = Field->getType().getNonReferenceType(); 11903 if (FieldType->isIncompleteArrayType()) { 11904 assert(ClassDecl->hasFlexibleArrayMember() && 11905 "Incomplete array type is not valid"); 11906 continue; 11907 } 11908 11909 // Build references to the field in the object we're copying from and to. 11910 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11911 LookupMemberName); 11912 MemberLookup.addDecl(Field); 11913 MemberLookup.resolveKind(); 11914 MemberBuilder From(MoveOther, OtherRefType, 11915 /*IsArrow=*/false, MemberLookup); 11916 MemberBuilder To(This, getCurrentThisType(), 11917 /*IsArrow=*/true, MemberLookup); 11918 11919 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 11920 "Member reference with rvalue base must be rvalue except for reference " 11921 "members, which aren't allowed for move assignment."); 11922 11923 // Build the move of this field. 11924 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 11925 To, From, 11926 /*CopyingBaseSubobject=*/false, 11927 /*Copying=*/false); 11928 if (Move.isInvalid()) { 11929 MoveAssignOperator->setInvalidDecl(); 11930 return; 11931 } 11932 11933 // Success! Record the copy. 11934 Statements.push_back(Move.getAs<Stmt>()); 11935 } 11936 11937 if (!Invalid) { 11938 // Add a "return *this;" 11939 ExprResult ThisObj = 11940 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11941 11942 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11943 if (Return.isInvalid()) 11944 Invalid = true; 11945 else 11946 Statements.push_back(Return.getAs<Stmt>()); 11947 } 11948 11949 if (Invalid) { 11950 MoveAssignOperator->setInvalidDecl(); 11951 return; 11952 } 11953 11954 StmtResult Body; 11955 { 11956 CompoundScopeRAII CompoundScope(*this); 11957 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11958 /*isStmtExpr=*/false); 11959 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11960 } 11961 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 11962 MoveAssignOperator->markUsed(Context); 11963 11964 if (ASTMutationListener *L = getASTMutationListener()) { 11965 L->CompletedImplicitDefinition(MoveAssignOperator); 11966 } 11967 } 11968 11969 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 11970 CXXRecordDecl *ClassDecl) { 11971 // C++ [class.copy]p4: 11972 // If the class definition does not explicitly declare a copy 11973 // constructor, one is declared implicitly. 11974 assert(ClassDecl->needsImplicitCopyConstructor()); 11975 11976 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 11977 if (DSM.isAlreadyBeingDeclared()) 11978 return nullptr; 11979 11980 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11981 QualType ArgType = ClassType; 11982 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 11983 if (Const) 11984 ArgType = ArgType.withConst(); 11985 ArgType = Context.getLValueReferenceType(ArgType); 11986 11987 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11988 CXXCopyConstructor, 11989 Const); 11990 11991 DeclarationName Name 11992 = Context.DeclarationNames.getCXXConstructorName( 11993 Context.getCanonicalType(ClassType)); 11994 SourceLocation ClassLoc = ClassDecl->getLocation(); 11995 DeclarationNameInfo NameInfo(Name, ClassLoc); 11996 11997 // An implicitly-declared copy constructor is an inline public 11998 // member of its class. 11999 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 12000 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12001 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12002 Constexpr); 12003 CopyConstructor->setAccess(AS_public); 12004 CopyConstructor->setDefaulted(); 12005 12006 if (getLangOpts().CUDA) { 12007 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 12008 CopyConstructor, 12009 /* ConstRHS */ Const, 12010 /* Diagnose */ false); 12011 } 12012 12013 // Build an exception specification pointing back at this member. 12014 FunctionProtoType::ExtProtoInfo EPI = 12015 getImplicitMethodEPI(*this, CopyConstructor); 12016 CopyConstructor->setType( 12017 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12018 12019 // Add the parameter to the constructor. 12020 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 12021 ClassLoc, ClassLoc, 12022 /*IdentifierInfo=*/nullptr, 12023 ArgType, /*TInfo=*/nullptr, 12024 SC_None, nullptr); 12025 CopyConstructor->setParams(FromParam); 12026 12027 CopyConstructor->setTrivial( 12028 ClassDecl->needsOverloadResolutionForCopyConstructor() 12029 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 12030 : ClassDecl->hasTrivialCopyConstructor()); 12031 12032 // Note that we have declared this constructor. 12033 ++ASTContext::NumImplicitCopyConstructorsDeclared; 12034 12035 Scope *S = getScopeForContext(ClassDecl); 12036 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 12037 12038 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 12039 ClassDecl->setImplicitCopyConstructorIsDeleted(); 12040 SetDeclDeleted(CopyConstructor, ClassLoc); 12041 } 12042 12043 if (S) 12044 PushOnScopeChains(CopyConstructor, S, false); 12045 ClassDecl->addDecl(CopyConstructor); 12046 12047 return CopyConstructor; 12048 } 12049 12050 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 12051 CXXConstructorDecl *CopyConstructor) { 12052 assert((CopyConstructor->isDefaulted() && 12053 CopyConstructor->isCopyConstructor() && 12054 !CopyConstructor->doesThisDeclarationHaveABody() && 12055 !CopyConstructor->isDeleted()) && 12056 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12057 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12058 return; 12059 12060 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12061 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12062 12063 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12064 12065 // The exception specification is needed because we are defining the 12066 // function. 12067 ResolveExceptionSpec(CurrentLocation, 12068 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12069 MarkVTableUsed(CurrentLocation, ClassDecl); 12070 12071 // Add a context note for diagnostics produced after this point. 12072 Scope.addContextNote(CurrentLocation); 12073 12074 // C++11 [class.copy]p7: 12075 // The [definition of an implicitly declared copy constructor] is 12076 // deprecated if the class has a user-declared copy assignment operator 12077 // or a user-declared destructor. 12078 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12079 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12080 12081 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12082 CopyConstructor->setInvalidDecl(); 12083 } else { 12084 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 12085 ? CopyConstructor->getLocEnd() 12086 : CopyConstructor->getLocation(); 12087 Sema::CompoundScopeRAII CompoundScope(*this); 12088 CopyConstructor->setBody( 12089 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12090 CopyConstructor->markUsed(Context); 12091 } 12092 12093 if (ASTMutationListener *L = getASTMutationListener()) { 12094 L->CompletedImplicitDefinition(CopyConstructor); 12095 } 12096 } 12097 12098 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12099 CXXRecordDecl *ClassDecl) { 12100 assert(ClassDecl->needsImplicitMoveConstructor()); 12101 12102 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12103 if (DSM.isAlreadyBeingDeclared()) 12104 return nullptr; 12105 12106 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12107 QualType ArgType = Context.getRValueReferenceType(ClassType); 12108 12109 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12110 CXXMoveConstructor, 12111 false); 12112 12113 DeclarationName Name 12114 = Context.DeclarationNames.getCXXConstructorName( 12115 Context.getCanonicalType(ClassType)); 12116 SourceLocation ClassLoc = ClassDecl->getLocation(); 12117 DeclarationNameInfo NameInfo(Name, ClassLoc); 12118 12119 // C++11 [class.copy]p11: 12120 // An implicitly-declared copy/move constructor is an inline public 12121 // member of its class. 12122 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12123 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12124 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12125 Constexpr); 12126 MoveConstructor->setAccess(AS_public); 12127 MoveConstructor->setDefaulted(); 12128 12129 if (getLangOpts().CUDA) { 12130 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12131 MoveConstructor, 12132 /* ConstRHS */ false, 12133 /* Diagnose */ false); 12134 } 12135 12136 // Build an exception specification pointing back at this member. 12137 FunctionProtoType::ExtProtoInfo EPI = 12138 getImplicitMethodEPI(*this, MoveConstructor); 12139 MoveConstructor->setType( 12140 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12141 12142 // Add the parameter to the constructor. 12143 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12144 ClassLoc, ClassLoc, 12145 /*IdentifierInfo=*/nullptr, 12146 ArgType, /*TInfo=*/nullptr, 12147 SC_None, nullptr); 12148 MoveConstructor->setParams(FromParam); 12149 12150 MoveConstructor->setTrivial( 12151 ClassDecl->needsOverloadResolutionForMoveConstructor() 12152 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12153 : ClassDecl->hasTrivialMoveConstructor()); 12154 12155 // Note that we have declared this constructor. 12156 ++ASTContext::NumImplicitMoveConstructorsDeclared; 12157 12158 Scope *S = getScopeForContext(ClassDecl); 12159 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12160 12161 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12162 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12163 SetDeclDeleted(MoveConstructor, ClassLoc); 12164 } 12165 12166 if (S) 12167 PushOnScopeChains(MoveConstructor, S, false); 12168 ClassDecl->addDecl(MoveConstructor); 12169 12170 return MoveConstructor; 12171 } 12172 12173 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12174 CXXConstructorDecl *MoveConstructor) { 12175 assert((MoveConstructor->isDefaulted() && 12176 MoveConstructor->isMoveConstructor() && 12177 !MoveConstructor->doesThisDeclarationHaveABody() && 12178 !MoveConstructor->isDeleted()) && 12179 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12180 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12181 return; 12182 12183 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12184 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12185 12186 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12187 12188 // The exception specification is needed because we are defining the 12189 // function. 12190 ResolveExceptionSpec(CurrentLocation, 12191 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12192 MarkVTableUsed(CurrentLocation, ClassDecl); 12193 12194 // Add a context note for diagnostics produced after this point. 12195 Scope.addContextNote(CurrentLocation); 12196 12197 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12198 MoveConstructor->setInvalidDecl(); 12199 } else { 12200 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 12201 ? MoveConstructor->getLocEnd() 12202 : MoveConstructor->getLocation(); 12203 Sema::CompoundScopeRAII CompoundScope(*this); 12204 MoveConstructor->setBody(ActOnCompoundStmt( 12205 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12206 MoveConstructor->markUsed(Context); 12207 } 12208 12209 if (ASTMutationListener *L = getASTMutationListener()) { 12210 L->CompletedImplicitDefinition(MoveConstructor); 12211 } 12212 } 12213 12214 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12215 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12216 } 12217 12218 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12219 SourceLocation CurrentLocation, 12220 CXXConversionDecl *Conv) { 12221 SynthesizedFunctionScope Scope(*this, Conv); 12222 12223 CXXRecordDecl *Lambda = Conv->getParent(); 12224 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 12225 // If we are defining a specialization of a conversion to function-ptr 12226 // cache the deduced template arguments for this specialization 12227 // so that we can use them to retrieve the corresponding call-operator 12228 // and static-invoker. 12229 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 12230 12231 // Retrieve the corresponding call-operator specialization. 12232 if (Lambda->isGenericLambda()) { 12233 assert(Conv->isFunctionTemplateSpecialization()); 12234 FunctionTemplateDecl *CallOpTemplate = 12235 CallOp->getDescribedFunctionTemplate(); 12236 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 12237 void *InsertPos = nullptr; 12238 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 12239 DeducedTemplateArgs->asArray(), 12240 InsertPos); 12241 assert(CallOpSpec && 12242 "Conversion operator must have a corresponding call operator"); 12243 CallOp = cast<CXXMethodDecl>(CallOpSpec); 12244 } 12245 12246 // Mark the call operator referenced (and add to pending instantiations 12247 // if necessary). 12248 // For both the conversion and static-invoker template specializations 12249 // we construct their body's in this function, so no need to add them 12250 // to the PendingInstantiations. 12251 MarkFunctionReferenced(CurrentLocation, CallOp); 12252 12253 // Retrieve the static invoker... 12254 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12255 // ... and get the corresponding specialization for a generic lambda. 12256 if (Lambda->isGenericLambda()) { 12257 assert(DeducedTemplateArgs && 12258 "Must have deduced template arguments from Conversion Operator"); 12259 FunctionTemplateDecl *InvokeTemplate = 12260 Invoker->getDescribedFunctionTemplate(); 12261 void *InsertPos = nullptr; 12262 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 12263 DeducedTemplateArgs->asArray(), 12264 InsertPos); 12265 assert(InvokeSpec && 12266 "Must have a corresponding static invoker specialization"); 12267 Invoker = cast<CXXMethodDecl>(InvokeSpec); 12268 } 12269 // Construct the body of the conversion function { return __invoke; }. 12270 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12271 VK_LValue, Conv->getLocation()).get(); 12272 assert(FunctionRef && "Can't refer to __invoke function?"); 12273 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12274 Conv->setBody(new (Context) CompoundStmt(Context, Return, 12275 Conv->getLocation(), 12276 Conv->getLocation())); 12277 12278 Conv->markUsed(Context); 12279 Conv->setReferenced(); 12280 12281 // Fill in the __invoke function with a dummy implementation. IR generation 12282 // will fill in the actual details. 12283 Invoker->markUsed(Context); 12284 Invoker->setReferenced(); 12285 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12286 12287 if (ASTMutationListener *L = getASTMutationListener()) { 12288 L->CompletedImplicitDefinition(Conv); 12289 L->CompletedImplicitDefinition(Invoker); 12290 } 12291 } 12292 12293 12294 12295 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12296 SourceLocation CurrentLocation, 12297 CXXConversionDecl *Conv) 12298 { 12299 assert(!Conv->getParent()->isGenericLambda()); 12300 12301 SynthesizedFunctionScope Scope(*this, Conv); 12302 12303 // Copy-initialize the lambda object as needed to capture it. 12304 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12305 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12306 12307 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12308 Conv->getLocation(), 12309 Conv, DerefThis); 12310 12311 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12312 // behavior. Note that only the general conversion function does this 12313 // (since it's unusable otherwise); in the case where we inline the 12314 // block literal, it has block literal lifetime semantics. 12315 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12316 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12317 CK_CopyAndAutoreleaseBlockObject, 12318 BuildBlock.get(), nullptr, VK_RValue); 12319 12320 if (BuildBlock.isInvalid()) { 12321 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12322 Conv->setInvalidDecl(); 12323 return; 12324 } 12325 12326 // Create the return statement that returns the block from the conversion 12327 // function. 12328 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12329 if (Return.isInvalid()) { 12330 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12331 Conv->setInvalidDecl(); 12332 return; 12333 } 12334 12335 // Set the body of the conversion function. 12336 Stmt *ReturnS = Return.get(); 12337 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 12338 Conv->getLocation(), 12339 Conv->getLocation())); 12340 Conv->markUsed(Context); 12341 12342 // We're done; notify the mutation listener, if any. 12343 if (ASTMutationListener *L = getASTMutationListener()) { 12344 L->CompletedImplicitDefinition(Conv); 12345 } 12346 } 12347 12348 /// \brief Determine whether the given list arguments contains exactly one 12349 /// "real" (non-default) argument. 12350 static bool hasOneRealArgument(MultiExprArg Args) { 12351 switch (Args.size()) { 12352 case 0: 12353 return false; 12354 12355 default: 12356 if (!Args[1]->isDefaultArgument()) 12357 return false; 12358 12359 // fall through 12360 case 1: 12361 return !Args[0]->isDefaultArgument(); 12362 } 12363 12364 return false; 12365 } 12366 12367 ExprResult 12368 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12369 NamedDecl *FoundDecl, 12370 CXXConstructorDecl *Constructor, 12371 MultiExprArg ExprArgs, 12372 bool HadMultipleCandidates, 12373 bool IsListInitialization, 12374 bool IsStdInitListInitialization, 12375 bool RequiresZeroInit, 12376 unsigned ConstructKind, 12377 SourceRange ParenRange) { 12378 bool Elidable = false; 12379 12380 // C++0x [class.copy]p34: 12381 // When certain criteria are met, an implementation is allowed to 12382 // omit the copy/move construction of a class object, even if the 12383 // copy/move constructor and/or destructor for the object have 12384 // side effects. [...] 12385 // - when a temporary class object that has not been bound to a 12386 // reference (12.2) would be copied/moved to a class object 12387 // with the same cv-unqualified type, the copy/move operation 12388 // can be omitted by constructing the temporary object 12389 // directly into the target of the omitted copy/move 12390 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12391 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12392 Expr *SubExpr = ExprArgs[0]; 12393 Elidable = SubExpr->isTemporaryObject( 12394 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12395 } 12396 12397 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12398 FoundDecl, Constructor, 12399 Elidable, ExprArgs, HadMultipleCandidates, 12400 IsListInitialization, 12401 IsStdInitListInitialization, RequiresZeroInit, 12402 ConstructKind, ParenRange); 12403 } 12404 12405 ExprResult 12406 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12407 NamedDecl *FoundDecl, 12408 CXXConstructorDecl *Constructor, 12409 bool Elidable, 12410 MultiExprArg ExprArgs, 12411 bool HadMultipleCandidates, 12412 bool IsListInitialization, 12413 bool IsStdInitListInitialization, 12414 bool RequiresZeroInit, 12415 unsigned ConstructKind, 12416 SourceRange ParenRange) { 12417 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12418 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12419 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12420 return ExprError(); 12421 } 12422 12423 return BuildCXXConstructExpr( 12424 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12425 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12426 RequiresZeroInit, ConstructKind, ParenRange); 12427 } 12428 12429 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12430 /// including handling of its default argument expressions. 12431 ExprResult 12432 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12433 CXXConstructorDecl *Constructor, 12434 bool Elidable, 12435 MultiExprArg ExprArgs, 12436 bool HadMultipleCandidates, 12437 bool IsListInitialization, 12438 bool IsStdInitListInitialization, 12439 bool RequiresZeroInit, 12440 unsigned ConstructKind, 12441 SourceRange ParenRange) { 12442 assert(declaresSameEntity( 12443 Constructor->getParent(), 12444 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 12445 "given constructor for wrong type"); 12446 MarkFunctionReferenced(ConstructLoc, Constructor); 12447 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 12448 return ExprError(); 12449 12450 return CXXConstructExpr::Create( 12451 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 12452 ExprArgs, HadMultipleCandidates, IsListInitialization, 12453 IsStdInitListInitialization, RequiresZeroInit, 12454 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 12455 ParenRange); 12456 } 12457 12458 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 12459 assert(Field->hasInClassInitializer()); 12460 12461 // If we already have the in-class initializer nothing needs to be done. 12462 if (Field->getInClassInitializer()) 12463 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12464 12465 // If we might have already tried and failed to instantiate, don't try again. 12466 if (Field->isInvalidDecl()) 12467 return ExprError(); 12468 12469 // Maybe we haven't instantiated the in-class initializer. Go check the 12470 // pattern FieldDecl to see if it has one. 12471 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 12472 12473 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 12474 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 12475 DeclContext::lookup_result Lookup = 12476 ClassPattern->lookup(Field->getDeclName()); 12477 12478 // Lookup can return at most two results: the pattern for the field, or the 12479 // injected class name of the parent record. No other member can have the 12480 // same name as the field. 12481 // In modules mode, lookup can return multiple results (coming from 12482 // different modules). 12483 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 12484 "more than two lookup results for field name"); 12485 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 12486 if (!Pattern) { 12487 assert(isa<CXXRecordDecl>(Lookup[0]) && 12488 "cannot have other non-field member with same name"); 12489 for (auto L : Lookup) 12490 if (isa<FieldDecl>(L)) { 12491 Pattern = cast<FieldDecl>(L); 12492 break; 12493 } 12494 assert(Pattern && "We must have set the Pattern!"); 12495 } 12496 12497 if (!Pattern->hasInClassInitializer() || 12498 InstantiateInClassInitializer(Loc, Field, Pattern, 12499 getTemplateInstantiationArgs(Field))) { 12500 // Don't diagnose this again. 12501 Field->setInvalidDecl(); 12502 return ExprError(); 12503 } 12504 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12505 } 12506 12507 // DR1351: 12508 // If the brace-or-equal-initializer of a non-static data member 12509 // invokes a defaulted default constructor of its class or of an 12510 // enclosing class in a potentially evaluated subexpression, the 12511 // program is ill-formed. 12512 // 12513 // This resolution is unworkable: the exception specification of the 12514 // default constructor can be needed in an unevaluated context, in 12515 // particular, in the operand of a noexcept-expression, and we can be 12516 // unable to compute an exception specification for an enclosed class. 12517 // 12518 // Any attempt to resolve the exception specification of a defaulted default 12519 // constructor before the initializer is lexically complete will ultimately 12520 // come here at which point we can diagnose it. 12521 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 12522 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 12523 << OutermostClass << Field; 12524 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed); 12525 // Recover by marking the field invalid, unless we're in a SFINAE context. 12526 if (!isSFINAEContext()) 12527 Field->setInvalidDecl(); 12528 return ExprError(); 12529 } 12530 12531 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 12532 if (VD->isInvalidDecl()) return; 12533 12534 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 12535 if (ClassDecl->isInvalidDecl()) return; 12536 if (ClassDecl->hasIrrelevantDestructor()) return; 12537 if (ClassDecl->isDependentContext()) return; 12538 12539 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12540 MarkFunctionReferenced(VD->getLocation(), Destructor); 12541 CheckDestructorAccess(VD->getLocation(), Destructor, 12542 PDiag(diag::err_access_dtor_var) 12543 << VD->getDeclName() 12544 << VD->getType()); 12545 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 12546 12547 if (Destructor->isTrivial()) return; 12548 if (!VD->hasGlobalStorage()) return; 12549 12550 // Emit warning for non-trivial dtor in global scope (a real global, 12551 // class-static, function-static). 12552 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 12553 12554 // TODO: this should be re-enabled for static locals by !CXAAtExit 12555 if (!VD->isStaticLocal()) 12556 Diag(VD->getLocation(), diag::warn_global_destructor); 12557 } 12558 12559 /// \brief Given a constructor and the set of arguments provided for the 12560 /// constructor, convert the arguments and add any required default arguments 12561 /// to form a proper call to this constructor. 12562 /// 12563 /// \returns true if an error occurred, false otherwise. 12564 bool 12565 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 12566 MultiExprArg ArgsPtr, 12567 SourceLocation Loc, 12568 SmallVectorImpl<Expr*> &ConvertedArgs, 12569 bool AllowExplicit, 12570 bool IsListInitialization) { 12571 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 12572 unsigned NumArgs = ArgsPtr.size(); 12573 Expr **Args = ArgsPtr.data(); 12574 12575 const FunctionProtoType *Proto 12576 = Constructor->getType()->getAs<FunctionProtoType>(); 12577 assert(Proto && "Constructor without a prototype?"); 12578 unsigned NumParams = Proto->getNumParams(); 12579 12580 // If too few arguments are available, we'll fill in the rest with defaults. 12581 if (NumArgs < NumParams) 12582 ConvertedArgs.reserve(NumParams); 12583 else 12584 ConvertedArgs.reserve(NumArgs); 12585 12586 VariadicCallType CallType = 12587 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 12588 SmallVector<Expr *, 8> AllArgs; 12589 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 12590 Proto, 0, 12591 llvm::makeArrayRef(Args, NumArgs), 12592 AllArgs, 12593 CallType, AllowExplicit, 12594 IsListInitialization); 12595 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 12596 12597 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 12598 12599 CheckConstructorCall(Constructor, 12600 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 12601 Proto, Loc); 12602 12603 return Invalid; 12604 } 12605 12606 static inline bool 12607 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 12608 const FunctionDecl *FnDecl) { 12609 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 12610 if (isa<NamespaceDecl>(DC)) { 12611 return SemaRef.Diag(FnDecl->getLocation(), 12612 diag::err_operator_new_delete_declared_in_namespace) 12613 << FnDecl->getDeclName(); 12614 } 12615 12616 if (isa<TranslationUnitDecl>(DC) && 12617 FnDecl->getStorageClass() == SC_Static) { 12618 return SemaRef.Diag(FnDecl->getLocation(), 12619 diag::err_operator_new_delete_declared_static) 12620 << FnDecl->getDeclName(); 12621 } 12622 12623 return false; 12624 } 12625 12626 static inline bool 12627 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 12628 CanQualType ExpectedResultType, 12629 CanQualType ExpectedFirstParamType, 12630 unsigned DependentParamTypeDiag, 12631 unsigned InvalidParamTypeDiag) { 12632 QualType ResultType = 12633 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 12634 12635 // Check that the result type is not dependent. 12636 if (ResultType->isDependentType()) 12637 return SemaRef.Diag(FnDecl->getLocation(), 12638 diag::err_operator_new_delete_dependent_result_type) 12639 << FnDecl->getDeclName() << ExpectedResultType; 12640 12641 // Check that the result type is what we expect. 12642 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 12643 return SemaRef.Diag(FnDecl->getLocation(), 12644 diag::err_operator_new_delete_invalid_result_type) 12645 << FnDecl->getDeclName() << ExpectedResultType; 12646 12647 // A function template must have at least 2 parameters. 12648 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 12649 return SemaRef.Diag(FnDecl->getLocation(), 12650 diag::err_operator_new_delete_template_too_few_parameters) 12651 << FnDecl->getDeclName(); 12652 12653 // The function decl must have at least 1 parameter. 12654 if (FnDecl->getNumParams() == 0) 12655 return SemaRef.Diag(FnDecl->getLocation(), 12656 diag::err_operator_new_delete_too_few_parameters) 12657 << FnDecl->getDeclName(); 12658 12659 // Check the first parameter type is not dependent. 12660 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 12661 if (FirstParamType->isDependentType()) 12662 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 12663 << FnDecl->getDeclName() << ExpectedFirstParamType; 12664 12665 // Check that the first parameter type is what we expect. 12666 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 12667 ExpectedFirstParamType) 12668 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 12669 << FnDecl->getDeclName() << ExpectedFirstParamType; 12670 12671 return false; 12672 } 12673 12674 static bool 12675 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 12676 // C++ [basic.stc.dynamic.allocation]p1: 12677 // A program is ill-formed if an allocation function is declared in a 12678 // namespace scope other than global scope or declared static in global 12679 // scope. 12680 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12681 return true; 12682 12683 CanQualType SizeTy = 12684 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 12685 12686 // C++ [basic.stc.dynamic.allocation]p1: 12687 // The return type shall be void*. The first parameter shall have type 12688 // std::size_t. 12689 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 12690 SizeTy, 12691 diag::err_operator_new_dependent_param_type, 12692 diag::err_operator_new_param_type)) 12693 return true; 12694 12695 // C++ [basic.stc.dynamic.allocation]p1: 12696 // The first parameter shall not have an associated default argument. 12697 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 12698 return SemaRef.Diag(FnDecl->getLocation(), 12699 diag::err_operator_new_default_arg) 12700 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 12701 12702 return false; 12703 } 12704 12705 static bool 12706 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 12707 // C++ [basic.stc.dynamic.deallocation]p1: 12708 // A program is ill-formed if deallocation functions are declared in a 12709 // namespace scope other than global scope or declared static in global 12710 // scope. 12711 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12712 return true; 12713 12714 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 12715 12716 // C++ P0722: 12717 // Within a class C, the first parameter of a destroying operator delete 12718 // shall be of type C *. The first parameter of any other deallocation 12719 // function shall be of type void *. 12720 CanQualType ExpectedFirstParamType = 12721 MD && MD->isDestroyingOperatorDelete() 12722 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 12723 SemaRef.Context.getRecordType(MD->getParent()))) 12724 : SemaRef.Context.VoidPtrTy; 12725 12726 // C++ [basic.stc.dynamic.deallocation]p2: 12727 // Each deallocation function shall return void 12728 if (CheckOperatorNewDeleteTypes( 12729 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 12730 diag::err_operator_delete_dependent_param_type, 12731 diag::err_operator_delete_param_type)) 12732 return true; 12733 12734 // C++ P0722: 12735 // A destroying operator delete shall be a usual deallocation function. 12736 if (MD && !MD->getParent()->isDependentContext() && 12737 MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) { 12738 SemaRef.Diag(MD->getLocation(), 12739 diag::err_destroying_operator_delete_not_usual); 12740 return true; 12741 } 12742 12743 return false; 12744 } 12745 12746 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 12747 /// of this overloaded operator is well-formed. If so, returns false; 12748 /// otherwise, emits appropriate diagnostics and returns true. 12749 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 12750 assert(FnDecl && FnDecl->isOverloadedOperator() && 12751 "Expected an overloaded operator declaration"); 12752 12753 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 12754 12755 // C++ [over.oper]p5: 12756 // The allocation and deallocation functions, operator new, 12757 // operator new[], operator delete and operator delete[], are 12758 // described completely in 3.7.3. The attributes and restrictions 12759 // found in the rest of this subclause do not apply to them unless 12760 // explicitly stated in 3.7.3. 12761 if (Op == OO_Delete || Op == OO_Array_Delete) 12762 return CheckOperatorDeleteDeclaration(*this, FnDecl); 12763 12764 if (Op == OO_New || Op == OO_Array_New) 12765 return CheckOperatorNewDeclaration(*this, FnDecl); 12766 12767 // C++ [over.oper]p6: 12768 // An operator function shall either be a non-static member 12769 // function or be a non-member function and have at least one 12770 // parameter whose type is a class, a reference to a class, an 12771 // enumeration, or a reference to an enumeration. 12772 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 12773 if (MethodDecl->isStatic()) 12774 return Diag(FnDecl->getLocation(), 12775 diag::err_operator_overload_static) << FnDecl->getDeclName(); 12776 } else { 12777 bool ClassOrEnumParam = false; 12778 for (auto Param : FnDecl->parameters()) { 12779 QualType ParamType = Param->getType().getNonReferenceType(); 12780 if (ParamType->isDependentType() || ParamType->isRecordType() || 12781 ParamType->isEnumeralType()) { 12782 ClassOrEnumParam = true; 12783 break; 12784 } 12785 } 12786 12787 if (!ClassOrEnumParam) 12788 return Diag(FnDecl->getLocation(), 12789 diag::err_operator_overload_needs_class_or_enum) 12790 << FnDecl->getDeclName(); 12791 } 12792 12793 // C++ [over.oper]p8: 12794 // An operator function cannot have default arguments (8.3.6), 12795 // except where explicitly stated below. 12796 // 12797 // Only the function-call operator allows default arguments 12798 // (C++ [over.call]p1). 12799 if (Op != OO_Call) { 12800 for (auto Param : FnDecl->parameters()) { 12801 if (Param->hasDefaultArg()) 12802 return Diag(Param->getLocation(), 12803 diag::err_operator_overload_default_arg) 12804 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 12805 } 12806 } 12807 12808 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 12809 { false, false, false } 12810 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 12811 , { Unary, Binary, MemberOnly } 12812 #include "clang/Basic/OperatorKinds.def" 12813 }; 12814 12815 bool CanBeUnaryOperator = OperatorUses[Op][0]; 12816 bool CanBeBinaryOperator = OperatorUses[Op][1]; 12817 bool MustBeMemberOperator = OperatorUses[Op][2]; 12818 12819 // C++ [over.oper]p8: 12820 // [...] Operator functions cannot have more or fewer parameters 12821 // than the number required for the corresponding operator, as 12822 // described in the rest of this subclause. 12823 unsigned NumParams = FnDecl->getNumParams() 12824 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 12825 if (Op != OO_Call && 12826 ((NumParams == 1 && !CanBeUnaryOperator) || 12827 (NumParams == 2 && !CanBeBinaryOperator) || 12828 (NumParams < 1) || (NumParams > 2))) { 12829 // We have the wrong number of parameters. 12830 unsigned ErrorKind; 12831 if (CanBeUnaryOperator && CanBeBinaryOperator) { 12832 ErrorKind = 2; // 2 -> unary or binary. 12833 } else if (CanBeUnaryOperator) { 12834 ErrorKind = 0; // 0 -> unary 12835 } else { 12836 assert(CanBeBinaryOperator && 12837 "All non-call overloaded operators are unary or binary!"); 12838 ErrorKind = 1; // 1 -> binary 12839 } 12840 12841 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 12842 << FnDecl->getDeclName() << NumParams << ErrorKind; 12843 } 12844 12845 // Overloaded operators other than operator() cannot be variadic. 12846 if (Op != OO_Call && 12847 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 12848 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 12849 << FnDecl->getDeclName(); 12850 } 12851 12852 // Some operators must be non-static member functions. 12853 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 12854 return Diag(FnDecl->getLocation(), 12855 diag::err_operator_overload_must_be_member) 12856 << FnDecl->getDeclName(); 12857 } 12858 12859 // C++ [over.inc]p1: 12860 // The user-defined function called operator++ implements the 12861 // prefix and postfix ++ operator. If this function is a member 12862 // function with no parameters, or a non-member function with one 12863 // parameter of class or enumeration type, it defines the prefix 12864 // increment operator ++ for objects of that type. If the function 12865 // is a member function with one parameter (which shall be of type 12866 // int) or a non-member function with two parameters (the second 12867 // of which shall be of type int), it defines the postfix 12868 // increment operator ++ for objects of that type. 12869 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 12870 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 12871 QualType ParamType = LastParam->getType(); 12872 12873 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 12874 !ParamType->isDependentType()) 12875 return Diag(LastParam->getLocation(), 12876 diag::err_operator_overload_post_incdec_must_be_int) 12877 << LastParam->getType() << (Op == OO_MinusMinus); 12878 } 12879 12880 return false; 12881 } 12882 12883 static bool 12884 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 12885 FunctionTemplateDecl *TpDecl) { 12886 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 12887 12888 // Must have one or two template parameters. 12889 if (TemplateParams->size() == 1) { 12890 NonTypeTemplateParmDecl *PmDecl = 12891 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 12892 12893 // The template parameter must be a char parameter pack. 12894 if (PmDecl && PmDecl->isTemplateParameterPack() && 12895 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 12896 return false; 12897 12898 } else if (TemplateParams->size() == 2) { 12899 TemplateTypeParmDecl *PmType = 12900 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 12901 NonTypeTemplateParmDecl *PmArgs = 12902 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 12903 12904 // The second template parameter must be a parameter pack with the 12905 // first template parameter as its type. 12906 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 12907 PmArgs->isTemplateParameterPack()) { 12908 const TemplateTypeParmType *TArgs = 12909 PmArgs->getType()->getAs<TemplateTypeParmType>(); 12910 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 12911 TArgs->getIndex() == PmType->getIndex()) { 12912 if (!SemaRef.inTemplateInstantiation()) 12913 SemaRef.Diag(TpDecl->getLocation(), 12914 diag::ext_string_literal_operator_template); 12915 return false; 12916 } 12917 } 12918 } 12919 12920 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 12921 diag::err_literal_operator_template) 12922 << TpDecl->getTemplateParameters()->getSourceRange(); 12923 return true; 12924 } 12925 12926 /// CheckLiteralOperatorDeclaration - Check whether the declaration 12927 /// of this literal operator function is well-formed. If so, returns 12928 /// false; otherwise, emits appropriate diagnostics and returns true. 12929 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 12930 if (isa<CXXMethodDecl>(FnDecl)) { 12931 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 12932 << FnDecl->getDeclName(); 12933 return true; 12934 } 12935 12936 if (FnDecl->isExternC()) { 12937 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 12938 if (const LinkageSpecDecl *LSD = 12939 FnDecl->getDeclContext()->getExternCContext()) 12940 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 12941 return true; 12942 } 12943 12944 // This might be the definition of a literal operator template. 12945 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 12946 12947 // This might be a specialization of a literal operator template. 12948 if (!TpDecl) 12949 TpDecl = FnDecl->getPrimaryTemplate(); 12950 12951 // template <char...> type operator "" name() and 12952 // template <class T, T...> type operator "" name() are the only valid 12953 // template signatures, and the only valid signatures with no parameters. 12954 if (TpDecl) { 12955 if (FnDecl->param_size() != 0) { 12956 Diag(FnDecl->getLocation(), 12957 diag::err_literal_operator_template_with_params); 12958 return true; 12959 } 12960 12961 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 12962 return true; 12963 12964 } else if (FnDecl->param_size() == 1) { 12965 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 12966 12967 QualType ParamType = Param->getType().getUnqualifiedType(); 12968 12969 // Only unsigned long long int, long double, any character type, and const 12970 // char * are allowed as the only parameters. 12971 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 12972 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 12973 Context.hasSameType(ParamType, Context.CharTy) || 12974 Context.hasSameType(ParamType, Context.WideCharTy) || 12975 Context.hasSameType(ParamType, Context.Char16Ty) || 12976 Context.hasSameType(ParamType, Context.Char32Ty)) { 12977 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 12978 QualType InnerType = Ptr->getPointeeType(); 12979 12980 // Pointer parameter must be a const char *. 12981 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 12982 Context.CharTy) && 12983 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 12984 Diag(Param->getSourceRange().getBegin(), 12985 diag::err_literal_operator_param) 12986 << ParamType << "'const char *'" << Param->getSourceRange(); 12987 return true; 12988 } 12989 12990 } else if (ParamType->isRealFloatingType()) { 12991 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12992 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 12993 return true; 12994 12995 } else if (ParamType->isIntegerType()) { 12996 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12997 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 12998 return true; 12999 13000 } else { 13001 Diag(Param->getSourceRange().getBegin(), 13002 diag::err_literal_operator_invalid_param) 13003 << ParamType << Param->getSourceRange(); 13004 return true; 13005 } 13006 13007 } else if (FnDecl->param_size() == 2) { 13008 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 13009 13010 // First, verify that the first parameter is correct. 13011 13012 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 13013 13014 // Two parameter function must have a pointer to const as a 13015 // first parameter; let's strip those qualifiers. 13016 const PointerType *PT = FirstParamType->getAs<PointerType>(); 13017 13018 if (!PT) { 13019 Diag((*Param)->getSourceRange().getBegin(), 13020 diag::err_literal_operator_param) 13021 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13022 return true; 13023 } 13024 13025 QualType PointeeType = PT->getPointeeType(); 13026 // First parameter must be const 13027 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 13028 Diag((*Param)->getSourceRange().getBegin(), 13029 diag::err_literal_operator_param) 13030 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13031 return true; 13032 } 13033 13034 QualType InnerType = PointeeType.getUnqualifiedType(); 13035 // Only const char *, const wchar_t*, const char16_t*, and const char32_t* 13036 // are allowed as the first parameter to a two-parameter function 13037 if (!(Context.hasSameType(InnerType, Context.CharTy) || 13038 Context.hasSameType(InnerType, Context.WideCharTy) || 13039 Context.hasSameType(InnerType, Context.Char16Ty) || 13040 Context.hasSameType(InnerType, Context.Char32Ty))) { 13041 Diag((*Param)->getSourceRange().getBegin(), 13042 diag::err_literal_operator_param) 13043 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13044 return true; 13045 } 13046 13047 // Move on to the second and final parameter. 13048 ++Param; 13049 13050 // The second parameter must be a std::size_t. 13051 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 13052 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 13053 Diag((*Param)->getSourceRange().getBegin(), 13054 diag::err_literal_operator_param) 13055 << SecondParamType << Context.getSizeType() 13056 << (*Param)->getSourceRange(); 13057 return true; 13058 } 13059 } else { 13060 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 13061 return true; 13062 } 13063 13064 // Parameters are good. 13065 13066 // A parameter-declaration-clause containing a default argument is not 13067 // equivalent to any of the permitted forms. 13068 for (auto Param : FnDecl->parameters()) { 13069 if (Param->hasDefaultArg()) { 13070 Diag(Param->getDefaultArgRange().getBegin(), 13071 diag::err_literal_operator_default_argument) 13072 << Param->getDefaultArgRange(); 13073 break; 13074 } 13075 } 13076 13077 StringRef LiteralName 13078 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13079 if (LiteralName[0] != '_') { 13080 // C++11 [usrlit.suffix]p1: 13081 // Literal suffix identifiers that do not start with an underscore 13082 // are reserved for future standardization. 13083 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13084 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13085 } 13086 13087 return false; 13088 } 13089 13090 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13091 /// linkage specification, including the language and (if present) 13092 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13093 /// language string literal. LBraceLoc, if valid, provides the location of 13094 /// the '{' brace. Otherwise, this linkage specification does not 13095 /// have any braces. 13096 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13097 Expr *LangStr, 13098 SourceLocation LBraceLoc) { 13099 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13100 if (!Lit->isAscii()) { 13101 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13102 << LangStr->getSourceRange(); 13103 return nullptr; 13104 } 13105 13106 StringRef Lang = Lit->getString(); 13107 LinkageSpecDecl::LanguageIDs Language; 13108 if (Lang == "C") 13109 Language = LinkageSpecDecl::lang_c; 13110 else if (Lang == "C++") 13111 Language = LinkageSpecDecl::lang_cxx; 13112 else { 13113 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13114 << LangStr->getSourceRange(); 13115 return nullptr; 13116 } 13117 13118 // FIXME: Add all the various semantics of linkage specifications 13119 13120 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13121 LangStr->getExprLoc(), Language, 13122 LBraceLoc.isValid()); 13123 CurContext->addDecl(D); 13124 PushDeclContext(S, D); 13125 return D; 13126 } 13127 13128 /// ActOnFinishLinkageSpecification - Complete the definition of 13129 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13130 /// valid, it's the position of the closing '}' brace in a linkage 13131 /// specification that uses braces. 13132 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13133 Decl *LinkageSpec, 13134 SourceLocation RBraceLoc) { 13135 if (RBraceLoc.isValid()) { 13136 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13137 LSDecl->setRBraceLoc(RBraceLoc); 13138 } 13139 PopDeclContext(); 13140 return LinkageSpec; 13141 } 13142 13143 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13144 AttributeList *AttrList, 13145 SourceLocation SemiLoc) { 13146 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13147 // Attribute declarations appertain to empty declaration so we handle 13148 // them here. 13149 if (AttrList) 13150 ProcessDeclAttributeList(S, ED, AttrList); 13151 13152 CurContext->addDecl(ED); 13153 return ED; 13154 } 13155 13156 /// \brief Perform semantic analysis for the variable declaration that 13157 /// occurs within a C++ catch clause, returning the newly-created 13158 /// variable. 13159 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13160 TypeSourceInfo *TInfo, 13161 SourceLocation StartLoc, 13162 SourceLocation Loc, 13163 IdentifierInfo *Name) { 13164 bool Invalid = false; 13165 QualType ExDeclType = TInfo->getType(); 13166 13167 // Arrays and functions decay. 13168 if (ExDeclType->isArrayType()) 13169 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13170 else if (ExDeclType->isFunctionType()) 13171 ExDeclType = Context.getPointerType(ExDeclType); 13172 13173 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13174 // The exception-declaration shall not denote a pointer or reference to an 13175 // incomplete type, other than [cv] void*. 13176 // N2844 forbids rvalue references. 13177 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13178 Diag(Loc, diag::err_catch_rvalue_ref); 13179 Invalid = true; 13180 } 13181 13182 if (ExDeclType->isVariablyModifiedType()) { 13183 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13184 Invalid = true; 13185 } 13186 13187 QualType BaseType = ExDeclType; 13188 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13189 unsigned DK = diag::err_catch_incomplete; 13190 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13191 BaseType = Ptr->getPointeeType(); 13192 Mode = 1; 13193 DK = diag::err_catch_incomplete_ptr; 13194 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13195 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13196 BaseType = Ref->getPointeeType(); 13197 Mode = 2; 13198 DK = diag::err_catch_incomplete_ref; 13199 } 13200 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13201 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13202 Invalid = true; 13203 13204 if (!Invalid && !ExDeclType->isDependentType() && 13205 RequireNonAbstractType(Loc, ExDeclType, 13206 diag::err_abstract_type_in_decl, 13207 AbstractVariableType)) 13208 Invalid = true; 13209 13210 // Only the non-fragile NeXT runtime currently supports C++ catches 13211 // of ObjC types, and no runtime supports catching ObjC types by value. 13212 if (!Invalid && getLangOpts().ObjC1) { 13213 QualType T = ExDeclType; 13214 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13215 T = RT->getPointeeType(); 13216 13217 if (T->isObjCObjectType()) { 13218 Diag(Loc, diag::err_objc_object_catch); 13219 Invalid = true; 13220 } else if (T->isObjCObjectPointerType()) { 13221 // FIXME: should this be a test for macosx-fragile specifically? 13222 if (getLangOpts().ObjCRuntime.isFragile()) 13223 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13224 } 13225 } 13226 13227 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13228 ExDeclType, TInfo, SC_None); 13229 ExDecl->setExceptionVariable(true); 13230 13231 // In ARC, infer 'retaining' for variables of retainable type. 13232 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13233 Invalid = true; 13234 13235 if (!Invalid && !ExDeclType->isDependentType()) { 13236 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13237 // Insulate this from anything else we might currently be parsing. 13238 EnterExpressionEvaluationContext scope( 13239 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 13240 13241 // C++ [except.handle]p16: 13242 // The object declared in an exception-declaration or, if the 13243 // exception-declaration does not specify a name, a temporary (12.2) is 13244 // copy-initialized (8.5) from the exception object. [...] 13245 // The object is destroyed when the handler exits, after the destruction 13246 // of any automatic objects initialized within the handler. 13247 // 13248 // We just pretend to initialize the object with itself, then make sure 13249 // it can be destroyed later. 13250 QualType initType = Context.getExceptionObjectType(ExDeclType); 13251 13252 InitializedEntity entity = 13253 InitializedEntity::InitializeVariable(ExDecl); 13254 InitializationKind initKind = 13255 InitializationKind::CreateCopy(Loc, SourceLocation()); 13256 13257 Expr *opaqueValue = 13258 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13259 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13260 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13261 if (result.isInvalid()) 13262 Invalid = true; 13263 else { 13264 // If the constructor used was non-trivial, set this as the 13265 // "initializer". 13266 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13267 if (!construct->getConstructor()->isTrivial()) { 13268 Expr *init = MaybeCreateExprWithCleanups(construct); 13269 ExDecl->setInit(init); 13270 } 13271 13272 // And make sure it's destructable. 13273 FinalizeVarWithDestructor(ExDecl, recordType); 13274 } 13275 } 13276 } 13277 13278 if (Invalid) 13279 ExDecl->setInvalidDecl(); 13280 13281 return ExDecl; 13282 } 13283 13284 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13285 /// handler. 13286 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13287 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13288 bool Invalid = D.isInvalidType(); 13289 13290 // Check for unexpanded parameter packs. 13291 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13292 UPPC_ExceptionType)) { 13293 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13294 D.getIdentifierLoc()); 13295 Invalid = true; 13296 } 13297 13298 IdentifierInfo *II = D.getIdentifier(); 13299 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13300 LookupOrdinaryName, 13301 ForVisibleRedeclaration)) { 13302 // The scope should be freshly made just for us. There is just no way 13303 // it contains any previous declaration, except for function parameters in 13304 // a function-try-block's catch statement. 13305 assert(!S->isDeclScope(PrevDecl)); 13306 if (isDeclInScope(PrevDecl, CurContext, S)) { 13307 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13308 << D.getIdentifier(); 13309 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13310 Invalid = true; 13311 } else if (PrevDecl->isTemplateParameter()) 13312 // Maybe we will complain about the shadowed template parameter. 13313 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13314 } 13315 13316 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13317 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13318 << D.getCXXScopeSpec().getRange(); 13319 Invalid = true; 13320 } 13321 13322 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 13323 D.getLocStart(), 13324 D.getIdentifierLoc(), 13325 D.getIdentifier()); 13326 if (Invalid) 13327 ExDecl->setInvalidDecl(); 13328 13329 // Add the exception declaration into this scope. 13330 if (II) 13331 PushOnScopeChains(ExDecl, S); 13332 else 13333 CurContext->addDecl(ExDecl); 13334 13335 ProcessDeclAttributes(S, ExDecl, D); 13336 return ExDecl; 13337 } 13338 13339 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13340 Expr *AssertExpr, 13341 Expr *AssertMessageExpr, 13342 SourceLocation RParenLoc) { 13343 StringLiteral *AssertMessage = 13344 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13345 13346 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13347 return nullptr; 13348 13349 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13350 AssertMessage, RParenLoc, false); 13351 } 13352 13353 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13354 Expr *AssertExpr, 13355 StringLiteral *AssertMessage, 13356 SourceLocation RParenLoc, 13357 bool Failed) { 13358 assert(AssertExpr != nullptr && "Expected non-null condition"); 13359 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13360 !Failed) { 13361 // In a static_assert-declaration, the constant-expression shall be a 13362 // constant expression that can be contextually converted to bool. 13363 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13364 if (Converted.isInvalid()) 13365 Failed = true; 13366 13367 llvm::APSInt Cond; 13368 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13369 diag::err_static_assert_expression_is_not_constant, 13370 /*AllowFold=*/false).isInvalid()) 13371 Failed = true; 13372 13373 if (!Failed && !Cond) { 13374 SmallString<256> MsgBuffer; 13375 llvm::raw_svector_ostream Msg(MsgBuffer); 13376 if (AssertMessage) 13377 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13378 13379 Expr *InnerCond = nullptr; 13380 std::string InnerCondDescription; 13381 std::tie(InnerCond, InnerCondDescription) = 13382 findFailedBooleanCondition(Converted.get(), 13383 /*AllowTopLevelCond=*/false); 13384 if (InnerCond) { 13385 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 13386 << InnerCondDescription << !AssertMessage 13387 << Msg.str() << InnerCond->getSourceRange(); 13388 } else { 13389 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13390 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13391 } 13392 Failed = true; 13393 } 13394 } 13395 13396 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 13397 /*DiscardedValue*/false, 13398 /*IsConstexpr*/true); 13399 if (FullAssertExpr.isInvalid()) 13400 Failed = true; 13401 else 13402 AssertExpr = FullAssertExpr.get(); 13403 13404 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13405 AssertExpr, AssertMessage, RParenLoc, 13406 Failed); 13407 13408 CurContext->addDecl(Decl); 13409 return Decl; 13410 } 13411 13412 /// \brief Perform semantic analysis of the given friend type declaration. 13413 /// 13414 /// \returns A friend declaration that. 13415 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 13416 SourceLocation FriendLoc, 13417 TypeSourceInfo *TSInfo) { 13418 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 13419 13420 QualType T = TSInfo->getType(); 13421 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 13422 13423 // C++03 [class.friend]p2: 13424 // An elaborated-type-specifier shall be used in a friend declaration 13425 // for a class.* 13426 // 13427 // * The class-key of the elaborated-type-specifier is required. 13428 if (!CodeSynthesisContexts.empty()) { 13429 // Do not complain about the form of friend template types during any kind 13430 // of code synthesis. For template instantiation, we will have complained 13431 // when the template was defined. 13432 } else { 13433 if (!T->isElaboratedTypeSpecifier()) { 13434 // If we evaluated the type to a record type, suggest putting 13435 // a tag in front. 13436 if (const RecordType *RT = T->getAs<RecordType>()) { 13437 RecordDecl *RD = RT->getDecl(); 13438 13439 SmallString<16> InsertionText(" "); 13440 InsertionText += RD->getKindName(); 13441 13442 Diag(TypeRange.getBegin(), 13443 getLangOpts().CPlusPlus11 ? 13444 diag::warn_cxx98_compat_unelaborated_friend_type : 13445 diag::ext_unelaborated_friend_type) 13446 << (unsigned) RD->getTagKind() 13447 << T 13448 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 13449 InsertionText); 13450 } else { 13451 Diag(FriendLoc, 13452 getLangOpts().CPlusPlus11 ? 13453 diag::warn_cxx98_compat_nonclass_type_friend : 13454 diag::ext_nonclass_type_friend) 13455 << T 13456 << TypeRange; 13457 } 13458 } else if (T->getAs<EnumType>()) { 13459 Diag(FriendLoc, 13460 getLangOpts().CPlusPlus11 ? 13461 diag::warn_cxx98_compat_enum_friend : 13462 diag::ext_enum_friend) 13463 << T 13464 << TypeRange; 13465 } 13466 13467 // C++11 [class.friend]p3: 13468 // A friend declaration that does not declare a function shall have one 13469 // of the following forms: 13470 // friend elaborated-type-specifier ; 13471 // friend simple-type-specifier ; 13472 // friend typename-specifier ; 13473 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 13474 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 13475 } 13476 13477 // If the type specifier in a friend declaration designates a (possibly 13478 // cv-qualified) class type, that class is declared as a friend; otherwise, 13479 // the friend declaration is ignored. 13480 return FriendDecl::Create(Context, CurContext, 13481 TSInfo->getTypeLoc().getLocStart(), TSInfo, 13482 FriendLoc); 13483 } 13484 13485 /// Handle a friend tag declaration where the scope specifier was 13486 /// templated. 13487 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 13488 unsigned TagSpec, SourceLocation TagLoc, 13489 CXXScopeSpec &SS, 13490 IdentifierInfo *Name, 13491 SourceLocation NameLoc, 13492 AttributeList *Attr, 13493 MultiTemplateParamsArg TempParamLists) { 13494 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13495 13496 bool IsMemberSpecialization = false; 13497 bool Invalid = false; 13498 13499 if (TemplateParameterList *TemplateParams = 13500 MatchTemplateParametersToScopeSpecifier( 13501 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 13502 IsMemberSpecialization, Invalid)) { 13503 if (TemplateParams->size() > 0) { 13504 // This is a declaration of a class template. 13505 if (Invalid) 13506 return nullptr; 13507 13508 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 13509 NameLoc, Attr, TemplateParams, AS_public, 13510 /*ModulePrivateLoc=*/SourceLocation(), 13511 FriendLoc, TempParamLists.size() - 1, 13512 TempParamLists.data()).get(); 13513 } else { 13514 // The "template<>" header is extraneous. 13515 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13516 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13517 IsMemberSpecialization = true; 13518 } 13519 } 13520 13521 if (Invalid) return nullptr; 13522 13523 bool isAllExplicitSpecializations = true; 13524 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 13525 if (TempParamLists[I]->size()) { 13526 isAllExplicitSpecializations = false; 13527 break; 13528 } 13529 } 13530 13531 // FIXME: don't ignore attributes. 13532 13533 // If it's explicit specializations all the way down, just forget 13534 // about the template header and build an appropriate non-templated 13535 // friend. TODO: for source fidelity, remember the headers. 13536 if (isAllExplicitSpecializations) { 13537 if (SS.isEmpty()) { 13538 bool Owned = false; 13539 bool IsDependent = false; 13540 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 13541 Attr, AS_public, 13542 /*ModulePrivateLoc=*/SourceLocation(), 13543 MultiTemplateParamsArg(), Owned, IsDependent, 13544 /*ScopedEnumKWLoc=*/SourceLocation(), 13545 /*ScopedEnumUsesClassTag=*/false, 13546 /*UnderlyingType=*/TypeResult(), 13547 /*IsTypeSpecifier=*/false, 13548 /*IsTemplateParamOrArg=*/false); 13549 } 13550 13551 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 13552 ElaboratedTypeKeyword Keyword 13553 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13554 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 13555 *Name, NameLoc); 13556 if (T.isNull()) 13557 return nullptr; 13558 13559 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13560 if (isa<DependentNameType>(T)) { 13561 DependentNameTypeLoc TL = 13562 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13563 TL.setElaboratedKeywordLoc(TagLoc); 13564 TL.setQualifierLoc(QualifierLoc); 13565 TL.setNameLoc(NameLoc); 13566 } else { 13567 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 13568 TL.setElaboratedKeywordLoc(TagLoc); 13569 TL.setQualifierLoc(QualifierLoc); 13570 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 13571 } 13572 13573 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13574 TSI, FriendLoc, TempParamLists); 13575 Friend->setAccess(AS_public); 13576 CurContext->addDecl(Friend); 13577 return Friend; 13578 } 13579 13580 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 13581 13582 13583 13584 // Handle the case of a templated-scope friend class. e.g. 13585 // template <class T> class A<T>::B; 13586 // FIXME: we don't support these right now. 13587 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 13588 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 13589 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13590 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 13591 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13592 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13593 TL.setElaboratedKeywordLoc(TagLoc); 13594 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 13595 TL.setNameLoc(NameLoc); 13596 13597 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13598 TSI, FriendLoc, TempParamLists); 13599 Friend->setAccess(AS_public); 13600 Friend->setUnsupportedFriend(true); 13601 CurContext->addDecl(Friend); 13602 return Friend; 13603 } 13604 13605 13606 /// Handle a friend type declaration. This works in tandem with 13607 /// ActOnTag. 13608 /// 13609 /// Notes on friend class templates: 13610 /// 13611 /// We generally treat friend class declarations as if they were 13612 /// declaring a class. So, for example, the elaborated type specifier 13613 /// in a friend declaration is required to obey the restrictions of a 13614 /// class-head (i.e. no typedefs in the scope chain), template 13615 /// parameters are required to match up with simple template-ids, &c. 13616 /// However, unlike when declaring a template specialization, it's 13617 /// okay to refer to a template specialization without an empty 13618 /// template parameter declaration, e.g. 13619 /// friend class A<T>::B<unsigned>; 13620 /// We permit this as a special case; if there are any template 13621 /// parameters present at all, require proper matching, i.e. 13622 /// template <> template \<class T> friend class A<int>::B; 13623 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 13624 MultiTemplateParamsArg TempParams) { 13625 SourceLocation Loc = DS.getLocStart(); 13626 13627 assert(DS.isFriendSpecified()); 13628 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13629 13630 // Try to convert the decl specifier to a type. This works for 13631 // friend templates because ActOnTag never produces a ClassTemplateDecl 13632 // for a TUK_Friend. 13633 Declarator TheDeclarator(DS, Declarator::MemberContext); 13634 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 13635 QualType T = TSI->getType(); 13636 if (TheDeclarator.isInvalidType()) 13637 return nullptr; 13638 13639 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 13640 return nullptr; 13641 13642 // This is definitely an error in C++98. It's probably meant to 13643 // be forbidden in C++0x, too, but the specification is just 13644 // poorly written. 13645 // 13646 // The problem is with declarations like the following: 13647 // template <T> friend A<T>::foo; 13648 // where deciding whether a class C is a friend or not now hinges 13649 // on whether there exists an instantiation of A that causes 13650 // 'foo' to equal C. There are restrictions on class-heads 13651 // (which we declare (by fiat) elaborated friend declarations to 13652 // be) that makes this tractable. 13653 // 13654 // FIXME: handle "template <> friend class A<T>;", which 13655 // is possibly well-formed? Who even knows? 13656 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 13657 Diag(Loc, diag::err_tagless_friend_type_template) 13658 << DS.getSourceRange(); 13659 return nullptr; 13660 } 13661 13662 // C++98 [class.friend]p1: A friend of a class is a function 13663 // or class that is not a member of the class . . . 13664 // This is fixed in DR77, which just barely didn't make the C++03 13665 // deadline. It's also a very silly restriction that seriously 13666 // affects inner classes and which nobody else seems to implement; 13667 // thus we never diagnose it, not even in -pedantic. 13668 // 13669 // But note that we could warn about it: it's always useless to 13670 // friend one of your own members (it's not, however, worthless to 13671 // friend a member of an arbitrary specialization of your template). 13672 13673 Decl *D; 13674 if (!TempParams.empty()) 13675 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 13676 TempParams, 13677 TSI, 13678 DS.getFriendSpecLoc()); 13679 else 13680 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 13681 13682 if (!D) 13683 return nullptr; 13684 13685 D->setAccess(AS_public); 13686 CurContext->addDecl(D); 13687 13688 return D; 13689 } 13690 13691 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 13692 MultiTemplateParamsArg TemplateParams) { 13693 const DeclSpec &DS = D.getDeclSpec(); 13694 13695 assert(DS.isFriendSpecified()); 13696 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13697 13698 SourceLocation Loc = D.getIdentifierLoc(); 13699 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13700 13701 // C++ [class.friend]p1 13702 // A friend of a class is a function or class.... 13703 // Note that this sees through typedefs, which is intended. 13704 // It *doesn't* see through dependent types, which is correct 13705 // according to [temp.arg.type]p3: 13706 // If a declaration acquires a function type through a 13707 // type dependent on a template-parameter and this causes 13708 // a declaration that does not use the syntactic form of a 13709 // function declarator to have a function type, the program 13710 // is ill-formed. 13711 if (!TInfo->getType()->isFunctionType()) { 13712 Diag(Loc, diag::err_unexpected_friend); 13713 13714 // It might be worthwhile to try to recover by creating an 13715 // appropriate declaration. 13716 return nullptr; 13717 } 13718 13719 // C++ [namespace.memdef]p3 13720 // - If a friend declaration in a non-local class first declares a 13721 // class or function, the friend class or function is a member 13722 // of the innermost enclosing namespace. 13723 // - The name of the friend is not found by simple name lookup 13724 // until a matching declaration is provided in that namespace 13725 // scope (either before or after the class declaration granting 13726 // friendship). 13727 // - If a friend function is called, its name may be found by the 13728 // name lookup that considers functions from namespaces and 13729 // classes associated with the types of the function arguments. 13730 // - When looking for a prior declaration of a class or a function 13731 // declared as a friend, scopes outside the innermost enclosing 13732 // namespace scope are not considered. 13733 13734 CXXScopeSpec &SS = D.getCXXScopeSpec(); 13735 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 13736 DeclarationName Name = NameInfo.getName(); 13737 assert(Name); 13738 13739 // Check for unexpanded parameter packs. 13740 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 13741 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 13742 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 13743 return nullptr; 13744 13745 // The context we found the declaration in, or in which we should 13746 // create the declaration. 13747 DeclContext *DC; 13748 Scope *DCScope = S; 13749 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 13750 ForExternalRedeclaration); 13751 13752 // There are five cases here. 13753 // - There's no scope specifier and we're in a local class. Only look 13754 // for functions declared in the immediately-enclosing block scope. 13755 // We recover from invalid scope qualifiers as if they just weren't there. 13756 FunctionDecl *FunctionContainingLocalClass = nullptr; 13757 if ((SS.isInvalid() || !SS.isSet()) && 13758 (FunctionContainingLocalClass = 13759 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 13760 // C++11 [class.friend]p11: 13761 // If a friend declaration appears in a local class and the name 13762 // specified is an unqualified name, a prior declaration is 13763 // looked up without considering scopes that are outside the 13764 // innermost enclosing non-class scope. For a friend function 13765 // declaration, if there is no prior declaration, the program is 13766 // ill-formed. 13767 13768 // Find the innermost enclosing non-class scope. This is the block 13769 // scope containing the local class definition (or for a nested class, 13770 // the outer local class). 13771 DCScope = S->getFnParent(); 13772 13773 // Look up the function name in the scope. 13774 Previous.clear(LookupLocalFriendName); 13775 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 13776 13777 if (!Previous.empty()) { 13778 // All possible previous declarations must have the same context: 13779 // either they were declared at block scope or they are members of 13780 // one of the enclosing local classes. 13781 DC = Previous.getRepresentativeDecl()->getDeclContext(); 13782 } else { 13783 // This is ill-formed, but provide the context that we would have 13784 // declared the function in, if we were permitted to, for error recovery. 13785 DC = FunctionContainingLocalClass; 13786 } 13787 adjustContextForLocalExternDecl(DC); 13788 13789 // C++ [class.friend]p6: 13790 // A function can be defined in a friend declaration of a class if and 13791 // only if the class is a non-local class (9.8), the function name is 13792 // unqualified, and the function has namespace scope. 13793 if (D.isFunctionDefinition()) { 13794 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 13795 } 13796 13797 // - There's no scope specifier, in which case we just go to the 13798 // appropriate scope and look for a function or function template 13799 // there as appropriate. 13800 } else if (SS.isInvalid() || !SS.isSet()) { 13801 // C++11 [namespace.memdef]p3: 13802 // If the name in a friend declaration is neither qualified nor 13803 // a template-id and the declaration is a function or an 13804 // elaborated-type-specifier, the lookup to determine whether 13805 // the entity has been previously declared shall not consider 13806 // any scopes outside the innermost enclosing namespace. 13807 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 13808 13809 // Find the appropriate context according to the above. 13810 DC = CurContext; 13811 13812 // Skip class contexts. If someone can cite chapter and verse 13813 // for this behavior, that would be nice --- it's what GCC and 13814 // EDG do, and it seems like a reasonable intent, but the spec 13815 // really only says that checks for unqualified existing 13816 // declarations should stop at the nearest enclosing namespace, 13817 // not that they should only consider the nearest enclosing 13818 // namespace. 13819 while (DC->isRecord()) 13820 DC = DC->getParent(); 13821 13822 DeclContext *LookupDC = DC; 13823 while (LookupDC->isTransparentContext()) 13824 LookupDC = LookupDC->getParent(); 13825 13826 while (true) { 13827 LookupQualifiedName(Previous, LookupDC); 13828 13829 if (!Previous.empty()) { 13830 DC = LookupDC; 13831 break; 13832 } 13833 13834 if (isTemplateId) { 13835 if (isa<TranslationUnitDecl>(LookupDC)) break; 13836 } else { 13837 if (LookupDC->isFileContext()) break; 13838 } 13839 LookupDC = LookupDC->getParent(); 13840 } 13841 13842 DCScope = getScopeForDeclContext(S, DC); 13843 13844 // - There's a non-dependent scope specifier, in which case we 13845 // compute it and do a previous lookup there for a function 13846 // or function template. 13847 } else if (!SS.getScopeRep()->isDependent()) { 13848 DC = computeDeclContext(SS); 13849 if (!DC) return nullptr; 13850 13851 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 13852 13853 LookupQualifiedName(Previous, DC); 13854 13855 // Ignore things found implicitly in the wrong scope. 13856 // TODO: better diagnostics for this case. Suggesting the right 13857 // qualified scope would be nice... 13858 LookupResult::Filter F = Previous.makeFilter(); 13859 while (F.hasNext()) { 13860 NamedDecl *D = F.next(); 13861 if (!DC->InEnclosingNamespaceSetOf( 13862 D->getDeclContext()->getRedeclContext())) 13863 F.erase(); 13864 } 13865 F.done(); 13866 13867 if (Previous.empty()) { 13868 D.setInvalidType(); 13869 Diag(Loc, diag::err_qualified_friend_not_found) 13870 << Name << TInfo->getType(); 13871 return nullptr; 13872 } 13873 13874 // C++ [class.friend]p1: A friend of a class is a function or 13875 // class that is not a member of the class . . . 13876 if (DC->Equals(CurContext)) 13877 Diag(DS.getFriendSpecLoc(), 13878 getLangOpts().CPlusPlus11 ? 13879 diag::warn_cxx98_compat_friend_is_member : 13880 diag::err_friend_is_member); 13881 13882 if (D.isFunctionDefinition()) { 13883 // C++ [class.friend]p6: 13884 // A function can be defined in a friend declaration of a class if and 13885 // only if the class is a non-local class (9.8), the function name is 13886 // unqualified, and the function has namespace scope. 13887 SemaDiagnosticBuilder DB 13888 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 13889 13890 DB << SS.getScopeRep(); 13891 if (DC->isFileContext()) 13892 DB << FixItHint::CreateRemoval(SS.getRange()); 13893 SS.clear(); 13894 } 13895 13896 // - There's a scope specifier that does not match any template 13897 // parameter lists, in which case we use some arbitrary context, 13898 // create a method or method template, and wait for instantiation. 13899 // - There's a scope specifier that does match some template 13900 // parameter lists, which we don't handle right now. 13901 } else { 13902 if (D.isFunctionDefinition()) { 13903 // C++ [class.friend]p6: 13904 // A function can be defined in a friend declaration of a class if and 13905 // only if the class is a non-local class (9.8), the function name is 13906 // unqualified, and the function has namespace scope. 13907 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 13908 << SS.getScopeRep(); 13909 } 13910 13911 DC = CurContext; 13912 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 13913 } 13914 13915 if (!DC->isRecord()) { 13916 int DiagArg = -1; 13917 switch (D.getName().getKind()) { 13918 case UnqualifiedId::IK_ConstructorTemplateId: 13919 case UnqualifiedId::IK_ConstructorName: 13920 DiagArg = 0; 13921 break; 13922 case UnqualifiedId::IK_DestructorName: 13923 DiagArg = 1; 13924 break; 13925 case UnqualifiedId::IK_ConversionFunctionId: 13926 DiagArg = 2; 13927 break; 13928 case UnqualifiedId::IK_DeductionGuideName: 13929 DiagArg = 3; 13930 break; 13931 case UnqualifiedId::IK_Identifier: 13932 case UnqualifiedId::IK_ImplicitSelfParam: 13933 case UnqualifiedId::IK_LiteralOperatorId: 13934 case UnqualifiedId::IK_OperatorFunctionId: 13935 case UnqualifiedId::IK_TemplateId: 13936 break; 13937 } 13938 // This implies that it has to be an operator or function. 13939 if (DiagArg >= 0) { 13940 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 13941 return nullptr; 13942 } 13943 } 13944 13945 // FIXME: This is an egregious hack to cope with cases where the scope stack 13946 // does not contain the declaration context, i.e., in an out-of-line 13947 // definition of a class. 13948 Scope FakeDCScope(S, Scope::DeclScope, Diags); 13949 if (!DCScope) { 13950 FakeDCScope.setEntity(DC); 13951 DCScope = &FakeDCScope; 13952 } 13953 13954 bool AddToScope = true; 13955 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 13956 TemplateParams, AddToScope); 13957 if (!ND) return nullptr; 13958 13959 assert(ND->getLexicalDeclContext() == CurContext); 13960 13961 // If we performed typo correction, we might have added a scope specifier 13962 // and changed the decl context. 13963 DC = ND->getDeclContext(); 13964 13965 // Add the function declaration to the appropriate lookup tables, 13966 // adjusting the redeclarations list as necessary. We don't 13967 // want to do this yet if the friending class is dependent. 13968 // 13969 // Also update the scope-based lookup if the target context's 13970 // lookup context is in lexical scope. 13971 if (!CurContext->isDependentContext()) { 13972 DC = DC->getRedeclContext(); 13973 DC->makeDeclVisibleInContext(ND); 13974 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13975 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 13976 } 13977 13978 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 13979 D.getIdentifierLoc(), ND, 13980 DS.getFriendSpecLoc()); 13981 FrD->setAccess(AS_public); 13982 CurContext->addDecl(FrD); 13983 13984 if (ND->isInvalidDecl()) { 13985 FrD->setInvalidDecl(); 13986 } else { 13987 if (DC->isRecord()) CheckFriendAccess(ND); 13988 13989 FunctionDecl *FD; 13990 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 13991 FD = FTD->getTemplatedDecl(); 13992 else 13993 FD = cast<FunctionDecl>(ND); 13994 13995 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 13996 // default argument expression, that declaration shall be a definition 13997 // and shall be the only declaration of the function or function 13998 // template in the translation unit. 13999 if (functionDeclHasDefaultArgument(FD)) { 14000 // We can't look at FD->getPreviousDecl() because it may not have been set 14001 // if we're in a dependent context. If the function is known to be a 14002 // redeclaration, we will have narrowed Previous down to the right decl. 14003 if (D.isRedeclaration()) { 14004 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 14005 Diag(Previous.getRepresentativeDecl()->getLocation(), 14006 diag::note_previous_declaration); 14007 } else if (!D.isFunctionDefinition()) 14008 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 14009 } 14010 14011 // Mark templated-scope function declarations as unsupported. 14012 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 14013 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 14014 << SS.getScopeRep() << SS.getRange() 14015 << cast<CXXRecordDecl>(CurContext); 14016 FrD->setUnsupportedFriend(true); 14017 } 14018 } 14019 14020 return ND; 14021 } 14022 14023 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 14024 AdjustDeclIfTemplate(Dcl); 14025 14026 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 14027 if (!Fn) { 14028 Diag(DelLoc, diag::err_deleted_non_function); 14029 return; 14030 } 14031 14032 // Deleted function does not have a body. 14033 Fn->setWillHaveBody(false); 14034 14035 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 14036 // Don't consider the implicit declaration we generate for explicit 14037 // specializations. FIXME: Do not generate these implicit declarations. 14038 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 14039 Prev->getPreviousDecl()) && 14040 !Prev->isDefined()) { 14041 Diag(DelLoc, diag::err_deleted_decl_not_first); 14042 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 14043 Prev->isImplicit() ? diag::note_previous_implicit_declaration 14044 : diag::note_previous_declaration); 14045 } 14046 // If the declaration wasn't the first, we delete the function anyway for 14047 // recovery. 14048 Fn = Fn->getCanonicalDecl(); 14049 } 14050 14051 // dllimport/dllexport cannot be deleted. 14052 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 14053 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 14054 Fn->setInvalidDecl(); 14055 } 14056 14057 if (Fn->isDeleted()) 14058 return; 14059 14060 // See if we're deleting a function which is already known to override a 14061 // non-deleted virtual function. 14062 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 14063 bool IssuedDiagnostic = false; 14064 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 14065 E = MD->end_overridden_methods(); 14066 I != E; ++I) { 14067 if (!(*MD->begin_overridden_methods())->isDeleted()) { 14068 if (!IssuedDiagnostic) { 14069 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 14070 IssuedDiagnostic = true; 14071 } 14072 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 14073 } 14074 } 14075 // If this function was implicitly deleted because it was defaulted, 14076 // explain why it was deleted. 14077 if (IssuedDiagnostic && MD->isDefaulted()) 14078 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14079 /*Diagnose*/true); 14080 } 14081 14082 // C++11 [basic.start.main]p3: 14083 // A program that defines main as deleted [...] is ill-formed. 14084 if (Fn->isMain()) 14085 Diag(DelLoc, diag::err_deleted_main); 14086 14087 // C++11 [dcl.fct.def.delete]p4: 14088 // A deleted function is implicitly inline. 14089 Fn->setImplicitlyInline(); 14090 Fn->setDeletedAsWritten(); 14091 } 14092 14093 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14094 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14095 14096 if (MD) { 14097 if (MD->getParent()->isDependentType()) { 14098 MD->setDefaulted(); 14099 MD->setExplicitlyDefaulted(); 14100 return; 14101 } 14102 14103 CXXSpecialMember Member = getSpecialMember(MD); 14104 if (Member == CXXInvalid) { 14105 if (!MD->isInvalidDecl()) 14106 Diag(DefaultLoc, diag::err_default_special_members); 14107 return; 14108 } 14109 14110 MD->setDefaulted(); 14111 MD->setExplicitlyDefaulted(); 14112 14113 // Unset that we will have a body for this function. We might not, 14114 // if it turns out to be trivial, and we don't need this marking now 14115 // that we've marked it as defaulted. 14116 MD->setWillHaveBody(false); 14117 14118 // If this definition appears within the record, do the checking when 14119 // the record is complete. 14120 const FunctionDecl *Primary = MD; 14121 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14122 // Ask the template instantiation pattern that actually had the 14123 // '= default' on it. 14124 Primary = Pattern; 14125 14126 // If the method was defaulted on its first declaration, we will have 14127 // already performed the checking in CheckCompletedCXXClass. Such a 14128 // declaration doesn't trigger an implicit definition. 14129 if (Primary->getCanonicalDecl()->isDefaulted()) 14130 return; 14131 14132 CheckExplicitlyDefaultedSpecialMember(MD); 14133 14134 if (!MD->isInvalidDecl()) 14135 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14136 } else { 14137 Diag(DefaultLoc, diag::err_default_special_members); 14138 } 14139 } 14140 14141 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14142 for (Stmt *SubStmt : S->children()) { 14143 if (!SubStmt) 14144 continue; 14145 if (isa<ReturnStmt>(SubStmt)) 14146 Self.Diag(SubStmt->getLocStart(), 14147 diag::err_return_in_constructor_handler); 14148 if (!isa<Expr>(SubStmt)) 14149 SearchForReturnInStmt(Self, SubStmt); 14150 } 14151 } 14152 14153 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14154 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14155 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14156 SearchForReturnInStmt(*this, Handler); 14157 } 14158 } 14159 14160 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14161 const CXXMethodDecl *Old) { 14162 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 14163 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 14164 14165 if (OldFT->hasExtParameterInfos()) { 14166 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 14167 // A parameter of the overriding method should be annotated with noescape 14168 // if the corresponding parameter of the overridden method is annotated. 14169 if (OldFT->getExtParameterInfo(I).isNoEscape() && 14170 !NewFT->getExtParameterInfo(I).isNoEscape()) { 14171 Diag(New->getParamDecl(I)->getLocation(), 14172 diag::warn_overriding_method_missing_noescape); 14173 Diag(Old->getParamDecl(I)->getLocation(), 14174 diag::note_overridden_marked_noescape); 14175 } 14176 } 14177 14178 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14179 14180 // If the calling conventions match, everything is fine 14181 if (NewCC == OldCC) 14182 return false; 14183 14184 // If the calling conventions mismatch because the new function is static, 14185 // suppress the calling convention mismatch error; the error about static 14186 // function override (err_static_overrides_virtual from 14187 // Sema::CheckFunctionDeclaration) is more clear. 14188 if (New->getStorageClass() == SC_Static) 14189 return false; 14190 14191 Diag(New->getLocation(), 14192 diag::err_conflicting_overriding_cc_attributes) 14193 << New->getDeclName() << New->getType() << Old->getType(); 14194 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14195 return true; 14196 } 14197 14198 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14199 const CXXMethodDecl *Old) { 14200 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14201 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 14202 14203 if (Context.hasSameType(NewTy, OldTy) || 14204 NewTy->isDependentType() || OldTy->isDependentType()) 14205 return false; 14206 14207 // Check if the return types are covariant 14208 QualType NewClassTy, OldClassTy; 14209 14210 /// Both types must be pointers or references to classes. 14211 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 14212 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 14213 NewClassTy = NewPT->getPointeeType(); 14214 OldClassTy = OldPT->getPointeeType(); 14215 } 14216 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 14217 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 14218 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 14219 NewClassTy = NewRT->getPointeeType(); 14220 OldClassTy = OldRT->getPointeeType(); 14221 } 14222 } 14223 } 14224 14225 // The return types aren't either both pointers or references to a class type. 14226 if (NewClassTy.isNull()) { 14227 Diag(New->getLocation(), 14228 diag::err_different_return_type_for_overriding_virtual_function) 14229 << New->getDeclName() << NewTy << OldTy 14230 << New->getReturnTypeSourceRange(); 14231 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14232 << Old->getReturnTypeSourceRange(); 14233 14234 return true; 14235 } 14236 14237 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 14238 // C++14 [class.virtual]p8: 14239 // If the class type in the covariant return type of D::f differs from 14240 // that of B::f, the class type in the return type of D::f shall be 14241 // complete at the point of declaration of D::f or shall be the class 14242 // type D. 14243 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14244 if (!RT->isBeingDefined() && 14245 RequireCompleteType(New->getLocation(), NewClassTy, 14246 diag::err_covariant_return_incomplete, 14247 New->getDeclName())) 14248 return true; 14249 } 14250 14251 // Check if the new class derives from the old class. 14252 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14253 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14254 << New->getDeclName() << NewTy << OldTy 14255 << New->getReturnTypeSourceRange(); 14256 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14257 << Old->getReturnTypeSourceRange(); 14258 return true; 14259 } 14260 14261 // Check if we the conversion from derived to base is valid. 14262 if (CheckDerivedToBaseConversion( 14263 NewClassTy, OldClassTy, 14264 diag::err_covariant_return_inaccessible_base, 14265 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14266 New->getLocation(), New->getReturnTypeSourceRange(), 14267 New->getDeclName(), nullptr)) { 14268 // FIXME: this note won't trigger for delayed access control 14269 // diagnostics, and it's impossible to get an undelayed error 14270 // here from access control during the original parse because 14271 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14272 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14273 << Old->getReturnTypeSourceRange(); 14274 return true; 14275 } 14276 } 14277 14278 // The qualifiers of the return types must be the same. 14279 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14280 Diag(New->getLocation(), 14281 diag::err_covariant_return_type_different_qualifications) 14282 << New->getDeclName() << NewTy << OldTy 14283 << New->getReturnTypeSourceRange(); 14284 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14285 << Old->getReturnTypeSourceRange(); 14286 return true; 14287 } 14288 14289 14290 // The new class type must have the same or less qualifiers as the old type. 14291 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14292 Diag(New->getLocation(), 14293 diag::err_covariant_return_type_class_type_more_qualified) 14294 << New->getDeclName() << NewTy << OldTy 14295 << New->getReturnTypeSourceRange(); 14296 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14297 << Old->getReturnTypeSourceRange(); 14298 return true; 14299 } 14300 14301 return false; 14302 } 14303 14304 /// \brief Mark the given method pure. 14305 /// 14306 /// \param Method the method to be marked pure. 14307 /// 14308 /// \param InitRange the source range that covers the "0" initializer. 14309 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14310 SourceLocation EndLoc = InitRange.getEnd(); 14311 if (EndLoc.isValid()) 14312 Method->setRangeEnd(EndLoc); 14313 14314 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14315 Method->setPure(); 14316 return false; 14317 } 14318 14319 if (!Method->isInvalidDecl()) 14320 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14321 << Method->getDeclName() << InitRange; 14322 return true; 14323 } 14324 14325 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14326 if (D->getFriendObjectKind()) 14327 Diag(D->getLocation(), diag::err_pure_friend); 14328 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14329 CheckPureMethod(M, ZeroLoc); 14330 else 14331 Diag(D->getLocation(), diag::err_illegal_initializer); 14332 } 14333 14334 /// \brief Determine whether the given declaration is a global variable or 14335 /// static data member. 14336 static bool isNonlocalVariable(const Decl *D) { 14337 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14338 return Var->hasGlobalStorage(); 14339 14340 return false; 14341 } 14342 14343 /// Invoked when we are about to parse an initializer for the declaration 14344 /// 'Dcl'. 14345 /// 14346 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14347 /// static data member of class X, names should be looked up in the scope of 14348 /// class X. If the declaration had a scope specifier, a scope will have 14349 /// been created and passed in for this purpose. Otherwise, S will be null. 14350 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14351 // If there is no declaration, there was an error parsing it. 14352 if (!D || D->isInvalidDecl()) 14353 return; 14354 14355 // We will always have a nested name specifier here, but this declaration 14356 // might not be out of line if the specifier names the current namespace: 14357 // extern int n; 14358 // int ::n = 0; 14359 if (S && D->isOutOfLine()) 14360 EnterDeclaratorContext(S, D->getDeclContext()); 14361 14362 // If we are parsing the initializer for a static data member, push a 14363 // new expression evaluation context that is associated with this static 14364 // data member. 14365 if (isNonlocalVariable(D)) 14366 PushExpressionEvaluationContext( 14367 ExpressionEvaluationContext::PotentiallyEvaluated, D); 14368 } 14369 14370 /// Invoked after we are finished parsing an initializer for the declaration D. 14371 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14372 // If there is no declaration, there was an error parsing it. 14373 if (!D || D->isInvalidDecl()) 14374 return; 14375 14376 if (isNonlocalVariable(D)) 14377 PopExpressionEvaluationContext(); 14378 14379 if (S && D->isOutOfLine()) 14380 ExitDeclaratorContext(S); 14381 } 14382 14383 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14384 /// C++ if/switch/while/for statement. 14385 /// e.g: "if (int x = f()) {...}" 14386 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14387 // C++ 6.4p2: 14388 // The declarator shall not specify a function or an array. 14389 // The type-specifier-seq shall not contain typedef and shall not declare a 14390 // new class or enumeration. 14391 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14392 "Parser allowed 'typedef' as storage class of condition decl."); 14393 14394 Decl *Dcl = ActOnDeclarator(S, D); 14395 if (!Dcl) 14396 return true; 14397 14398 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 14399 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 14400 << D.getSourceRange(); 14401 return true; 14402 } 14403 14404 return Dcl; 14405 } 14406 14407 void Sema::LoadExternalVTableUses() { 14408 if (!ExternalSource) 14409 return; 14410 14411 SmallVector<ExternalVTableUse, 4> VTables; 14412 ExternalSource->ReadUsedVTables(VTables); 14413 SmallVector<VTableUse, 4> NewUses; 14414 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 14415 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 14416 = VTablesUsed.find(VTables[I].Record); 14417 // Even if a definition wasn't required before, it may be required now. 14418 if (Pos != VTablesUsed.end()) { 14419 if (!Pos->second && VTables[I].DefinitionRequired) 14420 Pos->second = true; 14421 continue; 14422 } 14423 14424 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 14425 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 14426 } 14427 14428 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 14429 } 14430 14431 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 14432 bool DefinitionRequired) { 14433 // Ignore any vtable uses in unevaluated operands or for classes that do 14434 // not have a vtable. 14435 if (!Class->isDynamicClass() || Class->isDependentContext() || 14436 CurContext->isDependentContext() || isUnevaluatedContext()) 14437 return; 14438 14439 // Try to insert this class into the map. 14440 LoadExternalVTableUses(); 14441 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14442 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 14443 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 14444 if (!Pos.second) { 14445 // If we already had an entry, check to see if we are promoting this vtable 14446 // to require a definition. If so, we need to reappend to the VTableUses 14447 // list, since we may have already processed the first entry. 14448 if (DefinitionRequired && !Pos.first->second) { 14449 Pos.first->second = true; 14450 } else { 14451 // Otherwise, we can early exit. 14452 return; 14453 } 14454 } else { 14455 // The Microsoft ABI requires that we perform the destructor body 14456 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 14457 // the deleting destructor is emitted with the vtable, not with the 14458 // destructor definition as in the Itanium ABI. 14459 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14460 CXXDestructorDecl *DD = Class->getDestructor(); 14461 if (DD && DD->isVirtual() && !DD->isDeleted()) { 14462 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 14463 // If this is an out-of-line declaration, marking it referenced will 14464 // not do anything. Manually call CheckDestructor to look up operator 14465 // delete(). 14466 ContextRAII SavedContext(*this, DD); 14467 CheckDestructor(DD); 14468 } else { 14469 MarkFunctionReferenced(Loc, Class->getDestructor()); 14470 } 14471 } 14472 } 14473 } 14474 14475 // Local classes need to have their virtual members marked 14476 // immediately. For all other classes, we mark their virtual members 14477 // at the end of the translation unit. 14478 if (Class->isLocalClass()) 14479 MarkVirtualMembersReferenced(Loc, Class); 14480 else 14481 VTableUses.push_back(std::make_pair(Class, Loc)); 14482 } 14483 14484 bool Sema::DefineUsedVTables() { 14485 LoadExternalVTableUses(); 14486 if (VTableUses.empty()) 14487 return false; 14488 14489 // Note: The VTableUses vector could grow as a result of marking 14490 // the members of a class as "used", so we check the size each 14491 // time through the loop and prefer indices (which are stable) to 14492 // iterators (which are not). 14493 bool DefinedAnything = false; 14494 for (unsigned I = 0; I != VTableUses.size(); ++I) { 14495 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 14496 if (!Class) 14497 continue; 14498 TemplateSpecializationKind ClassTSK = 14499 Class->getTemplateSpecializationKind(); 14500 14501 SourceLocation Loc = VTableUses[I].second; 14502 14503 bool DefineVTable = true; 14504 14505 // If this class has a key function, but that key function is 14506 // defined in another translation unit, we don't need to emit the 14507 // vtable even though we're using it. 14508 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 14509 if (KeyFunction && !KeyFunction->hasBody()) { 14510 // The key function is in another translation unit. 14511 DefineVTable = false; 14512 TemplateSpecializationKind TSK = 14513 KeyFunction->getTemplateSpecializationKind(); 14514 assert(TSK != TSK_ExplicitInstantiationDefinition && 14515 TSK != TSK_ImplicitInstantiation && 14516 "Instantiations don't have key functions"); 14517 (void)TSK; 14518 } else if (!KeyFunction) { 14519 // If we have a class with no key function that is the subject 14520 // of an explicit instantiation declaration, suppress the 14521 // vtable; it will live with the explicit instantiation 14522 // definition. 14523 bool IsExplicitInstantiationDeclaration = 14524 ClassTSK == TSK_ExplicitInstantiationDeclaration; 14525 for (auto R : Class->redecls()) { 14526 TemplateSpecializationKind TSK 14527 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 14528 if (TSK == TSK_ExplicitInstantiationDeclaration) 14529 IsExplicitInstantiationDeclaration = true; 14530 else if (TSK == TSK_ExplicitInstantiationDefinition) { 14531 IsExplicitInstantiationDeclaration = false; 14532 break; 14533 } 14534 } 14535 14536 if (IsExplicitInstantiationDeclaration) 14537 DefineVTable = false; 14538 } 14539 14540 // The exception specifications for all virtual members may be needed even 14541 // if we are not providing an authoritative form of the vtable in this TU. 14542 // We may choose to emit it available_externally anyway. 14543 if (!DefineVTable) { 14544 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 14545 continue; 14546 } 14547 14548 // Mark all of the virtual members of this class as referenced, so 14549 // that we can build a vtable. Then, tell the AST consumer that a 14550 // vtable for this class is required. 14551 DefinedAnything = true; 14552 MarkVirtualMembersReferenced(Loc, Class); 14553 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14554 if (VTablesUsed[Canonical]) 14555 Consumer.HandleVTable(Class); 14556 14557 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 14558 // no key function or the key function is inlined. Don't warn in C++ ABIs 14559 // that lack key functions, since the user won't be able to make one. 14560 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 14561 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 14562 const FunctionDecl *KeyFunctionDef = nullptr; 14563 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 14564 KeyFunctionDef->isInlined())) { 14565 Diag(Class->getLocation(), 14566 ClassTSK == TSK_ExplicitInstantiationDefinition 14567 ? diag::warn_weak_template_vtable 14568 : diag::warn_weak_vtable) 14569 << Class; 14570 } 14571 } 14572 } 14573 VTableUses.clear(); 14574 14575 return DefinedAnything; 14576 } 14577 14578 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 14579 const CXXRecordDecl *RD) { 14580 for (const auto *I : RD->methods()) 14581 if (I->isVirtual() && !I->isPure()) 14582 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 14583 } 14584 14585 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 14586 const CXXRecordDecl *RD) { 14587 // Mark all functions which will appear in RD's vtable as used. 14588 CXXFinalOverriderMap FinalOverriders; 14589 RD->getFinalOverriders(FinalOverriders); 14590 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 14591 E = FinalOverriders.end(); 14592 I != E; ++I) { 14593 for (OverridingMethods::const_iterator OI = I->second.begin(), 14594 OE = I->second.end(); 14595 OI != OE; ++OI) { 14596 assert(OI->second.size() > 0 && "no final overrider"); 14597 CXXMethodDecl *Overrider = OI->second.front().Method; 14598 14599 // C++ [basic.def.odr]p2: 14600 // [...] A virtual member function is used if it is not pure. [...] 14601 if (!Overrider->isPure()) 14602 MarkFunctionReferenced(Loc, Overrider); 14603 } 14604 } 14605 14606 // Only classes that have virtual bases need a VTT. 14607 if (RD->getNumVBases() == 0) 14608 return; 14609 14610 for (const auto &I : RD->bases()) { 14611 const CXXRecordDecl *Base = 14612 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 14613 if (Base->getNumVBases() == 0) 14614 continue; 14615 MarkVirtualMembersReferenced(Loc, Base); 14616 } 14617 } 14618 14619 /// SetIvarInitializers - This routine builds initialization ASTs for the 14620 /// Objective-C implementation whose ivars need be initialized. 14621 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 14622 if (!getLangOpts().CPlusPlus) 14623 return; 14624 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 14625 SmallVector<ObjCIvarDecl*, 8> ivars; 14626 CollectIvarsToConstructOrDestruct(OID, ivars); 14627 if (ivars.empty()) 14628 return; 14629 SmallVector<CXXCtorInitializer*, 32> AllToInit; 14630 for (unsigned i = 0; i < ivars.size(); i++) { 14631 FieldDecl *Field = ivars[i]; 14632 if (Field->isInvalidDecl()) 14633 continue; 14634 14635 CXXCtorInitializer *Member; 14636 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 14637 InitializationKind InitKind = 14638 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 14639 14640 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 14641 ExprResult MemberInit = 14642 InitSeq.Perform(*this, InitEntity, InitKind, None); 14643 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 14644 // Note, MemberInit could actually come back empty if no initialization 14645 // is required (e.g., because it would call a trivial default constructor) 14646 if (!MemberInit.get() || MemberInit.isInvalid()) 14647 continue; 14648 14649 Member = 14650 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 14651 SourceLocation(), 14652 MemberInit.getAs<Expr>(), 14653 SourceLocation()); 14654 AllToInit.push_back(Member); 14655 14656 // Be sure that the destructor is accessible and is marked as referenced. 14657 if (const RecordType *RecordTy = 14658 Context.getBaseElementType(Field->getType()) 14659 ->getAs<RecordType>()) { 14660 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 14661 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 14662 MarkFunctionReferenced(Field->getLocation(), Destructor); 14663 CheckDestructorAccess(Field->getLocation(), Destructor, 14664 PDiag(diag::err_access_dtor_ivar) 14665 << Context.getBaseElementType(Field->getType())); 14666 } 14667 } 14668 } 14669 ObjCImplementation->setIvarInitializers(Context, 14670 AllToInit.data(), AllToInit.size()); 14671 } 14672 } 14673 14674 static 14675 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 14676 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 14677 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 14678 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 14679 Sema &S) { 14680 if (Ctor->isInvalidDecl()) 14681 return; 14682 14683 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 14684 14685 // Target may not be determinable yet, for instance if this is a dependent 14686 // call in an uninstantiated template. 14687 if (Target) { 14688 const FunctionDecl *FNTarget = nullptr; 14689 (void)Target->hasBody(FNTarget); 14690 Target = const_cast<CXXConstructorDecl*>( 14691 cast_or_null<CXXConstructorDecl>(FNTarget)); 14692 } 14693 14694 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 14695 // Avoid dereferencing a null pointer here. 14696 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 14697 14698 if (!Current.insert(Canonical).second) 14699 return; 14700 14701 // We know that beyond here, we aren't chaining into a cycle. 14702 if (!Target || !Target->isDelegatingConstructor() || 14703 Target->isInvalidDecl() || Valid.count(TCanonical)) { 14704 Valid.insert(Current.begin(), Current.end()); 14705 Current.clear(); 14706 // We've hit a cycle. 14707 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 14708 Current.count(TCanonical)) { 14709 // If we haven't diagnosed this cycle yet, do so now. 14710 if (!Invalid.count(TCanonical)) { 14711 S.Diag((*Ctor->init_begin())->getSourceLocation(), 14712 diag::warn_delegating_ctor_cycle) 14713 << Ctor; 14714 14715 // Don't add a note for a function delegating directly to itself. 14716 if (TCanonical != Canonical) 14717 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 14718 14719 CXXConstructorDecl *C = Target; 14720 while (C->getCanonicalDecl() != Canonical) { 14721 const FunctionDecl *FNTarget = nullptr; 14722 (void)C->getTargetConstructor()->hasBody(FNTarget); 14723 assert(FNTarget && "Ctor cycle through bodiless function"); 14724 14725 C = const_cast<CXXConstructorDecl*>( 14726 cast<CXXConstructorDecl>(FNTarget)); 14727 S.Diag(C->getLocation(), diag::note_which_delegates_to); 14728 } 14729 } 14730 14731 Invalid.insert(Current.begin(), Current.end()); 14732 Current.clear(); 14733 } else { 14734 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 14735 } 14736 } 14737 14738 14739 void Sema::CheckDelegatingCtorCycles() { 14740 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 14741 14742 for (DelegatingCtorDeclsType::iterator 14743 I = DelegatingCtorDecls.begin(ExternalSource), 14744 E = DelegatingCtorDecls.end(); 14745 I != E; ++I) 14746 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 14747 14748 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 14749 CE = Invalid.end(); 14750 CI != CE; ++CI) 14751 (*CI)->setInvalidDecl(); 14752 } 14753 14754 namespace { 14755 /// \brief AST visitor that finds references to the 'this' expression. 14756 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 14757 Sema &S; 14758 14759 public: 14760 explicit FindCXXThisExpr(Sema &S) : S(S) { } 14761 14762 bool VisitCXXThisExpr(CXXThisExpr *E) { 14763 S.Diag(E->getLocation(), diag::err_this_static_member_func) 14764 << E->isImplicit(); 14765 return false; 14766 } 14767 }; 14768 } 14769 14770 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 14771 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14772 if (!TSInfo) 14773 return false; 14774 14775 TypeLoc TL = TSInfo->getTypeLoc(); 14776 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14777 if (!ProtoTL) 14778 return false; 14779 14780 // C++11 [expr.prim.general]p3: 14781 // [The expression this] shall not appear before the optional 14782 // cv-qualifier-seq and it shall not appear within the declaration of a 14783 // static member function (although its type and value category are defined 14784 // within a static member function as they are within a non-static member 14785 // function). [ Note: this is because declaration matching does not occur 14786 // until the complete declarator is known. - end note ] 14787 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14788 FindCXXThisExpr Finder(*this); 14789 14790 // If the return type came after the cv-qualifier-seq, check it now. 14791 if (Proto->hasTrailingReturn() && 14792 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 14793 return true; 14794 14795 // Check the exception specification. 14796 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 14797 return true; 14798 14799 return checkThisInStaticMemberFunctionAttributes(Method); 14800 } 14801 14802 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 14803 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14804 if (!TSInfo) 14805 return false; 14806 14807 TypeLoc TL = TSInfo->getTypeLoc(); 14808 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14809 if (!ProtoTL) 14810 return false; 14811 14812 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14813 FindCXXThisExpr Finder(*this); 14814 14815 switch (Proto->getExceptionSpecType()) { 14816 case EST_Unparsed: 14817 case EST_Uninstantiated: 14818 case EST_Unevaluated: 14819 case EST_BasicNoexcept: 14820 case EST_DynamicNone: 14821 case EST_MSAny: 14822 case EST_None: 14823 break; 14824 14825 case EST_ComputedNoexcept: 14826 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 14827 return true; 14828 LLVM_FALLTHROUGH; 14829 14830 case EST_Dynamic: 14831 for (const auto &E : Proto->exceptions()) { 14832 if (!Finder.TraverseType(E)) 14833 return true; 14834 } 14835 break; 14836 } 14837 14838 return false; 14839 } 14840 14841 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 14842 FindCXXThisExpr Finder(*this); 14843 14844 // Check attributes. 14845 for (const auto *A : Method->attrs()) { 14846 // FIXME: This should be emitted by tblgen. 14847 Expr *Arg = nullptr; 14848 ArrayRef<Expr *> Args; 14849 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 14850 Arg = G->getArg(); 14851 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 14852 Arg = G->getArg(); 14853 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 14854 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 14855 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 14856 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 14857 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 14858 Arg = ETLF->getSuccessValue(); 14859 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 14860 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 14861 Arg = STLF->getSuccessValue(); 14862 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 14863 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 14864 Arg = LR->getArg(); 14865 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 14866 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 14867 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 14868 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14869 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 14870 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14871 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 14872 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14873 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 14874 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14875 14876 if (Arg && !Finder.TraverseStmt(Arg)) 14877 return true; 14878 14879 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 14880 if (!Finder.TraverseStmt(Args[I])) 14881 return true; 14882 } 14883 } 14884 14885 return false; 14886 } 14887 14888 void Sema::checkExceptionSpecification( 14889 bool IsTopLevel, ExceptionSpecificationType EST, 14890 ArrayRef<ParsedType> DynamicExceptions, 14891 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 14892 SmallVectorImpl<QualType> &Exceptions, 14893 FunctionProtoType::ExceptionSpecInfo &ESI) { 14894 Exceptions.clear(); 14895 ESI.Type = EST; 14896 if (EST == EST_Dynamic) { 14897 Exceptions.reserve(DynamicExceptions.size()); 14898 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 14899 // FIXME: Preserve type source info. 14900 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 14901 14902 if (IsTopLevel) { 14903 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 14904 collectUnexpandedParameterPacks(ET, Unexpanded); 14905 if (!Unexpanded.empty()) { 14906 DiagnoseUnexpandedParameterPacks( 14907 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 14908 Unexpanded); 14909 continue; 14910 } 14911 } 14912 14913 // Check that the type is valid for an exception spec, and 14914 // drop it if not. 14915 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 14916 Exceptions.push_back(ET); 14917 } 14918 ESI.Exceptions = Exceptions; 14919 return; 14920 } 14921 14922 if (EST == EST_ComputedNoexcept) { 14923 // If an error occurred, there's no expression here. 14924 if (NoexceptExpr) { 14925 assert((NoexceptExpr->isTypeDependent() || 14926 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 14927 Context.BoolTy) && 14928 "Parser should have made sure that the expression is boolean"); 14929 if (IsTopLevel && NoexceptExpr && 14930 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 14931 ESI.Type = EST_BasicNoexcept; 14932 return; 14933 } 14934 14935 if (!NoexceptExpr->isValueDependent()) { 14936 ExprResult Result = VerifyIntegerConstantExpression( 14937 NoexceptExpr, nullptr, diag::err_noexcept_needs_constant_expression, 14938 /*AllowFold*/ false); 14939 if (Result.isInvalid()) { 14940 ESI.Type = EST_BasicNoexcept; 14941 return; 14942 } 14943 NoexceptExpr = Result.get(); 14944 } 14945 ESI.NoexceptExpr = NoexceptExpr; 14946 } 14947 return; 14948 } 14949 } 14950 14951 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 14952 ExceptionSpecificationType EST, 14953 SourceRange SpecificationRange, 14954 ArrayRef<ParsedType> DynamicExceptions, 14955 ArrayRef<SourceRange> DynamicExceptionRanges, 14956 Expr *NoexceptExpr) { 14957 if (!MethodD) 14958 return; 14959 14960 // Dig out the method we're referring to. 14961 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 14962 MethodD = FunTmpl->getTemplatedDecl(); 14963 14964 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 14965 if (!Method) 14966 return; 14967 14968 // Check the exception specification. 14969 llvm::SmallVector<QualType, 4> Exceptions; 14970 FunctionProtoType::ExceptionSpecInfo ESI; 14971 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 14972 DynamicExceptionRanges, NoexceptExpr, Exceptions, 14973 ESI); 14974 14975 // Update the exception specification on the function type. 14976 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 14977 14978 if (Method->isStatic()) 14979 checkThisInStaticMemberFunctionExceptionSpec(Method); 14980 14981 if (Method->isVirtual()) { 14982 // Check overrides, which we previously had to delay. 14983 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 14984 OEnd = Method->end_overridden_methods(); 14985 O != OEnd; ++O) 14986 CheckOverridingFunctionExceptionSpec(Method, *O); 14987 } 14988 } 14989 14990 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 14991 /// 14992 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 14993 SourceLocation DeclStart, 14994 Declarator &D, Expr *BitWidth, 14995 InClassInitStyle InitStyle, 14996 AccessSpecifier AS, 14997 AttributeList *MSPropertyAttr) { 14998 IdentifierInfo *II = D.getIdentifier(); 14999 if (!II) { 15000 Diag(DeclStart, diag::err_anonymous_property); 15001 return nullptr; 15002 } 15003 SourceLocation Loc = D.getIdentifierLoc(); 15004 15005 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15006 QualType T = TInfo->getType(); 15007 if (getLangOpts().CPlusPlus) { 15008 CheckExtraCXXDefaultArguments(D); 15009 15010 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15011 UPPC_DataMemberType)) { 15012 D.setInvalidType(); 15013 T = Context.IntTy; 15014 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15015 } 15016 } 15017 15018 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15019 15020 if (D.getDeclSpec().isInlineSpecified()) 15021 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15022 << getLangOpts().CPlusPlus17; 15023 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15024 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15025 diag::err_invalid_thread) 15026 << DeclSpec::getSpecifierName(TSCS); 15027 15028 // Check to see if this name was declared as a member previously 15029 NamedDecl *PrevDecl = nullptr; 15030 LookupResult Previous(*this, II, Loc, LookupMemberName, 15031 ForVisibleRedeclaration); 15032 LookupName(Previous, S); 15033 switch (Previous.getResultKind()) { 15034 case LookupResult::Found: 15035 case LookupResult::FoundUnresolvedValue: 15036 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15037 break; 15038 15039 case LookupResult::FoundOverloaded: 15040 PrevDecl = Previous.getRepresentativeDecl(); 15041 break; 15042 15043 case LookupResult::NotFound: 15044 case LookupResult::NotFoundInCurrentInstantiation: 15045 case LookupResult::Ambiguous: 15046 break; 15047 } 15048 15049 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15050 // Maybe we will complain about the shadowed template parameter. 15051 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15052 // Just pretend that we didn't see the previous declaration. 15053 PrevDecl = nullptr; 15054 } 15055 15056 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15057 PrevDecl = nullptr; 15058 15059 SourceLocation TSSL = D.getLocStart(); 15060 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 15061 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 15062 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 15063 ProcessDeclAttributes(TUScope, NewPD, D); 15064 NewPD->setAccess(AS); 15065 15066 if (NewPD->isInvalidDecl()) 15067 Record->setInvalidDecl(); 15068 15069 if (D.getDeclSpec().isModulePrivateSpecified()) 15070 NewPD->setModulePrivate(); 15071 15072 if (NewPD->isInvalidDecl() && PrevDecl) { 15073 // Don't introduce NewFD into scope; there's already something 15074 // with the same name in the same scope. 15075 } else if (II) { 15076 PushOnScopeChains(NewPD, S); 15077 } else 15078 Record->addDecl(NewPD); 15079 15080 return NewPD; 15081 } 15082