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 switch(EST) { 171 // If this function can throw any exceptions, make a note of that. 172 case EST_MSAny: 173 case EST_None: 174 ClearExceptions(); 175 ComputedEST = EST; 176 return; 177 // FIXME: If the call to this decl is using any of its default arguments, we 178 // need to search them for potentially-throwing calls. 179 // If this function has a basic noexcept, it doesn't affect the outcome. 180 case EST_BasicNoexcept: 181 return; 182 // If we're still at noexcept(true) and there's a nothrow() callee, 183 // change to that specification. 184 case EST_DynamicNone: 185 if (ComputedEST == EST_BasicNoexcept) 186 ComputedEST = EST_DynamicNone; 187 return; 188 // Check out noexcept specs. 189 case EST_ComputedNoexcept: 190 { 191 FunctionProtoType::NoexceptResult NR = 192 Proto->getNoexceptSpec(Self->Context); 193 assert(NR != FunctionProtoType::NR_NoNoexcept && 194 "Must have noexcept result for EST_ComputedNoexcept."); 195 assert(NR != FunctionProtoType::NR_Dependent && 196 "Should not generate implicit declarations for dependent cases, " 197 "and don't know how to handle them anyway."); 198 // noexcept(false) -> no spec on the new function 199 if (NR == FunctionProtoType::NR_Throw) { 200 ClearExceptions(); 201 ComputedEST = EST_None; 202 } 203 // noexcept(true) won't change anything either. 204 return; 205 } 206 default: 207 break; 208 } 209 assert(EST == EST_Dynamic && "EST case not considered earlier."); 210 assert(ComputedEST != EST_None && 211 "Shouldn't collect exceptions when throw-all is guaranteed."); 212 ComputedEST = EST_Dynamic; 213 // Record the exceptions in this function's exception specification. 214 for (const auto &E : Proto->exceptions()) 215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 216 Exceptions.push_back(E); 217 } 218 219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 220 if (!E || ComputedEST == EST_MSAny) 221 return; 222 223 // FIXME: 224 // 225 // C++0x [except.spec]p14: 226 // [An] implicit exception-specification specifies the type-id T if and 227 // only if T is allowed by the exception-specification of a function directly 228 // invoked by f's implicit definition; f shall allow all exceptions if any 229 // function it directly invokes allows all exceptions, and f shall allow no 230 // exceptions if every function it directly invokes allows no exceptions. 231 // 232 // Note in particular that if an implicit exception-specification is generated 233 // for a function containing a throw-expression, that specification can still 234 // be noexcept(true). 235 // 236 // Note also that 'directly invoked' is not defined in the standard, and there 237 // is no indication that we should only consider potentially-evaluated calls. 238 // 239 // Ultimately we should implement the intent of the standard: the exception 240 // specification should be the set of exceptions which can be thrown by the 241 // implicit definition. For now, we assume that any non-nothrow expression can 242 // throw any exception. 243 244 if (Self->canThrow(E)) 245 ComputedEST = EST_None; 246 } 247 248 bool 249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 250 SourceLocation EqualLoc) { 251 if (RequireCompleteType(Param->getLocation(), Param->getType(), 252 diag::err_typecheck_decl_incomplete_type)) { 253 Param->setInvalidDecl(); 254 return true; 255 } 256 257 // C++ [dcl.fct.default]p5 258 // A default argument expression is implicitly converted (clause 259 // 4) to the parameter type. The default argument expression has 260 // the same semantic constraints as the initializer expression in 261 // a declaration of a variable of the parameter type, using the 262 // copy-initialization semantics (8.5). 263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 264 Param); 265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 266 EqualLoc); 267 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 269 if (Result.isInvalid()) 270 return true; 271 Arg = Result.getAs<Expr>(); 272 273 CheckCompletedExpr(Arg, EqualLoc); 274 Arg = MaybeCreateExprWithCleanups(Arg); 275 276 // Okay: add the default argument to the parameter 277 Param->setDefaultArg(Arg); 278 279 // We have already instantiated this parameter; provide each of the 280 // instantiations with the uninstantiated default argument. 281 UnparsedDefaultArgInstantiationsMap::iterator InstPos 282 = UnparsedDefaultArgInstantiations.find(Param); 283 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 286 287 // We're done tracking this parameter's instantiations. 288 UnparsedDefaultArgInstantiations.erase(InstPos); 289 } 290 291 return false; 292 } 293 294 /// ActOnParamDefaultArgument - Check whether the default argument 295 /// provided for a function parameter is well-formed. If so, attach it 296 /// to the parameter declaration. 297 void 298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 299 Expr *DefaultArg) { 300 if (!param || !DefaultArg) 301 return; 302 303 ParmVarDecl *Param = cast<ParmVarDecl>(param); 304 UnparsedDefaultArgLocs.erase(Param); 305 306 // Default arguments are only permitted in C++ 307 if (!getLangOpts().CPlusPlus) { 308 Diag(EqualLoc, diag::err_param_default_argument) 309 << DefaultArg->getSourceRange(); 310 Param->setInvalidDecl(); 311 return; 312 } 313 314 // Check for unexpanded parameter packs. 315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 316 Param->setInvalidDecl(); 317 return; 318 } 319 320 // C++11 [dcl.fct.default]p3 321 // A default argument expression [...] shall not be specified for a 322 // parameter pack. 323 if (Param->isParameterPack()) { 324 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 325 << DefaultArg->getSourceRange(); 326 return; 327 } 328 329 // Check that the default argument is well-formed 330 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 331 if (DefaultArgChecker.Visit(DefaultArg)) { 332 Param->setInvalidDecl(); 333 return; 334 } 335 336 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 337 } 338 339 /// ActOnParamUnparsedDefaultArgument - We've seen a default 340 /// argument for a function parameter, but we can't parse it yet 341 /// because we're inside a class definition. Note that this default 342 /// argument will be parsed later. 343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 344 SourceLocation EqualLoc, 345 SourceLocation ArgLoc) { 346 if (!param) 347 return; 348 349 ParmVarDecl *Param = cast<ParmVarDecl>(param); 350 Param->setUnparsedDefaultArg(); 351 UnparsedDefaultArgLocs[Param] = ArgLoc; 352 } 353 354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 355 /// the default argument for the parameter param failed. 356 void Sema::ActOnParamDefaultArgumentError(Decl *param, 357 SourceLocation EqualLoc) { 358 if (!param) 359 return; 360 361 ParmVarDecl *Param = cast<ParmVarDecl>(param); 362 Param->setInvalidDecl(); 363 UnparsedDefaultArgLocs.erase(Param); 364 Param->setDefaultArg(new(Context) 365 OpaqueValueExpr(EqualLoc, 366 Param->getType().getNonReferenceType(), 367 VK_RValue)); 368 } 369 370 /// CheckExtraCXXDefaultArguments - Check for any extra default 371 /// arguments in the declarator, which is not a function declaration 372 /// or definition and therefore is not permitted to have default 373 /// arguments. This routine should be invoked for every declarator 374 /// that is not a function declaration or definition. 375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 376 // C++ [dcl.fct.default]p3 377 // A default argument expression shall be specified only in the 378 // parameter-declaration-clause of a function declaration or in a 379 // template-parameter (14.1). It shall not be specified for a 380 // parameter pack. If it is specified in a 381 // parameter-declaration-clause, it shall not occur within a 382 // declarator or abstract-declarator of a parameter-declaration. 383 bool MightBeFunction = D.isFunctionDeclarationContext(); 384 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 385 DeclaratorChunk &chunk = D.getTypeObject(i); 386 if (chunk.Kind == DeclaratorChunk::Function) { 387 if (MightBeFunction) { 388 // This is a function declaration. It can have default arguments, but 389 // keep looking in case its return type is a function type with default 390 // arguments. 391 MightBeFunction = false; 392 continue; 393 } 394 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 395 ++argIdx) { 396 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 397 if (Param->hasUnparsedDefaultArg()) { 398 std::unique_ptr<CachedTokens> Toks = 399 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 400 SourceRange SR; 401 if (Toks->size() > 1) 402 SR = SourceRange((*Toks)[1].getLocation(), 403 Toks->back().getLocation()); 404 else 405 SR = UnparsedDefaultArgLocs[Param]; 406 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 407 << SR; 408 } else if (Param->getDefaultArg()) { 409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 410 << Param->getDefaultArg()->getSourceRange(); 411 Param->setDefaultArg(nullptr); 412 } 413 } 414 } else if (chunk.Kind != DeclaratorChunk::Paren) { 415 MightBeFunction = false; 416 } 417 } 418 } 419 420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 423 if (!PVD->hasDefaultArg()) 424 return false; 425 if (!PVD->hasInheritedDefaultArg()) 426 return true; 427 } 428 return false; 429 } 430 431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 432 /// function, once we already know that they have the same 433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 434 /// error, false otherwise. 435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 436 Scope *S) { 437 bool Invalid = false; 438 439 // The declaration context corresponding to the scope is the semantic 440 // parent, unless this is a local function declaration, in which case 441 // it is that surrounding function. 442 DeclContext *ScopeDC = New->isLocalExternDecl() 443 ? New->getLexicalDeclContext() 444 : New->getDeclContext(); 445 446 // Find the previous declaration for the purpose of default arguments. 447 FunctionDecl *PrevForDefaultArgs = Old; 448 for (/**/; PrevForDefaultArgs; 449 // Don't bother looking back past the latest decl if this is a local 450 // extern declaration; nothing else could work. 451 PrevForDefaultArgs = New->isLocalExternDecl() 452 ? nullptr 453 : PrevForDefaultArgs->getPreviousDecl()) { 454 // Ignore hidden declarations. 455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 456 continue; 457 458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 459 !New->isCXXClassMember()) { 460 // Ignore default arguments of old decl if they are not in 461 // the same scope and this is not an out-of-line definition of 462 // a member function. 463 continue; 464 } 465 466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 467 // If only one of these is a local function declaration, then they are 468 // declared in different scopes, even though isDeclInScope may think 469 // they're in the same scope. (If both are local, the scope check is 470 // sufficient, and if neither is local, then they are in the same scope.) 471 continue; 472 } 473 474 // We found the right previous declaration. 475 break; 476 } 477 478 // C++ [dcl.fct.default]p4: 479 // For non-template functions, default arguments can be added in 480 // later declarations of a function in the same 481 // scope. Declarations in different scopes have completely 482 // distinct sets of default arguments. That is, declarations in 483 // inner scopes do not acquire default arguments from 484 // declarations in outer scopes, and vice versa. In a given 485 // function declaration, all parameters subsequent to a 486 // parameter with a default argument shall have default 487 // arguments supplied in this or previous declarations. A 488 // default argument shall not be redefined by a later 489 // declaration (not even to the same value). 490 // 491 // C++ [dcl.fct.default]p6: 492 // Except for member functions of class templates, the default arguments 493 // in a member function definition that appears outside of the class 494 // definition are added to the set of default arguments provided by the 495 // member function declaration in the class definition. 496 for (unsigned p = 0, NumParams = PrevForDefaultArgs 497 ? PrevForDefaultArgs->getNumParams() 498 : 0; 499 p < NumParams; ++p) { 500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 501 ParmVarDecl *NewParam = New->getParamDecl(p); 502 503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 504 bool NewParamHasDfl = NewParam->hasDefaultArg(); 505 506 if (OldParamHasDfl && NewParamHasDfl) { 507 unsigned DiagDefaultParamID = 508 diag::err_param_default_argument_redefinition; 509 510 // MSVC accepts that default parameters be redefined for member functions 511 // of template class. The new default parameter's value is ignored. 512 Invalid = true; 513 if (getLangOpts().MicrosoftExt) { 514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 515 if (MD && MD->getParent()->getDescribedClassTemplate()) { 516 // Merge the old default argument into the new parameter. 517 NewParam->setHasInheritedDefaultArg(); 518 if (OldParam->hasUninstantiatedDefaultArg()) 519 NewParam->setUninstantiatedDefaultArg( 520 OldParam->getUninstantiatedDefaultArg()); 521 else 522 NewParam->setDefaultArg(OldParam->getInit()); 523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 524 Invalid = false; 525 } 526 } 527 528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 529 // hint here. Alternatively, we could walk the type-source information 530 // for NewParam to find the last source location in the type... but it 531 // isn't worth the effort right now. This is the kind of test case that 532 // is hard to get right: 533 // int f(int); 534 // void g(int (*fp)(int) = f); 535 // void g(int (*fp)(int) = &f); 536 Diag(NewParam->getLocation(), DiagDefaultParamID) 537 << NewParam->getDefaultArgRange(); 538 539 // Look for the function declaration where the default argument was 540 // actually written, which may be a declaration prior to Old. 541 for (auto Older = PrevForDefaultArgs; 542 OldParam->hasInheritedDefaultArg(); /**/) { 543 Older = Older->getPreviousDecl(); 544 OldParam = Older->getParamDecl(p); 545 } 546 547 Diag(OldParam->getLocation(), diag::note_previous_definition) 548 << OldParam->getDefaultArgRange(); 549 } else if (OldParamHasDfl) { 550 // Merge the old default argument into the new parameter unless the new 551 // function is a friend declaration in a template class. In the latter 552 // case the default arguments will be inherited when the friend 553 // declaration will be instantiated. 554 if (New->getFriendObjectKind() == Decl::FOK_None || 555 !New->getLexicalDeclContext()->isDependentContext()) { 556 // It's important to use getInit() here; getDefaultArg() 557 // strips off any top-level ExprWithCleanups. 558 NewParam->setHasInheritedDefaultArg(); 559 if (OldParam->hasUnparsedDefaultArg()) 560 NewParam->setUnparsedDefaultArg(); 561 else if (OldParam->hasUninstantiatedDefaultArg()) 562 NewParam->setUninstantiatedDefaultArg( 563 OldParam->getUninstantiatedDefaultArg()); 564 else 565 NewParam->setDefaultArg(OldParam->getInit()); 566 } 567 } else if (NewParamHasDfl) { 568 if (New->getDescribedFunctionTemplate()) { 569 // Paragraph 4, quoted above, only applies to non-template functions. 570 Diag(NewParam->getLocation(), 571 diag::err_param_default_argument_template_redecl) 572 << NewParam->getDefaultArgRange(); 573 Diag(PrevForDefaultArgs->getLocation(), 574 diag::note_template_prev_declaration) 575 << false; 576 } else if (New->getTemplateSpecializationKind() 577 != TSK_ImplicitInstantiation && 578 New->getTemplateSpecializationKind() != TSK_Undeclared) { 579 // C++ [temp.expr.spec]p21: 580 // Default function arguments shall not be specified in a declaration 581 // or a definition for one of the following explicit specializations: 582 // - the explicit specialization of a function template; 583 // - the explicit specialization of a member function template; 584 // - the explicit specialization of a member function of a class 585 // template where the class template specialization to which the 586 // member function specialization belongs is implicitly 587 // instantiated. 588 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 589 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 590 << New->getDeclName() 591 << NewParam->getDefaultArgRange(); 592 } else if (New->getDeclContext()->isDependentContext()) { 593 // C++ [dcl.fct.default]p6 (DR217): 594 // Default arguments for a member function of a class template shall 595 // be specified on the initial declaration of the member function 596 // within the class template. 597 // 598 // Reading the tea leaves a bit in DR217 and its reference to DR205 599 // leads me to the conclusion that one cannot add default function 600 // arguments for an out-of-line definition of a member function of a 601 // dependent type. 602 int WhichKind = 2; 603 if (CXXRecordDecl *Record 604 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 605 if (Record->getDescribedClassTemplate()) 606 WhichKind = 0; 607 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 608 WhichKind = 1; 609 else 610 WhichKind = 2; 611 } 612 613 Diag(NewParam->getLocation(), 614 diag::err_param_default_argument_member_template_redecl) 615 << WhichKind 616 << NewParam->getDefaultArgRange(); 617 } 618 } 619 } 620 621 // DR1344: If a default argument is added outside a class definition and that 622 // default argument makes the function a special member function, the program 623 // is ill-formed. This can only happen for constructors. 624 if (isa<CXXConstructorDecl>(New) && 625 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 626 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 627 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 628 if (NewSM != OldSM) { 629 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 630 assert(NewParam->hasDefaultArg()); 631 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 632 << NewParam->getDefaultArgRange() << NewSM; 633 Diag(Old->getLocation(), diag::note_previous_declaration); 634 } 635 } 636 637 const FunctionDecl *Def; 638 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 639 // template has a constexpr specifier then all its declarations shall 640 // contain the constexpr specifier. 641 if (New->isConstexpr() != Old->isConstexpr()) { 642 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 643 << New << New->isConstexpr(); 644 Diag(Old->getLocation(), diag::note_previous_declaration); 645 Invalid = true; 646 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 647 Old->isDefined(Def) && 648 // If a friend function is inlined but does not have 'inline' 649 // specifier, it is a definition. Do not report attribute conflict 650 // in this case, redefinition will be diagnosed later. 651 (New->isInlineSpecified() || 652 New->getFriendObjectKind() == Decl::FOK_None)) { 653 // C++11 [dcl.fcn.spec]p4: 654 // If the definition of a function appears in a translation unit before its 655 // first declaration as inline, the program is ill-formed. 656 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 657 Diag(Def->getLocation(), diag::note_previous_definition); 658 Invalid = true; 659 } 660 661 // FIXME: It's not clear what should happen if multiple declarations of a 662 // deduction guide have different explicitness. For now at least we simply 663 // reject any case where the explicitness changes. 664 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New); 665 if (NewGuide && NewGuide->isExplicitSpecified() != 666 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) { 667 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch) 668 << NewGuide->isExplicitSpecified(); 669 Diag(Old->getLocation(), diag::note_previous_declaration); 670 } 671 672 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 673 // argument expression, that declaration shall be a definition and shall be 674 // the only declaration of the function or function template in the 675 // translation unit. 676 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 677 functionDeclHasDefaultArgument(Old)) { 678 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 679 Diag(Old->getLocation(), diag::note_previous_declaration); 680 Invalid = true; 681 } 682 683 return Invalid; 684 } 685 686 NamedDecl * 687 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 688 MultiTemplateParamsArg TemplateParamLists) { 689 assert(D.isDecompositionDeclarator()); 690 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 691 692 // The syntax only allows a decomposition declarator as a simple-declaration 693 // or a for-range-declaration, but we parse it in more cases than that. 694 if (!D.mayHaveDecompositionDeclarator()) { 695 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 696 << Decomp.getSourceRange(); 697 return nullptr; 698 } 699 700 if (!TemplateParamLists.empty()) { 701 // FIXME: There's no rule against this, but there are also no rules that 702 // would actually make it usable, so we reject it for now. 703 Diag(TemplateParamLists.front()->getTemplateLoc(), 704 diag::err_decomp_decl_template); 705 return nullptr; 706 } 707 708 Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z 709 ? diag::warn_cxx14_compat_decomp_decl 710 : diag::ext_decomp_decl) 711 << Decomp.getSourceRange(); 712 713 // The semantic context is always just the current context. 714 DeclContext *const DC = CurContext; 715 716 // C++1z [dcl.dcl]/8: 717 // The decl-specifier-seq shall contain only the type-specifier auto 718 // and cv-qualifiers. 719 auto &DS = D.getDeclSpec(); 720 { 721 SmallVector<StringRef, 8> BadSpecifiers; 722 SmallVector<SourceLocation, 8> BadSpecifierLocs; 723 if (auto SCS = DS.getStorageClassSpec()) { 724 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 725 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 726 } 727 if (auto TSCS = DS.getThreadStorageClassSpec()) { 728 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 729 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 730 } 731 if (DS.isConstexprSpecified()) { 732 BadSpecifiers.push_back("constexpr"); 733 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 734 } 735 if (DS.isInlineSpecified()) { 736 BadSpecifiers.push_back("inline"); 737 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 738 } 739 if (!BadSpecifiers.empty()) { 740 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 741 Err << (int)BadSpecifiers.size() 742 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 743 // Don't add FixItHints to remove the specifiers; we do still respect 744 // them when building the underlying variable. 745 for (auto Loc : BadSpecifierLocs) 746 Err << SourceRange(Loc, Loc); 747 } 748 // We can't recover from it being declared as a typedef. 749 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 750 return nullptr; 751 } 752 753 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 754 QualType R = TInfo->getType(); 755 756 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 757 UPPC_DeclarationType)) 758 D.setInvalidType(); 759 760 // The syntax only allows a single ref-qualifier prior to the decomposition 761 // declarator. No other declarator chunks are permitted. Also check the type 762 // specifier here. 763 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 764 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 765 (D.getNumTypeObjects() == 1 && 766 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 767 Diag(Decomp.getLSquareLoc(), 768 (D.hasGroupingParens() || 769 (D.getNumTypeObjects() && 770 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 771 ? diag::err_decomp_decl_parens 772 : diag::err_decomp_decl_type) 773 << R; 774 775 // In most cases, there's no actual problem with an explicitly-specified 776 // type, but a function type won't work here, and ActOnVariableDeclarator 777 // shouldn't be called for such a type. 778 if (R->isFunctionType()) 779 D.setInvalidType(); 780 } 781 782 // Build the BindingDecls. 783 SmallVector<BindingDecl*, 8> Bindings; 784 785 // Build the BindingDecls. 786 for (auto &B : D.getDecompositionDeclarator().bindings()) { 787 // Check for name conflicts. 788 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 789 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 790 ForRedeclaration); 791 LookupName(Previous, S, 792 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 793 794 // It's not permitted to shadow a template parameter name. 795 if (Previous.isSingleResult() && 796 Previous.getFoundDecl()->isTemplateParameter()) { 797 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 798 Previous.getFoundDecl()); 799 Previous.clear(); 800 } 801 802 bool ConsiderLinkage = DC->isFunctionOrMethod() && 803 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 804 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 805 /*AllowInlineNamespace*/false); 806 if (!Previous.empty()) { 807 auto *Old = Previous.getRepresentativeDecl(); 808 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 809 Diag(Old->getLocation(), diag::note_previous_definition); 810 } 811 812 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 813 PushOnScopeChains(BD, S, true); 814 Bindings.push_back(BD); 815 ParsingInitForAutoVars.insert(BD); 816 } 817 818 // There are no prior lookup results for the variable itself, because it 819 // is unnamed. 820 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 821 Decomp.getLSquareLoc()); 822 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 823 824 // Build the variable that holds the non-decomposed object. 825 bool AddToScope = true; 826 NamedDecl *New = 827 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 828 MultiTemplateParamsArg(), AddToScope, Bindings); 829 CurContext->addHiddenDecl(New); 830 831 if (isInOpenMPDeclareTargetContext()) 832 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 833 834 return New; 835 } 836 837 static bool checkSimpleDecomposition( 838 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 839 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 840 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 841 if ((int64_t)Bindings.size() != NumElems) { 842 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 843 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 844 << (NumElems < Bindings.size()); 845 return true; 846 } 847 848 unsigned I = 0; 849 for (auto *B : Bindings) { 850 SourceLocation Loc = B->getLocation(); 851 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 852 if (E.isInvalid()) 853 return true; 854 E = GetInit(Loc, E.get(), I++); 855 if (E.isInvalid()) 856 return true; 857 B->setBinding(ElemType, E.get()); 858 } 859 860 return false; 861 } 862 863 static bool checkArrayLikeDecomposition(Sema &S, 864 ArrayRef<BindingDecl *> Bindings, 865 ValueDecl *Src, QualType DecompType, 866 const llvm::APSInt &NumElems, 867 QualType ElemType) { 868 return checkSimpleDecomposition( 869 S, Bindings, Src, DecompType, NumElems, ElemType, 870 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 871 ExprResult E = S.ActOnIntegerConstant(Loc, I); 872 if (E.isInvalid()) 873 return ExprError(); 874 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 875 }); 876 } 877 878 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 879 ValueDecl *Src, QualType DecompType, 880 const ConstantArrayType *CAT) { 881 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 882 llvm::APSInt(CAT->getSize()), 883 CAT->getElementType()); 884 } 885 886 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 887 ValueDecl *Src, QualType DecompType, 888 const VectorType *VT) { 889 return checkArrayLikeDecomposition( 890 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 891 S.Context.getQualifiedType(VT->getElementType(), 892 DecompType.getQualifiers())); 893 } 894 895 static bool checkComplexDecomposition(Sema &S, 896 ArrayRef<BindingDecl *> Bindings, 897 ValueDecl *Src, QualType DecompType, 898 const ComplexType *CT) { 899 return checkSimpleDecomposition( 900 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 901 S.Context.getQualifiedType(CT->getElementType(), 902 DecompType.getQualifiers()), 903 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 904 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 905 }); 906 } 907 908 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 909 TemplateArgumentListInfo &Args) { 910 SmallString<128> SS; 911 llvm::raw_svector_ostream OS(SS); 912 bool First = true; 913 for (auto &Arg : Args.arguments()) { 914 if (!First) 915 OS << ", "; 916 Arg.getArgument().print(PrintingPolicy, OS); 917 First = false; 918 } 919 return OS.str(); 920 } 921 922 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 923 SourceLocation Loc, StringRef Trait, 924 TemplateArgumentListInfo &Args, 925 unsigned DiagID) { 926 auto DiagnoseMissing = [&] { 927 if (DiagID) 928 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 929 Args); 930 return true; 931 }; 932 933 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 934 NamespaceDecl *Std = S.getStdNamespace(); 935 if (!Std) 936 return DiagnoseMissing(); 937 938 // Look up the trait itself, within namespace std. We can diagnose various 939 // problems with this lookup even if we've been asked to not diagnose a 940 // missing specialization, because this can only fail if the user has been 941 // declaring their own names in namespace std or we don't support the 942 // standard library implementation in use. 943 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 944 Loc, Sema::LookupOrdinaryName); 945 if (!S.LookupQualifiedName(Result, Std)) 946 return DiagnoseMissing(); 947 if (Result.isAmbiguous()) 948 return true; 949 950 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 951 if (!TraitTD) { 952 Result.suppressDiagnostics(); 953 NamedDecl *Found = *Result.begin(); 954 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 955 S.Diag(Found->getLocation(), diag::note_declared_at); 956 return true; 957 } 958 959 // Build the template-id. 960 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 961 if (TraitTy.isNull()) 962 return true; 963 if (!S.isCompleteType(Loc, TraitTy)) { 964 if (DiagID) 965 S.RequireCompleteType( 966 Loc, TraitTy, DiagID, 967 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 968 return true; 969 } 970 971 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 972 assert(RD && "specialization of class template is not a class?"); 973 974 // Look up the member of the trait type. 975 S.LookupQualifiedName(TraitMemberLookup, RD); 976 return TraitMemberLookup.isAmbiguous(); 977 } 978 979 static TemplateArgumentLoc 980 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 981 uint64_t I) { 982 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 983 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 984 } 985 986 static TemplateArgumentLoc 987 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 988 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 989 } 990 991 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 992 993 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 994 llvm::APSInt &Size) { 995 EnterExpressionEvaluationContext ContextRAII( 996 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 997 998 DeclarationName Value = S.PP.getIdentifierInfo("value"); 999 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1000 1001 // Form template argument list for tuple_size<T>. 1002 TemplateArgumentListInfo Args(Loc, Loc); 1003 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1004 1005 // If there's no tuple_size specialization, it's not tuple-like. 1006 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0)) 1007 return IsTupleLike::NotTupleLike; 1008 1009 // If we get this far, we've committed to the tuple interpretation, but 1010 // we can still fail if there actually isn't a usable ::value. 1011 1012 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1013 LookupResult &R; 1014 TemplateArgumentListInfo &Args; 1015 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1016 : R(R), Args(Args) {} 1017 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1018 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1019 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1020 } 1021 } Diagnoser(R, Args); 1022 1023 if (R.empty()) { 1024 Diagnoser.diagnoseNotICE(S, Loc, SourceRange()); 1025 return IsTupleLike::Error; 1026 } 1027 1028 ExprResult E = 1029 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1030 if (E.isInvalid()) 1031 return IsTupleLike::Error; 1032 1033 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1034 if (E.isInvalid()) 1035 return IsTupleLike::Error; 1036 1037 return IsTupleLike::TupleLike; 1038 } 1039 1040 /// \return std::tuple_element<I, T>::type. 1041 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1042 unsigned I, QualType T) { 1043 // Form template argument list for tuple_element<I, T>. 1044 TemplateArgumentListInfo Args(Loc, Loc); 1045 Args.addArgument( 1046 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1047 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1048 1049 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1050 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1051 if (lookupStdTypeTraitMember( 1052 S, R, Loc, "tuple_element", Args, 1053 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1054 return QualType(); 1055 1056 auto *TD = R.getAsSingle<TypeDecl>(); 1057 if (!TD) { 1058 R.suppressDiagnostics(); 1059 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1060 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1061 if (!R.empty()) 1062 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1063 return QualType(); 1064 } 1065 1066 return S.Context.getTypeDeclType(TD); 1067 } 1068 1069 namespace { 1070 struct BindingDiagnosticTrap { 1071 Sema &S; 1072 DiagnosticErrorTrap Trap; 1073 BindingDecl *BD; 1074 1075 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1076 : S(S), Trap(S.Diags), BD(BD) {} 1077 ~BindingDiagnosticTrap() { 1078 if (Trap.hasErrorOccurred()) 1079 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1080 } 1081 }; 1082 } 1083 1084 static bool checkTupleLikeDecomposition(Sema &S, 1085 ArrayRef<BindingDecl *> Bindings, 1086 VarDecl *Src, QualType DecompType, 1087 const llvm::APSInt &TupleSize) { 1088 if ((int64_t)Bindings.size() != TupleSize) { 1089 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1090 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1091 << (TupleSize < Bindings.size()); 1092 return true; 1093 } 1094 1095 if (Bindings.empty()) 1096 return false; 1097 1098 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1099 1100 // [dcl.decomp]p3: 1101 // The unqualified-id get is looked up in the scope of E by class member 1102 // access lookup 1103 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1104 bool UseMemberGet = false; 1105 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1106 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1107 S.LookupQualifiedName(MemberGet, RD); 1108 if (MemberGet.isAmbiguous()) 1109 return true; 1110 UseMemberGet = !MemberGet.empty(); 1111 S.FilterAcceptableTemplateNames(MemberGet); 1112 } 1113 1114 unsigned I = 0; 1115 for (auto *B : Bindings) { 1116 BindingDiagnosticTrap Trap(S, B); 1117 SourceLocation Loc = B->getLocation(); 1118 1119 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1120 if (E.isInvalid()) 1121 return true; 1122 1123 // e is an lvalue if the type of the entity is an lvalue reference and 1124 // an xvalue otherwise 1125 if (!Src->getType()->isLValueReferenceType()) 1126 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1127 E.get(), nullptr, VK_XValue); 1128 1129 TemplateArgumentListInfo Args(Loc, Loc); 1130 Args.addArgument( 1131 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1132 1133 if (UseMemberGet) { 1134 // if [lookup of member get] finds at least one declaration, the 1135 // initializer is e.get<i-1>(). 1136 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1137 CXXScopeSpec(), SourceLocation(), nullptr, 1138 MemberGet, &Args, nullptr); 1139 if (E.isInvalid()) 1140 return true; 1141 1142 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc); 1143 } else { 1144 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1145 // in the associated namespaces. 1146 Expr *Get = UnresolvedLookupExpr::Create( 1147 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1148 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1149 UnresolvedSetIterator(), UnresolvedSetIterator()); 1150 1151 Expr *Arg = E.get(); 1152 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc); 1153 } 1154 if (E.isInvalid()) 1155 return true; 1156 Expr *Init = E.get(); 1157 1158 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1159 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1160 if (T.isNull()) 1161 return true; 1162 1163 // each vi is a variable of type "reference to T" initialized with the 1164 // initializer, where the reference is an lvalue reference if the 1165 // initializer is an lvalue and an rvalue reference otherwise 1166 QualType RefType = 1167 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1168 if (RefType.isNull()) 1169 return true; 1170 auto *RefVD = VarDecl::Create( 1171 S.Context, Src->getDeclContext(), Loc, Loc, 1172 B->getDeclName().getAsIdentifierInfo(), RefType, 1173 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1174 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1175 RefVD->setTSCSpec(Src->getTSCSpec()); 1176 RefVD->setImplicit(); 1177 if (Src->isInlineSpecified()) 1178 RefVD->setInlineSpecified(); 1179 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1180 1181 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1182 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1183 InitializationSequence Seq(S, Entity, Kind, Init); 1184 E = Seq.Perform(S, Entity, Kind, Init); 1185 if (E.isInvalid()) 1186 return true; 1187 E = S.ActOnFinishFullExpr(E.get(), Loc); 1188 if (E.isInvalid()) 1189 return true; 1190 RefVD->setInit(E.get()); 1191 RefVD->checkInitIsICE(); 1192 1193 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1194 DeclarationNameInfo(B->getDeclName(), Loc), 1195 RefVD); 1196 if (E.isInvalid()) 1197 return true; 1198 1199 B->setBinding(T, E.get()); 1200 I++; 1201 } 1202 1203 return false; 1204 } 1205 1206 /// Find the base class to decompose in a built-in decomposition of a class type. 1207 /// This base class search is, unfortunately, not quite like any other that we 1208 /// perform anywhere else in C++. 1209 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S, 1210 SourceLocation Loc, 1211 const CXXRecordDecl *RD, 1212 CXXCastPath &BasePath) { 1213 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1214 CXXBasePath &Path) { 1215 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1216 }; 1217 1218 const CXXRecordDecl *ClassWithFields = nullptr; 1219 if (RD->hasDirectFields()) 1220 // [dcl.decomp]p4: 1221 // Otherwise, all of E's non-static data members shall be public direct 1222 // members of E ... 1223 ClassWithFields = RD; 1224 else { 1225 // ... or of ... 1226 CXXBasePaths Paths; 1227 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1228 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1229 // If no classes have fields, just decompose RD itself. (This will work 1230 // if and only if zero bindings were provided.) 1231 return RD; 1232 } 1233 1234 CXXBasePath *BestPath = nullptr; 1235 for (auto &P : Paths) { 1236 if (!BestPath) 1237 BestPath = &P; 1238 else if (!S.Context.hasSameType(P.back().Base->getType(), 1239 BestPath->back().Base->getType())) { 1240 // ... the same ... 1241 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1242 << false << RD << BestPath->back().Base->getType() 1243 << P.back().Base->getType(); 1244 return nullptr; 1245 } else if (P.Access < BestPath->Access) { 1246 BestPath = &P; 1247 } 1248 } 1249 1250 // ... unambiguous ... 1251 QualType BaseType = BestPath->back().Base->getType(); 1252 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1253 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1254 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1255 return nullptr; 1256 } 1257 1258 // ... public base class of E. 1259 if (BestPath->Access != AS_public) { 1260 S.Diag(Loc, diag::err_decomp_decl_non_public_base) 1261 << RD << BaseType; 1262 for (auto &BS : *BestPath) { 1263 if (BS.Base->getAccessSpecifier() != AS_public) { 1264 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path) 1265 << (BS.Base->getAccessSpecifier() == AS_protected) 1266 << (BS.Base->getAccessSpecifierAsWritten() == AS_none); 1267 break; 1268 } 1269 } 1270 return nullptr; 1271 } 1272 1273 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1274 S.BuildBasePathArray(Paths, BasePath); 1275 } 1276 1277 // The above search did not check whether the selected class itself has base 1278 // classes with fields, so check that now. 1279 CXXBasePaths Paths; 1280 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1281 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1282 << (ClassWithFields == RD) << RD << ClassWithFields 1283 << Paths.front().back().Base->getType(); 1284 return nullptr; 1285 } 1286 1287 return ClassWithFields; 1288 } 1289 1290 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1291 ValueDecl *Src, QualType DecompType, 1292 const CXXRecordDecl *RD) { 1293 CXXCastPath BasePath; 1294 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath); 1295 if (!RD) 1296 return true; 1297 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1298 DecompType.getQualifiers()); 1299 1300 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1301 unsigned NumFields = 1302 std::count_if(RD->field_begin(), RD->field_end(), 1303 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1304 assert(Bindings.size() != NumFields); 1305 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1306 << DecompType << (unsigned)Bindings.size() << NumFields 1307 << (NumFields < Bindings.size()); 1308 return true; 1309 }; 1310 1311 // all of E's non-static data members shall be public [...] members, 1312 // E shall not have an anonymous union member, ... 1313 unsigned I = 0; 1314 for (auto *FD : RD->fields()) { 1315 if (FD->isUnnamedBitfield()) 1316 continue; 1317 1318 if (FD->isAnonymousStructOrUnion()) { 1319 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1320 << DecompType << FD->getType()->isUnionType(); 1321 S.Diag(FD->getLocation(), diag::note_declared_at); 1322 return true; 1323 } 1324 1325 // We have a real field to bind. 1326 if (I >= Bindings.size()) 1327 return DiagnoseBadNumberOfBindings(); 1328 auto *B = Bindings[I++]; 1329 1330 SourceLocation Loc = B->getLocation(); 1331 if (FD->getAccess() != AS_public) { 1332 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType; 1333 1334 // Determine whether the access specifier was explicit. 1335 bool Implicit = true; 1336 for (const auto *D : RD->decls()) { 1337 if (declaresSameEntity(D, FD)) 1338 break; 1339 if (isa<AccessSpecDecl>(D)) { 1340 Implicit = false; 1341 break; 1342 } 1343 } 1344 1345 S.Diag(FD->getLocation(), diag::note_access_natural) 1346 << (FD->getAccess() == AS_protected) << Implicit; 1347 return true; 1348 } 1349 1350 // Initialize the binding to Src.FD. 1351 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1352 if (E.isInvalid()) 1353 return true; 1354 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1355 VK_LValue, &BasePath); 1356 if (E.isInvalid()) 1357 return true; 1358 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1359 CXXScopeSpec(), FD, 1360 DeclAccessPair::make(FD, FD->getAccess()), 1361 DeclarationNameInfo(FD->getDeclName(), Loc)); 1362 if (E.isInvalid()) 1363 return true; 1364 1365 // If the type of the member is T, the referenced type is cv T, where cv is 1366 // the cv-qualification of the decomposition expression. 1367 // 1368 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1369 // 'const' to the type of the field. 1370 Qualifiers Q = DecompType.getQualifiers(); 1371 if (FD->isMutable()) 1372 Q.removeConst(); 1373 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1374 } 1375 1376 if (I != Bindings.size()) 1377 return DiagnoseBadNumberOfBindings(); 1378 1379 return false; 1380 } 1381 1382 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1383 QualType DecompType = DD->getType(); 1384 1385 // If the type of the decomposition is dependent, then so is the type of 1386 // each binding. 1387 if (DecompType->isDependentType()) { 1388 for (auto *B : DD->bindings()) 1389 B->setType(Context.DependentTy); 1390 return; 1391 } 1392 1393 DecompType = DecompType.getNonReferenceType(); 1394 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1395 1396 // C++1z [dcl.decomp]/2: 1397 // If E is an array type [...] 1398 // As an extension, we also support decomposition of built-in complex and 1399 // vector types. 1400 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1401 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1402 DD->setInvalidDecl(); 1403 return; 1404 } 1405 if (auto *VT = DecompType->getAs<VectorType>()) { 1406 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1407 DD->setInvalidDecl(); 1408 return; 1409 } 1410 if (auto *CT = DecompType->getAs<ComplexType>()) { 1411 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1412 DD->setInvalidDecl(); 1413 return; 1414 } 1415 1416 // C++1z [dcl.decomp]/3: 1417 // if the expression std::tuple_size<E>::value is a well-formed integral 1418 // constant expression, [...] 1419 llvm::APSInt TupleSize(32); 1420 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1421 case IsTupleLike::Error: 1422 DD->setInvalidDecl(); 1423 return; 1424 1425 case IsTupleLike::TupleLike: 1426 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1427 DD->setInvalidDecl(); 1428 return; 1429 1430 case IsTupleLike::NotTupleLike: 1431 break; 1432 } 1433 1434 // C++1z [dcl.dcl]/8: 1435 // [E shall be of array or non-union class type] 1436 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1437 if (!RD || RD->isUnion()) { 1438 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1439 << DD << !RD << DecompType; 1440 DD->setInvalidDecl(); 1441 return; 1442 } 1443 1444 // C++1z [dcl.decomp]/4: 1445 // all of E's non-static data members shall be [...] direct members of 1446 // E or of the same unambiguous public base class of E, ... 1447 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1448 DD->setInvalidDecl(); 1449 } 1450 1451 /// \brief Merge the exception specifications of two variable declarations. 1452 /// 1453 /// This is called when there's a redeclaration of a VarDecl. The function 1454 /// checks if the redeclaration might have an exception specification and 1455 /// validates compatibility and merges the specs if necessary. 1456 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1457 // Shortcut if exceptions are disabled. 1458 if (!getLangOpts().CXXExceptions) 1459 return; 1460 1461 assert(Context.hasSameType(New->getType(), Old->getType()) && 1462 "Should only be called if types are otherwise the same."); 1463 1464 QualType NewType = New->getType(); 1465 QualType OldType = Old->getType(); 1466 1467 // We're only interested in pointers and references to functions, as well 1468 // as pointers to member functions. 1469 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1470 NewType = R->getPointeeType(); 1471 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1472 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1473 NewType = P->getPointeeType(); 1474 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1475 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1476 NewType = M->getPointeeType(); 1477 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1478 } 1479 1480 if (!NewType->isFunctionProtoType()) 1481 return; 1482 1483 // There's lots of special cases for functions. For function pointers, system 1484 // libraries are hopefully not as broken so that we don't need these 1485 // workarounds. 1486 if (CheckEquivalentExceptionSpec( 1487 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1488 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1489 New->setInvalidDecl(); 1490 } 1491 } 1492 1493 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1494 /// function declaration are well-formed according to C++ 1495 /// [dcl.fct.default]. 1496 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1497 unsigned NumParams = FD->getNumParams(); 1498 unsigned p; 1499 1500 // Find first parameter with a default argument 1501 for (p = 0; p < NumParams; ++p) { 1502 ParmVarDecl *Param = FD->getParamDecl(p); 1503 if (Param->hasDefaultArg()) 1504 break; 1505 } 1506 1507 // C++11 [dcl.fct.default]p4: 1508 // In a given function declaration, each parameter subsequent to a parameter 1509 // with a default argument shall have a default argument supplied in this or 1510 // a previous declaration or shall be a function parameter pack. A default 1511 // argument shall not be redefined by a later declaration (not even to the 1512 // same value). 1513 unsigned LastMissingDefaultArg = 0; 1514 for (; p < NumParams; ++p) { 1515 ParmVarDecl *Param = FD->getParamDecl(p); 1516 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1517 if (Param->isInvalidDecl()) 1518 /* We already complained about this parameter. */; 1519 else if (Param->getIdentifier()) 1520 Diag(Param->getLocation(), 1521 diag::err_param_default_argument_missing_name) 1522 << Param->getIdentifier(); 1523 else 1524 Diag(Param->getLocation(), 1525 diag::err_param_default_argument_missing); 1526 1527 LastMissingDefaultArg = p; 1528 } 1529 } 1530 1531 if (LastMissingDefaultArg > 0) { 1532 // Some default arguments were missing. Clear out all of the 1533 // default arguments up to (and including) the last missing 1534 // default argument, so that we leave the function parameters 1535 // in a semantically valid state. 1536 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1537 ParmVarDecl *Param = FD->getParamDecl(p); 1538 if (Param->hasDefaultArg()) { 1539 Param->setDefaultArg(nullptr); 1540 } 1541 } 1542 } 1543 } 1544 1545 // CheckConstexprParameterTypes - Check whether a function's parameter types 1546 // are all literal types. If so, return true. If not, produce a suitable 1547 // diagnostic and return false. 1548 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1549 const FunctionDecl *FD) { 1550 unsigned ArgIndex = 0; 1551 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1552 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1553 e = FT->param_type_end(); 1554 i != e; ++i, ++ArgIndex) { 1555 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1556 SourceLocation ParamLoc = PD->getLocation(); 1557 if (!(*i)->isDependentType() && 1558 SemaRef.RequireLiteralType(ParamLoc, *i, 1559 diag::err_constexpr_non_literal_param, 1560 ArgIndex+1, PD->getSourceRange(), 1561 isa<CXXConstructorDecl>(FD))) 1562 return false; 1563 } 1564 return true; 1565 } 1566 1567 /// \brief Get diagnostic %select index for tag kind for 1568 /// record diagnostic message. 1569 /// WARNING: Indexes apply to particular diagnostics only! 1570 /// 1571 /// \returns diagnostic %select index. 1572 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1573 switch (Tag) { 1574 case TTK_Struct: return 0; 1575 case TTK_Interface: return 1; 1576 case TTK_Class: return 2; 1577 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1578 } 1579 } 1580 1581 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 1582 // the requirements of a constexpr function definition or a constexpr 1583 // constructor definition. If so, return true. If not, produce appropriate 1584 // diagnostics and return false. 1585 // 1586 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1587 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 1588 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1589 if (MD && MD->isInstance()) { 1590 // C++11 [dcl.constexpr]p4: 1591 // The definition of a constexpr constructor shall satisfy the following 1592 // constraints: 1593 // - the class shall not have any virtual base classes; 1594 const CXXRecordDecl *RD = MD->getParent(); 1595 if (RD->getNumVBases()) { 1596 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1597 << isa<CXXConstructorDecl>(NewFD) 1598 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1599 for (const auto &I : RD->vbases()) 1600 Diag(I.getLocStart(), 1601 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 1602 return false; 1603 } 1604 } 1605 1606 if (!isa<CXXConstructorDecl>(NewFD)) { 1607 // C++11 [dcl.constexpr]p3: 1608 // The definition of a constexpr function shall satisfy the following 1609 // constraints: 1610 // - it shall not be virtual; 1611 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1612 if (Method && Method->isVirtual()) { 1613 Method = Method->getCanonicalDecl(); 1614 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1615 1616 // If it's not obvious why this function is virtual, find an overridden 1617 // function which uses the 'virtual' keyword. 1618 const CXXMethodDecl *WrittenVirtual = Method; 1619 while (!WrittenVirtual->isVirtualAsWritten()) 1620 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1621 if (WrittenVirtual != Method) 1622 Diag(WrittenVirtual->getLocation(), 1623 diag::note_overridden_virtual_function); 1624 return false; 1625 } 1626 1627 // - its return type shall be a literal type; 1628 QualType RT = NewFD->getReturnType(); 1629 if (!RT->isDependentType() && 1630 RequireLiteralType(NewFD->getLocation(), RT, 1631 diag::err_constexpr_non_literal_return)) 1632 return false; 1633 } 1634 1635 // - each of its parameter types shall be a literal type; 1636 if (!CheckConstexprParameterTypes(*this, NewFD)) 1637 return false; 1638 1639 return true; 1640 } 1641 1642 /// Check the given declaration statement is legal within a constexpr function 1643 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1644 /// 1645 /// \return true if the body is OK (maybe only as an extension), false if we 1646 /// have diagnosed a problem. 1647 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1648 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 1649 // C++11 [dcl.constexpr]p3 and p4: 1650 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1651 // contain only 1652 for (const auto *DclIt : DS->decls()) { 1653 switch (DclIt->getKind()) { 1654 case Decl::StaticAssert: 1655 case Decl::Using: 1656 case Decl::UsingShadow: 1657 case Decl::UsingDirective: 1658 case Decl::UnresolvedUsingTypename: 1659 case Decl::UnresolvedUsingValue: 1660 // - static_assert-declarations 1661 // - using-declarations, 1662 // - using-directives, 1663 continue; 1664 1665 case Decl::Typedef: 1666 case Decl::TypeAlias: { 1667 // - typedef declarations and alias-declarations that do not define 1668 // classes or enumerations, 1669 const auto *TN = cast<TypedefNameDecl>(DclIt); 1670 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1671 // Don't allow variably-modified types in constexpr functions. 1672 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1673 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1674 << TL.getSourceRange() << TL.getType() 1675 << isa<CXXConstructorDecl>(Dcl); 1676 return false; 1677 } 1678 continue; 1679 } 1680 1681 case Decl::Enum: 1682 case Decl::CXXRecord: 1683 // C++1y allows types to be defined, not just declared. 1684 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 1685 SemaRef.Diag(DS->getLocStart(), 1686 SemaRef.getLangOpts().CPlusPlus14 1687 ? diag::warn_cxx11_compat_constexpr_type_definition 1688 : diag::ext_constexpr_type_definition) 1689 << isa<CXXConstructorDecl>(Dcl); 1690 continue; 1691 1692 case Decl::EnumConstant: 1693 case Decl::IndirectField: 1694 case Decl::ParmVar: 1695 // These can only appear with other declarations which are banned in 1696 // C++11 and permitted in C++1y, so ignore them. 1697 continue; 1698 1699 case Decl::Var: 1700 case Decl::Decomposition: { 1701 // C++1y [dcl.constexpr]p3 allows anything except: 1702 // a definition of a variable of non-literal type or of static or 1703 // thread storage duration or for which no initialization is performed. 1704 const auto *VD = cast<VarDecl>(DclIt); 1705 if (VD->isThisDeclarationADefinition()) { 1706 if (VD->isStaticLocal()) { 1707 SemaRef.Diag(VD->getLocation(), 1708 diag::err_constexpr_local_var_static) 1709 << isa<CXXConstructorDecl>(Dcl) 1710 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1711 return false; 1712 } 1713 if (!VD->getType()->isDependentType() && 1714 SemaRef.RequireLiteralType( 1715 VD->getLocation(), VD->getType(), 1716 diag::err_constexpr_local_var_non_literal_type, 1717 isa<CXXConstructorDecl>(Dcl))) 1718 return false; 1719 if (!VD->getType()->isDependentType() && 1720 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1721 SemaRef.Diag(VD->getLocation(), 1722 diag::err_constexpr_local_var_no_init) 1723 << isa<CXXConstructorDecl>(Dcl); 1724 return false; 1725 } 1726 } 1727 SemaRef.Diag(VD->getLocation(), 1728 SemaRef.getLangOpts().CPlusPlus14 1729 ? diag::warn_cxx11_compat_constexpr_local_var 1730 : diag::ext_constexpr_local_var) 1731 << isa<CXXConstructorDecl>(Dcl); 1732 continue; 1733 } 1734 1735 case Decl::NamespaceAlias: 1736 case Decl::Function: 1737 // These are disallowed in C++11 and permitted in C++1y. Allow them 1738 // everywhere as an extension. 1739 if (!Cxx1yLoc.isValid()) 1740 Cxx1yLoc = DS->getLocStart(); 1741 continue; 1742 1743 default: 1744 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1745 << isa<CXXConstructorDecl>(Dcl); 1746 return false; 1747 } 1748 } 1749 1750 return true; 1751 } 1752 1753 /// Check that the given field is initialized within a constexpr constructor. 1754 /// 1755 /// \param Dcl The constexpr constructor being checked. 1756 /// \param Field The field being checked. This may be a member of an anonymous 1757 /// struct or union nested within the class being checked. 1758 /// \param Inits All declarations, including anonymous struct/union members and 1759 /// indirect members, for which any initialization was provided. 1760 /// \param Diagnosed Set to true if an error is produced. 1761 static void CheckConstexprCtorInitializer(Sema &SemaRef, 1762 const FunctionDecl *Dcl, 1763 FieldDecl *Field, 1764 llvm::SmallSet<Decl*, 16> &Inits, 1765 bool &Diagnosed) { 1766 if (Field->isInvalidDecl()) 1767 return; 1768 1769 if (Field->isUnnamedBitfield()) 1770 return; 1771 1772 // Anonymous unions with no variant members and empty anonymous structs do not 1773 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1774 // indirect fields don't need initializing. 1775 if (Field->isAnonymousStructOrUnion() && 1776 (Field->getType()->isUnionType() 1777 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1778 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1779 return; 1780 1781 if (!Inits.count(Field)) { 1782 if (!Diagnosed) { 1783 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 1784 Diagnosed = true; 1785 } 1786 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 1787 } else if (Field->isAnonymousStructOrUnion()) { 1788 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1789 for (auto *I : RD->fields()) 1790 // If an anonymous union contains an anonymous struct of which any member 1791 // is initialized, all members must be initialized. 1792 if (!RD->isUnion() || Inits.count(I)) 1793 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 1794 } 1795 } 1796 1797 /// Check the provided statement is allowed in a constexpr function 1798 /// definition. 1799 static bool 1800 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1801 SmallVectorImpl<SourceLocation> &ReturnStmts, 1802 SourceLocation &Cxx1yLoc) { 1803 // - its function-body shall be [...] a compound-statement that contains only 1804 switch (S->getStmtClass()) { 1805 case Stmt::NullStmtClass: 1806 // - null statements, 1807 return true; 1808 1809 case Stmt::DeclStmtClass: 1810 // - static_assert-declarations 1811 // - using-declarations, 1812 // - using-directives, 1813 // - typedef declarations and alias-declarations that do not define 1814 // classes or enumerations, 1815 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 1816 return false; 1817 return true; 1818 1819 case Stmt::ReturnStmtClass: 1820 // - and exactly one return statement; 1821 if (isa<CXXConstructorDecl>(Dcl)) { 1822 // C++1y allows return statements in constexpr constructors. 1823 if (!Cxx1yLoc.isValid()) 1824 Cxx1yLoc = S->getLocStart(); 1825 return true; 1826 } 1827 1828 ReturnStmts.push_back(S->getLocStart()); 1829 return true; 1830 1831 case Stmt::CompoundStmtClass: { 1832 // C++1y allows compound-statements. 1833 if (!Cxx1yLoc.isValid()) 1834 Cxx1yLoc = S->getLocStart(); 1835 1836 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1837 for (auto *BodyIt : CompStmt->body()) { 1838 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1839 Cxx1yLoc)) 1840 return false; 1841 } 1842 return true; 1843 } 1844 1845 case Stmt::AttributedStmtClass: 1846 if (!Cxx1yLoc.isValid()) 1847 Cxx1yLoc = S->getLocStart(); 1848 return true; 1849 1850 case Stmt::IfStmtClass: { 1851 // C++1y allows if-statements. 1852 if (!Cxx1yLoc.isValid()) 1853 Cxx1yLoc = S->getLocStart(); 1854 1855 IfStmt *If = cast<IfStmt>(S); 1856 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1857 Cxx1yLoc)) 1858 return false; 1859 if (If->getElse() && 1860 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1861 Cxx1yLoc)) 1862 return false; 1863 return true; 1864 } 1865 1866 case Stmt::WhileStmtClass: 1867 case Stmt::DoStmtClass: 1868 case Stmt::ForStmtClass: 1869 case Stmt::CXXForRangeStmtClass: 1870 case Stmt::ContinueStmtClass: 1871 // C++1y allows all of these. We don't allow them as extensions in C++11, 1872 // because they don't make sense without variable mutation. 1873 if (!SemaRef.getLangOpts().CPlusPlus14) 1874 break; 1875 if (!Cxx1yLoc.isValid()) 1876 Cxx1yLoc = S->getLocStart(); 1877 for (Stmt *SubStmt : S->children()) 1878 if (SubStmt && 1879 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1880 Cxx1yLoc)) 1881 return false; 1882 return true; 1883 1884 case Stmt::SwitchStmtClass: 1885 case Stmt::CaseStmtClass: 1886 case Stmt::DefaultStmtClass: 1887 case Stmt::BreakStmtClass: 1888 // C++1y allows switch-statements, and since they don't need variable 1889 // mutation, we can reasonably allow them in C++11 as an extension. 1890 if (!Cxx1yLoc.isValid()) 1891 Cxx1yLoc = S->getLocStart(); 1892 for (Stmt *SubStmt : S->children()) 1893 if (SubStmt && 1894 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 1895 Cxx1yLoc)) 1896 return false; 1897 return true; 1898 1899 default: 1900 if (!isa<Expr>(S)) 1901 break; 1902 1903 // C++1y allows expression-statements. 1904 if (!Cxx1yLoc.isValid()) 1905 Cxx1yLoc = S->getLocStart(); 1906 return true; 1907 } 1908 1909 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1910 << isa<CXXConstructorDecl>(Dcl); 1911 return false; 1912 } 1913 1914 /// Check the body for the given constexpr function declaration only contains 1915 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1916 /// 1917 /// \return true if the body is OK, false if we have diagnosed a problem. 1918 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1919 if (isa<CXXTryStmt>(Body)) { 1920 // C++11 [dcl.constexpr]p3: 1921 // The definition of a constexpr function shall satisfy the following 1922 // constraints: [...] 1923 // - its function-body shall be = delete, = default, or a 1924 // compound-statement 1925 // 1926 // C++11 [dcl.constexpr]p4: 1927 // In the definition of a constexpr constructor, [...] 1928 // - its function-body shall not be a function-try-block; 1929 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1930 << isa<CXXConstructorDecl>(Dcl); 1931 return false; 1932 } 1933 1934 SmallVector<SourceLocation, 4> ReturnStmts; 1935 1936 // - its function-body shall be [...] a compound-statement that contains only 1937 // [... list of cases ...] 1938 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1939 SourceLocation Cxx1yLoc; 1940 for (auto *BodyIt : CompBody->body()) { 1941 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1942 return false; 1943 } 1944 1945 if (Cxx1yLoc.isValid()) 1946 Diag(Cxx1yLoc, 1947 getLangOpts().CPlusPlus14 1948 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1949 : diag::ext_constexpr_body_invalid_stmt) 1950 << isa<CXXConstructorDecl>(Dcl); 1951 1952 if (const CXXConstructorDecl *Constructor 1953 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1954 const CXXRecordDecl *RD = Constructor->getParent(); 1955 // DR1359: 1956 // - every non-variant non-static data member and base class sub-object 1957 // shall be initialized; 1958 // DR1460: 1959 // - if the class is a union having variant members, exactly one of them 1960 // shall be initialized; 1961 if (RD->isUnion()) { 1962 if (Constructor->getNumCtorInitializers() == 0 && 1963 RD->hasVariantMembers()) { 1964 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1965 return false; 1966 } 1967 } else if (!Constructor->isDependentContext() && 1968 !Constructor->isDelegatingConstructor()) { 1969 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1970 1971 // Skip detailed checking if we have enough initializers, and we would 1972 // allow at most one initializer per member. 1973 bool AnyAnonStructUnionMembers = false; 1974 unsigned Fields = 0; 1975 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1976 E = RD->field_end(); I != E; ++I, ++Fields) { 1977 if (I->isAnonymousStructOrUnion()) { 1978 AnyAnonStructUnionMembers = true; 1979 break; 1980 } 1981 } 1982 // DR1460: 1983 // - if the class is a union-like class, but is not a union, for each of 1984 // its anonymous union members having variant members, exactly one of 1985 // them shall be initialized; 1986 if (AnyAnonStructUnionMembers || 1987 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1988 // Check initialization of non-static data members. Base classes are 1989 // always initialized so do not need to be checked. Dependent bases 1990 // might not have initializers in the member initializer list. 1991 llvm::SmallSet<Decl*, 16> Inits; 1992 for (const auto *I: Constructor->inits()) { 1993 if (FieldDecl *FD = I->getMember()) 1994 Inits.insert(FD); 1995 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1996 Inits.insert(ID->chain_begin(), ID->chain_end()); 1997 } 1998 1999 bool Diagnosed = false; 2000 for (auto *I : RD->fields()) 2001 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 2002 if (Diagnosed) 2003 return false; 2004 } 2005 } 2006 } else { 2007 if (ReturnStmts.empty()) { 2008 // C++1y doesn't require constexpr functions to contain a 'return' 2009 // statement. We still do, unless the return type might be void, because 2010 // otherwise if there's no return statement, the function cannot 2011 // be used in a core constant expression. 2012 bool OK = getLangOpts().CPlusPlus14 && 2013 (Dcl->getReturnType()->isVoidType() || 2014 Dcl->getReturnType()->isDependentType()); 2015 Diag(Dcl->getLocation(), 2016 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2017 : diag::err_constexpr_body_no_return); 2018 if (!OK) 2019 return false; 2020 } else if (ReturnStmts.size() > 1) { 2021 Diag(ReturnStmts.back(), 2022 getLangOpts().CPlusPlus14 2023 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2024 : diag::ext_constexpr_body_multiple_return); 2025 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2026 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 2027 } 2028 } 2029 2030 // C++11 [dcl.constexpr]p5: 2031 // if no function argument values exist such that the function invocation 2032 // substitution would produce a constant expression, the program is 2033 // ill-formed; no diagnostic required. 2034 // C++11 [dcl.constexpr]p3: 2035 // - every constructor call and implicit conversion used in initializing the 2036 // return value shall be one of those allowed in a constant expression. 2037 // C++11 [dcl.constexpr]p4: 2038 // - every constructor involved in initializing non-static data members and 2039 // base class sub-objects shall be a constexpr constructor. 2040 SmallVector<PartialDiagnosticAt, 8> Diags; 2041 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 2042 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 2043 << isa<CXXConstructorDecl>(Dcl); 2044 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2045 Diag(Diags[I].first, Diags[I].second); 2046 // Don't return false here: we allow this for compatibility in 2047 // system headers. 2048 } 2049 2050 return true; 2051 } 2052 2053 /// isCurrentClassName - Determine whether the identifier II is the 2054 /// name of the class type currently being defined. In the case of 2055 /// nested classes, this will only return true if II is the name of 2056 /// the innermost class. 2057 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 2058 const CXXScopeSpec *SS) { 2059 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2060 2061 CXXRecordDecl *CurDecl; 2062 if (SS && SS->isSet() && !SS->isInvalid()) { 2063 DeclContext *DC = computeDeclContext(*SS, true); 2064 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2065 } else 2066 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2067 2068 if (CurDecl && CurDecl->getIdentifier()) 2069 return &II == CurDecl->getIdentifier(); 2070 return false; 2071 } 2072 2073 /// \brief Determine whether the identifier II is a typo for the name of 2074 /// the class type currently being defined. If so, update it to the identifier 2075 /// that should have been used. 2076 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2077 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2078 2079 if (!getLangOpts().SpellChecking) 2080 return false; 2081 2082 CXXRecordDecl *CurDecl; 2083 if (SS && SS->isSet() && !SS->isInvalid()) { 2084 DeclContext *DC = computeDeclContext(*SS, true); 2085 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2086 } else 2087 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2088 2089 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2090 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2091 < II->getLength()) { 2092 II = CurDecl->getIdentifier(); 2093 return true; 2094 } 2095 2096 return false; 2097 } 2098 2099 /// \brief Determine whether the given class is a base class of the given 2100 /// class, including looking at dependent bases. 2101 static bool findCircularInheritance(const CXXRecordDecl *Class, 2102 const CXXRecordDecl *Current) { 2103 SmallVector<const CXXRecordDecl*, 8> Queue; 2104 2105 Class = Class->getCanonicalDecl(); 2106 while (true) { 2107 for (const auto &I : Current->bases()) { 2108 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2109 if (!Base) 2110 continue; 2111 2112 Base = Base->getDefinition(); 2113 if (!Base) 2114 continue; 2115 2116 if (Base->getCanonicalDecl() == Class) 2117 return true; 2118 2119 Queue.push_back(Base); 2120 } 2121 2122 if (Queue.empty()) 2123 return false; 2124 2125 Current = Queue.pop_back_val(); 2126 } 2127 2128 return false; 2129 } 2130 2131 /// \brief Check the validity of a C++ base class specifier. 2132 /// 2133 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2134 /// and returns NULL otherwise. 2135 CXXBaseSpecifier * 2136 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2137 SourceRange SpecifierRange, 2138 bool Virtual, AccessSpecifier Access, 2139 TypeSourceInfo *TInfo, 2140 SourceLocation EllipsisLoc) { 2141 QualType BaseType = TInfo->getType(); 2142 2143 // C++ [class.union]p1: 2144 // A union shall not have base classes. 2145 if (Class->isUnion()) { 2146 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2147 << SpecifierRange; 2148 return nullptr; 2149 } 2150 2151 if (EllipsisLoc.isValid() && 2152 !TInfo->getType()->containsUnexpandedParameterPack()) { 2153 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2154 << TInfo->getTypeLoc().getSourceRange(); 2155 EllipsisLoc = SourceLocation(); 2156 } 2157 2158 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2159 2160 if (BaseType->isDependentType()) { 2161 // Make sure that we don't have circular inheritance among our dependent 2162 // bases. For non-dependent bases, the check for completeness below handles 2163 // this. 2164 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2165 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2166 ((BaseDecl = BaseDecl->getDefinition()) && 2167 findCircularInheritance(Class, BaseDecl))) { 2168 Diag(BaseLoc, diag::err_circular_inheritance) 2169 << BaseType << Context.getTypeDeclType(Class); 2170 2171 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2172 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2173 << BaseType; 2174 2175 return nullptr; 2176 } 2177 } 2178 2179 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2180 Class->getTagKind() == TTK_Class, 2181 Access, TInfo, EllipsisLoc); 2182 } 2183 2184 // Base specifiers must be record types. 2185 if (!BaseType->isRecordType()) { 2186 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2187 return nullptr; 2188 } 2189 2190 // C++ [class.union]p1: 2191 // A union shall not be used as a base class. 2192 if (BaseType->isUnionType()) { 2193 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2194 return nullptr; 2195 } 2196 2197 // For the MS ABI, propagate DLL attributes to base class templates. 2198 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2199 if (Attr *ClassAttr = getDLLAttr(Class)) { 2200 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2201 BaseType->getAsCXXRecordDecl())) { 2202 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2203 BaseLoc); 2204 } 2205 } 2206 } 2207 2208 // C++ [class.derived]p2: 2209 // The class-name in a base-specifier shall not be an incompletely 2210 // defined class. 2211 if (RequireCompleteType(BaseLoc, BaseType, 2212 diag::err_incomplete_base_class, SpecifierRange)) { 2213 Class->setInvalidDecl(); 2214 return nullptr; 2215 } 2216 2217 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2218 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2219 assert(BaseDecl && "Record type has no declaration"); 2220 BaseDecl = BaseDecl->getDefinition(); 2221 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2222 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2223 assert(CXXBaseDecl && "Base type is not a C++ type"); 2224 2225 // A class which contains a flexible array member is not suitable for use as a 2226 // base class: 2227 // - If the layout determines that a base comes before another base, 2228 // the flexible array member would index into the subsequent base. 2229 // - If the layout determines that base comes before the derived class, 2230 // the flexible array member would index into the derived class. 2231 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2232 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2233 << CXXBaseDecl->getDeclName(); 2234 return nullptr; 2235 } 2236 2237 // C++ [class]p3: 2238 // If a class is marked final and it appears as a base-type-specifier in 2239 // base-clause, the program is ill-formed. 2240 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2241 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2242 << CXXBaseDecl->getDeclName() 2243 << FA->isSpelledAsSealed(); 2244 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2245 << CXXBaseDecl->getDeclName() << FA->getRange(); 2246 return nullptr; 2247 } 2248 2249 if (BaseDecl->isInvalidDecl()) 2250 Class->setInvalidDecl(); 2251 2252 // Create the base specifier. 2253 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2254 Class->getTagKind() == TTK_Class, 2255 Access, TInfo, EllipsisLoc); 2256 } 2257 2258 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2259 /// one entry in the base class list of a class specifier, for 2260 /// example: 2261 /// class foo : public bar, virtual private baz { 2262 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2263 BaseResult 2264 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2265 ParsedAttributes &Attributes, 2266 bool Virtual, AccessSpecifier Access, 2267 ParsedType basetype, SourceLocation BaseLoc, 2268 SourceLocation EllipsisLoc) { 2269 if (!classdecl) 2270 return true; 2271 2272 AdjustDeclIfTemplate(classdecl); 2273 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2274 if (!Class) 2275 return true; 2276 2277 // We haven't yet attached the base specifiers. 2278 Class->setIsParsingBaseSpecifiers(); 2279 2280 // We do not support any C++11 attributes on base-specifiers yet. 2281 // Diagnose any attributes we see. 2282 if (!Attributes.empty()) { 2283 for (AttributeList *Attr = Attributes.getList(); Attr; 2284 Attr = Attr->getNext()) { 2285 if (Attr->isInvalid() || 2286 Attr->getKind() == AttributeList::IgnoredAttribute) 2287 continue; 2288 Diag(Attr->getLoc(), 2289 Attr->getKind() == AttributeList::UnknownAttribute 2290 ? diag::warn_unknown_attribute_ignored 2291 : diag::err_base_specifier_attribute) 2292 << Attr->getName(); 2293 } 2294 } 2295 2296 TypeSourceInfo *TInfo = nullptr; 2297 GetTypeFromParser(basetype, &TInfo); 2298 2299 if (EllipsisLoc.isInvalid() && 2300 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2301 UPPC_BaseType)) 2302 return true; 2303 2304 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2305 Virtual, Access, TInfo, 2306 EllipsisLoc)) 2307 return BaseSpec; 2308 else 2309 Class->setInvalidDecl(); 2310 2311 return true; 2312 } 2313 2314 /// Use small set to collect indirect bases. As this is only used 2315 /// locally, there's no need to abstract the small size parameter. 2316 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2317 2318 /// \brief Recursively add the bases of Type. Don't add Type itself. 2319 static void 2320 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2321 const QualType &Type) 2322 { 2323 // Even though the incoming type is a base, it might not be 2324 // a class -- it could be a template parm, for instance. 2325 if (auto Rec = Type->getAs<RecordType>()) { 2326 auto Decl = Rec->getAsCXXRecordDecl(); 2327 2328 // Iterate over its bases. 2329 for (const auto &BaseSpec : Decl->bases()) { 2330 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2331 .getUnqualifiedType(); 2332 if (Set.insert(Base).second) 2333 // If we've not already seen it, recurse. 2334 NoteIndirectBases(Context, Set, Base); 2335 } 2336 } 2337 } 2338 2339 /// \brief Performs the actual work of attaching the given base class 2340 /// specifiers to a C++ class. 2341 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2342 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2343 if (Bases.empty()) 2344 return false; 2345 2346 // Used to keep track of which base types we have already seen, so 2347 // that we can properly diagnose redundant direct base types. Note 2348 // that the key is always the unqualified canonical type of the base 2349 // class. 2350 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2351 2352 // Used to track indirect bases so we can see if a direct base is 2353 // ambiguous. 2354 IndirectBaseSet IndirectBaseTypes; 2355 2356 // Copy non-redundant base specifiers into permanent storage. 2357 unsigned NumGoodBases = 0; 2358 bool Invalid = false; 2359 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2360 QualType NewBaseType 2361 = Context.getCanonicalType(Bases[idx]->getType()); 2362 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2363 2364 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2365 if (KnownBase) { 2366 // C++ [class.mi]p3: 2367 // A class shall not be specified as a direct base class of a 2368 // derived class more than once. 2369 Diag(Bases[idx]->getLocStart(), 2370 diag::err_duplicate_base_class) 2371 << KnownBase->getType() 2372 << Bases[idx]->getSourceRange(); 2373 2374 // Delete the duplicate base class specifier; we're going to 2375 // overwrite its pointer later. 2376 Context.Deallocate(Bases[idx]); 2377 2378 Invalid = true; 2379 } else { 2380 // Okay, add this new base class. 2381 KnownBase = Bases[idx]; 2382 Bases[NumGoodBases++] = Bases[idx]; 2383 2384 // Note this base's direct & indirect bases, if there could be ambiguity. 2385 if (Bases.size() > 1) 2386 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2387 2388 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2389 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2390 if (Class->isInterface() && 2391 (!RD->isInterface() || 2392 KnownBase->getAccessSpecifier() != AS_public)) { 2393 // The Microsoft extension __interface does not permit bases that 2394 // are not themselves public interfaces. 2395 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 2396 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 2397 << RD->getSourceRange(); 2398 Invalid = true; 2399 } 2400 if (RD->hasAttr<WeakAttr>()) 2401 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2402 } 2403 } 2404 } 2405 2406 // Attach the remaining base class specifiers to the derived class. 2407 Class->setBases(Bases.data(), NumGoodBases); 2408 2409 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2410 // Check whether this direct base is inaccessible due to ambiguity. 2411 QualType BaseType = Bases[idx]->getType(); 2412 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2413 .getUnqualifiedType(); 2414 2415 if (IndirectBaseTypes.count(CanonicalBase)) { 2416 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2417 /*DetectVirtual=*/true); 2418 bool found 2419 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2420 assert(found); 2421 (void)found; 2422 2423 if (Paths.isAmbiguous(CanonicalBase)) 2424 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class) 2425 << BaseType << getAmbiguousPathsDisplayString(Paths) 2426 << Bases[idx]->getSourceRange(); 2427 else 2428 assert(Bases[idx]->isVirtual()); 2429 } 2430 2431 // Delete the base class specifier, since its data has been copied 2432 // into the CXXRecordDecl. 2433 Context.Deallocate(Bases[idx]); 2434 } 2435 2436 return Invalid; 2437 } 2438 2439 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2440 /// class, after checking whether there are any duplicate base 2441 /// classes. 2442 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2443 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2444 if (!ClassDecl || Bases.empty()) 2445 return; 2446 2447 AdjustDeclIfTemplate(ClassDecl); 2448 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2449 } 2450 2451 /// \brief Determine whether the type \p Derived is a C++ class that is 2452 /// derived from the type \p Base. 2453 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2454 if (!getLangOpts().CPlusPlus) 2455 return false; 2456 2457 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2458 if (!DerivedRD) 2459 return false; 2460 2461 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2462 if (!BaseRD) 2463 return false; 2464 2465 // If either the base or the derived type is invalid, don't try to 2466 // check whether one is derived from the other. 2467 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2468 return false; 2469 2470 // FIXME: In a modules build, do we need the entire path to be visible for us 2471 // to be able to use the inheritance relationship? 2472 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2473 return false; 2474 2475 return DerivedRD->isDerivedFrom(BaseRD); 2476 } 2477 2478 /// \brief Determine whether the type \p Derived is a C++ class that is 2479 /// derived from the type \p Base. 2480 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2481 CXXBasePaths &Paths) { 2482 if (!getLangOpts().CPlusPlus) 2483 return false; 2484 2485 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2486 if (!DerivedRD) 2487 return false; 2488 2489 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2490 if (!BaseRD) 2491 return false; 2492 2493 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2494 return false; 2495 2496 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2497 } 2498 2499 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2500 CXXCastPath &BasePathArray) { 2501 assert(BasePathArray.empty() && "Base path array must be empty!"); 2502 assert(Paths.isRecordingPaths() && "Must record paths!"); 2503 2504 const CXXBasePath &Path = Paths.front(); 2505 2506 // We first go backward and check if we have a virtual base. 2507 // FIXME: It would be better if CXXBasePath had the base specifier for 2508 // the nearest virtual base. 2509 unsigned Start = 0; 2510 for (unsigned I = Path.size(); I != 0; --I) { 2511 if (Path[I - 1].Base->isVirtual()) { 2512 Start = I - 1; 2513 break; 2514 } 2515 } 2516 2517 // Now add all bases. 2518 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2519 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2520 } 2521 2522 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2523 /// conversion (where Derived and Base are class types) is 2524 /// well-formed, meaning that the conversion is unambiguous (and 2525 /// that all of the base classes are accessible). Returns true 2526 /// and emits a diagnostic if the code is ill-formed, returns false 2527 /// otherwise. Loc is the location where this routine should point to 2528 /// if there is an error, and Range is the source range to highlight 2529 /// if there is an error. 2530 /// 2531 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2532 /// diagnostic for the respective type of error will be suppressed, but the 2533 /// check for ill-formed code will still be performed. 2534 bool 2535 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2536 unsigned InaccessibleBaseID, 2537 unsigned AmbigiousBaseConvID, 2538 SourceLocation Loc, SourceRange Range, 2539 DeclarationName Name, 2540 CXXCastPath *BasePath, 2541 bool IgnoreAccess) { 2542 // First, determine whether the path from Derived to Base is 2543 // ambiguous. This is slightly more expensive than checking whether 2544 // the Derived to Base conversion exists, because here we need to 2545 // explore multiple paths to determine if there is an ambiguity. 2546 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2547 /*DetectVirtual=*/false); 2548 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2549 assert(DerivationOkay && 2550 "Can only be used with a derived-to-base conversion"); 2551 (void)DerivationOkay; 2552 2553 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 2554 if (!IgnoreAccess) { 2555 // Check that the base class can be accessed. 2556 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 2557 InaccessibleBaseID)) { 2558 case AR_inaccessible: 2559 return true; 2560 case AR_accessible: 2561 case AR_dependent: 2562 case AR_delayed: 2563 break; 2564 } 2565 } 2566 2567 // Build a base path if necessary. 2568 if (BasePath) 2569 BuildBasePathArray(Paths, *BasePath); 2570 return false; 2571 } 2572 2573 if (AmbigiousBaseConvID) { 2574 // We know that the derived-to-base conversion is ambiguous, and 2575 // we're going to produce a diagnostic. Perform the derived-to-base 2576 // search just one more time to compute all of the possible paths so 2577 // that we can print them out. This is more expensive than any of 2578 // the previous derived-to-base checks we've done, but at this point 2579 // performance isn't as much of an issue. 2580 Paths.clear(); 2581 Paths.setRecordingPaths(true); 2582 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2583 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2584 (void)StillOkay; 2585 2586 // Build up a textual representation of the ambiguous paths, e.g., 2587 // D -> B -> A, that will be used to illustrate the ambiguous 2588 // conversions in the diagnostic. We only print one of the paths 2589 // to each base class subobject. 2590 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2591 2592 Diag(Loc, AmbigiousBaseConvID) 2593 << Derived << Base << PathDisplayStr << Range << Name; 2594 } 2595 return true; 2596 } 2597 2598 bool 2599 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2600 SourceLocation Loc, SourceRange Range, 2601 CXXCastPath *BasePath, 2602 bool IgnoreAccess) { 2603 return CheckDerivedToBaseConversion( 2604 Derived, Base, diag::err_upcast_to_inaccessible_base, 2605 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2606 BasePath, IgnoreAccess); 2607 } 2608 2609 2610 /// @brief Builds a string representing ambiguous paths from a 2611 /// specific derived class to different subobjects of the same base 2612 /// class. 2613 /// 2614 /// This function builds a string that can be used in error messages 2615 /// to show the different paths that one can take through the 2616 /// inheritance hierarchy to go from the derived class to different 2617 /// subobjects of a base class. The result looks something like this: 2618 /// @code 2619 /// struct D -> struct B -> struct A 2620 /// struct D -> struct C -> struct A 2621 /// @endcode 2622 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2623 std::string PathDisplayStr; 2624 std::set<unsigned> DisplayedPaths; 2625 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2626 Path != Paths.end(); ++Path) { 2627 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2628 // We haven't displayed a path to this particular base 2629 // class subobject yet. 2630 PathDisplayStr += "\n "; 2631 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2632 for (CXXBasePath::const_iterator Element = Path->begin(); 2633 Element != Path->end(); ++Element) 2634 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2635 } 2636 } 2637 2638 return PathDisplayStr; 2639 } 2640 2641 //===----------------------------------------------------------------------===// 2642 // C++ class member Handling 2643 //===----------------------------------------------------------------------===// 2644 2645 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2646 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 2647 SourceLocation ASLoc, 2648 SourceLocation ColonLoc, 2649 AttributeList *Attrs) { 2650 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2651 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2652 ASLoc, ColonLoc); 2653 CurContext->addHiddenDecl(ASDecl); 2654 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2655 } 2656 2657 /// CheckOverrideControl - Check C++11 override control semantics. 2658 void Sema::CheckOverrideControl(NamedDecl *D) { 2659 if (D->isInvalidDecl()) 2660 return; 2661 2662 // We only care about "override" and "final" declarations. 2663 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2664 return; 2665 2666 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2667 2668 // We can't check dependent instance methods. 2669 if (MD && MD->isInstance() && 2670 (MD->getParent()->hasAnyDependentBases() || 2671 MD->getType()->isDependentType())) 2672 return; 2673 2674 if (MD && !MD->isVirtual()) { 2675 // If we have a non-virtual method, check if if hides a virtual method. 2676 // (In that case, it's most likely the method has the wrong type.) 2677 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2678 FindHiddenVirtualMethods(MD, OverloadedMethods); 2679 2680 if (!OverloadedMethods.empty()) { 2681 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2682 Diag(OA->getLocation(), 2683 diag::override_keyword_hides_virtual_member_function) 2684 << "override" << (OverloadedMethods.size() > 1); 2685 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2686 Diag(FA->getLocation(), 2687 diag::override_keyword_hides_virtual_member_function) 2688 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2689 << (OverloadedMethods.size() > 1); 2690 } 2691 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2692 MD->setInvalidDecl(); 2693 return; 2694 } 2695 // Fall through into the general case diagnostic. 2696 // FIXME: We might want to attempt typo correction here. 2697 } 2698 2699 if (!MD || !MD->isVirtual()) { 2700 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2701 Diag(OA->getLocation(), 2702 diag::override_keyword_only_allowed_on_virtual_member_functions) 2703 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 2704 D->dropAttr<OverrideAttr>(); 2705 } 2706 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2707 Diag(FA->getLocation(), 2708 diag::override_keyword_only_allowed_on_virtual_member_functions) 2709 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2710 << FixItHint::CreateRemoval(FA->getLocation()); 2711 D->dropAttr<FinalAttr>(); 2712 } 2713 return; 2714 } 2715 2716 // C++11 [class.virtual]p5: 2717 // If a function is marked with the virt-specifier override and 2718 // does not override a member function of a base class, the program is 2719 // ill-formed. 2720 bool HasOverriddenMethods = 2721 MD->begin_overridden_methods() != MD->end_overridden_methods(); 2722 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 2723 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 2724 << MD->getDeclName(); 2725 } 2726 2727 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 2728 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 2729 return; 2730 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2731 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 2732 return; 2733 2734 SourceLocation Loc = MD->getLocation(); 2735 SourceLocation SpellingLoc = Loc; 2736 if (getSourceManager().isMacroArgExpansion(Loc)) 2737 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 2738 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 2739 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 2740 return; 2741 2742 if (MD->size_overridden_methods() > 0) { 2743 unsigned DiagID = isa<CXXDestructorDecl>(MD) 2744 ? diag::warn_destructor_marked_not_override_overriding 2745 : diag::warn_function_marked_not_override_overriding; 2746 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 2747 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 2748 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 2749 } 2750 } 2751 2752 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 2753 /// function overrides a virtual member function marked 'final', according to 2754 /// C++11 [class.virtual]p4. 2755 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 2756 const CXXMethodDecl *Old) { 2757 FinalAttr *FA = Old->getAttr<FinalAttr>(); 2758 if (!FA) 2759 return false; 2760 2761 Diag(New->getLocation(), diag::err_final_function_overridden) 2762 << New->getDeclName() 2763 << FA->isSpelledAsSealed(); 2764 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 2765 return true; 2766 } 2767 2768 static bool InitializationHasSideEffects(const FieldDecl &FD) { 2769 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 2770 // FIXME: Destruction of ObjC lifetime types has side-effects. 2771 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2772 return !RD->isCompleteDefinition() || 2773 !RD->hasTrivialDefaultConstructor() || 2774 !RD->hasTrivialDestructor(); 2775 return false; 2776 } 2777 2778 static AttributeList *getMSPropertyAttr(AttributeList *list) { 2779 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 2780 if (it->isDeclspecPropertyAttribute()) 2781 return it; 2782 return nullptr; 2783 } 2784 2785 // Check if there is a field shadowing. 2786 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 2787 DeclarationName FieldName, 2788 const CXXRecordDecl *RD) { 2789 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 2790 return; 2791 2792 // To record a shadowed field in a base 2793 std::map<CXXRecordDecl*, NamedDecl*> Bases; 2794 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 2795 CXXBasePath &Path) { 2796 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 2797 // Record an ambiguous path directly 2798 if (Bases.find(Base) != Bases.end()) 2799 return true; 2800 for (const auto Field : Base->lookup(FieldName)) { 2801 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 2802 Field->getAccess() != AS_private) { 2803 assert(Field->getAccess() != AS_none); 2804 assert(Bases.find(Base) == Bases.end()); 2805 Bases[Base] = Field; 2806 return true; 2807 } 2808 } 2809 return false; 2810 }; 2811 2812 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2813 /*DetectVirtual=*/true); 2814 if (!RD->lookupInBases(FieldShadowed, Paths)) 2815 return; 2816 2817 for (const auto &P : Paths) { 2818 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 2819 auto It = Bases.find(Base); 2820 // Skip duplicated bases 2821 if (It == Bases.end()) 2822 continue; 2823 auto BaseField = It->second; 2824 assert(BaseField->getAccess() != AS_private); 2825 if (AS_none != 2826 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 2827 Diag(Loc, diag::warn_shadow_field) 2828 << FieldName.getAsString() << RD->getName() << Base->getName(); 2829 Diag(BaseField->getLocation(), diag::note_shadow_field); 2830 Bases.erase(It); 2831 } 2832 } 2833 } 2834 2835 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 2836 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 2837 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 2838 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 2839 /// present (but parsing it has been deferred). 2840 NamedDecl * 2841 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 2842 MultiTemplateParamsArg TemplateParameterLists, 2843 Expr *BW, const VirtSpecifiers &VS, 2844 InClassInitStyle InitStyle) { 2845 const DeclSpec &DS = D.getDeclSpec(); 2846 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 2847 DeclarationName Name = NameInfo.getName(); 2848 SourceLocation Loc = NameInfo.getLoc(); 2849 2850 // For anonymous bitfields, the location should point to the type. 2851 if (Loc.isInvalid()) 2852 Loc = D.getLocStart(); 2853 2854 Expr *BitWidth = static_cast<Expr*>(BW); 2855 2856 assert(isa<CXXRecordDecl>(CurContext)); 2857 assert(!DS.isFriendSpecified()); 2858 2859 bool isFunc = D.isDeclarationOfFunction(); 2860 2861 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 2862 // The Microsoft extension __interface only permits public member functions 2863 // and prohibits constructors, destructors, operators, non-public member 2864 // functions, static methods and data members. 2865 unsigned InvalidDecl; 2866 bool ShowDeclName = true; 2867 if (!isFunc) 2868 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 2869 else if (AS != AS_public) 2870 InvalidDecl = 2; 2871 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 2872 InvalidDecl = 3; 2873 else switch (Name.getNameKind()) { 2874 case DeclarationName::CXXConstructorName: 2875 InvalidDecl = 4; 2876 ShowDeclName = false; 2877 break; 2878 2879 case DeclarationName::CXXDestructorName: 2880 InvalidDecl = 5; 2881 ShowDeclName = false; 2882 break; 2883 2884 case DeclarationName::CXXOperatorName: 2885 case DeclarationName::CXXConversionFunctionName: 2886 InvalidDecl = 6; 2887 break; 2888 2889 default: 2890 InvalidDecl = 0; 2891 break; 2892 } 2893 2894 if (InvalidDecl) { 2895 if (ShowDeclName) 2896 Diag(Loc, diag::err_invalid_member_in_interface) 2897 << (InvalidDecl-1) << Name; 2898 else 2899 Diag(Loc, diag::err_invalid_member_in_interface) 2900 << (InvalidDecl-1) << ""; 2901 return nullptr; 2902 } 2903 } 2904 2905 // C++ 9.2p6: A member shall not be declared to have automatic storage 2906 // duration (auto, register) or with the extern storage-class-specifier. 2907 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2908 // data members and cannot be applied to names declared const or static, 2909 // and cannot be applied to reference members. 2910 switch (DS.getStorageClassSpec()) { 2911 case DeclSpec::SCS_unspecified: 2912 case DeclSpec::SCS_typedef: 2913 case DeclSpec::SCS_static: 2914 break; 2915 case DeclSpec::SCS_mutable: 2916 if (isFunc) { 2917 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2918 2919 // FIXME: It would be nicer if the keyword was ignored only for this 2920 // declarator. Otherwise we could get follow-up errors. 2921 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2922 } 2923 break; 2924 default: 2925 Diag(DS.getStorageClassSpecLoc(), 2926 diag::err_storageclass_invalid_for_member); 2927 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2928 break; 2929 } 2930 2931 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2932 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2933 !isFunc); 2934 2935 if (DS.isConstexprSpecified() && isInstField) { 2936 SemaDiagnosticBuilder B = 2937 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2938 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2939 if (InitStyle == ICIS_NoInit) { 2940 B << 0 << 0; 2941 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2942 B << FixItHint::CreateRemoval(ConstexprLoc); 2943 else { 2944 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2945 D.getMutableDeclSpec().ClearConstexprSpec(); 2946 const char *PrevSpec; 2947 unsigned DiagID; 2948 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2949 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2950 (void)Failed; 2951 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2952 } 2953 } else { 2954 B << 1; 2955 const char *PrevSpec; 2956 unsigned DiagID; 2957 if (D.getMutableDeclSpec().SetStorageClassSpec( 2958 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2959 Context.getPrintingPolicy())) { 2960 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2961 "This is the only DeclSpec that should fail to be applied"); 2962 B << 1; 2963 } else { 2964 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2965 isInstField = false; 2966 } 2967 } 2968 } 2969 2970 NamedDecl *Member; 2971 if (isInstField) { 2972 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2973 2974 // Data members must have identifiers for names. 2975 if (!Name.isIdentifier()) { 2976 Diag(Loc, diag::err_bad_variable_name) 2977 << Name; 2978 return nullptr; 2979 } 2980 2981 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2982 2983 // Member field could not be with "template" keyword. 2984 // So TemplateParameterLists should be empty in this case. 2985 if (TemplateParameterLists.size()) { 2986 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2987 if (TemplateParams->size()) { 2988 // There is no such thing as a member field template. 2989 Diag(D.getIdentifierLoc(), diag::err_template_member) 2990 << II 2991 << SourceRange(TemplateParams->getTemplateLoc(), 2992 TemplateParams->getRAngleLoc()); 2993 } else { 2994 // There is an extraneous 'template<>' for this member. 2995 Diag(TemplateParams->getTemplateLoc(), 2996 diag::err_template_member_noparams) 2997 << II 2998 << SourceRange(TemplateParams->getTemplateLoc(), 2999 TemplateParams->getRAngleLoc()); 3000 } 3001 return nullptr; 3002 } 3003 3004 if (SS.isSet() && !SS.isInvalid()) { 3005 // The user provided a superfluous scope specifier inside a class 3006 // definition: 3007 // 3008 // class X { 3009 // int X::member; 3010 // }; 3011 if (DeclContext *DC = computeDeclContext(SS, false)) 3012 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 3013 else 3014 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3015 << Name << SS.getRange(); 3016 3017 SS.clear(); 3018 } 3019 3020 AttributeList *MSPropertyAttr = 3021 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 3022 if (MSPropertyAttr) { 3023 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3024 BitWidth, InitStyle, AS, MSPropertyAttr); 3025 if (!Member) 3026 return nullptr; 3027 isInstField = false; 3028 } else { 3029 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3030 BitWidth, InitStyle, AS); 3031 if (!Member) 3032 return nullptr; 3033 } 3034 3035 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3036 } else { 3037 Member = HandleDeclarator(S, D, TemplateParameterLists); 3038 if (!Member) 3039 return nullptr; 3040 3041 // Non-instance-fields can't have a bitfield. 3042 if (BitWidth) { 3043 if (Member->isInvalidDecl()) { 3044 // don't emit another diagnostic. 3045 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3046 // C++ 9.6p3: A bit-field shall not be a static member. 3047 // "static member 'A' cannot be a bit-field" 3048 Diag(Loc, diag::err_static_not_bitfield) 3049 << Name << BitWidth->getSourceRange(); 3050 } else if (isa<TypedefDecl>(Member)) { 3051 // "typedef member 'x' cannot be a bit-field" 3052 Diag(Loc, diag::err_typedef_not_bitfield) 3053 << Name << BitWidth->getSourceRange(); 3054 } else { 3055 // A function typedef ("typedef int f(); f a;"). 3056 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3057 Diag(Loc, diag::err_not_integral_type_bitfield) 3058 << Name << cast<ValueDecl>(Member)->getType() 3059 << BitWidth->getSourceRange(); 3060 } 3061 3062 BitWidth = nullptr; 3063 Member->setInvalidDecl(); 3064 } 3065 3066 Member->setAccess(AS); 3067 3068 // If we have declared a member function template or static data member 3069 // template, set the access of the templated declaration as well. 3070 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3071 FunTmpl->getTemplatedDecl()->setAccess(AS); 3072 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3073 VarTmpl->getTemplatedDecl()->setAccess(AS); 3074 } 3075 3076 if (VS.isOverrideSpecified()) 3077 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 3078 if (VS.isFinalSpecified()) 3079 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 3080 VS.isFinalSpelledSealed())); 3081 3082 if (VS.getLastLocation().isValid()) { 3083 // Update the end location of a method that has a virt-specifiers. 3084 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3085 MD->setRangeEnd(VS.getLastLocation()); 3086 } 3087 3088 CheckOverrideControl(Member); 3089 3090 assert((Name || isInstField) && "No identifier for non-field ?"); 3091 3092 if (isInstField) { 3093 FieldDecl *FD = cast<FieldDecl>(Member); 3094 FieldCollector->Add(FD); 3095 3096 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3097 // Remember all explicit private FieldDecls that have a name, no side 3098 // effects and are not part of a dependent type declaration. 3099 if (!FD->isImplicit() && FD->getDeclName() && 3100 FD->getAccess() == AS_private && 3101 !FD->hasAttr<UnusedAttr>() && 3102 !FD->getParent()->isDependentContext() && 3103 !InitializationHasSideEffects(*FD)) 3104 UnusedPrivateFields.insert(FD); 3105 } 3106 } 3107 3108 return Member; 3109 } 3110 3111 namespace { 3112 class UninitializedFieldVisitor 3113 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3114 Sema &S; 3115 // List of Decls to generate a warning on. Also remove Decls that become 3116 // initialized. 3117 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3118 // List of base classes of the record. Classes are removed after their 3119 // initializers. 3120 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3121 // Vector of decls to be removed from the Decl set prior to visiting the 3122 // nodes. These Decls may have been initialized in the prior initializer. 3123 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3124 // If non-null, add a note to the warning pointing back to the constructor. 3125 const CXXConstructorDecl *Constructor; 3126 // Variables to hold state when processing an initializer list. When 3127 // InitList is true, special case initialization of FieldDecls matching 3128 // InitListFieldDecl. 3129 bool InitList; 3130 FieldDecl *InitListFieldDecl; 3131 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3132 3133 public: 3134 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3135 UninitializedFieldVisitor(Sema &S, 3136 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3137 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3138 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3139 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3140 3141 // Returns true if the use of ME is not an uninitialized use. 3142 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3143 bool CheckReferenceOnly) { 3144 llvm::SmallVector<FieldDecl*, 4> Fields; 3145 bool ReferenceField = false; 3146 while (ME) { 3147 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3148 if (!FD) 3149 return false; 3150 Fields.push_back(FD); 3151 if (FD->getType()->isReferenceType()) 3152 ReferenceField = true; 3153 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3154 } 3155 3156 // Binding a reference to an unintialized field is not an 3157 // uninitialized use. 3158 if (CheckReferenceOnly && !ReferenceField) 3159 return true; 3160 3161 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3162 // Discard the first field since it is the field decl that is being 3163 // initialized. 3164 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3165 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3166 } 3167 3168 for (auto UsedIter = UsedFieldIndex.begin(), 3169 UsedEnd = UsedFieldIndex.end(), 3170 OrigIter = InitFieldIndex.begin(), 3171 OrigEnd = InitFieldIndex.end(); 3172 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3173 if (*UsedIter < *OrigIter) 3174 return true; 3175 if (*UsedIter > *OrigIter) 3176 break; 3177 } 3178 3179 return false; 3180 } 3181 3182 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3183 bool AddressOf) { 3184 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3185 return; 3186 3187 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3188 // or union. 3189 MemberExpr *FieldME = ME; 3190 3191 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3192 3193 Expr *Base = ME; 3194 while (MemberExpr *SubME = 3195 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3196 3197 if (isa<VarDecl>(SubME->getMemberDecl())) 3198 return; 3199 3200 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3201 if (!FD->isAnonymousStructOrUnion()) 3202 FieldME = SubME; 3203 3204 if (!FieldME->getType().isPODType(S.Context)) 3205 AllPODFields = false; 3206 3207 Base = SubME->getBase(); 3208 } 3209 3210 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3211 return; 3212 3213 if (AddressOf && AllPODFields) 3214 return; 3215 3216 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3217 3218 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3219 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3220 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3221 } 3222 3223 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3224 QualType T = BaseCast->getType(); 3225 if (T->isPointerType() && 3226 BaseClasses.count(T->getPointeeType())) { 3227 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3228 << T->getPointeeType() << FoundVD; 3229 } 3230 } 3231 } 3232 3233 if (!Decls.count(FoundVD)) 3234 return; 3235 3236 const bool IsReference = FoundVD->getType()->isReferenceType(); 3237 3238 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3239 // Special checking for initializer lists. 3240 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3241 return; 3242 } 3243 } else { 3244 // Prevent double warnings on use of unbounded references. 3245 if (CheckReferenceOnly && !IsReference) 3246 return; 3247 } 3248 3249 unsigned diag = IsReference 3250 ? diag::warn_reference_field_is_uninit 3251 : diag::warn_field_is_uninit; 3252 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3253 if (Constructor) 3254 S.Diag(Constructor->getLocation(), 3255 diag::note_uninit_in_this_constructor) 3256 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3257 3258 } 3259 3260 void HandleValue(Expr *E, bool AddressOf) { 3261 E = E->IgnoreParens(); 3262 3263 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3264 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3265 AddressOf /*AddressOf*/); 3266 return; 3267 } 3268 3269 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3270 Visit(CO->getCond()); 3271 HandleValue(CO->getTrueExpr(), AddressOf); 3272 HandleValue(CO->getFalseExpr(), AddressOf); 3273 return; 3274 } 3275 3276 if (BinaryConditionalOperator *BCO = 3277 dyn_cast<BinaryConditionalOperator>(E)) { 3278 Visit(BCO->getCond()); 3279 HandleValue(BCO->getFalseExpr(), AddressOf); 3280 return; 3281 } 3282 3283 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3284 HandleValue(OVE->getSourceExpr(), AddressOf); 3285 return; 3286 } 3287 3288 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3289 switch (BO->getOpcode()) { 3290 default: 3291 break; 3292 case(BO_PtrMemD): 3293 case(BO_PtrMemI): 3294 HandleValue(BO->getLHS(), AddressOf); 3295 Visit(BO->getRHS()); 3296 return; 3297 case(BO_Comma): 3298 Visit(BO->getLHS()); 3299 HandleValue(BO->getRHS(), AddressOf); 3300 return; 3301 } 3302 } 3303 3304 Visit(E); 3305 } 3306 3307 void CheckInitListExpr(InitListExpr *ILE) { 3308 InitFieldIndex.push_back(0); 3309 for (auto Child : ILE->children()) { 3310 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3311 CheckInitListExpr(SubList); 3312 } else { 3313 Visit(Child); 3314 } 3315 ++InitFieldIndex.back(); 3316 } 3317 InitFieldIndex.pop_back(); 3318 } 3319 3320 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3321 FieldDecl *Field, const Type *BaseClass) { 3322 // Remove Decls that may have been initialized in the previous 3323 // initializer. 3324 for (ValueDecl* VD : DeclsToRemove) 3325 Decls.erase(VD); 3326 DeclsToRemove.clear(); 3327 3328 Constructor = FieldConstructor; 3329 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3330 3331 if (ILE && Field) { 3332 InitList = true; 3333 InitListFieldDecl = Field; 3334 InitFieldIndex.clear(); 3335 CheckInitListExpr(ILE); 3336 } else { 3337 InitList = false; 3338 Visit(E); 3339 } 3340 3341 if (Field) 3342 Decls.erase(Field); 3343 if (BaseClass) 3344 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3345 } 3346 3347 void VisitMemberExpr(MemberExpr *ME) { 3348 // All uses of unbounded reference fields will warn. 3349 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3350 } 3351 3352 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3353 if (E->getCastKind() == CK_LValueToRValue) { 3354 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3355 return; 3356 } 3357 3358 Inherited::VisitImplicitCastExpr(E); 3359 } 3360 3361 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3362 if (E->getConstructor()->isCopyConstructor()) { 3363 Expr *ArgExpr = E->getArg(0); 3364 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3365 if (ILE->getNumInits() == 1) 3366 ArgExpr = ILE->getInit(0); 3367 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3368 if (ICE->getCastKind() == CK_NoOp) 3369 ArgExpr = ICE->getSubExpr(); 3370 HandleValue(ArgExpr, false /*AddressOf*/); 3371 return; 3372 } 3373 Inherited::VisitCXXConstructExpr(E); 3374 } 3375 3376 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3377 Expr *Callee = E->getCallee(); 3378 if (isa<MemberExpr>(Callee)) { 3379 HandleValue(Callee, false /*AddressOf*/); 3380 for (auto Arg : E->arguments()) 3381 Visit(Arg); 3382 return; 3383 } 3384 3385 Inherited::VisitCXXMemberCallExpr(E); 3386 } 3387 3388 void VisitCallExpr(CallExpr *E) { 3389 // Treat std::move as a use. 3390 if (E->getNumArgs() == 1) { 3391 if (FunctionDecl *FD = E->getDirectCallee()) { 3392 if (FD->isInStdNamespace() && FD->getIdentifier() && 3393 FD->getIdentifier()->isStr("move")) { 3394 HandleValue(E->getArg(0), false /*AddressOf*/); 3395 return; 3396 } 3397 } 3398 } 3399 3400 Inherited::VisitCallExpr(E); 3401 } 3402 3403 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3404 Expr *Callee = E->getCallee(); 3405 3406 if (isa<UnresolvedLookupExpr>(Callee)) 3407 return Inherited::VisitCXXOperatorCallExpr(E); 3408 3409 Visit(Callee); 3410 for (auto Arg : E->arguments()) 3411 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3412 } 3413 3414 void VisitBinaryOperator(BinaryOperator *E) { 3415 // If a field assignment is detected, remove the field from the 3416 // uninitiailized field set. 3417 if (E->getOpcode() == BO_Assign) 3418 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3419 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3420 if (!FD->getType()->isReferenceType()) 3421 DeclsToRemove.push_back(FD); 3422 3423 if (E->isCompoundAssignmentOp()) { 3424 HandleValue(E->getLHS(), false /*AddressOf*/); 3425 Visit(E->getRHS()); 3426 return; 3427 } 3428 3429 Inherited::VisitBinaryOperator(E); 3430 } 3431 3432 void VisitUnaryOperator(UnaryOperator *E) { 3433 if (E->isIncrementDecrementOp()) { 3434 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3435 return; 3436 } 3437 if (E->getOpcode() == UO_AddrOf) { 3438 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3439 HandleValue(ME->getBase(), true /*AddressOf*/); 3440 return; 3441 } 3442 } 3443 3444 Inherited::VisitUnaryOperator(E); 3445 } 3446 }; 3447 3448 // Diagnose value-uses of fields to initialize themselves, e.g. 3449 // foo(foo) 3450 // where foo is not also a parameter to the constructor. 3451 // Also diagnose across field uninitialized use such as 3452 // x(y), y(x) 3453 // TODO: implement -Wuninitialized and fold this into that framework. 3454 static void DiagnoseUninitializedFields( 3455 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3456 3457 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3458 Constructor->getLocation())) { 3459 return; 3460 } 3461 3462 if (Constructor->isInvalidDecl()) 3463 return; 3464 3465 const CXXRecordDecl *RD = Constructor->getParent(); 3466 3467 if (RD->getDescribedClassTemplate()) 3468 return; 3469 3470 // Holds fields that are uninitialized. 3471 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3472 3473 // At the beginning, all fields are uninitialized. 3474 for (auto *I : RD->decls()) { 3475 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3476 UninitializedFields.insert(FD); 3477 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3478 UninitializedFields.insert(IFD->getAnonField()); 3479 } 3480 } 3481 3482 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3483 for (auto I : RD->bases()) 3484 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3485 3486 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3487 return; 3488 3489 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3490 UninitializedFields, 3491 UninitializedBaseClasses); 3492 3493 for (const auto *FieldInit : Constructor->inits()) { 3494 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3495 break; 3496 3497 Expr *InitExpr = FieldInit->getInit(); 3498 if (!InitExpr) 3499 continue; 3500 3501 if (CXXDefaultInitExpr *Default = 3502 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3503 InitExpr = Default->getExpr(); 3504 if (!InitExpr) 3505 continue; 3506 // In class initializers will point to the constructor. 3507 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3508 FieldInit->getAnyMember(), 3509 FieldInit->getBaseClass()); 3510 } else { 3511 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3512 FieldInit->getAnyMember(), 3513 FieldInit->getBaseClass()); 3514 } 3515 } 3516 } 3517 } // namespace 3518 3519 /// \brief Enter a new C++ default initializer scope. After calling this, the 3520 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3521 /// parsing or instantiating the initializer failed. 3522 void Sema::ActOnStartCXXInClassMemberInitializer() { 3523 // Create a synthetic function scope to represent the call to the constructor 3524 // that notionally surrounds a use of this initializer. 3525 PushFunctionScope(); 3526 } 3527 3528 /// \brief This is invoked after parsing an in-class initializer for a 3529 /// non-static C++ class member, and after instantiating an in-class initializer 3530 /// in a class template. Such actions are deferred until the class is complete. 3531 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3532 SourceLocation InitLoc, 3533 Expr *InitExpr) { 3534 // Pop the notional constructor scope we created earlier. 3535 PopFunctionScopeInfo(nullptr, D); 3536 3537 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3538 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3539 "must set init style when field is created"); 3540 3541 if (!InitExpr) { 3542 D->setInvalidDecl(); 3543 if (FD) 3544 FD->removeInClassInitializer(); 3545 return; 3546 } 3547 3548 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3549 FD->setInvalidDecl(); 3550 FD->removeInClassInitializer(); 3551 return; 3552 } 3553 3554 ExprResult Init = InitExpr; 3555 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3556 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 3557 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 3558 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 3559 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 3560 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3561 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3562 if (Init.isInvalid()) { 3563 FD->setInvalidDecl(); 3564 return; 3565 } 3566 } 3567 3568 // C++11 [class.base.init]p7: 3569 // The initialization of each base and member constitutes a 3570 // full-expression. 3571 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 3572 if (Init.isInvalid()) { 3573 FD->setInvalidDecl(); 3574 return; 3575 } 3576 3577 InitExpr = Init.get(); 3578 3579 FD->setInClassInitializer(InitExpr); 3580 } 3581 3582 /// \brief Find the direct and/or virtual base specifiers that 3583 /// correspond to the given base type, for use in base initialization 3584 /// within a constructor. 3585 static bool FindBaseInitializer(Sema &SemaRef, 3586 CXXRecordDecl *ClassDecl, 3587 QualType BaseType, 3588 const CXXBaseSpecifier *&DirectBaseSpec, 3589 const CXXBaseSpecifier *&VirtualBaseSpec) { 3590 // First, check for a direct base class. 3591 DirectBaseSpec = nullptr; 3592 for (const auto &Base : ClassDecl->bases()) { 3593 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3594 // We found a direct base of this type. That's what we're 3595 // initializing. 3596 DirectBaseSpec = &Base; 3597 break; 3598 } 3599 } 3600 3601 // Check for a virtual base class. 3602 // FIXME: We might be able to short-circuit this if we know in advance that 3603 // there are no virtual bases. 3604 VirtualBaseSpec = nullptr; 3605 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3606 // We haven't found a base yet; search the class hierarchy for a 3607 // virtual base class. 3608 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3609 /*DetectVirtual=*/false); 3610 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3611 SemaRef.Context.getTypeDeclType(ClassDecl), 3612 BaseType, Paths)) { 3613 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3614 Path != Paths.end(); ++Path) { 3615 if (Path->back().Base->isVirtual()) { 3616 VirtualBaseSpec = Path->back().Base; 3617 break; 3618 } 3619 } 3620 } 3621 } 3622 3623 return DirectBaseSpec || VirtualBaseSpec; 3624 } 3625 3626 /// \brief Handle a C++ member initializer using braced-init-list syntax. 3627 MemInitResult 3628 Sema::ActOnMemInitializer(Decl *ConstructorD, 3629 Scope *S, 3630 CXXScopeSpec &SS, 3631 IdentifierInfo *MemberOrBase, 3632 ParsedType TemplateTypeTy, 3633 const DeclSpec &DS, 3634 SourceLocation IdLoc, 3635 Expr *InitList, 3636 SourceLocation EllipsisLoc) { 3637 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3638 DS, IdLoc, InitList, 3639 EllipsisLoc); 3640 } 3641 3642 /// \brief Handle a C++ member initializer using parentheses syntax. 3643 MemInitResult 3644 Sema::ActOnMemInitializer(Decl *ConstructorD, 3645 Scope *S, 3646 CXXScopeSpec &SS, 3647 IdentifierInfo *MemberOrBase, 3648 ParsedType TemplateTypeTy, 3649 const DeclSpec &DS, 3650 SourceLocation IdLoc, 3651 SourceLocation LParenLoc, 3652 ArrayRef<Expr *> Args, 3653 SourceLocation RParenLoc, 3654 SourceLocation EllipsisLoc) { 3655 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 3656 Args, RParenLoc); 3657 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3658 DS, IdLoc, List, EllipsisLoc); 3659 } 3660 3661 namespace { 3662 3663 // Callback to only accept typo corrections that can be a valid C++ member 3664 // intializer: either a non-static field member or a base class. 3665 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 3666 public: 3667 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 3668 : ClassDecl(ClassDecl) {} 3669 3670 bool ValidateCandidate(const TypoCorrection &candidate) override { 3671 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 3672 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 3673 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 3674 return isa<TypeDecl>(ND); 3675 } 3676 return false; 3677 } 3678 3679 private: 3680 CXXRecordDecl *ClassDecl; 3681 }; 3682 3683 } 3684 3685 /// \brief Handle a C++ member initializer. 3686 MemInitResult 3687 Sema::BuildMemInitializer(Decl *ConstructorD, 3688 Scope *S, 3689 CXXScopeSpec &SS, 3690 IdentifierInfo *MemberOrBase, 3691 ParsedType TemplateTypeTy, 3692 const DeclSpec &DS, 3693 SourceLocation IdLoc, 3694 Expr *Init, 3695 SourceLocation EllipsisLoc) { 3696 ExprResult Res = CorrectDelayedTyposInExpr(Init); 3697 if (!Res.isUsable()) 3698 return true; 3699 Init = Res.get(); 3700 3701 if (!ConstructorD) 3702 return true; 3703 3704 AdjustDeclIfTemplate(ConstructorD); 3705 3706 CXXConstructorDecl *Constructor 3707 = dyn_cast<CXXConstructorDecl>(ConstructorD); 3708 if (!Constructor) { 3709 // The user wrote a constructor initializer on a function that is 3710 // not a C++ constructor. Ignore the error for now, because we may 3711 // have more member initializers coming; we'll diagnose it just 3712 // once in ActOnMemInitializers. 3713 return true; 3714 } 3715 3716 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3717 3718 // C++ [class.base.init]p2: 3719 // Names in a mem-initializer-id are looked up in the scope of the 3720 // constructor's class and, if not found in that scope, are looked 3721 // up in the scope containing the constructor's definition. 3722 // [Note: if the constructor's class contains a member with the 3723 // same name as a direct or virtual base class of the class, a 3724 // mem-initializer-id naming the member or base class and composed 3725 // of a single identifier refers to the class member. A 3726 // mem-initializer-id for the hidden base class may be specified 3727 // using a qualified name. ] 3728 if (!SS.getScopeRep() && !TemplateTypeTy) { 3729 // Look for a member, first. 3730 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 3731 if (!Result.empty()) { 3732 ValueDecl *Member; 3733 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 3734 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 3735 if (EllipsisLoc.isValid()) 3736 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 3737 << MemberOrBase 3738 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 3739 3740 return BuildMemberInitializer(Member, Init, IdLoc); 3741 } 3742 } 3743 } 3744 // It didn't name a member, so see if it names a class. 3745 QualType BaseType; 3746 TypeSourceInfo *TInfo = nullptr; 3747 3748 if (TemplateTypeTy) { 3749 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 3750 } else if (DS.getTypeSpecType() == TST_decltype) { 3751 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3752 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 3753 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 3754 return true; 3755 } else { 3756 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 3757 LookupParsedName(R, S, &SS); 3758 3759 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 3760 if (!TyD) { 3761 if (R.isAmbiguous()) return true; 3762 3763 // We don't want access-control diagnostics here. 3764 R.suppressDiagnostics(); 3765 3766 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 3767 bool NotUnknownSpecialization = false; 3768 DeclContext *DC = computeDeclContext(SS, false); 3769 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 3770 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 3771 3772 if (!NotUnknownSpecialization) { 3773 // When the scope specifier can refer to a member of an unknown 3774 // specialization, we take it as a type name. 3775 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 3776 SS.getWithLocInContext(Context), 3777 *MemberOrBase, IdLoc); 3778 if (BaseType.isNull()) 3779 return true; 3780 3781 TInfo = Context.CreateTypeSourceInfo(BaseType); 3782 DependentNameTypeLoc TL = 3783 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 3784 if (!TL.isNull()) { 3785 TL.setNameLoc(IdLoc); 3786 TL.setElaboratedKeywordLoc(SourceLocation()); 3787 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3788 } 3789 3790 R.clear(); 3791 R.setLookupName(MemberOrBase); 3792 } 3793 } 3794 3795 // If no results were found, try to correct typos. 3796 TypoCorrection Corr; 3797 if (R.empty() && BaseType.isNull() && 3798 (Corr = CorrectTypo( 3799 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 3800 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 3801 CTK_ErrorRecovery, ClassDecl))) { 3802 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 3803 // We have found a non-static data member with a similar 3804 // name to what was typed; complain and initialize that 3805 // member. 3806 diagnoseTypo(Corr, 3807 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3808 << MemberOrBase << true); 3809 return BuildMemberInitializer(Member, Init, IdLoc); 3810 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 3811 const CXXBaseSpecifier *DirectBaseSpec; 3812 const CXXBaseSpecifier *VirtualBaseSpec; 3813 if (FindBaseInitializer(*this, ClassDecl, 3814 Context.getTypeDeclType(Type), 3815 DirectBaseSpec, VirtualBaseSpec)) { 3816 // We have found a direct or virtual base class with a 3817 // similar name to what was typed; complain and initialize 3818 // that base class. 3819 diagnoseTypo(Corr, 3820 PDiag(diag::err_mem_init_not_member_or_class_suggest) 3821 << MemberOrBase << false, 3822 PDiag() /*Suppress note, we provide our own.*/); 3823 3824 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 3825 : VirtualBaseSpec; 3826 Diag(BaseSpec->getLocStart(), 3827 diag::note_base_class_specified_here) 3828 << BaseSpec->getType() 3829 << BaseSpec->getSourceRange(); 3830 3831 TyD = Type; 3832 } 3833 } 3834 } 3835 3836 if (!TyD && BaseType.isNull()) { 3837 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 3838 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 3839 return true; 3840 } 3841 } 3842 3843 if (BaseType.isNull()) { 3844 BaseType = Context.getTypeDeclType(TyD); 3845 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 3846 if (SS.isSet()) { 3847 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 3848 BaseType); 3849 TInfo = Context.CreateTypeSourceInfo(BaseType); 3850 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 3851 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 3852 TL.setElaboratedKeywordLoc(SourceLocation()); 3853 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3854 } 3855 } 3856 } 3857 3858 if (!TInfo) 3859 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 3860 3861 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 3862 } 3863 3864 /// Checks a member initializer expression for cases where reference (or 3865 /// pointer) members are bound to by-value parameters (or their addresses). 3866 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 3867 Expr *Init, 3868 SourceLocation IdLoc) { 3869 QualType MemberTy = Member->getType(); 3870 3871 // We only handle pointers and references currently. 3872 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 3873 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 3874 return; 3875 3876 const bool IsPointer = MemberTy->isPointerType(); 3877 if (IsPointer) { 3878 if (const UnaryOperator *Op 3879 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 3880 // The only case we're worried about with pointers requires taking the 3881 // address. 3882 if (Op->getOpcode() != UO_AddrOf) 3883 return; 3884 3885 Init = Op->getSubExpr(); 3886 } else { 3887 // We only handle address-of expression initializers for pointers. 3888 return; 3889 } 3890 } 3891 3892 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 3893 // We only warn when referring to a non-reference parameter declaration. 3894 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 3895 if (!Parameter || Parameter->getType()->isReferenceType()) 3896 return; 3897 3898 S.Diag(Init->getExprLoc(), 3899 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 3900 : diag::warn_bind_ref_member_to_parameter) 3901 << Member << Parameter << Init->getSourceRange(); 3902 } else { 3903 // Other initializers are fine. 3904 return; 3905 } 3906 3907 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3908 << (unsigned)IsPointer; 3909 } 3910 3911 MemInitResult 3912 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3913 SourceLocation IdLoc) { 3914 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3915 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3916 assert((DirectMember || IndirectMember) && 3917 "Member must be a FieldDecl or IndirectFieldDecl"); 3918 3919 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3920 return true; 3921 3922 if (Member->isInvalidDecl()) 3923 return true; 3924 3925 MultiExprArg Args; 3926 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3927 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3928 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3929 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3930 } else { 3931 // Template instantiation doesn't reconstruct ParenListExprs for us. 3932 Args = Init; 3933 } 3934 3935 SourceRange InitRange = Init->getSourceRange(); 3936 3937 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3938 // Can't check initialization for a member of dependent type or when 3939 // any of the arguments are type-dependent expressions. 3940 DiscardCleanupsInEvaluationContext(); 3941 } else { 3942 bool InitList = false; 3943 if (isa<InitListExpr>(Init)) { 3944 InitList = true; 3945 Args = Init; 3946 } 3947 3948 // Initialize the member. 3949 InitializedEntity MemberEntity = 3950 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3951 : InitializedEntity::InitializeMember(IndirectMember, 3952 nullptr); 3953 InitializationKind Kind = 3954 InitList ? InitializationKind::CreateDirectList(IdLoc) 3955 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3956 InitRange.getEnd()); 3957 3958 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3959 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3960 nullptr); 3961 if (MemberInit.isInvalid()) 3962 return true; 3963 3964 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3965 3966 // C++11 [class.base.init]p7: 3967 // The initialization of each base and member constitutes a 3968 // full-expression. 3969 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3970 if (MemberInit.isInvalid()) 3971 return true; 3972 3973 Init = MemberInit.get(); 3974 } 3975 3976 if (DirectMember) { 3977 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 3978 InitRange.getBegin(), Init, 3979 InitRange.getEnd()); 3980 } else { 3981 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 3982 InitRange.getBegin(), Init, 3983 InitRange.getEnd()); 3984 } 3985 } 3986 3987 MemInitResult 3988 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 3989 CXXRecordDecl *ClassDecl) { 3990 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3991 if (!LangOpts.CPlusPlus11) 3992 return Diag(NameLoc, diag::err_delegating_ctor) 3993 << TInfo->getTypeLoc().getLocalSourceRange(); 3994 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 3995 3996 bool InitList = true; 3997 MultiExprArg Args = Init; 3998 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3999 InitList = false; 4000 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4001 } 4002 4003 SourceRange InitRange = Init->getSourceRange(); 4004 // Initialize the object. 4005 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4006 QualType(ClassDecl->getTypeForDecl(), 0)); 4007 InitializationKind Kind = 4008 InitList ? InitializationKind::CreateDirectList(NameLoc) 4009 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4010 InitRange.getEnd()); 4011 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4012 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4013 Args, nullptr); 4014 if (DelegationInit.isInvalid()) 4015 return true; 4016 4017 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4018 "Delegating constructor with no target?"); 4019 4020 // C++11 [class.base.init]p7: 4021 // The initialization of each base and member constitutes a 4022 // full-expression. 4023 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 4024 InitRange.getBegin()); 4025 if (DelegationInit.isInvalid()) 4026 return true; 4027 4028 // If we are in a dependent context, template instantiation will 4029 // perform this type-checking again. Just save the arguments that we 4030 // received in a ParenListExpr. 4031 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4032 // of the information that we have about the base 4033 // initializer. However, deconstructing the ASTs is a dicey process, 4034 // and this approach is far more likely to get the corner cases right. 4035 if (CurContext->isDependentContext()) 4036 DelegationInit = Init; 4037 4038 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4039 DelegationInit.getAs<Expr>(), 4040 InitRange.getEnd()); 4041 } 4042 4043 MemInitResult 4044 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4045 Expr *Init, CXXRecordDecl *ClassDecl, 4046 SourceLocation EllipsisLoc) { 4047 SourceLocation BaseLoc 4048 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4049 4050 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4051 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4052 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4053 4054 // C++ [class.base.init]p2: 4055 // [...] Unless the mem-initializer-id names a nonstatic data 4056 // member of the constructor's class or a direct or virtual base 4057 // of that class, the mem-initializer is ill-formed. A 4058 // mem-initializer-list can initialize a base class using any 4059 // name that denotes that base class type. 4060 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4061 4062 SourceRange InitRange = Init->getSourceRange(); 4063 if (EllipsisLoc.isValid()) { 4064 // This is a pack expansion. 4065 if (!BaseType->containsUnexpandedParameterPack()) { 4066 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4067 << SourceRange(BaseLoc, InitRange.getEnd()); 4068 4069 EllipsisLoc = SourceLocation(); 4070 } 4071 } else { 4072 // Check for any unexpanded parameter packs. 4073 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4074 return true; 4075 4076 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4077 return true; 4078 } 4079 4080 // Check for direct and virtual base classes. 4081 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4082 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4083 if (!Dependent) { 4084 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4085 BaseType)) 4086 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4087 4088 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4089 VirtualBaseSpec); 4090 4091 // C++ [base.class.init]p2: 4092 // Unless the mem-initializer-id names a nonstatic data member of the 4093 // constructor's class or a direct or virtual base of that class, the 4094 // mem-initializer is ill-formed. 4095 if (!DirectBaseSpec && !VirtualBaseSpec) { 4096 // If the class has any dependent bases, then it's possible that 4097 // one of those types will resolve to the same type as 4098 // BaseType. Therefore, just treat this as a dependent base 4099 // class initialization. FIXME: Should we try to check the 4100 // initialization anyway? It seems odd. 4101 if (ClassDecl->hasAnyDependentBases()) 4102 Dependent = true; 4103 else 4104 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4105 << BaseType << Context.getTypeDeclType(ClassDecl) 4106 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4107 } 4108 } 4109 4110 if (Dependent) { 4111 DiscardCleanupsInEvaluationContext(); 4112 4113 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4114 /*IsVirtual=*/false, 4115 InitRange.getBegin(), Init, 4116 InitRange.getEnd(), EllipsisLoc); 4117 } 4118 4119 // C++ [base.class.init]p2: 4120 // If a mem-initializer-id is ambiguous because it designates both 4121 // a direct non-virtual base class and an inherited virtual base 4122 // class, the mem-initializer is ill-formed. 4123 if (DirectBaseSpec && VirtualBaseSpec) 4124 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4125 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4126 4127 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4128 if (!BaseSpec) 4129 BaseSpec = VirtualBaseSpec; 4130 4131 // Initialize the base. 4132 bool InitList = true; 4133 MultiExprArg Args = Init; 4134 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4135 InitList = false; 4136 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4137 } 4138 4139 InitializedEntity BaseEntity = 4140 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4141 InitializationKind Kind = 4142 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4143 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4144 InitRange.getEnd()); 4145 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4146 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4147 if (BaseInit.isInvalid()) 4148 return true; 4149 4150 // C++11 [class.base.init]p7: 4151 // The initialization of each base and member constitutes a 4152 // full-expression. 4153 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 4154 if (BaseInit.isInvalid()) 4155 return true; 4156 4157 // If we are in a dependent context, template instantiation will 4158 // perform this type-checking again. Just save the arguments that we 4159 // received in a ParenListExpr. 4160 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4161 // of the information that we have about the base 4162 // initializer. However, deconstructing the ASTs is a dicey process, 4163 // and this approach is far more likely to get the corner cases right. 4164 if (CurContext->isDependentContext()) 4165 BaseInit = Init; 4166 4167 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4168 BaseSpec->isVirtual(), 4169 InitRange.getBegin(), 4170 BaseInit.getAs<Expr>(), 4171 InitRange.getEnd(), EllipsisLoc); 4172 } 4173 4174 // Create a static_cast\<T&&>(expr). 4175 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4176 if (T.isNull()) T = E->getType(); 4177 QualType TargetType = SemaRef.BuildReferenceType( 4178 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4179 SourceLocation ExprLoc = E->getLocStart(); 4180 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4181 TargetType, ExprLoc); 4182 4183 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4184 SourceRange(ExprLoc, ExprLoc), 4185 E->getSourceRange()).get(); 4186 } 4187 4188 /// ImplicitInitializerKind - How an implicit base or member initializer should 4189 /// initialize its base or member. 4190 enum ImplicitInitializerKind { 4191 IIK_Default, 4192 IIK_Copy, 4193 IIK_Move, 4194 IIK_Inherit 4195 }; 4196 4197 static bool 4198 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4199 ImplicitInitializerKind ImplicitInitKind, 4200 CXXBaseSpecifier *BaseSpec, 4201 bool IsInheritedVirtualBase, 4202 CXXCtorInitializer *&CXXBaseInit) { 4203 InitializedEntity InitEntity 4204 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4205 IsInheritedVirtualBase); 4206 4207 ExprResult BaseInit; 4208 4209 switch (ImplicitInitKind) { 4210 case IIK_Inherit: 4211 case IIK_Default: { 4212 InitializationKind InitKind 4213 = InitializationKind::CreateDefault(Constructor->getLocation()); 4214 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4215 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4216 break; 4217 } 4218 4219 case IIK_Move: 4220 case IIK_Copy: { 4221 bool Moving = ImplicitInitKind == IIK_Move; 4222 ParmVarDecl *Param = Constructor->getParamDecl(0); 4223 QualType ParamType = Param->getType().getNonReferenceType(); 4224 4225 Expr *CopyCtorArg = 4226 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4227 SourceLocation(), Param, false, 4228 Constructor->getLocation(), ParamType, 4229 VK_LValue, nullptr); 4230 4231 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4232 4233 // Cast to the base class to avoid ambiguities. 4234 QualType ArgTy = 4235 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4236 ParamType.getQualifiers()); 4237 4238 if (Moving) { 4239 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4240 } 4241 4242 CXXCastPath BasePath; 4243 BasePath.push_back(BaseSpec); 4244 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4245 CK_UncheckedDerivedToBase, 4246 Moving ? VK_XValue : VK_LValue, 4247 &BasePath).get(); 4248 4249 InitializationKind InitKind 4250 = InitializationKind::CreateDirect(Constructor->getLocation(), 4251 SourceLocation(), SourceLocation()); 4252 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4253 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4254 break; 4255 } 4256 } 4257 4258 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4259 if (BaseInit.isInvalid()) 4260 return true; 4261 4262 CXXBaseInit = 4263 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4264 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4265 SourceLocation()), 4266 BaseSpec->isVirtual(), 4267 SourceLocation(), 4268 BaseInit.getAs<Expr>(), 4269 SourceLocation(), 4270 SourceLocation()); 4271 4272 return false; 4273 } 4274 4275 static bool RefersToRValueRef(Expr *MemRef) { 4276 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4277 return Referenced->getType()->isRValueReferenceType(); 4278 } 4279 4280 static bool 4281 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4282 ImplicitInitializerKind ImplicitInitKind, 4283 FieldDecl *Field, IndirectFieldDecl *Indirect, 4284 CXXCtorInitializer *&CXXMemberInit) { 4285 if (Field->isInvalidDecl()) 4286 return true; 4287 4288 SourceLocation Loc = Constructor->getLocation(); 4289 4290 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4291 bool Moving = ImplicitInitKind == IIK_Move; 4292 ParmVarDecl *Param = Constructor->getParamDecl(0); 4293 QualType ParamType = Param->getType().getNonReferenceType(); 4294 4295 // Suppress copying zero-width bitfields. 4296 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 4297 return false; 4298 4299 Expr *MemberExprBase = 4300 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4301 SourceLocation(), Param, false, 4302 Loc, ParamType, VK_LValue, nullptr); 4303 4304 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4305 4306 if (Moving) { 4307 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4308 } 4309 4310 // Build a reference to this field within the parameter. 4311 CXXScopeSpec SS; 4312 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4313 Sema::LookupMemberName); 4314 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4315 : cast<ValueDecl>(Field), AS_public); 4316 MemberLookup.resolveKind(); 4317 ExprResult CtorArg 4318 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4319 ParamType, Loc, 4320 /*IsArrow=*/false, 4321 SS, 4322 /*TemplateKWLoc=*/SourceLocation(), 4323 /*FirstQualifierInScope=*/nullptr, 4324 MemberLookup, 4325 /*TemplateArgs=*/nullptr, 4326 /*S*/nullptr); 4327 if (CtorArg.isInvalid()) 4328 return true; 4329 4330 // C++11 [class.copy]p15: 4331 // - if a member m has rvalue reference type T&&, it is direct-initialized 4332 // with static_cast<T&&>(x.m); 4333 if (RefersToRValueRef(CtorArg.get())) { 4334 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4335 } 4336 4337 InitializedEntity Entity = 4338 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4339 /*Implicit*/ true) 4340 : InitializedEntity::InitializeMember(Field, nullptr, 4341 /*Implicit*/ true); 4342 4343 // Direct-initialize to use the copy constructor. 4344 InitializationKind InitKind = 4345 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4346 4347 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4348 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4349 ExprResult MemberInit = 4350 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4351 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4352 if (MemberInit.isInvalid()) 4353 return true; 4354 4355 if (Indirect) 4356 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4357 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4358 else 4359 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4360 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4361 return false; 4362 } 4363 4364 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4365 "Unhandled implicit init kind!"); 4366 4367 QualType FieldBaseElementType = 4368 SemaRef.Context.getBaseElementType(Field->getType()); 4369 4370 if (FieldBaseElementType->isRecordType()) { 4371 InitializedEntity InitEntity = 4372 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4373 /*Implicit*/ true) 4374 : InitializedEntity::InitializeMember(Field, nullptr, 4375 /*Implicit*/ true); 4376 InitializationKind InitKind = 4377 InitializationKind::CreateDefault(Loc); 4378 4379 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4380 ExprResult MemberInit = 4381 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4382 4383 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4384 if (MemberInit.isInvalid()) 4385 return true; 4386 4387 if (Indirect) 4388 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4389 Indirect, Loc, 4390 Loc, 4391 MemberInit.get(), 4392 Loc); 4393 else 4394 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4395 Field, Loc, Loc, 4396 MemberInit.get(), 4397 Loc); 4398 return false; 4399 } 4400 4401 if (!Field->getParent()->isUnion()) { 4402 if (FieldBaseElementType->isReferenceType()) { 4403 SemaRef.Diag(Constructor->getLocation(), 4404 diag::err_uninitialized_member_in_ctor) 4405 << (int)Constructor->isImplicit() 4406 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4407 << 0 << Field->getDeclName(); 4408 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4409 return true; 4410 } 4411 4412 if (FieldBaseElementType.isConstQualified()) { 4413 SemaRef.Diag(Constructor->getLocation(), 4414 diag::err_uninitialized_member_in_ctor) 4415 << (int)Constructor->isImplicit() 4416 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4417 << 1 << Field->getDeclName(); 4418 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4419 return true; 4420 } 4421 } 4422 4423 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4424 // ARC and Weak: 4425 // Default-initialize Objective-C pointers to NULL. 4426 CXXMemberInit 4427 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4428 Loc, Loc, 4429 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4430 Loc); 4431 return false; 4432 } 4433 4434 // Nothing to initialize. 4435 CXXMemberInit = nullptr; 4436 return false; 4437 } 4438 4439 namespace { 4440 struct BaseAndFieldInfo { 4441 Sema &S; 4442 CXXConstructorDecl *Ctor; 4443 bool AnyErrorsInInits; 4444 ImplicitInitializerKind IIK; 4445 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4446 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4447 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4448 4449 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4450 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4451 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4452 if (Ctor->getInheritedConstructor()) 4453 IIK = IIK_Inherit; 4454 else if (Generated && Ctor->isCopyConstructor()) 4455 IIK = IIK_Copy; 4456 else if (Generated && Ctor->isMoveConstructor()) 4457 IIK = IIK_Move; 4458 else 4459 IIK = IIK_Default; 4460 } 4461 4462 bool isImplicitCopyOrMove() const { 4463 switch (IIK) { 4464 case IIK_Copy: 4465 case IIK_Move: 4466 return true; 4467 4468 case IIK_Default: 4469 case IIK_Inherit: 4470 return false; 4471 } 4472 4473 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4474 } 4475 4476 bool addFieldInitializer(CXXCtorInitializer *Init) { 4477 AllToInit.push_back(Init); 4478 4479 // Check whether this initializer makes the field "used". 4480 if (Init->getInit()->HasSideEffects(S.Context)) 4481 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4482 4483 return false; 4484 } 4485 4486 bool isInactiveUnionMember(FieldDecl *Field) { 4487 RecordDecl *Record = Field->getParent(); 4488 if (!Record->isUnion()) 4489 return false; 4490 4491 if (FieldDecl *Active = 4492 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4493 return Active != Field->getCanonicalDecl(); 4494 4495 // In an implicit copy or move constructor, ignore any in-class initializer. 4496 if (isImplicitCopyOrMove()) 4497 return true; 4498 4499 // If there's no explicit initialization, the field is active only if it 4500 // has an in-class initializer... 4501 if (Field->hasInClassInitializer()) 4502 return false; 4503 // ... or it's an anonymous struct or union whose class has an in-class 4504 // initializer. 4505 if (!Field->isAnonymousStructOrUnion()) 4506 return true; 4507 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4508 return !FieldRD->hasInClassInitializer(); 4509 } 4510 4511 /// \brief Determine whether the given field is, or is within, a union member 4512 /// that is inactive (because there was an initializer given for a different 4513 /// member of the union, or because the union was not initialized at all). 4514 bool isWithinInactiveUnionMember(FieldDecl *Field, 4515 IndirectFieldDecl *Indirect) { 4516 if (!Indirect) 4517 return isInactiveUnionMember(Field); 4518 4519 for (auto *C : Indirect->chain()) { 4520 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4521 if (Field && isInactiveUnionMember(Field)) 4522 return true; 4523 } 4524 return false; 4525 } 4526 }; 4527 } 4528 4529 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 4530 /// array type. 4531 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4532 if (T->isIncompleteArrayType()) 4533 return true; 4534 4535 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4536 if (!ArrayT->getSize()) 4537 return true; 4538 4539 T = ArrayT->getElementType(); 4540 } 4541 4542 return false; 4543 } 4544 4545 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4546 FieldDecl *Field, 4547 IndirectFieldDecl *Indirect = nullptr) { 4548 if (Field->isInvalidDecl()) 4549 return false; 4550 4551 // Overwhelmingly common case: we have a direct initializer for this field. 4552 if (CXXCtorInitializer *Init = 4553 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4554 return Info.addFieldInitializer(Init); 4555 4556 // C++11 [class.base.init]p8: 4557 // if the entity is a non-static data member that has a 4558 // brace-or-equal-initializer and either 4559 // -- the constructor's class is a union and no other variant member of that 4560 // union is designated by a mem-initializer-id or 4561 // -- the constructor's class is not a union, and, if the entity is a member 4562 // of an anonymous union, no other member of that union is designated by 4563 // a mem-initializer-id, 4564 // the entity is initialized as specified in [dcl.init]. 4565 // 4566 // We also apply the same rules to handle anonymous structs within anonymous 4567 // unions. 4568 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4569 return false; 4570 4571 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4572 ExprResult DIE = 4573 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4574 if (DIE.isInvalid()) 4575 return true; 4576 CXXCtorInitializer *Init; 4577 if (Indirect) 4578 Init = new (SemaRef.Context) 4579 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4580 SourceLocation(), DIE.get(), SourceLocation()); 4581 else 4582 Init = new (SemaRef.Context) 4583 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4584 SourceLocation(), DIE.get(), SourceLocation()); 4585 return Info.addFieldInitializer(Init); 4586 } 4587 4588 // Don't initialize incomplete or zero-length arrays. 4589 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4590 return false; 4591 4592 // Don't try to build an implicit initializer if there were semantic 4593 // errors in any of the initializers (and therefore we might be 4594 // missing some that the user actually wrote). 4595 if (Info.AnyErrorsInInits) 4596 return false; 4597 4598 CXXCtorInitializer *Init = nullptr; 4599 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4600 Indirect, Init)) 4601 return true; 4602 4603 if (!Init) 4604 return false; 4605 4606 return Info.addFieldInitializer(Init); 4607 } 4608 4609 bool 4610 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4611 CXXCtorInitializer *Initializer) { 4612 assert(Initializer->isDelegatingInitializer()); 4613 Constructor->setNumCtorInitializers(1); 4614 CXXCtorInitializer **initializer = 4615 new (Context) CXXCtorInitializer*[1]; 4616 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4617 Constructor->setCtorInitializers(initializer); 4618 4619 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4620 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4621 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4622 } 4623 4624 DelegatingCtorDecls.push_back(Constructor); 4625 4626 DiagnoseUninitializedFields(*this, Constructor); 4627 4628 return false; 4629 } 4630 4631 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4632 ArrayRef<CXXCtorInitializer *> Initializers) { 4633 if (Constructor->isDependentContext()) { 4634 // Just store the initializers as written, they will be checked during 4635 // instantiation. 4636 if (!Initializers.empty()) { 4637 Constructor->setNumCtorInitializers(Initializers.size()); 4638 CXXCtorInitializer **baseOrMemberInitializers = 4639 new (Context) CXXCtorInitializer*[Initializers.size()]; 4640 memcpy(baseOrMemberInitializers, Initializers.data(), 4641 Initializers.size() * sizeof(CXXCtorInitializer*)); 4642 Constructor->setCtorInitializers(baseOrMemberInitializers); 4643 } 4644 4645 // Let template instantiation know whether we had errors. 4646 if (AnyErrors) 4647 Constructor->setInvalidDecl(); 4648 4649 return false; 4650 } 4651 4652 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4653 4654 // We need to build the initializer AST according to order of construction 4655 // and not what user specified in the Initializers list. 4656 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4657 if (!ClassDecl) 4658 return true; 4659 4660 bool HadError = false; 4661 4662 for (unsigned i = 0; i < Initializers.size(); i++) { 4663 CXXCtorInitializer *Member = Initializers[i]; 4664 4665 if (Member->isBaseInitializer()) 4666 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4667 else { 4668 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4669 4670 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4671 for (auto *C : F->chain()) { 4672 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4673 if (FD && FD->getParent()->isUnion()) 4674 Info.ActiveUnionMember.insert(std::make_pair( 4675 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4676 } 4677 } else if (FieldDecl *FD = Member->getMember()) { 4678 if (FD->getParent()->isUnion()) 4679 Info.ActiveUnionMember.insert(std::make_pair( 4680 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4681 } 4682 } 4683 } 4684 4685 // Keep track of the direct virtual bases. 4686 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4687 for (auto &I : ClassDecl->bases()) { 4688 if (I.isVirtual()) 4689 DirectVBases.insert(&I); 4690 } 4691 4692 // Push virtual bases before others. 4693 for (auto &VBase : ClassDecl->vbases()) { 4694 if (CXXCtorInitializer *Value 4695 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 4696 // [class.base.init]p7, per DR257: 4697 // A mem-initializer where the mem-initializer-id names a virtual base 4698 // class is ignored during execution of a constructor of any class that 4699 // is not the most derived class. 4700 if (ClassDecl->isAbstract()) { 4701 // FIXME: Provide a fixit to remove the base specifier. This requires 4702 // tracking the location of the associated comma for a base specifier. 4703 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 4704 << VBase.getType() << ClassDecl; 4705 DiagnoseAbstractType(ClassDecl); 4706 } 4707 4708 Info.AllToInit.push_back(Value); 4709 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 4710 // [class.base.init]p8, per DR257: 4711 // If a given [...] base class is not named by a mem-initializer-id 4712 // [...] and the entity is not a virtual base class of an abstract 4713 // class, then [...] the entity is default-initialized. 4714 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 4715 CXXCtorInitializer *CXXBaseInit; 4716 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4717 &VBase, IsInheritedVirtualBase, 4718 CXXBaseInit)) { 4719 HadError = true; 4720 continue; 4721 } 4722 4723 Info.AllToInit.push_back(CXXBaseInit); 4724 } 4725 } 4726 4727 // Non-virtual bases. 4728 for (auto &Base : ClassDecl->bases()) { 4729 // Virtuals are in the virtual base list and already constructed. 4730 if (Base.isVirtual()) 4731 continue; 4732 4733 if (CXXCtorInitializer *Value 4734 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 4735 Info.AllToInit.push_back(Value); 4736 } else if (!AnyErrors) { 4737 CXXCtorInitializer *CXXBaseInit; 4738 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 4739 &Base, /*IsInheritedVirtualBase=*/false, 4740 CXXBaseInit)) { 4741 HadError = true; 4742 continue; 4743 } 4744 4745 Info.AllToInit.push_back(CXXBaseInit); 4746 } 4747 } 4748 4749 // Fields. 4750 for (auto *Mem : ClassDecl->decls()) { 4751 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 4752 // C++ [class.bit]p2: 4753 // A declaration for a bit-field that omits the identifier declares an 4754 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 4755 // initialized. 4756 if (F->isUnnamedBitfield()) 4757 continue; 4758 4759 // If we're not generating the implicit copy/move constructor, then we'll 4760 // handle anonymous struct/union fields based on their individual 4761 // indirect fields. 4762 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 4763 continue; 4764 4765 if (CollectFieldInitializer(*this, Info, F)) 4766 HadError = true; 4767 continue; 4768 } 4769 4770 // Beyond this point, we only consider default initialization. 4771 if (Info.isImplicitCopyOrMove()) 4772 continue; 4773 4774 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 4775 if (F->getType()->isIncompleteArrayType()) { 4776 assert(ClassDecl->hasFlexibleArrayMember() && 4777 "Incomplete array type is not valid"); 4778 continue; 4779 } 4780 4781 // Initialize each field of an anonymous struct individually. 4782 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 4783 HadError = true; 4784 4785 continue; 4786 } 4787 } 4788 4789 unsigned NumInitializers = Info.AllToInit.size(); 4790 if (NumInitializers > 0) { 4791 Constructor->setNumCtorInitializers(NumInitializers); 4792 CXXCtorInitializer **baseOrMemberInitializers = 4793 new (Context) CXXCtorInitializer*[NumInitializers]; 4794 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 4795 NumInitializers * sizeof(CXXCtorInitializer*)); 4796 Constructor->setCtorInitializers(baseOrMemberInitializers); 4797 4798 // Constructors implicitly reference the base and member 4799 // destructors. 4800 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 4801 Constructor->getParent()); 4802 } 4803 4804 return HadError; 4805 } 4806 4807 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4808 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4809 const RecordDecl *RD = RT->getDecl(); 4810 if (RD->isAnonymousStructOrUnion()) { 4811 for (auto *Field : RD->fields()) 4812 PopulateKeysForFields(Field, IdealInits); 4813 return; 4814 } 4815 } 4816 IdealInits.push_back(Field->getCanonicalDecl()); 4817 } 4818 4819 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4820 return Context.getCanonicalType(BaseType).getTypePtr(); 4821 } 4822 4823 static const void *GetKeyForMember(ASTContext &Context, 4824 CXXCtorInitializer *Member) { 4825 if (!Member->isAnyMemberInitializer()) 4826 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4827 4828 return Member->getAnyMember()->getCanonicalDecl(); 4829 } 4830 4831 static void DiagnoseBaseOrMemInitializerOrder( 4832 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4833 ArrayRef<CXXCtorInitializer *> Inits) { 4834 if (Constructor->getDeclContext()->isDependentContext()) 4835 return; 4836 4837 // Don't check initializers order unless the warning is enabled at the 4838 // location of at least one initializer. 4839 bool ShouldCheckOrder = false; 4840 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4841 CXXCtorInitializer *Init = Inits[InitIndex]; 4842 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4843 Init->getSourceLocation())) { 4844 ShouldCheckOrder = true; 4845 break; 4846 } 4847 } 4848 if (!ShouldCheckOrder) 4849 return; 4850 4851 // Build the list of bases and members in the order that they'll 4852 // actually be initialized. The explicit initializers should be in 4853 // this same order but may be missing things. 4854 SmallVector<const void*, 32> IdealInitKeys; 4855 4856 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4857 4858 // 1. Virtual bases. 4859 for (const auto &VBase : ClassDecl->vbases()) 4860 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4861 4862 // 2. Non-virtual bases. 4863 for (const auto &Base : ClassDecl->bases()) { 4864 if (Base.isVirtual()) 4865 continue; 4866 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4867 } 4868 4869 // 3. Direct fields. 4870 for (auto *Field : ClassDecl->fields()) { 4871 if (Field->isUnnamedBitfield()) 4872 continue; 4873 4874 PopulateKeysForFields(Field, IdealInitKeys); 4875 } 4876 4877 unsigned NumIdealInits = IdealInitKeys.size(); 4878 unsigned IdealIndex = 0; 4879 4880 CXXCtorInitializer *PrevInit = nullptr; 4881 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4882 CXXCtorInitializer *Init = Inits[InitIndex]; 4883 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4884 4885 // Scan forward to try to find this initializer in the idealized 4886 // initializers list. 4887 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4888 if (InitKey == IdealInitKeys[IdealIndex]) 4889 break; 4890 4891 // If we didn't find this initializer, it must be because we 4892 // scanned past it on a previous iteration. That can only 4893 // happen if we're out of order; emit a warning. 4894 if (IdealIndex == NumIdealInits && PrevInit) { 4895 Sema::SemaDiagnosticBuilder D = 4896 SemaRef.Diag(PrevInit->getSourceLocation(), 4897 diag::warn_initializer_out_of_order); 4898 4899 if (PrevInit->isAnyMemberInitializer()) 4900 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4901 else 4902 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4903 4904 if (Init->isAnyMemberInitializer()) 4905 D << 0 << Init->getAnyMember()->getDeclName(); 4906 else 4907 D << 1 << Init->getTypeSourceInfo()->getType(); 4908 4909 // Move back to the initializer's location in the ideal list. 4910 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4911 if (InitKey == IdealInitKeys[IdealIndex]) 4912 break; 4913 4914 assert(IdealIndex < NumIdealInits && 4915 "initializer not found in initializer list"); 4916 } 4917 4918 PrevInit = Init; 4919 } 4920 } 4921 4922 namespace { 4923 bool CheckRedundantInit(Sema &S, 4924 CXXCtorInitializer *Init, 4925 CXXCtorInitializer *&PrevInit) { 4926 if (!PrevInit) { 4927 PrevInit = Init; 4928 return false; 4929 } 4930 4931 if (FieldDecl *Field = Init->getAnyMember()) 4932 S.Diag(Init->getSourceLocation(), 4933 diag::err_multiple_mem_initialization) 4934 << Field->getDeclName() 4935 << Init->getSourceRange(); 4936 else { 4937 const Type *BaseClass = Init->getBaseClass(); 4938 assert(BaseClass && "neither field nor base"); 4939 S.Diag(Init->getSourceLocation(), 4940 diag::err_multiple_base_initialization) 4941 << QualType(BaseClass, 0) 4942 << Init->getSourceRange(); 4943 } 4944 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4945 << 0 << PrevInit->getSourceRange(); 4946 4947 return true; 4948 } 4949 4950 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4951 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4952 4953 bool CheckRedundantUnionInit(Sema &S, 4954 CXXCtorInitializer *Init, 4955 RedundantUnionMap &Unions) { 4956 FieldDecl *Field = Init->getAnyMember(); 4957 RecordDecl *Parent = Field->getParent(); 4958 NamedDecl *Child = Field; 4959 4960 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4961 if (Parent->isUnion()) { 4962 UnionEntry &En = Unions[Parent]; 4963 if (En.first && En.first != Child) { 4964 S.Diag(Init->getSourceLocation(), 4965 diag::err_multiple_mem_union_initialization) 4966 << Field->getDeclName() 4967 << Init->getSourceRange(); 4968 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4969 << 0 << En.second->getSourceRange(); 4970 return true; 4971 } 4972 if (!En.first) { 4973 En.first = Child; 4974 En.second = Init; 4975 } 4976 if (!Parent->isAnonymousStructOrUnion()) 4977 return false; 4978 } 4979 4980 Child = Parent; 4981 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4982 } 4983 4984 return false; 4985 } 4986 } 4987 4988 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4989 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4990 SourceLocation ColonLoc, 4991 ArrayRef<CXXCtorInitializer*> MemInits, 4992 bool AnyErrors) { 4993 if (!ConstructorDecl) 4994 return; 4995 4996 AdjustDeclIfTemplate(ConstructorDecl); 4997 4998 CXXConstructorDecl *Constructor 4999 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5000 5001 if (!Constructor) { 5002 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5003 return; 5004 } 5005 5006 // Mapping for the duplicate initializers check. 5007 // For member initializers, this is keyed with a FieldDecl*. 5008 // For base initializers, this is keyed with a Type*. 5009 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5010 5011 // Mapping for the inconsistent anonymous-union initializers check. 5012 RedundantUnionMap MemberUnions; 5013 5014 bool HadError = false; 5015 for (unsigned i = 0; i < MemInits.size(); i++) { 5016 CXXCtorInitializer *Init = MemInits[i]; 5017 5018 // Set the source order index. 5019 Init->setSourceOrder(i); 5020 5021 if (Init->isAnyMemberInitializer()) { 5022 const void *Key = GetKeyForMember(Context, Init); 5023 if (CheckRedundantInit(*this, Init, Members[Key]) || 5024 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5025 HadError = true; 5026 } else if (Init->isBaseInitializer()) { 5027 const void *Key = GetKeyForMember(Context, Init); 5028 if (CheckRedundantInit(*this, Init, Members[Key])) 5029 HadError = true; 5030 } else { 5031 assert(Init->isDelegatingInitializer()); 5032 // This must be the only initializer 5033 if (MemInits.size() != 1) { 5034 Diag(Init->getSourceLocation(), 5035 diag::err_delegating_initializer_alone) 5036 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5037 // We will treat this as being the only initializer. 5038 } 5039 SetDelegatingInitializer(Constructor, MemInits[i]); 5040 // Return immediately as the initializer is set. 5041 return; 5042 } 5043 } 5044 5045 if (HadError) 5046 return; 5047 5048 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5049 5050 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5051 5052 DiagnoseUninitializedFields(*this, Constructor); 5053 } 5054 5055 void 5056 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5057 CXXRecordDecl *ClassDecl) { 5058 // Ignore dependent contexts. Also ignore unions, since their members never 5059 // have destructors implicitly called. 5060 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5061 return; 5062 5063 // FIXME: all the access-control diagnostics are positioned on the 5064 // field/base declaration. That's probably good; that said, the 5065 // user might reasonably want to know why the destructor is being 5066 // emitted, and we currently don't say. 5067 5068 // Non-static data members. 5069 for (auto *Field : ClassDecl->fields()) { 5070 if (Field->isInvalidDecl()) 5071 continue; 5072 5073 // Don't destroy incomplete or zero-length arrays. 5074 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5075 continue; 5076 5077 QualType FieldType = Context.getBaseElementType(Field->getType()); 5078 5079 const RecordType* RT = FieldType->getAs<RecordType>(); 5080 if (!RT) 5081 continue; 5082 5083 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5084 if (FieldClassDecl->isInvalidDecl()) 5085 continue; 5086 if (FieldClassDecl->hasIrrelevantDestructor()) 5087 continue; 5088 // The destructor for an implicit anonymous union member is never invoked. 5089 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5090 continue; 5091 5092 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5093 assert(Dtor && "No dtor found for FieldClassDecl!"); 5094 CheckDestructorAccess(Field->getLocation(), Dtor, 5095 PDiag(diag::err_access_dtor_field) 5096 << Field->getDeclName() 5097 << FieldType); 5098 5099 MarkFunctionReferenced(Location, Dtor); 5100 DiagnoseUseOfDecl(Dtor, Location); 5101 } 5102 5103 // We only potentially invoke the destructors of potentially constructed 5104 // subobjects. 5105 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5106 5107 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5108 5109 // Bases. 5110 for (const auto &Base : ClassDecl->bases()) { 5111 // Bases are always records in a well-formed non-dependent class. 5112 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5113 5114 // Remember direct virtual bases. 5115 if (Base.isVirtual()) { 5116 if (!VisitVirtualBases) 5117 continue; 5118 DirectVirtualBases.insert(RT); 5119 } 5120 5121 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5122 // If our base class is invalid, we probably can't get its dtor anyway. 5123 if (BaseClassDecl->isInvalidDecl()) 5124 continue; 5125 if (BaseClassDecl->hasIrrelevantDestructor()) 5126 continue; 5127 5128 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5129 assert(Dtor && "No dtor found for BaseClassDecl!"); 5130 5131 // FIXME: caret should be on the start of the class name 5132 CheckDestructorAccess(Base.getLocStart(), Dtor, 5133 PDiag(diag::err_access_dtor_base) 5134 << Base.getType() 5135 << Base.getSourceRange(), 5136 Context.getTypeDeclType(ClassDecl)); 5137 5138 MarkFunctionReferenced(Location, Dtor); 5139 DiagnoseUseOfDecl(Dtor, Location); 5140 } 5141 5142 if (!VisitVirtualBases) 5143 return; 5144 5145 // Virtual bases. 5146 for (const auto &VBase : ClassDecl->vbases()) { 5147 // Bases are always records in a well-formed non-dependent class. 5148 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5149 5150 // Ignore direct virtual bases. 5151 if (DirectVirtualBases.count(RT)) 5152 continue; 5153 5154 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5155 // If our base class is invalid, we probably can't get its dtor anyway. 5156 if (BaseClassDecl->isInvalidDecl()) 5157 continue; 5158 if (BaseClassDecl->hasIrrelevantDestructor()) 5159 continue; 5160 5161 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5162 assert(Dtor && "No dtor found for BaseClassDecl!"); 5163 if (CheckDestructorAccess( 5164 ClassDecl->getLocation(), Dtor, 5165 PDiag(diag::err_access_dtor_vbase) 5166 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5167 Context.getTypeDeclType(ClassDecl)) == 5168 AR_accessible) { 5169 CheckDerivedToBaseConversion( 5170 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5171 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5172 SourceRange(), DeclarationName(), nullptr); 5173 } 5174 5175 MarkFunctionReferenced(Location, Dtor); 5176 DiagnoseUseOfDecl(Dtor, Location); 5177 } 5178 } 5179 5180 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5181 if (!CDtorDecl) 5182 return; 5183 5184 if (CXXConstructorDecl *Constructor 5185 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5186 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5187 DiagnoseUninitializedFields(*this, Constructor); 5188 } 5189 } 5190 5191 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5192 if (!getLangOpts().CPlusPlus) 5193 return false; 5194 5195 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5196 if (!RD) 5197 return false; 5198 5199 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5200 // class template specialization here, but doing so breaks a lot of code. 5201 5202 // We can't answer whether something is abstract until it has a 5203 // definition. If it's currently being defined, we'll walk back 5204 // over all the declarations when we have a full definition. 5205 const CXXRecordDecl *Def = RD->getDefinition(); 5206 if (!Def || Def->isBeingDefined()) 5207 return false; 5208 5209 return RD->isAbstract(); 5210 } 5211 5212 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5213 TypeDiagnoser &Diagnoser) { 5214 if (!isAbstractType(Loc, T)) 5215 return false; 5216 5217 T = Context.getBaseElementType(T); 5218 Diagnoser.diagnose(*this, Loc, T); 5219 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5220 return true; 5221 } 5222 5223 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5224 // Check if we've already emitted the list of pure virtual functions 5225 // for this class. 5226 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5227 return; 5228 5229 // If the diagnostic is suppressed, don't emit the notes. We're only 5230 // going to emit them once, so try to attach them to a diagnostic we're 5231 // actually going to show. 5232 if (Diags.isLastDiagnosticIgnored()) 5233 return; 5234 5235 CXXFinalOverriderMap FinalOverriders; 5236 RD->getFinalOverriders(FinalOverriders); 5237 5238 // Keep a set of seen pure methods so we won't diagnose the same method 5239 // more than once. 5240 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5241 5242 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5243 MEnd = FinalOverriders.end(); 5244 M != MEnd; 5245 ++M) { 5246 for (OverridingMethods::iterator SO = M->second.begin(), 5247 SOEnd = M->second.end(); 5248 SO != SOEnd; ++SO) { 5249 // C++ [class.abstract]p4: 5250 // A class is abstract if it contains or inherits at least one 5251 // pure virtual function for which the final overrider is pure 5252 // virtual. 5253 5254 // 5255 if (SO->second.size() != 1) 5256 continue; 5257 5258 if (!SO->second.front().Method->isPure()) 5259 continue; 5260 5261 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5262 continue; 5263 5264 Diag(SO->second.front().Method->getLocation(), 5265 diag::note_pure_virtual_function) 5266 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5267 } 5268 } 5269 5270 if (!PureVirtualClassDiagSet) 5271 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5272 PureVirtualClassDiagSet->insert(RD); 5273 } 5274 5275 namespace { 5276 struct AbstractUsageInfo { 5277 Sema &S; 5278 CXXRecordDecl *Record; 5279 CanQualType AbstractType; 5280 bool Invalid; 5281 5282 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5283 : S(S), Record(Record), 5284 AbstractType(S.Context.getCanonicalType( 5285 S.Context.getTypeDeclType(Record))), 5286 Invalid(false) {} 5287 5288 void DiagnoseAbstractType() { 5289 if (Invalid) return; 5290 S.DiagnoseAbstractType(Record); 5291 Invalid = true; 5292 } 5293 5294 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5295 }; 5296 5297 struct CheckAbstractUsage { 5298 AbstractUsageInfo &Info; 5299 const NamedDecl *Ctx; 5300 5301 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5302 : Info(Info), Ctx(Ctx) {} 5303 5304 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5305 switch (TL.getTypeLocClass()) { 5306 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5307 #define TYPELOC(CLASS, PARENT) \ 5308 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5309 #include "clang/AST/TypeLocNodes.def" 5310 } 5311 } 5312 5313 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5314 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5315 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5316 if (!TL.getParam(I)) 5317 continue; 5318 5319 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5320 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5321 } 5322 } 5323 5324 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5325 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5326 } 5327 5328 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5329 // Visit the type parameters from a permissive context. 5330 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5331 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5332 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5333 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5334 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5335 // TODO: other template argument types? 5336 } 5337 } 5338 5339 // Visit pointee types from a permissive context. 5340 #define CheckPolymorphic(Type) \ 5341 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5342 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5343 } 5344 CheckPolymorphic(PointerTypeLoc) 5345 CheckPolymorphic(ReferenceTypeLoc) 5346 CheckPolymorphic(MemberPointerTypeLoc) 5347 CheckPolymorphic(BlockPointerTypeLoc) 5348 CheckPolymorphic(AtomicTypeLoc) 5349 5350 /// Handle all the types we haven't given a more specific 5351 /// implementation for above. 5352 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5353 // Every other kind of type that we haven't called out already 5354 // that has an inner type is either (1) sugar or (2) contains that 5355 // inner type in some way as a subobject. 5356 if (TypeLoc Next = TL.getNextTypeLoc()) 5357 return Visit(Next, Sel); 5358 5359 // If there's no inner type and we're in a permissive context, 5360 // don't diagnose. 5361 if (Sel == Sema::AbstractNone) return; 5362 5363 // Check whether the type matches the abstract type. 5364 QualType T = TL.getType(); 5365 if (T->isArrayType()) { 5366 Sel = Sema::AbstractArrayType; 5367 T = Info.S.Context.getBaseElementType(T); 5368 } 5369 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5370 if (CT != Info.AbstractType) return; 5371 5372 // It matched; do some magic. 5373 if (Sel == Sema::AbstractArrayType) { 5374 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5375 << T << TL.getSourceRange(); 5376 } else { 5377 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5378 << Sel << T << TL.getSourceRange(); 5379 } 5380 Info.DiagnoseAbstractType(); 5381 } 5382 }; 5383 5384 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5385 Sema::AbstractDiagSelID Sel) { 5386 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5387 } 5388 5389 } 5390 5391 /// Check for invalid uses of an abstract type in a method declaration. 5392 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5393 CXXMethodDecl *MD) { 5394 // No need to do the check on definitions, which require that 5395 // the return/param types be complete. 5396 if (MD->doesThisDeclarationHaveABody()) 5397 return; 5398 5399 // For safety's sake, just ignore it if we don't have type source 5400 // information. This should never happen for non-implicit methods, 5401 // but... 5402 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5403 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5404 } 5405 5406 /// Check for invalid uses of an abstract type within a class definition. 5407 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5408 CXXRecordDecl *RD) { 5409 for (auto *D : RD->decls()) { 5410 if (D->isImplicit()) continue; 5411 5412 // Methods and method templates. 5413 if (isa<CXXMethodDecl>(D)) { 5414 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5415 } else if (isa<FunctionTemplateDecl>(D)) { 5416 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5417 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5418 5419 // Fields and static variables. 5420 } else if (isa<FieldDecl>(D)) { 5421 FieldDecl *FD = cast<FieldDecl>(D); 5422 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5423 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5424 } else if (isa<VarDecl>(D)) { 5425 VarDecl *VD = cast<VarDecl>(D); 5426 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5427 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5428 5429 // Nested classes and class templates. 5430 } else if (isa<CXXRecordDecl>(D)) { 5431 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5432 } else if (isa<ClassTemplateDecl>(D)) { 5433 CheckAbstractClassUsage(Info, 5434 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5435 } 5436 } 5437 } 5438 5439 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) { 5440 Attr *ClassAttr = getDLLAttr(Class); 5441 if (!ClassAttr) 5442 return; 5443 5444 assert(ClassAttr->getKind() == attr::DLLExport); 5445 5446 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5447 5448 if (TSK == TSK_ExplicitInstantiationDeclaration) 5449 // Don't go any further if this is just an explicit instantiation 5450 // declaration. 5451 return; 5452 5453 for (Decl *Member : Class->decls()) { 5454 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5455 if (!MD) 5456 continue; 5457 5458 if (Member->getAttr<DLLExportAttr>()) { 5459 if (MD->isUserProvided()) { 5460 // Instantiate non-default class member functions ... 5461 5462 // .. except for certain kinds of template specializations. 5463 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5464 continue; 5465 5466 S.MarkFunctionReferenced(Class->getLocation(), MD); 5467 5468 // The function will be passed to the consumer when its definition is 5469 // encountered. 5470 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5471 MD->isCopyAssignmentOperator() || 5472 MD->isMoveAssignmentOperator()) { 5473 // Synthesize and instantiate non-trivial implicit methods, explicitly 5474 // defaulted methods, and the copy and move assignment operators. The 5475 // latter are exported even if they are trivial, because the address of 5476 // an operator can be taken and should compare equal across libraries. 5477 DiagnosticErrorTrap Trap(S.Diags); 5478 S.MarkFunctionReferenced(Class->getLocation(), MD); 5479 if (Trap.hasErrorOccurred()) { 5480 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5481 << Class->getName() << !S.getLangOpts().CPlusPlus11; 5482 break; 5483 } 5484 5485 // There is no later point when we will see the definition of this 5486 // function, so pass it to the consumer now. 5487 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5488 } 5489 } 5490 } 5491 } 5492 5493 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5494 CXXRecordDecl *Class) { 5495 // Only the MS ABI has default constructor closures, so we don't need to do 5496 // this semantic checking anywhere else. 5497 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5498 return; 5499 5500 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5501 for (Decl *Member : Class->decls()) { 5502 // Look for exported default constructors. 5503 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5504 if (!CD || !CD->isDefaultConstructor()) 5505 continue; 5506 auto *Attr = CD->getAttr<DLLExportAttr>(); 5507 if (!Attr) 5508 continue; 5509 5510 // If the class is non-dependent, mark the default arguments as ODR-used so 5511 // that we can properly codegen the constructor closure. 5512 if (!Class->isDependentContext()) { 5513 for (ParmVarDecl *PD : CD->parameters()) { 5514 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5515 S.DiscardCleanupsInEvaluationContext(); 5516 } 5517 } 5518 5519 if (LastExportedDefaultCtor) { 5520 S.Diag(LastExportedDefaultCtor->getLocation(), 5521 diag::err_attribute_dll_ambiguous_default_ctor) 5522 << Class; 5523 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5524 << CD->getDeclName(); 5525 return; 5526 } 5527 LastExportedDefaultCtor = CD; 5528 } 5529 } 5530 5531 /// \brief Check class-level dllimport/dllexport attribute. 5532 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5533 Attr *ClassAttr = getDLLAttr(Class); 5534 5535 // MSVC inherits DLL attributes to partial class template specializations. 5536 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5537 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5538 if (Attr *TemplateAttr = 5539 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5540 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5541 A->setInherited(true); 5542 ClassAttr = A; 5543 } 5544 } 5545 } 5546 5547 if (!ClassAttr) 5548 return; 5549 5550 if (!Class->isExternallyVisible()) { 5551 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5552 << Class << ClassAttr; 5553 return; 5554 } 5555 5556 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5557 !ClassAttr->isInherited()) { 5558 // Diagnose dll attributes on members of class with dll attribute. 5559 for (Decl *Member : Class->decls()) { 5560 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5561 continue; 5562 InheritableAttr *MemberAttr = getDLLAttr(Member); 5563 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5564 continue; 5565 5566 Diag(MemberAttr->getLocation(), 5567 diag::err_attribute_dll_member_of_dll_class) 5568 << MemberAttr << ClassAttr; 5569 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5570 Member->setInvalidDecl(); 5571 } 5572 } 5573 5574 if (Class->getDescribedClassTemplate()) 5575 // Don't inherit dll attribute until the template is instantiated. 5576 return; 5577 5578 // The class is either imported or exported. 5579 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5580 5581 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5582 5583 // Ignore explicit dllexport on explicit class template instantiation declarations. 5584 if (ClassExported && !ClassAttr->isInherited() && 5585 TSK == TSK_ExplicitInstantiationDeclaration) { 5586 Class->dropAttr<DLLExportAttr>(); 5587 return; 5588 } 5589 5590 // Force declaration of implicit members so they can inherit the attribute. 5591 ForceDeclarationOfImplicitMembers(Class); 5592 5593 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5594 // seem to be true in practice? 5595 5596 for (Decl *Member : Class->decls()) { 5597 VarDecl *VD = dyn_cast<VarDecl>(Member); 5598 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5599 5600 // Only methods and static fields inherit the attributes. 5601 if (!VD && !MD) 5602 continue; 5603 5604 if (MD) { 5605 // Don't process deleted methods. 5606 if (MD->isDeleted()) 5607 continue; 5608 5609 if (MD->isInlined()) { 5610 // MinGW does not import or export inline methods. 5611 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5612 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) 5613 continue; 5614 5615 // MSVC versions before 2015 don't export the move assignment operators 5616 // and move constructor, so don't attempt to import/export them if 5617 // we have a definition. 5618 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5619 if ((MD->isMoveAssignmentOperator() || 5620 (Ctor && Ctor->isMoveConstructor())) && 5621 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5622 continue; 5623 5624 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5625 // operator is exported anyway. 5626 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5627 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5628 continue; 5629 } 5630 } 5631 5632 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5633 continue; 5634 5635 if (!getDLLAttr(Member)) { 5636 auto *NewAttr = 5637 cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5638 NewAttr->setInherited(true); 5639 Member->addAttr(NewAttr); 5640 } 5641 } 5642 5643 if (ClassExported) 5644 DelayedDllExportClasses.push_back(Class); 5645 } 5646 5647 /// \brief Perform propagation of DLL attributes from a derived class to a 5648 /// templated base class for MS compatibility. 5649 void Sema::propagateDLLAttrToBaseClassTemplate( 5650 CXXRecordDecl *Class, Attr *ClassAttr, 5651 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 5652 if (getDLLAttr( 5653 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 5654 // If the base class template has a DLL attribute, don't try to change it. 5655 return; 5656 } 5657 5658 auto TSK = BaseTemplateSpec->getSpecializationKind(); 5659 if (!getDLLAttr(BaseTemplateSpec) && 5660 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 5661 TSK == TSK_ImplicitInstantiation)) { 5662 // The template hasn't been instantiated yet (or it has, but only as an 5663 // explicit instantiation declaration or implicit instantiation, which means 5664 // we haven't codegenned any members yet), so propagate the attribute. 5665 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5666 NewAttr->setInherited(true); 5667 BaseTemplateSpec->addAttr(NewAttr); 5668 5669 // If the template is already instantiated, checkDLLAttributeRedeclaration() 5670 // needs to be run again to work see the new attribute. Otherwise this will 5671 // get run whenever the template is instantiated. 5672 if (TSK != TSK_Undeclared) 5673 checkClassLevelDLLAttribute(BaseTemplateSpec); 5674 5675 return; 5676 } 5677 5678 if (getDLLAttr(BaseTemplateSpec)) { 5679 // The template has already been specialized or instantiated with an 5680 // attribute, explicitly or through propagation. We should not try to change 5681 // it. 5682 return; 5683 } 5684 5685 // The template was previously instantiated or explicitly specialized without 5686 // a dll attribute, It's too late for us to add an attribute, so warn that 5687 // this is unsupported. 5688 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 5689 << BaseTemplateSpec->isExplicitSpecialization(); 5690 Diag(ClassAttr->getLocation(), diag::note_attribute); 5691 if (BaseTemplateSpec->isExplicitSpecialization()) { 5692 Diag(BaseTemplateSpec->getLocation(), 5693 diag::note_template_class_explicit_specialization_was_here) 5694 << BaseTemplateSpec; 5695 } else { 5696 Diag(BaseTemplateSpec->getPointOfInstantiation(), 5697 diag::note_template_class_instantiation_was_here) 5698 << BaseTemplateSpec; 5699 } 5700 } 5701 5702 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 5703 SourceLocation DefaultLoc) { 5704 switch (S.getSpecialMember(MD)) { 5705 case Sema::CXXDefaultConstructor: 5706 S.DefineImplicitDefaultConstructor(DefaultLoc, 5707 cast<CXXConstructorDecl>(MD)); 5708 break; 5709 case Sema::CXXCopyConstructor: 5710 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5711 break; 5712 case Sema::CXXCopyAssignment: 5713 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 5714 break; 5715 case Sema::CXXDestructor: 5716 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 5717 break; 5718 case Sema::CXXMoveConstructor: 5719 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 5720 break; 5721 case Sema::CXXMoveAssignment: 5722 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 5723 break; 5724 case Sema::CXXInvalid: 5725 llvm_unreachable("Invalid special member."); 5726 } 5727 } 5728 5729 /// Determine whether a type is permitted to be passed or returned in 5730 /// registers, per C++ [class.temporary]p3. 5731 static bool computeCanPassInRegisters(Sema &S, CXXRecordDecl *D) { 5732 if (D->isDependentType() || D->isInvalidDecl()) 5733 return false; 5734 5735 // Per C++ [class.temporary]p3, the relevant condition is: 5736 // each copy constructor, move constructor, and destructor of X is 5737 // either trivial or deleted, and X has at least one non-deleted copy 5738 // or move constructor 5739 bool HasNonDeletedCopyOrMove = false; 5740 5741 if (D->needsImplicitCopyConstructor() && 5742 !D->defaultedCopyConstructorIsDeleted()) { 5743 if (!D->hasTrivialCopyConstructor()) 5744 return false; 5745 HasNonDeletedCopyOrMove = true; 5746 } 5747 5748 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 5749 !D->defaultedMoveConstructorIsDeleted()) { 5750 if (!D->hasTrivialMoveConstructor()) 5751 return false; 5752 HasNonDeletedCopyOrMove = true; 5753 } 5754 5755 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 5756 !D->hasTrivialDestructor()) 5757 return false; 5758 5759 for (const CXXMethodDecl *MD : D->methods()) { 5760 if (MD->isDeleted()) 5761 continue; 5762 5763 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 5764 if (CD && CD->isCopyOrMoveConstructor()) 5765 HasNonDeletedCopyOrMove = true; 5766 else if (!isa<CXXDestructorDecl>(MD)) 5767 continue; 5768 5769 if (!MD->isTrivial()) 5770 return false; 5771 } 5772 5773 return HasNonDeletedCopyOrMove; 5774 } 5775 5776 /// \brief Perform semantic checks on a class definition that has been 5777 /// completing, introducing implicitly-declared members, checking for 5778 /// abstract types, etc. 5779 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 5780 if (!Record) 5781 return; 5782 5783 if (Record->isAbstract() && !Record->isInvalidDecl()) { 5784 AbstractUsageInfo Info(*this, Record); 5785 CheckAbstractClassUsage(Info, Record); 5786 } 5787 5788 // If this is not an aggregate type and has no user-declared constructor, 5789 // complain about any non-static data members of reference or const scalar 5790 // type, since they will never get initializers. 5791 if (!Record->isInvalidDecl() && !Record->isDependentType() && 5792 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 5793 !Record->isLambda()) { 5794 bool Complained = false; 5795 for (const auto *F : Record->fields()) { 5796 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 5797 continue; 5798 5799 if (F->getType()->isReferenceType() || 5800 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 5801 if (!Complained) { 5802 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 5803 << Record->getTagKind() << Record; 5804 Complained = true; 5805 } 5806 5807 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 5808 << F->getType()->isReferenceType() 5809 << F->getDeclName(); 5810 } 5811 } 5812 } 5813 5814 if (Record->getIdentifier()) { 5815 // C++ [class.mem]p13: 5816 // If T is the name of a class, then each of the following shall have a 5817 // name different from T: 5818 // - every member of every anonymous union that is a member of class T. 5819 // 5820 // C++ [class.mem]p14: 5821 // In addition, if class T has a user-declared constructor (12.1), every 5822 // non-static data member of class T shall have a name different from T. 5823 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 5824 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 5825 ++I) { 5826 NamedDecl *D = *I; 5827 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 5828 isa<IndirectFieldDecl>(D)) { 5829 Diag(D->getLocation(), diag::err_member_name_of_class) 5830 << D->getDeclName(); 5831 break; 5832 } 5833 } 5834 } 5835 5836 // Warn if the class has virtual methods but non-virtual public destructor. 5837 if (Record->isPolymorphic() && !Record->isDependentType()) { 5838 CXXDestructorDecl *dtor = Record->getDestructor(); 5839 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 5840 !Record->hasAttr<FinalAttr>()) 5841 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 5842 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 5843 } 5844 5845 if (Record->isAbstract()) { 5846 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 5847 Diag(Record->getLocation(), diag::warn_abstract_final_class) 5848 << FA->isSpelledAsSealed(); 5849 DiagnoseAbstractType(Record); 5850 } 5851 } 5852 5853 bool HasMethodWithOverrideControl = false, 5854 HasOverridingMethodWithoutOverrideControl = false; 5855 if (!Record->isDependentType()) { 5856 for (auto *M : Record->methods()) { 5857 // See if a method overloads virtual methods in a base 5858 // class without overriding any. 5859 if (!M->isStatic()) 5860 DiagnoseHiddenVirtualMethods(M); 5861 if (M->hasAttr<OverrideAttr>()) 5862 HasMethodWithOverrideControl = true; 5863 else if (M->size_overridden_methods() > 0) 5864 HasOverridingMethodWithoutOverrideControl = true; 5865 // Check whether the explicitly-defaulted special members are valid. 5866 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 5867 CheckExplicitlyDefaultedSpecialMember(M); 5868 5869 // For an explicitly defaulted or deleted special member, we defer 5870 // determining triviality until the class is complete. That time is now! 5871 CXXSpecialMember CSM = getSpecialMember(M); 5872 if (!M->isImplicit() && !M->isUserProvided()) { 5873 if (CSM != CXXInvalid) { 5874 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 5875 5876 // Inform the class that we've finished declaring this member. 5877 Record->finishedDefaultedOrDeletedMember(M); 5878 } 5879 } 5880 5881 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 5882 M->hasAttr<DLLExportAttr>()) { 5883 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5884 M->isTrivial() && 5885 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 5886 CSM == CXXDestructor)) 5887 M->dropAttr<DLLExportAttr>(); 5888 5889 if (M->hasAttr<DLLExportAttr>()) { 5890 DefineImplicitSpecialMember(*this, M, M->getLocation()); 5891 ActOnFinishInlineFunctionDef(M); 5892 } 5893 } 5894 } 5895 } 5896 5897 if (HasMethodWithOverrideControl && 5898 HasOverridingMethodWithoutOverrideControl) { 5899 // At least one method has the 'override' control declared. 5900 // Diagnose all other overridden methods which do not have 'override' specified on them. 5901 for (auto *M : Record->methods()) 5902 DiagnoseAbsenceOfOverrideControl(M); 5903 } 5904 5905 // ms_struct is a request to use the same ABI rules as MSVC. Check 5906 // whether this class uses any C++ features that are implemented 5907 // completely differently in MSVC, and if so, emit a diagnostic. 5908 // That diagnostic defaults to an error, but we allow projects to 5909 // map it down to a warning (or ignore it). It's a fairly common 5910 // practice among users of the ms_struct pragma to mass-annotate 5911 // headers, sweeping up a bunch of types that the project doesn't 5912 // really rely on MSVC-compatible layout for. We must therefore 5913 // support "ms_struct except for C++ stuff" as a secondary ABI. 5914 if (Record->isMsStruct(Context) && 5915 (Record->isPolymorphic() || Record->getNumBases())) { 5916 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 5917 } 5918 5919 checkClassLevelDLLAttribute(Record); 5920 5921 Record->setCanPassInRegisters(computeCanPassInRegisters(*this, Record)); 5922 } 5923 5924 /// Look up the special member function that would be called by a special 5925 /// member function for a subobject of class type. 5926 /// 5927 /// \param Class The class type of the subobject. 5928 /// \param CSM The kind of special member function. 5929 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 5930 /// \param ConstRHS True if this is a copy operation with a const object 5931 /// on its RHS, that is, if the argument to the outer special member 5932 /// function is 'const' and this is not a field marked 'mutable'. 5933 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 5934 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 5935 unsigned FieldQuals, bool ConstRHS) { 5936 unsigned LHSQuals = 0; 5937 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 5938 LHSQuals = FieldQuals; 5939 5940 unsigned RHSQuals = FieldQuals; 5941 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 5942 RHSQuals = 0; 5943 else if (ConstRHS) 5944 RHSQuals |= Qualifiers::Const; 5945 5946 return S.LookupSpecialMember(Class, CSM, 5947 RHSQuals & Qualifiers::Const, 5948 RHSQuals & Qualifiers::Volatile, 5949 false, 5950 LHSQuals & Qualifiers::Const, 5951 LHSQuals & Qualifiers::Volatile); 5952 } 5953 5954 class Sema::InheritedConstructorInfo { 5955 Sema &S; 5956 SourceLocation UseLoc; 5957 5958 /// A mapping from the base classes through which the constructor was 5959 /// inherited to the using shadow declaration in that base class (or a null 5960 /// pointer if the constructor was declared in that base class). 5961 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 5962 InheritedFromBases; 5963 5964 public: 5965 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 5966 ConstructorUsingShadowDecl *Shadow) 5967 : S(S), UseLoc(UseLoc) { 5968 bool DiagnosedMultipleConstructedBases = false; 5969 CXXRecordDecl *ConstructedBase = nullptr; 5970 UsingDecl *ConstructedBaseUsing = nullptr; 5971 5972 // Find the set of such base class subobjects and check that there's a 5973 // unique constructed subobject. 5974 for (auto *D : Shadow->redecls()) { 5975 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 5976 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 5977 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 5978 5979 InheritedFromBases.insert( 5980 std::make_pair(DNominatedBase->getCanonicalDecl(), 5981 DShadow->getNominatedBaseClassShadowDecl())); 5982 if (DShadow->constructsVirtualBase()) 5983 InheritedFromBases.insert( 5984 std::make_pair(DConstructedBase->getCanonicalDecl(), 5985 DShadow->getConstructedBaseClassShadowDecl())); 5986 else 5987 assert(DNominatedBase == DConstructedBase); 5988 5989 // [class.inhctor.init]p2: 5990 // If the constructor was inherited from multiple base class subobjects 5991 // of type B, the program is ill-formed. 5992 if (!ConstructedBase) { 5993 ConstructedBase = DConstructedBase; 5994 ConstructedBaseUsing = D->getUsingDecl(); 5995 } else if (ConstructedBase != DConstructedBase && 5996 !Shadow->isInvalidDecl()) { 5997 if (!DiagnosedMultipleConstructedBases) { 5998 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 5999 << Shadow->getTargetDecl(); 6000 S.Diag(ConstructedBaseUsing->getLocation(), 6001 diag::note_ambiguous_inherited_constructor_using) 6002 << ConstructedBase; 6003 DiagnosedMultipleConstructedBases = true; 6004 } 6005 S.Diag(D->getUsingDecl()->getLocation(), 6006 diag::note_ambiguous_inherited_constructor_using) 6007 << DConstructedBase; 6008 } 6009 } 6010 6011 if (DiagnosedMultipleConstructedBases) 6012 Shadow->setInvalidDecl(); 6013 } 6014 6015 /// Find the constructor to use for inherited construction of a base class, 6016 /// and whether that base class constructor inherits the constructor from a 6017 /// virtual base class (in which case it won't actually invoke it). 6018 std::pair<CXXConstructorDecl *, bool> 6019 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6020 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6021 if (It == InheritedFromBases.end()) 6022 return std::make_pair(nullptr, false); 6023 6024 // This is an intermediary class. 6025 if (It->second) 6026 return std::make_pair( 6027 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6028 It->second->constructsVirtualBase()); 6029 6030 // This is the base class from which the constructor was inherited. 6031 return std::make_pair(Ctor, false); 6032 } 6033 }; 6034 6035 /// Is the special member function which would be selected to perform the 6036 /// specified operation on the specified class type a constexpr constructor? 6037 static bool 6038 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6039 Sema::CXXSpecialMember CSM, unsigned Quals, 6040 bool ConstRHS, 6041 CXXConstructorDecl *InheritedCtor = nullptr, 6042 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6043 // If we're inheriting a constructor, see if we need to call it for this base 6044 // class. 6045 if (InheritedCtor) { 6046 assert(CSM == Sema::CXXDefaultConstructor); 6047 auto BaseCtor = 6048 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6049 if (BaseCtor) 6050 return BaseCtor->isConstexpr(); 6051 } 6052 6053 if (CSM == Sema::CXXDefaultConstructor) 6054 return ClassDecl->hasConstexprDefaultConstructor(); 6055 6056 Sema::SpecialMemberOverloadResult SMOR = 6057 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6058 if (!SMOR.getMethod()) 6059 // A constructor we wouldn't select can't be "involved in initializing" 6060 // anything. 6061 return true; 6062 return SMOR.getMethod()->isConstexpr(); 6063 } 6064 6065 /// Determine whether the specified special member function would be constexpr 6066 /// if it were implicitly defined. 6067 static bool defaultedSpecialMemberIsConstexpr( 6068 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6069 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6070 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6071 if (!S.getLangOpts().CPlusPlus11) 6072 return false; 6073 6074 // C++11 [dcl.constexpr]p4: 6075 // In the definition of a constexpr constructor [...] 6076 bool Ctor = true; 6077 switch (CSM) { 6078 case Sema::CXXDefaultConstructor: 6079 if (Inherited) 6080 break; 6081 // Since default constructor lookup is essentially trivial (and cannot 6082 // involve, for instance, template instantiation), we compute whether a 6083 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6084 // 6085 // This is important for performance; we need to know whether the default 6086 // constructor is constexpr to determine whether the type is a literal type. 6087 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6088 6089 case Sema::CXXCopyConstructor: 6090 case Sema::CXXMoveConstructor: 6091 // For copy or move constructors, we need to perform overload resolution. 6092 break; 6093 6094 case Sema::CXXCopyAssignment: 6095 case Sema::CXXMoveAssignment: 6096 if (!S.getLangOpts().CPlusPlus14) 6097 return false; 6098 // In C++1y, we need to perform overload resolution. 6099 Ctor = false; 6100 break; 6101 6102 case Sema::CXXDestructor: 6103 case Sema::CXXInvalid: 6104 return false; 6105 } 6106 6107 // -- if the class is a non-empty union, or for each non-empty anonymous 6108 // union member of a non-union class, exactly one non-static data member 6109 // shall be initialized; [DR1359] 6110 // 6111 // If we squint, this is guaranteed, since exactly one non-static data member 6112 // will be initialized (if the constructor isn't deleted), we just don't know 6113 // which one. 6114 if (Ctor && ClassDecl->isUnion()) 6115 return CSM == Sema::CXXDefaultConstructor 6116 ? ClassDecl->hasInClassInitializer() || 6117 !ClassDecl->hasVariantMembers() 6118 : true; 6119 6120 // -- the class shall not have any virtual base classes; 6121 if (Ctor && ClassDecl->getNumVBases()) 6122 return false; 6123 6124 // C++1y [class.copy]p26: 6125 // -- [the class] is a literal type, and 6126 if (!Ctor && !ClassDecl->isLiteral()) 6127 return false; 6128 6129 // -- every constructor involved in initializing [...] base class 6130 // sub-objects shall be a constexpr constructor; 6131 // -- the assignment operator selected to copy/move each direct base 6132 // class is a constexpr function, and 6133 for (const auto &B : ClassDecl->bases()) { 6134 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6135 if (!BaseType) continue; 6136 6137 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6138 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6139 InheritedCtor, Inherited)) 6140 return false; 6141 } 6142 6143 // -- every constructor involved in initializing non-static data members 6144 // [...] shall be a constexpr constructor; 6145 // -- every non-static data member and base class sub-object shall be 6146 // initialized 6147 // -- for each non-static data member of X that is of class type (or array 6148 // thereof), the assignment operator selected to copy/move that member is 6149 // a constexpr function 6150 for (const auto *F : ClassDecl->fields()) { 6151 if (F->isInvalidDecl()) 6152 continue; 6153 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6154 continue; 6155 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6156 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6157 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6158 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6159 BaseType.getCVRQualifiers(), 6160 ConstArg && !F->isMutable())) 6161 return false; 6162 } else if (CSM == Sema::CXXDefaultConstructor) { 6163 return false; 6164 } 6165 } 6166 6167 // All OK, it's constexpr! 6168 return true; 6169 } 6170 6171 static Sema::ImplicitExceptionSpecification 6172 ComputeDefaultedSpecialMemberExceptionSpec( 6173 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6174 Sema::InheritedConstructorInfo *ICI); 6175 6176 static Sema::ImplicitExceptionSpecification 6177 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6178 auto CSM = S.getSpecialMember(MD); 6179 if (CSM != Sema::CXXInvalid) 6180 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6181 6182 auto *CD = cast<CXXConstructorDecl>(MD); 6183 assert(CD->getInheritedConstructor() && 6184 "only special members have implicit exception specs"); 6185 Sema::InheritedConstructorInfo ICI( 6186 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6187 return ComputeDefaultedSpecialMemberExceptionSpec( 6188 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6189 } 6190 6191 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6192 CXXMethodDecl *MD) { 6193 FunctionProtoType::ExtProtoInfo EPI; 6194 6195 // Build an exception specification pointing back at this member. 6196 EPI.ExceptionSpec.Type = EST_Unevaluated; 6197 EPI.ExceptionSpec.SourceDecl = MD; 6198 6199 // Set the calling convention to the default for C++ instance methods. 6200 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6201 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6202 /*IsCXXMethod=*/true)); 6203 return EPI; 6204 } 6205 6206 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6207 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6208 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6209 return; 6210 6211 // Evaluate the exception specification. 6212 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6213 auto ESI = IES.getExceptionSpec(); 6214 6215 // Update the type of the special member to use it. 6216 UpdateExceptionSpec(MD, ESI); 6217 6218 // A user-provided destructor can be defined outside the class. When that 6219 // happens, be sure to update the exception specification on both 6220 // declarations. 6221 const FunctionProtoType *CanonicalFPT = 6222 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6223 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6224 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6225 } 6226 6227 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6228 CXXRecordDecl *RD = MD->getParent(); 6229 CXXSpecialMember CSM = getSpecialMember(MD); 6230 6231 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6232 "not an explicitly-defaulted special member"); 6233 6234 // Whether this was the first-declared instance of the constructor. 6235 // This affects whether we implicitly add an exception spec and constexpr. 6236 bool First = MD == MD->getCanonicalDecl(); 6237 6238 bool HadError = false; 6239 6240 // C++11 [dcl.fct.def.default]p1: 6241 // A function that is explicitly defaulted shall 6242 // -- be a special member function (checked elsewhere), 6243 // -- have the same type (except for ref-qualifiers, and except that a 6244 // copy operation can take a non-const reference) as an implicit 6245 // declaration, and 6246 // -- not have default arguments. 6247 unsigned ExpectedParams = 1; 6248 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6249 ExpectedParams = 0; 6250 if (MD->getNumParams() != ExpectedParams) { 6251 // This also checks for default arguments: a copy or move constructor with a 6252 // default argument is classified as a default constructor, and assignment 6253 // operations and destructors can't have default arguments. 6254 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6255 << CSM << MD->getSourceRange(); 6256 HadError = true; 6257 } else if (MD->isVariadic()) { 6258 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6259 << CSM << MD->getSourceRange(); 6260 HadError = true; 6261 } 6262 6263 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6264 6265 bool CanHaveConstParam = false; 6266 if (CSM == CXXCopyConstructor) 6267 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6268 else if (CSM == CXXCopyAssignment) 6269 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6270 6271 QualType ReturnType = Context.VoidTy; 6272 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6273 // Check for return type matching. 6274 ReturnType = Type->getReturnType(); 6275 QualType ExpectedReturnType = 6276 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 6277 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6278 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6279 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6280 HadError = true; 6281 } 6282 6283 // A defaulted special member cannot have cv-qualifiers. 6284 if (Type->getTypeQuals()) { 6285 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6286 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6287 HadError = true; 6288 } 6289 } 6290 6291 // Check for parameter type matching. 6292 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6293 bool HasConstParam = false; 6294 if (ExpectedParams && ArgType->isReferenceType()) { 6295 // Argument must be reference to possibly-const T. 6296 QualType ReferentType = ArgType->getPointeeType(); 6297 HasConstParam = ReferentType.isConstQualified(); 6298 6299 if (ReferentType.isVolatileQualified()) { 6300 Diag(MD->getLocation(), 6301 diag::err_defaulted_special_member_volatile_param) << CSM; 6302 HadError = true; 6303 } 6304 6305 if (HasConstParam && !CanHaveConstParam) { 6306 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6307 Diag(MD->getLocation(), 6308 diag::err_defaulted_special_member_copy_const_param) 6309 << (CSM == CXXCopyAssignment); 6310 // FIXME: Explain why this special member can't be const. 6311 } else { 6312 Diag(MD->getLocation(), 6313 diag::err_defaulted_special_member_move_const_param) 6314 << (CSM == CXXMoveAssignment); 6315 } 6316 HadError = true; 6317 } 6318 } else if (ExpectedParams) { 6319 // A copy assignment operator can take its argument by value, but a 6320 // defaulted one cannot. 6321 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6322 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6323 HadError = true; 6324 } 6325 6326 // C++11 [dcl.fct.def.default]p2: 6327 // An explicitly-defaulted function may be declared constexpr only if it 6328 // would have been implicitly declared as constexpr, 6329 // Do not apply this rule to members of class templates, since core issue 1358 6330 // makes such functions always instantiate to constexpr functions. For 6331 // functions which cannot be constexpr (for non-constructors in C++11 and for 6332 // destructors in C++1y), this is checked elsewhere. 6333 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6334 HasConstParam); 6335 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6336 : isa<CXXConstructorDecl>(MD)) && 6337 MD->isConstexpr() && !Constexpr && 6338 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6339 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 6340 // FIXME: Explain why the special member can't be constexpr. 6341 HadError = true; 6342 } 6343 6344 // and may have an explicit exception-specification only if it is compatible 6345 // with the exception-specification on the implicit declaration. 6346 if (Type->hasExceptionSpec()) { 6347 // Delay the check if this is the first declaration of the special member, 6348 // since we may not have parsed some necessary in-class initializers yet. 6349 if (First) { 6350 // If the exception specification needs to be instantiated, do so now, 6351 // before we clobber it with an EST_Unevaluated specification below. 6352 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 6353 InstantiateExceptionSpec(MD->getLocStart(), MD); 6354 Type = MD->getType()->getAs<FunctionProtoType>(); 6355 } 6356 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 6357 } else 6358 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 6359 } 6360 6361 // If a function is explicitly defaulted on its first declaration, 6362 if (First) { 6363 // -- it is implicitly considered to be constexpr if the implicit 6364 // definition would be, 6365 MD->setConstexpr(Constexpr); 6366 6367 // -- it is implicitly considered to have the same exception-specification 6368 // as if it had been implicitly declared, 6369 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6370 EPI.ExceptionSpec.Type = EST_Unevaluated; 6371 EPI.ExceptionSpec.SourceDecl = MD; 6372 MD->setType(Context.getFunctionType(ReturnType, 6373 llvm::makeArrayRef(&ArgType, 6374 ExpectedParams), 6375 EPI)); 6376 } 6377 6378 if (ShouldDeleteSpecialMember(MD, CSM)) { 6379 if (First) { 6380 SetDeclDeleted(MD, MD->getLocation()); 6381 } else { 6382 // C++11 [dcl.fct.def.default]p4: 6383 // [For a] user-provided explicitly-defaulted function [...] if such a 6384 // function is implicitly defined as deleted, the program is ill-formed. 6385 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6386 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6387 HadError = true; 6388 } 6389 } 6390 6391 if (HadError) 6392 MD->setInvalidDecl(); 6393 } 6394 6395 /// Check whether the exception specification provided for an 6396 /// explicitly-defaulted special member matches the exception specification 6397 /// that would have been generated for an implicit special member, per 6398 /// C++11 [dcl.fct.def.default]p2. 6399 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 6400 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 6401 // If the exception specification was explicitly specified but hadn't been 6402 // parsed when the method was defaulted, grab it now. 6403 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 6404 SpecifiedType = 6405 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 6406 6407 // Compute the implicit exception specification. 6408 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6409 /*IsCXXMethod=*/true); 6410 FunctionProtoType::ExtProtoInfo EPI(CC); 6411 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD); 6412 EPI.ExceptionSpec = IES.getExceptionSpec(); 6413 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 6414 Context.getFunctionType(Context.VoidTy, None, EPI)); 6415 6416 // Ensure that it matches. 6417 CheckEquivalentExceptionSpec( 6418 PDiag(diag::err_incorrect_defaulted_exception_spec) 6419 << getSpecialMember(MD), PDiag(), 6420 ImplicitType, SourceLocation(), 6421 SpecifiedType, MD->getLocation()); 6422 } 6423 6424 void Sema::CheckDelayedMemberExceptionSpecs() { 6425 decltype(DelayedExceptionSpecChecks) Checks; 6426 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 6427 6428 std::swap(Checks, DelayedExceptionSpecChecks); 6429 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 6430 6431 // Perform any deferred checking of exception specifications for virtual 6432 // destructors. 6433 for (auto &Check : Checks) 6434 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6435 6436 // Check that any explicitly-defaulted methods have exception specifications 6437 // compatible with their implicit exception specifications. 6438 for (auto &Spec : Specs) 6439 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 6440 } 6441 6442 namespace { 6443 /// CRTP base class for visiting operations performed by a special member 6444 /// function (or inherited constructor). 6445 template<typename Derived> 6446 struct SpecialMemberVisitor { 6447 Sema &S; 6448 CXXMethodDecl *MD; 6449 Sema::CXXSpecialMember CSM; 6450 Sema::InheritedConstructorInfo *ICI; 6451 6452 // Properties of the special member, computed for convenience. 6453 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6454 6455 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6456 Sema::InheritedConstructorInfo *ICI) 6457 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6458 switch (CSM) { 6459 case Sema::CXXDefaultConstructor: 6460 case Sema::CXXCopyConstructor: 6461 case Sema::CXXMoveConstructor: 6462 IsConstructor = true; 6463 break; 6464 case Sema::CXXCopyAssignment: 6465 case Sema::CXXMoveAssignment: 6466 IsAssignment = true; 6467 break; 6468 case Sema::CXXDestructor: 6469 break; 6470 case Sema::CXXInvalid: 6471 llvm_unreachable("invalid special member kind"); 6472 } 6473 6474 if (MD->getNumParams()) { 6475 if (const ReferenceType *RT = 6476 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 6477 ConstArg = RT->getPointeeType().isConstQualified(); 6478 } 6479 } 6480 6481 Derived &getDerived() { return static_cast<Derived&>(*this); } 6482 6483 /// Is this a "move" special member? 6484 bool isMove() const { 6485 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 6486 } 6487 6488 /// Look up the corresponding special member in the given class. 6489 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 6490 unsigned Quals, bool IsMutable) { 6491 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 6492 ConstArg && !IsMutable); 6493 } 6494 6495 /// Look up the constructor for the specified base class to see if it's 6496 /// overridden due to this being an inherited constructor. 6497 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 6498 if (!ICI) 6499 return {}; 6500 assert(CSM == Sema::CXXDefaultConstructor); 6501 auto *BaseCtor = 6502 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 6503 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 6504 return MD; 6505 return {}; 6506 } 6507 6508 /// A base or member subobject. 6509 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 6510 6511 /// Get the location to use for a subobject in diagnostics. 6512 static SourceLocation getSubobjectLoc(Subobject Subobj) { 6513 // FIXME: For an indirect virtual base, the direct base leading to 6514 // the indirect virtual base would be a more useful choice. 6515 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 6516 return B->getBaseTypeLoc(); 6517 else 6518 return Subobj.get<FieldDecl*>()->getLocation(); 6519 } 6520 6521 enum BasesToVisit { 6522 /// Visit all non-virtual (direct) bases. 6523 VisitNonVirtualBases, 6524 /// Visit all direct bases, virtual or not. 6525 VisitDirectBases, 6526 /// Visit all non-virtual bases, and all virtual bases if the class 6527 /// is not abstract. 6528 VisitPotentiallyConstructedBases, 6529 /// Visit all direct or virtual bases. 6530 VisitAllBases 6531 }; 6532 6533 // Visit the bases and members of the class. 6534 bool visit(BasesToVisit Bases) { 6535 CXXRecordDecl *RD = MD->getParent(); 6536 6537 if (Bases == VisitPotentiallyConstructedBases) 6538 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 6539 6540 for (auto &B : RD->bases()) 6541 if ((Bases == VisitDirectBases || !B.isVirtual()) && 6542 getDerived().visitBase(&B)) 6543 return true; 6544 6545 if (Bases == VisitAllBases) 6546 for (auto &B : RD->vbases()) 6547 if (getDerived().visitBase(&B)) 6548 return true; 6549 6550 for (auto *F : RD->fields()) 6551 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 6552 getDerived().visitField(F)) 6553 return true; 6554 6555 return false; 6556 } 6557 }; 6558 } 6559 6560 namespace { 6561 struct SpecialMemberDeletionInfo 6562 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 6563 bool Diagnose; 6564 6565 SourceLocation Loc; 6566 6567 bool AllFieldsAreConst; 6568 6569 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 6570 Sema::CXXSpecialMember CSM, 6571 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 6572 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 6573 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 6574 6575 bool inUnion() const { return MD->getParent()->isUnion(); } 6576 6577 Sema::CXXSpecialMember getEffectiveCSM() { 6578 return ICI ? Sema::CXXInvalid : CSM; 6579 } 6580 6581 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 6582 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 6583 6584 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 6585 bool shouldDeleteForField(FieldDecl *FD); 6586 bool shouldDeleteForAllConstMembers(); 6587 6588 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 6589 unsigned Quals); 6590 bool shouldDeleteForSubobjectCall(Subobject Subobj, 6591 Sema::SpecialMemberOverloadResult SMOR, 6592 bool IsDtorCallInCtor); 6593 6594 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 6595 }; 6596 } 6597 6598 /// Is the given special member inaccessible when used on the given 6599 /// sub-object. 6600 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 6601 CXXMethodDecl *target) { 6602 /// If we're operating on a base class, the object type is the 6603 /// type of this special member. 6604 QualType objectTy; 6605 AccessSpecifier access = target->getAccess(); 6606 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 6607 objectTy = S.Context.getTypeDeclType(MD->getParent()); 6608 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 6609 6610 // If we're operating on a field, the object type is the type of the field. 6611 } else { 6612 objectTy = S.Context.getTypeDeclType(target->getParent()); 6613 } 6614 6615 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 6616 } 6617 6618 /// Check whether we should delete a special member due to the implicit 6619 /// definition containing a call to a special member of a subobject. 6620 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 6621 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 6622 bool IsDtorCallInCtor) { 6623 CXXMethodDecl *Decl = SMOR.getMethod(); 6624 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6625 6626 int DiagKind = -1; 6627 6628 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 6629 DiagKind = !Decl ? 0 : 1; 6630 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 6631 DiagKind = 2; 6632 else if (!isAccessible(Subobj, Decl)) 6633 DiagKind = 3; 6634 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 6635 !Decl->isTrivial()) { 6636 // A member of a union must have a trivial corresponding special member. 6637 // As a weird special case, a destructor call from a union's constructor 6638 // must be accessible and non-deleted, but need not be trivial. Such a 6639 // destructor is never actually called, but is semantically checked as 6640 // if it were. 6641 DiagKind = 4; 6642 } 6643 6644 if (DiagKind == -1) 6645 return false; 6646 6647 if (Diagnose) { 6648 if (Field) { 6649 S.Diag(Field->getLocation(), 6650 diag::note_deleted_special_member_class_subobject) 6651 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 6652 << Field << DiagKind << IsDtorCallInCtor; 6653 } else { 6654 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 6655 S.Diag(Base->getLocStart(), 6656 diag::note_deleted_special_member_class_subobject) 6657 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6658 << Base->getType() << DiagKind << IsDtorCallInCtor; 6659 } 6660 6661 if (DiagKind == 1) 6662 S.NoteDeletedFunction(Decl); 6663 // FIXME: Explain inaccessibility if DiagKind == 3. 6664 } 6665 6666 return true; 6667 } 6668 6669 /// Check whether we should delete a special member function due to having a 6670 /// direct or virtual base class or non-static data member of class type M. 6671 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 6672 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 6673 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 6674 bool IsMutable = Field && Field->isMutable(); 6675 6676 // C++11 [class.ctor]p5: 6677 // -- any direct or virtual base class, or non-static data member with no 6678 // brace-or-equal-initializer, has class type M (or array thereof) and 6679 // either M has no default constructor or overload resolution as applied 6680 // to M's default constructor results in an ambiguity or in a function 6681 // that is deleted or inaccessible 6682 // C++11 [class.copy]p11, C++11 [class.copy]p23: 6683 // -- a direct or virtual base class B that cannot be copied/moved because 6684 // overload resolution, as applied to B's corresponding special member, 6685 // results in an ambiguity or a function that is deleted or inaccessible 6686 // from the defaulted special member 6687 // C++11 [class.dtor]p5: 6688 // -- any direct or virtual base class [...] has a type with a destructor 6689 // that is deleted or inaccessible 6690 if (!(CSM == Sema::CXXDefaultConstructor && 6691 Field && Field->hasInClassInitializer()) && 6692 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 6693 false)) 6694 return true; 6695 6696 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 6697 // -- any direct or virtual base class or non-static data member has a 6698 // type with a destructor that is deleted or inaccessible 6699 if (IsConstructor) { 6700 Sema::SpecialMemberOverloadResult SMOR = 6701 S.LookupSpecialMember(Class, Sema::CXXDestructor, 6702 false, false, false, false, false); 6703 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 6704 return true; 6705 } 6706 6707 return false; 6708 } 6709 6710 /// Check whether we should delete a special member function due to the class 6711 /// having a particular direct or virtual base class. 6712 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 6713 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 6714 // If program is correct, BaseClass cannot be null, but if it is, the error 6715 // must be reported elsewhere. 6716 if (!BaseClass) 6717 return false; 6718 // If we have an inheriting constructor, check whether we're calling an 6719 // inherited constructor instead of a default constructor. 6720 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 6721 if (auto *BaseCtor = SMOR.getMethod()) { 6722 // Note that we do not check access along this path; other than that, 6723 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 6724 // FIXME: Check that the base has a usable destructor! Sink this into 6725 // shouldDeleteForClassSubobject. 6726 if (BaseCtor->isDeleted() && Diagnose) { 6727 S.Diag(Base->getLocStart(), 6728 diag::note_deleted_special_member_class_subobject) 6729 << getEffectiveCSM() << MD->getParent() << /*IsField*/false 6730 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false; 6731 S.NoteDeletedFunction(BaseCtor); 6732 } 6733 return BaseCtor->isDeleted(); 6734 } 6735 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 6736 } 6737 6738 /// Check whether we should delete a special member function due to the class 6739 /// having a particular non-static data member. 6740 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 6741 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 6742 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 6743 6744 if (CSM == Sema::CXXDefaultConstructor) { 6745 // For a default constructor, all references must be initialized in-class 6746 // and, if a union, it must have a non-const member. 6747 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 6748 if (Diagnose) 6749 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6750 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 6751 return true; 6752 } 6753 // C++11 [class.ctor]p5: any non-variant non-static data member of 6754 // const-qualified type (or array thereof) with no 6755 // brace-or-equal-initializer does not have a user-provided default 6756 // constructor. 6757 if (!inUnion() && FieldType.isConstQualified() && 6758 !FD->hasInClassInitializer() && 6759 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 6760 if (Diagnose) 6761 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 6762 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 6763 return true; 6764 } 6765 6766 if (inUnion() && !FieldType.isConstQualified()) 6767 AllFieldsAreConst = false; 6768 } else if (CSM == Sema::CXXCopyConstructor) { 6769 // For a copy constructor, data members must not be of rvalue reference 6770 // type. 6771 if (FieldType->isRValueReferenceType()) { 6772 if (Diagnose) 6773 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 6774 << MD->getParent() << FD << FieldType; 6775 return true; 6776 } 6777 } else if (IsAssignment) { 6778 // For an assignment operator, data members must not be of reference type. 6779 if (FieldType->isReferenceType()) { 6780 if (Diagnose) 6781 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6782 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 6783 return true; 6784 } 6785 if (!FieldRecord && FieldType.isConstQualified()) { 6786 // C++11 [class.copy]p23: 6787 // -- a non-static data member of const non-class type (or array thereof) 6788 if (Diagnose) 6789 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 6790 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 6791 return true; 6792 } 6793 } 6794 6795 if (FieldRecord) { 6796 // Some additional restrictions exist on the variant members. 6797 if (!inUnion() && FieldRecord->isUnion() && 6798 FieldRecord->isAnonymousStructOrUnion()) { 6799 bool AllVariantFieldsAreConst = true; 6800 6801 // FIXME: Handle anonymous unions declared within anonymous unions. 6802 for (auto *UI : FieldRecord->fields()) { 6803 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 6804 6805 if (!UnionFieldType.isConstQualified()) 6806 AllVariantFieldsAreConst = false; 6807 6808 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 6809 if (UnionFieldRecord && 6810 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 6811 UnionFieldType.getCVRQualifiers())) 6812 return true; 6813 } 6814 6815 // At least one member in each anonymous union must be non-const 6816 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 6817 !FieldRecord->field_empty()) { 6818 if (Diagnose) 6819 S.Diag(FieldRecord->getLocation(), 6820 diag::note_deleted_default_ctor_all_const) 6821 << !!ICI << MD->getParent() << /*anonymous union*/1; 6822 return true; 6823 } 6824 6825 // Don't check the implicit member of the anonymous union type. 6826 // This is technically non-conformant, but sanity demands it. 6827 return false; 6828 } 6829 6830 if (shouldDeleteForClassSubobject(FieldRecord, FD, 6831 FieldType.getCVRQualifiers())) 6832 return true; 6833 } 6834 6835 return false; 6836 } 6837 6838 /// C++11 [class.ctor] p5: 6839 /// A defaulted default constructor for a class X is defined as deleted if 6840 /// X is a union and all of its variant members are of const-qualified type. 6841 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 6842 // This is a silly definition, because it gives an empty union a deleted 6843 // default constructor. Don't do that. 6844 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 6845 bool AnyFields = false; 6846 for (auto *F : MD->getParent()->fields()) 6847 if ((AnyFields = !F->isUnnamedBitfield())) 6848 break; 6849 if (!AnyFields) 6850 return false; 6851 if (Diagnose) 6852 S.Diag(MD->getParent()->getLocation(), 6853 diag::note_deleted_default_ctor_all_const) 6854 << !!ICI << MD->getParent() << /*not anonymous union*/0; 6855 return true; 6856 } 6857 return false; 6858 } 6859 6860 /// Determine whether a defaulted special member function should be defined as 6861 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 6862 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 6863 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 6864 InheritedConstructorInfo *ICI, 6865 bool Diagnose) { 6866 if (MD->isInvalidDecl()) 6867 return false; 6868 CXXRecordDecl *RD = MD->getParent(); 6869 assert(!RD->isDependentType() && "do deletion after instantiation"); 6870 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 6871 return false; 6872 6873 // C++11 [expr.lambda.prim]p19: 6874 // The closure type associated with a lambda-expression has a 6875 // deleted (8.4.3) default constructor and a deleted copy 6876 // assignment operator. 6877 if (RD->isLambda() && 6878 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 6879 if (Diagnose) 6880 Diag(RD->getLocation(), diag::note_lambda_decl); 6881 return true; 6882 } 6883 6884 // For an anonymous struct or union, the copy and assignment special members 6885 // will never be used, so skip the check. For an anonymous union declared at 6886 // namespace scope, the constructor and destructor are used. 6887 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 6888 RD->isAnonymousStructOrUnion()) 6889 return false; 6890 6891 // C++11 [class.copy]p7, p18: 6892 // If the class definition declares a move constructor or move assignment 6893 // operator, an implicitly declared copy constructor or copy assignment 6894 // operator is defined as deleted. 6895 if (MD->isImplicit() && 6896 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 6897 CXXMethodDecl *UserDeclaredMove = nullptr; 6898 6899 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 6900 // deletion of the corresponding copy operation, not both copy operations. 6901 // MSVC 2015 has adopted the standards conforming behavior. 6902 bool DeletesOnlyMatchingCopy = 6903 getLangOpts().MSVCCompat && 6904 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 6905 6906 if (RD->hasUserDeclaredMoveConstructor() && 6907 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 6908 if (!Diagnose) return true; 6909 6910 // Find any user-declared move constructor. 6911 for (auto *I : RD->ctors()) { 6912 if (I->isMoveConstructor()) { 6913 UserDeclaredMove = I; 6914 break; 6915 } 6916 } 6917 assert(UserDeclaredMove); 6918 } else if (RD->hasUserDeclaredMoveAssignment() && 6919 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 6920 if (!Diagnose) return true; 6921 6922 // Find any user-declared move assignment operator. 6923 for (auto *I : RD->methods()) { 6924 if (I->isMoveAssignmentOperator()) { 6925 UserDeclaredMove = I; 6926 break; 6927 } 6928 } 6929 assert(UserDeclaredMove); 6930 } 6931 6932 if (UserDeclaredMove) { 6933 Diag(UserDeclaredMove->getLocation(), 6934 diag::note_deleted_copy_user_declared_move) 6935 << (CSM == CXXCopyAssignment) << RD 6936 << UserDeclaredMove->isMoveAssignmentOperator(); 6937 return true; 6938 } 6939 } 6940 6941 // Do access control from the special member function 6942 ContextRAII MethodContext(*this, MD); 6943 6944 // C++11 [class.dtor]p5: 6945 // -- for a virtual destructor, lookup of the non-array deallocation function 6946 // results in an ambiguity or in a function that is deleted or inaccessible 6947 if (CSM == CXXDestructor && MD->isVirtual()) { 6948 FunctionDecl *OperatorDelete = nullptr; 6949 DeclarationName Name = 6950 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6951 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 6952 OperatorDelete, /*Diagnose*/false)) { 6953 if (Diagnose) 6954 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 6955 return true; 6956 } 6957 } 6958 6959 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 6960 6961 // Per DR1611, do not consider virtual bases of constructors of abstract 6962 // classes, since we are not going to construct them. 6963 // Per DR1658, do not consider virtual bases of destructors of abstract 6964 // classes either. 6965 // Per DR2180, for assignment operators we only assign (and thus only 6966 // consider) direct bases. 6967 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 6968 : SMI.VisitPotentiallyConstructedBases)) 6969 return true; 6970 6971 if (SMI.shouldDeleteForAllConstMembers()) 6972 return true; 6973 6974 if (getLangOpts().CUDA) { 6975 // We should delete the special member in CUDA mode if target inference 6976 // failed. 6977 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 6978 Diagnose); 6979 } 6980 6981 return false; 6982 } 6983 6984 /// Perform lookup for a special member of the specified kind, and determine 6985 /// whether it is trivial. If the triviality can be determined without the 6986 /// lookup, skip it. This is intended for use when determining whether a 6987 /// special member of a containing object is trivial, and thus does not ever 6988 /// perform overload resolution for default constructors. 6989 /// 6990 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 6991 /// member that was most likely to be intended to be trivial, if any. 6992 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 6993 Sema::CXXSpecialMember CSM, unsigned Quals, 6994 bool ConstRHS, CXXMethodDecl **Selected) { 6995 if (Selected) 6996 *Selected = nullptr; 6997 6998 switch (CSM) { 6999 case Sema::CXXInvalid: 7000 llvm_unreachable("not a special member"); 7001 7002 case Sema::CXXDefaultConstructor: 7003 // C++11 [class.ctor]p5: 7004 // A default constructor is trivial if: 7005 // - all the [direct subobjects] have trivial default constructors 7006 // 7007 // Note, no overload resolution is performed in this case. 7008 if (RD->hasTrivialDefaultConstructor()) 7009 return true; 7010 7011 if (Selected) { 7012 // If there's a default constructor which could have been trivial, dig it 7013 // out. Otherwise, if there's any user-provided default constructor, point 7014 // to that as an example of why there's not a trivial one. 7015 CXXConstructorDecl *DefCtor = nullptr; 7016 if (RD->needsImplicitDefaultConstructor()) 7017 S.DeclareImplicitDefaultConstructor(RD); 7018 for (auto *CI : RD->ctors()) { 7019 if (!CI->isDefaultConstructor()) 7020 continue; 7021 DefCtor = CI; 7022 if (!DefCtor->isUserProvided()) 7023 break; 7024 } 7025 7026 *Selected = DefCtor; 7027 } 7028 7029 return false; 7030 7031 case Sema::CXXDestructor: 7032 // C++11 [class.dtor]p5: 7033 // A destructor is trivial if: 7034 // - all the direct [subobjects] have trivial destructors 7035 if (RD->hasTrivialDestructor()) 7036 return true; 7037 7038 if (Selected) { 7039 if (RD->needsImplicitDestructor()) 7040 S.DeclareImplicitDestructor(RD); 7041 *Selected = RD->getDestructor(); 7042 } 7043 7044 return false; 7045 7046 case Sema::CXXCopyConstructor: 7047 // C++11 [class.copy]p12: 7048 // A copy constructor is trivial if: 7049 // - the constructor selected to copy each direct [subobject] is trivial 7050 if (RD->hasTrivialCopyConstructor()) { 7051 if (Quals == Qualifiers::Const) 7052 // We must either select the trivial copy constructor or reach an 7053 // ambiguity; no need to actually perform overload resolution. 7054 return true; 7055 } else if (!Selected) { 7056 return false; 7057 } 7058 // In C++98, we are not supposed to perform overload resolution here, but we 7059 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7060 // cases like B as having a non-trivial copy constructor: 7061 // struct A { template<typename T> A(T&); }; 7062 // struct B { mutable A a; }; 7063 goto NeedOverloadResolution; 7064 7065 case Sema::CXXCopyAssignment: 7066 // C++11 [class.copy]p25: 7067 // A copy assignment operator is trivial if: 7068 // - the assignment operator selected to copy each direct [subobject] is 7069 // trivial 7070 if (RD->hasTrivialCopyAssignment()) { 7071 if (Quals == Qualifiers::Const) 7072 return true; 7073 } else if (!Selected) { 7074 return false; 7075 } 7076 // In C++98, we are not supposed to perform overload resolution here, but we 7077 // treat that as a language defect. 7078 goto NeedOverloadResolution; 7079 7080 case Sema::CXXMoveConstructor: 7081 case Sema::CXXMoveAssignment: 7082 NeedOverloadResolution: 7083 Sema::SpecialMemberOverloadResult SMOR = 7084 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7085 7086 // The standard doesn't describe how to behave if the lookup is ambiguous. 7087 // We treat it as not making the member non-trivial, just like the standard 7088 // mandates for the default constructor. This should rarely matter, because 7089 // the member will also be deleted. 7090 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7091 return true; 7092 7093 if (!SMOR.getMethod()) { 7094 assert(SMOR.getKind() == 7095 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7096 return false; 7097 } 7098 7099 // We deliberately don't check if we found a deleted special member. We're 7100 // not supposed to! 7101 if (Selected) 7102 *Selected = SMOR.getMethod(); 7103 return SMOR.getMethod()->isTrivial(); 7104 } 7105 7106 llvm_unreachable("unknown special method kind"); 7107 } 7108 7109 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7110 for (auto *CI : RD->ctors()) 7111 if (!CI->isImplicit()) 7112 return CI; 7113 7114 // Look for constructor templates. 7115 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7116 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7117 if (CXXConstructorDecl *CD = 7118 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7119 return CD; 7120 } 7121 7122 return nullptr; 7123 } 7124 7125 /// The kind of subobject we are checking for triviality. The values of this 7126 /// enumeration are used in diagnostics. 7127 enum TrivialSubobjectKind { 7128 /// The subobject is a base class. 7129 TSK_BaseClass, 7130 /// The subobject is a non-static data member. 7131 TSK_Field, 7132 /// The object is actually the complete object. 7133 TSK_CompleteObject 7134 }; 7135 7136 /// Check whether the special member selected for a given type would be trivial. 7137 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7138 QualType SubType, bool ConstRHS, 7139 Sema::CXXSpecialMember CSM, 7140 TrivialSubobjectKind Kind, 7141 bool Diagnose) { 7142 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7143 if (!SubRD) 7144 return true; 7145 7146 CXXMethodDecl *Selected; 7147 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7148 ConstRHS, Diagnose ? &Selected : nullptr)) 7149 return true; 7150 7151 if (Diagnose) { 7152 if (ConstRHS) 7153 SubType.addConst(); 7154 7155 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7156 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7157 << Kind << SubType.getUnqualifiedType(); 7158 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7159 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7160 } else if (!Selected) 7161 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7162 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7163 else if (Selected->isUserProvided()) { 7164 if (Kind == TSK_CompleteObject) 7165 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7166 << Kind << SubType.getUnqualifiedType() << CSM; 7167 else { 7168 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7169 << Kind << SubType.getUnqualifiedType() << CSM; 7170 S.Diag(Selected->getLocation(), diag::note_declared_at); 7171 } 7172 } else { 7173 if (Kind != TSK_CompleteObject) 7174 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7175 << Kind << SubType.getUnqualifiedType() << CSM; 7176 7177 // Explain why the defaulted or deleted special member isn't trivial. 7178 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 7179 } 7180 } 7181 7182 return false; 7183 } 7184 7185 /// Check whether the members of a class type allow a special member to be 7186 /// trivial. 7187 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7188 Sema::CXXSpecialMember CSM, 7189 bool ConstArg, bool Diagnose) { 7190 for (const auto *FI : RD->fields()) { 7191 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7192 continue; 7193 7194 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7195 7196 // Pretend anonymous struct or union members are members of this class. 7197 if (FI->isAnonymousStructOrUnion()) { 7198 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7199 CSM, ConstArg, Diagnose)) 7200 return false; 7201 continue; 7202 } 7203 7204 // C++11 [class.ctor]p5: 7205 // A default constructor is trivial if [...] 7206 // -- no non-static data member of its class has a 7207 // brace-or-equal-initializer 7208 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7209 if (Diagnose) 7210 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7211 return false; 7212 } 7213 7214 // Objective C ARC 4.3.5: 7215 // [...] nontrivally ownership-qualified types are [...] not trivially 7216 // default constructible, copy constructible, move constructible, copy 7217 // assignable, move assignable, or destructible [...] 7218 if (FieldType.hasNonTrivialObjCLifetime()) { 7219 if (Diagnose) 7220 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7221 << RD << FieldType.getObjCLifetime(); 7222 return false; 7223 } 7224 7225 bool ConstRHS = ConstArg && !FI->isMutable(); 7226 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7227 CSM, TSK_Field, Diagnose)) 7228 return false; 7229 } 7230 7231 return true; 7232 } 7233 7234 /// Diagnose why the specified class does not have a trivial special member of 7235 /// the given kind. 7236 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7237 QualType Ty = Context.getRecordType(RD); 7238 7239 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7240 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7241 TSK_CompleteObject, /*Diagnose*/true); 7242 } 7243 7244 /// Determine whether a defaulted or deleted special member function is trivial, 7245 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7246 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7247 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7248 bool Diagnose) { 7249 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7250 7251 CXXRecordDecl *RD = MD->getParent(); 7252 7253 bool ConstArg = false; 7254 7255 // C++11 [class.copy]p12, p25: [DR1593] 7256 // A [special member] is trivial if [...] its parameter-type-list is 7257 // equivalent to the parameter-type-list of an implicit declaration [...] 7258 switch (CSM) { 7259 case CXXDefaultConstructor: 7260 case CXXDestructor: 7261 // Trivial default constructors and destructors cannot have parameters. 7262 break; 7263 7264 case CXXCopyConstructor: 7265 case CXXCopyAssignment: { 7266 // Trivial copy operations always have const, non-volatile parameter types. 7267 ConstArg = true; 7268 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7269 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7270 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7271 if (Diagnose) 7272 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7273 << Param0->getSourceRange() << Param0->getType() 7274 << Context.getLValueReferenceType( 7275 Context.getRecordType(RD).withConst()); 7276 return false; 7277 } 7278 break; 7279 } 7280 7281 case CXXMoveConstructor: 7282 case CXXMoveAssignment: { 7283 // Trivial move operations always have non-cv-qualified parameters. 7284 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7285 const RValueReferenceType *RT = 7286 Param0->getType()->getAs<RValueReferenceType>(); 7287 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7288 if (Diagnose) 7289 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7290 << Param0->getSourceRange() << Param0->getType() 7291 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7292 return false; 7293 } 7294 break; 7295 } 7296 7297 case CXXInvalid: 7298 llvm_unreachable("not a special member"); 7299 } 7300 7301 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7302 if (Diagnose) 7303 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7304 diag::note_nontrivial_default_arg) 7305 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7306 return false; 7307 } 7308 if (MD->isVariadic()) { 7309 if (Diagnose) 7310 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7311 return false; 7312 } 7313 7314 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7315 // A copy/move [constructor or assignment operator] is trivial if 7316 // -- the [member] selected to copy/move each direct base class subobject 7317 // is trivial 7318 // 7319 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7320 // A [default constructor or destructor] is trivial if 7321 // -- all the direct base classes have trivial [default constructors or 7322 // destructors] 7323 for (const auto &BI : RD->bases()) 7324 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 7325 ConstArg, CSM, TSK_BaseClass, Diagnose)) 7326 return false; 7327 7328 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7329 // A copy/move [constructor or assignment operator] for a class X is 7330 // trivial if 7331 // -- for each non-static data member of X that is of class type (or array 7332 // thereof), the constructor selected to copy/move that member is 7333 // trivial 7334 // 7335 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7336 // A [default constructor or destructor] is trivial if 7337 // -- for all of the non-static data members of its class that are of class 7338 // type (or array thereof), each such class has a trivial [default 7339 // constructor or destructor] 7340 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 7341 return false; 7342 7343 // C++11 [class.dtor]p5: 7344 // A destructor is trivial if [...] 7345 // -- the destructor is not virtual 7346 if (CSM == CXXDestructor && MD->isVirtual()) { 7347 if (Diagnose) 7348 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7349 return false; 7350 } 7351 7352 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7353 // A [special member] for class X is trivial if [...] 7354 // -- class X has no virtual functions and no virtual base classes 7355 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7356 if (!Diagnose) 7357 return false; 7358 7359 if (RD->getNumVBases()) { 7360 // Check for virtual bases. We already know that the corresponding 7361 // member in all bases is trivial, so vbases must all be direct. 7362 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7363 assert(BS.isVirtual()); 7364 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 7365 return false; 7366 } 7367 7368 // Must have a virtual method. 7369 for (const auto *MI : RD->methods()) { 7370 if (MI->isVirtual()) { 7371 SourceLocation MLoc = MI->getLocStart(); 7372 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7373 return false; 7374 } 7375 } 7376 7377 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7378 } 7379 7380 // Looks like it's trivial! 7381 return true; 7382 } 7383 7384 namespace { 7385 struct FindHiddenVirtualMethod { 7386 Sema *S; 7387 CXXMethodDecl *Method; 7388 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7389 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7390 7391 private: 7392 /// Check whether any most overriden method from MD in Methods 7393 static bool CheckMostOverridenMethods( 7394 const CXXMethodDecl *MD, 7395 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7396 if (MD->size_overridden_methods() == 0) 7397 return Methods.count(MD->getCanonicalDecl()); 7398 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7399 E = MD->end_overridden_methods(); 7400 I != E; ++I) 7401 if (CheckMostOverridenMethods(*I, Methods)) 7402 return true; 7403 return false; 7404 } 7405 7406 public: 7407 /// Member lookup function that determines whether a given C++ 7408 /// method overloads virtual methods in a base class without overriding any, 7409 /// to be used with CXXRecordDecl::lookupInBases(). 7410 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7411 RecordDecl *BaseRecord = 7412 Specifier->getType()->getAs<RecordType>()->getDecl(); 7413 7414 DeclarationName Name = Method->getDeclName(); 7415 assert(Name.getNameKind() == DeclarationName::Identifier); 7416 7417 bool foundSameNameMethod = false; 7418 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 7419 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7420 Path.Decls = Path.Decls.slice(1)) { 7421 NamedDecl *D = Path.Decls.front(); 7422 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7423 MD = MD->getCanonicalDecl(); 7424 foundSameNameMethod = true; 7425 // Interested only in hidden virtual methods. 7426 if (!MD->isVirtual()) 7427 continue; 7428 // If the method we are checking overrides a method from its base 7429 // don't warn about the other overloaded methods. Clang deviates from 7430 // GCC by only diagnosing overloads of inherited virtual functions that 7431 // do not override any other virtual functions in the base. GCC's 7432 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 7433 // function from a base class. These cases may be better served by a 7434 // warning (not specific to virtual functions) on call sites when the 7435 // call would select a different function from the base class, were it 7436 // visible. 7437 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 7438 if (!S->IsOverload(Method, MD, false)) 7439 return true; 7440 // Collect the overload only if its hidden. 7441 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 7442 overloadedMethods.push_back(MD); 7443 } 7444 } 7445 7446 if (foundSameNameMethod) 7447 OverloadedMethods.append(overloadedMethods.begin(), 7448 overloadedMethods.end()); 7449 return foundSameNameMethod; 7450 } 7451 }; 7452 } // end anonymous namespace 7453 7454 /// \brief Add the most overriden methods from MD to Methods 7455 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 7456 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 7457 if (MD->size_overridden_methods() == 0) 7458 Methods.insert(MD->getCanonicalDecl()); 7459 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7460 E = MD->end_overridden_methods(); 7461 I != E; ++I) 7462 AddMostOverridenMethods(*I, Methods); 7463 } 7464 7465 /// \brief Check if a method overloads virtual methods in a base class without 7466 /// overriding any. 7467 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 7468 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7469 if (!MD->getDeclName().isIdentifier()) 7470 return; 7471 7472 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 7473 /*bool RecordPaths=*/false, 7474 /*bool DetectVirtual=*/false); 7475 FindHiddenVirtualMethod FHVM; 7476 FHVM.Method = MD; 7477 FHVM.S = this; 7478 7479 // Keep the base methods that were overriden or introduced in the subclass 7480 // by 'using' in a set. A base method not in this set is hidden. 7481 CXXRecordDecl *DC = MD->getParent(); 7482 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 7483 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 7484 NamedDecl *ND = *I; 7485 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 7486 ND = shad->getTargetDecl(); 7487 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7488 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 7489 } 7490 7491 if (DC->lookupInBases(FHVM, Paths)) 7492 OverloadedMethods = FHVM.OverloadedMethods; 7493 } 7494 7495 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 7496 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 7497 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 7498 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 7499 PartialDiagnostic PD = PDiag( 7500 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 7501 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 7502 Diag(overloadedMD->getLocation(), PD); 7503 } 7504 } 7505 7506 /// \brief Diagnose methods which overload virtual methods in a base class 7507 /// without overriding any. 7508 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 7509 if (MD->isInvalidDecl()) 7510 return; 7511 7512 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 7513 return; 7514 7515 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7516 FindHiddenVirtualMethods(MD, OverloadedMethods); 7517 if (!OverloadedMethods.empty()) { 7518 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 7519 << MD << (OverloadedMethods.size() > 1); 7520 7521 NoteHiddenVirtualMethods(MD, OverloadedMethods); 7522 } 7523 } 7524 7525 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 7526 Decl *TagDecl, 7527 SourceLocation LBrac, 7528 SourceLocation RBrac, 7529 AttributeList *AttrList) { 7530 if (!TagDecl) 7531 return; 7532 7533 AdjustDeclIfTemplate(TagDecl); 7534 7535 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 7536 if (l->getKind() != AttributeList::AT_Visibility) 7537 continue; 7538 l->setInvalid(); 7539 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 7540 l->getName(); 7541 } 7542 7543 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 7544 // strict aliasing violation! 7545 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 7546 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 7547 7548 CheckCompletedCXXClass(dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 7549 } 7550 7551 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 7552 /// special functions, such as the default constructor, copy 7553 /// constructor, or destructor, to the given C++ class (C++ 7554 /// [special]p1). This routine can only be executed just before the 7555 /// definition of the class is complete. 7556 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 7557 if (ClassDecl->needsImplicitDefaultConstructor()) { 7558 ++ASTContext::NumImplicitDefaultConstructors; 7559 7560 if (ClassDecl->hasInheritedConstructor()) 7561 DeclareImplicitDefaultConstructor(ClassDecl); 7562 } 7563 7564 if (ClassDecl->needsImplicitCopyConstructor()) { 7565 ++ASTContext::NumImplicitCopyConstructors; 7566 7567 // If the properties or semantics of the copy constructor couldn't be 7568 // determined while the class was being declared, force a declaration 7569 // of it now. 7570 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 7571 ClassDecl->hasInheritedConstructor()) 7572 DeclareImplicitCopyConstructor(ClassDecl); 7573 // For the MS ABI we need to know whether the copy ctor is deleted. A 7574 // prerequisite for deleting the implicit copy ctor is that the class has a 7575 // move ctor or move assignment that is either user-declared or whose 7576 // semantics are inherited from a subobject. FIXME: We should provide a more 7577 // direct way for CodeGen to ask whether the constructor was deleted. 7578 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 7579 (ClassDecl->hasUserDeclaredMoveConstructor() || 7580 ClassDecl->needsOverloadResolutionForMoveConstructor() || 7581 ClassDecl->hasUserDeclaredMoveAssignment() || 7582 ClassDecl->needsOverloadResolutionForMoveAssignment())) 7583 DeclareImplicitCopyConstructor(ClassDecl); 7584 } 7585 7586 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 7587 ++ASTContext::NumImplicitMoveConstructors; 7588 7589 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 7590 ClassDecl->hasInheritedConstructor()) 7591 DeclareImplicitMoveConstructor(ClassDecl); 7592 } 7593 7594 if (ClassDecl->needsImplicitCopyAssignment()) { 7595 ++ASTContext::NumImplicitCopyAssignmentOperators; 7596 7597 // If we have a dynamic class, then the copy assignment operator may be 7598 // virtual, so we have to declare it immediately. This ensures that, e.g., 7599 // it shows up in the right place in the vtable and that we diagnose 7600 // problems with the implicit exception specification. 7601 if (ClassDecl->isDynamicClass() || 7602 ClassDecl->needsOverloadResolutionForCopyAssignment() || 7603 ClassDecl->hasInheritedAssignment()) 7604 DeclareImplicitCopyAssignment(ClassDecl); 7605 } 7606 7607 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 7608 ++ASTContext::NumImplicitMoveAssignmentOperators; 7609 7610 // Likewise for the move assignment operator. 7611 if (ClassDecl->isDynamicClass() || 7612 ClassDecl->needsOverloadResolutionForMoveAssignment() || 7613 ClassDecl->hasInheritedAssignment()) 7614 DeclareImplicitMoveAssignment(ClassDecl); 7615 } 7616 7617 if (ClassDecl->needsImplicitDestructor()) { 7618 ++ASTContext::NumImplicitDestructors; 7619 7620 // If we have a dynamic class, then the destructor may be virtual, so we 7621 // have to declare the destructor immediately. This ensures that, e.g., it 7622 // shows up in the right place in the vtable and that we diagnose problems 7623 // with the implicit exception specification. 7624 if (ClassDecl->isDynamicClass() || 7625 ClassDecl->needsOverloadResolutionForDestructor()) 7626 DeclareImplicitDestructor(ClassDecl); 7627 } 7628 } 7629 7630 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 7631 if (!D) 7632 return 0; 7633 7634 // The order of template parameters is not important here. All names 7635 // get added to the same scope. 7636 SmallVector<TemplateParameterList *, 4> ParameterLists; 7637 7638 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 7639 D = TD->getTemplatedDecl(); 7640 7641 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 7642 ParameterLists.push_back(PSD->getTemplateParameters()); 7643 7644 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 7645 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 7646 ParameterLists.push_back(DD->getTemplateParameterList(i)); 7647 7648 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7649 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 7650 ParameterLists.push_back(FTD->getTemplateParameters()); 7651 } 7652 } 7653 7654 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 7655 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 7656 ParameterLists.push_back(TD->getTemplateParameterList(i)); 7657 7658 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 7659 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 7660 ParameterLists.push_back(CTD->getTemplateParameters()); 7661 } 7662 } 7663 7664 unsigned Count = 0; 7665 for (TemplateParameterList *Params : ParameterLists) { 7666 if (Params->size() > 0) 7667 // Ignore explicit specializations; they don't contribute to the template 7668 // depth. 7669 ++Count; 7670 for (NamedDecl *Param : *Params) { 7671 if (Param->getDeclName()) { 7672 S->AddDecl(Param); 7673 IdResolver.AddDecl(Param); 7674 } 7675 } 7676 } 7677 7678 return Count; 7679 } 7680 7681 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7682 if (!RecordD) return; 7683 AdjustDeclIfTemplate(RecordD); 7684 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 7685 PushDeclContext(S, Record); 7686 } 7687 7688 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 7689 if (!RecordD) return; 7690 PopDeclContext(); 7691 } 7692 7693 /// This is used to implement the constant expression evaluation part of the 7694 /// attribute enable_if extension. There is nothing in standard C++ which would 7695 /// require reentering parameters. 7696 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 7697 if (!Param) 7698 return; 7699 7700 S->AddDecl(Param); 7701 if (Param->getDeclName()) 7702 IdResolver.AddDecl(Param); 7703 } 7704 7705 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 7706 /// parsing a top-level (non-nested) C++ class, and we are now 7707 /// parsing those parts of the given Method declaration that could 7708 /// not be parsed earlier (C++ [class.mem]p2), such as default 7709 /// arguments. This action should enter the scope of the given 7710 /// Method declaration as if we had just parsed the qualified method 7711 /// name. However, it should not bring the parameters into scope; 7712 /// that will be performed by ActOnDelayedCXXMethodParameter. 7713 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7714 } 7715 7716 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 7717 /// C++ method declaration. We're (re-)introducing the given 7718 /// function parameter into scope for use in parsing later parts of 7719 /// the method declaration. For example, we could see an 7720 /// ActOnParamDefaultArgument event for this parameter. 7721 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 7722 if (!ParamD) 7723 return; 7724 7725 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 7726 7727 // If this parameter has an unparsed default argument, clear it out 7728 // to make way for the parsed default argument. 7729 if (Param->hasUnparsedDefaultArg()) 7730 Param->setDefaultArg(nullptr); 7731 7732 S->AddDecl(Param); 7733 if (Param->getDeclName()) 7734 IdResolver.AddDecl(Param); 7735 } 7736 7737 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 7738 /// processing the delayed method declaration for Method. The method 7739 /// declaration is now considered finished. There may be a separate 7740 /// ActOnStartOfFunctionDef action later (not necessarily 7741 /// immediately!) for this method, if it was also defined inside the 7742 /// class body. 7743 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 7744 if (!MethodD) 7745 return; 7746 7747 AdjustDeclIfTemplate(MethodD); 7748 7749 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 7750 7751 // Now that we have our default arguments, check the constructor 7752 // again. It could produce additional diagnostics or affect whether 7753 // the class has implicitly-declared destructors, among other 7754 // things. 7755 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 7756 CheckConstructor(Constructor); 7757 7758 // Check the default arguments, which we may have added. 7759 if (!Method->isInvalidDecl()) 7760 CheckCXXDefaultArguments(Method); 7761 } 7762 7763 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 7764 /// the well-formedness of the constructor declarator @p D with type @p 7765 /// R. If there are any errors in the declarator, this routine will 7766 /// emit diagnostics and set the invalid bit to true. In any case, the type 7767 /// will be updated to reflect a well-formed type for the constructor and 7768 /// returned. 7769 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 7770 StorageClass &SC) { 7771 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7772 7773 // C++ [class.ctor]p3: 7774 // A constructor shall not be virtual (10.3) or static (9.4). A 7775 // constructor can be invoked for a const, volatile or const 7776 // volatile object. A constructor shall not be declared const, 7777 // volatile, or const volatile (9.3.2). 7778 if (isVirtual) { 7779 if (!D.isInvalidType()) 7780 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7781 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 7782 << SourceRange(D.getIdentifierLoc()); 7783 D.setInvalidType(); 7784 } 7785 if (SC == SC_Static) { 7786 if (!D.isInvalidType()) 7787 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 7788 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7789 << SourceRange(D.getIdentifierLoc()); 7790 D.setInvalidType(); 7791 SC = SC_None; 7792 } 7793 7794 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7795 diagnoseIgnoredQualifiers( 7796 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 7797 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 7798 D.getDeclSpec().getRestrictSpecLoc(), 7799 D.getDeclSpec().getAtomicSpecLoc()); 7800 D.setInvalidType(); 7801 } 7802 7803 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7804 if (FTI.TypeQuals != 0) { 7805 if (FTI.TypeQuals & Qualifiers::Const) 7806 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7807 << "const" << SourceRange(D.getIdentifierLoc()); 7808 if (FTI.TypeQuals & Qualifiers::Volatile) 7809 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7810 << "volatile" << SourceRange(D.getIdentifierLoc()); 7811 if (FTI.TypeQuals & Qualifiers::Restrict) 7812 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 7813 << "restrict" << SourceRange(D.getIdentifierLoc()); 7814 D.setInvalidType(); 7815 } 7816 7817 // C++0x [class.ctor]p4: 7818 // A constructor shall not be declared with a ref-qualifier. 7819 if (FTI.hasRefQualifier()) { 7820 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 7821 << FTI.RefQualifierIsLValueRef 7822 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7823 D.setInvalidType(); 7824 } 7825 7826 // Rebuild the function type "R" without any type qualifiers (in 7827 // case any of the errors above fired) and with "void" as the 7828 // return type, since constructors don't have return types. 7829 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 7830 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 7831 return R; 7832 7833 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 7834 EPI.TypeQuals = 0; 7835 EPI.RefQualifier = RQ_None; 7836 7837 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 7838 } 7839 7840 /// CheckConstructor - Checks a fully-formed constructor for 7841 /// well-formedness, issuing any diagnostics required. Returns true if 7842 /// the constructor declarator is invalid. 7843 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 7844 CXXRecordDecl *ClassDecl 7845 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 7846 if (!ClassDecl) 7847 return Constructor->setInvalidDecl(); 7848 7849 // C++ [class.copy]p3: 7850 // A declaration of a constructor for a class X is ill-formed if 7851 // its first parameter is of type (optionally cv-qualified) X and 7852 // either there are no other parameters or else all other 7853 // parameters have default arguments. 7854 if (!Constructor->isInvalidDecl() && 7855 ((Constructor->getNumParams() == 1) || 7856 (Constructor->getNumParams() > 1 && 7857 Constructor->getParamDecl(1)->hasDefaultArg())) && 7858 Constructor->getTemplateSpecializationKind() 7859 != TSK_ImplicitInstantiation) { 7860 QualType ParamType = Constructor->getParamDecl(0)->getType(); 7861 QualType ClassTy = Context.getTagDeclType(ClassDecl); 7862 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 7863 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 7864 const char *ConstRef 7865 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 7866 : " const &"; 7867 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 7868 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 7869 7870 // FIXME: Rather that making the constructor invalid, we should endeavor 7871 // to fix the type. 7872 Constructor->setInvalidDecl(); 7873 } 7874 } 7875 } 7876 7877 /// CheckDestructor - Checks a fully-formed destructor definition for 7878 /// well-formedness, issuing any diagnostics required. Returns true 7879 /// on error. 7880 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 7881 CXXRecordDecl *RD = Destructor->getParent(); 7882 7883 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 7884 SourceLocation Loc; 7885 7886 if (!Destructor->isImplicit()) 7887 Loc = Destructor->getLocation(); 7888 else 7889 Loc = RD->getLocation(); 7890 7891 // If we have a virtual destructor, look up the deallocation function 7892 if (FunctionDecl *OperatorDelete = 7893 FindDeallocationFunctionForDestructor(Loc, RD)) { 7894 MarkFunctionReferenced(Loc, OperatorDelete); 7895 Destructor->setOperatorDelete(OperatorDelete); 7896 } 7897 } 7898 7899 return false; 7900 } 7901 7902 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 7903 /// the well-formednes of the destructor declarator @p D with type @p 7904 /// R. If there are any errors in the declarator, this routine will 7905 /// emit diagnostics and set the declarator to invalid. Even if this happens, 7906 /// will be updated to reflect a well-formed type for the destructor and 7907 /// returned. 7908 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 7909 StorageClass& SC) { 7910 // C++ [class.dtor]p1: 7911 // [...] A typedef-name that names a class is a class-name 7912 // (7.1.3); however, a typedef-name that names a class shall not 7913 // be used as the identifier in the declarator for a destructor 7914 // declaration. 7915 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 7916 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 7917 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7918 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 7919 else if (const TemplateSpecializationType *TST = 7920 DeclaratorType->getAs<TemplateSpecializationType>()) 7921 if (TST->isTypeAlias()) 7922 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 7923 << DeclaratorType << 1; 7924 7925 // C++ [class.dtor]p2: 7926 // A destructor is used to destroy objects of its class type. A 7927 // destructor takes no parameters, and no return type can be 7928 // specified for it (not even void). The address of a destructor 7929 // shall not be taken. A destructor shall not be static. A 7930 // destructor can be invoked for a const, volatile or const 7931 // volatile object. A destructor shall not be declared const, 7932 // volatile or const volatile (9.3.2). 7933 if (SC == SC_Static) { 7934 if (!D.isInvalidType()) 7935 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 7936 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 7937 << SourceRange(D.getIdentifierLoc()) 7938 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7939 7940 SC = SC_None; 7941 } 7942 if (!D.isInvalidType()) { 7943 // Destructors don't have return types, but the parser will 7944 // happily parse something like: 7945 // 7946 // class X { 7947 // float ~X(); 7948 // }; 7949 // 7950 // The return type will be eliminated later. 7951 if (D.getDeclSpec().hasTypeSpecifier()) 7952 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 7953 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7954 << SourceRange(D.getIdentifierLoc()); 7955 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 7956 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 7957 SourceLocation(), 7958 D.getDeclSpec().getConstSpecLoc(), 7959 D.getDeclSpec().getVolatileSpecLoc(), 7960 D.getDeclSpec().getRestrictSpecLoc(), 7961 D.getDeclSpec().getAtomicSpecLoc()); 7962 D.setInvalidType(); 7963 } 7964 } 7965 7966 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7967 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 7968 if (FTI.TypeQuals & Qualifiers::Const) 7969 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7970 << "const" << SourceRange(D.getIdentifierLoc()); 7971 if (FTI.TypeQuals & Qualifiers::Volatile) 7972 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7973 << "volatile" << SourceRange(D.getIdentifierLoc()); 7974 if (FTI.TypeQuals & Qualifiers::Restrict) 7975 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 7976 << "restrict" << SourceRange(D.getIdentifierLoc()); 7977 D.setInvalidType(); 7978 } 7979 7980 // C++0x [class.dtor]p2: 7981 // A destructor shall not be declared with a ref-qualifier. 7982 if (FTI.hasRefQualifier()) { 7983 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 7984 << FTI.RefQualifierIsLValueRef 7985 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 7986 D.setInvalidType(); 7987 } 7988 7989 // Make sure we don't have any parameters. 7990 if (FTIHasNonVoidParameters(FTI)) { 7991 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 7992 7993 // Delete the parameters. 7994 FTI.freeParams(); 7995 D.setInvalidType(); 7996 } 7997 7998 // Make sure the destructor isn't variadic. 7999 if (FTI.isVariadic) { 8000 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8001 D.setInvalidType(); 8002 } 8003 8004 // Rebuild the function type "R" without any type qualifiers or 8005 // parameters (in case any of the errors above fired) and with 8006 // "void" as the return type, since destructors don't have return 8007 // types. 8008 if (!D.isInvalidType()) 8009 return R; 8010 8011 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8012 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8013 EPI.Variadic = false; 8014 EPI.TypeQuals = 0; 8015 EPI.RefQualifier = RQ_None; 8016 return Context.getFunctionType(Context.VoidTy, None, EPI); 8017 } 8018 8019 static void extendLeft(SourceRange &R, SourceRange Before) { 8020 if (Before.isInvalid()) 8021 return; 8022 R.setBegin(Before.getBegin()); 8023 if (R.getEnd().isInvalid()) 8024 R.setEnd(Before.getEnd()); 8025 } 8026 8027 static void extendRight(SourceRange &R, SourceRange After) { 8028 if (After.isInvalid()) 8029 return; 8030 if (R.getBegin().isInvalid()) 8031 R.setBegin(After.getBegin()); 8032 R.setEnd(After.getEnd()); 8033 } 8034 8035 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8036 /// well-formednes of the conversion function declarator @p D with 8037 /// type @p R. If there are any errors in the declarator, this routine 8038 /// will emit diagnostics and return true. Otherwise, it will return 8039 /// false. Either way, the type @p R will be updated to reflect a 8040 /// well-formed type for the conversion operator. 8041 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8042 StorageClass& SC) { 8043 // C++ [class.conv.fct]p1: 8044 // Neither parameter types nor return type can be specified. The 8045 // type of a conversion function (8.3.5) is "function taking no 8046 // parameter returning conversion-type-id." 8047 if (SC == SC_Static) { 8048 if (!D.isInvalidType()) 8049 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8050 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8051 << D.getName().getSourceRange(); 8052 D.setInvalidType(); 8053 SC = SC_None; 8054 } 8055 8056 TypeSourceInfo *ConvTSI = nullptr; 8057 QualType ConvType = 8058 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8059 8060 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 8061 // Conversion functions don't have return types, but the parser will 8062 // happily parse something like: 8063 // 8064 // class X { 8065 // float operator bool(); 8066 // }; 8067 // 8068 // The return type will be changed later anyway. 8069 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8070 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8071 << SourceRange(D.getIdentifierLoc()); 8072 D.setInvalidType(); 8073 } 8074 8075 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8076 8077 // Make sure we don't have any parameters. 8078 if (Proto->getNumParams() > 0) { 8079 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8080 8081 // Delete the parameters. 8082 D.getFunctionTypeInfo().freeParams(); 8083 D.setInvalidType(); 8084 } else if (Proto->isVariadic()) { 8085 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8086 D.setInvalidType(); 8087 } 8088 8089 // Diagnose "&operator bool()" and other such nonsense. This 8090 // is actually a gcc extension which we don't support. 8091 if (Proto->getReturnType() != ConvType) { 8092 bool NeedsTypedef = false; 8093 SourceRange Before, After; 8094 8095 // Walk the chunks and extract information on them for our diagnostic. 8096 bool PastFunctionChunk = false; 8097 for (auto &Chunk : D.type_objects()) { 8098 switch (Chunk.Kind) { 8099 case DeclaratorChunk::Function: 8100 if (!PastFunctionChunk) { 8101 if (Chunk.Fun.HasTrailingReturnType) { 8102 TypeSourceInfo *TRT = nullptr; 8103 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8104 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8105 } 8106 PastFunctionChunk = true; 8107 break; 8108 } 8109 // Fall through. 8110 case DeclaratorChunk::Array: 8111 NeedsTypedef = true; 8112 extendRight(After, Chunk.getSourceRange()); 8113 break; 8114 8115 case DeclaratorChunk::Pointer: 8116 case DeclaratorChunk::BlockPointer: 8117 case DeclaratorChunk::Reference: 8118 case DeclaratorChunk::MemberPointer: 8119 case DeclaratorChunk::Pipe: 8120 extendLeft(Before, Chunk.getSourceRange()); 8121 break; 8122 8123 case DeclaratorChunk::Paren: 8124 extendLeft(Before, Chunk.Loc); 8125 extendRight(After, Chunk.EndLoc); 8126 break; 8127 } 8128 } 8129 8130 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8131 After.isValid() ? After.getBegin() : 8132 D.getIdentifierLoc(); 8133 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8134 DB << Before << After; 8135 8136 if (!NeedsTypedef) { 8137 DB << /*don't need a typedef*/0; 8138 8139 // If we can provide a correct fix-it hint, do so. 8140 if (After.isInvalid() && ConvTSI) { 8141 SourceLocation InsertLoc = 8142 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd()); 8143 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8144 << FixItHint::CreateInsertionFromRange( 8145 InsertLoc, CharSourceRange::getTokenRange(Before)) 8146 << FixItHint::CreateRemoval(Before); 8147 } 8148 } else if (!Proto->getReturnType()->isDependentType()) { 8149 DB << /*typedef*/1 << Proto->getReturnType(); 8150 } else if (getLangOpts().CPlusPlus11) { 8151 DB << /*alias template*/2 << Proto->getReturnType(); 8152 } else { 8153 DB << /*might not be fixable*/3; 8154 } 8155 8156 // Recover by incorporating the other type chunks into the result type. 8157 // Note, this does *not* change the name of the function. This is compatible 8158 // with the GCC extension: 8159 // struct S { &operator int(); } s; 8160 // int &r = s.operator int(); // ok in GCC 8161 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8162 ConvType = Proto->getReturnType(); 8163 } 8164 8165 // C++ [class.conv.fct]p4: 8166 // The conversion-type-id shall not represent a function type nor 8167 // an array type. 8168 if (ConvType->isArrayType()) { 8169 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8170 ConvType = Context.getPointerType(ConvType); 8171 D.setInvalidType(); 8172 } else if (ConvType->isFunctionType()) { 8173 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8174 ConvType = Context.getPointerType(ConvType); 8175 D.setInvalidType(); 8176 } 8177 8178 // Rebuild the function type "R" without any parameters (in case any 8179 // of the errors above fired) and with the conversion type as the 8180 // return type. 8181 if (D.isInvalidType()) 8182 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8183 8184 // C++0x explicit conversion operators. 8185 if (D.getDeclSpec().isExplicitSpecified()) 8186 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8187 getLangOpts().CPlusPlus11 ? 8188 diag::warn_cxx98_compat_explicit_conversion_functions : 8189 diag::ext_explicit_conversion_functions) 8190 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 8191 } 8192 8193 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8194 /// the declaration of the given C++ conversion function. This routine 8195 /// is responsible for recording the conversion function in the C++ 8196 /// class, if possible. 8197 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8198 assert(Conversion && "Expected to receive a conversion function declaration"); 8199 8200 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8201 8202 // Make sure we aren't redeclaring the conversion function. 8203 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8204 8205 // C++ [class.conv.fct]p1: 8206 // [...] A conversion function is never used to convert a 8207 // (possibly cv-qualified) object to the (possibly cv-qualified) 8208 // same object type (or a reference to it), to a (possibly 8209 // cv-qualified) base class of that type (or a reference to it), 8210 // or to (possibly cv-qualified) void. 8211 // FIXME: Suppress this warning if the conversion function ends up being a 8212 // virtual function that overrides a virtual function in a base class. 8213 QualType ClassType 8214 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8215 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8216 ConvType = ConvTypeRef->getPointeeType(); 8217 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8218 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8219 /* Suppress diagnostics for instantiations. */; 8220 else if (ConvType->isRecordType()) { 8221 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8222 if (ConvType == ClassType) 8223 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8224 << ClassType; 8225 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8226 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8227 << ClassType << ConvType; 8228 } else if (ConvType->isVoidType()) { 8229 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8230 << ClassType << ConvType; 8231 } 8232 8233 if (FunctionTemplateDecl *ConversionTemplate 8234 = Conversion->getDescribedFunctionTemplate()) 8235 return ConversionTemplate; 8236 8237 return Conversion; 8238 } 8239 8240 namespace { 8241 /// Utility class to accumulate and print a diagnostic listing the invalid 8242 /// specifier(s) on a declaration. 8243 struct BadSpecifierDiagnoser { 8244 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8245 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8246 ~BadSpecifierDiagnoser() { 8247 Diagnostic << Specifiers; 8248 } 8249 8250 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8251 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8252 } 8253 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8254 return check(SpecLoc, 8255 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8256 } 8257 void check(SourceLocation SpecLoc, const char *Spec) { 8258 if (SpecLoc.isInvalid()) return; 8259 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8260 if (!Specifiers.empty()) Specifiers += " "; 8261 Specifiers += Spec; 8262 } 8263 8264 Sema &S; 8265 Sema::SemaDiagnosticBuilder Diagnostic; 8266 std::string Specifiers; 8267 }; 8268 } 8269 8270 /// Check the validity of a declarator that we parsed for a deduction-guide. 8271 /// These aren't actually declarators in the grammar, so we need to check that 8272 /// the user didn't specify any pieces that are not part of the deduction-guide 8273 /// grammar. 8274 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8275 StorageClass &SC) { 8276 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8277 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8278 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8279 8280 // C++ [temp.deduct.guide]p3: 8281 // A deduction-gide shall be declared in the same scope as the 8282 // corresponding class template. 8283 if (!CurContext->getRedeclContext()->Equals( 8284 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8285 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8286 << GuidedTemplateDecl; 8287 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8288 } 8289 8290 auto &DS = D.getMutableDeclSpec(); 8291 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8292 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8293 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8294 DS.isNoreturnSpecified() || DS.isConstexprSpecified() || 8295 DS.isConceptSpecified()) { 8296 BadSpecifierDiagnoser Diagnoser( 8297 *this, D.getIdentifierLoc(), 8298 diag::err_deduction_guide_invalid_specifier); 8299 8300 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8301 DS.ClearStorageClassSpecs(); 8302 SC = SC_None; 8303 8304 // 'explicit' is permitted. 8305 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8306 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8307 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8308 Diagnoser.check(DS.getConceptSpecLoc(), "concept"); 8309 DS.ClearConstexprSpec(); 8310 DS.ClearConceptSpec(); 8311 8312 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8313 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8314 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8315 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8316 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8317 DS.ClearTypeQualifiers(); 8318 8319 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8320 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8321 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8322 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8323 DS.ClearTypeSpecType(); 8324 } 8325 8326 if (D.isInvalidType()) 8327 return; 8328 8329 // Check the declarator is simple enough. 8330 bool FoundFunction = false; 8331 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 8332 if (Chunk.Kind == DeclaratorChunk::Paren) 8333 continue; 8334 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 8335 Diag(D.getDeclSpec().getLocStart(), 8336 diag::err_deduction_guide_with_complex_decl) 8337 << D.getSourceRange(); 8338 break; 8339 } 8340 if (!Chunk.Fun.hasTrailingReturnType()) { 8341 Diag(D.getName().getLocStart(), 8342 diag::err_deduction_guide_no_trailing_return_type); 8343 break; 8344 } 8345 8346 // Check that the return type is written as a specialization of 8347 // the template specified as the deduction-guide's name. 8348 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 8349 TypeSourceInfo *TSI = nullptr; 8350 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 8351 assert(TSI && "deduction guide has valid type but invalid return type?"); 8352 bool AcceptableReturnType = false; 8353 bool MightInstantiateToSpecialization = false; 8354 if (auto RetTST = 8355 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 8356 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 8357 bool TemplateMatches = 8358 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 8359 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 8360 AcceptableReturnType = true; 8361 else { 8362 // This could still instantiate to the right type, unless we know it 8363 // names the wrong class template. 8364 auto *TD = SpecifiedName.getAsTemplateDecl(); 8365 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 8366 !TemplateMatches); 8367 } 8368 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 8369 MightInstantiateToSpecialization = true; 8370 } 8371 8372 if (!AcceptableReturnType) { 8373 Diag(TSI->getTypeLoc().getLocStart(), 8374 diag::err_deduction_guide_bad_trailing_return_type) 8375 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization 8376 << TSI->getTypeLoc().getSourceRange(); 8377 } 8378 8379 // Keep going to check that we don't have any inner declarator pieces (we 8380 // could still have a function returning a pointer to a function). 8381 FoundFunction = true; 8382 } 8383 8384 if (D.isFunctionDefinition()) 8385 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 8386 } 8387 8388 //===----------------------------------------------------------------------===// 8389 // Namespace Handling 8390 //===----------------------------------------------------------------------===// 8391 8392 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 8393 /// reopened. 8394 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 8395 SourceLocation Loc, 8396 IdentifierInfo *II, bool *IsInline, 8397 NamespaceDecl *PrevNS) { 8398 assert(*IsInline != PrevNS->isInline()); 8399 8400 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 8401 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 8402 // inline namespaces, with the intention of bringing names into namespace std. 8403 // 8404 // We support this just well enough to get that case working; this is not 8405 // sufficient to support reopening namespaces as inline in general. 8406 if (*IsInline && II && II->getName().startswith("__atomic") && 8407 S.getSourceManager().isInSystemHeader(Loc)) { 8408 // Mark all prior declarations of the namespace as inline. 8409 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 8410 NS = NS->getPreviousDecl()) 8411 NS->setInline(*IsInline); 8412 // Patch up the lookup table for the containing namespace. This isn't really 8413 // correct, but it's good enough for this particular case. 8414 for (auto *I : PrevNS->decls()) 8415 if (auto *ND = dyn_cast<NamedDecl>(I)) 8416 PrevNS->getParent()->makeDeclVisibleInContext(ND); 8417 return; 8418 } 8419 8420 if (PrevNS->isInline()) 8421 // The user probably just forgot the 'inline', so suggest that it 8422 // be added back. 8423 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 8424 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 8425 else 8426 S.Diag(Loc, diag::err_inline_namespace_mismatch); 8427 8428 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 8429 *IsInline = PrevNS->isInline(); 8430 } 8431 8432 /// ActOnStartNamespaceDef - This is called at the start of a namespace 8433 /// definition. 8434 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 8435 SourceLocation InlineLoc, 8436 SourceLocation NamespaceLoc, 8437 SourceLocation IdentLoc, 8438 IdentifierInfo *II, 8439 SourceLocation LBrace, 8440 AttributeList *AttrList, 8441 UsingDirectiveDecl *&UD) { 8442 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 8443 // For anonymous namespace, take the location of the left brace. 8444 SourceLocation Loc = II ? IdentLoc : LBrace; 8445 bool IsInline = InlineLoc.isValid(); 8446 bool IsInvalid = false; 8447 bool IsStd = false; 8448 bool AddToKnown = false; 8449 Scope *DeclRegionScope = NamespcScope->getParent(); 8450 8451 NamespaceDecl *PrevNS = nullptr; 8452 if (II) { 8453 // C++ [namespace.def]p2: 8454 // The identifier in an original-namespace-definition shall not 8455 // have been previously defined in the declarative region in 8456 // which the original-namespace-definition appears. The 8457 // identifier in an original-namespace-definition is the name of 8458 // the namespace. Subsequently in that declarative region, it is 8459 // treated as an original-namespace-name. 8460 // 8461 // Since namespace names are unique in their scope, and we don't 8462 // look through using directives, just look for any ordinary names 8463 // as if by qualified name lookup. 8464 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration); 8465 LookupQualifiedName(R, CurContext->getRedeclContext()); 8466 NamedDecl *PrevDecl = 8467 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 8468 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 8469 8470 if (PrevNS) { 8471 // This is an extended namespace definition. 8472 if (IsInline != PrevNS->isInline()) 8473 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 8474 &IsInline, PrevNS); 8475 } else if (PrevDecl) { 8476 // This is an invalid name redefinition. 8477 Diag(Loc, diag::err_redefinition_different_kind) 8478 << II; 8479 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8480 IsInvalid = true; 8481 // Continue on to push Namespc as current DeclContext and return it. 8482 } else if (II->isStr("std") && 8483 CurContext->getRedeclContext()->isTranslationUnit()) { 8484 // This is the first "real" definition of the namespace "std", so update 8485 // our cache of the "std" namespace to point at this definition. 8486 PrevNS = getStdNamespace(); 8487 IsStd = true; 8488 AddToKnown = !IsInline; 8489 } else { 8490 // We've seen this namespace for the first time. 8491 AddToKnown = !IsInline; 8492 } 8493 } else { 8494 // Anonymous namespaces. 8495 8496 // Determine whether the parent already has an anonymous namespace. 8497 DeclContext *Parent = CurContext->getRedeclContext(); 8498 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8499 PrevNS = TU->getAnonymousNamespace(); 8500 } else { 8501 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 8502 PrevNS = ND->getAnonymousNamespace(); 8503 } 8504 8505 if (PrevNS && IsInline != PrevNS->isInline()) 8506 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 8507 &IsInline, PrevNS); 8508 } 8509 8510 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 8511 StartLoc, Loc, II, PrevNS); 8512 if (IsInvalid) 8513 Namespc->setInvalidDecl(); 8514 8515 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 8516 AddPragmaAttributes(DeclRegionScope, Namespc); 8517 8518 // FIXME: Should we be merging attributes? 8519 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 8520 PushNamespaceVisibilityAttr(Attr, Loc); 8521 8522 if (IsStd) 8523 StdNamespace = Namespc; 8524 if (AddToKnown) 8525 KnownNamespaces[Namespc] = false; 8526 8527 if (II) { 8528 PushOnScopeChains(Namespc, DeclRegionScope); 8529 } else { 8530 // Link the anonymous namespace into its parent. 8531 DeclContext *Parent = CurContext->getRedeclContext(); 8532 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 8533 TU->setAnonymousNamespace(Namespc); 8534 } else { 8535 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 8536 } 8537 8538 CurContext->addDecl(Namespc); 8539 8540 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 8541 // behaves as if it were replaced by 8542 // namespace unique { /* empty body */ } 8543 // using namespace unique; 8544 // namespace unique { namespace-body } 8545 // where all occurrences of 'unique' in a translation unit are 8546 // replaced by the same identifier and this identifier differs 8547 // from all other identifiers in the entire program. 8548 8549 // We just create the namespace with an empty name and then add an 8550 // implicit using declaration, just like the standard suggests. 8551 // 8552 // CodeGen enforces the "universally unique" aspect by giving all 8553 // declarations semantically contained within an anonymous 8554 // namespace internal linkage. 8555 8556 if (!PrevNS) { 8557 UD = UsingDirectiveDecl::Create(Context, Parent, 8558 /* 'using' */ LBrace, 8559 /* 'namespace' */ SourceLocation(), 8560 /* qualifier */ NestedNameSpecifierLoc(), 8561 /* identifier */ SourceLocation(), 8562 Namespc, 8563 /* Ancestor */ Parent); 8564 UD->setImplicit(); 8565 Parent->addDecl(UD); 8566 } 8567 } 8568 8569 ActOnDocumentableDecl(Namespc); 8570 8571 // Although we could have an invalid decl (i.e. the namespace name is a 8572 // redefinition), push it as current DeclContext and try to continue parsing. 8573 // FIXME: We should be able to push Namespc here, so that the each DeclContext 8574 // for the namespace has the declarations that showed up in that particular 8575 // namespace definition. 8576 PushDeclContext(NamespcScope, Namespc); 8577 return Namespc; 8578 } 8579 8580 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 8581 /// is a namespace alias, returns the namespace it points to. 8582 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 8583 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 8584 return AD->getNamespace(); 8585 return dyn_cast_or_null<NamespaceDecl>(D); 8586 } 8587 8588 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 8589 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 8590 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 8591 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 8592 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 8593 Namespc->setRBraceLoc(RBrace); 8594 PopDeclContext(); 8595 if (Namespc->hasAttr<VisibilityAttr>()) 8596 PopPragmaVisibility(true, RBrace); 8597 } 8598 8599 CXXRecordDecl *Sema::getStdBadAlloc() const { 8600 return cast_or_null<CXXRecordDecl>( 8601 StdBadAlloc.get(Context.getExternalSource())); 8602 } 8603 8604 EnumDecl *Sema::getStdAlignValT() const { 8605 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 8606 } 8607 8608 NamespaceDecl *Sema::getStdNamespace() const { 8609 return cast_or_null<NamespaceDecl>( 8610 StdNamespace.get(Context.getExternalSource())); 8611 } 8612 8613 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 8614 if (!StdExperimentalNamespaceCache) { 8615 if (auto Std = getStdNamespace()) { 8616 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 8617 SourceLocation(), LookupNamespaceName); 8618 if (!LookupQualifiedName(Result, Std) || 8619 !(StdExperimentalNamespaceCache = 8620 Result.getAsSingle<NamespaceDecl>())) 8621 Result.suppressDiagnostics(); 8622 } 8623 } 8624 return StdExperimentalNamespaceCache; 8625 } 8626 8627 /// \brief Retrieve the special "std" namespace, which may require us to 8628 /// implicitly define the namespace. 8629 NamespaceDecl *Sema::getOrCreateStdNamespace() { 8630 if (!StdNamespace) { 8631 // The "std" namespace has not yet been defined, so build one implicitly. 8632 StdNamespace = NamespaceDecl::Create(Context, 8633 Context.getTranslationUnitDecl(), 8634 /*Inline=*/false, 8635 SourceLocation(), SourceLocation(), 8636 &PP.getIdentifierTable().get("std"), 8637 /*PrevDecl=*/nullptr); 8638 getStdNamespace()->setImplicit(true); 8639 } 8640 8641 return getStdNamespace(); 8642 } 8643 8644 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 8645 assert(getLangOpts().CPlusPlus && 8646 "Looking for std::initializer_list outside of C++."); 8647 8648 // We're looking for implicit instantiations of 8649 // template <typename E> class std::initializer_list. 8650 8651 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 8652 return false; 8653 8654 ClassTemplateDecl *Template = nullptr; 8655 const TemplateArgument *Arguments = nullptr; 8656 8657 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8658 8659 ClassTemplateSpecializationDecl *Specialization = 8660 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 8661 if (!Specialization) 8662 return false; 8663 8664 Template = Specialization->getSpecializedTemplate(); 8665 Arguments = Specialization->getTemplateArgs().data(); 8666 } else if (const TemplateSpecializationType *TST = 8667 Ty->getAs<TemplateSpecializationType>()) { 8668 Template = dyn_cast_or_null<ClassTemplateDecl>( 8669 TST->getTemplateName().getAsTemplateDecl()); 8670 Arguments = TST->getArgs(); 8671 } 8672 if (!Template) 8673 return false; 8674 8675 if (!StdInitializerList) { 8676 // Haven't recognized std::initializer_list yet, maybe this is it. 8677 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 8678 if (TemplateClass->getIdentifier() != 8679 &PP.getIdentifierTable().get("initializer_list") || 8680 !getStdNamespace()->InEnclosingNamespaceSetOf( 8681 TemplateClass->getDeclContext())) 8682 return false; 8683 // This is a template called std::initializer_list, but is it the right 8684 // template? 8685 TemplateParameterList *Params = Template->getTemplateParameters(); 8686 if (Params->getMinRequiredArguments() != 1) 8687 return false; 8688 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 8689 return false; 8690 8691 // It's the right template. 8692 StdInitializerList = Template; 8693 } 8694 8695 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 8696 return false; 8697 8698 // This is an instance of std::initializer_list. Find the argument type. 8699 if (Element) 8700 *Element = Arguments[0].getAsType(); 8701 return true; 8702 } 8703 8704 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 8705 NamespaceDecl *Std = S.getStdNamespace(); 8706 if (!Std) { 8707 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8708 return nullptr; 8709 } 8710 8711 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 8712 Loc, Sema::LookupOrdinaryName); 8713 if (!S.LookupQualifiedName(Result, Std)) { 8714 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 8715 return nullptr; 8716 } 8717 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 8718 if (!Template) { 8719 Result.suppressDiagnostics(); 8720 // We found something weird. Complain about the first thing we found. 8721 NamedDecl *Found = *Result.begin(); 8722 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 8723 return nullptr; 8724 } 8725 8726 // We found some template called std::initializer_list. Now verify that it's 8727 // correct. 8728 TemplateParameterList *Params = Template->getTemplateParameters(); 8729 if (Params->getMinRequiredArguments() != 1 || 8730 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 8731 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 8732 return nullptr; 8733 } 8734 8735 return Template; 8736 } 8737 8738 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 8739 if (!StdInitializerList) { 8740 StdInitializerList = LookupStdInitializerList(*this, Loc); 8741 if (!StdInitializerList) 8742 return QualType(); 8743 } 8744 8745 TemplateArgumentListInfo Args(Loc, Loc); 8746 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 8747 Context.getTrivialTypeSourceInfo(Element, 8748 Loc))); 8749 return Context.getCanonicalType( 8750 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 8751 } 8752 8753 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 8754 // C++ [dcl.init.list]p2: 8755 // A constructor is an initializer-list constructor if its first parameter 8756 // is of type std::initializer_list<E> or reference to possibly cv-qualified 8757 // std::initializer_list<E> for some type E, and either there are no other 8758 // parameters or else all other parameters have default arguments. 8759 if (Ctor->getNumParams() < 1 || 8760 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 8761 return false; 8762 8763 QualType ArgType = Ctor->getParamDecl(0)->getType(); 8764 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 8765 ArgType = RT->getPointeeType().getUnqualifiedType(); 8766 8767 return isStdInitializerList(ArgType, nullptr); 8768 } 8769 8770 /// \brief Determine whether a using statement is in a context where it will be 8771 /// apply in all contexts. 8772 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 8773 switch (CurContext->getDeclKind()) { 8774 case Decl::TranslationUnit: 8775 return true; 8776 case Decl::LinkageSpec: 8777 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 8778 default: 8779 return false; 8780 } 8781 } 8782 8783 namespace { 8784 8785 // Callback to only accept typo corrections that are namespaces. 8786 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 8787 public: 8788 bool ValidateCandidate(const TypoCorrection &candidate) override { 8789 if (NamedDecl *ND = candidate.getCorrectionDecl()) 8790 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 8791 return false; 8792 } 8793 }; 8794 8795 } 8796 8797 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 8798 CXXScopeSpec &SS, 8799 SourceLocation IdentLoc, 8800 IdentifierInfo *Ident) { 8801 R.clear(); 8802 if (TypoCorrection Corrected = 8803 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 8804 llvm::make_unique<NamespaceValidatorCCC>(), 8805 Sema::CTK_ErrorRecovery)) { 8806 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 8807 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 8808 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 8809 Ident->getName().equals(CorrectedStr); 8810 S.diagnoseTypo(Corrected, 8811 S.PDiag(diag::err_using_directive_member_suggest) 8812 << Ident << DC << DroppedSpecifier << SS.getRange(), 8813 S.PDiag(diag::note_namespace_defined_here)); 8814 } else { 8815 S.diagnoseTypo(Corrected, 8816 S.PDiag(diag::err_using_directive_suggest) << Ident, 8817 S.PDiag(diag::note_namespace_defined_here)); 8818 } 8819 R.addDecl(Corrected.getFoundDecl()); 8820 return true; 8821 } 8822 return false; 8823 } 8824 8825 Decl *Sema::ActOnUsingDirective(Scope *S, 8826 SourceLocation UsingLoc, 8827 SourceLocation NamespcLoc, 8828 CXXScopeSpec &SS, 8829 SourceLocation IdentLoc, 8830 IdentifierInfo *NamespcName, 8831 AttributeList *AttrList) { 8832 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 8833 assert(NamespcName && "Invalid NamespcName."); 8834 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 8835 8836 // This can only happen along a recovery path. 8837 while (S->isTemplateParamScope()) 8838 S = S->getParent(); 8839 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8840 8841 UsingDirectiveDecl *UDir = nullptr; 8842 NestedNameSpecifier *Qualifier = nullptr; 8843 if (SS.isSet()) 8844 Qualifier = SS.getScopeRep(); 8845 8846 // Lookup namespace name. 8847 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 8848 LookupParsedName(R, S, &SS); 8849 if (R.isAmbiguous()) 8850 return nullptr; 8851 8852 if (R.empty()) { 8853 R.clear(); 8854 // Allow "using namespace std;" or "using namespace ::std;" even if 8855 // "std" hasn't been defined yet, for GCC compatibility. 8856 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 8857 NamespcName->isStr("std")) { 8858 Diag(IdentLoc, diag::ext_using_undefined_std); 8859 R.addDecl(getOrCreateStdNamespace()); 8860 R.resolveKind(); 8861 } 8862 // Otherwise, attempt typo correction. 8863 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 8864 } 8865 8866 if (!R.empty()) { 8867 NamedDecl *Named = R.getRepresentativeDecl(); 8868 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 8869 assert(NS && "expected namespace decl"); 8870 8871 // The use of a nested name specifier may trigger deprecation warnings. 8872 DiagnoseUseOfDecl(Named, IdentLoc); 8873 8874 // C++ [namespace.udir]p1: 8875 // A using-directive specifies that the names in the nominated 8876 // namespace can be used in the scope in which the 8877 // using-directive appears after the using-directive. During 8878 // unqualified name lookup (3.4.1), the names appear as if they 8879 // were declared in the nearest enclosing namespace which 8880 // contains both the using-directive and the nominated 8881 // namespace. [Note: in this context, "contains" means "contains 8882 // directly or indirectly". ] 8883 8884 // Find enclosing context containing both using-directive and 8885 // nominated namespace. 8886 DeclContext *CommonAncestor = cast<DeclContext>(NS); 8887 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 8888 CommonAncestor = CommonAncestor->getParent(); 8889 8890 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 8891 SS.getWithLocInContext(Context), 8892 IdentLoc, Named, CommonAncestor); 8893 8894 if (IsUsingDirectiveInToplevelContext(CurContext) && 8895 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 8896 Diag(IdentLoc, diag::warn_using_directive_in_header); 8897 } 8898 8899 PushUsingDirective(S, UDir); 8900 } else { 8901 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8902 } 8903 8904 if (UDir) 8905 ProcessDeclAttributeList(S, UDir, AttrList); 8906 8907 return UDir; 8908 } 8909 8910 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 8911 // If the scope has an associated entity and the using directive is at 8912 // namespace or translation unit scope, add the UsingDirectiveDecl into 8913 // its lookup structure so qualified name lookup can find it. 8914 DeclContext *Ctx = S->getEntity(); 8915 if (Ctx && !Ctx->isFunctionOrMethod()) 8916 Ctx->addDecl(UDir); 8917 else 8918 // Otherwise, it is at block scope. The using-directives will affect lookup 8919 // only to the end of the scope. 8920 S->PushUsingDirective(UDir); 8921 } 8922 8923 8924 Decl *Sema::ActOnUsingDeclaration(Scope *S, 8925 AccessSpecifier AS, 8926 SourceLocation UsingLoc, 8927 SourceLocation TypenameLoc, 8928 CXXScopeSpec &SS, 8929 UnqualifiedId &Name, 8930 SourceLocation EllipsisLoc, 8931 AttributeList *AttrList) { 8932 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 8933 8934 if (SS.isEmpty()) { 8935 Diag(Name.getLocStart(), diag::err_using_requires_qualname); 8936 return nullptr; 8937 } 8938 8939 switch (Name.getKind()) { 8940 case UnqualifiedId::IK_ImplicitSelfParam: 8941 case UnqualifiedId::IK_Identifier: 8942 case UnqualifiedId::IK_OperatorFunctionId: 8943 case UnqualifiedId::IK_LiteralOperatorId: 8944 case UnqualifiedId::IK_ConversionFunctionId: 8945 break; 8946 8947 case UnqualifiedId::IK_ConstructorName: 8948 case UnqualifiedId::IK_ConstructorTemplateId: 8949 // C++11 inheriting constructors. 8950 Diag(Name.getLocStart(), 8951 getLangOpts().CPlusPlus11 ? 8952 diag::warn_cxx98_compat_using_decl_constructor : 8953 diag::err_using_decl_constructor) 8954 << SS.getRange(); 8955 8956 if (getLangOpts().CPlusPlus11) break; 8957 8958 return nullptr; 8959 8960 case UnqualifiedId::IK_DestructorName: 8961 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 8962 << SS.getRange(); 8963 return nullptr; 8964 8965 case UnqualifiedId::IK_TemplateId: 8966 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 8967 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 8968 return nullptr; 8969 8970 case UnqualifiedId::IK_DeductionGuideName: 8971 llvm_unreachable("cannot parse qualified deduction guide name"); 8972 } 8973 8974 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 8975 DeclarationName TargetName = TargetNameInfo.getName(); 8976 if (!TargetName) 8977 return nullptr; 8978 8979 // Warn about access declarations. 8980 if (UsingLoc.isInvalid()) { 8981 Diag(Name.getLocStart(), 8982 getLangOpts().CPlusPlus11 ? diag::err_access_decl 8983 : diag::warn_access_decl_deprecated) 8984 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 8985 } 8986 8987 if (EllipsisLoc.isInvalid()) { 8988 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 8989 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 8990 return nullptr; 8991 } else { 8992 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 8993 !TargetNameInfo.containsUnexpandedParameterPack()) { 8994 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 8995 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 8996 EllipsisLoc = SourceLocation(); 8997 } 8998 } 8999 9000 NamedDecl *UD = 9001 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9002 SS, TargetNameInfo, EllipsisLoc, AttrList, 9003 /*IsInstantiation*/false); 9004 if (UD) 9005 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9006 9007 return UD; 9008 } 9009 9010 /// \brief Determine whether a using declaration considers the given 9011 /// declarations as "equivalent", e.g., if they are redeclarations of 9012 /// the same entity or are both typedefs of the same type. 9013 static bool 9014 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9015 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9016 return true; 9017 9018 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9019 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9020 return Context.hasSameType(TD1->getUnderlyingType(), 9021 TD2->getUnderlyingType()); 9022 9023 return false; 9024 } 9025 9026 9027 /// Determines whether to create a using shadow decl for a particular 9028 /// decl, given the set of decls existing prior to this using lookup. 9029 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9030 const LookupResult &Previous, 9031 UsingShadowDecl *&PrevShadow) { 9032 // Diagnose finding a decl which is not from a base class of the 9033 // current class. We do this now because there are cases where this 9034 // function will silently decide not to build a shadow decl, which 9035 // will pre-empt further diagnostics. 9036 // 9037 // We don't need to do this in C++11 because we do the check once on 9038 // the qualifier. 9039 // 9040 // FIXME: diagnose the following if we care enough: 9041 // struct A { int foo; }; 9042 // struct B : A { using A::foo; }; 9043 // template <class T> struct C : A {}; 9044 // template <class T> struct D : C<T> { using B::foo; } // <--- 9045 // This is invalid (during instantiation) in C++03 because B::foo 9046 // resolves to the using decl in B, which is not a base class of D<T>. 9047 // We can't diagnose it immediately because C<T> is an unknown 9048 // specialization. The UsingShadowDecl in D<T> then points directly 9049 // to A::foo, which will look well-formed when we instantiate. 9050 // The right solution is to not collapse the shadow-decl chain. 9051 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9052 DeclContext *OrigDC = Orig->getDeclContext(); 9053 9054 // Handle enums and anonymous structs. 9055 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9056 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9057 while (OrigRec->isAnonymousStructOrUnion()) 9058 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9059 9060 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9061 if (OrigDC == CurContext) { 9062 Diag(Using->getLocation(), 9063 diag::err_using_decl_nested_name_specifier_is_current_class) 9064 << Using->getQualifierLoc().getSourceRange(); 9065 Diag(Orig->getLocation(), diag::note_using_decl_target); 9066 Using->setInvalidDecl(); 9067 return true; 9068 } 9069 9070 Diag(Using->getQualifierLoc().getBeginLoc(), 9071 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9072 << Using->getQualifier() 9073 << cast<CXXRecordDecl>(CurContext) 9074 << Using->getQualifierLoc().getSourceRange(); 9075 Diag(Orig->getLocation(), diag::note_using_decl_target); 9076 Using->setInvalidDecl(); 9077 return true; 9078 } 9079 } 9080 9081 if (Previous.empty()) return false; 9082 9083 NamedDecl *Target = Orig; 9084 if (isa<UsingShadowDecl>(Target)) 9085 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9086 9087 // If the target happens to be one of the previous declarations, we 9088 // don't have a conflict. 9089 // 9090 // FIXME: but we might be increasing its access, in which case we 9091 // should redeclare it. 9092 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9093 bool FoundEquivalentDecl = false; 9094 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9095 I != E; ++I) { 9096 NamedDecl *D = (*I)->getUnderlyingDecl(); 9097 // We can have UsingDecls in our Previous results because we use the same 9098 // LookupResult for checking whether the UsingDecl itself is a valid 9099 // redeclaration. 9100 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9101 continue; 9102 9103 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9104 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9105 PrevShadow = Shadow; 9106 FoundEquivalentDecl = true; 9107 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9108 // We don't conflict with an existing using shadow decl of an equivalent 9109 // declaration, but we're not a redeclaration of it. 9110 FoundEquivalentDecl = true; 9111 } 9112 9113 if (isVisible(D)) 9114 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9115 } 9116 9117 if (FoundEquivalentDecl) 9118 return false; 9119 9120 if (FunctionDecl *FD = Target->getAsFunction()) { 9121 NamedDecl *OldDecl = nullptr; 9122 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9123 /*IsForUsingDecl*/ true)) { 9124 case Ovl_Overload: 9125 return false; 9126 9127 case Ovl_NonFunction: 9128 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9129 break; 9130 9131 // We found a decl with the exact signature. 9132 case Ovl_Match: 9133 // If we're in a record, we want to hide the target, so we 9134 // return true (without a diagnostic) to tell the caller not to 9135 // build a shadow decl. 9136 if (CurContext->isRecord()) 9137 return true; 9138 9139 // If we're not in a record, this is an error. 9140 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9141 break; 9142 } 9143 9144 Diag(Target->getLocation(), diag::note_using_decl_target); 9145 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9146 Using->setInvalidDecl(); 9147 return true; 9148 } 9149 9150 // Target is not a function. 9151 9152 if (isa<TagDecl>(Target)) { 9153 // No conflict between a tag and a non-tag. 9154 if (!Tag) return false; 9155 9156 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9157 Diag(Target->getLocation(), diag::note_using_decl_target); 9158 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9159 Using->setInvalidDecl(); 9160 return true; 9161 } 9162 9163 // No conflict between a tag and a non-tag. 9164 if (!NonTag) return false; 9165 9166 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9167 Diag(Target->getLocation(), diag::note_using_decl_target); 9168 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9169 Using->setInvalidDecl(); 9170 return true; 9171 } 9172 9173 /// Determine whether a direct base class is a virtual base class. 9174 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9175 if (!Derived->getNumVBases()) 9176 return false; 9177 for (auto &B : Derived->bases()) 9178 if (B.getType()->getAsCXXRecordDecl() == Base) 9179 return B.isVirtual(); 9180 llvm_unreachable("not a direct base class"); 9181 } 9182 9183 /// Builds a shadow declaration corresponding to a 'using' declaration. 9184 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9185 UsingDecl *UD, 9186 NamedDecl *Orig, 9187 UsingShadowDecl *PrevDecl) { 9188 // If we resolved to another shadow declaration, just coalesce them. 9189 NamedDecl *Target = Orig; 9190 if (isa<UsingShadowDecl>(Target)) { 9191 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9192 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 9193 } 9194 9195 NamedDecl *NonTemplateTarget = Target; 9196 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 9197 NonTemplateTarget = TargetTD->getTemplatedDecl(); 9198 9199 UsingShadowDecl *Shadow; 9200 if (isa<CXXConstructorDecl>(NonTemplateTarget)) { 9201 bool IsVirtualBase = 9202 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 9203 UD->getQualifier()->getAsRecordDecl()); 9204 Shadow = ConstructorUsingShadowDecl::Create( 9205 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 9206 } else { 9207 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 9208 Target); 9209 } 9210 UD->addShadowDecl(Shadow); 9211 9212 Shadow->setAccess(UD->getAccess()); 9213 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 9214 Shadow->setInvalidDecl(); 9215 9216 Shadow->setPreviousDecl(PrevDecl); 9217 9218 if (S) 9219 PushOnScopeChains(Shadow, S); 9220 else 9221 CurContext->addDecl(Shadow); 9222 9223 9224 return Shadow; 9225 } 9226 9227 /// Hides a using shadow declaration. This is required by the current 9228 /// using-decl implementation when a resolvable using declaration in a 9229 /// class is followed by a declaration which would hide or override 9230 /// one or more of the using decl's targets; for example: 9231 /// 9232 /// struct Base { void foo(int); }; 9233 /// struct Derived : Base { 9234 /// using Base::foo; 9235 /// void foo(int); 9236 /// }; 9237 /// 9238 /// The governing language is C++03 [namespace.udecl]p12: 9239 /// 9240 /// When a using-declaration brings names from a base class into a 9241 /// derived class scope, member functions in the derived class 9242 /// override and/or hide member functions with the same name and 9243 /// parameter types in a base class (rather than conflicting). 9244 /// 9245 /// There are two ways to implement this: 9246 /// (1) optimistically create shadow decls when they're not hidden 9247 /// by existing declarations, or 9248 /// (2) don't create any shadow decls (or at least don't make them 9249 /// visible) until we've fully parsed/instantiated the class. 9250 /// The problem with (1) is that we might have to retroactively remove 9251 /// a shadow decl, which requires several O(n) operations because the 9252 /// decl structures are (very reasonably) not designed for removal. 9253 /// (2) avoids this but is very fiddly and phase-dependent. 9254 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 9255 if (Shadow->getDeclName().getNameKind() == 9256 DeclarationName::CXXConversionFunctionName) 9257 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 9258 9259 // Remove it from the DeclContext... 9260 Shadow->getDeclContext()->removeDecl(Shadow); 9261 9262 // ...and the scope, if applicable... 9263 if (S) { 9264 S->RemoveDecl(Shadow); 9265 IdResolver.RemoveDecl(Shadow); 9266 } 9267 9268 // ...and the using decl. 9269 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 9270 9271 // TODO: complain somehow if Shadow was used. It shouldn't 9272 // be possible for this to happen, because...? 9273 } 9274 9275 /// Find the base specifier for a base class with the given type. 9276 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 9277 QualType DesiredBase, 9278 bool &AnyDependentBases) { 9279 // Check whether the named type is a direct base class. 9280 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 9281 for (auto &Base : Derived->bases()) { 9282 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 9283 if (CanonicalDesiredBase == BaseType) 9284 return &Base; 9285 if (BaseType->isDependentType()) 9286 AnyDependentBases = true; 9287 } 9288 return nullptr; 9289 } 9290 9291 namespace { 9292 class UsingValidatorCCC : public CorrectionCandidateCallback { 9293 public: 9294 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 9295 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 9296 : HasTypenameKeyword(HasTypenameKeyword), 9297 IsInstantiation(IsInstantiation), OldNNS(NNS), 9298 RequireMemberOf(RequireMemberOf) {} 9299 9300 bool ValidateCandidate(const TypoCorrection &Candidate) override { 9301 NamedDecl *ND = Candidate.getCorrectionDecl(); 9302 9303 // Keywords are not valid here. 9304 if (!ND || isa<NamespaceDecl>(ND)) 9305 return false; 9306 9307 // Completely unqualified names are invalid for a 'using' declaration. 9308 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 9309 return false; 9310 9311 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 9312 // reject. 9313 9314 if (RequireMemberOf) { 9315 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9316 if (FoundRecord && FoundRecord->isInjectedClassName()) { 9317 // No-one ever wants a using-declaration to name an injected-class-name 9318 // of a base class, unless they're declaring an inheriting constructor. 9319 ASTContext &Ctx = ND->getASTContext(); 9320 if (!Ctx.getLangOpts().CPlusPlus11) 9321 return false; 9322 QualType FoundType = Ctx.getRecordType(FoundRecord); 9323 9324 // Check that the injected-class-name is named as a member of its own 9325 // type; we don't want to suggest 'using Derived::Base;', since that 9326 // means something else. 9327 NestedNameSpecifier *Specifier = 9328 Candidate.WillReplaceSpecifier() 9329 ? Candidate.getCorrectionSpecifier() 9330 : OldNNS; 9331 if (!Specifier->getAsType() || 9332 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 9333 return false; 9334 9335 // Check that this inheriting constructor declaration actually names a 9336 // direct base class of the current class. 9337 bool AnyDependentBases = false; 9338 if (!findDirectBaseWithType(RequireMemberOf, 9339 Ctx.getRecordType(FoundRecord), 9340 AnyDependentBases) && 9341 !AnyDependentBases) 9342 return false; 9343 } else { 9344 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 9345 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 9346 return false; 9347 9348 // FIXME: Check that the base class member is accessible? 9349 } 9350 } else { 9351 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 9352 if (FoundRecord && FoundRecord->isInjectedClassName()) 9353 return false; 9354 } 9355 9356 if (isa<TypeDecl>(ND)) 9357 return HasTypenameKeyword || !IsInstantiation; 9358 9359 return !HasTypenameKeyword; 9360 } 9361 9362 private: 9363 bool HasTypenameKeyword; 9364 bool IsInstantiation; 9365 NestedNameSpecifier *OldNNS; 9366 CXXRecordDecl *RequireMemberOf; 9367 }; 9368 } // end anonymous namespace 9369 9370 /// Builds a using declaration. 9371 /// 9372 /// \param IsInstantiation - Whether this call arises from an 9373 /// instantiation of an unresolved using declaration. We treat 9374 /// the lookup differently for these declarations. 9375 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 9376 SourceLocation UsingLoc, 9377 bool HasTypenameKeyword, 9378 SourceLocation TypenameLoc, 9379 CXXScopeSpec &SS, 9380 DeclarationNameInfo NameInfo, 9381 SourceLocation EllipsisLoc, 9382 AttributeList *AttrList, 9383 bool IsInstantiation) { 9384 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9385 SourceLocation IdentLoc = NameInfo.getLoc(); 9386 assert(IdentLoc.isValid() && "Invalid TargetName location."); 9387 9388 // FIXME: We ignore attributes for now. 9389 9390 // For an inheriting constructor declaration, the name of the using 9391 // declaration is the name of a constructor in this class, not in the 9392 // base class. 9393 DeclarationNameInfo UsingName = NameInfo; 9394 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 9395 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 9396 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9397 Context.getCanonicalType(Context.getRecordType(RD)))); 9398 9399 // Do the redeclaration lookup in the current scope. 9400 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 9401 ForRedeclaration); 9402 Previous.setHideTags(false); 9403 if (S) { 9404 LookupName(Previous, S); 9405 9406 // It is really dumb that we have to do this. 9407 LookupResult::Filter F = Previous.makeFilter(); 9408 while (F.hasNext()) { 9409 NamedDecl *D = F.next(); 9410 if (!isDeclInScope(D, CurContext, S)) 9411 F.erase(); 9412 // If we found a local extern declaration that's not ordinarily visible, 9413 // and this declaration is being added to a non-block scope, ignore it. 9414 // We're only checking for scope conflicts here, not also for violations 9415 // of the linkage rules. 9416 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 9417 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 9418 F.erase(); 9419 } 9420 F.done(); 9421 } else { 9422 assert(IsInstantiation && "no scope in non-instantiation"); 9423 if (CurContext->isRecord()) 9424 LookupQualifiedName(Previous, CurContext); 9425 else { 9426 // No redeclaration check is needed here; in non-member contexts we 9427 // diagnosed all possible conflicts with other using-declarations when 9428 // building the template: 9429 // 9430 // For a dependent non-type using declaration, the only valid case is 9431 // if we instantiate to a single enumerator. We check for conflicts 9432 // between shadow declarations we introduce, and we check in the template 9433 // definition for conflicts between a non-type using declaration and any 9434 // other declaration, which together covers all cases. 9435 // 9436 // A dependent typename using declaration will never successfully 9437 // instantiate, since it will always name a class member, so we reject 9438 // that in the template definition. 9439 } 9440 } 9441 9442 // Check for invalid redeclarations. 9443 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 9444 SS, IdentLoc, Previous)) 9445 return nullptr; 9446 9447 // Check for bad qualifiers. 9448 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 9449 IdentLoc)) 9450 return nullptr; 9451 9452 DeclContext *LookupContext = computeDeclContext(SS); 9453 NamedDecl *D; 9454 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9455 if (!LookupContext || EllipsisLoc.isValid()) { 9456 if (HasTypenameKeyword) { 9457 // FIXME: not all declaration name kinds are legal here 9458 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 9459 UsingLoc, TypenameLoc, 9460 QualifierLoc, 9461 IdentLoc, NameInfo.getName(), 9462 EllipsisLoc); 9463 } else { 9464 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 9465 QualifierLoc, NameInfo, EllipsisLoc); 9466 } 9467 D->setAccess(AS); 9468 CurContext->addDecl(D); 9469 return D; 9470 } 9471 9472 auto Build = [&](bool Invalid) { 9473 UsingDecl *UD = 9474 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 9475 UsingName, HasTypenameKeyword); 9476 UD->setAccess(AS); 9477 CurContext->addDecl(UD); 9478 UD->setInvalidDecl(Invalid); 9479 return UD; 9480 }; 9481 auto BuildInvalid = [&]{ return Build(true); }; 9482 auto BuildValid = [&]{ return Build(false); }; 9483 9484 if (RequireCompleteDeclContext(SS, LookupContext)) 9485 return BuildInvalid(); 9486 9487 // Look up the target name. 9488 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9489 9490 // Unlike most lookups, we don't always want to hide tag 9491 // declarations: tag names are visible through the using declaration 9492 // even if hidden by ordinary names, *except* in a dependent context 9493 // where it's important for the sanity of two-phase lookup. 9494 if (!IsInstantiation) 9495 R.setHideTags(false); 9496 9497 // For the purposes of this lookup, we have a base object type 9498 // equal to that of the current context. 9499 if (CurContext->isRecord()) { 9500 R.setBaseObjectType( 9501 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 9502 } 9503 9504 LookupQualifiedName(R, LookupContext); 9505 9506 // Try to correct typos if possible. If constructor name lookup finds no 9507 // results, that means the named class has no explicit constructors, and we 9508 // suppressed declaring implicit ones (probably because it's dependent or 9509 // invalid). 9510 if (R.empty() && 9511 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 9512 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 9513 // it will believe that glibc provides a ::gets in cases where it does not, 9514 // and will try to pull it into namespace std with a using-declaration. 9515 // Just ignore the using-declaration in that case. 9516 auto *II = NameInfo.getName().getAsIdentifierInfo(); 9517 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 9518 CurContext->isStdNamespace() && 9519 isa<TranslationUnitDecl>(LookupContext) && 9520 getSourceManager().isInSystemHeader(UsingLoc)) 9521 return nullptr; 9522 if (TypoCorrection Corrected = CorrectTypo( 9523 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 9524 llvm::make_unique<UsingValidatorCCC>( 9525 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 9526 dyn_cast<CXXRecordDecl>(CurContext)), 9527 CTK_ErrorRecovery)) { 9528 // We reject candidates where DroppedSpecifier == true, hence the 9529 // literal '0' below. 9530 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 9531 << NameInfo.getName() << LookupContext << 0 9532 << SS.getRange()); 9533 9534 // If we picked a correction with no attached Decl we can't do anything 9535 // useful with it, bail out. 9536 NamedDecl *ND = Corrected.getCorrectionDecl(); 9537 if (!ND) 9538 return BuildInvalid(); 9539 9540 // If we corrected to an inheriting constructor, handle it as one. 9541 auto *RD = dyn_cast<CXXRecordDecl>(ND); 9542 if (RD && RD->isInjectedClassName()) { 9543 // The parent of the injected class name is the class itself. 9544 RD = cast<CXXRecordDecl>(RD->getParent()); 9545 9546 // Fix up the information we'll use to build the using declaration. 9547 if (Corrected.WillReplaceSpecifier()) { 9548 NestedNameSpecifierLocBuilder Builder; 9549 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 9550 QualifierLoc.getSourceRange()); 9551 QualifierLoc = Builder.getWithLocInContext(Context); 9552 } 9553 9554 // In this case, the name we introduce is the name of a derived class 9555 // constructor. 9556 auto *CurClass = cast<CXXRecordDecl>(CurContext); 9557 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 9558 Context.getCanonicalType(Context.getRecordType(CurClass)))); 9559 UsingName.setNamedTypeInfo(nullptr); 9560 for (auto *Ctor : LookupConstructors(RD)) 9561 R.addDecl(Ctor); 9562 R.resolveKind(); 9563 } else { 9564 // FIXME: Pick up all the declarations if we found an overloaded 9565 // function. 9566 UsingName.setName(ND->getDeclName()); 9567 R.addDecl(ND); 9568 } 9569 } else { 9570 Diag(IdentLoc, diag::err_no_member) 9571 << NameInfo.getName() << LookupContext << SS.getRange(); 9572 return BuildInvalid(); 9573 } 9574 } 9575 9576 if (R.isAmbiguous()) 9577 return BuildInvalid(); 9578 9579 if (HasTypenameKeyword) { 9580 // If we asked for a typename and got a non-type decl, error out. 9581 if (!R.getAsSingle<TypeDecl>()) { 9582 Diag(IdentLoc, diag::err_using_typename_non_type); 9583 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9584 Diag((*I)->getUnderlyingDecl()->getLocation(), 9585 diag::note_using_decl_target); 9586 return BuildInvalid(); 9587 } 9588 } else { 9589 // If we asked for a non-typename and we got a type, error out, 9590 // but only if this is an instantiation of an unresolved using 9591 // decl. Otherwise just silently find the type name. 9592 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 9593 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 9594 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 9595 return BuildInvalid(); 9596 } 9597 } 9598 9599 // C++14 [namespace.udecl]p6: 9600 // A using-declaration shall not name a namespace. 9601 if (R.getAsSingle<NamespaceDecl>()) { 9602 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 9603 << SS.getRange(); 9604 return BuildInvalid(); 9605 } 9606 9607 // C++14 [namespace.udecl]p7: 9608 // A using-declaration shall not name a scoped enumerator. 9609 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 9610 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 9611 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 9612 << SS.getRange(); 9613 return BuildInvalid(); 9614 } 9615 } 9616 9617 UsingDecl *UD = BuildValid(); 9618 9619 // Some additional rules apply to inheriting constructors. 9620 if (UsingName.getName().getNameKind() == 9621 DeclarationName::CXXConstructorName) { 9622 // Suppress access diagnostics; the access check is instead performed at the 9623 // point of use for an inheriting constructor. 9624 R.suppressDiagnostics(); 9625 if (CheckInheritingConstructorUsingDecl(UD)) 9626 return UD; 9627 } 9628 9629 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9630 UsingShadowDecl *PrevDecl = nullptr; 9631 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 9632 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 9633 } 9634 9635 return UD; 9636 } 9637 9638 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 9639 ArrayRef<NamedDecl *> Expansions) { 9640 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 9641 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 9642 isa<UsingPackDecl>(InstantiatedFrom)); 9643 9644 auto *UPD = 9645 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 9646 UPD->setAccess(InstantiatedFrom->getAccess()); 9647 CurContext->addDecl(UPD); 9648 return UPD; 9649 } 9650 9651 /// Additional checks for a using declaration referring to a constructor name. 9652 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 9653 assert(!UD->hasTypename() && "expecting a constructor name"); 9654 9655 const Type *SourceType = UD->getQualifier()->getAsType(); 9656 assert(SourceType && 9657 "Using decl naming constructor doesn't have type in scope spec."); 9658 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 9659 9660 // Check whether the named type is a direct base class. 9661 bool AnyDependentBases = false; 9662 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 9663 AnyDependentBases); 9664 if (!Base && !AnyDependentBases) { 9665 Diag(UD->getUsingLoc(), 9666 diag::err_using_decl_constructor_not_in_direct_base) 9667 << UD->getNameInfo().getSourceRange() 9668 << QualType(SourceType, 0) << TargetClass; 9669 UD->setInvalidDecl(); 9670 return true; 9671 } 9672 9673 if (Base) 9674 Base->setInheritConstructors(); 9675 9676 return false; 9677 } 9678 9679 /// Checks that the given using declaration is not an invalid 9680 /// redeclaration. Note that this is checking only for the using decl 9681 /// itself, not for any ill-formedness among the UsingShadowDecls. 9682 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 9683 bool HasTypenameKeyword, 9684 const CXXScopeSpec &SS, 9685 SourceLocation NameLoc, 9686 const LookupResult &Prev) { 9687 NestedNameSpecifier *Qual = SS.getScopeRep(); 9688 9689 // C++03 [namespace.udecl]p8: 9690 // C++0x [namespace.udecl]p10: 9691 // A using-declaration is a declaration and can therefore be used 9692 // repeatedly where (and only where) multiple declarations are 9693 // allowed. 9694 // 9695 // That's in non-member contexts. 9696 if (!CurContext->getRedeclContext()->isRecord()) { 9697 // A dependent qualifier outside a class can only ever resolve to an 9698 // enumeration type. Therefore it conflicts with any other non-type 9699 // declaration in the same scope. 9700 // FIXME: How should we check for dependent type-type conflicts at block 9701 // scope? 9702 if (Qual->isDependent() && !HasTypenameKeyword) { 9703 for (auto *D : Prev) { 9704 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 9705 bool OldCouldBeEnumerator = 9706 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 9707 Diag(NameLoc, 9708 OldCouldBeEnumerator ? diag::err_redefinition 9709 : diag::err_redefinition_different_kind) 9710 << Prev.getLookupName(); 9711 Diag(D->getLocation(), diag::note_previous_definition); 9712 return true; 9713 } 9714 } 9715 } 9716 return false; 9717 } 9718 9719 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 9720 NamedDecl *D = *I; 9721 9722 bool DTypename; 9723 NestedNameSpecifier *DQual; 9724 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 9725 DTypename = UD->hasTypename(); 9726 DQual = UD->getQualifier(); 9727 } else if (UnresolvedUsingValueDecl *UD 9728 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 9729 DTypename = false; 9730 DQual = UD->getQualifier(); 9731 } else if (UnresolvedUsingTypenameDecl *UD 9732 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 9733 DTypename = true; 9734 DQual = UD->getQualifier(); 9735 } else continue; 9736 9737 // using decls differ if one says 'typename' and the other doesn't. 9738 // FIXME: non-dependent using decls? 9739 if (HasTypenameKeyword != DTypename) continue; 9740 9741 // using decls differ if they name different scopes (but note that 9742 // template instantiation can cause this check to trigger when it 9743 // didn't before instantiation). 9744 if (Context.getCanonicalNestedNameSpecifier(Qual) != 9745 Context.getCanonicalNestedNameSpecifier(DQual)) 9746 continue; 9747 9748 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 9749 Diag(D->getLocation(), diag::note_using_decl) << 1; 9750 return true; 9751 } 9752 9753 return false; 9754 } 9755 9756 9757 /// Checks that the given nested-name qualifier used in a using decl 9758 /// in the current context is appropriately related to the current 9759 /// scope. If an error is found, diagnoses it and returns true. 9760 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 9761 bool HasTypename, 9762 const CXXScopeSpec &SS, 9763 const DeclarationNameInfo &NameInfo, 9764 SourceLocation NameLoc) { 9765 DeclContext *NamedContext = computeDeclContext(SS); 9766 9767 if (!CurContext->isRecord()) { 9768 // C++03 [namespace.udecl]p3: 9769 // C++0x [namespace.udecl]p8: 9770 // A using-declaration for a class member shall be a member-declaration. 9771 9772 // If we weren't able to compute a valid scope, it might validly be a 9773 // dependent class scope or a dependent enumeration unscoped scope. If 9774 // we have a 'typename' keyword, the scope must resolve to a class type. 9775 if ((HasTypename && !NamedContext) || 9776 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 9777 auto *RD = NamedContext 9778 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 9779 : nullptr; 9780 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 9781 RD = nullptr; 9782 9783 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 9784 << SS.getRange(); 9785 9786 // If we have a complete, non-dependent source type, try to suggest a 9787 // way to get the same effect. 9788 if (!RD) 9789 return true; 9790 9791 // Find what this using-declaration was referring to. 9792 LookupResult R(*this, NameInfo, LookupOrdinaryName); 9793 R.setHideTags(false); 9794 R.suppressDiagnostics(); 9795 LookupQualifiedName(R, RD); 9796 9797 if (R.getAsSingle<TypeDecl>()) { 9798 if (getLangOpts().CPlusPlus11) { 9799 // Convert 'using X::Y;' to 'using Y = X::Y;'. 9800 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 9801 << 0 // alias declaration 9802 << FixItHint::CreateInsertion(SS.getBeginLoc(), 9803 NameInfo.getName().getAsString() + 9804 " = "); 9805 } else { 9806 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 9807 SourceLocation InsertLoc = 9808 getLocForEndOfToken(NameInfo.getLocEnd()); 9809 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 9810 << 1 // typedef declaration 9811 << FixItHint::CreateReplacement(UsingLoc, "typedef") 9812 << FixItHint::CreateInsertion( 9813 InsertLoc, " " + NameInfo.getName().getAsString()); 9814 } 9815 } else if (R.getAsSingle<VarDecl>()) { 9816 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9817 // repeating the type of the static data member here. 9818 FixItHint FixIt; 9819 if (getLangOpts().CPlusPlus11) { 9820 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9821 FixIt = FixItHint::CreateReplacement( 9822 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 9823 } 9824 9825 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9826 << 2 // reference declaration 9827 << FixIt; 9828 } else if (R.getAsSingle<EnumConstantDecl>()) { 9829 // Don't provide a fixit outside C++11 mode; we don't want to suggest 9830 // repeating the type of the enumeration here, and we can't do so if 9831 // the type is anonymous. 9832 FixItHint FixIt; 9833 if (getLangOpts().CPlusPlus11) { 9834 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 9835 FixIt = FixItHint::CreateReplacement( 9836 UsingLoc, 9837 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 9838 } 9839 9840 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 9841 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 9842 << FixIt; 9843 } 9844 return true; 9845 } 9846 9847 // Otherwise, this might be valid. 9848 return false; 9849 } 9850 9851 // The current scope is a record. 9852 9853 // If the named context is dependent, we can't decide much. 9854 if (!NamedContext) { 9855 // FIXME: in C++0x, we can diagnose if we can prove that the 9856 // nested-name-specifier does not refer to a base class, which is 9857 // still possible in some cases. 9858 9859 // Otherwise we have to conservatively report that things might be 9860 // okay. 9861 return false; 9862 } 9863 9864 if (!NamedContext->isRecord()) { 9865 // Ideally this would point at the last name in the specifier, 9866 // but we don't have that level of source info. 9867 Diag(SS.getRange().getBegin(), 9868 diag::err_using_decl_nested_name_specifier_is_not_class) 9869 << SS.getScopeRep() << SS.getRange(); 9870 return true; 9871 } 9872 9873 if (!NamedContext->isDependentContext() && 9874 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 9875 return true; 9876 9877 if (getLangOpts().CPlusPlus11) { 9878 // C++11 [namespace.udecl]p3: 9879 // In a using-declaration used as a member-declaration, the 9880 // nested-name-specifier shall name a base class of the class 9881 // being defined. 9882 9883 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 9884 cast<CXXRecordDecl>(NamedContext))) { 9885 if (CurContext == NamedContext) { 9886 Diag(NameLoc, 9887 diag::err_using_decl_nested_name_specifier_is_current_class) 9888 << SS.getRange(); 9889 return true; 9890 } 9891 9892 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 9893 Diag(SS.getRange().getBegin(), 9894 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9895 << SS.getScopeRep() 9896 << cast<CXXRecordDecl>(CurContext) 9897 << SS.getRange(); 9898 } 9899 return true; 9900 } 9901 9902 return false; 9903 } 9904 9905 // C++03 [namespace.udecl]p4: 9906 // A using-declaration used as a member-declaration shall refer 9907 // to a member of a base class of the class being defined [etc.]. 9908 9909 // Salient point: SS doesn't have to name a base class as long as 9910 // lookup only finds members from base classes. Therefore we can 9911 // diagnose here only if we can prove that that can't happen, 9912 // i.e. if the class hierarchies provably don't intersect. 9913 9914 // TODO: it would be nice if "definitely valid" results were cached 9915 // in the UsingDecl and UsingShadowDecl so that these checks didn't 9916 // need to be repeated. 9917 9918 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 9919 auto Collect = [&Bases](const CXXRecordDecl *Base) { 9920 Bases.insert(Base); 9921 return true; 9922 }; 9923 9924 // Collect all bases. Return false if we find a dependent base. 9925 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 9926 return false; 9927 9928 // Returns true if the base is dependent or is one of the accumulated base 9929 // classes. 9930 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 9931 return !Bases.count(Base); 9932 }; 9933 9934 // Return false if the class has a dependent base or if it or one 9935 // of its bases is present in the base set of the current context. 9936 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 9937 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 9938 return false; 9939 9940 Diag(SS.getRange().getBegin(), 9941 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9942 << SS.getScopeRep() 9943 << cast<CXXRecordDecl>(CurContext) 9944 << SS.getRange(); 9945 9946 return true; 9947 } 9948 9949 Decl *Sema::ActOnAliasDeclaration(Scope *S, 9950 AccessSpecifier AS, 9951 MultiTemplateParamsArg TemplateParamLists, 9952 SourceLocation UsingLoc, 9953 UnqualifiedId &Name, 9954 AttributeList *AttrList, 9955 TypeResult Type, 9956 Decl *DeclFromDeclSpec) { 9957 // Skip up to the relevant declaration scope. 9958 while (S->isTemplateParamScope()) 9959 S = S->getParent(); 9960 assert((S->getFlags() & Scope::DeclScope) && 9961 "got alias-declaration outside of declaration scope"); 9962 9963 if (Type.isInvalid()) 9964 return nullptr; 9965 9966 bool Invalid = false; 9967 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 9968 TypeSourceInfo *TInfo = nullptr; 9969 GetTypeFromParser(Type.get(), &TInfo); 9970 9971 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 9972 return nullptr; 9973 9974 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 9975 UPPC_DeclarationType)) { 9976 Invalid = true; 9977 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 9978 TInfo->getTypeLoc().getBeginLoc()); 9979 } 9980 9981 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 9982 LookupName(Previous, S); 9983 9984 // Warn about shadowing the name of a template parameter. 9985 if (Previous.isSingleResult() && 9986 Previous.getFoundDecl()->isTemplateParameter()) { 9987 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 9988 Previous.clear(); 9989 } 9990 9991 assert(Name.Kind == UnqualifiedId::IK_Identifier && 9992 "name in alias declaration must be an identifier"); 9993 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 9994 Name.StartLocation, 9995 Name.Identifier, TInfo); 9996 9997 NewTD->setAccess(AS); 9998 9999 if (Invalid) 10000 NewTD->setInvalidDecl(); 10001 10002 ProcessDeclAttributeList(S, NewTD, AttrList); 10003 AddPragmaAttributes(S, NewTD); 10004 10005 CheckTypedefForVariablyModifiedType(S, NewTD); 10006 Invalid |= NewTD->isInvalidDecl(); 10007 10008 bool Redeclaration = false; 10009 10010 NamedDecl *NewND; 10011 if (TemplateParamLists.size()) { 10012 TypeAliasTemplateDecl *OldDecl = nullptr; 10013 TemplateParameterList *OldTemplateParams = nullptr; 10014 10015 if (TemplateParamLists.size() != 1) { 10016 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10017 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10018 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10019 } 10020 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10021 10022 // Check that we can declare a template here. 10023 if (CheckTemplateDeclScope(S, TemplateParams)) 10024 return nullptr; 10025 10026 // Only consider previous declarations in the same scope. 10027 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10028 /*ExplicitInstantiationOrSpecialization*/false); 10029 if (!Previous.empty()) { 10030 Redeclaration = true; 10031 10032 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10033 if (!OldDecl && !Invalid) { 10034 Diag(UsingLoc, diag::err_redefinition_different_kind) 10035 << Name.Identifier; 10036 10037 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10038 if (OldD->getLocation().isValid()) 10039 Diag(OldD->getLocation(), diag::note_previous_definition); 10040 10041 Invalid = true; 10042 } 10043 10044 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10045 if (TemplateParameterListsAreEqual(TemplateParams, 10046 OldDecl->getTemplateParameters(), 10047 /*Complain=*/true, 10048 TPL_TemplateMatch)) 10049 OldTemplateParams = OldDecl->getTemplateParameters(); 10050 else 10051 Invalid = true; 10052 10053 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10054 if (!Invalid && 10055 !Context.hasSameType(OldTD->getUnderlyingType(), 10056 NewTD->getUnderlyingType())) { 10057 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10058 // but we can't reasonably accept it. 10059 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10060 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10061 if (OldTD->getLocation().isValid()) 10062 Diag(OldTD->getLocation(), diag::note_previous_definition); 10063 Invalid = true; 10064 } 10065 } 10066 } 10067 10068 // Merge any previous default template arguments into our parameters, 10069 // and check the parameter list. 10070 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10071 TPC_TypeAliasTemplate)) 10072 return nullptr; 10073 10074 TypeAliasTemplateDecl *NewDecl = 10075 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10076 Name.Identifier, TemplateParams, 10077 NewTD); 10078 NewTD->setDescribedAliasTemplate(NewDecl); 10079 10080 NewDecl->setAccess(AS); 10081 10082 if (Invalid) 10083 NewDecl->setInvalidDecl(); 10084 else if (OldDecl) 10085 NewDecl->setPreviousDecl(OldDecl); 10086 10087 NewND = NewDecl; 10088 } else { 10089 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10090 setTagNameForLinkagePurposes(TD, NewTD); 10091 handleTagNumbering(TD, S); 10092 } 10093 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10094 NewND = NewTD; 10095 } 10096 10097 PushOnScopeChains(NewND, S); 10098 ActOnDocumentableDecl(NewND); 10099 return NewND; 10100 } 10101 10102 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10103 SourceLocation AliasLoc, 10104 IdentifierInfo *Alias, CXXScopeSpec &SS, 10105 SourceLocation IdentLoc, 10106 IdentifierInfo *Ident) { 10107 10108 // Lookup the namespace name. 10109 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10110 LookupParsedName(R, S, &SS); 10111 10112 if (R.isAmbiguous()) 10113 return nullptr; 10114 10115 if (R.empty()) { 10116 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10117 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10118 return nullptr; 10119 } 10120 } 10121 assert(!R.isAmbiguous() && !R.empty()); 10122 NamedDecl *ND = R.getRepresentativeDecl(); 10123 10124 // Check if we have a previous declaration with the same name. 10125 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10126 ForRedeclaration); 10127 LookupName(PrevR, S); 10128 10129 // Check we're not shadowing a template parameter. 10130 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10131 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10132 PrevR.clear(); 10133 } 10134 10135 // Filter out any other lookup result from an enclosing scope. 10136 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10137 /*AllowInlineNamespace*/false); 10138 10139 // Find the previous declaration and check that we can redeclare it. 10140 NamespaceAliasDecl *Prev = nullptr; 10141 if (PrevR.isSingleResult()) { 10142 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10143 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10144 // We already have an alias with the same name that points to the same 10145 // namespace; check that it matches. 10146 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10147 Prev = AD; 10148 } else if (isVisible(PrevDecl)) { 10149 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10150 << Alias; 10151 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10152 << AD->getNamespace(); 10153 return nullptr; 10154 } 10155 } else if (isVisible(PrevDecl)) { 10156 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10157 ? diag::err_redefinition 10158 : diag::err_redefinition_different_kind; 10159 Diag(AliasLoc, DiagID) << Alias; 10160 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10161 return nullptr; 10162 } 10163 } 10164 10165 // The use of a nested name specifier may trigger deprecation warnings. 10166 DiagnoseUseOfDecl(ND, IdentLoc); 10167 10168 NamespaceAliasDecl *AliasDecl = 10169 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10170 Alias, SS.getWithLocInContext(Context), 10171 IdentLoc, ND); 10172 if (Prev) 10173 AliasDecl->setPreviousDecl(Prev); 10174 10175 PushOnScopeChains(AliasDecl, S); 10176 return AliasDecl; 10177 } 10178 10179 namespace { 10180 struct SpecialMemberExceptionSpecInfo 10181 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10182 SourceLocation Loc; 10183 Sema::ImplicitExceptionSpecification ExceptSpec; 10184 10185 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10186 Sema::CXXSpecialMember CSM, 10187 Sema::InheritedConstructorInfo *ICI, 10188 SourceLocation Loc) 10189 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 10190 10191 bool visitBase(CXXBaseSpecifier *Base); 10192 bool visitField(FieldDecl *FD); 10193 10194 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 10195 unsigned Quals); 10196 10197 void visitSubobjectCall(Subobject Subobj, 10198 Sema::SpecialMemberOverloadResult SMOR); 10199 }; 10200 } 10201 10202 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 10203 auto *RT = Base->getType()->getAs<RecordType>(); 10204 if (!RT) 10205 return false; 10206 10207 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 10208 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 10209 if (auto *BaseCtor = SMOR.getMethod()) { 10210 visitSubobjectCall(Base, BaseCtor); 10211 return false; 10212 } 10213 10214 visitClassSubobject(BaseClass, Base, 0); 10215 return false; 10216 } 10217 10218 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 10219 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 10220 Expr *E = FD->getInClassInitializer(); 10221 if (!E) 10222 // FIXME: It's a little wasteful to build and throw away a 10223 // CXXDefaultInitExpr here. 10224 // FIXME: We should have a single context note pointing at Loc, and 10225 // this location should be MD->getLocation() instead, since that's 10226 // the location where we actually use the default init expression. 10227 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 10228 if (E) 10229 ExceptSpec.CalledExpr(E); 10230 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 10231 ->getAs<RecordType>()) { 10232 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 10233 FD->getType().getCVRQualifiers()); 10234 } 10235 return false; 10236 } 10237 10238 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 10239 Subobject Subobj, 10240 unsigned Quals) { 10241 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 10242 bool IsMutable = Field && Field->isMutable(); 10243 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 10244 } 10245 10246 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 10247 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 10248 // Note, if lookup fails, it doesn't matter what exception specification we 10249 // choose because the special member will be deleted. 10250 if (CXXMethodDecl *MD = SMOR.getMethod()) 10251 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 10252 } 10253 10254 static Sema::ImplicitExceptionSpecification 10255 ComputeDefaultedSpecialMemberExceptionSpec( 10256 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 10257 Sema::InheritedConstructorInfo *ICI) { 10258 CXXRecordDecl *ClassDecl = MD->getParent(); 10259 10260 // C++ [except.spec]p14: 10261 // An implicitly declared special member function (Clause 12) shall have an 10262 // exception-specification. [...] 10263 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc); 10264 if (ClassDecl->isInvalidDecl()) 10265 return Info.ExceptSpec; 10266 10267 // C++1z [except.spec]p7: 10268 // [Look for exceptions thrown by] a constructor selected [...] to 10269 // initialize a potentially constructed subobject, 10270 // C++1z [except.spec]p8: 10271 // The exception specification for an implicitly-declared destructor, or a 10272 // destructor without a noexcept-specifier, is potentially-throwing if and 10273 // only if any of the destructors for any of its potentially constructed 10274 // subojects is potentially throwing. 10275 // FIXME: We respect the first rule but ignore the "potentially constructed" 10276 // in the second rule to resolve a core issue (no number yet) that would have 10277 // us reject: 10278 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 10279 // struct B : A {}; 10280 // struct C : B { void f(); }; 10281 // ... due to giving B::~B() a non-throwing exception specification. 10282 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 10283 : Info.VisitAllBases); 10284 10285 return Info.ExceptSpec; 10286 } 10287 10288 namespace { 10289 /// RAII object to register a special member as being currently declared. 10290 struct DeclaringSpecialMember { 10291 Sema &S; 10292 Sema::SpecialMemberDecl D; 10293 Sema::ContextRAII SavedContext; 10294 bool WasAlreadyBeingDeclared; 10295 10296 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 10297 : S(S), D(RD, CSM), SavedContext(S, RD) { 10298 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 10299 if (WasAlreadyBeingDeclared) 10300 // This almost never happens, but if it does, ensure that our cache 10301 // doesn't contain a stale result. 10302 S.SpecialMemberCache.clear(); 10303 else { 10304 // Register a note to be produced if we encounter an error while 10305 // declaring the special member. 10306 Sema::CodeSynthesisContext Ctx; 10307 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 10308 // FIXME: We don't have a location to use here. Using the class's 10309 // location maintains the fiction that we declare all special members 10310 // with the class, but (1) it's not clear that lying about that helps our 10311 // users understand what's going on, and (2) there may be outer contexts 10312 // on the stack (some of which are relevant) and printing them exposes 10313 // our lies. 10314 Ctx.PointOfInstantiation = RD->getLocation(); 10315 Ctx.Entity = RD; 10316 Ctx.SpecialMember = CSM; 10317 S.pushCodeSynthesisContext(Ctx); 10318 } 10319 } 10320 ~DeclaringSpecialMember() { 10321 if (!WasAlreadyBeingDeclared) { 10322 S.SpecialMembersBeingDeclared.erase(D); 10323 S.popCodeSynthesisContext(); 10324 } 10325 } 10326 10327 /// \brief Are we already trying to declare this special member? 10328 bool isAlreadyBeingDeclared() const { 10329 return WasAlreadyBeingDeclared; 10330 } 10331 }; 10332 } 10333 10334 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 10335 // Look up any existing declarations, but don't trigger declaration of all 10336 // implicit special members with this name. 10337 DeclarationName Name = FD->getDeclName(); 10338 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 10339 ForRedeclaration); 10340 for (auto *D : FD->getParent()->lookup(Name)) 10341 if (auto *Acceptable = R.getAcceptableDecl(D)) 10342 R.addDecl(Acceptable); 10343 R.resolveKind(); 10344 R.suppressDiagnostics(); 10345 10346 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 10347 } 10348 10349 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 10350 CXXRecordDecl *ClassDecl) { 10351 // C++ [class.ctor]p5: 10352 // A default constructor for a class X is a constructor of class X 10353 // that can be called without an argument. If there is no 10354 // user-declared constructor for class X, a default constructor is 10355 // implicitly declared. An implicitly-declared default constructor 10356 // is an inline public member of its class. 10357 assert(ClassDecl->needsImplicitDefaultConstructor() && 10358 "Should not build implicit default constructor!"); 10359 10360 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 10361 if (DSM.isAlreadyBeingDeclared()) 10362 return nullptr; 10363 10364 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10365 CXXDefaultConstructor, 10366 false); 10367 10368 // Create the actual constructor declaration. 10369 CanQualType ClassType 10370 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10371 SourceLocation ClassLoc = ClassDecl->getLocation(); 10372 DeclarationName Name 10373 = Context.DeclarationNames.getCXXConstructorName(ClassType); 10374 DeclarationNameInfo NameInfo(Name, ClassLoc); 10375 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 10376 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 10377 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 10378 /*isImplicitlyDeclared=*/true, Constexpr); 10379 DefaultCon->setAccess(AS_public); 10380 DefaultCon->setDefaulted(); 10381 10382 if (getLangOpts().CUDA) { 10383 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 10384 DefaultCon, 10385 /* ConstRHS */ false, 10386 /* Diagnose */ false); 10387 } 10388 10389 // Build an exception specification pointing back at this constructor. 10390 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 10391 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10392 10393 // We don't need to use SpecialMemberIsTrivial here; triviality for default 10394 // constructors is easy to compute. 10395 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 10396 10397 // Note that we have declared this constructor. 10398 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 10399 10400 Scope *S = getScopeForContext(ClassDecl); 10401 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 10402 10403 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 10404 SetDeclDeleted(DefaultCon, ClassLoc); 10405 10406 if (S) 10407 PushOnScopeChains(DefaultCon, S, false); 10408 ClassDecl->addDecl(DefaultCon); 10409 10410 return DefaultCon; 10411 } 10412 10413 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 10414 CXXConstructorDecl *Constructor) { 10415 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 10416 !Constructor->doesThisDeclarationHaveABody() && 10417 !Constructor->isDeleted()) && 10418 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 10419 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10420 return; 10421 10422 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10423 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 10424 10425 SynthesizedFunctionScope Scope(*this, Constructor); 10426 10427 // The exception specification is needed because we are defining the 10428 // function. 10429 ResolveExceptionSpec(CurrentLocation, 10430 Constructor->getType()->castAs<FunctionProtoType>()); 10431 MarkVTableUsed(CurrentLocation, ClassDecl); 10432 10433 // Add a context note for diagnostics produced after this point. 10434 Scope.addContextNote(CurrentLocation); 10435 10436 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 10437 Constructor->setInvalidDecl(); 10438 return; 10439 } 10440 10441 SourceLocation Loc = Constructor->getLocEnd().isValid() 10442 ? Constructor->getLocEnd() 10443 : Constructor->getLocation(); 10444 Constructor->setBody(new (Context) CompoundStmt(Loc)); 10445 Constructor->markUsed(Context); 10446 10447 if (ASTMutationListener *L = getASTMutationListener()) { 10448 L->CompletedImplicitDefinition(Constructor); 10449 } 10450 10451 DiagnoseUninitializedFields(*this, Constructor); 10452 } 10453 10454 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 10455 // Perform any delayed checks on exception specifications. 10456 CheckDelayedMemberExceptionSpecs(); 10457 } 10458 10459 /// Find or create the fake constructor we synthesize to model constructing an 10460 /// object of a derived class via a constructor of a base class. 10461 CXXConstructorDecl * 10462 Sema::findInheritingConstructor(SourceLocation Loc, 10463 CXXConstructorDecl *BaseCtor, 10464 ConstructorUsingShadowDecl *Shadow) { 10465 CXXRecordDecl *Derived = Shadow->getParent(); 10466 SourceLocation UsingLoc = Shadow->getLocation(); 10467 10468 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 10469 // For now we use the name of the base class constructor as a member of the 10470 // derived class to indicate a (fake) inherited constructor name. 10471 DeclarationName Name = BaseCtor->getDeclName(); 10472 10473 // Check to see if we already have a fake constructor for this inherited 10474 // constructor call. 10475 for (NamedDecl *Ctor : Derived->lookup(Name)) 10476 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 10477 ->getInheritedConstructor() 10478 .getConstructor(), 10479 BaseCtor)) 10480 return cast<CXXConstructorDecl>(Ctor); 10481 10482 DeclarationNameInfo NameInfo(Name, UsingLoc); 10483 TypeSourceInfo *TInfo = 10484 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 10485 FunctionProtoTypeLoc ProtoLoc = 10486 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 10487 10488 // Check the inherited constructor is valid and find the list of base classes 10489 // from which it was inherited. 10490 InheritedConstructorInfo ICI(*this, Loc, Shadow); 10491 10492 bool Constexpr = 10493 BaseCtor->isConstexpr() && 10494 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 10495 false, BaseCtor, &ICI); 10496 10497 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 10498 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 10499 BaseCtor->isExplicit(), /*Inline=*/true, 10500 /*ImplicitlyDeclared=*/true, Constexpr, 10501 InheritedConstructor(Shadow, BaseCtor)); 10502 if (Shadow->isInvalidDecl()) 10503 DerivedCtor->setInvalidDecl(); 10504 10505 // Build an unevaluated exception specification for this fake constructor. 10506 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 10507 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10508 EPI.ExceptionSpec.Type = EST_Unevaluated; 10509 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 10510 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 10511 FPT->getParamTypes(), EPI)); 10512 10513 // Build the parameter declarations. 10514 SmallVector<ParmVarDecl *, 16> ParamDecls; 10515 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 10516 TypeSourceInfo *TInfo = 10517 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 10518 ParmVarDecl *PD = ParmVarDecl::Create( 10519 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 10520 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 10521 PD->setScopeInfo(0, I); 10522 PD->setImplicit(); 10523 // Ensure attributes are propagated onto parameters (this matters for 10524 // format, pass_object_size, ...). 10525 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 10526 ParamDecls.push_back(PD); 10527 ProtoLoc.setParam(I, PD); 10528 } 10529 10530 // Set up the new constructor. 10531 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 10532 DerivedCtor->setAccess(BaseCtor->getAccess()); 10533 DerivedCtor->setParams(ParamDecls); 10534 Derived->addDecl(DerivedCtor); 10535 10536 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 10537 SetDeclDeleted(DerivedCtor, UsingLoc); 10538 10539 return DerivedCtor; 10540 } 10541 10542 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 10543 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 10544 Ctor->getInheritedConstructor().getShadowDecl()); 10545 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 10546 /*Diagnose*/true); 10547 } 10548 10549 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 10550 CXXConstructorDecl *Constructor) { 10551 CXXRecordDecl *ClassDecl = Constructor->getParent(); 10552 assert(Constructor->getInheritedConstructor() && 10553 !Constructor->doesThisDeclarationHaveABody() && 10554 !Constructor->isDeleted()); 10555 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 10556 return; 10557 10558 // Initializations are performed "as if by a defaulted default constructor", 10559 // so enter the appropriate scope. 10560 SynthesizedFunctionScope Scope(*this, Constructor); 10561 10562 // The exception specification is needed because we are defining the 10563 // function. 10564 ResolveExceptionSpec(CurrentLocation, 10565 Constructor->getType()->castAs<FunctionProtoType>()); 10566 MarkVTableUsed(CurrentLocation, ClassDecl); 10567 10568 // Add a context note for diagnostics produced after this point. 10569 Scope.addContextNote(CurrentLocation); 10570 10571 ConstructorUsingShadowDecl *Shadow = 10572 Constructor->getInheritedConstructor().getShadowDecl(); 10573 CXXConstructorDecl *InheritedCtor = 10574 Constructor->getInheritedConstructor().getConstructor(); 10575 10576 // [class.inhctor.init]p1: 10577 // initialization proceeds as if a defaulted default constructor is used to 10578 // initialize the D object and each base class subobject from which the 10579 // constructor was inherited 10580 10581 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 10582 CXXRecordDecl *RD = Shadow->getParent(); 10583 SourceLocation InitLoc = Shadow->getLocation(); 10584 10585 // Build explicit initializers for all base classes from which the 10586 // constructor was inherited. 10587 SmallVector<CXXCtorInitializer*, 8> Inits; 10588 for (bool VBase : {false, true}) { 10589 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 10590 if (B.isVirtual() != VBase) 10591 continue; 10592 10593 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 10594 if (!BaseRD) 10595 continue; 10596 10597 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 10598 if (!BaseCtor.first) 10599 continue; 10600 10601 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 10602 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 10603 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 10604 10605 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 10606 Inits.push_back(new (Context) CXXCtorInitializer( 10607 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 10608 SourceLocation())); 10609 } 10610 } 10611 10612 // We now proceed as if for a defaulted default constructor, with the relevant 10613 // initializers replaced. 10614 10615 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 10616 Constructor->setInvalidDecl(); 10617 return; 10618 } 10619 10620 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 10621 Constructor->markUsed(Context); 10622 10623 if (ASTMutationListener *L = getASTMutationListener()) { 10624 L->CompletedImplicitDefinition(Constructor); 10625 } 10626 10627 DiagnoseUninitializedFields(*this, Constructor); 10628 } 10629 10630 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 10631 // C++ [class.dtor]p2: 10632 // If a class has no user-declared destructor, a destructor is 10633 // declared implicitly. An implicitly-declared destructor is an 10634 // inline public member of its class. 10635 assert(ClassDecl->needsImplicitDestructor()); 10636 10637 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 10638 if (DSM.isAlreadyBeingDeclared()) 10639 return nullptr; 10640 10641 // Create the actual destructor declaration. 10642 CanQualType ClassType 10643 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10644 SourceLocation ClassLoc = ClassDecl->getLocation(); 10645 DeclarationName Name 10646 = Context.DeclarationNames.getCXXDestructorName(ClassType); 10647 DeclarationNameInfo NameInfo(Name, ClassLoc); 10648 CXXDestructorDecl *Destructor 10649 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 10650 QualType(), nullptr, /*isInline=*/true, 10651 /*isImplicitlyDeclared=*/true); 10652 Destructor->setAccess(AS_public); 10653 Destructor->setDefaulted(); 10654 10655 if (getLangOpts().CUDA) { 10656 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 10657 Destructor, 10658 /* ConstRHS */ false, 10659 /* Diagnose */ false); 10660 } 10661 10662 // Build an exception specification pointing back at this destructor. 10663 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 10664 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10665 10666 // We don't need to use SpecialMemberIsTrivial here; triviality for 10667 // destructors is easy to compute. 10668 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 10669 10670 // Note that we have declared this destructor. 10671 ++ASTContext::NumImplicitDestructorsDeclared; 10672 10673 Scope *S = getScopeForContext(ClassDecl); 10674 CheckImplicitSpecialMemberDeclaration(S, Destructor); 10675 10676 // We can't check whether an implicit destructor is deleted before we complete 10677 // the definition of the class, because its validity depends on the alignment 10678 // of the class. We'll check this from ActOnFields once the class is complete. 10679 if (ClassDecl->isCompleteDefinition() && 10680 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 10681 SetDeclDeleted(Destructor, ClassLoc); 10682 10683 // Introduce this destructor into its scope. 10684 if (S) 10685 PushOnScopeChains(Destructor, S, false); 10686 ClassDecl->addDecl(Destructor); 10687 10688 return Destructor; 10689 } 10690 10691 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 10692 CXXDestructorDecl *Destructor) { 10693 assert((Destructor->isDefaulted() && 10694 !Destructor->doesThisDeclarationHaveABody() && 10695 !Destructor->isDeleted()) && 10696 "DefineImplicitDestructor - call it for implicit default dtor"); 10697 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 10698 return; 10699 10700 CXXRecordDecl *ClassDecl = Destructor->getParent(); 10701 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 10702 10703 SynthesizedFunctionScope Scope(*this, Destructor); 10704 10705 // The exception specification is needed because we are defining the 10706 // function. 10707 ResolveExceptionSpec(CurrentLocation, 10708 Destructor->getType()->castAs<FunctionProtoType>()); 10709 MarkVTableUsed(CurrentLocation, ClassDecl); 10710 10711 // Add a context note for diagnostics produced after this point. 10712 Scope.addContextNote(CurrentLocation); 10713 10714 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10715 Destructor->getParent()); 10716 10717 if (CheckDestructor(Destructor)) { 10718 Destructor->setInvalidDecl(); 10719 return; 10720 } 10721 10722 SourceLocation Loc = Destructor->getLocEnd().isValid() 10723 ? Destructor->getLocEnd() 10724 : Destructor->getLocation(); 10725 Destructor->setBody(new (Context) CompoundStmt(Loc)); 10726 Destructor->markUsed(Context); 10727 10728 if (ASTMutationListener *L = getASTMutationListener()) { 10729 L->CompletedImplicitDefinition(Destructor); 10730 } 10731 } 10732 10733 /// \brief Perform any semantic analysis which needs to be delayed until all 10734 /// pending class member declarations have been parsed. 10735 void Sema::ActOnFinishCXXMemberDecls() { 10736 // If the context is an invalid C++ class, just suppress these checks. 10737 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 10738 if (Record->isInvalidDecl()) { 10739 DelayedDefaultedMemberExceptionSpecs.clear(); 10740 DelayedExceptionSpecChecks.clear(); 10741 return; 10742 } 10743 checkForMultipleExportedDefaultConstructors(*this, Record); 10744 } 10745 } 10746 10747 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 10748 referenceDLLExportedClassMethods(); 10749 } 10750 10751 void Sema::referenceDLLExportedClassMethods() { 10752 if (!DelayedDllExportClasses.empty()) { 10753 // Calling ReferenceDllExportedMethods might cause the current function to 10754 // be called again, so use a local copy of DelayedDllExportClasses. 10755 SmallVector<CXXRecordDecl *, 4> WorkList; 10756 std::swap(DelayedDllExportClasses, WorkList); 10757 for (CXXRecordDecl *Class : WorkList) 10758 ReferenceDllExportedMethods(*this, Class); 10759 } 10760 } 10761 10762 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 10763 CXXDestructorDecl *Destructor) { 10764 assert(getLangOpts().CPlusPlus11 && 10765 "adjusting dtor exception specs was introduced in c++11"); 10766 10767 // C++11 [class.dtor]p3: 10768 // A declaration of a destructor that does not have an exception- 10769 // specification is implicitly considered to have the same exception- 10770 // specification as an implicit declaration. 10771 const FunctionProtoType *DtorType = Destructor->getType()-> 10772 getAs<FunctionProtoType>(); 10773 if (DtorType->hasExceptionSpec()) 10774 return; 10775 10776 // Replace the destructor's type, building off the existing one. Fortunately, 10777 // the only thing of interest in the destructor type is its extended info. 10778 // The return and arguments are fixed. 10779 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 10780 EPI.ExceptionSpec.Type = EST_Unevaluated; 10781 EPI.ExceptionSpec.SourceDecl = Destructor; 10782 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 10783 10784 // FIXME: If the destructor has a body that could throw, and the newly created 10785 // spec doesn't allow exceptions, we should emit a warning, because this 10786 // change in behavior can break conforming C++03 programs at runtime. 10787 // However, we don't have a body or an exception specification yet, so it 10788 // needs to be done somewhere else. 10789 } 10790 10791 namespace { 10792 /// \brief An abstract base class for all helper classes used in building the 10793 // copy/move operators. These classes serve as factory functions and help us 10794 // avoid using the same Expr* in the AST twice. 10795 class ExprBuilder { 10796 ExprBuilder(const ExprBuilder&) = delete; 10797 ExprBuilder &operator=(const ExprBuilder&) = delete; 10798 10799 protected: 10800 static Expr *assertNotNull(Expr *E) { 10801 assert(E && "Expression construction must not fail."); 10802 return E; 10803 } 10804 10805 public: 10806 ExprBuilder() {} 10807 virtual ~ExprBuilder() {} 10808 10809 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 10810 }; 10811 10812 class RefBuilder: public ExprBuilder { 10813 VarDecl *Var; 10814 QualType VarType; 10815 10816 public: 10817 Expr *build(Sema &S, SourceLocation Loc) const override { 10818 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 10819 } 10820 10821 RefBuilder(VarDecl *Var, QualType VarType) 10822 : Var(Var), VarType(VarType) {} 10823 }; 10824 10825 class ThisBuilder: public ExprBuilder { 10826 public: 10827 Expr *build(Sema &S, SourceLocation Loc) const override { 10828 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 10829 } 10830 }; 10831 10832 class CastBuilder: public ExprBuilder { 10833 const ExprBuilder &Builder; 10834 QualType Type; 10835 ExprValueKind Kind; 10836 const CXXCastPath &Path; 10837 10838 public: 10839 Expr *build(Sema &S, SourceLocation Loc) const override { 10840 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 10841 CK_UncheckedDerivedToBase, Kind, 10842 &Path).get()); 10843 } 10844 10845 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 10846 const CXXCastPath &Path) 10847 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 10848 }; 10849 10850 class DerefBuilder: public ExprBuilder { 10851 const ExprBuilder &Builder; 10852 10853 public: 10854 Expr *build(Sema &S, SourceLocation Loc) const override { 10855 return assertNotNull( 10856 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 10857 } 10858 10859 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10860 }; 10861 10862 class MemberBuilder: public ExprBuilder { 10863 const ExprBuilder &Builder; 10864 QualType Type; 10865 CXXScopeSpec SS; 10866 bool IsArrow; 10867 LookupResult &MemberLookup; 10868 10869 public: 10870 Expr *build(Sema &S, SourceLocation Loc) const override { 10871 return assertNotNull(S.BuildMemberReferenceExpr( 10872 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 10873 nullptr, MemberLookup, nullptr, nullptr).get()); 10874 } 10875 10876 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 10877 LookupResult &MemberLookup) 10878 : Builder(Builder), Type(Type), IsArrow(IsArrow), 10879 MemberLookup(MemberLookup) {} 10880 }; 10881 10882 class MoveCastBuilder: public ExprBuilder { 10883 const ExprBuilder &Builder; 10884 10885 public: 10886 Expr *build(Sema &S, SourceLocation Loc) const override { 10887 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 10888 } 10889 10890 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10891 }; 10892 10893 class LvalueConvBuilder: public ExprBuilder { 10894 const ExprBuilder &Builder; 10895 10896 public: 10897 Expr *build(Sema &S, SourceLocation Loc) const override { 10898 return assertNotNull( 10899 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 10900 } 10901 10902 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 10903 }; 10904 10905 class SubscriptBuilder: public ExprBuilder { 10906 const ExprBuilder &Base; 10907 const ExprBuilder &Index; 10908 10909 public: 10910 Expr *build(Sema &S, SourceLocation Loc) const override { 10911 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 10912 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 10913 } 10914 10915 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 10916 : Base(Base), Index(Index) {} 10917 }; 10918 10919 } // end anonymous namespace 10920 10921 /// When generating a defaulted copy or move assignment operator, if a field 10922 /// should be copied with __builtin_memcpy rather than via explicit assignments, 10923 /// do so. This optimization only applies for arrays of scalars, and for arrays 10924 /// of class type where the selected copy/move-assignment operator is trivial. 10925 static StmtResult 10926 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 10927 const ExprBuilder &ToB, const ExprBuilder &FromB) { 10928 // Compute the size of the memory buffer to be copied. 10929 QualType SizeType = S.Context.getSizeType(); 10930 llvm::APInt Size(S.Context.getTypeSize(SizeType), 10931 S.Context.getTypeSizeInChars(T).getQuantity()); 10932 10933 // Take the address of the field references for "from" and "to". We 10934 // directly construct UnaryOperators here because semantic analysis 10935 // does not permit us to take the address of an xvalue. 10936 Expr *From = FromB.build(S, Loc); 10937 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 10938 S.Context.getPointerType(From->getType()), 10939 VK_RValue, OK_Ordinary, Loc); 10940 Expr *To = ToB.build(S, Loc); 10941 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 10942 S.Context.getPointerType(To->getType()), 10943 VK_RValue, OK_Ordinary, Loc); 10944 10945 const Type *E = T->getBaseElementTypeUnsafe(); 10946 bool NeedsCollectableMemCpy = 10947 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 10948 10949 // Create a reference to the __builtin_objc_memmove_collectable function 10950 StringRef MemCpyName = NeedsCollectableMemCpy ? 10951 "__builtin_objc_memmove_collectable" : 10952 "__builtin_memcpy"; 10953 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 10954 Sema::LookupOrdinaryName); 10955 S.LookupName(R, S.TUScope, true); 10956 10957 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 10958 if (!MemCpy) 10959 // Something went horribly wrong earlier, and we will have complained 10960 // about it. 10961 return StmtError(); 10962 10963 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 10964 VK_RValue, Loc, nullptr); 10965 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 10966 10967 Expr *CallArgs[] = { 10968 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 10969 }; 10970 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 10971 Loc, CallArgs, Loc); 10972 10973 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 10974 return Call.getAs<Stmt>(); 10975 } 10976 10977 /// \brief Builds a statement that copies/moves the given entity from \p From to 10978 /// \c To. 10979 /// 10980 /// This routine is used to copy/move the members of a class with an 10981 /// implicitly-declared copy/move assignment operator. When the entities being 10982 /// copied are arrays, this routine builds for loops to copy them. 10983 /// 10984 /// \param S The Sema object used for type-checking. 10985 /// 10986 /// \param Loc The location where the implicit copy/move is being generated. 10987 /// 10988 /// \param T The type of the expressions being copied/moved. Both expressions 10989 /// must have this type. 10990 /// 10991 /// \param To The expression we are copying/moving to. 10992 /// 10993 /// \param From The expression we are copying/moving from. 10994 /// 10995 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 10996 /// Otherwise, it's a non-static member subobject. 10997 /// 10998 /// \param Copying Whether we're copying or moving. 10999 /// 11000 /// \param Depth Internal parameter recording the depth of the recursion. 11001 /// 11002 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11003 /// if a memcpy should be used instead. 11004 static StmtResult 11005 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11006 const ExprBuilder &To, const ExprBuilder &From, 11007 bool CopyingBaseSubobject, bool Copying, 11008 unsigned Depth = 0) { 11009 // C++11 [class.copy]p28: 11010 // Each subobject is assigned in the manner appropriate to its type: 11011 // 11012 // - if the subobject is of class type, as if by a call to operator= with 11013 // the subobject as the object expression and the corresponding 11014 // subobject of x as a single function argument (as if by explicit 11015 // qualification; that is, ignoring any possible virtual overriding 11016 // functions in more derived classes); 11017 // 11018 // C++03 [class.copy]p13: 11019 // - if the subobject is of class type, the copy assignment operator for 11020 // the class is used (as if by explicit qualification; that is, 11021 // ignoring any possible virtual overriding functions in more derived 11022 // classes); 11023 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11024 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11025 11026 // Look for operator=. 11027 DeclarationName Name 11028 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11029 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11030 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11031 11032 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11033 // operator. 11034 if (!S.getLangOpts().CPlusPlus11) { 11035 LookupResult::Filter F = OpLookup.makeFilter(); 11036 while (F.hasNext()) { 11037 NamedDecl *D = F.next(); 11038 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11039 if (Method->isCopyAssignmentOperator() || 11040 (!Copying && Method->isMoveAssignmentOperator())) 11041 continue; 11042 11043 F.erase(); 11044 } 11045 F.done(); 11046 } 11047 11048 // Suppress the protected check (C++ [class.protected]) for each of the 11049 // assignment operators we found. This strange dance is required when 11050 // we're assigning via a base classes's copy-assignment operator. To 11051 // ensure that we're getting the right base class subobject (without 11052 // ambiguities), we need to cast "this" to that subobject type; to 11053 // ensure that we don't go through the virtual call mechanism, we need 11054 // to qualify the operator= name with the base class (see below). However, 11055 // this means that if the base class has a protected copy assignment 11056 // operator, the protected member access check will fail. So, we 11057 // rewrite "protected" access to "public" access in this case, since we 11058 // know by construction that we're calling from a derived class. 11059 if (CopyingBaseSubobject) { 11060 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11061 L != LEnd; ++L) { 11062 if (L.getAccess() == AS_protected) 11063 L.setAccess(AS_public); 11064 } 11065 } 11066 11067 // Create the nested-name-specifier that will be used to qualify the 11068 // reference to operator=; this is required to suppress the virtual 11069 // call mechanism. 11070 CXXScopeSpec SS; 11071 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11072 SS.MakeTrivial(S.Context, 11073 NestedNameSpecifier::Create(S.Context, nullptr, false, 11074 CanonicalT), 11075 Loc); 11076 11077 // Create the reference to operator=. 11078 ExprResult OpEqualRef 11079 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 11080 SS, /*TemplateKWLoc=*/SourceLocation(), 11081 /*FirstQualifierInScope=*/nullptr, 11082 OpLookup, 11083 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11084 /*SuppressQualifierCheck=*/true); 11085 if (OpEqualRef.isInvalid()) 11086 return StmtError(); 11087 11088 // Build the call to the assignment operator. 11089 11090 Expr *FromInst = From.build(S, Loc); 11091 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11092 OpEqualRef.getAs<Expr>(), 11093 Loc, FromInst, Loc); 11094 if (Call.isInvalid()) 11095 return StmtError(); 11096 11097 // If we built a call to a trivial 'operator=' while copying an array, 11098 // bail out. We'll replace the whole shebang with a memcpy. 11099 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 11100 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 11101 return StmtResult((Stmt*)nullptr); 11102 11103 // Convert to an expression-statement, and clean up any produced 11104 // temporaries. 11105 return S.ActOnExprStmt(Call); 11106 } 11107 11108 // - if the subobject is of scalar type, the built-in assignment 11109 // operator is used. 11110 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 11111 if (!ArrayTy) { 11112 ExprResult Assignment = S.CreateBuiltinBinOp( 11113 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 11114 if (Assignment.isInvalid()) 11115 return StmtError(); 11116 return S.ActOnExprStmt(Assignment); 11117 } 11118 11119 // - if the subobject is an array, each element is assigned, in the 11120 // manner appropriate to the element type; 11121 11122 // Construct a loop over the array bounds, e.g., 11123 // 11124 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 11125 // 11126 // that will copy each of the array elements. 11127 QualType SizeType = S.Context.getSizeType(); 11128 11129 // Create the iteration variable. 11130 IdentifierInfo *IterationVarName = nullptr; 11131 { 11132 SmallString<8> Str; 11133 llvm::raw_svector_ostream OS(Str); 11134 OS << "__i" << Depth; 11135 IterationVarName = &S.Context.Idents.get(OS.str()); 11136 } 11137 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11138 IterationVarName, SizeType, 11139 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11140 SC_None); 11141 11142 // Initialize the iteration variable to zero. 11143 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 11144 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 11145 11146 // Creates a reference to the iteration variable. 11147 RefBuilder IterationVarRef(IterationVar, SizeType); 11148 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 11149 11150 // Create the DeclStmt that holds the iteration variable. 11151 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 11152 11153 // Subscript the "from" and "to" expressions with the iteration variable. 11154 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 11155 MoveCastBuilder FromIndexMove(FromIndexCopy); 11156 const ExprBuilder *FromIndex; 11157 if (Copying) 11158 FromIndex = &FromIndexCopy; 11159 else 11160 FromIndex = &FromIndexMove; 11161 11162 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 11163 11164 // Build the copy/move for an individual element of the array. 11165 StmtResult Copy = 11166 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 11167 ToIndex, *FromIndex, CopyingBaseSubobject, 11168 Copying, Depth + 1); 11169 // Bail out if copying fails or if we determined that we should use memcpy. 11170 if (Copy.isInvalid() || !Copy.get()) 11171 return Copy; 11172 11173 // Create the comparison against the array bound. 11174 llvm::APInt Upper 11175 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 11176 Expr *Comparison 11177 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 11178 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 11179 BO_NE, S.Context.BoolTy, 11180 VK_RValue, OK_Ordinary, Loc, FPOptions()); 11181 11182 // Create the pre-increment of the iteration variable. 11183 Expr *Increment 11184 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 11185 SizeType, VK_LValue, OK_Ordinary, Loc); 11186 11187 // Construct the loop that copies all elements of this array. 11188 return S.ActOnForStmt( 11189 Loc, Loc, InitStmt, 11190 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 11191 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 11192 } 11193 11194 static StmtResult 11195 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 11196 const ExprBuilder &To, const ExprBuilder &From, 11197 bool CopyingBaseSubobject, bool Copying) { 11198 // Maybe we should use a memcpy? 11199 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 11200 T.isTriviallyCopyableType(S.Context)) 11201 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11202 11203 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 11204 CopyingBaseSubobject, 11205 Copying, 0)); 11206 11207 // If we ended up picking a trivial assignment operator for an array of a 11208 // non-trivially-copyable class type, just emit a memcpy. 11209 if (!Result.isInvalid() && !Result.get()) 11210 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 11211 11212 return Result; 11213 } 11214 11215 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 11216 // Note: The following rules are largely analoguous to the copy 11217 // constructor rules. Note that virtual bases are not taken into account 11218 // for determining the argument type of the operator. Note also that 11219 // operators taking an object instead of a reference are allowed. 11220 assert(ClassDecl->needsImplicitCopyAssignment()); 11221 11222 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 11223 if (DSM.isAlreadyBeingDeclared()) 11224 return nullptr; 11225 11226 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11227 QualType RetType = Context.getLValueReferenceType(ArgType); 11228 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 11229 if (Const) 11230 ArgType = ArgType.withConst(); 11231 ArgType = Context.getLValueReferenceType(ArgType); 11232 11233 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11234 CXXCopyAssignment, 11235 Const); 11236 11237 // An implicitly-declared copy assignment operator is an inline public 11238 // member of its class. 11239 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11240 SourceLocation ClassLoc = ClassDecl->getLocation(); 11241 DeclarationNameInfo NameInfo(Name, ClassLoc); 11242 CXXMethodDecl *CopyAssignment = 11243 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11244 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11245 /*isInline=*/true, Constexpr, SourceLocation()); 11246 CopyAssignment->setAccess(AS_public); 11247 CopyAssignment->setDefaulted(); 11248 CopyAssignment->setImplicit(); 11249 11250 if (getLangOpts().CUDA) { 11251 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 11252 CopyAssignment, 11253 /* ConstRHS */ Const, 11254 /* Diagnose */ false); 11255 } 11256 11257 // Build an exception specification pointing back at this member. 11258 FunctionProtoType::ExtProtoInfo EPI = 11259 getImplicitMethodEPI(*this, CopyAssignment); 11260 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11261 11262 // Add the parameter to the operator. 11263 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 11264 ClassLoc, ClassLoc, 11265 /*Id=*/nullptr, ArgType, 11266 /*TInfo=*/nullptr, SC_None, 11267 nullptr); 11268 CopyAssignment->setParams(FromParam); 11269 11270 CopyAssignment->setTrivial( 11271 ClassDecl->needsOverloadResolutionForCopyAssignment() 11272 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 11273 : ClassDecl->hasTrivialCopyAssignment()); 11274 11275 // Note that we have added this copy-assignment operator. 11276 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 11277 11278 Scope *S = getScopeForContext(ClassDecl); 11279 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 11280 11281 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 11282 SetDeclDeleted(CopyAssignment, ClassLoc); 11283 11284 if (S) 11285 PushOnScopeChains(CopyAssignment, S, false); 11286 ClassDecl->addDecl(CopyAssignment); 11287 11288 return CopyAssignment; 11289 } 11290 11291 /// Diagnose an implicit copy operation for a class which is odr-used, but 11292 /// which is deprecated because the class has a user-declared copy constructor, 11293 /// copy assignment operator, or destructor. 11294 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 11295 assert(CopyOp->isImplicit()); 11296 11297 CXXRecordDecl *RD = CopyOp->getParent(); 11298 CXXMethodDecl *UserDeclaredOperation = nullptr; 11299 11300 // In Microsoft mode, assignment operations don't affect constructors and 11301 // vice versa. 11302 if (RD->hasUserDeclaredDestructor()) { 11303 UserDeclaredOperation = RD->getDestructor(); 11304 } else if (!isa<CXXConstructorDecl>(CopyOp) && 11305 RD->hasUserDeclaredCopyConstructor() && 11306 !S.getLangOpts().MSVCCompat) { 11307 // Find any user-declared copy constructor. 11308 for (auto *I : RD->ctors()) { 11309 if (I->isCopyConstructor()) { 11310 UserDeclaredOperation = I; 11311 break; 11312 } 11313 } 11314 assert(UserDeclaredOperation); 11315 } else if (isa<CXXConstructorDecl>(CopyOp) && 11316 RD->hasUserDeclaredCopyAssignment() && 11317 !S.getLangOpts().MSVCCompat) { 11318 // Find any user-declared move assignment operator. 11319 for (auto *I : RD->methods()) { 11320 if (I->isCopyAssignmentOperator()) { 11321 UserDeclaredOperation = I; 11322 break; 11323 } 11324 } 11325 assert(UserDeclaredOperation); 11326 } 11327 11328 if (UserDeclaredOperation) { 11329 S.Diag(UserDeclaredOperation->getLocation(), 11330 diag::warn_deprecated_copy_operation) 11331 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 11332 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 11333 } 11334 } 11335 11336 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 11337 CXXMethodDecl *CopyAssignOperator) { 11338 assert((CopyAssignOperator->isDefaulted() && 11339 CopyAssignOperator->isOverloadedOperator() && 11340 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 11341 !CopyAssignOperator->doesThisDeclarationHaveABody() && 11342 !CopyAssignOperator->isDeleted()) && 11343 "DefineImplicitCopyAssignment called for wrong function"); 11344 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 11345 return; 11346 11347 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 11348 if (ClassDecl->isInvalidDecl()) { 11349 CopyAssignOperator->setInvalidDecl(); 11350 return; 11351 } 11352 11353 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 11354 11355 // The exception specification is needed because we are defining the 11356 // function. 11357 ResolveExceptionSpec(CurrentLocation, 11358 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 11359 11360 // Add a context note for diagnostics produced after this point. 11361 Scope.addContextNote(CurrentLocation); 11362 11363 // C++11 [class.copy]p18: 11364 // The [definition of an implicitly declared copy assignment operator] is 11365 // deprecated if the class has a user-declared copy constructor or a 11366 // user-declared destructor. 11367 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 11368 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 11369 11370 // C++0x [class.copy]p30: 11371 // The implicitly-defined or explicitly-defaulted copy assignment operator 11372 // for a non-union class X performs memberwise copy assignment of its 11373 // subobjects. The direct base classes of X are assigned first, in the 11374 // order of their declaration in the base-specifier-list, and then the 11375 // immediate non-static data members of X are assigned, in the order in 11376 // which they were declared in the class definition. 11377 11378 // The statements that form the synthesized function body. 11379 SmallVector<Stmt*, 8> Statements; 11380 11381 // The parameter for the "other" object, which we are copying from. 11382 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 11383 Qualifiers OtherQuals = Other->getType().getQualifiers(); 11384 QualType OtherRefType = Other->getType(); 11385 if (const LValueReferenceType *OtherRef 11386 = OtherRefType->getAs<LValueReferenceType>()) { 11387 OtherRefType = OtherRef->getPointeeType(); 11388 OtherQuals = OtherRefType.getQualifiers(); 11389 } 11390 11391 // Our location for everything implicitly-generated. 11392 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 11393 ? CopyAssignOperator->getLocEnd() 11394 : CopyAssignOperator->getLocation(); 11395 11396 // Builds a DeclRefExpr for the "other" object. 11397 RefBuilder OtherRef(Other, OtherRefType); 11398 11399 // Builds the "this" pointer. 11400 ThisBuilder This; 11401 11402 // Assign base classes. 11403 bool Invalid = false; 11404 for (auto &Base : ClassDecl->bases()) { 11405 // Form the assignment: 11406 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 11407 QualType BaseType = Base.getType().getUnqualifiedType(); 11408 if (!BaseType->isRecordType()) { 11409 Invalid = true; 11410 continue; 11411 } 11412 11413 CXXCastPath BasePath; 11414 BasePath.push_back(&Base); 11415 11416 // Construct the "from" expression, which is an implicit cast to the 11417 // appropriately-qualified base type. 11418 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 11419 VK_LValue, BasePath); 11420 11421 // Dereference "this". 11422 DerefBuilder DerefThis(This); 11423 CastBuilder To(DerefThis, 11424 Context.getCVRQualifiedType( 11425 BaseType, CopyAssignOperator->getTypeQualifiers()), 11426 VK_LValue, BasePath); 11427 11428 // Build the copy. 11429 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 11430 To, From, 11431 /*CopyingBaseSubobject=*/true, 11432 /*Copying=*/true); 11433 if (Copy.isInvalid()) { 11434 CopyAssignOperator->setInvalidDecl(); 11435 return; 11436 } 11437 11438 // Success! Record the copy. 11439 Statements.push_back(Copy.getAs<Expr>()); 11440 } 11441 11442 // Assign non-static members. 11443 for (auto *Field : ClassDecl->fields()) { 11444 // FIXME: We should form some kind of AST representation for the implied 11445 // memcpy in a union copy operation. 11446 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11447 continue; 11448 11449 if (Field->isInvalidDecl()) { 11450 Invalid = true; 11451 continue; 11452 } 11453 11454 // Check for members of reference type; we can't copy those. 11455 if (Field->getType()->isReferenceType()) { 11456 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11457 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11458 Diag(Field->getLocation(), diag::note_declared_at); 11459 Invalid = true; 11460 continue; 11461 } 11462 11463 // Check for members of const-qualified, non-class type. 11464 QualType BaseType = Context.getBaseElementType(Field->getType()); 11465 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11466 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11467 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11468 Diag(Field->getLocation(), diag::note_declared_at); 11469 Invalid = true; 11470 continue; 11471 } 11472 11473 // Suppress assigning zero-width bitfields. 11474 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11475 continue; 11476 11477 QualType FieldType = Field->getType().getNonReferenceType(); 11478 if (FieldType->isIncompleteArrayType()) { 11479 assert(ClassDecl->hasFlexibleArrayMember() && 11480 "Incomplete array type is not valid"); 11481 continue; 11482 } 11483 11484 // Build references to the field in the object we're copying from and to. 11485 CXXScopeSpec SS; // Intentionally empty 11486 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11487 LookupMemberName); 11488 MemberLookup.addDecl(Field); 11489 MemberLookup.resolveKind(); 11490 11491 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 11492 11493 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 11494 11495 // Build the copy of this field. 11496 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 11497 To, From, 11498 /*CopyingBaseSubobject=*/false, 11499 /*Copying=*/true); 11500 if (Copy.isInvalid()) { 11501 CopyAssignOperator->setInvalidDecl(); 11502 return; 11503 } 11504 11505 // Success! Record the copy. 11506 Statements.push_back(Copy.getAs<Stmt>()); 11507 } 11508 11509 if (!Invalid) { 11510 // Add a "return *this;" 11511 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11512 11513 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11514 if (Return.isInvalid()) 11515 Invalid = true; 11516 else 11517 Statements.push_back(Return.getAs<Stmt>()); 11518 } 11519 11520 if (Invalid) { 11521 CopyAssignOperator->setInvalidDecl(); 11522 return; 11523 } 11524 11525 StmtResult Body; 11526 { 11527 CompoundScopeRAII CompoundScope(*this); 11528 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11529 /*isStmtExpr=*/false); 11530 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11531 } 11532 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 11533 CopyAssignOperator->markUsed(Context); 11534 11535 if (ASTMutationListener *L = getASTMutationListener()) { 11536 L->CompletedImplicitDefinition(CopyAssignOperator); 11537 } 11538 } 11539 11540 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 11541 assert(ClassDecl->needsImplicitMoveAssignment()); 11542 11543 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 11544 if (DSM.isAlreadyBeingDeclared()) 11545 return nullptr; 11546 11547 // Note: The following rules are largely analoguous to the move 11548 // constructor rules. 11549 11550 QualType ArgType = Context.getTypeDeclType(ClassDecl); 11551 QualType RetType = Context.getLValueReferenceType(ArgType); 11552 ArgType = Context.getRValueReferenceType(ArgType); 11553 11554 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11555 CXXMoveAssignment, 11556 false); 11557 11558 // An implicitly-declared move assignment operator is an inline public 11559 // member of its class. 11560 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11561 SourceLocation ClassLoc = ClassDecl->getLocation(); 11562 DeclarationNameInfo NameInfo(Name, ClassLoc); 11563 CXXMethodDecl *MoveAssignment = 11564 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 11565 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 11566 /*isInline=*/true, Constexpr, SourceLocation()); 11567 MoveAssignment->setAccess(AS_public); 11568 MoveAssignment->setDefaulted(); 11569 MoveAssignment->setImplicit(); 11570 11571 if (getLangOpts().CUDA) { 11572 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 11573 MoveAssignment, 11574 /* ConstRHS */ false, 11575 /* Diagnose */ false); 11576 } 11577 11578 // Build an exception specification pointing back at this member. 11579 FunctionProtoType::ExtProtoInfo EPI = 11580 getImplicitMethodEPI(*this, MoveAssignment); 11581 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 11582 11583 // Add the parameter to the operator. 11584 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 11585 ClassLoc, ClassLoc, 11586 /*Id=*/nullptr, ArgType, 11587 /*TInfo=*/nullptr, SC_None, 11588 nullptr); 11589 MoveAssignment->setParams(FromParam); 11590 11591 MoveAssignment->setTrivial( 11592 ClassDecl->needsOverloadResolutionForMoveAssignment() 11593 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 11594 : ClassDecl->hasTrivialMoveAssignment()); 11595 11596 // Note that we have added this copy-assignment operator. 11597 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 11598 11599 Scope *S = getScopeForContext(ClassDecl); 11600 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 11601 11602 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 11603 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 11604 SetDeclDeleted(MoveAssignment, ClassLoc); 11605 } 11606 11607 if (S) 11608 PushOnScopeChains(MoveAssignment, S, false); 11609 ClassDecl->addDecl(MoveAssignment); 11610 11611 return MoveAssignment; 11612 } 11613 11614 /// Check if we're implicitly defining a move assignment operator for a class 11615 /// with virtual bases. Such a move assignment might move-assign the virtual 11616 /// base multiple times. 11617 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 11618 SourceLocation CurrentLocation) { 11619 assert(!Class->isDependentContext() && "should not define dependent move"); 11620 11621 // Only a virtual base could get implicitly move-assigned multiple times. 11622 // Only a non-trivial move assignment can observe this. We only want to 11623 // diagnose if we implicitly define an assignment operator that assigns 11624 // two base classes, both of which move-assign the same virtual base. 11625 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 11626 Class->getNumBases() < 2) 11627 return; 11628 11629 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 11630 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 11631 VBaseMap VBases; 11632 11633 for (auto &BI : Class->bases()) { 11634 Worklist.push_back(&BI); 11635 while (!Worklist.empty()) { 11636 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 11637 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 11638 11639 // If the base has no non-trivial move assignment operators, 11640 // we don't care about moves from it. 11641 if (!Base->hasNonTrivialMoveAssignment()) 11642 continue; 11643 11644 // If there's nothing virtual here, skip it. 11645 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 11646 continue; 11647 11648 // If we're not actually going to call a move assignment for this base, 11649 // or the selected move assignment is trivial, skip it. 11650 Sema::SpecialMemberOverloadResult SMOR = 11651 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 11652 /*ConstArg*/false, /*VolatileArg*/false, 11653 /*RValueThis*/true, /*ConstThis*/false, 11654 /*VolatileThis*/false); 11655 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 11656 !SMOR.getMethod()->isMoveAssignmentOperator()) 11657 continue; 11658 11659 if (BaseSpec->isVirtual()) { 11660 // We're going to move-assign this virtual base, and its move 11661 // assignment operator is not trivial. If this can happen for 11662 // multiple distinct direct bases of Class, diagnose it. (If it 11663 // only happens in one base, we'll diagnose it when synthesizing 11664 // that base class's move assignment operator.) 11665 CXXBaseSpecifier *&Existing = 11666 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 11667 .first->second; 11668 if (Existing && Existing != &BI) { 11669 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 11670 << Class << Base; 11671 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 11672 << (Base->getCanonicalDecl() == 11673 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11674 << Base << Existing->getType() << Existing->getSourceRange(); 11675 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 11676 << (Base->getCanonicalDecl() == 11677 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 11678 << Base << BI.getType() << BaseSpec->getSourceRange(); 11679 11680 // Only diagnose each vbase once. 11681 Existing = nullptr; 11682 } 11683 } else { 11684 // Only walk over bases that have defaulted move assignment operators. 11685 // We assume that any user-provided move assignment operator handles 11686 // the multiple-moves-of-vbase case itself somehow. 11687 if (!SMOR.getMethod()->isDefaulted()) 11688 continue; 11689 11690 // We're going to move the base classes of Base. Add them to the list. 11691 for (auto &BI : Base->bases()) 11692 Worklist.push_back(&BI); 11693 } 11694 } 11695 } 11696 } 11697 11698 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 11699 CXXMethodDecl *MoveAssignOperator) { 11700 assert((MoveAssignOperator->isDefaulted() && 11701 MoveAssignOperator->isOverloadedOperator() && 11702 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 11703 !MoveAssignOperator->doesThisDeclarationHaveABody() && 11704 !MoveAssignOperator->isDeleted()) && 11705 "DefineImplicitMoveAssignment called for wrong function"); 11706 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 11707 return; 11708 11709 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 11710 if (ClassDecl->isInvalidDecl()) { 11711 MoveAssignOperator->setInvalidDecl(); 11712 return; 11713 } 11714 11715 // C++0x [class.copy]p28: 11716 // The implicitly-defined or move assignment operator for a non-union class 11717 // X performs memberwise move assignment of its subobjects. The direct base 11718 // classes of X are assigned first, in the order of their declaration in the 11719 // base-specifier-list, and then the immediate non-static data members of X 11720 // are assigned, in the order in which they were declared in the class 11721 // definition. 11722 11723 // Issue a warning if our implicit move assignment operator will move 11724 // from a virtual base more than once. 11725 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 11726 11727 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 11728 11729 // The exception specification is needed because we are defining the 11730 // function. 11731 ResolveExceptionSpec(CurrentLocation, 11732 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 11733 11734 // Add a context note for diagnostics produced after this point. 11735 Scope.addContextNote(CurrentLocation); 11736 11737 // The statements that form the synthesized function body. 11738 SmallVector<Stmt*, 8> Statements; 11739 11740 // The parameter for the "other" object, which we are move from. 11741 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 11742 QualType OtherRefType = Other->getType()-> 11743 getAs<RValueReferenceType>()->getPointeeType(); 11744 assert(!OtherRefType.getQualifiers() && 11745 "Bad argument type of defaulted move assignment"); 11746 11747 // Our location for everything implicitly-generated. 11748 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 11749 ? MoveAssignOperator->getLocEnd() 11750 : MoveAssignOperator->getLocation(); 11751 11752 // Builds a reference to the "other" object. 11753 RefBuilder OtherRef(Other, OtherRefType); 11754 // Cast to rvalue. 11755 MoveCastBuilder MoveOther(OtherRef); 11756 11757 // Builds the "this" pointer. 11758 ThisBuilder This; 11759 11760 // Assign base classes. 11761 bool Invalid = false; 11762 for (auto &Base : ClassDecl->bases()) { 11763 // C++11 [class.copy]p28: 11764 // It is unspecified whether subobjects representing virtual base classes 11765 // are assigned more than once by the implicitly-defined copy assignment 11766 // operator. 11767 // FIXME: Do not assign to a vbase that will be assigned by some other base 11768 // class. For a move-assignment, this can result in the vbase being moved 11769 // multiple times. 11770 11771 // Form the assignment: 11772 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 11773 QualType BaseType = Base.getType().getUnqualifiedType(); 11774 if (!BaseType->isRecordType()) { 11775 Invalid = true; 11776 continue; 11777 } 11778 11779 CXXCastPath BasePath; 11780 BasePath.push_back(&Base); 11781 11782 // Construct the "from" expression, which is an implicit cast to the 11783 // appropriately-qualified base type. 11784 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 11785 11786 // Dereference "this". 11787 DerefBuilder DerefThis(This); 11788 11789 // Implicitly cast "this" to the appropriately-qualified base type. 11790 CastBuilder To(DerefThis, 11791 Context.getCVRQualifiedType( 11792 BaseType, MoveAssignOperator->getTypeQualifiers()), 11793 VK_LValue, BasePath); 11794 11795 // Build the move. 11796 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 11797 To, From, 11798 /*CopyingBaseSubobject=*/true, 11799 /*Copying=*/false); 11800 if (Move.isInvalid()) { 11801 MoveAssignOperator->setInvalidDecl(); 11802 return; 11803 } 11804 11805 // Success! Record the move. 11806 Statements.push_back(Move.getAs<Expr>()); 11807 } 11808 11809 // Assign non-static members. 11810 for (auto *Field : ClassDecl->fields()) { 11811 // FIXME: We should form some kind of AST representation for the implied 11812 // memcpy in a union copy operation. 11813 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 11814 continue; 11815 11816 if (Field->isInvalidDecl()) { 11817 Invalid = true; 11818 continue; 11819 } 11820 11821 // Check for members of reference type; we can't move those. 11822 if (Field->getType()->isReferenceType()) { 11823 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11824 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 11825 Diag(Field->getLocation(), diag::note_declared_at); 11826 Invalid = true; 11827 continue; 11828 } 11829 11830 // Check for members of const-qualified, non-class type. 11831 QualType BaseType = Context.getBaseElementType(Field->getType()); 11832 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 11833 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 11834 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 11835 Diag(Field->getLocation(), diag::note_declared_at); 11836 Invalid = true; 11837 continue; 11838 } 11839 11840 // Suppress assigning zero-width bitfields. 11841 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 11842 continue; 11843 11844 QualType FieldType = Field->getType().getNonReferenceType(); 11845 if (FieldType->isIncompleteArrayType()) { 11846 assert(ClassDecl->hasFlexibleArrayMember() && 11847 "Incomplete array type is not valid"); 11848 continue; 11849 } 11850 11851 // Build references to the field in the object we're copying from and to. 11852 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 11853 LookupMemberName); 11854 MemberLookup.addDecl(Field); 11855 MemberLookup.resolveKind(); 11856 MemberBuilder From(MoveOther, OtherRefType, 11857 /*IsArrow=*/false, MemberLookup); 11858 MemberBuilder To(This, getCurrentThisType(), 11859 /*IsArrow=*/true, MemberLookup); 11860 11861 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 11862 "Member reference with rvalue base must be rvalue except for reference " 11863 "members, which aren't allowed for move assignment."); 11864 11865 // Build the move of this field. 11866 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 11867 To, From, 11868 /*CopyingBaseSubobject=*/false, 11869 /*Copying=*/false); 11870 if (Move.isInvalid()) { 11871 MoveAssignOperator->setInvalidDecl(); 11872 return; 11873 } 11874 11875 // Success! Record the copy. 11876 Statements.push_back(Move.getAs<Stmt>()); 11877 } 11878 11879 if (!Invalid) { 11880 // Add a "return *this;" 11881 ExprResult ThisObj = 11882 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 11883 11884 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 11885 if (Return.isInvalid()) 11886 Invalid = true; 11887 else 11888 Statements.push_back(Return.getAs<Stmt>()); 11889 } 11890 11891 if (Invalid) { 11892 MoveAssignOperator->setInvalidDecl(); 11893 return; 11894 } 11895 11896 StmtResult Body; 11897 { 11898 CompoundScopeRAII CompoundScope(*this); 11899 Body = ActOnCompoundStmt(Loc, Loc, Statements, 11900 /*isStmtExpr=*/false); 11901 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 11902 } 11903 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 11904 MoveAssignOperator->markUsed(Context); 11905 11906 if (ASTMutationListener *L = getASTMutationListener()) { 11907 L->CompletedImplicitDefinition(MoveAssignOperator); 11908 } 11909 } 11910 11911 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 11912 CXXRecordDecl *ClassDecl) { 11913 // C++ [class.copy]p4: 11914 // If the class definition does not explicitly declare a copy 11915 // constructor, one is declared implicitly. 11916 assert(ClassDecl->needsImplicitCopyConstructor()); 11917 11918 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 11919 if (DSM.isAlreadyBeingDeclared()) 11920 return nullptr; 11921 11922 QualType ClassType = Context.getTypeDeclType(ClassDecl); 11923 QualType ArgType = ClassType; 11924 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 11925 if (Const) 11926 ArgType = ArgType.withConst(); 11927 ArgType = Context.getLValueReferenceType(ArgType); 11928 11929 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11930 CXXCopyConstructor, 11931 Const); 11932 11933 DeclarationName Name 11934 = Context.DeclarationNames.getCXXConstructorName( 11935 Context.getCanonicalType(ClassType)); 11936 SourceLocation ClassLoc = ClassDecl->getLocation(); 11937 DeclarationNameInfo NameInfo(Name, ClassLoc); 11938 11939 // An implicitly-declared copy constructor is an inline public 11940 // member of its class. 11941 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 11942 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 11943 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11944 Constexpr); 11945 CopyConstructor->setAccess(AS_public); 11946 CopyConstructor->setDefaulted(); 11947 11948 if (getLangOpts().CUDA) { 11949 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 11950 CopyConstructor, 11951 /* ConstRHS */ Const, 11952 /* Diagnose */ false); 11953 } 11954 11955 // Build an exception specification pointing back at this member. 11956 FunctionProtoType::ExtProtoInfo EPI = 11957 getImplicitMethodEPI(*this, CopyConstructor); 11958 CopyConstructor->setType( 11959 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 11960 11961 // Add the parameter to the constructor. 11962 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 11963 ClassLoc, ClassLoc, 11964 /*IdentifierInfo=*/nullptr, 11965 ArgType, /*TInfo=*/nullptr, 11966 SC_None, nullptr); 11967 CopyConstructor->setParams(FromParam); 11968 11969 CopyConstructor->setTrivial( 11970 ClassDecl->needsOverloadResolutionForCopyConstructor() 11971 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 11972 : ClassDecl->hasTrivialCopyConstructor()); 11973 11974 // Note that we have declared this constructor. 11975 ++ASTContext::NumImplicitCopyConstructorsDeclared; 11976 11977 Scope *S = getScopeForContext(ClassDecl); 11978 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 11979 11980 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 11981 ClassDecl->setImplicitCopyConstructorIsDeleted(); 11982 SetDeclDeleted(CopyConstructor, ClassLoc); 11983 } 11984 11985 if (S) 11986 PushOnScopeChains(CopyConstructor, S, false); 11987 ClassDecl->addDecl(CopyConstructor); 11988 11989 return CopyConstructor; 11990 } 11991 11992 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 11993 CXXConstructorDecl *CopyConstructor) { 11994 assert((CopyConstructor->isDefaulted() && 11995 CopyConstructor->isCopyConstructor() && 11996 !CopyConstructor->doesThisDeclarationHaveABody() && 11997 !CopyConstructor->isDeleted()) && 11998 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 11999 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12000 return; 12001 12002 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12003 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12004 12005 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12006 12007 // The exception specification is needed because we are defining the 12008 // function. 12009 ResolveExceptionSpec(CurrentLocation, 12010 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12011 MarkVTableUsed(CurrentLocation, ClassDecl); 12012 12013 // Add a context note for diagnostics produced after this point. 12014 Scope.addContextNote(CurrentLocation); 12015 12016 // C++11 [class.copy]p7: 12017 // The [definition of an implicitly declared copy constructor] is 12018 // deprecated if the class has a user-declared copy assignment operator 12019 // or a user-declared destructor. 12020 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12021 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12022 12023 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12024 CopyConstructor->setInvalidDecl(); 12025 } else { 12026 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 12027 ? CopyConstructor->getLocEnd() 12028 : CopyConstructor->getLocation(); 12029 Sema::CompoundScopeRAII CompoundScope(*this); 12030 CopyConstructor->setBody( 12031 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12032 CopyConstructor->markUsed(Context); 12033 } 12034 12035 if (ASTMutationListener *L = getASTMutationListener()) { 12036 L->CompletedImplicitDefinition(CopyConstructor); 12037 } 12038 } 12039 12040 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12041 CXXRecordDecl *ClassDecl) { 12042 assert(ClassDecl->needsImplicitMoveConstructor()); 12043 12044 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12045 if (DSM.isAlreadyBeingDeclared()) 12046 return nullptr; 12047 12048 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12049 QualType ArgType = Context.getRValueReferenceType(ClassType); 12050 12051 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12052 CXXMoveConstructor, 12053 false); 12054 12055 DeclarationName Name 12056 = Context.DeclarationNames.getCXXConstructorName( 12057 Context.getCanonicalType(ClassType)); 12058 SourceLocation ClassLoc = ClassDecl->getLocation(); 12059 DeclarationNameInfo NameInfo(Name, ClassLoc); 12060 12061 // C++11 [class.copy]p11: 12062 // An implicitly-declared copy/move constructor is an inline public 12063 // member of its class. 12064 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12065 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12066 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12067 Constexpr); 12068 MoveConstructor->setAccess(AS_public); 12069 MoveConstructor->setDefaulted(); 12070 12071 if (getLangOpts().CUDA) { 12072 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12073 MoveConstructor, 12074 /* ConstRHS */ false, 12075 /* Diagnose */ false); 12076 } 12077 12078 // Build an exception specification pointing back at this member. 12079 FunctionProtoType::ExtProtoInfo EPI = 12080 getImplicitMethodEPI(*this, MoveConstructor); 12081 MoveConstructor->setType( 12082 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 12083 12084 // Add the parameter to the constructor. 12085 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 12086 ClassLoc, ClassLoc, 12087 /*IdentifierInfo=*/nullptr, 12088 ArgType, /*TInfo=*/nullptr, 12089 SC_None, nullptr); 12090 MoveConstructor->setParams(FromParam); 12091 12092 MoveConstructor->setTrivial( 12093 ClassDecl->needsOverloadResolutionForMoveConstructor() 12094 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 12095 : ClassDecl->hasTrivialMoveConstructor()); 12096 12097 // Note that we have declared this constructor. 12098 ++ASTContext::NumImplicitMoveConstructorsDeclared; 12099 12100 Scope *S = getScopeForContext(ClassDecl); 12101 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 12102 12103 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 12104 ClassDecl->setImplicitMoveConstructorIsDeleted(); 12105 SetDeclDeleted(MoveConstructor, ClassLoc); 12106 } 12107 12108 if (S) 12109 PushOnScopeChains(MoveConstructor, S, false); 12110 ClassDecl->addDecl(MoveConstructor); 12111 12112 return MoveConstructor; 12113 } 12114 12115 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 12116 CXXConstructorDecl *MoveConstructor) { 12117 assert((MoveConstructor->isDefaulted() && 12118 MoveConstructor->isMoveConstructor() && 12119 !MoveConstructor->doesThisDeclarationHaveABody() && 12120 !MoveConstructor->isDeleted()) && 12121 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 12122 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 12123 return; 12124 12125 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 12126 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 12127 12128 SynthesizedFunctionScope Scope(*this, MoveConstructor); 12129 12130 // The exception specification is needed because we are defining the 12131 // function. 12132 ResolveExceptionSpec(CurrentLocation, 12133 MoveConstructor->getType()->castAs<FunctionProtoType>()); 12134 MarkVTableUsed(CurrentLocation, ClassDecl); 12135 12136 // Add a context note for diagnostics produced after this point. 12137 Scope.addContextNote(CurrentLocation); 12138 12139 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 12140 MoveConstructor->setInvalidDecl(); 12141 } else { 12142 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 12143 ? MoveConstructor->getLocEnd() 12144 : MoveConstructor->getLocation(); 12145 Sema::CompoundScopeRAII CompoundScope(*this); 12146 MoveConstructor->setBody(ActOnCompoundStmt( 12147 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 12148 MoveConstructor->markUsed(Context); 12149 } 12150 12151 if (ASTMutationListener *L = getASTMutationListener()) { 12152 L->CompletedImplicitDefinition(MoveConstructor); 12153 } 12154 } 12155 12156 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 12157 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 12158 } 12159 12160 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 12161 SourceLocation CurrentLocation, 12162 CXXConversionDecl *Conv) { 12163 SynthesizedFunctionScope Scope(*this, Conv); 12164 12165 CXXRecordDecl *Lambda = Conv->getParent(); 12166 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 12167 // If we are defining a specialization of a conversion to function-ptr 12168 // cache the deduced template arguments for this specialization 12169 // so that we can use them to retrieve the corresponding call-operator 12170 // and static-invoker. 12171 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 12172 12173 // Retrieve the corresponding call-operator specialization. 12174 if (Lambda->isGenericLambda()) { 12175 assert(Conv->isFunctionTemplateSpecialization()); 12176 FunctionTemplateDecl *CallOpTemplate = 12177 CallOp->getDescribedFunctionTemplate(); 12178 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 12179 void *InsertPos = nullptr; 12180 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 12181 DeducedTemplateArgs->asArray(), 12182 InsertPos); 12183 assert(CallOpSpec && 12184 "Conversion operator must have a corresponding call operator"); 12185 CallOp = cast<CXXMethodDecl>(CallOpSpec); 12186 } 12187 12188 // Mark the call operator referenced (and add to pending instantiations 12189 // if necessary). 12190 // For both the conversion and static-invoker template specializations 12191 // we construct their body's in this function, so no need to add them 12192 // to the PendingInstantiations. 12193 MarkFunctionReferenced(CurrentLocation, CallOp); 12194 12195 // Retrieve the static invoker... 12196 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 12197 // ... and get the corresponding specialization for a generic lambda. 12198 if (Lambda->isGenericLambda()) { 12199 assert(DeducedTemplateArgs && 12200 "Must have deduced template arguments from Conversion Operator"); 12201 FunctionTemplateDecl *InvokeTemplate = 12202 Invoker->getDescribedFunctionTemplate(); 12203 void *InsertPos = nullptr; 12204 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 12205 DeducedTemplateArgs->asArray(), 12206 InsertPos); 12207 assert(InvokeSpec && 12208 "Must have a corresponding static invoker specialization"); 12209 Invoker = cast<CXXMethodDecl>(InvokeSpec); 12210 } 12211 // Construct the body of the conversion function { return __invoke; }. 12212 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 12213 VK_LValue, Conv->getLocation()).get(); 12214 assert(FunctionRef && "Can't refer to __invoke function?"); 12215 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 12216 Conv->setBody(new (Context) CompoundStmt(Context, Return, 12217 Conv->getLocation(), 12218 Conv->getLocation())); 12219 12220 Conv->markUsed(Context); 12221 Conv->setReferenced(); 12222 12223 // Fill in the __invoke function with a dummy implementation. IR generation 12224 // will fill in the actual details. 12225 Invoker->markUsed(Context); 12226 Invoker->setReferenced(); 12227 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 12228 12229 if (ASTMutationListener *L = getASTMutationListener()) { 12230 L->CompletedImplicitDefinition(Conv); 12231 L->CompletedImplicitDefinition(Invoker); 12232 } 12233 } 12234 12235 12236 12237 void Sema::DefineImplicitLambdaToBlockPointerConversion( 12238 SourceLocation CurrentLocation, 12239 CXXConversionDecl *Conv) 12240 { 12241 assert(!Conv->getParent()->isGenericLambda()); 12242 12243 SynthesizedFunctionScope Scope(*this, Conv); 12244 12245 // Copy-initialize the lambda object as needed to capture it. 12246 Expr *This = ActOnCXXThis(CurrentLocation).get(); 12247 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 12248 12249 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 12250 Conv->getLocation(), 12251 Conv, DerefThis); 12252 12253 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 12254 // behavior. Note that only the general conversion function does this 12255 // (since it's unusable otherwise); in the case where we inline the 12256 // block literal, it has block literal lifetime semantics. 12257 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 12258 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 12259 CK_CopyAndAutoreleaseBlockObject, 12260 BuildBlock.get(), nullptr, VK_RValue); 12261 12262 if (BuildBlock.isInvalid()) { 12263 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12264 Conv->setInvalidDecl(); 12265 return; 12266 } 12267 12268 // Create the return statement that returns the block from the conversion 12269 // function. 12270 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 12271 if (Return.isInvalid()) { 12272 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 12273 Conv->setInvalidDecl(); 12274 return; 12275 } 12276 12277 // Set the body of the conversion function. 12278 Stmt *ReturnS = Return.get(); 12279 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 12280 Conv->getLocation(), 12281 Conv->getLocation())); 12282 Conv->markUsed(Context); 12283 12284 // We're done; notify the mutation listener, if any. 12285 if (ASTMutationListener *L = getASTMutationListener()) { 12286 L->CompletedImplicitDefinition(Conv); 12287 } 12288 } 12289 12290 /// \brief Determine whether the given list arguments contains exactly one 12291 /// "real" (non-default) argument. 12292 static bool hasOneRealArgument(MultiExprArg Args) { 12293 switch (Args.size()) { 12294 case 0: 12295 return false; 12296 12297 default: 12298 if (!Args[1]->isDefaultArgument()) 12299 return false; 12300 12301 // fall through 12302 case 1: 12303 return !Args[0]->isDefaultArgument(); 12304 } 12305 12306 return false; 12307 } 12308 12309 ExprResult 12310 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12311 NamedDecl *FoundDecl, 12312 CXXConstructorDecl *Constructor, 12313 MultiExprArg ExprArgs, 12314 bool HadMultipleCandidates, 12315 bool IsListInitialization, 12316 bool IsStdInitListInitialization, 12317 bool RequiresZeroInit, 12318 unsigned ConstructKind, 12319 SourceRange ParenRange) { 12320 bool Elidable = false; 12321 12322 // C++0x [class.copy]p34: 12323 // When certain criteria are met, an implementation is allowed to 12324 // omit the copy/move construction of a class object, even if the 12325 // copy/move constructor and/or destructor for the object have 12326 // side effects. [...] 12327 // - when a temporary class object that has not been bound to a 12328 // reference (12.2) would be copied/moved to a class object 12329 // with the same cv-unqualified type, the copy/move operation 12330 // can be omitted by constructing the temporary object 12331 // directly into the target of the omitted copy/move 12332 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 12333 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 12334 Expr *SubExpr = ExprArgs[0]; 12335 Elidable = SubExpr->isTemporaryObject( 12336 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 12337 } 12338 12339 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 12340 FoundDecl, Constructor, 12341 Elidable, ExprArgs, HadMultipleCandidates, 12342 IsListInitialization, 12343 IsStdInitListInitialization, RequiresZeroInit, 12344 ConstructKind, ParenRange); 12345 } 12346 12347 ExprResult 12348 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12349 NamedDecl *FoundDecl, 12350 CXXConstructorDecl *Constructor, 12351 bool Elidable, 12352 MultiExprArg ExprArgs, 12353 bool HadMultipleCandidates, 12354 bool IsListInitialization, 12355 bool IsStdInitListInitialization, 12356 bool RequiresZeroInit, 12357 unsigned ConstructKind, 12358 SourceRange ParenRange) { 12359 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 12360 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 12361 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 12362 return ExprError(); 12363 } 12364 12365 return BuildCXXConstructExpr( 12366 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 12367 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 12368 RequiresZeroInit, ConstructKind, ParenRange); 12369 } 12370 12371 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 12372 /// including handling of its default argument expressions. 12373 ExprResult 12374 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 12375 CXXConstructorDecl *Constructor, 12376 bool Elidable, 12377 MultiExprArg ExprArgs, 12378 bool HadMultipleCandidates, 12379 bool IsListInitialization, 12380 bool IsStdInitListInitialization, 12381 bool RequiresZeroInit, 12382 unsigned ConstructKind, 12383 SourceRange ParenRange) { 12384 assert(declaresSameEntity( 12385 Constructor->getParent(), 12386 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 12387 "given constructor for wrong type"); 12388 MarkFunctionReferenced(ConstructLoc, Constructor); 12389 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 12390 return ExprError(); 12391 12392 return CXXConstructExpr::Create( 12393 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 12394 ExprArgs, HadMultipleCandidates, IsListInitialization, 12395 IsStdInitListInitialization, RequiresZeroInit, 12396 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 12397 ParenRange); 12398 } 12399 12400 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 12401 assert(Field->hasInClassInitializer()); 12402 12403 // If we already have the in-class initializer nothing needs to be done. 12404 if (Field->getInClassInitializer()) 12405 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12406 12407 // If we might have already tried and failed to instantiate, don't try again. 12408 if (Field->isInvalidDecl()) 12409 return ExprError(); 12410 12411 // Maybe we haven't instantiated the in-class initializer. Go check the 12412 // pattern FieldDecl to see if it has one. 12413 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 12414 12415 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 12416 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 12417 DeclContext::lookup_result Lookup = 12418 ClassPattern->lookup(Field->getDeclName()); 12419 12420 // Lookup can return at most two results: the pattern for the field, or the 12421 // injected class name of the parent record. No other member can have the 12422 // same name as the field. 12423 // In modules mode, lookup can return multiple results (coming from 12424 // different modules). 12425 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 12426 "more than two lookup results for field name"); 12427 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 12428 if (!Pattern) { 12429 assert(isa<CXXRecordDecl>(Lookup[0]) && 12430 "cannot have other non-field member with same name"); 12431 for (auto L : Lookup) 12432 if (isa<FieldDecl>(L)) { 12433 Pattern = cast<FieldDecl>(L); 12434 break; 12435 } 12436 assert(Pattern && "We must have set the Pattern!"); 12437 } 12438 12439 if (InstantiateInClassInitializer(Loc, Field, Pattern, 12440 getTemplateInstantiationArgs(Field))) { 12441 // Don't diagnose this again. 12442 Field->setInvalidDecl(); 12443 return ExprError(); 12444 } 12445 return CXXDefaultInitExpr::Create(Context, Loc, Field); 12446 } 12447 12448 // DR1351: 12449 // If the brace-or-equal-initializer of a non-static data member 12450 // invokes a defaulted default constructor of its class or of an 12451 // enclosing class in a potentially evaluated subexpression, the 12452 // program is ill-formed. 12453 // 12454 // This resolution is unworkable: the exception specification of the 12455 // default constructor can be needed in an unevaluated context, in 12456 // particular, in the operand of a noexcept-expression, and we can be 12457 // unable to compute an exception specification for an enclosed class. 12458 // 12459 // Any attempt to resolve the exception specification of a defaulted default 12460 // constructor before the initializer is lexically complete will ultimately 12461 // come here at which point we can diagnose it. 12462 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 12463 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 12464 << OutermostClass << Field; 12465 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed); 12466 // Recover by marking the field invalid, unless we're in a SFINAE context. 12467 if (!isSFINAEContext()) 12468 Field->setInvalidDecl(); 12469 return ExprError(); 12470 } 12471 12472 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 12473 if (VD->isInvalidDecl()) return; 12474 12475 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 12476 if (ClassDecl->isInvalidDecl()) return; 12477 if (ClassDecl->hasIrrelevantDestructor()) return; 12478 if (ClassDecl->isDependentContext()) return; 12479 12480 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12481 MarkFunctionReferenced(VD->getLocation(), Destructor); 12482 CheckDestructorAccess(VD->getLocation(), Destructor, 12483 PDiag(diag::err_access_dtor_var) 12484 << VD->getDeclName() 12485 << VD->getType()); 12486 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 12487 12488 if (Destructor->isTrivial()) return; 12489 if (!VD->hasGlobalStorage()) return; 12490 12491 // Emit warning for non-trivial dtor in global scope (a real global, 12492 // class-static, function-static). 12493 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 12494 12495 // TODO: this should be re-enabled for static locals by !CXAAtExit 12496 if (!VD->isStaticLocal()) 12497 Diag(VD->getLocation(), diag::warn_global_destructor); 12498 } 12499 12500 /// \brief Given a constructor and the set of arguments provided for the 12501 /// constructor, convert the arguments and add any required default arguments 12502 /// to form a proper call to this constructor. 12503 /// 12504 /// \returns true if an error occurred, false otherwise. 12505 bool 12506 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 12507 MultiExprArg ArgsPtr, 12508 SourceLocation Loc, 12509 SmallVectorImpl<Expr*> &ConvertedArgs, 12510 bool AllowExplicit, 12511 bool IsListInitialization) { 12512 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 12513 unsigned NumArgs = ArgsPtr.size(); 12514 Expr **Args = ArgsPtr.data(); 12515 12516 const FunctionProtoType *Proto 12517 = Constructor->getType()->getAs<FunctionProtoType>(); 12518 assert(Proto && "Constructor without a prototype?"); 12519 unsigned NumParams = Proto->getNumParams(); 12520 12521 // If too few arguments are available, we'll fill in the rest with defaults. 12522 if (NumArgs < NumParams) 12523 ConvertedArgs.reserve(NumParams); 12524 else 12525 ConvertedArgs.reserve(NumArgs); 12526 12527 VariadicCallType CallType = 12528 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 12529 SmallVector<Expr *, 8> AllArgs; 12530 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 12531 Proto, 0, 12532 llvm::makeArrayRef(Args, NumArgs), 12533 AllArgs, 12534 CallType, AllowExplicit, 12535 IsListInitialization); 12536 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 12537 12538 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 12539 12540 CheckConstructorCall(Constructor, 12541 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 12542 Proto, Loc); 12543 12544 return Invalid; 12545 } 12546 12547 static inline bool 12548 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 12549 const FunctionDecl *FnDecl) { 12550 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 12551 if (isa<NamespaceDecl>(DC)) { 12552 return SemaRef.Diag(FnDecl->getLocation(), 12553 diag::err_operator_new_delete_declared_in_namespace) 12554 << FnDecl->getDeclName(); 12555 } 12556 12557 if (isa<TranslationUnitDecl>(DC) && 12558 FnDecl->getStorageClass() == SC_Static) { 12559 return SemaRef.Diag(FnDecl->getLocation(), 12560 diag::err_operator_new_delete_declared_static) 12561 << FnDecl->getDeclName(); 12562 } 12563 12564 return false; 12565 } 12566 12567 static inline bool 12568 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 12569 CanQualType ExpectedResultType, 12570 CanQualType ExpectedFirstParamType, 12571 unsigned DependentParamTypeDiag, 12572 unsigned InvalidParamTypeDiag) { 12573 QualType ResultType = 12574 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 12575 12576 // Check that the result type is not dependent. 12577 if (ResultType->isDependentType()) 12578 return SemaRef.Diag(FnDecl->getLocation(), 12579 diag::err_operator_new_delete_dependent_result_type) 12580 << FnDecl->getDeclName() << ExpectedResultType; 12581 12582 // Check that the result type is what we expect. 12583 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 12584 return SemaRef.Diag(FnDecl->getLocation(), 12585 diag::err_operator_new_delete_invalid_result_type) 12586 << FnDecl->getDeclName() << ExpectedResultType; 12587 12588 // A function template must have at least 2 parameters. 12589 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 12590 return SemaRef.Diag(FnDecl->getLocation(), 12591 diag::err_operator_new_delete_template_too_few_parameters) 12592 << FnDecl->getDeclName(); 12593 12594 // The function decl must have at least 1 parameter. 12595 if (FnDecl->getNumParams() == 0) 12596 return SemaRef.Diag(FnDecl->getLocation(), 12597 diag::err_operator_new_delete_too_few_parameters) 12598 << FnDecl->getDeclName(); 12599 12600 // Check the first parameter type is not dependent. 12601 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 12602 if (FirstParamType->isDependentType()) 12603 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 12604 << FnDecl->getDeclName() << ExpectedFirstParamType; 12605 12606 // Check that the first parameter type is what we expect. 12607 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 12608 ExpectedFirstParamType) 12609 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 12610 << FnDecl->getDeclName() << ExpectedFirstParamType; 12611 12612 return false; 12613 } 12614 12615 static bool 12616 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 12617 // C++ [basic.stc.dynamic.allocation]p1: 12618 // A program is ill-formed if an allocation function is declared in a 12619 // namespace scope other than global scope or declared static in global 12620 // scope. 12621 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12622 return true; 12623 12624 CanQualType SizeTy = 12625 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 12626 12627 // C++ [basic.stc.dynamic.allocation]p1: 12628 // The return type shall be void*. The first parameter shall have type 12629 // std::size_t. 12630 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 12631 SizeTy, 12632 diag::err_operator_new_dependent_param_type, 12633 diag::err_operator_new_param_type)) 12634 return true; 12635 12636 // C++ [basic.stc.dynamic.allocation]p1: 12637 // The first parameter shall not have an associated default argument. 12638 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 12639 return SemaRef.Diag(FnDecl->getLocation(), 12640 diag::err_operator_new_default_arg) 12641 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 12642 12643 return false; 12644 } 12645 12646 static bool 12647 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 12648 // C++ [basic.stc.dynamic.deallocation]p1: 12649 // A program is ill-formed if deallocation functions are declared in a 12650 // namespace scope other than global scope or declared static in global 12651 // scope. 12652 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 12653 return true; 12654 12655 // C++ [basic.stc.dynamic.deallocation]p2: 12656 // Each deallocation function shall return void and its first parameter 12657 // shall be void*. 12658 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 12659 SemaRef.Context.VoidPtrTy, 12660 diag::err_operator_delete_dependent_param_type, 12661 diag::err_operator_delete_param_type)) 12662 return true; 12663 12664 return false; 12665 } 12666 12667 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 12668 /// of this overloaded operator is well-formed. If so, returns false; 12669 /// otherwise, emits appropriate diagnostics and returns true. 12670 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 12671 assert(FnDecl && FnDecl->isOverloadedOperator() && 12672 "Expected an overloaded operator declaration"); 12673 12674 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 12675 12676 // C++ [over.oper]p5: 12677 // The allocation and deallocation functions, operator new, 12678 // operator new[], operator delete and operator delete[], are 12679 // described completely in 3.7.3. The attributes and restrictions 12680 // found in the rest of this subclause do not apply to them unless 12681 // explicitly stated in 3.7.3. 12682 if (Op == OO_Delete || Op == OO_Array_Delete) 12683 return CheckOperatorDeleteDeclaration(*this, FnDecl); 12684 12685 if (Op == OO_New || Op == OO_Array_New) 12686 return CheckOperatorNewDeclaration(*this, FnDecl); 12687 12688 // C++ [over.oper]p6: 12689 // An operator function shall either be a non-static member 12690 // function or be a non-member function and have at least one 12691 // parameter whose type is a class, a reference to a class, an 12692 // enumeration, or a reference to an enumeration. 12693 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 12694 if (MethodDecl->isStatic()) 12695 return Diag(FnDecl->getLocation(), 12696 diag::err_operator_overload_static) << FnDecl->getDeclName(); 12697 } else { 12698 bool ClassOrEnumParam = false; 12699 for (auto Param : FnDecl->parameters()) { 12700 QualType ParamType = Param->getType().getNonReferenceType(); 12701 if (ParamType->isDependentType() || ParamType->isRecordType() || 12702 ParamType->isEnumeralType()) { 12703 ClassOrEnumParam = true; 12704 break; 12705 } 12706 } 12707 12708 if (!ClassOrEnumParam) 12709 return Diag(FnDecl->getLocation(), 12710 diag::err_operator_overload_needs_class_or_enum) 12711 << FnDecl->getDeclName(); 12712 } 12713 12714 // C++ [over.oper]p8: 12715 // An operator function cannot have default arguments (8.3.6), 12716 // except where explicitly stated below. 12717 // 12718 // Only the function-call operator allows default arguments 12719 // (C++ [over.call]p1). 12720 if (Op != OO_Call) { 12721 for (auto Param : FnDecl->parameters()) { 12722 if (Param->hasDefaultArg()) 12723 return Diag(Param->getLocation(), 12724 diag::err_operator_overload_default_arg) 12725 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 12726 } 12727 } 12728 12729 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 12730 { false, false, false } 12731 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 12732 , { Unary, Binary, MemberOnly } 12733 #include "clang/Basic/OperatorKinds.def" 12734 }; 12735 12736 bool CanBeUnaryOperator = OperatorUses[Op][0]; 12737 bool CanBeBinaryOperator = OperatorUses[Op][1]; 12738 bool MustBeMemberOperator = OperatorUses[Op][2]; 12739 12740 // C++ [over.oper]p8: 12741 // [...] Operator functions cannot have more or fewer parameters 12742 // than the number required for the corresponding operator, as 12743 // described in the rest of this subclause. 12744 unsigned NumParams = FnDecl->getNumParams() 12745 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 12746 if (Op != OO_Call && 12747 ((NumParams == 1 && !CanBeUnaryOperator) || 12748 (NumParams == 2 && !CanBeBinaryOperator) || 12749 (NumParams < 1) || (NumParams > 2))) { 12750 // We have the wrong number of parameters. 12751 unsigned ErrorKind; 12752 if (CanBeUnaryOperator && CanBeBinaryOperator) { 12753 ErrorKind = 2; // 2 -> unary or binary. 12754 } else if (CanBeUnaryOperator) { 12755 ErrorKind = 0; // 0 -> unary 12756 } else { 12757 assert(CanBeBinaryOperator && 12758 "All non-call overloaded operators are unary or binary!"); 12759 ErrorKind = 1; // 1 -> binary 12760 } 12761 12762 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 12763 << FnDecl->getDeclName() << NumParams << ErrorKind; 12764 } 12765 12766 // Overloaded operators other than operator() cannot be variadic. 12767 if (Op != OO_Call && 12768 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 12769 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 12770 << FnDecl->getDeclName(); 12771 } 12772 12773 // Some operators must be non-static member functions. 12774 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 12775 return Diag(FnDecl->getLocation(), 12776 diag::err_operator_overload_must_be_member) 12777 << FnDecl->getDeclName(); 12778 } 12779 12780 // C++ [over.inc]p1: 12781 // The user-defined function called operator++ implements the 12782 // prefix and postfix ++ operator. If this function is a member 12783 // function with no parameters, or a non-member function with one 12784 // parameter of class or enumeration type, it defines the prefix 12785 // increment operator ++ for objects of that type. If the function 12786 // is a member function with one parameter (which shall be of type 12787 // int) or a non-member function with two parameters (the second 12788 // of which shall be of type int), it defines the postfix 12789 // increment operator ++ for objects of that type. 12790 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 12791 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 12792 QualType ParamType = LastParam->getType(); 12793 12794 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 12795 !ParamType->isDependentType()) 12796 return Diag(LastParam->getLocation(), 12797 diag::err_operator_overload_post_incdec_must_be_int) 12798 << LastParam->getType() << (Op == OO_MinusMinus); 12799 } 12800 12801 return false; 12802 } 12803 12804 static bool 12805 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 12806 FunctionTemplateDecl *TpDecl) { 12807 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 12808 12809 // Must have one or two template parameters. 12810 if (TemplateParams->size() == 1) { 12811 NonTypeTemplateParmDecl *PmDecl = 12812 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 12813 12814 // The template parameter must be a char parameter pack. 12815 if (PmDecl && PmDecl->isTemplateParameterPack() && 12816 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 12817 return false; 12818 12819 } else if (TemplateParams->size() == 2) { 12820 TemplateTypeParmDecl *PmType = 12821 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 12822 NonTypeTemplateParmDecl *PmArgs = 12823 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 12824 12825 // The second template parameter must be a parameter pack with the 12826 // first template parameter as its type. 12827 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 12828 PmArgs->isTemplateParameterPack()) { 12829 const TemplateTypeParmType *TArgs = 12830 PmArgs->getType()->getAs<TemplateTypeParmType>(); 12831 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 12832 TArgs->getIndex() == PmType->getIndex()) { 12833 if (!SemaRef.inTemplateInstantiation()) 12834 SemaRef.Diag(TpDecl->getLocation(), 12835 diag::ext_string_literal_operator_template); 12836 return false; 12837 } 12838 } 12839 } 12840 12841 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 12842 diag::err_literal_operator_template) 12843 << TpDecl->getTemplateParameters()->getSourceRange(); 12844 return true; 12845 } 12846 12847 /// CheckLiteralOperatorDeclaration - Check whether the declaration 12848 /// of this literal operator function is well-formed. If so, returns 12849 /// false; otherwise, emits appropriate diagnostics and returns true. 12850 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 12851 if (isa<CXXMethodDecl>(FnDecl)) { 12852 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 12853 << FnDecl->getDeclName(); 12854 return true; 12855 } 12856 12857 if (FnDecl->isExternC()) { 12858 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 12859 if (const LinkageSpecDecl *LSD = 12860 FnDecl->getDeclContext()->getExternCContext()) 12861 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 12862 return true; 12863 } 12864 12865 // This might be the definition of a literal operator template. 12866 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 12867 12868 // This might be a specialization of a literal operator template. 12869 if (!TpDecl) 12870 TpDecl = FnDecl->getPrimaryTemplate(); 12871 12872 // template <char...> type operator "" name() and 12873 // template <class T, T...> type operator "" name() are the only valid 12874 // template signatures, and the only valid signatures with no parameters. 12875 if (TpDecl) { 12876 if (FnDecl->param_size() != 0) { 12877 Diag(FnDecl->getLocation(), 12878 diag::err_literal_operator_template_with_params); 12879 return true; 12880 } 12881 12882 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 12883 return true; 12884 12885 } else if (FnDecl->param_size() == 1) { 12886 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 12887 12888 QualType ParamType = Param->getType().getUnqualifiedType(); 12889 12890 // Only unsigned long long int, long double, any character type, and const 12891 // char * are allowed as the only parameters. 12892 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 12893 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 12894 Context.hasSameType(ParamType, Context.CharTy) || 12895 Context.hasSameType(ParamType, Context.WideCharTy) || 12896 Context.hasSameType(ParamType, Context.Char16Ty) || 12897 Context.hasSameType(ParamType, Context.Char32Ty)) { 12898 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 12899 QualType InnerType = Ptr->getPointeeType(); 12900 12901 // Pointer parameter must be a const char *. 12902 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 12903 Context.CharTy) && 12904 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 12905 Diag(Param->getSourceRange().getBegin(), 12906 diag::err_literal_operator_param) 12907 << ParamType << "'const char *'" << Param->getSourceRange(); 12908 return true; 12909 } 12910 12911 } else if (ParamType->isRealFloatingType()) { 12912 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12913 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 12914 return true; 12915 12916 } else if (ParamType->isIntegerType()) { 12917 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 12918 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 12919 return true; 12920 12921 } else { 12922 Diag(Param->getSourceRange().getBegin(), 12923 diag::err_literal_operator_invalid_param) 12924 << ParamType << Param->getSourceRange(); 12925 return true; 12926 } 12927 12928 } else if (FnDecl->param_size() == 2) { 12929 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 12930 12931 // First, verify that the first parameter is correct. 12932 12933 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 12934 12935 // Two parameter function must have a pointer to const as a 12936 // first parameter; let's strip those qualifiers. 12937 const PointerType *PT = FirstParamType->getAs<PointerType>(); 12938 12939 if (!PT) { 12940 Diag((*Param)->getSourceRange().getBegin(), 12941 diag::err_literal_operator_param) 12942 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12943 return true; 12944 } 12945 12946 QualType PointeeType = PT->getPointeeType(); 12947 // First parameter must be const 12948 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 12949 Diag((*Param)->getSourceRange().getBegin(), 12950 diag::err_literal_operator_param) 12951 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12952 return true; 12953 } 12954 12955 QualType InnerType = PointeeType.getUnqualifiedType(); 12956 // Only const char *, const wchar_t*, const char16_t*, and const char32_t* 12957 // are allowed as the first parameter to a two-parameter function 12958 if (!(Context.hasSameType(InnerType, Context.CharTy) || 12959 Context.hasSameType(InnerType, Context.WideCharTy) || 12960 Context.hasSameType(InnerType, Context.Char16Ty) || 12961 Context.hasSameType(InnerType, Context.Char32Ty))) { 12962 Diag((*Param)->getSourceRange().getBegin(), 12963 diag::err_literal_operator_param) 12964 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 12965 return true; 12966 } 12967 12968 // Move on to the second and final parameter. 12969 ++Param; 12970 12971 // The second parameter must be a std::size_t. 12972 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 12973 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 12974 Diag((*Param)->getSourceRange().getBegin(), 12975 diag::err_literal_operator_param) 12976 << SecondParamType << Context.getSizeType() 12977 << (*Param)->getSourceRange(); 12978 return true; 12979 } 12980 } else { 12981 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 12982 return true; 12983 } 12984 12985 // Parameters are good. 12986 12987 // A parameter-declaration-clause containing a default argument is not 12988 // equivalent to any of the permitted forms. 12989 for (auto Param : FnDecl->parameters()) { 12990 if (Param->hasDefaultArg()) { 12991 Diag(Param->getDefaultArgRange().getBegin(), 12992 diag::err_literal_operator_default_argument) 12993 << Param->getDefaultArgRange(); 12994 break; 12995 } 12996 } 12997 12998 StringRef LiteralName 12999 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13000 if (LiteralName[0] != '_') { 13001 // C++11 [usrlit.suffix]p1: 13002 // Literal suffix identifiers that do not start with an underscore 13003 // are reserved for future standardization. 13004 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13005 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13006 } 13007 13008 return false; 13009 } 13010 13011 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13012 /// linkage specification, including the language and (if present) 13013 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13014 /// language string literal. LBraceLoc, if valid, provides the location of 13015 /// the '{' brace. Otherwise, this linkage specification does not 13016 /// have any braces. 13017 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13018 Expr *LangStr, 13019 SourceLocation LBraceLoc) { 13020 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13021 if (!Lit->isAscii()) { 13022 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13023 << LangStr->getSourceRange(); 13024 return nullptr; 13025 } 13026 13027 StringRef Lang = Lit->getString(); 13028 LinkageSpecDecl::LanguageIDs Language; 13029 if (Lang == "C") 13030 Language = LinkageSpecDecl::lang_c; 13031 else if (Lang == "C++") 13032 Language = LinkageSpecDecl::lang_cxx; 13033 else { 13034 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 13035 << LangStr->getSourceRange(); 13036 return nullptr; 13037 } 13038 13039 // FIXME: Add all the various semantics of linkage specifications 13040 13041 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 13042 LangStr->getExprLoc(), Language, 13043 LBraceLoc.isValid()); 13044 CurContext->addDecl(D); 13045 PushDeclContext(S, D); 13046 return D; 13047 } 13048 13049 /// ActOnFinishLinkageSpecification - Complete the definition of 13050 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 13051 /// valid, it's the position of the closing '}' brace in a linkage 13052 /// specification that uses braces. 13053 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 13054 Decl *LinkageSpec, 13055 SourceLocation RBraceLoc) { 13056 if (RBraceLoc.isValid()) { 13057 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 13058 LSDecl->setRBraceLoc(RBraceLoc); 13059 } 13060 PopDeclContext(); 13061 return LinkageSpec; 13062 } 13063 13064 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 13065 AttributeList *AttrList, 13066 SourceLocation SemiLoc) { 13067 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 13068 // Attribute declarations appertain to empty declaration so we handle 13069 // them here. 13070 if (AttrList) 13071 ProcessDeclAttributeList(S, ED, AttrList); 13072 13073 CurContext->addDecl(ED); 13074 return ED; 13075 } 13076 13077 /// \brief Perform semantic analysis for the variable declaration that 13078 /// occurs within a C++ catch clause, returning the newly-created 13079 /// variable. 13080 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 13081 TypeSourceInfo *TInfo, 13082 SourceLocation StartLoc, 13083 SourceLocation Loc, 13084 IdentifierInfo *Name) { 13085 bool Invalid = false; 13086 QualType ExDeclType = TInfo->getType(); 13087 13088 // Arrays and functions decay. 13089 if (ExDeclType->isArrayType()) 13090 ExDeclType = Context.getArrayDecayedType(ExDeclType); 13091 else if (ExDeclType->isFunctionType()) 13092 ExDeclType = Context.getPointerType(ExDeclType); 13093 13094 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 13095 // The exception-declaration shall not denote a pointer or reference to an 13096 // incomplete type, other than [cv] void*. 13097 // N2844 forbids rvalue references. 13098 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 13099 Diag(Loc, diag::err_catch_rvalue_ref); 13100 Invalid = true; 13101 } 13102 13103 if (ExDeclType->isVariablyModifiedType()) { 13104 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 13105 Invalid = true; 13106 } 13107 13108 QualType BaseType = ExDeclType; 13109 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 13110 unsigned DK = diag::err_catch_incomplete; 13111 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 13112 BaseType = Ptr->getPointeeType(); 13113 Mode = 1; 13114 DK = diag::err_catch_incomplete_ptr; 13115 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 13116 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 13117 BaseType = Ref->getPointeeType(); 13118 Mode = 2; 13119 DK = diag::err_catch_incomplete_ref; 13120 } 13121 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 13122 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 13123 Invalid = true; 13124 13125 if (!Invalid && !ExDeclType->isDependentType() && 13126 RequireNonAbstractType(Loc, ExDeclType, 13127 diag::err_abstract_type_in_decl, 13128 AbstractVariableType)) 13129 Invalid = true; 13130 13131 // Only the non-fragile NeXT runtime currently supports C++ catches 13132 // of ObjC types, and no runtime supports catching ObjC types by value. 13133 if (!Invalid && getLangOpts().ObjC1) { 13134 QualType T = ExDeclType; 13135 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 13136 T = RT->getPointeeType(); 13137 13138 if (T->isObjCObjectType()) { 13139 Diag(Loc, diag::err_objc_object_catch); 13140 Invalid = true; 13141 } else if (T->isObjCObjectPointerType()) { 13142 // FIXME: should this be a test for macosx-fragile specifically? 13143 if (getLangOpts().ObjCRuntime.isFragile()) 13144 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 13145 } 13146 } 13147 13148 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 13149 ExDeclType, TInfo, SC_None); 13150 ExDecl->setExceptionVariable(true); 13151 13152 // In ARC, infer 'retaining' for variables of retainable type. 13153 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 13154 Invalid = true; 13155 13156 if (!Invalid && !ExDeclType->isDependentType()) { 13157 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 13158 // Insulate this from anything else we might currently be parsing. 13159 EnterExpressionEvaluationContext scope( 13160 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 13161 13162 // C++ [except.handle]p16: 13163 // The object declared in an exception-declaration or, if the 13164 // exception-declaration does not specify a name, a temporary (12.2) is 13165 // copy-initialized (8.5) from the exception object. [...] 13166 // The object is destroyed when the handler exits, after the destruction 13167 // of any automatic objects initialized within the handler. 13168 // 13169 // We just pretend to initialize the object with itself, then make sure 13170 // it can be destroyed later. 13171 QualType initType = Context.getExceptionObjectType(ExDeclType); 13172 13173 InitializedEntity entity = 13174 InitializedEntity::InitializeVariable(ExDecl); 13175 InitializationKind initKind = 13176 InitializationKind::CreateCopy(Loc, SourceLocation()); 13177 13178 Expr *opaqueValue = 13179 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 13180 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 13181 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 13182 if (result.isInvalid()) 13183 Invalid = true; 13184 else { 13185 // If the constructor used was non-trivial, set this as the 13186 // "initializer". 13187 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 13188 if (!construct->getConstructor()->isTrivial()) { 13189 Expr *init = MaybeCreateExprWithCleanups(construct); 13190 ExDecl->setInit(init); 13191 } 13192 13193 // And make sure it's destructable. 13194 FinalizeVarWithDestructor(ExDecl, recordType); 13195 } 13196 } 13197 } 13198 13199 if (Invalid) 13200 ExDecl->setInvalidDecl(); 13201 13202 return ExDecl; 13203 } 13204 13205 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 13206 /// handler. 13207 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 13208 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13209 bool Invalid = D.isInvalidType(); 13210 13211 // Check for unexpanded parameter packs. 13212 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13213 UPPC_ExceptionType)) { 13214 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13215 D.getIdentifierLoc()); 13216 Invalid = true; 13217 } 13218 13219 IdentifierInfo *II = D.getIdentifier(); 13220 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 13221 LookupOrdinaryName, 13222 ForRedeclaration)) { 13223 // The scope should be freshly made just for us. There is just no way 13224 // it contains any previous declaration, except for function parameters in 13225 // a function-try-block's catch statement. 13226 assert(!S->isDeclScope(PrevDecl)); 13227 if (isDeclInScope(PrevDecl, CurContext, S)) { 13228 Diag(D.getIdentifierLoc(), diag::err_redefinition) 13229 << D.getIdentifier(); 13230 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13231 Invalid = true; 13232 } else if (PrevDecl->isTemplateParameter()) 13233 // Maybe we will complain about the shadowed template parameter. 13234 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13235 } 13236 13237 if (D.getCXXScopeSpec().isSet() && !Invalid) { 13238 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 13239 << D.getCXXScopeSpec().getRange(); 13240 Invalid = true; 13241 } 13242 13243 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 13244 D.getLocStart(), 13245 D.getIdentifierLoc(), 13246 D.getIdentifier()); 13247 if (Invalid) 13248 ExDecl->setInvalidDecl(); 13249 13250 // Add the exception declaration into this scope. 13251 if (II) 13252 PushOnScopeChains(ExDecl, S); 13253 else 13254 CurContext->addDecl(ExDecl); 13255 13256 ProcessDeclAttributes(S, ExDecl, D); 13257 return ExDecl; 13258 } 13259 13260 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13261 Expr *AssertExpr, 13262 Expr *AssertMessageExpr, 13263 SourceLocation RParenLoc) { 13264 StringLiteral *AssertMessage = 13265 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 13266 13267 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 13268 return nullptr; 13269 13270 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 13271 AssertMessage, RParenLoc, false); 13272 } 13273 13274 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 13275 Expr *AssertExpr, 13276 StringLiteral *AssertMessage, 13277 SourceLocation RParenLoc, 13278 bool Failed) { 13279 assert(AssertExpr != nullptr && "Expected non-null condition"); 13280 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 13281 !Failed) { 13282 // In a static_assert-declaration, the constant-expression shall be a 13283 // constant expression that can be contextually converted to bool. 13284 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 13285 if (Converted.isInvalid()) 13286 Failed = true; 13287 13288 llvm::APSInt Cond; 13289 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 13290 diag::err_static_assert_expression_is_not_constant, 13291 /*AllowFold=*/false).isInvalid()) 13292 Failed = true; 13293 13294 if (!Failed && !Cond) { 13295 SmallString<256> MsgBuffer; 13296 llvm::raw_svector_ostream Msg(MsgBuffer); 13297 if (AssertMessage) 13298 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 13299 Diag(StaticAssertLoc, diag::err_static_assert_failed) 13300 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 13301 Failed = true; 13302 } 13303 } 13304 13305 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 13306 /*DiscardedValue*/false, 13307 /*IsConstexpr*/true); 13308 if (FullAssertExpr.isInvalid()) 13309 Failed = true; 13310 else 13311 AssertExpr = FullAssertExpr.get(); 13312 13313 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 13314 AssertExpr, AssertMessage, RParenLoc, 13315 Failed); 13316 13317 CurContext->addDecl(Decl); 13318 return Decl; 13319 } 13320 13321 /// \brief Perform semantic analysis of the given friend type declaration. 13322 /// 13323 /// \returns A friend declaration that. 13324 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 13325 SourceLocation FriendLoc, 13326 TypeSourceInfo *TSInfo) { 13327 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 13328 13329 QualType T = TSInfo->getType(); 13330 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 13331 13332 // C++03 [class.friend]p2: 13333 // An elaborated-type-specifier shall be used in a friend declaration 13334 // for a class.* 13335 // 13336 // * The class-key of the elaborated-type-specifier is required. 13337 if (!CodeSynthesisContexts.empty()) { 13338 // Do not complain about the form of friend template types during any kind 13339 // of code synthesis. For template instantiation, we will have complained 13340 // when the template was defined. 13341 } else { 13342 if (!T->isElaboratedTypeSpecifier()) { 13343 // If we evaluated the type to a record type, suggest putting 13344 // a tag in front. 13345 if (const RecordType *RT = T->getAs<RecordType>()) { 13346 RecordDecl *RD = RT->getDecl(); 13347 13348 SmallString<16> InsertionText(" "); 13349 InsertionText += RD->getKindName(); 13350 13351 Diag(TypeRange.getBegin(), 13352 getLangOpts().CPlusPlus11 ? 13353 diag::warn_cxx98_compat_unelaborated_friend_type : 13354 diag::ext_unelaborated_friend_type) 13355 << (unsigned) RD->getTagKind() 13356 << T 13357 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 13358 InsertionText); 13359 } else { 13360 Diag(FriendLoc, 13361 getLangOpts().CPlusPlus11 ? 13362 diag::warn_cxx98_compat_nonclass_type_friend : 13363 diag::ext_nonclass_type_friend) 13364 << T 13365 << TypeRange; 13366 } 13367 } else if (T->getAs<EnumType>()) { 13368 Diag(FriendLoc, 13369 getLangOpts().CPlusPlus11 ? 13370 diag::warn_cxx98_compat_enum_friend : 13371 diag::ext_enum_friend) 13372 << T 13373 << TypeRange; 13374 } 13375 13376 // C++11 [class.friend]p3: 13377 // A friend declaration that does not declare a function shall have one 13378 // of the following forms: 13379 // friend elaborated-type-specifier ; 13380 // friend simple-type-specifier ; 13381 // friend typename-specifier ; 13382 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 13383 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 13384 } 13385 13386 // If the type specifier in a friend declaration designates a (possibly 13387 // cv-qualified) class type, that class is declared as a friend; otherwise, 13388 // the friend declaration is ignored. 13389 return FriendDecl::Create(Context, CurContext, 13390 TSInfo->getTypeLoc().getLocStart(), TSInfo, 13391 FriendLoc); 13392 } 13393 13394 /// Handle a friend tag declaration where the scope specifier was 13395 /// templated. 13396 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 13397 unsigned TagSpec, SourceLocation TagLoc, 13398 CXXScopeSpec &SS, 13399 IdentifierInfo *Name, 13400 SourceLocation NameLoc, 13401 AttributeList *Attr, 13402 MultiTemplateParamsArg TempParamLists) { 13403 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13404 13405 bool IsMemberSpecialization = false; 13406 bool Invalid = false; 13407 13408 if (TemplateParameterList *TemplateParams = 13409 MatchTemplateParametersToScopeSpecifier( 13410 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 13411 IsMemberSpecialization, Invalid)) { 13412 if (TemplateParams->size() > 0) { 13413 // This is a declaration of a class template. 13414 if (Invalid) 13415 return nullptr; 13416 13417 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 13418 NameLoc, Attr, TemplateParams, AS_public, 13419 /*ModulePrivateLoc=*/SourceLocation(), 13420 FriendLoc, TempParamLists.size() - 1, 13421 TempParamLists.data()).get(); 13422 } else { 13423 // The "template<>" header is extraneous. 13424 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13425 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13426 IsMemberSpecialization = true; 13427 } 13428 } 13429 13430 if (Invalid) return nullptr; 13431 13432 bool isAllExplicitSpecializations = true; 13433 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 13434 if (TempParamLists[I]->size()) { 13435 isAllExplicitSpecializations = false; 13436 break; 13437 } 13438 } 13439 13440 // FIXME: don't ignore attributes. 13441 13442 // If it's explicit specializations all the way down, just forget 13443 // about the template header and build an appropriate non-templated 13444 // friend. TODO: for source fidelity, remember the headers. 13445 if (isAllExplicitSpecializations) { 13446 if (SS.isEmpty()) { 13447 bool Owned = false; 13448 bool IsDependent = false; 13449 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 13450 Attr, AS_public, 13451 /*ModulePrivateLoc=*/SourceLocation(), 13452 MultiTemplateParamsArg(), Owned, IsDependent, 13453 /*ScopedEnumKWLoc=*/SourceLocation(), 13454 /*ScopedEnumUsesClassTag=*/false, 13455 /*UnderlyingType=*/TypeResult(), 13456 /*IsTypeSpecifier=*/false, 13457 /*IsTemplateParamOrArg=*/false); 13458 } 13459 13460 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 13461 ElaboratedTypeKeyword Keyword 13462 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13463 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 13464 *Name, NameLoc); 13465 if (T.isNull()) 13466 return nullptr; 13467 13468 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13469 if (isa<DependentNameType>(T)) { 13470 DependentNameTypeLoc TL = 13471 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13472 TL.setElaboratedKeywordLoc(TagLoc); 13473 TL.setQualifierLoc(QualifierLoc); 13474 TL.setNameLoc(NameLoc); 13475 } else { 13476 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 13477 TL.setElaboratedKeywordLoc(TagLoc); 13478 TL.setQualifierLoc(QualifierLoc); 13479 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 13480 } 13481 13482 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13483 TSI, FriendLoc, TempParamLists); 13484 Friend->setAccess(AS_public); 13485 CurContext->addDecl(Friend); 13486 return Friend; 13487 } 13488 13489 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 13490 13491 13492 13493 // Handle the case of a templated-scope friend class. e.g. 13494 // template <class T> class A<T>::B; 13495 // FIXME: we don't support these right now. 13496 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 13497 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 13498 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 13499 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 13500 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 13501 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 13502 TL.setElaboratedKeywordLoc(TagLoc); 13503 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 13504 TL.setNameLoc(NameLoc); 13505 13506 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 13507 TSI, FriendLoc, TempParamLists); 13508 Friend->setAccess(AS_public); 13509 Friend->setUnsupportedFriend(true); 13510 CurContext->addDecl(Friend); 13511 return Friend; 13512 } 13513 13514 13515 /// Handle a friend type declaration. This works in tandem with 13516 /// ActOnTag. 13517 /// 13518 /// Notes on friend class templates: 13519 /// 13520 /// We generally treat friend class declarations as if they were 13521 /// declaring a class. So, for example, the elaborated type specifier 13522 /// in a friend declaration is required to obey the restrictions of a 13523 /// class-head (i.e. no typedefs in the scope chain), template 13524 /// parameters are required to match up with simple template-ids, &c. 13525 /// However, unlike when declaring a template specialization, it's 13526 /// okay to refer to a template specialization without an empty 13527 /// template parameter declaration, e.g. 13528 /// friend class A<T>::B<unsigned>; 13529 /// We permit this as a special case; if there are any template 13530 /// parameters present at all, require proper matching, i.e. 13531 /// template <> template \<class T> friend class A<int>::B; 13532 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 13533 MultiTemplateParamsArg TempParams) { 13534 SourceLocation Loc = DS.getLocStart(); 13535 13536 assert(DS.isFriendSpecified()); 13537 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13538 13539 // Try to convert the decl specifier to a type. This works for 13540 // friend templates because ActOnTag never produces a ClassTemplateDecl 13541 // for a TUK_Friend. 13542 Declarator TheDeclarator(DS, Declarator::MemberContext); 13543 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 13544 QualType T = TSI->getType(); 13545 if (TheDeclarator.isInvalidType()) 13546 return nullptr; 13547 13548 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 13549 return nullptr; 13550 13551 // This is definitely an error in C++98. It's probably meant to 13552 // be forbidden in C++0x, too, but the specification is just 13553 // poorly written. 13554 // 13555 // The problem is with declarations like the following: 13556 // template <T> friend A<T>::foo; 13557 // where deciding whether a class C is a friend or not now hinges 13558 // on whether there exists an instantiation of A that causes 13559 // 'foo' to equal C. There are restrictions on class-heads 13560 // (which we declare (by fiat) elaborated friend declarations to 13561 // be) that makes this tractable. 13562 // 13563 // FIXME: handle "template <> friend class A<T>;", which 13564 // is possibly well-formed? Who even knows? 13565 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 13566 Diag(Loc, diag::err_tagless_friend_type_template) 13567 << DS.getSourceRange(); 13568 return nullptr; 13569 } 13570 13571 // C++98 [class.friend]p1: A friend of a class is a function 13572 // or class that is not a member of the class . . . 13573 // This is fixed in DR77, which just barely didn't make the C++03 13574 // deadline. It's also a very silly restriction that seriously 13575 // affects inner classes and which nobody else seems to implement; 13576 // thus we never diagnose it, not even in -pedantic. 13577 // 13578 // But note that we could warn about it: it's always useless to 13579 // friend one of your own members (it's not, however, worthless to 13580 // friend a member of an arbitrary specialization of your template). 13581 13582 Decl *D; 13583 if (!TempParams.empty()) 13584 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 13585 TempParams, 13586 TSI, 13587 DS.getFriendSpecLoc()); 13588 else 13589 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 13590 13591 if (!D) 13592 return nullptr; 13593 13594 D->setAccess(AS_public); 13595 CurContext->addDecl(D); 13596 13597 return D; 13598 } 13599 13600 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 13601 MultiTemplateParamsArg TemplateParams) { 13602 const DeclSpec &DS = D.getDeclSpec(); 13603 13604 assert(DS.isFriendSpecified()); 13605 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 13606 13607 SourceLocation Loc = D.getIdentifierLoc(); 13608 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13609 13610 // C++ [class.friend]p1 13611 // A friend of a class is a function or class.... 13612 // Note that this sees through typedefs, which is intended. 13613 // It *doesn't* see through dependent types, which is correct 13614 // according to [temp.arg.type]p3: 13615 // If a declaration acquires a function type through a 13616 // type dependent on a template-parameter and this causes 13617 // a declaration that does not use the syntactic form of a 13618 // function declarator to have a function type, the program 13619 // is ill-formed. 13620 if (!TInfo->getType()->isFunctionType()) { 13621 Diag(Loc, diag::err_unexpected_friend); 13622 13623 // It might be worthwhile to try to recover by creating an 13624 // appropriate declaration. 13625 return nullptr; 13626 } 13627 13628 // C++ [namespace.memdef]p3 13629 // - If a friend declaration in a non-local class first declares a 13630 // class or function, the friend class or function is a member 13631 // of the innermost enclosing namespace. 13632 // - The name of the friend is not found by simple name lookup 13633 // until a matching declaration is provided in that namespace 13634 // scope (either before or after the class declaration granting 13635 // friendship). 13636 // - If a friend function is called, its name may be found by the 13637 // name lookup that considers functions from namespaces and 13638 // classes associated with the types of the function arguments. 13639 // - When looking for a prior declaration of a class or a function 13640 // declared as a friend, scopes outside the innermost enclosing 13641 // namespace scope are not considered. 13642 13643 CXXScopeSpec &SS = D.getCXXScopeSpec(); 13644 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 13645 DeclarationName Name = NameInfo.getName(); 13646 assert(Name); 13647 13648 // Check for unexpanded parameter packs. 13649 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 13650 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 13651 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 13652 return nullptr; 13653 13654 // The context we found the declaration in, or in which we should 13655 // create the declaration. 13656 DeclContext *DC; 13657 Scope *DCScope = S; 13658 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 13659 ForRedeclaration); 13660 13661 // There are five cases here. 13662 // - There's no scope specifier and we're in a local class. Only look 13663 // for functions declared in the immediately-enclosing block scope. 13664 // We recover from invalid scope qualifiers as if they just weren't there. 13665 FunctionDecl *FunctionContainingLocalClass = nullptr; 13666 if ((SS.isInvalid() || !SS.isSet()) && 13667 (FunctionContainingLocalClass = 13668 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 13669 // C++11 [class.friend]p11: 13670 // If a friend declaration appears in a local class and the name 13671 // specified is an unqualified name, a prior declaration is 13672 // looked up without considering scopes that are outside the 13673 // innermost enclosing non-class scope. For a friend function 13674 // declaration, if there is no prior declaration, the program is 13675 // ill-formed. 13676 13677 // Find the innermost enclosing non-class scope. This is the block 13678 // scope containing the local class definition (or for a nested class, 13679 // the outer local class). 13680 DCScope = S->getFnParent(); 13681 13682 // Look up the function name in the scope. 13683 Previous.clear(LookupLocalFriendName); 13684 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 13685 13686 if (!Previous.empty()) { 13687 // All possible previous declarations must have the same context: 13688 // either they were declared at block scope or they are members of 13689 // one of the enclosing local classes. 13690 DC = Previous.getRepresentativeDecl()->getDeclContext(); 13691 } else { 13692 // This is ill-formed, but provide the context that we would have 13693 // declared the function in, if we were permitted to, for error recovery. 13694 DC = FunctionContainingLocalClass; 13695 } 13696 adjustContextForLocalExternDecl(DC); 13697 13698 // C++ [class.friend]p6: 13699 // A function can be defined in a friend declaration of a class if and 13700 // only if the class is a non-local class (9.8), the function name is 13701 // unqualified, and the function has namespace scope. 13702 if (D.isFunctionDefinition()) { 13703 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 13704 } 13705 13706 // - There's no scope specifier, in which case we just go to the 13707 // appropriate scope and look for a function or function template 13708 // there as appropriate. 13709 } else if (SS.isInvalid() || !SS.isSet()) { 13710 // C++11 [namespace.memdef]p3: 13711 // If the name in a friend declaration is neither qualified nor 13712 // a template-id and the declaration is a function or an 13713 // elaborated-type-specifier, the lookup to determine whether 13714 // the entity has been previously declared shall not consider 13715 // any scopes outside the innermost enclosing namespace. 13716 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 13717 13718 // Find the appropriate context according to the above. 13719 DC = CurContext; 13720 13721 // Skip class contexts. If someone can cite chapter and verse 13722 // for this behavior, that would be nice --- it's what GCC and 13723 // EDG do, and it seems like a reasonable intent, but the spec 13724 // really only says that checks for unqualified existing 13725 // declarations should stop at the nearest enclosing namespace, 13726 // not that they should only consider the nearest enclosing 13727 // namespace. 13728 while (DC->isRecord()) 13729 DC = DC->getParent(); 13730 13731 DeclContext *LookupDC = DC; 13732 while (LookupDC->isTransparentContext()) 13733 LookupDC = LookupDC->getParent(); 13734 13735 while (true) { 13736 LookupQualifiedName(Previous, LookupDC); 13737 13738 if (!Previous.empty()) { 13739 DC = LookupDC; 13740 break; 13741 } 13742 13743 if (isTemplateId) { 13744 if (isa<TranslationUnitDecl>(LookupDC)) break; 13745 } else { 13746 if (LookupDC->isFileContext()) break; 13747 } 13748 LookupDC = LookupDC->getParent(); 13749 } 13750 13751 DCScope = getScopeForDeclContext(S, DC); 13752 13753 // - There's a non-dependent scope specifier, in which case we 13754 // compute it and do a previous lookup there for a function 13755 // or function template. 13756 } else if (!SS.getScopeRep()->isDependent()) { 13757 DC = computeDeclContext(SS); 13758 if (!DC) return nullptr; 13759 13760 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 13761 13762 LookupQualifiedName(Previous, DC); 13763 13764 // Ignore things found implicitly in the wrong scope. 13765 // TODO: better diagnostics for this case. Suggesting the right 13766 // qualified scope would be nice... 13767 LookupResult::Filter F = Previous.makeFilter(); 13768 while (F.hasNext()) { 13769 NamedDecl *D = F.next(); 13770 if (!DC->InEnclosingNamespaceSetOf( 13771 D->getDeclContext()->getRedeclContext())) 13772 F.erase(); 13773 } 13774 F.done(); 13775 13776 if (Previous.empty()) { 13777 D.setInvalidType(); 13778 Diag(Loc, diag::err_qualified_friend_not_found) 13779 << Name << TInfo->getType(); 13780 return nullptr; 13781 } 13782 13783 // C++ [class.friend]p1: A friend of a class is a function or 13784 // class that is not a member of the class . . . 13785 if (DC->Equals(CurContext)) 13786 Diag(DS.getFriendSpecLoc(), 13787 getLangOpts().CPlusPlus11 ? 13788 diag::warn_cxx98_compat_friend_is_member : 13789 diag::err_friend_is_member); 13790 13791 if (D.isFunctionDefinition()) { 13792 // C++ [class.friend]p6: 13793 // A function can be defined in a friend declaration of a class if and 13794 // only if the class is a non-local class (9.8), the function name is 13795 // unqualified, and the function has namespace scope. 13796 SemaDiagnosticBuilder DB 13797 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 13798 13799 DB << SS.getScopeRep(); 13800 if (DC->isFileContext()) 13801 DB << FixItHint::CreateRemoval(SS.getRange()); 13802 SS.clear(); 13803 } 13804 13805 // - There's a scope specifier that does not match any template 13806 // parameter lists, in which case we use some arbitrary context, 13807 // create a method or method template, and wait for instantiation. 13808 // - There's a scope specifier that does match some template 13809 // parameter lists, which we don't handle right now. 13810 } else { 13811 if (D.isFunctionDefinition()) { 13812 // C++ [class.friend]p6: 13813 // A function can be defined in a friend declaration of a class if and 13814 // only if the class is a non-local class (9.8), the function name is 13815 // unqualified, and the function has namespace scope. 13816 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 13817 << SS.getScopeRep(); 13818 } 13819 13820 DC = CurContext; 13821 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 13822 } 13823 13824 if (!DC->isRecord()) { 13825 int DiagArg = -1; 13826 switch (D.getName().getKind()) { 13827 case UnqualifiedId::IK_ConstructorTemplateId: 13828 case UnqualifiedId::IK_ConstructorName: 13829 DiagArg = 0; 13830 break; 13831 case UnqualifiedId::IK_DestructorName: 13832 DiagArg = 1; 13833 break; 13834 case UnqualifiedId::IK_ConversionFunctionId: 13835 DiagArg = 2; 13836 break; 13837 case UnqualifiedId::IK_DeductionGuideName: 13838 DiagArg = 3; 13839 break; 13840 case UnqualifiedId::IK_Identifier: 13841 case UnqualifiedId::IK_ImplicitSelfParam: 13842 case UnqualifiedId::IK_LiteralOperatorId: 13843 case UnqualifiedId::IK_OperatorFunctionId: 13844 case UnqualifiedId::IK_TemplateId: 13845 break; 13846 } 13847 // This implies that it has to be an operator or function. 13848 if (DiagArg >= 0) { 13849 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 13850 return nullptr; 13851 } 13852 } 13853 13854 // FIXME: This is an egregious hack to cope with cases where the scope stack 13855 // does not contain the declaration context, i.e., in an out-of-line 13856 // definition of a class. 13857 Scope FakeDCScope(S, Scope::DeclScope, Diags); 13858 if (!DCScope) { 13859 FakeDCScope.setEntity(DC); 13860 DCScope = &FakeDCScope; 13861 } 13862 13863 bool AddToScope = true; 13864 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 13865 TemplateParams, AddToScope); 13866 if (!ND) return nullptr; 13867 13868 assert(ND->getLexicalDeclContext() == CurContext); 13869 13870 // If we performed typo correction, we might have added a scope specifier 13871 // and changed the decl context. 13872 DC = ND->getDeclContext(); 13873 13874 // Add the function declaration to the appropriate lookup tables, 13875 // adjusting the redeclarations list as necessary. We don't 13876 // want to do this yet if the friending class is dependent. 13877 // 13878 // Also update the scope-based lookup if the target context's 13879 // lookup context is in lexical scope. 13880 if (!CurContext->isDependentContext()) { 13881 DC = DC->getRedeclContext(); 13882 DC->makeDeclVisibleInContext(ND); 13883 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13884 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 13885 } 13886 13887 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 13888 D.getIdentifierLoc(), ND, 13889 DS.getFriendSpecLoc()); 13890 FrD->setAccess(AS_public); 13891 CurContext->addDecl(FrD); 13892 13893 if (ND->isInvalidDecl()) { 13894 FrD->setInvalidDecl(); 13895 } else { 13896 if (DC->isRecord()) CheckFriendAccess(ND); 13897 13898 FunctionDecl *FD; 13899 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 13900 FD = FTD->getTemplatedDecl(); 13901 else 13902 FD = cast<FunctionDecl>(ND); 13903 13904 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 13905 // default argument expression, that declaration shall be a definition 13906 // and shall be the only declaration of the function or function 13907 // template in the translation unit. 13908 if (functionDeclHasDefaultArgument(FD)) { 13909 // We can't look at FD->getPreviousDecl() because it may not have been set 13910 // if we're in a dependent context. If the function is known to be a 13911 // redeclaration, we will have narrowed Previous down to the right decl. 13912 if (D.isRedeclaration()) { 13913 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 13914 Diag(Previous.getRepresentativeDecl()->getLocation(), 13915 diag::note_previous_declaration); 13916 } else if (!D.isFunctionDefinition()) 13917 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 13918 } 13919 13920 // Mark templated-scope function declarations as unsupported. 13921 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 13922 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 13923 << SS.getScopeRep() << SS.getRange() 13924 << cast<CXXRecordDecl>(CurContext); 13925 FrD->setUnsupportedFriend(true); 13926 } 13927 } 13928 13929 return ND; 13930 } 13931 13932 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 13933 AdjustDeclIfTemplate(Dcl); 13934 13935 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 13936 if (!Fn) { 13937 Diag(DelLoc, diag::err_deleted_non_function); 13938 return; 13939 } 13940 13941 // Deleted function does not have a body. 13942 Fn->setWillHaveBody(false); 13943 13944 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 13945 // Don't consider the implicit declaration we generate for explicit 13946 // specializations. FIXME: Do not generate these implicit declarations. 13947 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 13948 Prev->getPreviousDecl()) && 13949 !Prev->isDefined()) { 13950 Diag(DelLoc, diag::err_deleted_decl_not_first); 13951 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 13952 Prev->isImplicit() ? diag::note_previous_implicit_declaration 13953 : diag::note_previous_declaration); 13954 } 13955 // If the declaration wasn't the first, we delete the function anyway for 13956 // recovery. 13957 Fn = Fn->getCanonicalDecl(); 13958 } 13959 13960 // dllimport/dllexport cannot be deleted. 13961 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 13962 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 13963 Fn->setInvalidDecl(); 13964 } 13965 13966 if (Fn->isDeleted()) 13967 return; 13968 13969 // See if we're deleting a function which is already known to override a 13970 // non-deleted virtual function. 13971 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 13972 bool IssuedDiagnostic = false; 13973 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 13974 E = MD->end_overridden_methods(); 13975 I != E; ++I) { 13976 if (!(*MD->begin_overridden_methods())->isDeleted()) { 13977 if (!IssuedDiagnostic) { 13978 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 13979 IssuedDiagnostic = true; 13980 } 13981 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 13982 } 13983 } 13984 // If this function was implicitly deleted because it was defaulted, 13985 // explain why it was deleted. 13986 if (IssuedDiagnostic && MD->isDefaulted()) 13987 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 13988 /*Diagnose*/true); 13989 } 13990 13991 // C++11 [basic.start.main]p3: 13992 // A program that defines main as deleted [...] is ill-formed. 13993 if (Fn->isMain()) 13994 Diag(DelLoc, diag::err_deleted_main); 13995 13996 // C++11 [dcl.fct.def.delete]p4: 13997 // A deleted function is implicitly inline. 13998 Fn->setImplicitlyInline(); 13999 Fn->setDeletedAsWritten(); 14000 } 14001 14002 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 14003 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 14004 14005 if (MD) { 14006 if (MD->getParent()->isDependentType()) { 14007 MD->setDefaulted(); 14008 MD->setExplicitlyDefaulted(); 14009 return; 14010 } 14011 14012 CXXSpecialMember Member = getSpecialMember(MD); 14013 if (Member == CXXInvalid) { 14014 if (!MD->isInvalidDecl()) 14015 Diag(DefaultLoc, diag::err_default_special_members); 14016 return; 14017 } 14018 14019 MD->setDefaulted(); 14020 MD->setExplicitlyDefaulted(); 14021 14022 // Unset that we will have a body for this function. We might not, 14023 // if it turns out to be trivial, and we don't need this marking now 14024 // that we've marked it as defaulted. 14025 MD->setWillHaveBody(false); 14026 14027 // If this definition appears within the record, do the checking when 14028 // the record is complete. 14029 const FunctionDecl *Primary = MD; 14030 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 14031 // Ask the template instantiation pattern that actually had the 14032 // '= default' on it. 14033 Primary = Pattern; 14034 14035 // If the method was defaulted on its first declaration, we will have 14036 // already performed the checking in CheckCompletedCXXClass. Such a 14037 // declaration doesn't trigger an implicit definition. 14038 if (Primary->getCanonicalDecl()->isDefaulted()) 14039 return; 14040 14041 CheckExplicitlyDefaultedSpecialMember(MD); 14042 14043 if (!MD->isInvalidDecl()) 14044 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 14045 } else { 14046 Diag(DefaultLoc, diag::err_default_special_members); 14047 } 14048 } 14049 14050 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 14051 for (Stmt *SubStmt : S->children()) { 14052 if (!SubStmt) 14053 continue; 14054 if (isa<ReturnStmt>(SubStmt)) 14055 Self.Diag(SubStmt->getLocStart(), 14056 diag::err_return_in_constructor_handler); 14057 if (!isa<Expr>(SubStmt)) 14058 SearchForReturnInStmt(Self, SubStmt); 14059 } 14060 } 14061 14062 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 14063 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 14064 CXXCatchStmt *Handler = TryBlock->getHandler(I); 14065 SearchForReturnInStmt(*this, Handler); 14066 } 14067 } 14068 14069 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 14070 const CXXMethodDecl *Old) { 14071 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 14072 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 14073 14074 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 14075 14076 // If the calling conventions match, everything is fine 14077 if (NewCC == OldCC) 14078 return false; 14079 14080 // If the calling conventions mismatch because the new function is static, 14081 // suppress the calling convention mismatch error; the error about static 14082 // function override (err_static_overrides_virtual from 14083 // Sema::CheckFunctionDeclaration) is more clear. 14084 if (New->getStorageClass() == SC_Static) 14085 return false; 14086 14087 Diag(New->getLocation(), 14088 diag::err_conflicting_overriding_cc_attributes) 14089 << New->getDeclName() << New->getType() << Old->getType(); 14090 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 14091 return true; 14092 } 14093 14094 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 14095 const CXXMethodDecl *Old) { 14096 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 14097 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 14098 14099 if (Context.hasSameType(NewTy, OldTy) || 14100 NewTy->isDependentType() || OldTy->isDependentType()) 14101 return false; 14102 14103 // Check if the return types are covariant 14104 QualType NewClassTy, OldClassTy; 14105 14106 /// Both types must be pointers or references to classes. 14107 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 14108 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 14109 NewClassTy = NewPT->getPointeeType(); 14110 OldClassTy = OldPT->getPointeeType(); 14111 } 14112 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 14113 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 14114 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 14115 NewClassTy = NewRT->getPointeeType(); 14116 OldClassTy = OldRT->getPointeeType(); 14117 } 14118 } 14119 } 14120 14121 // The return types aren't either both pointers or references to a class type. 14122 if (NewClassTy.isNull()) { 14123 Diag(New->getLocation(), 14124 diag::err_different_return_type_for_overriding_virtual_function) 14125 << New->getDeclName() << NewTy << OldTy 14126 << New->getReturnTypeSourceRange(); 14127 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14128 << Old->getReturnTypeSourceRange(); 14129 14130 return true; 14131 } 14132 14133 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 14134 // C++14 [class.virtual]p8: 14135 // If the class type in the covariant return type of D::f differs from 14136 // that of B::f, the class type in the return type of D::f shall be 14137 // complete at the point of declaration of D::f or shall be the class 14138 // type D. 14139 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 14140 if (!RT->isBeingDefined() && 14141 RequireCompleteType(New->getLocation(), NewClassTy, 14142 diag::err_covariant_return_incomplete, 14143 New->getDeclName())) 14144 return true; 14145 } 14146 14147 // Check if the new class derives from the old class. 14148 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 14149 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 14150 << New->getDeclName() << NewTy << OldTy 14151 << New->getReturnTypeSourceRange(); 14152 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14153 << Old->getReturnTypeSourceRange(); 14154 return true; 14155 } 14156 14157 // Check if we the conversion from derived to base is valid. 14158 if (CheckDerivedToBaseConversion( 14159 NewClassTy, OldClassTy, 14160 diag::err_covariant_return_inaccessible_base, 14161 diag::err_covariant_return_ambiguous_derived_to_base_conv, 14162 New->getLocation(), New->getReturnTypeSourceRange(), 14163 New->getDeclName(), nullptr)) { 14164 // FIXME: this note won't trigger for delayed access control 14165 // diagnostics, and it's impossible to get an undelayed error 14166 // here from access control during the original parse because 14167 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 14168 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14169 << Old->getReturnTypeSourceRange(); 14170 return true; 14171 } 14172 } 14173 14174 // The qualifiers of the return types must be the same. 14175 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 14176 Diag(New->getLocation(), 14177 diag::err_covariant_return_type_different_qualifications) 14178 << New->getDeclName() << NewTy << OldTy 14179 << New->getReturnTypeSourceRange(); 14180 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14181 << Old->getReturnTypeSourceRange(); 14182 return true; 14183 } 14184 14185 14186 // The new class type must have the same or less qualifiers as the old type. 14187 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 14188 Diag(New->getLocation(), 14189 diag::err_covariant_return_type_class_type_more_qualified) 14190 << New->getDeclName() << NewTy << OldTy 14191 << New->getReturnTypeSourceRange(); 14192 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 14193 << Old->getReturnTypeSourceRange(); 14194 return true; 14195 } 14196 14197 return false; 14198 } 14199 14200 /// \brief Mark the given method pure. 14201 /// 14202 /// \param Method the method to be marked pure. 14203 /// 14204 /// \param InitRange the source range that covers the "0" initializer. 14205 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 14206 SourceLocation EndLoc = InitRange.getEnd(); 14207 if (EndLoc.isValid()) 14208 Method->setRangeEnd(EndLoc); 14209 14210 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 14211 Method->setPure(); 14212 return false; 14213 } 14214 14215 if (!Method->isInvalidDecl()) 14216 Diag(Method->getLocation(), diag::err_non_virtual_pure) 14217 << Method->getDeclName() << InitRange; 14218 return true; 14219 } 14220 14221 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 14222 if (D->getFriendObjectKind()) 14223 Diag(D->getLocation(), diag::err_pure_friend); 14224 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 14225 CheckPureMethod(M, ZeroLoc); 14226 else 14227 Diag(D->getLocation(), diag::err_illegal_initializer); 14228 } 14229 14230 /// \brief Determine whether the given declaration is a static data member. 14231 static bool isStaticDataMember(const Decl *D) { 14232 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 14233 return Var->isStaticDataMember(); 14234 14235 return false; 14236 } 14237 14238 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 14239 /// an initializer for the out-of-line declaration 'Dcl'. The scope 14240 /// is a fresh scope pushed for just this purpose. 14241 /// 14242 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 14243 /// static data member of class X, names should be looked up in the scope of 14244 /// class X. 14245 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 14246 // If there is no declaration, there was an error parsing it. 14247 if (!D || D->isInvalidDecl()) 14248 return; 14249 14250 // We will always have a nested name specifier here, but this declaration 14251 // might not be out of line if the specifier names the current namespace: 14252 // extern int n; 14253 // int ::n = 0; 14254 if (D->isOutOfLine()) 14255 EnterDeclaratorContext(S, D->getDeclContext()); 14256 14257 // If we are parsing the initializer for a static data member, push a 14258 // new expression evaluation context that is associated with this static 14259 // data member. 14260 if (isStaticDataMember(D)) 14261 PushExpressionEvaluationContext( 14262 ExpressionEvaluationContext::PotentiallyEvaluated, D); 14263 } 14264 14265 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 14266 /// initializer for the out-of-line declaration 'D'. 14267 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 14268 // If there is no declaration, there was an error parsing it. 14269 if (!D || D->isInvalidDecl()) 14270 return; 14271 14272 if (isStaticDataMember(D)) 14273 PopExpressionEvaluationContext(); 14274 14275 if (D->isOutOfLine()) 14276 ExitDeclaratorContext(S); 14277 } 14278 14279 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 14280 /// C++ if/switch/while/for statement. 14281 /// e.g: "if (int x = f()) {...}" 14282 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 14283 // C++ 6.4p2: 14284 // The declarator shall not specify a function or an array. 14285 // The type-specifier-seq shall not contain typedef and shall not declare a 14286 // new class or enumeration. 14287 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 14288 "Parser allowed 'typedef' as storage class of condition decl."); 14289 14290 Decl *Dcl = ActOnDeclarator(S, D); 14291 if (!Dcl) 14292 return true; 14293 14294 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 14295 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 14296 << D.getSourceRange(); 14297 return true; 14298 } 14299 14300 return Dcl; 14301 } 14302 14303 void Sema::LoadExternalVTableUses() { 14304 if (!ExternalSource) 14305 return; 14306 14307 SmallVector<ExternalVTableUse, 4> VTables; 14308 ExternalSource->ReadUsedVTables(VTables); 14309 SmallVector<VTableUse, 4> NewUses; 14310 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 14311 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 14312 = VTablesUsed.find(VTables[I].Record); 14313 // Even if a definition wasn't required before, it may be required now. 14314 if (Pos != VTablesUsed.end()) { 14315 if (!Pos->second && VTables[I].DefinitionRequired) 14316 Pos->second = true; 14317 continue; 14318 } 14319 14320 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 14321 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 14322 } 14323 14324 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 14325 } 14326 14327 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 14328 bool DefinitionRequired) { 14329 // Ignore any vtable uses in unevaluated operands or for classes that do 14330 // not have a vtable. 14331 if (!Class->isDynamicClass() || Class->isDependentContext() || 14332 CurContext->isDependentContext() || isUnevaluatedContext()) 14333 return; 14334 14335 // Try to insert this class into the map. 14336 LoadExternalVTableUses(); 14337 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14338 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 14339 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 14340 if (!Pos.second) { 14341 // If we already had an entry, check to see if we are promoting this vtable 14342 // to require a definition. If so, we need to reappend to the VTableUses 14343 // list, since we may have already processed the first entry. 14344 if (DefinitionRequired && !Pos.first->second) { 14345 Pos.first->second = true; 14346 } else { 14347 // Otherwise, we can early exit. 14348 return; 14349 } 14350 } else { 14351 // The Microsoft ABI requires that we perform the destructor body 14352 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 14353 // the deleting destructor is emitted with the vtable, not with the 14354 // destructor definition as in the Itanium ABI. 14355 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14356 CXXDestructorDecl *DD = Class->getDestructor(); 14357 if (DD && DD->isVirtual() && !DD->isDeleted()) { 14358 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 14359 // If this is an out-of-line declaration, marking it referenced will 14360 // not do anything. Manually call CheckDestructor to look up operator 14361 // delete(). 14362 ContextRAII SavedContext(*this, DD); 14363 CheckDestructor(DD); 14364 } else { 14365 MarkFunctionReferenced(Loc, Class->getDestructor()); 14366 } 14367 } 14368 } 14369 } 14370 14371 // Local classes need to have their virtual members marked 14372 // immediately. For all other classes, we mark their virtual members 14373 // at the end of the translation unit. 14374 if (Class->isLocalClass()) 14375 MarkVirtualMembersReferenced(Loc, Class); 14376 else 14377 VTableUses.push_back(std::make_pair(Class, Loc)); 14378 } 14379 14380 bool Sema::DefineUsedVTables() { 14381 LoadExternalVTableUses(); 14382 if (VTableUses.empty()) 14383 return false; 14384 14385 // Note: The VTableUses vector could grow as a result of marking 14386 // the members of a class as "used", so we check the size each 14387 // time through the loop and prefer indices (which are stable) to 14388 // iterators (which are not). 14389 bool DefinedAnything = false; 14390 for (unsigned I = 0; I != VTableUses.size(); ++I) { 14391 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 14392 if (!Class) 14393 continue; 14394 TemplateSpecializationKind ClassTSK = 14395 Class->getTemplateSpecializationKind(); 14396 14397 SourceLocation Loc = VTableUses[I].second; 14398 14399 bool DefineVTable = true; 14400 14401 // If this class has a key function, but that key function is 14402 // defined in another translation unit, we don't need to emit the 14403 // vtable even though we're using it. 14404 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 14405 if (KeyFunction && !KeyFunction->hasBody()) { 14406 // The key function is in another translation unit. 14407 DefineVTable = false; 14408 TemplateSpecializationKind TSK = 14409 KeyFunction->getTemplateSpecializationKind(); 14410 assert(TSK != TSK_ExplicitInstantiationDefinition && 14411 TSK != TSK_ImplicitInstantiation && 14412 "Instantiations don't have key functions"); 14413 (void)TSK; 14414 } else if (!KeyFunction) { 14415 // If we have a class with no key function that is the subject 14416 // of an explicit instantiation declaration, suppress the 14417 // vtable; it will live with the explicit instantiation 14418 // definition. 14419 bool IsExplicitInstantiationDeclaration = 14420 ClassTSK == TSK_ExplicitInstantiationDeclaration; 14421 for (auto R : Class->redecls()) { 14422 TemplateSpecializationKind TSK 14423 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 14424 if (TSK == TSK_ExplicitInstantiationDeclaration) 14425 IsExplicitInstantiationDeclaration = true; 14426 else if (TSK == TSK_ExplicitInstantiationDefinition) { 14427 IsExplicitInstantiationDeclaration = false; 14428 break; 14429 } 14430 } 14431 14432 if (IsExplicitInstantiationDeclaration) 14433 DefineVTable = false; 14434 } 14435 14436 // The exception specifications for all virtual members may be needed even 14437 // if we are not providing an authoritative form of the vtable in this TU. 14438 // We may choose to emit it available_externally anyway. 14439 if (!DefineVTable) { 14440 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 14441 continue; 14442 } 14443 14444 // Mark all of the virtual members of this class as referenced, so 14445 // that we can build a vtable. Then, tell the AST consumer that a 14446 // vtable for this class is required. 14447 DefinedAnything = true; 14448 MarkVirtualMembersReferenced(Loc, Class); 14449 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 14450 if (VTablesUsed[Canonical]) 14451 Consumer.HandleVTable(Class); 14452 14453 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 14454 // no key function or the key function is inlined. Don't warn in C++ ABIs 14455 // that lack key functions, since the user won't be able to make one. 14456 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 14457 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 14458 const FunctionDecl *KeyFunctionDef = nullptr; 14459 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 14460 KeyFunctionDef->isInlined())) { 14461 Diag(Class->getLocation(), 14462 ClassTSK == TSK_ExplicitInstantiationDefinition 14463 ? diag::warn_weak_template_vtable 14464 : diag::warn_weak_vtable) 14465 << Class; 14466 } 14467 } 14468 } 14469 VTableUses.clear(); 14470 14471 return DefinedAnything; 14472 } 14473 14474 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 14475 const CXXRecordDecl *RD) { 14476 for (const auto *I : RD->methods()) 14477 if (I->isVirtual() && !I->isPure()) 14478 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 14479 } 14480 14481 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 14482 const CXXRecordDecl *RD) { 14483 // Mark all functions which will appear in RD's vtable as used. 14484 CXXFinalOverriderMap FinalOverriders; 14485 RD->getFinalOverriders(FinalOverriders); 14486 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 14487 E = FinalOverriders.end(); 14488 I != E; ++I) { 14489 for (OverridingMethods::const_iterator OI = I->second.begin(), 14490 OE = I->second.end(); 14491 OI != OE; ++OI) { 14492 assert(OI->second.size() > 0 && "no final overrider"); 14493 CXXMethodDecl *Overrider = OI->second.front().Method; 14494 14495 // C++ [basic.def.odr]p2: 14496 // [...] A virtual member function is used if it is not pure. [...] 14497 if (!Overrider->isPure()) 14498 MarkFunctionReferenced(Loc, Overrider); 14499 } 14500 } 14501 14502 // Only classes that have virtual bases need a VTT. 14503 if (RD->getNumVBases() == 0) 14504 return; 14505 14506 for (const auto &I : RD->bases()) { 14507 const CXXRecordDecl *Base = 14508 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 14509 if (Base->getNumVBases() == 0) 14510 continue; 14511 MarkVirtualMembersReferenced(Loc, Base); 14512 } 14513 } 14514 14515 /// SetIvarInitializers - This routine builds initialization ASTs for the 14516 /// Objective-C implementation whose ivars need be initialized. 14517 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 14518 if (!getLangOpts().CPlusPlus) 14519 return; 14520 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 14521 SmallVector<ObjCIvarDecl*, 8> ivars; 14522 CollectIvarsToConstructOrDestruct(OID, ivars); 14523 if (ivars.empty()) 14524 return; 14525 SmallVector<CXXCtorInitializer*, 32> AllToInit; 14526 for (unsigned i = 0; i < ivars.size(); i++) { 14527 FieldDecl *Field = ivars[i]; 14528 if (Field->isInvalidDecl()) 14529 continue; 14530 14531 CXXCtorInitializer *Member; 14532 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 14533 InitializationKind InitKind = 14534 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 14535 14536 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 14537 ExprResult MemberInit = 14538 InitSeq.Perform(*this, InitEntity, InitKind, None); 14539 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 14540 // Note, MemberInit could actually come back empty if no initialization 14541 // is required (e.g., because it would call a trivial default constructor) 14542 if (!MemberInit.get() || MemberInit.isInvalid()) 14543 continue; 14544 14545 Member = 14546 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 14547 SourceLocation(), 14548 MemberInit.getAs<Expr>(), 14549 SourceLocation()); 14550 AllToInit.push_back(Member); 14551 14552 // Be sure that the destructor is accessible and is marked as referenced. 14553 if (const RecordType *RecordTy = 14554 Context.getBaseElementType(Field->getType()) 14555 ->getAs<RecordType>()) { 14556 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 14557 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 14558 MarkFunctionReferenced(Field->getLocation(), Destructor); 14559 CheckDestructorAccess(Field->getLocation(), Destructor, 14560 PDiag(diag::err_access_dtor_ivar) 14561 << Context.getBaseElementType(Field->getType())); 14562 } 14563 } 14564 } 14565 ObjCImplementation->setIvarInitializers(Context, 14566 AllToInit.data(), AllToInit.size()); 14567 } 14568 } 14569 14570 static 14571 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 14572 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 14573 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 14574 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 14575 Sema &S) { 14576 if (Ctor->isInvalidDecl()) 14577 return; 14578 14579 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 14580 14581 // Target may not be determinable yet, for instance if this is a dependent 14582 // call in an uninstantiated template. 14583 if (Target) { 14584 const FunctionDecl *FNTarget = nullptr; 14585 (void)Target->hasBody(FNTarget); 14586 Target = const_cast<CXXConstructorDecl*>( 14587 cast_or_null<CXXConstructorDecl>(FNTarget)); 14588 } 14589 14590 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 14591 // Avoid dereferencing a null pointer here. 14592 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 14593 14594 if (!Current.insert(Canonical).second) 14595 return; 14596 14597 // We know that beyond here, we aren't chaining into a cycle. 14598 if (!Target || !Target->isDelegatingConstructor() || 14599 Target->isInvalidDecl() || Valid.count(TCanonical)) { 14600 Valid.insert(Current.begin(), Current.end()); 14601 Current.clear(); 14602 // We've hit a cycle. 14603 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 14604 Current.count(TCanonical)) { 14605 // If we haven't diagnosed this cycle yet, do so now. 14606 if (!Invalid.count(TCanonical)) { 14607 S.Diag((*Ctor->init_begin())->getSourceLocation(), 14608 diag::warn_delegating_ctor_cycle) 14609 << Ctor; 14610 14611 // Don't add a note for a function delegating directly to itself. 14612 if (TCanonical != Canonical) 14613 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 14614 14615 CXXConstructorDecl *C = Target; 14616 while (C->getCanonicalDecl() != Canonical) { 14617 const FunctionDecl *FNTarget = nullptr; 14618 (void)C->getTargetConstructor()->hasBody(FNTarget); 14619 assert(FNTarget && "Ctor cycle through bodiless function"); 14620 14621 C = const_cast<CXXConstructorDecl*>( 14622 cast<CXXConstructorDecl>(FNTarget)); 14623 S.Diag(C->getLocation(), diag::note_which_delegates_to); 14624 } 14625 } 14626 14627 Invalid.insert(Current.begin(), Current.end()); 14628 Current.clear(); 14629 } else { 14630 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 14631 } 14632 } 14633 14634 14635 void Sema::CheckDelegatingCtorCycles() { 14636 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 14637 14638 for (DelegatingCtorDeclsType::iterator 14639 I = DelegatingCtorDecls.begin(ExternalSource), 14640 E = DelegatingCtorDecls.end(); 14641 I != E; ++I) 14642 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 14643 14644 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 14645 CE = Invalid.end(); 14646 CI != CE; ++CI) 14647 (*CI)->setInvalidDecl(); 14648 } 14649 14650 namespace { 14651 /// \brief AST visitor that finds references to the 'this' expression. 14652 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 14653 Sema &S; 14654 14655 public: 14656 explicit FindCXXThisExpr(Sema &S) : S(S) { } 14657 14658 bool VisitCXXThisExpr(CXXThisExpr *E) { 14659 S.Diag(E->getLocation(), diag::err_this_static_member_func) 14660 << E->isImplicit(); 14661 return false; 14662 } 14663 }; 14664 } 14665 14666 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 14667 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14668 if (!TSInfo) 14669 return false; 14670 14671 TypeLoc TL = TSInfo->getTypeLoc(); 14672 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14673 if (!ProtoTL) 14674 return false; 14675 14676 // C++11 [expr.prim.general]p3: 14677 // [The expression this] shall not appear before the optional 14678 // cv-qualifier-seq and it shall not appear within the declaration of a 14679 // static member function (although its type and value category are defined 14680 // within a static member function as they are within a non-static member 14681 // function). [ Note: this is because declaration matching does not occur 14682 // until the complete declarator is known. - end note ] 14683 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14684 FindCXXThisExpr Finder(*this); 14685 14686 // If the return type came after the cv-qualifier-seq, check it now. 14687 if (Proto->hasTrailingReturn() && 14688 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 14689 return true; 14690 14691 // Check the exception specification. 14692 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 14693 return true; 14694 14695 return checkThisInStaticMemberFunctionAttributes(Method); 14696 } 14697 14698 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 14699 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 14700 if (!TSInfo) 14701 return false; 14702 14703 TypeLoc TL = TSInfo->getTypeLoc(); 14704 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 14705 if (!ProtoTL) 14706 return false; 14707 14708 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 14709 FindCXXThisExpr Finder(*this); 14710 14711 switch (Proto->getExceptionSpecType()) { 14712 case EST_Unparsed: 14713 case EST_Uninstantiated: 14714 case EST_Unevaluated: 14715 case EST_BasicNoexcept: 14716 case EST_DynamicNone: 14717 case EST_MSAny: 14718 case EST_None: 14719 break; 14720 14721 case EST_ComputedNoexcept: 14722 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 14723 return true; 14724 LLVM_FALLTHROUGH; 14725 14726 case EST_Dynamic: 14727 for (const auto &E : Proto->exceptions()) { 14728 if (!Finder.TraverseType(E)) 14729 return true; 14730 } 14731 break; 14732 } 14733 14734 return false; 14735 } 14736 14737 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 14738 FindCXXThisExpr Finder(*this); 14739 14740 // Check attributes. 14741 for (const auto *A : Method->attrs()) { 14742 // FIXME: This should be emitted by tblgen. 14743 Expr *Arg = nullptr; 14744 ArrayRef<Expr *> Args; 14745 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 14746 Arg = G->getArg(); 14747 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 14748 Arg = G->getArg(); 14749 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 14750 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 14751 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 14752 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 14753 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 14754 Arg = ETLF->getSuccessValue(); 14755 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 14756 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 14757 Arg = STLF->getSuccessValue(); 14758 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 14759 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 14760 Arg = LR->getArg(); 14761 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 14762 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 14763 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 14764 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14765 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 14766 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14767 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 14768 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 14769 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 14770 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 14771 14772 if (Arg && !Finder.TraverseStmt(Arg)) 14773 return true; 14774 14775 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 14776 if (!Finder.TraverseStmt(Args[I])) 14777 return true; 14778 } 14779 } 14780 14781 return false; 14782 } 14783 14784 void Sema::checkExceptionSpecification( 14785 bool IsTopLevel, ExceptionSpecificationType EST, 14786 ArrayRef<ParsedType> DynamicExceptions, 14787 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 14788 SmallVectorImpl<QualType> &Exceptions, 14789 FunctionProtoType::ExceptionSpecInfo &ESI) { 14790 Exceptions.clear(); 14791 ESI.Type = EST; 14792 if (EST == EST_Dynamic) { 14793 Exceptions.reserve(DynamicExceptions.size()); 14794 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 14795 // FIXME: Preserve type source info. 14796 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 14797 14798 if (IsTopLevel) { 14799 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 14800 collectUnexpandedParameterPacks(ET, Unexpanded); 14801 if (!Unexpanded.empty()) { 14802 DiagnoseUnexpandedParameterPacks( 14803 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 14804 Unexpanded); 14805 continue; 14806 } 14807 } 14808 14809 // Check that the type is valid for an exception spec, and 14810 // drop it if not. 14811 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 14812 Exceptions.push_back(ET); 14813 } 14814 ESI.Exceptions = Exceptions; 14815 return; 14816 } 14817 14818 if (EST == EST_ComputedNoexcept) { 14819 // If an error occurred, there's no expression here. 14820 if (NoexceptExpr) { 14821 assert((NoexceptExpr->isTypeDependent() || 14822 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 14823 Context.BoolTy) && 14824 "Parser should have made sure that the expression is boolean"); 14825 if (IsTopLevel && NoexceptExpr && 14826 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 14827 ESI.Type = EST_BasicNoexcept; 14828 return; 14829 } 14830 14831 if (!NoexceptExpr->isValueDependent()) 14832 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 14833 diag::err_noexcept_needs_constant_expression, 14834 /*AllowFold*/ false).get(); 14835 ESI.NoexceptExpr = NoexceptExpr; 14836 } 14837 return; 14838 } 14839 } 14840 14841 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 14842 ExceptionSpecificationType EST, 14843 SourceRange SpecificationRange, 14844 ArrayRef<ParsedType> DynamicExceptions, 14845 ArrayRef<SourceRange> DynamicExceptionRanges, 14846 Expr *NoexceptExpr) { 14847 if (!MethodD) 14848 return; 14849 14850 // Dig out the method we're referring to. 14851 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 14852 MethodD = FunTmpl->getTemplatedDecl(); 14853 14854 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 14855 if (!Method) 14856 return; 14857 14858 // Check the exception specification. 14859 llvm::SmallVector<QualType, 4> Exceptions; 14860 FunctionProtoType::ExceptionSpecInfo ESI; 14861 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 14862 DynamicExceptionRanges, NoexceptExpr, Exceptions, 14863 ESI); 14864 14865 // Update the exception specification on the function type. 14866 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 14867 14868 if (Method->isStatic()) 14869 checkThisInStaticMemberFunctionExceptionSpec(Method); 14870 14871 if (Method->isVirtual()) { 14872 // Check overrides, which we previously had to delay. 14873 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 14874 OEnd = Method->end_overridden_methods(); 14875 O != OEnd; ++O) 14876 CheckOverridingFunctionExceptionSpec(Method, *O); 14877 } 14878 } 14879 14880 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 14881 /// 14882 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 14883 SourceLocation DeclStart, 14884 Declarator &D, Expr *BitWidth, 14885 InClassInitStyle InitStyle, 14886 AccessSpecifier AS, 14887 AttributeList *MSPropertyAttr) { 14888 IdentifierInfo *II = D.getIdentifier(); 14889 if (!II) { 14890 Diag(DeclStart, diag::err_anonymous_property); 14891 return nullptr; 14892 } 14893 SourceLocation Loc = D.getIdentifierLoc(); 14894 14895 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14896 QualType T = TInfo->getType(); 14897 if (getLangOpts().CPlusPlus) { 14898 CheckExtraCXXDefaultArguments(D); 14899 14900 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14901 UPPC_DataMemberType)) { 14902 D.setInvalidType(); 14903 T = Context.IntTy; 14904 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14905 } 14906 } 14907 14908 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14909 14910 if (D.getDeclSpec().isInlineSpecified()) 14911 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14912 << getLangOpts().CPlusPlus1z; 14913 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14914 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14915 diag::err_invalid_thread) 14916 << DeclSpec::getSpecifierName(TSCS); 14917 14918 // Check to see if this name was declared as a member previously 14919 NamedDecl *PrevDecl = nullptr; 14920 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 14921 LookupName(Previous, S); 14922 switch (Previous.getResultKind()) { 14923 case LookupResult::Found: 14924 case LookupResult::FoundUnresolvedValue: 14925 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14926 break; 14927 14928 case LookupResult::FoundOverloaded: 14929 PrevDecl = Previous.getRepresentativeDecl(); 14930 break; 14931 14932 case LookupResult::NotFound: 14933 case LookupResult::NotFoundInCurrentInstantiation: 14934 case LookupResult::Ambiguous: 14935 break; 14936 } 14937 14938 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14939 // Maybe we will complain about the shadowed template parameter. 14940 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14941 // Just pretend that we didn't see the previous declaration. 14942 PrevDecl = nullptr; 14943 } 14944 14945 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14946 PrevDecl = nullptr; 14947 14948 SourceLocation TSSL = D.getLocStart(); 14949 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 14950 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 14951 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 14952 ProcessDeclAttributes(TUScope, NewPD, D); 14953 NewPD->setAccess(AS); 14954 14955 if (NewPD->isInvalidDecl()) 14956 Record->setInvalidDecl(); 14957 14958 if (D.getDeclSpec().isModulePrivateSpecified()) 14959 NewPD->setModulePrivate(); 14960 14961 if (NewPD->isInvalidDecl() && PrevDecl) { 14962 // Don't introduce NewFD into scope; there's already something 14963 // with the same name in the same scope. 14964 } else if (II) { 14965 PushOnScopeChains(NewPD, S); 14966 } else 14967 Record->addDecl(NewPD); 14968 14969 return NewPD; 14970 } 14971