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/Sema/SemaInternal.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/RecordLayout.h" 24 #include "clang/AST/RecursiveASTVisitor.h" 25 #include "clang/AST/StmtVisitor.h" 26 #include "clang/AST/TypeLoc.h" 27 #include "clang/AST/TypeOrdering.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/CXXFieldCollector.h" 33 #include "clang/Sema/DeclSpec.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedTemplate.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "clang/Sema/Template.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/SmallString.h" 42 #include <map> 43 #include <set> 44 45 using namespace clang; 46 47 //===----------------------------------------------------------------------===// 48 // CheckDefaultArgumentVisitor 49 //===----------------------------------------------------------------------===// 50 51 namespace { 52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 53 /// the default argument of a parameter to determine whether it 54 /// contains any ill-formed subexpressions. For example, this will 55 /// diagnose the use of local variables or parameters within the 56 /// default argument expression. 57 class CheckDefaultArgumentVisitor 58 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 59 Expr *DefaultArg; 60 Sema *S; 61 62 public: 63 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 64 : DefaultArg(defarg), S(s) {} 65 66 bool VisitExpr(Expr *Node); 67 bool VisitDeclRefExpr(DeclRefExpr *DRE); 68 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 69 bool VisitLambdaExpr(LambdaExpr *Lambda); 70 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 71 }; 72 73 /// VisitExpr - Visit all of the children of this expression. 74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 75 bool IsInvalid = false; 76 for (Stmt::child_range I = Node->children(); I; ++I) 77 IsInvalid |= Visit(*I); 78 return IsInvalid; 79 } 80 81 /// VisitDeclRefExpr - Visit a reference to a declaration, to 82 /// determine whether this declaration can be used in the default 83 /// argument expression. 84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 85 NamedDecl *Decl = DRE->getDecl(); 86 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 87 // C++ [dcl.fct.default]p9 88 // Default arguments are evaluated each time the function is 89 // called. The order of evaluation of function arguments is 90 // unspecified. Consequently, parameters of a function shall not 91 // be used in default argument expressions, even if they are not 92 // evaluated. Parameters of a function declared before a default 93 // argument expression are in scope and can hide namespace and 94 // class member names. 95 return S->Diag(DRE->getLocStart(), 96 diag::err_param_default_argument_references_param) 97 << Param->getDeclName() << DefaultArg->getSourceRange(); 98 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 99 // C++ [dcl.fct.default]p7 100 // Local variables shall not be used in default argument 101 // expressions. 102 if (VDecl->isLocalVarDecl()) 103 return S->Diag(DRE->getLocStart(), 104 diag::err_param_default_argument_references_local) 105 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 106 } 107 108 return false; 109 } 110 111 /// VisitCXXThisExpr - Visit a C++ "this" expression. 112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 113 // C++ [dcl.fct.default]p8: 114 // The keyword this shall not be used in a default argument of a 115 // member function. 116 return S->Diag(ThisE->getLocStart(), 117 diag::err_param_default_argument_references_this) 118 << ThisE->getSourceRange(); 119 } 120 121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 122 bool Invalid = false; 123 for (PseudoObjectExpr::semantics_iterator 124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 125 Expr *E = *i; 126 127 // Look through bindings. 128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 129 E = OVE->getSourceExpr(); 130 assert(E && "pseudo-object binding without source expression?"); 131 } 132 133 Invalid |= Visit(E); 134 } 135 return Invalid; 136 } 137 138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 139 // C++11 [expr.lambda.prim]p13: 140 // A lambda-expression appearing in a default argument shall not 141 // implicitly or explicitly capture any entity. 142 if (Lambda->capture_begin() == Lambda->capture_end()) 143 return false; 144 145 return S->Diag(Lambda->getLocStart(), 146 diag::err_lambda_capture_default_arg); 147 } 148 } 149 150 void 151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 152 const CXXMethodDecl *Method) { 153 // If we have an MSAny spec already, don't bother. 154 if (!Method || ComputedEST == EST_MSAny) 155 return; 156 157 const FunctionProtoType *Proto 158 = Method->getType()->getAs<FunctionProtoType>(); 159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 160 if (!Proto) 161 return; 162 163 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 164 165 // If this function can throw any exceptions, make a note of that. 166 if (EST == EST_MSAny || EST == EST_None) { 167 ClearExceptions(); 168 ComputedEST = EST; 169 return; 170 } 171 172 // FIXME: If the call to this decl is using any of its default arguments, we 173 // need to search them for potentially-throwing calls. 174 175 // If this function has a basic noexcept, it doesn't affect the outcome. 176 if (EST == EST_BasicNoexcept) 177 return; 178 179 // If we have a throw-all spec at this point, ignore the function. 180 if (ComputedEST == EST_None) 181 return; 182 183 // If we're still at noexcept(true) and there's a nothrow() callee, 184 // change to that specification. 185 if (EST == EST_DynamicNone) { 186 if (ComputedEST == EST_BasicNoexcept) 187 ComputedEST = EST_DynamicNone; 188 return; 189 } 190 191 // Check out noexcept specs. 192 if (EST == EST_ComputedNoexcept) { 193 FunctionProtoType::NoexceptResult NR = 194 Proto->getNoexceptSpec(Self->Context); 195 assert(NR != FunctionProtoType::NR_NoNoexcept && 196 "Must have noexcept result for EST_ComputedNoexcept."); 197 assert(NR != FunctionProtoType::NR_Dependent && 198 "Should not generate implicit declarations for dependent cases, " 199 "and don't know how to handle them anyway."); 200 201 // noexcept(false) -> no spec on the new function 202 if (NR == FunctionProtoType::NR_Throw) { 203 ClearExceptions(); 204 ComputedEST = EST_None; 205 } 206 // noexcept(true) won't change anything either. 207 return; 208 } 209 210 assert(EST == EST_Dynamic && "EST case not considered earlier."); 211 assert(ComputedEST != EST_None && 212 "Shouldn't collect exceptions when throw-all is guaranteed."); 213 ComputedEST = EST_Dynamic; 214 // Record the exceptions in this function's exception specification. 215 for (const auto &E : Proto->exceptions()) 216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 217 Exceptions.push_back(E); 218 } 219 220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 221 if (!E || ComputedEST == EST_MSAny) 222 return; 223 224 // FIXME: 225 // 226 // C++0x [except.spec]p14: 227 // [An] implicit exception-specification specifies the type-id T if and 228 // only if T is allowed by the exception-specification of a function directly 229 // invoked by f's implicit definition; f shall allow all exceptions if any 230 // function it directly invokes allows all exceptions, and f shall allow no 231 // exceptions if every function it directly invokes allows no exceptions. 232 // 233 // Note in particular that if an implicit exception-specification is generated 234 // for a function containing a throw-expression, that specification can still 235 // be noexcept(true). 236 // 237 // Note also that 'directly invoked' is not defined in the standard, and there 238 // is no indication that we should only consider potentially-evaluated calls. 239 // 240 // Ultimately we should implement the intent of the standard: the exception 241 // specification should be the set of exceptions which can be thrown by the 242 // implicit definition. For now, we assume that any non-nothrow expression can 243 // throw any exception. 244 245 if (Self->canThrow(E)) 246 ComputedEST = EST_None; 247 } 248 249 bool 250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 251 SourceLocation EqualLoc) { 252 if (RequireCompleteType(Param->getLocation(), Param->getType(), 253 diag::err_typecheck_decl_incomplete_type)) { 254 Param->setInvalidDecl(); 255 return true; 256 } 257 258 // C++ [dcl.fct.default]p5 259 // A default argument expression is implicitly converted (clause 260 // 4) to the parameter type. The default argument expression has 261 // the same semantic constraints as the initializer expression in 262 // a declaration of a variable of the parameter type, using the 263 // copy-initialization semantics (8.5). 264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 265 Param); 266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 267 EqualLoc); 268 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 270 if (Result.isInvalid()) 271 return true; 272 Arg = Result.getAs<Expr>(); 273 274 CheckCompletedExpr(Arg, EqualLoc); 275 Arg = MaybeCreateExprWithCleanups(Arg); 276 277 // Okay: add the default argument to the parameter 278 Param->setDefaultArg(Arg); 279 280 // We have already instantiated this parameter; provide each of the 281 // instantiations with the uninstantiated default argument. 282 UnparsedDefaultArgInstantiationsMap::iterator InstPos 283 = UnparsedDefaultArgInstantiations.find(Param); 284 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 287 288 // We're done tracking this parameter's instantiations. 289 UnparsedDefaultArgInstantiations.erase(InstPos); 290 } 291 292 return false; 293 } 294 295 /// ActOnParamDefaultArgument - Check whether the default argument 296 /// provided for a function parameter is well-formed. If so, attach it 297 /// to the parameter declaration. 298 void 299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 300 Expr *DefaultArg) { 301 if (!param || !DefaultArg) 302 return; 303 304 ParmVarDecl *Param = cast<ParmVarDecl>(param); 305 UnparsedDefaultArgLocs.erase(Param); 306 307 // Default arguments are only permitted in C++ 308 if (!getLangOpts().CPlusPlus) { 309 Diag(EqualLoc, diag::err_param_default_argument) 310 << DefaultArg->getSourceRange(); 311 Param->setInvalidDecl(); 312 return; 313 } 314 315 // Check for unexpanded parameter packs. 316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 317 Param->setInvalidDecl(); 318 return; 319 } 320 321 // Check that the default argument is well-formed 322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 323 if (DefaultArgChecker.Visit(DefaultArg)) { 324 Param->setInvalidDecl(); 325 return; 326 } 327 328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 329 } 330 331 /// ActOnParamUnparsedDefaultArgument - We've seen a default 332 /// argument for a function parameter, but we can't parse it yet 333 /// because we're inside a class definition. Note that this default 334 /// argument will be parsed later. 335 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 336 SourceLocation EqualLoc, 337 SourceLocation ArgLoc) { 338 if (!param) 339 return; 340 341 ParmVarDecl *Param = cast<ParmVarDecl>(param); 342 Param->setUnparsedDefaultArg(); 343 UnparsedDefaultArgLocs[Param] = ArgLoc; 344 } 345 346 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 347 /// the default argument for the parameter param failed. 348 void Sema::ActOnParamDefaultArgumentError(Decl *param, 349 SourceLocation EqualLoc) { 350 if (!param) 351 return; 352 353 ParmVarDecl *Param = cast<ParmVarDecl>(param); 354 Param->setInvalidDecl(); 355 UnparsedDefaultArgLocs.erase(Param); 356 Param->setDefaultArg(new(Context) 357 OpaqueValueExpr(EqualLoc, 358 Param->getType().getNonReferenceType(), 359 VK_RValue)); 360 } 361 362 /// CheckExtraCXXDefaultArguments - Check for any extra default 363 /// arguments in the declarator, which is not a function declaration 364 /// or definition and therefore is not permitted to have default 365 /// arguments. This routine should be invoked for every declarator 366 /// that is not a function declaration or definition. 367 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 368 // C++ [dcl.fct.default]p3 369 // A default argument expression shall be specified only in the 370 // parameter-declaration-clause of a function declaration or in a 371 // template-parameter (14.1). It shall not be specified for a 372 // parameter pack. If it is specified in a 373 // parameter-declaration-clause, it shall not occur within a 374 // declarator or abstract-declarator of a parameter-declaration. 375 bool MightBeFunction = D.isFunctionDeclarationContext(); 376 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 377 DeclaratorChunk &chunk = D.getTypeObject(i); 378 if (chunk.Kind == DeclaratorChunk::Function) { 379 if (MightBeFunction) { 380 // This is a function declaration. It can have default arguments, but 381 // keep looking in case its return type is a function type with default 382 // arguments. 383 MightBeFunction = false; 384 continue; 385 } 386 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 387 ++argIdx) { 388 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 389 if (Param->hasUnparsedDefaultArg()) { 390 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens; 391 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 392 << SourceRange((*Toks)[1].getLocation(), 393 Toks->back().getLocation()); 394 delete Toks; 395 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr; 396 } else if (Param->getDefaultArg()) { 397 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 398 << Param->getDefaultArg()->getSourceRange(); 399 Param->setDefaultArg(nullptr); 400 } 401 } 402 } else if (chunk.Kind != DeclaratorChunk::Paren) { 403 MightBeFunction = false; 404 } 405 } 406 } 407 408 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 409 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 410 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 411 if (!PVD->hasDefaultArg()) 412 return false; 413 if (!PVD->hasInheritedDefaultArg()) 414 return true; 415 } 416 return false; 417 } 418 419 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 420 /// function, once we already know that they have the same 421 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 422 /// error, false otherwise. 423 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 424 Scope *S) { 425 bool Invalid = false; 426 427 // C++ [dcl.fct.default]p4: 428 // For non-template functions, default arguments can be added in 429 // later declarations of a function in the same 430 // scope. Declarations in different scopes have completely 431 // distinct sets of default arguments. That is, declarations in 432 // inner scopes do not acquire default arguments from 433 // declarations in outer scopes, and vice versa. In a given 434 // function declaration, all parameters subsequent to a 435 // parameter with a default argument shall have default 436 // arguments supplied in this or previous declarations. A 437 // default argument shall not be redefined by a later 438 // declaration (not even to the same value). 439 // 440 // C++ [dcl.fct.default]p6: 441 // Except for member functions of class templates, the default arguments 442 // in a member function definition that appears outside of the class 443 // definition are added to the set of default arguments provided by the 444 // member function declaration in the class definition. 445 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 446 ParmVarDecl *OldParam = Old->getParamDecl(p); 447 ParmVarDecl *NewParam = New->getParamDecl(p); 448 449 bool OldParamHasDfl = OldParam->hasDefaultArg(); 450 bool NewParamHasDfl = NewParam->hasDefaultArg(); 451 452 // The declaration context corresponding to the scope is the semantic 453 // parent, unless this is a local function declaration, in which case 454 // it is that surrounding function. 455 DeclContext *ScopeDC = New->isLocalExternDecl() 456 ? New->getLexicalDeclContext() 457 : New->getDeclContext(); 458 if (S && !isDeclInScope(Old, ScopeDC, S) && 459 !New->getDeclContext()->isRecord()) 460 // Ignore default parameters 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 OldParamHasDfl = false; 464 if (New->isLocalExternDecl() != Old->isLocalExternDecl()) 465 // If only one of these is a local function declaration, then they are 466 // declared in different scopes, even though isDeclInScope may think 467 // they're in the same scope. (If both are local, the scope check is 468 // sufficent, and if neither is local, then they are in the same scope.) 469 OldParamHasDfl = false; 470 471 if (OldParamHasDfl && NewParamHasDfl) { 472 473 unsigned DiagDefaultParamID = 474 diag::err_param_default_argument_redefinition; 475 476 // MSVC accepts that default parameters be redefined for member functions 477 // of template class. The new default parameter's value is ignored. 478 Invalid = true; 479 if (getLangOpts().MicrosoftExt) { 480 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 481 if (MD && MD->getParent()->getDescribedClassTemplate()) { 482 // Merge the old default argument into the new parameter. 483 NewParam->setHasInheritedDefaultArg(); 484 if (OldParam->hasUninstantiatedDefaultArg()) 485 NewParam->setUninstantiatedDefaultArg( 486 OldParam->getUninstantiatedDefaultArg()); 487 else 488 NewParam->setDefaultArg(OldParam->getInit()); 489 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 490 Invalid = false; 491 } 492 } 493 494 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 495 // hint here. Alternatively, we could walk the type-source information 496 // for NewParam to find the last source location in the type... but it 497 // isn't worth the effort right now. This is the kind of test case that 498 // is hard to get right: 499 // int f(int); 500 // void g(int (*fp)(int) = f); 501 // void g(int (*fp)(int) = &f); 502 Diag(NewParam->getLocation(), DiagDefaultParamID) 503 << NewParam->getDefaultArgRange(); 504 505 // Look for the function declaration where the default argument was 506 // actually written, which may be a declaration prior to Old. 507 for (FunctionDecl *Older = Old->getPreviousDecl(); 508 Older; Older = Older->getPreviousDecl()) { 509 if (!Older->getParamDecl(p)->hasDefaultArg()) 510 break; 511 512 OldParam = Older->getParamDecl(p); 513 } 514 515 Diag(OldParam->getLocation(), diag::note_previous_definition) 516 << OldParam->getDefaultArgRange(); 517 } else if (OldParamHasDfl) { 518 // Merge the old default argument into the new parameter. 519 // It's important to use getInit() here; getDefaultArg() 520 // strips off any top-level ExprWithCleanups. 521 NewParam->setHasInheritedDefaultArg(); 522 if (OldParam->hasUninstantiatedDefaultArg()) 523 NewParam->setUninstantiatedDefaultArg( 524 OldParam->getUninstantiatedDefaultArg()); 525 else 526 NewParam->setDefaultArg(OldParam->getInit()); 527 } else if (NewParamHasDfl) { 528 if (New->getDescribedFunctionTemplate()) { 529 // Paragraph 4, quoted above, only applies to non-template functions. 530 Diag(NewParam->getLocation(), 531 diag::err_param_default_argument_template_redecl) 532 << NewParam->getDefaultArgRange(); 533 Diag(Old->getLocation(), diag::note_template_prev_declaration) 534 << false; 535 } else if (New->getTemplateSpecializationKind() 536 != TSK_ImplicitInstantiation && 537 New->getTemplateSpecializationKind() != TSK_Undeclared) { 538 // C++ [temp.expr.spec]p21: 539 // Default function arguments shall not be specified in a declaration 540 // or a definition for one of the following explicit specializations: 541 // - the explicit specialization of a function template; 542 // - the explicit specialization of a member function template; 543 // - the explicit specialization of a member function of a class 544 // template where the class template specialization to which the 545 // member function specialization belongs is implicitly 546 // instantiated. 547 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 548 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 549 << New->getDeclName() 550 << NewParam->getDefaultArgRange(); 551 } else if (New->getDeclContext()->isDependentContext()) { 552 // C++ [dcl.fct.default]p6 (DR217): 553 // Default arguments for a member function of a class template shall 554 // be specified on the initial declaration of the member function 555 // within the class template. 556 // 557 // Reading the tea leaves a bit in DR217 and its reference to DR205 558 // leads me to the conclusion that one cannot add default function 559 // arguments for an out-of-line definition of a member function of a 560 // dependent type. 561 int WhichKind = 2; 562 if (CXXRecordDecl *Record 563 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 564 if (Record->getDescribedClassTemplate()) 565 WhichKind = 0; 566 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 567 WhichKind = 1; 568 else 569 WhichKind = 2; 570 } 571 572 Diag(NewParam->getLocation(), 573 diag::err_param_default_argument_member_template_redecl) 574 << WhichKind 575 << NewParam->getDefaultArgRange(); 576 } 577 } 578 } 579 580 // DR1344: If a default argument is added outside a class definition and that 581 // default argument makes the function a special member function, the program 582 // is ill-formed. This can only happen for constructors. 583 if (isa<CXXConstructorDecl>(New) && 584 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 585 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 586 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 587 if (NewSM != OldSM) { 588 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 589 assert(NewParam->hasDefaultArg()); 590 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 591 << NewParam->getDefaultArgRange() << NewSM; 592 Diag(Old->getLocation(), diag::note_previous_declaration); 593 } 594 } 595 596 const FunctionDecl *Def; 597 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 598 // template has a constexpr specifier then all its declarations shall 599 // contain the constexpr specifier. 600 if (New->isConstexpr() != Old->isConstexpr()) { 601 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 602 << New << New->isConstexpr(); 603 Diag(Old->getLocation(), diag::note_previous_declaration); 604 Invalid = true; 605 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) { 606 // C++11 [dcl.fcn.spec]p4: 607 // If the definition of a function appears in a translation unit before its 608 // first declaration as inline, the program is ill-formed. 609 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 610 Diag(Def->getLocation(), diag::note_previous_definition); 611 Invalid = true; 612 } 613 614 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 615 // argument expression, that declaration shall be a definition and shall be 616 // the only declaration of the function or function template in the 617 // translation unit. 618 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 619 functionDeclHasDefaultArgument(Old)) { 620 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 621 Diag(Old->getLocation(), diag::note_previous_declaration); 622 Invalid = true; 623 } 624 625 if (CheckEquivalentExceptionSpec(Old, New)) 626 Invalid = true; 627 628 return Invalid; 629 } 630 631 /// \brief Merge the exception specifications of two variable declarations. 632 /// 633 /// This is called when there's a redeclaration of a VarDecl. The function 634 /// checks if the redeclaration might have an exception specification and 635 /// validates compatibility and merges the specs if necessary. 636 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 637 // Shortcut if exceptions are disabled. 638 if (!getLangOpts().CXXExceptions) 639 return; 640 641 assert(Context.hasSameType(New->getType(), Old->getType()) && 642 "Should only be called if types are otherwise the same."); 643 644 QualType NewType = New->getType(); 645 QualType OldType = Old->getType(); 646 647 // We're only interested in pointers and references to functions, as well 648 // as pointers to member functions. 649 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 650 NewType = R->getPointeeType(); 651 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 652 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 653 NewType = P->getPointeeType(); 654 OldType = OldType->getAs<PointerType>()->getPointeeType(); 655 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 656 NewType = M->getPointeeType(); 657 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 658 } 659 660 if (!NewType->isFunctionProtoType()) 661 return; 662 663 // There's lots of special cases for functions. For function pointers, system 664 // libraries are hopefully not as broken so that we don't need these 665 // workarounds. 666 if (CheckEquivalentExceptionSpec( 667 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 668 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 669 New->setInvalidDecl(); 670 } 671 } 672 673 /// CheckCXXDefaultArguments - Verify that the default arguments for a 674 /// function declaration are well-formed according to C++ 675 /// [dcl.fct.default]. 676 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 677 unsigned NumParams = FD->getNumParams(); 678 unsigned p; 679 680 // Find first parameter with a default argument 681 for (p = 0; p < NumParams; ++p) { 682 ParmVarDecl *Param = FD->getParamDecl(p); 683 if (Param->hasDefaultArg()) 684 break; 685 } 686 687 // C++ [dcl.fct.default]p4: 688 // In a given function declaration, all parameters 689 // subsequent to a parameter with a default argument shall 690 // have default arguments supplied in this or previous 691 // declarations. A default argument shall not be redefined 692 // by a later declaration (not even to the same value). 693 unsigned LastMissingDefaultArg = 0; 694 for (; p < NumParams; ++p) { 695 ParmVarDecl *Param = FD->getParamDecl(p); 696 if (!Param->hasDefaultArg()) { 697 if (Param->isInvalidDecl()) 698 /* We already complained about this parameter. */; 699 else if (Param->getIdentifier()) 700 Diag(Param->getLocation(), 701 diag::err_param_default_argument_missing_name) 702 << Param->getIdentifier(); 703 else 704 Diag(Param->getLocation(), 705 diag::err_param_default_argument_missing); 706 707 LastMissingDefaultArg = p; 708 } 709 } 710 711 if (LastMissingDefaultArg > 0) { 712 // Some default arguments were missing. Clear out all of the 713 // default arguments up to (and including) the last missing 714 // default argument, so that we leave the function parameters 715 // in a semantically valid state. 716 for (p = 0; p <= LastMissingDefaultArg; ++p) { 717 ParmVarDecl *Param = FD->getParamDecl(p); 718 if (Param->hasDefaultArg()) { 719 Param->setDefaultArg(nullptr); 720 } 721 } 722 } 723 } 724 725 // CheckConstexprParameterTypes - Check whether a function's parameter types 726 // are all literal types. If so, return true. If not, produce a suitable 727 // diagnostic and return false. 728 static bool CheckConstexprParameterTypes(Sema &SemaRef, 729 const FunctionDecl *FD) { 730 unsigned ArgIndex = 0; 731 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 732 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 733 e = FT->param_type_end(); 734 i != e; ++i, ++ArgIndex) { 735 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 736 SourceLocation ParamLoc = PD->getLocation(); 737 if (!(*i)->isDependentType() && 738 SemaRef.RequireLiteralType(ParamLoc, *i, 739 diag::err_constexpr_non_literal_param, 740 ArgIndex+1, PD->getSourceRange(), 741 isa<CXXConstructorDecl>(FD))) 742 return false; 743 } 744 return true; 745 } 746 747 /// \brief Get diagnostic %select index for tag kind for 748 /// record diagnostic message. 749 /// WARNING: Indexes apply to particular diagnostics only! 750 /// 751 /// \returns diagnostic %select index. 752 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 753 switch (Tag) { 754 case TTK_Struct: return 0; 755 case TTK_Interface: return 1; 756 case TTK_Class: return 2; 757 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 758 } 759 } 760 761 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 762 // the requirements of a constexpr function definition or a constexpr 763 // constructor definition. If so, return true. If not, produce appropriate 764 // diagnostics and return false. 765 // 766 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 767 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 768 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 769 if (MD && MD->isInstance()) { 770 // C++11 [dcl.constexpr]p4: 771 // The definition of a constexpr constructor shall satisfy the following 772 // constraints: 773 // - the class shall not have any virtual base classes; 774 const CXXRecordDecl *RD = MD->getParent(); 775 if (RD->getNumVBases()) { 776 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 777 << isa<CXXConstructorDecl>(NewFD) 778 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 779 for (const auto &I : RD->vbases()) 780 Diag(I.getLocStart(), 781 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 782 return false; 783 } 784 } 785 786 if (!isa<CXXConstructorDecl>(NewFD)) { 787 // C++11 [dcl.constexpr]p3: 788 // The definition of a constexpr function shall satisfy the following 789 // constraints: 790 // - it shall not be virtual; 791 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 792 if (Method && Method->isVirtual()) { 793 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 794 795 // If it's not obvious why this function is virtual, find an overridden 796 // function which uses the 'virtual' keyword. 797 const CXXMethodDecl *WrittenVirtual = Method; 798 while (!WrittenVirtual->isVirtualAsWritten()) 799 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 800 if (WrittenVirtual != Method) 801 Diag(WrittenVirtual->getLocation(), 802 diag::note_overridden_virtual_function); 803 return false; 804 } 805 806 // - its return type shall be a literal type; 807 QualType RT = NewFD->getReturnType(); 808 if (!RT->isDependentType() && 809 RequireLiteralType(NewFD->getLocation(), RT, 810 diag::err_constexpr_non_literal_return)) 811 return false; 812 } 813 814 // - each of its parameter types shall be a literal type; 815 if (!CheckConstexprParameterTypes(*this, NewFD)) 816 return false; 817 818 return true; 819 } 820 821 /// Check the given declaration statement is legal within a constexpr function 822 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 823 /// 824 /// \return true if the body is OK (maybe only as an extension), false if we 825 /// have diagnosed a problem. 826 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 827 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 828 // C++11 [dcl.constexpr]p3 and p4: 829 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 830 // contain only 831 for (const auto *DclIt : DS->decls()) { 832 switch (DclIt->getKind()) { 833 case Decl::StaticAssert: 834 case Decl::Using: 835 case Decl::UsingShadow: 836 case Decl::UsingDirective: 837 case Decl::UnresolvedUsingTypename: 838 case Decl::UnresolvedUsingValue: 839 // - static_assert-declarations 840 // - using-declarations, 841 // - using-directives, 842 continue; 843 844 case Decl::Typedef: 845 case Decl::TypeAlias: { 846 // - typedef declarations and alias-declarations that do not define 847 // classes or enumerations, 848 const auto *TN = cast<TypedefNameDecl>(DclIt); 849 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 850 // Don't allow variably-modified types in constexpr functions. 851 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 852 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 853 << TL.getSourceRange() << TL.getType() 854 << isa<CXXConstructorDecl>(Dcl); 855 return false; 856 } 857 continue; 858 } 859 860 case Decl::Enum: 861 case Decl::CXXRecord: 862 // C++1y allows types to be defined, not just declared. 863 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 864 SemaRef.Diag(DS->getLocStart(), 865 SemaRef.getLangOpts().CPlusPlus14 866 ? diag::warn_cxx11_compat_constexpr_type_definition 867 : diag::ext_constexpr_type_definition) 868 << isa<CXXConstructorDecl>(Dcl); 869 continue; 870 871 case Decl::EnumConstant: 872 case Decl::IndirectField: 873 case Decl::ParmVar: 874 // These can only appear with other declarations which are banned in 875 // C++11 and permitted in C++1y, so ignore them. 876 continue; 877 878 case Decl::Var: { 879 // C++1y [dcl.constexpr]p3 allows anything except: 880 // a definition of a variable of non-literal type or of static or 881 // thread storage duration or for which no initialization is performed. 882 const auto *VD = cast<VarDecl>(DclIt); 883 if (VD->isThisDeclarationADefinition()) { 884 if (VD->isStaticLocal()) { 885 SemaRef.Diag(VD->getLocation(), 886 diag::err_constexpr_local_var_static) 887 << isa<CXXConstructorDecl>(Dcl) 888 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 889 return false; 890 } 891 if (!VD->getType()->isDependentType() && 892 SemaRef.RequireLiteralType( 893 VD->getLocation(), VD->getType(), 894 diag::err_constexpr_local_var_non_literal_type, 895 isa<CXXConstructorDecl>(Dcl))) 896 return false; 897 if (!VD->getType()->isDependentType() && 898 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 899 SemaRef.Diag(VD->getLocation(), 900 diag::err_constexpr_local_var_no_init) 901 << isa<CXXConstructorDecl>(Dcl); 902 return false; 903 } 904 } 905 SemaRef.Diag(VD->getLocation(), 906 SemaRef.getLangOpts().CPlusPlus14 907 ? diag::warn_cxx11_compat_constexpr_local_var 908 : diag::ext_constexpr_local_var) 909 << isa<CXXConstructorDecl>(Dcl); 910 continue; 911 } 912 913 case Decl::NamespaceAlias: 914 case Decl::Function: 915 // These are disallowed in C++11 and permitted in C++1y. Allow them 916 // everywhere as an extension. 917 if (!Cxx1yLoc.isValid()) 918 Cxx1yLoc = DS->getLocStart(); 919 continue; 920 921 default: 922 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 923 << isa<CXXConstructorDecl>(Dcl); 924 return false; 925 } 926 } 927 928 return true; 929 } 930 931 /// Check that the given field is initialized within a constexpr constructor. 932 /// 933 /// \param Dcl The constexpr constructor being checked. 934 /// \param Field The field being checked. This may be a member of an anonymous 935 /// struct or union nested within the class being checked. 936 /// \param Inits All declarations, including anonymous struct/union members and 937 /// indirect members, for which any initialization was provided. 938 /// \param Diagnosed Set to true if an error is produced. 939 static void CheckConstexprCtorInitializer(Sema &SemaRef, 940 const FunctionDecl *Dcl, 941 FieldDecl *Field, 942 llvm::SmallSet<Decl*, 16> &Inits, 943 bool &Diagnosed) { 944 if (Field->isInvalidDecl()) 945 return; 946 947 if (Field->isUnnamedBitfield()) 948 return; 949 950 // Anonymous unions with no variant members and empty anonymous structs do not 951 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 952 // indirect fields don't need initializing. 953 if (Field->isAnonymousStructOrUnion() && 954 (Field->getType()->isUnionType() 955 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 956 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 957 return; 958 959 if (!Inits.count(Field)) { 960 if (!Diagnosed) { 961 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 962 Diagnosed = true; 963 } 964 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 965 } else if (Field->isAnonymousStructOrUnion()) { 966 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 967 for (auto *I : RD->fields()) 968 // If an anonymous union contains an anonymous struct of which any member 969 // is initialized, all members must be initialized. 970 if (!RD->isUnion() || Inits.count(I)) 971 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 972 } 973 } 974 975 /// Check the provided statement is allowed in a constexpr function 976 /// definition. 977 static bool 978 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 979 SmallVectorImpl<SourceLocation> &ReturnStmts, 980 SourceLocation &Cxx1yLoc) { 981 // - its function-body shall be [...] a compound-statement that contains only 982 switch (S->getStmtClass()) { 983 case Stmt::NullStmtClass: 984 // - null statements, 985 return true; 986 987 case Stmt::DeclStmtClass: 988 // - static_assert-declarations 989 // - using-declarations, 990 // - using-directives, 991 // - typedef declarations and alias-declarations that do not define 992 // classes or enumerations, 993 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 994 return false; 995 return true; 996 997 case Stmt::ReturnStmtClass: 998 // - and exactly one return statement; 999 if (isa<CXXConstructorDecl>(Dcl)) { 1000 // C++1y allows return statements in constexpr constructors. 1001 if (!Cxx1yLoc.isValid()) 1002 Cxx1yLoc = S->getLocStart(); 1003 return true; 1004 } 1005 1006 ReturnStmts.push_back(S->getLocStart()); 1007 return true; 1008 1009 case Stmt::CompoundStmtClass: { 1010 // C++1y allows compound-statements. 1011 if (!Cxx1yLoc.isValid()) 1012 Cxx1yLoc = S->getLocStart(); 1013 1014 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1015 for (auto *BodyIt : CompStmt->body()) { 1016 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1017 Cxx1yLoc)) 1018 return false; 1019 } 1020 return true; 1021 } 1022 1023 case Stmt::AttributedStmtClass: 1024 if (!Cxx1yLoc.isValid()) 1025 Cxx1yLoc = S->getLocStart(); 1026 return true; 1027 1028 case Stmt::IfStmtClass: { 1029 // C++1y allows if-statements. 1030 if (!Cxx1yLoc.isValid()) 1031 Cxx1yLoc = S->getLocStart(); 1032 1033 IfStmt *If = cast<IfStmt>(S); 1034 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1035 Cxx1yLoc)) 1036 return false; 1037 if (If->getElse() && 1038 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1039 Cxx1yLoc)) 1040 return false; 1041 return true; 1042 } 1043 1044 case Stmt::WhileStmtClass: 1045 case Stmt::DoStmtClass: 1046 case Stmt::ForStmtClass: 1047 case Stmt::CXXForRangeStmtClass: 1048 case Stmt::ContinueStmtClass: 1049 // C++1y allows all of these. We don't allow them as extensions in C++11, 1050 // because they don't make sense without variable mutation. 1051 if (!SemaRef.getLangOpts().CPlusPlus14) 1052 break; 1053 if (!Cxx1yLoc.isValid()) 1054 Cxx1yLoc = S->getLocStart(); 1055 for (Stmt::child_range Children = S->children(); Children; ++Children) 1056 if (*Children && 1057 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1058 Cxx1yLoc)) 1059 return false; 1060 return true; 1061 1062 case Stmt::SwitchStmtClass: 1063 case Stmt::CaseStmtClass: 1064 case Stmt::DefaultStmtClass: 1065 case Stmt::BreakStmtClass: 1066 // C++1y allows switch-statements, and since they don't need variable 1067 // mutation, we can reasonably allow them in C++11 as an extension. 1068 if (!Cxx1yLoc.isValid()) 1069 Cxx1yLoc = S->getLocStart(); 1070 for (Stmt::child_range Children = S->children(); Children; ++Children) 1071 if (*Children && 1072 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1073 Cxx1yLoc)) 1074 return false; 1075 return true; 1076 1077 default: 1078 if (!isa<Expr>(S)) 1079 break; 1080 1081 // C++1y allows expression-statements. 1082 if (!Cxx1yLoc.isValid()) 1083 Cxx1yLoc = S->getLocStart(); 1084 return true; 1085 } 1086 1087 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1088 << isa<CXXConstructorDecl>(Dcl); 1089 return false; 1090 } 1091 1092 /// Check the body for the given constexpr function declaration only contains 1093 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1094 /// 1095 /// \return true if the body is OK, false if we have diagnosed a problem. 1096 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1097 if (isa<CXXTryStmt>(Body)) { 1098 // C++11 [dcl.constexpr]p3: 1099 // The definition of a constexpr function shall satisfy the following 1100 // constraints: [...] 1101 // - its function-body shall be = delete, = default, or a 1102 // compound-statement 1103 // 1104 // C++11 [dcl.constexpr]p4: 1105 // In the definition of a constexpr constructor, [...] 1106 // - its function-body shall not be a function-try-block; 1107 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1108 << isa<CXXConstructorDecl>(Dcl); 1109 return false; 1110 } 1111 1112 SmallVector<SourceLocation, 4> ReturnStmts; 1113 1114 // - its function-body shall be [...] a compound-statement that contains only 1115 // [... list of cases ...] 1116 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1117 SourceLocation Cxx1yLoc; 1118 for (auto *BodyIt : CompBody->body()) { 1119 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1120 return false; 1121 } 1122 1123 if (Cxx1yLoc.isValid()) 1124 Diag(Cxx1yLoc, 1125 getLangOpts().CPlusPlus14 1126 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1127 : diag::ext_constexpr_body_invalid_stmt) 1128 << isa<CXXConstructorDecl>(Dcl); 1129 1130 if (const CXXConstructorDecl *Constructor 1131 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1132 const CXXRecordDecl *RD = Constructor->getParent(); 1133 // DR1359: 1134 // - every non-variant non-static data member and base class sub-object 1135 // shall be initialized; 1136 // DR1460: 1137 // - if the class is a union having variant members, exactly one of them 1138 // shall be initialized; 1139 if (RD->isUnion()) { 1140 if (Constructor->getNumCtorInitializers() == 0 && 1141 RD->hasVariantMembers()) { 1142 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1143 return false; 1144 } 1145 } else if (!Constructor->isDependentContext() && 1146 !Constructor->isDelegatingConstructor()) { 1147 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1148 1149 // Skip detailed checking if we have enough initializers, and we would 1150 // allow at most one initializer per member. 1151 bool AnyAnonStructUnionMembers = false; 1152 unsigned Fields = 0; 1153 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1154 E = RD->field_end(); I != E; ++I, ++Fields) { 1155 if (I->isAnonymousStructOrUnion()) { 1156 AnyAnonStructUnionMembers = true; 1157 break; 1158 } 1159 } 1160 // DR1460: 1161 // - if the class is a union-like class, but is not a union, for each of 1162 // its anonymous union members having variant members, exactly one of 1163 // them shall be initialized; 1164 if (AnyAnonStructUnionMembers || 1165 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1166 // Check initialization of non-static data members. Base classes are 1167 // always initialized so do not need to be checked. Dependent bases 1168 // might not have initializers in the member initializer list. 1169 llvm::SmallSet<Decl*, 16> Inits; 1170 for (const auto *I: Constructor->inits()) { 1171 if (FieldDecl *FD = I->getMember()) 1172 Inits.insert(FD); 1173 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1174 Inits.insert(ID->chain_begin(), ID->chain_end()); 1175 } 1176 1177 bool Diagnosed = false; 1178 for (auto *I : RD->fields()) 1179 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1180 if (Diagnosed) 1181 return false; 1182 } 1183 } 1184 } else { 1185 if (ReturnStmts.empty()) { 1186 // C++1y doesn't require constexpr functions to contain a 'return' 1187 // statement. We still do, unless the return type might be void, because 1188 // otherwise if there's no return statement, the function cannot 1189 // be used in a core constant expression. 1190 bool OK = getLangOpts().CPlusPlus14 && 1191 (Dcl->getReturnType()->isVoidType() || 1192 Dcl->getReturnType()->isDependentType()); 1193 Diag(Dcl->getLocation(), 1194 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1195 : diag::err_constexpr_body_no_return); 1196 return OK; 1197 } 1198 if (ReturnStmts.size() > 1) { 1199 Diag(ReturnStmts.back(), 1200 getLangOpts().CPlusPlus14 1201 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1202 : diag::ext_constexpr_body_multiple_return); 1203 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1204 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1205 } 1206 } 1207 1208 // C++11 [dcl.constexpr]p5: 1209 // if no function argument values exist such that the function invocation 1210 // substitution would produce a constant expression, the program is 1211 // ill-formed; no diagnostic required. 1212 // C++11 [dcl.constexpr]p3: 1213 // - every constructor call and implicit conversion used in initializing the 1214 // return value shall be one of those allowed in a constant expression. 1215 // C++11 [dcl.constexpr]p4: 1216 // - every constructor involved in initializing non-static data members and 1217 // base class sub-objects shall be a constexpr constructor. 1218 SmallVector<PartialDiagnosticAt, 8> Diags; 1219 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1220 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1221 << isa<CXXConstructorDecl>(Dcl); 1222 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1223 Diag(Diags[I].first, Diags[I].second); 1224 // Don't return false here: we allow this for compatibility in 1225 // system headers. 1226 } 1227 1228 return true; 1229 } 1230 1231 /// isCurrentClassName - Determine whether the identifier II is the 1232 /// name of the class type currently being defined. In the case of 1233 /// nested classes, this will only return true if II is the name of 1234 /// the innermost class. 1235 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1236 const CXXScopeSpec *SS) { 1237 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1238 1239 CXXRecordDecl *CurDecl; 1240 if (SS && SS->isSet() && !SS->isInvalid()) { 1241 DeclContext *DC = computeDeclContext(*SS, true); 1242 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1243 } else 1244 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1245 1246 if (CurDecl && CurDecl->getIdentifier()) 1247 return &II == CurDecl->getIdentifier(); 1248 return false; 1249 } 1250 1251 /// \brief Determine whether the identifier II is a typo for the name of 1252 /// the class type currently being defined. If so, update it to the identifier 1253 /// that should have been used. 1254 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1255 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1256 1257 if (!getLangOpts().SpellChecking) 1258 return false; 1259 1260 CXXRecordDecl *CurDecl; 1261 if (SS && SS->isSet() && !SS->isInvalid()) { 1262 DeclContext *DC = computeDeclContext(*SS, true); 1263 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1264 } else 1265 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1266 1267 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1268 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1269 < II->getLength()) { 1270 II = CurDecl->getIdentifier(); 1271 return true; 1272 } 1273 1274 return false; 1275 } 1276 1277 /// \brief Determine whether the given class is a base class of the given 1278 /// class, including looking at dependent bases. 1279 static bool findCircularInheritance(const CXXRecordDecl *Class, 1280 const CXXRecordDecl *Current) { 1281 SmallVector<const CXXRecordDecl*, 8> Queue; 1282 1283 Class = Class->getCanonicalDecl(); 1284 while (true) { 1285 for (const auto &I : Current->bases()) { 1286 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1287 if (!Base) 1288 continue; 1289 1290 Base = Base->getDefinition(); 1291 if (!Base) 1292 continue; 1293 1294 if (Base->getCanonicalDecl() == Class) 1295 return true; 1296 1297 Queue.push_back(Base); 1298 } 1299 1300 if (Queue.empty()) 1301 return false; 1302 1303 Current = Queue.pop_back_val(); 1304 } 1305 1306 return false; 1307 } 1308 1309 /// \brief Perform propagation of DLL attributes from a derived class to a 1310 /// templated base class for MS compatibility. 1311 static void propagateDLLAttrToBaseClassTemplate( 1312 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr, 1313 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 1314 if (getDLLAttr( 1315 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 1316 // If the base class template has a DLL attribute, don't try to change it. 1317 return; 1318 } 1319 1320 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 1321 // If the base class is not already specialized, we can do the propagation. 1322 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 1323 NewAttr->setInherited(true); 1324 BaseTemplateSpec->addAttr(NewAttr); 1325 return; 1326 } 1327 1328 bool DifferentAttribute = false; 1329 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) { 1330 if (!SpecializationAttr->isInherited()) { 1331 // The template has previously been specialized or instantiated with an 1332 // explicit attribute. We should not try to change it. 1333 return; 1334 } 1335 if (SpecializationAttr->getKind() == ClassAttr->getKind()) { 1336 // The specialization already has the right attribute. 1337 return; 1338 } 1339 DifferentAttribute = true; 1340 } 1341 1342 // The template was previously instantiated or explicitly specialized without 1343 // a dll attribute, or the template was previously instantiated with a 1344 // different inherited attribute. It's too late for us to change the 1345 // attribute, so warn that this is unsupported. 1346 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 1347 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute; 1348 S.Diag(ClassAttr->getLocation(), diag::note_attribute); 1349 if (BaseTemplateSpec->isExplicitSpecialization()) { 1350 S.Diag(BaseTemplateSpec->getLocation(), 1351 diag::note_template_class_explicit_specialization_was_here) 1352 << BaseTemplateSpec; 1353 } else { 1354 S.Diag(BaseTemplateSpec->getPointOfInstantiation(), 1355 diag::note_template_class_instantiation_was_here) 1356 << BaseTemplateSpec; 1357 } 1358 } 1359 1360 /// \brief Check the validity of a C++ base class specifier. 1361 /// 1362 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1363 /// and returns NULL otherwise. 1364 CXXBaseSpecifier * 1365 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1366 SourceRange SpecifierRange, 1367 bool Virtual, AccessSpecifier Access, 1368 TypeSourceInfo *TInfo, 1369 SourceLocation EllipsisLoc) { 1370 QualType BaseType = TInfo->getType(); 1371 1372 // C++ [class.union]p1: 1373 // A union shall not have base classes. 1374 if (Class->isUnion()) { 1375 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1376 << SpecifierRange; 1377 return nullptr; 1378 } 1379 1380 if (EllipsisLoc.isValid() && 1381 !TInfo->getType()->containsUnexpandedParameterPack()) { 1382 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1383 << TInfo->getTypeLoc().getSourceRange(); 1384 EllipsisLoc = SourceLocation(); 1385 } 1386 1387 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1388 1389 if (BaseType->isDependentType()) { 1390 // Make sure that we don't have circular inheritance among our dependent 1391 // bases. For non-dependent bases, the check for completeness below handles 1392 // this. 1393 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1394 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1395 ((BaseDecl = BaseDecl->getDefinition()) && 1396 findCircularInheritance(Class, BaseDecl))) { 1397 Diag(BaseLoc, diag::err_circular_inheritance) 1398 << BaseType << Context.getTypeDeclType(Class); 1399 1400 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1401 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1402 << BaseType; 1403 1404 return nullptr; 1405 } 1406 } 1407 1408 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1409 Class->getTagKind() == TTK_Class, 1410 Access, TInfo, EllipsisLoc); 1411 } 1412 1413 // Base specifiers must be record types. 1414 if (!BaseType->isRecordType()) { 1415 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1416 return nullptr; 1417 } 1418 1419 // C++ [class.union]p1: 1420 // A union shall not be used as a base class. 1421 if (BaseType->isUnionType()) { 1422 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1423 return nullptr; 1424 } 1425 1426 // For the MS ABI, propagate DLL attributes to base class templates. 1427 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1428 if (Attr *ClassAttr = getDLLAttr(Class)) { 1429 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1430 BaseType->getAsCXXRecordDecl())) { 1431 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr, 1432 BaseTemplate, BaseLoc); 1433 } 1434 } 1435 } 1436 1437 // C++ [class.derived]p2: 1438 // The class-name in a base-specifier shall not be an incompletely 1439 // defined class. 1440 if (RequireCompleteType(BaseLoc, BaseType, 1441 diag::err_incomplete_base_class, SpecifierRange)) { 1442 Class->setInvalidDecl(); 1443 return nullptr; 1444 } 1445 1446 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1447 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1448 assert(BaseDecl && "Record type has no declaration"); 1449 BaseDecl = BaseDecl->getDefinition(); 1450 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1451 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1452 assert(CXXBaseDecl && "Base type is not a C++ type"); 1453 1454 // A class which contains a flexible array member is not suitable for use as a 1455 // base class: 1456 // - If the layout determines that a base comes before another base, 1457 // the flexible array member would index into the subsequent base. 1458 // - If the layout determines that base comes before the derived class, 1459 // the flexible array member would index into the derived class. 1460 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1461 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1462 << CXXBaseDecl->getDeclName(); 1463 return nullptr; 1464 } 1465 1466 // C++ [class]p3: 1467 // If a class is marked final and it appears as a base-type-specifier in 1468 // base-clause, the program is ill-formed. 1469 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1470 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1471 << CXXBaseDecl->getDeclName() 1472 << FA->isSpelledAsSealed(); 1473 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 1474 << CXXBaseDecl->getDeclName() << FA->getRange(); 1475 return nullptr; 1476 } 1477 1478 if (BaseDecl->isInvalidDecl()) 1479 Class->setInvalidDecl(); 1480 1481 // Create the base specifier. 1482 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1483 Class->getTagKind() == TTK_Class, 1484 Access, TInfo, EllipsisLoc); 1485 } 1486 1487 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1488 /// one entry in the base class list of a class specifier, for 1489 /// example: 1490 /// class foo : public bar, virtual private baz { 1491 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1492 BaseResult 1493 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1494 ParsedAttributes &Attributes, 1495 bool Virtual, AccessSpecifier Access, 1496 ParsedType basetype, SourceLocation BaseLoc, 1497 SourceLocation EllipsisLoc) { 1498 if (!classdecl) 1499 return true; 1500 1501 AdjustDeclIfTemplate(classdecl); 1502 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1503 if (!Class) 1504 return true; 1505 1506 // We haven't yet attached the base specifiers. 1507 Class->setIsParsingBaseSpecifiers(); 1508 1509 // We do not support any C++11 attributes on base-specifiers yet. 1510 // Diagnose any attributes we see. 1511 if (!Attributes.empty()) { 1512 for (AttributeList *Attr = Attributes.getList(); Attr; 1513 Attr = Attr->getNext()) { 1514 if (Attr->isInvalid() || 1515 Attr->getKind() == AttributeList::IgnoredAttribute) 1516 continue; 1517 Diag(Attr->getLoc(), 1518 Attr->getKind() == AttributeList::UnknownAttribute 1519 ? diag::warn_unknown_attribute_ignored 1520 : diag::err_base_specifier_attribute) 1521 << Attr->getName(); 1522 } 1523 } 1524 1525 TypeSourceInfo *TInfo = nullptr; 1526 GetTypeFromParser(basetype, &TInfo); 1527 1528 if (EllipsisLoc.isInvalid() && 1529 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1530 UPPC_BaseType)) 1531 return true; 1532 1533 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1534 Virtual, Access, TInfo, 1535 EllipsisLoc)) 1536 return BaseSpec; 1537 else 1538 Class->setInvalidDecl(); 1539 1540 return true; 1541 } 1542 1543 /// \brief Performs the actual work of attaching the given base class 1544 /// specifiers to a C++ class. 1545 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1546 unsigned NumBases) { 1547 if (NumBases == 0) 1548 return false; 1549 1550 // Used to keep track of which base types we have already seen, so 1551 // that we can properly diagnose redundant direct base types. Note 1552 // that the key is always the unqualified canonical type of the base 1553 // class. 1554 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1555 1556 // Copy non-redundant base specifiers into permanent storage. 1557 unsigned NumGoodBases = 0; 1558 bool Invalid = false; 1559 for (unsigned idx = 0; idx < NumBases; ++idx) { 1560 QualType NewBaseType 1561 = Context.getCanonicalType(Bases[idx]->getType()); 1562 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1563 1564 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1565 if (KnownBase) { 1566 // C++ [class.mi]p3: 1567 // A class shall not be specified as a direct base class of a 1568 // derived class more than once. 1569 Diag(Bases[idx]->getLocStart(), 1570 diag::err_duplicate_base_class) 1571 << KnownBase->getType() 1572 << Bases[idx]->getSourceRange(); 1573 1574 // Delete the duplicate base class specifier; we're going to 1575 // overwrite its pointer later. 1576 Context.Deallocate(Bases[idx]); 1577 1578 Invalid = true; 1579 } else { 1580 // Okay, add this new base class. 1581 KnownBase = Bases[idx]; 1582 Bases[NumGoodBases++] = Bases[idx]; 1583 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1584 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1585 if (Class->isInterface() && 1586 (!RD->isInterface() || 1587 KnownBase->getAccessSpecifier() != AS_public)) { 1588 // The Microsoft extension __interface does not permit bases that 1589 // are not themselves public interfaces. 1590 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1591 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1592 << RD->getSourceRange(); 1593 Invalid = true; 1594 } 1595 if (RD->hasAttr<WeakAttr>()) 1596 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1597 } 1598 } 1599 } 1600 1601 // Attach the remaining base class specifiers to the derived class. 1602 Class->setBases(Bases, NumGoodBases); 1603 1604 // Delete the remaining (good) base class specifiers, since their 1605 // data has been copied into the CXXRecordDecl. 1606 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1607 Context.Deallocate(Bases[idx]); 1608 1609 return Invalid; 1610 } 1611 1612 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1613 /// class, after checking whether there are any duplicate base 1614 /// classes. 1615 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1616 unsigned NumBases) { 1617 if (!ClassDecl || !Bases || !NumBases) 1618 return; 1619 1620 AdjustDeclIfTemplate(ClassDecl); 1621 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1622 } 1623 1624 /// \brief Determine whether the type \p Derived is a C++ class that is 1625 /// derived from the type \p Base. 1626 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1627 if (!getLangOpts().CPlusPlus) 1628 return false; 1629 1630 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1631 if (!DerivedRD) 1632 return false; 1633 1634 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1635 if (!BaseRD) 1636 return false; 1637 1638 // If either the base or the derived type is invalid, don't try to 1639 // check whether one is derived from the other. 1640 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1641 return false; 1642 1643 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1644 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1645 } 1646 1647 /// \brief Determine whether the type \p Derived is a C++ class that is 1648 /// derived from the type \p Base. 1649 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1650 if (!getLangOpts().CPlusPlus) 1651 return false; 1652 1653 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1654 if (!DerivedRD) 1655 return false; 1656 1657 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1658 if (!BaseRD) 1659 return false; 1660 1661 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1662 } 1663 1664 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1665 CXXCastPath &BasePathArray) { 1666 assert(BasePathArray.empty() && "Base path array must be empty!"); 1667 assert(Paths.isRecordingPaths() && "Must record paths!"); 1668 1669 const CXXBasePath &Path = Paths.front(); 1670 1671 // We first go backward and check if we have a virtual base. 1672 // FIXME: It would be better if CXXBasePath had the base specifier for 1673 // the nearest virtual base. 1674 unsigned Start = 0; 1675 for (unsigned I = Path.size(); I != 0; --I) { 1676 if (Path[I - 1].Base->isVirtual()) { 1677 Start = I - 1; 1678 break; 1679 } 1680 } 1681 1682 // Now add all bases. 1683 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1684 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1685 } 1686 1687 /// \brief Determine whether the given base path includes a virtual 1688 /// base class. 1689 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1690 for (CXXCastPath::const_iterator B = BasePath.begin(), 1691 BEnd = BasePath.end(); 1692 B != BEnd; ++B) 1693 if ((*B)->isVirtual()) 1694 return true; 1695 1696 return false; 1697 } 1698 1699 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1700 /// conversion (where Derived and Base are class types) is 1701 /// well-formed, meaning that the conversion is unambiguous (and 1702 /// that all of the base classes are accessible). Returns true 1703 /// and emits a diagnostic if the code is ill-formed, returns false 1704 /// otherwise. Loc is the location where this routine should point to 1705 /// if there is an error, and Range is the source range to highlight 1706 /// if there is an error. 1707 bool 1708 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1709 unsigned InaccessibleBaseID, 1710 unsigned AmbigiousBaseConvID, 1711 SourceLocation Loc, SourceRange Range, 1712 DeclarationName Name, 1713 CXXCastPath *BasePath) { 1714 // First, determine whether the path from Derived to Base is 1715 // ambiguous. This is slightly more expensive than checking whether 1716 // the Derived to Base conversion exists, because here we need to 1717 // explore multiple paths to determine if there is an ambiguity. 1718 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1719 /*DetectVirtual=*/false); 1720 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1721 assert(DerivationOkay && 1722 "Can only be used with a derived-to-base conversion"); 1723 (void)DerivationOkay; 1724 1725 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1726 if (InaccessibleBaseID) { 1727 // Check that the base class can be accessed. 1728 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1729 InaccessibleBaseID)) { 1730 case AR_inaccessible: 1731 return true; 1732 case AR_accessible: 1733 case AR_dependent: 1734 case AR_delayed: 1735 break; 1736 } 1737 } 1738 1739 // Build a base path if necessary. 1740 if (BasePath) 1741 BuildBasePathArray(Paths, *BasePath); 1742 return false; 1743 } 1744 1745 if (AmbigiousBaseConvID) { 1746 // We know that the derived-to-base conversion is ambiguous, and 1747 // we're going to produce a diagnostic. Perform the derived-to-base 1748 // search just one more time to compute all of the possible paths so 1749 // that we can print them out. This is more expensive than any of 1750 // the previous derived-to-base checks we've done, but at this point 1751 // performance isn't as much of an issue. 1752 Paths.clear(); 1753 Paths.setRecordingPaths(true); 1754 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1755 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1756 (void)StillOkay; 1757 1758 // Build up a textual representation of the ambiguous paths, e.g., 1759 // D -> B -> A, that will be used to illustrate the ambiguous 1760 // conversions in the diagnostic. We only print one of the paths 1761 // to each base class subobject. 1762 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1763 1764 Diag(Loc, AmbigiousBaseConvID) 1765 << Derived << Base << PathDisplayStr << Range << Name; 1766 } 1767 return true; 1768 } 1769 1770 bool 1771 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1772 SourceLocation Loc, SourceRange Range, 1773 CXXCastPath *BasePath, 1774 bool IgnoreAccess) { 1775 return CheckDerivedToBaseConversion(Derived, Base, 1776 IgnoreAccess ? 0 1777 : diag::err_upcast_to_inaccessible_base, 1778 diag::err_ambiguous_derived_to_base_conv, 1779 Loc, Range, DeclarationName(), 1780 BasePath); 1781 } 1782 1783 1784 /// @brief Builds a string representing ambiguous paths from a 1785 /// specific derived class to different subobjects of the same base 1786 /// class. 1787 /// 1788 /// This function builds a string that can be used in error messages 1789 /// to show the different paths that one can take through the 1790 /// inheritance hierarchy to go from the derived class to different 1791 /// subobjects of a base class. The result looks something like this: 1792 /// @code 1793 /// struct D -> struct B -> struct A 1794 /// struct D -> struct C -> struct A 1795 /// @endcode 1796 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1797 std::string PathDisplayStr; 1798 std::set<unsigned> DisplayedPaths; 1799 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1800 Path != Paths.end(); ++Path) { 1801 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1802 // We haven't displayed a path to this particular base 1803 // class subobject yet. 1804 PathDisplayStr += "\n "; 1805 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1806 for (CXXBasePath::const_iterator Element = Path->begin(); 1807 Element != Path->end(); ++Element) 1808 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1809 } 1810 } 1811 1812 return PathDisplayStr; 1813 } 1814 1815 //===----------------------------------------------------------------------===// 1816 // C++ class member Handling 1817 //===----------------------------------------------------------------------===// 1818 1819 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1820 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1821 SourceLocation ASLoc, 1822 SourceLocation ColonLoc, 1823 AttributeList *Attrs) { 1824 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1825 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1826 ASLoc, ColonLoc); 1827 CurContext->addHiddenDecl(ASDecl); 1828 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1829 } 1830 1831 /// CheckOverrideControl - Check C++11 override control semantics. 1832 void Sema::CheckOverrideControl(NamedDecl *D) { 1833 if (D->isInvalidDecl()) 1834 return; 1835 1836 // We only care about "override" and "final" declarations. 1837 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1838 return; 1839 1840 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1841 1842 // We can't check dependent instance methods. 1843 if (MD && MD->isInstance() && 1844 (MD->getParent()->hasAnyDependentBases() || 1845 MD->getType()->isDependentType())) 1846 return; 1847 1848 if (MD && !MD->isVirtual()) { 1849 // If we have a non-virtual method, check if if hides a virtual method. 1850 // (In that case, it's most likely the method has the wrong type.) 1851 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1852 FindHiddenVirtualMethods(MD, OverloadedMethods); 1853 1854 if (!OverloadedMethods.empty()) { 1855 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1856 Diag(OA->getLocation(), 1857 diag::override_keyword_hides_virtual_member_function) 1858 << "override" << (OverloadedMethods.size() > 1); 1859 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1860 Diag(FA->getLocation(), 1861 diag::override_keyword_hides_virtual_member_function) 1862 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1863 << (OverloadedMethods.size() > 1); 1864 } 1865 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1866 MD->setInvalidDecl(); 1867 return; 1868 } 1869 // Fall through into the general case diagnostic. 1870 // FIXME: We might want to attempt typo correction here. 1871 } 1872 1873 if (!MD || !MD->isVirtual()) { 1874 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1875 Diag(OA->getLocation(), 1876 diag::override_keyword_only_allowed_on_virtual_member_functions) 1877 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1878 D->dropAttr<OverrideAttr>(); 1879 } 1880 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1881 Diag(FA->getLocation(), 1882 diag::override_keyword_only_allowed_on_virtual_member_functions) 1883 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1884 << FixItHint::CreateRemoval(FA->getLocation()); 1885 D->dropAttr<FinalAttr>(); 1886 } 1887 return; 1888 } 1889 1890 // C++11 [class.virtual]p5: 1891 // If a function is marked with the virt-specifier override and 1892 // does not override a member function of a base class, the program is 1893 // ill-formed. 1894 bool HasOverriddenMethods = 1895 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1896 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1897 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1898 << MD->getDeclName(); 1899 } 1900 1901 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 1902 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 1903 return; 1904 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1905 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() || 1906 isa<CXXDestructorDecl>(MD)) 1907 return; 1908 1909 SourceLocation Loc = MD->getLocation(); 1910 SourceLocation SpellingLoc = Loc; 1911 if (getSourceManager().isMacroArgExpansion(Loc)) 1912 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first; 1913 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 1914 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 1915 return; 1916 1917 if (MD->size_overridden_methods() > 0) { 1918 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding) 1919 << MD->getDeclName(); 1920 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 1921 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 1922 } 1923 } 1924 1925 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1926 /// function overrides a virtual member function marked 'final', according to 1927 /// C++11 [class.virtual]p4. 1928 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1929 const CXXMethodDecl *Old) { 1930 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1931 if (!FA) 1932 return false; 1933 1934 Diag(New->getLocation(), diag::err_final_function_overridden) 1935 << New->getDeclName() 1936 << FA->isSpelledAsSealed(); 1937 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1938 return true; 1939 } 1940 1941 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1942 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1943 // FIXME: Destruction of ObjC lifetime types has side-effects. 1944 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1945 return !RD->isCompleteDefinition() || 1946 !RD->hasTrivialDefaultConstructor() || 1947 !RD->hasTrivialDestructor(); 1948 return false; 1949 } 1950 1951 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1952 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 1953 if (it->isDeclspecPropertyAttribute()) 1954 return it; 1955 return nullptr; 1956 } 1957 1958 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1959 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1960 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1961 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1962 /// present (but parsing it has been deferred). 1963 NamedDecl * 1964 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1965 MultiTemplateParamsArg TemplateParameterLists, 1966 Expr *BW, const VirtSpecifiers &VS, 1967 InClassInitStyle InitStyle) { 1968 const DeclSpec &DS = D.getDeclSpec(); 1969 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1970 DeclarationName Name = NameInfo.getName(); 1971 SourceLocation Loc = NameInfo.getLoc(); 1972 1973 // For anonymous bitfields, the location should point to the type. 1974 if (Loc.isInvalid()) 1975 Loc = D.getLocStart(); 1976 1977 Expr *BitWidth = static_cast<Expr*>(BW); 1978 1979 assert(isa<CXXRecordDecl>(CurContext)); 1980 assert(!DS.isFriendSpecified()); 1981 1982 bool isFunc = D.isDeclarationOfFunction(); 1983 1984 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1985 // The Microsoft extension __interface only permits public member functions 1986 // and prohibits constructors, destructors, operators, non-public member 1987 // functions, static methods and data members. 1988 unsigned InvalidDecl; 1989 bool ShowDeclName = true; 1990 if (!isFunc) 1991 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1992 else if (AS != AS_public) 1993 InvalidDecl = 2; 1994 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1995 InvalidDecl = 3; 1996 else switch (Name.getNameKind()) { 1997 case DeclarationName::CXXConstructorName: 1998 InvalidDecl = 4; 1999 ShowDeclName = false; 2000 break; 2001 2002 case DeclarationName::CXXDestructorName: 2003 InvalidDecl = 5; 2004 ShowDeclName = false; 2005 break; 2006 2007 case DeclarationName::CXXOperatorName: 2008 case DeclarationName::CXXConversionFunctionName: 2009 InvalidDecl = 6; 2010 break; 2011 2012 default: 2013 InvalidDecl = 0; 2014 break; 2015 } 2016 2017 if (InvalidDecl) { 2018 if (ShowDeclName) 2019 Diag(Loc, diag::err_invalid_member_in_interface) 2020 << (InvalidDecl-1) << Name; 2021 else 2022 Diag(Loc, diag::err_invalid_member_in_interface) 2023 << (InvalidDecl-1) << ""; 2024 return nullptr; 2025 } 2026 } 2027 2028 // C++ 9.2p6: A member shall not be declared to have automatic storage 2029 // duration (auto, register) or with the extern storage-class-specifier. 2030 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2031 // data members and cannot be applied to names declared const or static, 2032 // and cannot be applied to reference members. 2033 switch (DS.getStorageClassSpec()) { 2034 case DeclSpec::SCS_unspecified: 2035 case DeclSpec::SCS_typedef: 2036 case DeclSpec::SCS_static: 2037 break; 2038 case DeclSpec::SCS_mutable: 2039 if (isFunc) { 2040 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2041 2042 // FIXME: It would be nicer if the keyword was ignored only for this 2043 // declarator. Otherwise we could get follow-up errors. 2044 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2045 } 2046 break; 2047 default: 2048 Diag(DS.getStorageClassSpecLoc(), 2049 diag::err_storageclass_invalid_for_member); 2050 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2051 break; 2052 } 2053 2054 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2055 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2056 !isFunc); 2057 2058 if (DS.isConstexprSpecified() && isInstField) { 2059 SemaDiagnosticBuilder B = 2060 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2061 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2062 if (InitStyle == ICIS_NoInit) { 2063 B << 0 << 0; 2064 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2065 B << FixItHint::CreateRemoval(ConstexprLoc); 2066 else { 2067 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2068 D.getMutableDeclSpec().ClearConstexprSpec(); 2069 const char *PrevSpec; 2070 unsigned DiagID; 2071 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2072 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2073 (void)Failed; 2074 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2075 } 2076 } else { 2077 B << 1; 2078 const char *PrevSpec; 2079 unsigned DiagID; 2080 if (D.getMutableDeclSpec().SetStorageClassSpec( 2081 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2082 Context.getPrintingPolicy())) { 2083 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2084 "This is the only DeclSpec that should fail to be applied"); 2085 B << 1; 2086 } else { 2087 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2088 isInstField = false; 2089 } 2090 } 2091 } 2092 2093 NamedDecl *Member; 2094 if (isInstField) { 2095 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2096 2097 // Data members must have identifiers for names. 2098 if (!Name.isIdentifier()) { 2099 Diag(Loc, diag::err_bad_variable_name) 2100 << Name; 2101 return nullptr; 2102 } 2103 2104 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2105 2106 // Member field could not be with "template" keyword. 2107 // So TemplateParameterLists should be empty in this case. 2108 if (TemplateParameterLists.size()) { 2109 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2110 if (TemplateParams->size()) { 2111 // There is no such thing as a member field template. 2112 Diag(D.getIdentifierLoc(), diag::err_template_member) 2113 << II 2114 << SourceRange(TemplateParams->getTemplateLoc(), 2115 TemplateParams->getRAngleLoc()); 2116 } else { 2117 // There is an extraneous 'template<>' for this member. 2118 Diag(TemplateParams->getTemplateLoc(), 2119 diag::err_template_member_noparams) 2120 << II 2121 << SourceRange(TemplateParams->getTemplateLoc(), 2122 TemplateParams->getRAngleLoc()); 2123 } 2124 return nullptr; 2125 } 2126 2127 if (SS.isSet() && !SS.isInvalid()) { 2128 // The user provided a superfluous scope specifier inside a class 2129 // definition: 2130 // 2131 // class X { 2132 // int X::member; 2133 // }; 2134 if (DeclContext *DC = computeDeclContext(SS, false)) 2135 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2136 else 2137 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2138 << Name << SS.getRange(); 2139 2140 SS.clear(); 2141 } 2142 2143 AttributeList *MSPropertyAttr = 2144 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2145 if (MSPropertyAttr) { 2146 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2147 BitWidth, InitStyle, AS, MSPropertyAttr); 2148 if (!Member) 2149 return nullptr; 2150 isInstField = false; 2151 } else { 2152 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2153 BitWidth, InitStyle, AS); 2154 assert(Member && "HandleField never returns null"); 2155 } 2156 } else { 2157 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2158 2159 Member = HandleDeclarator(S, D, TemplateParameterLists); 2160 if (!Member) 2161 return nullptr; 2162 2163 // Non-instance-fields can't have a bitfield. 2164 if (BitWidth) { 2165 if (Member->isInvalidDecl()) { 2166 // don't emit another diagnostic. 2167 } else if (isa<VarDecl>(Member)) { 2168 // C++ 9.6p3: A bit-field shall not be a static member. 2169 // "static member 'A' cannot be a bit-field" 2170 Diag(Loc, diag::err_static_not_bitfield) 2171 << Name << BitWidth->getSourceRange(); 2172 } else if (isa<TypedefDecl>(Member)) { 2173 // "typedef member 'x' cannot be a bit-field" 2174 Diag(Loc, diag::err_typedef_not_bitfield) 2175 << Name << BitWidth->getSourceRange(); 2176 } else { 2177 // A function typedef ("typedef int f(); f a;"). 2178 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2179 Diag(Loc, diag::err_not_integral_type_bitfield) 2180 << Name << cast<ValueDecl>(Member)->getType() 2181 << BitWidth->getSourceRange(); 2182 } 2183 2184 BitWidth = nullptr; 2185 Member->setInvalidDecl(); 2186 } 2187 2188 Member->setAccess(AS); 2189 2190 // If we have declared a member function template or static data member 2191 // template, set the access of the templated declaration as well. 2192 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2193 FunTmpl->getTemplatedDecl()->setAccess(AS); 2194 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2195 VarTmpl->getTemplatedDecl()->setAccess(AS); 2196 } 2197 2198 if (VS.isOverrideSpecified()) 2199 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2200 if (VS.isFinalSpecified()) 2201 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2202 VS.isFinalSpelledSealed())); 2203 2204 if (VS.getLastLocation().isValid()) { 2205 // Update the end location of a method that has a virt-specifiers. 2206 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2207 MD->setRangeEnd(VS.getLastLocation()); 2208 } 2209 2210 CheckOverrideControl(Member); 2211 2212 assert((Name || isInstField) && "No identifier for non-field ?"); 2213 2214 if (isInstField) { 2215 FieldDecl *FD = cast<FieldDecl>(Member); 2216 FieldCollector->Add(FD); 2217 2218 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 2219 // Remember all explicit private FieldDecls that have a name, no side 2220 // effects and are not part of a dependent type declaration. 2221 if (!FD->isImplicit() && FD->getDeclName() && 2222 FD->getAccess() == AS_private && 2223 !FD->hasAttr<UnusedAttr>() && 2224 !FD->getParent()->isDependentContext() && 2225 !InitializationHasSideEffects(*FD)) 2226 UnusedPrivateFields.insert(FD); 2227 } 2228 } 2229 2230 return Member; 2231 } 2232 2233 namespace { 2234 class UninitializedFieldVisitor 2235 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2236 Sema &S; 2237 // List of Decls to generate a warning on. Also remove Decls that become 2238 // initialized. 2239 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 2240 // List of base classes of the record. Classes are removed after their 2241 // initializers. 2242 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 2243 // Vector of decls to be removed from the Decl set prior to visiting the 2244 // nodes. These Decls may have been initialized in the prior initializer. 2245 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 2246 // If non-null, add a note to the warning pointing back to the constructor. 2247 const CXXConstructorDecl *Constructor; 2248 // Variables to hold state when processing an initializer list. When 2249 // InitList is true, special case initialization of FieldDecls matching 2250 // InitListFieldDecl. 2251 bool InitList; 2252 FieldDecl *InitListFieldDecl; 2253 llvm::SmallVector<unsigned, 4> InitFieldIndex; 2254 2255 public: 2256 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2257 UninitializedFieldVisitor(Sema &S, 2258 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 2259 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 2260 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 2261 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 2262 2263 // Returns true if the use of ME is not an uninitialized use. 2264 bool IsInitListMemberExprInitialized(MemberExpr *ME, 2265 bool CheckReferenceOnly) { 2266 llvm::SmallVector<FieldDecl*, 4> Fields; 2267 bool ReferenceField = false; 2268 while (ME) { 2269 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 2270 if (!FD) 2271 return false; 2272 Fields.push_back(FD); 2273 if (FD->getType()->isReferenceType()) 2274 ReferenceField = true; 2275 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 2276 } 2277 2278 // Binding a reference to an unintialized field is not an 2279 // uninitialized use. 2280 if (CheckReferenceOnly && !ReferenceField) 2281 return true; 2282 2283 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 2284 // Discard the first field since it is the field decl that is being 2285 // initialized. 2286 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 2287 UsedFieldIndex.push_back((*I)->getFieldIndex()); 2288 } 2289 2290 for (auto UsedIter = UsedFieldIndex.begin(), 2291 UsedEnd = UsedFieldIndex.end(), 2292 OrigIter = InitFieldIndex.begin(), 2293 OrigEnd = InitFieldIndex.end(); 2294 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 2295 if (*UsedIter < *OrigIter) 2296 return true; 2297 if (*UsedIter > *OrigIter) 2298 break; 2299 } 2300 2301 return false; 2302 } 2303 2304 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 2305 bool AddressOf) { 2306 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2307 return; 2308 2309 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2310 // or union. 2311 MemberExpr *FieldME = ME; 2312 2313 bool AllPODFields = FieldME->getType().isPODType(S.Context); 2314 2315 Expr *Base = ME; 2316 while (MemberExpr *SubME = 2317 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 2318 2319 if (isa<VarDecl>(SubME->getMemberDecl())) 2320 return; 2321 2322 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 2323 if (!FD->isAnonymousStructOrUnion()) 2324 FieldME = SubME; 2325 2326 if (!FieldME->getType().isPODType(S.Context)) 2327 AllPODFields = false; 2328 2329 Base = SubME->getBase(); 2330 } 2331 2332 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 2333 return; 2334 2335 if (AddressOf && AllPODFields) 2336 return; 2337 2338 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2339 2340 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 2341 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 2342 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 2343 } 2344 2345 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 2346 QualType T = BaseCast->getType(); 2347 if (T->isPointerType() && 2348 BaseClasses.count(T->getPointeeType())) { 2349 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 2350 << T->getPointeeType() << FoundVD; 2351 } 2352 } 2353 } 2354 2355 if (!Decls.count(FoundVD)) 2356 return; 2357 2358 const bool IsReference = FoundVD->getType()->isReferenceType(); 2359 2360 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 2361 // Special checking for initializer lists. 2362 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 2363 return; 2364 } 2365 } else { 2366 // Prevent double warnings on use of unbounded references. 2367 if (CheckReferenceOnly && !IsReference) 2368 return; 2369 } 2370 2371 unsigned diag = IsReference 2372 ? diag::warn_reference_field_is_uninit 2373 : diag::warn_field_is_uninit; 2374 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2375 if (Constructor) 2376 S.Diag(Constructor->getLocation(), 2377 diag::note_uninit_in_this_constructor) 2378 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2379 2380 } 2381 2382 void HandleValue(Expr *E, bool AddressOf) { 2383 E = E->IgnoreParens(); 2384 2385 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2386 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 2387 AddressOf /*AddressOf*/); 2388 return; 2389 } 2390 2391 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2392 Visit(CO->getCond()); 2393 HandleValue(CO->getTrueExpr(), AddressOf); 2394 HandleValue(CO->getFalseExpr(), AddressOf); 2395 return; 2396 } 2397 2398 if (BinaryConditionalOperator *BCO = 2399 dyn_cast<BinaryConditionalOperator>(E)) { 2400 Visit(BCO->getCond()); 2401 HandleValue(BCO->getFalseExpr(), AddressOf); 2402 return; 2403 } 2404 2405 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 2406 HandleValue(OVE->getSourceExpr(), AddressOf); 2407 return; 2408 } 2409 2410 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2411 switch (BO->getOpcode()) { 2412 default: 2413 break; 2414 case(BO_PtrMemD): 2415 case(BO_PtrMemI): 2416 HandleValue(BO->getLHS(), AddressOf); 2417 Visit(BO->getRHS()); 2418 return; 2419 case(BO_Comma): 2420 Visit(BO->getLHS()); 2421 HandleValue(BO->getRHS(), AddressOf); 2422 return; 2423 } 2424 } 2425 2426 Visit(E); 2427 } 2428 2429 void CheckInitListExpr(InitListExpr *ILE) { 2430 InitFieldIndex.push_back(0); 2431 for (auto Child : ILE->children()) { 2432 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 2433 CheckInitListExpr(SubList); 2434 } else { 2435 Visit(Child); 2436 } 2437 ++InitFieldIndex.back(); 2438 } 2439 InitFieldIndex.pop_back(); 2440 } 2441 2442 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 2443 FieldDecl *Field, const Type *BaseClass) { 2444 // Remove Decls that may have been initialized in the previous 2445 // initializer. 2446 for (ValueDecl* VD : DeclsToRemove) 2447 Decls.erase(VD); 2448 DeclsToRemove.clear(); 2449 2450 Constructor = FieldConstructor; 2451 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 2452 2453 if (ILE && Field) { 2454 InitList = true; 2455 InitListFieldDecl = Field; 2456 InitFieldIndex.clear(); 2457 CheckInitListExpr(ILE); 2458 } else { 2459 InitList = false; 2460 Visit(E); 2461 } 2462 2463 if (Field) 2464 Decls.erase(Field); 2465 if (BaseClass) 2466 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 2467 } 2468 2469 void VisitMemberExpr(MemberExpr *ME) { 2470 // All uses of unbounded reference fields will warn. 2471 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 2472 } 2473 2474 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2475 if (E->getCastKind() == CK_LValueToRValue) { 2476 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2477 return; 2478 } 2479 2480 Inherited::VisitImplicitCastExpr(E); 2481 } 2482 2483 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2484 if (E->getConstructor()->isCopyConstructor()) { 2485 Expr *ArgExpr = E->getArg(0); 2486 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 2487 if (ILE->getNumInits() == 1) 2488 ArgExpr = ILE->getInit(0); 2489 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 2490 if (ICE->getCastKind() == CK_NoOp) 2491 ArgExpr = ICE->getSubExpr(); 2492 HandleValue(ArgExpr, false /*AddressOf*/); 2493 return; 2494 } 2495 Inherited::VisitCXXConstructExpr(E); 2496 } 2497 2498 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2499 Expr *Callee = E->getCallee(); 2500 if (isa<MemberExpr>(Callee)) { 2501 HandleValue(Callee, false /*AddressOf*/); 2502 for (auto Arg : E->arguments()) 2503 Visit(Arg); 2504 return; 2505 } 2506 2507 Inherited::VisitCXXMemberCallExpr(E); 2508 } 2509 2510 void VisitCallExpr(CallExpr *E) { 2511 // Treat std::move as a use. 2512 if (E->getNumArgs() == 1) { 2513 if (FunctionDecl *FD = E->getDirectCallee()) { 2514 if (FD->isInStdNamespace() && FD->getIdentifier() && 2515 FD->getIdentifier()->isStr("move")) { 2516 HandleValue(E->getArg(0), false /*AddressOf*/); 2517 return; 2518 } 2519 } 2520 } 2521 2522 Inherited::VisitCallExpr(E); 2523 } 2524 2525 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 2526 Expr *Callee = E->getCallee(); 2527 2528 if (isa<UnresolvedLookupExpr>(Callee)) 2529 return Inherited::VisitCXXOperatorCallExpr(E); 2530 2531 Visit(Callee); 2532 for (auto Arg : E->arguments()) 2533 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 2534 } 2535 2536 void VisitBinaryOperator(BinaryOperator *E) { 2537 // If a field assignment is detected, remove the field from the 2538 // uninitiailized field set. 2539 if (E->getOpcode() == BO_Assign) 2540 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2541 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2542 if (!FD->getType()->isReferenceType()) 2543 DeclsToRemove.push_back(FD); 2544 2545 if (E->isCompoundAssignmentOp()) { 2546 HandleValue(E->getLHS(), false /*AddressOf*/); 2547 Visit(E->getRHS()); 2548 return; 2549 } 2550 2551 Inherited::VisitBinaryOperator(E); 2552 } 2553 2554 void VisitUnaryOperator(UnaryOperator *E) { 2555 if (E->isIncrementDecrementOp()) { 2556 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2557 return; 2558 } 2559 if (E->getOpcode() == UO_AddrOf) { 2560 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 2561 HandleValue(ME->getBase(), true /*AddressOf*/); 2562 return; 2563 } 2564 } 2565 2566 Inherited::VisitUnaryOperator(E); 2567 } 2568 }; 2569 2570 // Diagnose value-uses of fields to initialize themselves, e.g. 2571 // foo(foo) 2572 // where foo is not also a parameter to the constructor. 2573 // Also diagnose across field uninitialized use such as 2574 // x(y), y(x) 2575 // TODO: implement -Wuninitialized and fold this into that framework. 2576 static void DiagnoseUninitializedFields( 2577 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2578 2579 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 2580 Constructor->getLocation())) { 2581 return; 2582 } 2583 2584 if (Constructor->isInvalidDecl()) 2585 return; 2586 2587 const CXXRecordDecl *RD = Constructor->getParent(); 2588 2589 if (RD->getDescribedClassTemplate()) 2590 return; 2591 2592 // Holds fields that are uninitialized. 2593 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2594 2595 // At the beginning, all fields are uninitialized. 2596 for (auto *I : RD->decls()) { 2597 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2598 UninitializedFields.insert(FD); 2599 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2600 UninitializedFields.insert(IFD->getAnonField()); 2601 } 2602 } 2603 2604 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 2605 for (auto I : RD->bases()) 2606 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 2607 2608 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2609 return; 2610 2611 UninitializedFieldVisitor UninitializedChecker(SemaRef, 2612 UninitializedFields, 2613 UninitializedBaseClasses); 2614 2615 for (const auto *FieldInit : Constructor->inits()) { 2616 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 2617 break; 2618 2619 Expr *InitExpr = FieldInit->getInit(); 2620 if (!InitExpr) 2621 continue; 2622 2623 if (CXXDefaultInitExpr *Default = 2624 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 2625 InitExpr = Default->getExpr(); 2626 if (!InitExpr) 2627 continue; 2628 // In class initializers will point to the constructor. 2629 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 2630 FieldInit->getAnyMember(), 2631 FieldInit->getBaseClass()); 2632 } else { 2633 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 2634 FieldInit->getAnyMember(), 2635 FieldInit->getBaseClass()); 2636 } 2637 } 2638 } 2639 } // namespace 2640 2641 /// \brief Enter a new C++ default initializer scope. After calling this, the 2642 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2643 /// parsing or instantiating the initializer failed. 2644 void Sema::ActOnStartCXXInClassMemberInitializer() { 2645 // Create a synthetic function scope to represent the call to the constructor 2646 // that notionally surrounds a use of this initializer. 2647 PushFunctionScope(); 2648 } 2649 2650 /// \brief This is invoked after parsing an in-class initializer for a 2651 /// non-static C++ class member, and after instantiating an in-class initializer 2652 /// in a class template. Such actions are deferred until the class is complete. 2653 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2654 SourceLocation InitLoc, 2655 Expr *InitExpr) { 2656 // Pop the notional constructor scope we created earlier. 2657 PopFunctionScopeInfo(nullptr, D); 2658 2659 FieldDecl *FD = cast<FieldDecl>(D); 2660 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2661 "must set init style when field is created"); 2662 2663 if (!InitExpr) { 2664 FD->setInvalidDecl(); 2665 FD->removeInClassInitializer(); 2666 return; 2667 } 2668 2669 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2670 FD->setInvalidDecl(); 2671 FD->removeInClassInitializer(); 2672 return; 2673 } 2674 2675 ExprResult Init = InitExpr; 2676 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2677 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2678 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2679 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2680 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2681 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2682 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2683 if (Init.isInvalid()) { 2684 FD->setInvalidDecl(); 2685 return; 2686 } 2687 } 2688 2689 // C++11 [class.base.init]p7: 2690 // The initialization of each base and member constitutes a 2691 // full-expression. 2692 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 2693 if (Init.isInvalid()) { 2694 FD->setInvalidDecl(); 2695 return; 2696 } 2697 2698 InitExpr = Init.get(); 2699 2700 FD->setInClassInitializer(InitExpr); 2701 } 2702 2703 /// \brief Find the direct and/or virtual base specifiers that 2704 /// correspond to the given base type, for use in base initialization 2705 /// within a constructor. 2706 static bool FindBaseInitializer(Sema &SemaRef, 2707 CXXRecordDecl *ClassDecl, 2708 QualType BaseType, 2709 const CXXBaseSpecifier *&DirectBaseSpec, 2710 const CXXBaseSpecifier *&VirtualBaseSpec) { 2711 // First, check for a direct base class. 2712 DirectBaseSpec = nullptr; 2713 for (const auto &Base : ClassDecl->bases()) { 2714 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2715 // We found a direct base of this type. That's what we're 2716 // initializing. 2717 DirectBaseSpec = &Base; 2718 break; 2719 } 2720 } 2721 2722 // Check for a virtual base class. 2723 // FIXME: We might be able to short-circuit this if we know in advance that 2724 // there are no virtual bases. 2725 VirtualBaseSpec = nullptr; 2726 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2727 // We haven't found a base yet; search the class hierarchy for a 2728 // virtual base class. 2729 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2730 /*DetectVirtual=*/false); 2731 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2732 BaseType, Paths)) { 2733 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2734 Path != Paths.end(); ++Path) { 2735 if (Path->back().Base->isVirtual()) { 2736 VirtualBaseSpec = Path->back().Base; 2737 break; 2738 } 2739 } 2740 } 2741 } 2742 2743 return DirectBaseSpec || VirtualBaseSpec; 2744 } 2745 2746 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2747 MemInitResult 2748 Sema::ActOnMemInitializer(Decl *ConstructorD, 2749 Scope *S, 2750 CXXScopeSpec &SS, 2751 IdentifierInfo *MemberOrBase, 2752 ParsedType TemplateTypeTy, 2753 const DeclSpec &DS, 2754 SourceLocation IdLoc, 2755 Expr *InitList, 2756 SourceLocation EllipsisLoc) { 2757 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2758 DS, IdLoc, InitList, 2759 EllipsisLoc); 2760 } 2761 2762 /// \brief Handle a C++ member initializer using parentheses syntax. 2763 MemInitResult 2764 Sema::ActOnMemInitializer(Decl *ConstructorD, 2765 Scope *S, 2766 CXXScopeSpec &SS, 2767 IdentifierInfo *MemberOrBase, 2768 ParsedType TemplateTypeTy, 2769 const DeclSpec &DS, 2770 SourceLocation IdLoc, 2771 SourceLocation LParenLoc, 2772 ArrayRef<Expr *> Args, 2773 SourceLocation RParenLoc, 2774 SourceLocation EllipsisLoc) { 2775 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2776 Args, RParenLoc); 2777 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2778 DS, IdLoc, List, EllipsisLoc); 2779 } 2780 2781 namespace { 2782 2783 // Callback to only accept typo corrections that can be a valid C++ member 2784 // intializer: either a non-static field member or a base class. 2785 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2786 public: 2787 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2788 : ClassDecl(ClassDecl) {} 2789 2790 bool ValidateCandidate(const TypoCorrection &candidate) override { 2791 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2792 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2793 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2794 return isa<TypeDecl>(ND); 2795 } 2796 return false; 2797 } 2798 2799 private: 2800 CXXRecordDecl *ClassDecl; 2801 }; 2802 2803 } 2804 2805 /// \brief Handle a C++ member initializer. 2806 MemInitResult 2807 Sema::BuildMemInitializer(Decl *ConstructorD, 2808 Scope *S, 2809 CXXScopeSpec &SS, 2810 IdentifierInfo *MemberOrBase, 2811 ParsedType TemplateTypeTy, 2812 const DeclSpec &DS, 2813 SourceLocation IdLoc, 2814 Expr *Init, 2815 SourceLocation EllipsisLoc) { 2816 if (!ConstructorD) 2817 return true; 2818 2819 AdjustDeclIfTemplate(ConstructorD); 2820 2821 CXXConstructorDecl *Constructor 2822 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2823 if (!Constructor) { 2824 // The user wrote a constructor initializer on a function that is 2825 // not a C++ constructor. Ignore the error for now, because we may 2826 // have more member initializers coming; we'll diagnose it just 2827 // once in ActOnMemInitializers. 2828 return true; 2829 } 2830 2831 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2832 2833 // C++ [class.base.init]p2: 2834 // Names in a mem-initializer-id are looked up in the scope of the 2835 // constructor's class and, if not found in that scope, are looked 2836 // up in the scope containing the constructor's definition. 2837 // [Note: if the constructor's class contains a member with the 2838 // same name as a direct or virtual base class of the class, a 2839 // mem-initializer-id naming the member or base class and composed 2840 // of a single identifier refers to the class member. A 2841 // mem-initializer-id for the hidden base class may be specified 2842 // using a qualified name. ] 2843 if (!SS.getScopeRep() && !TemplateTypeTy) { 2844 // Look for a member, first. 2845 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 2846 if (!Result.empty()) { 2847 ValueDecl *Member; 2848 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2849 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2850 if (EllipsisLoc.isValid()) 2851 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2852 << MemberOrBase 2853 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2854 2855 return BuildMemberInitializer(Member, Init, IdLoc); 2856 } 2857 } 2858 } 2859 // It didn't name a member, so see if it names a class. 2860 QualType BaseType; 2861 TypeSourceInfo *TInfo = nullptr; 2862 2863 if (TemplateTypeTy) { 2864 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2865 } else if (DS.getTypeSpecType() == TST_decltype) { 2866 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2867 } else { 2868 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2869 LookupParsedName(R, S, &SS); 2870 2871 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2872 if (!TyD) { 2873 if (R.isAmbiguous()) return true; 2874 2875 // We don't want access-control diagnostics here. 2876 R.suppressDiagnostics(); 2877 2878 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2879 bool NotUnknownSpecialization = false; 2880 DeclContext *DC = computeDeclContext(SS, false); 2881 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2882 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2883 2884 if (!NotUnknownSpecialization) { 2885 // When the scope specifier can refer to a member of an unknown 2886 // specialization, we take it as a type name. 2887 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2888 SS.getWithLocInContext(Context), 2889 *MemberOrBase, IdLoc); 2890 if (BaseType.isNull()) 2891 return true; 2892 2893 R.clear(); 2894 R.setLookupName(MemberOrBase); 2895 } 2896 } 2897 2898 // If no results were found, try to correct typos. 2899 TypoCorrection Corr; 2900 if (R.empty() && BaseType.isNull() && 2901 (Corr = CorrectTypo( 2902 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2903 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl), 2904 CTK_ErrorRecovery, ClassDecl))) { 2905 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2906 // We have found a non-static data member with a similar 2907 // name to what was typed; complain and initialize that 2908 // member. 2909 diagnoseTypo(Corr, 2910 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2911 << MemberOrBase << true); 2912 return BuildMemberInitializer(Member, Init, IdLoc); 2913 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2914 const CXXBaseSpecifier *DirectBaseSpec; 2915 const CXXBaseSpecifier *VirtualBaseSpec; 2916 if (FindBaseInitializer(*this, ClassDecl, 2917 Context.getTypeDeclType(Type), 2918 DirectBaseSpec, VirtualBaseSpec)) { 2919 // We have found a direct or virtual base class with a 2920 // similar name to what was typed; complain and initialize 2921 // that base class. 2922 diagnoseTypo(Corr, 2923 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2924 << MemberOrBase << false, 2925 PDiag() /*Suppress note, we provide our own.*/); 2926 2927 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2928 : VirtualBaseSpec; 2929 Diag(BaseSpec->getLocStart(), 2930 diag::note_base_class_specified_here) 2931 << BaseSpec->getType() 2932 << BaseSpec->getSourceRange(); 2933 2934 TyD = Type; 2935 } 2936 } 2937 } 2938 2939 if (!TyD && BaseType.isNull()) { 2940 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2941 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2942 return true; 2943 } 2944 } 2945 2946 if (BaseType.isNull()) { 2947 BaseType = Context.getTypeDeclType(TyD); 2948 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 2949 if (SS.isSet()) 2950 // FIXME: preserve source range information 2951 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 2952 BaseType); 2953 } 2954 } 2955 2956 if (!TInfo) 2957 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2958 2959 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2960 } 2961 2962 /// Checks a member initializer expression for cases where reference (or 2963 /// pointer) members are bound to by-value parameters (or their addresses). 2964 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2965 Expr *Init, 2966 SourceLocation IdLoc) { 2967 QualType MemberTy = Member->getType(); 2968 2969 // We only handle pointers and references currently. 2970 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2971 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2972 return; 2973 2974 const bool IsPointer = MemberTy->isPointerType(); 2975 if (IsPointer) { 2976 if (const UnaryOperator *Op 2977 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2978 // The only case we're worried about with pointers requires taking the 2979 // address. 2980 if (Op->getOpcode() != UO_AddrOf) 2981 return; 2982 2983 Init = Op->getSubExpr(); 2984 } else { 2985 // We only handle address-of expression initializers for pointers. 2986 return; 2987 } 2988 } 2989 2990 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2991 // We only warn when referring to a non-reference parameter declaration. 2992 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2993 if (!Parameter || Parameter->getType()->isReferenceType()) 2994 return; 2995 2996 S.Diag(Init->getExprLoc(), 2997 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2998 : diag::warn_bind_ref_member_to_parameter) 2999 << Member << Parameter << Init->getSourceRange(); 3000 } else { 3001 // Other initializers are fine. 3002 return; 3003 } 3004 3005 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 3006 << (unsigned)IsPointer; 3007 } 3008 3009 MemInitResult 3010 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 3011 SourceLocation IdLoc) { 3012 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 3013 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 3014 assert((DirectMember || IndirectMember) && 3015 "Member must be a FieldDecl or IndirectFieldDecl"); 3016 3017 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3018 return true; 3019 3020 if (Member->isInvalidDecl()) 3021 return true; 3022 3023 MultiExprArg Args; 3024 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3025 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3026 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 3027 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 3028 } else { 3029 // Template instantiation doesn't reconstruct ParenListExprs for us. 3030 Args = Init; 3031 } 3032 3033 SourceRange InitRange = Init->getSourceRange(); 3034 3035 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 3036 // Can't check initialization for a member of dependent type or when 3037 // any of the arguments are type-dependent expressions. 3038 DiscardCleanupsInEvaluationContext(); 3039 } else { 3040 bool InitList = false; 3041 if (isa<InitListExpr>(Init)) { 3042 InitList = true; 3043 Args = Init; 3044 } 3045 3046 // Initialize the member. 3047 InitializedEntity MemberEntity = 3048 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 3049 : InitializedEntity::InitializeMember(IndirectMember, 3050 nullptr); 3051 InitializationKind Kind = 3052 InitList ? InitializationKind::CreateDirectList(IdLoc) 3053 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 3054 InitRange.getEnd()); 3055 3056 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 3057 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 3058 nullptr); 3059 if (MemberInit.isInvalid()) 3060 return true; 3061 3062 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 3063 3064 // C++11 [class.base.init]p7: 3065 // The initialization of each base and member constitutes a 3066 // full-expression. 3067 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 3068 if (MemberInit.isInvalid()) 3069 return true; 3070 3071 Init = MemberInit.get(); 3072 } 3073 3074 if (DirectMember) { 3075 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 3076 InitRange.getBegin(), Init, 3077 InitRange.getEnd()); 3078 } else { 3079 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 3080 InitRange.getBegin(), Init, 3081 InitRange.getEnd()); 3082 } 3083 } 3084 3085 MemInitResult 3086 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 3087 CXXRecordDecl *ClassDecl) { 3088 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3089 if (!LangOpts.CPlusPlus11) 3090 return Diag(NameLoc, diag::err_delegating_ctor) 3091 << TInfo->getTypeLoc().getLocalSourceRange(); 3092 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 3093 3094 bool InitList = true; 3095 MultiExprArg Args = Init; 3096 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3097 InitList = false; 3098 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3099 } 3100 3101 SourceRange InitRange = Init->getSourceRange(); 3102 // Initialize the object. 3103 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 3104 QualType(ClassDecl->getTypeForDecl(), 0)); 3105 InitializationKind Kind = 3106 InitList ? InitializationKind::CreateDirectList(NameLoc) 3107 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 3108 InitRange.getEnd()); 3109 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 3110 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 3111 Args, nullptr); 3112 if (DelegationInit.isInvalid()) 3113 return true; 3114 3115 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 3116 "Delegating constructor with no target?"); 3117 3118 // C++11 [class.base.init]p7: 3119 // The initialization of each base and member constitutes a 3120 // full-expression. 3121 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 3122 InitRange.getBegin()); 3123 if (DelegationInit.isInvalid()) 3124 return true; 3125 3126 // If we are in a dependent context, template instantiation will 3127 // perform this type-checking again. Just save the arguments that we 3128 // received in a ParenListExpr. 3129 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3130 // of the information that we have about the base 3131 // initializer. However, deconstructing the ASTs is a dicey process, 3132 // and this approach is far more likely to get the corner cases right. 3133 if (CurContext->isDependentContext()) 3134 DelegationInit = Init; 3135 3136 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 3137 DelegationInit.getAs<Expr>(), 3138 InitRange.getEnd()); 3139 } 3140 3141 MemInitResult 3142 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 3143 Expr *Init, CXXRecordDecl *ClassDecl, 3144 SourceLocation EllipsisLoc) { 3145 SourceLocation BaseLoc 3146 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 3147 3148 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 3149 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 3150 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3151 3152 // C++ [class.base.init]p2: 3153 // [...] Unless the mem-initializer-id names a nonstatic data 3154 // member of the constructor's class or a direct or virtual base 3155 // of that class, the mem-initializer is ill-formed. A 3156 // mem-initializer-list can initialize a base class using any 3157 // name that denotes that base class type. 3158 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 3159 3160 SourceRange InitRange = Init->getSourceRange(); 3161 if (EllipsisLoc.isValid()) { 3162 // This is a pack expansion. 3163 if (!BaseType->containsUnexpandedParameterPack()) { 3164 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 3165 << SourceRange(BaseLoc, InitRange.getEnd()); 3166 3167 EllipsisLoc = SourceLocation(); 3168 } 3169 } else { 3170 // Check for any unexpanded parameter packs. 3171 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 3172 return true; 3173 3174 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3175 return true; 3176 } 3177 3178 // Check for direct and virtual base classes. 3179 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 3180 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 3181 if (!Dependent) { 3182 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 3183 BaseType)) 3184 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 3185 3186 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 3187 VirtualBaseSpec); 3188 3189 // C++ [base.class.init]p2: 3190 // Unless the mem-initializer-id names a nonstatic data member of the 3191 // constructor's class or a direct or virtual base of that class, the 3192 // mem-initializer is ill-formed. 3193 if (!DirectBaseSpec && !VirtualBaseSpec) { 3194 // If the class has any dependent bases, then it's possible that 3195 // one of those types will resolve to the same type as 3196 // BaseType. Therefore, just treat this as a dependent base 3197 // class initialization. FIXME: Should we try to check the 3198 // initialization anyway? It seems odd. 3199 if (ClassDecl->hasAnyDependentBases()) 3200 Dependent = true; 3201 else 3202 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 3203 << BaseType << Context.getTypeDeclType(ClassDecl) 3204 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3205 } 3206 } 3207 3208 if (Dependent) { 3209 DiscardCleanupsInEvaluationContext(); 3210 3211 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3212 /*IsVirtual=*/false, 3213 InitRange.getBegin(), Init, 3214 InitRange.getEnd(), EllipsisLoc); 3215 } 3216 3217 // C++ [base.class.init]p2: 3218 // If a mem-initializer-id is ambiguous because it designates both 3219 // a direct non-virtual base class and an inherited virtual base 3220 // class, the mem-initializer is ill-formed. 3221 if (DirectBaseSpec && VirtualBaseSpec) 3222 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 3223 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3224 3225 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 3226 if (!BaseSpec) 3227 BaseSpec = VirtualBaseSpec; 3228 3229 // Initialize the base. 3230 bool InitList = true; 3231 MultiExprArg Args = Init; 3232 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3233 InitList = false; 3234 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3235 } 3236 3237 InitializedEntity BaseEntity = 3238 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 3239 InitializationKind Kind = 3240 InitList ? InitializationKind::CreateDirectList(BaseLoc) 3241 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 3242 InitRange.getEnd()); 3243 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 3244 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 3245 if (BaseInit.isInvalid()) 3246 return true; 3247 3248 // C++11 [class.base.init]p7: 3249 // The initialization of each base and member constitutes a 3250 // full-expression. 3251 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 3252 if (BaseInit.isInvalid()) 3253 return true; 3254 3255 // If we are in a dependent context, template instantiation will 3256 // perform this type-checking again. Just save the arguments that we 3257 // received in a ParenListExpr. 3258 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3259 // of the information that we have about the base 3260 // initializer. However, deconstructing the ASTs is a dicey process, 3261 // and this approach is far more likely to get the corner cases right. 3262 if (CurContext->isDependentContext()) 3263 BaseInit = Init; 3264 3265 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3266 BaseSpec->isVirtual(), 3267 InitRange.getBegin(), 3268 BaseInit.getAs<Expr>(), 3269 InitRange.getEnd(), EllipsisLoc); 3270 } 3271 3272 // Create a static_cast\<T&&>(expr). 3273 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 3274 if (T.isNull()) T = E->getType(); 3275 QualType TargetType = SemaRef.BuildReferenceType( 3276 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 3277 SourceLocation ExprLoc = E->getLocStart(); 3278 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 3279 TargetType, ExprLoc); 3280 3281 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 3282 SourceRange(ExprLoc, ExprLoc), 3283 E->getSourceRange()).get(); 3284 } 3285 3286 /// ImplicitInitializerKind - How an implicit base or member initializer should 3287 /// initialize its base or member. 3288 enum ImplicitInitializerKind { 3289 IIK_Default, 3290 IIK_Copy, 3291 IIK_Move, 3292 IIK_Inherit 3293 }; 3294 3295 static bool 3296 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3297 ImplicitInitializerKind ImplicitInitKind, 3298 CXXBaseSpecifier *BaseSpec, 3299 bool IsInheritedVirtualBase, 3300 CXXCtorInitializer *&CXXBaseInit) { 3301 InitializedEntity InitEntity 3302 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3303 IsInheritedVirtualBase); 3304 3305 ExprResult BaseInit; 3306 3307 switch (ImplicitInitKind) { 3308 case IIK_Inherit: { 3309 const CXXRecordDecl *Inherited = 3310 Constructor->getInheritedConstructor()->getParent(); 3311 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3312 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3313 // C++11 [class.inhctor]p8: 3314 // Each expression in the expression-list is of the form 3315 // static_cast<T&&>(p), where p is the name of the corresponding 3316 // constructor parameter and T is the declared type of p. 3317 SmallVector<Expr*, 16> Args; 3318 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3319 ParmVarDecl *PD = Constructor->getParamDecl(I); 3320 ExprResult ArgExpr = 3321 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3322 VK_LValue, SourceLocation()); 3323 if (ArgExpr.isInvalid()) 3324 return true; 3325 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType())); 3326 } 3327 3328 InitializationKind InitKind = InitializationKind::CreateDirect( 3329 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3330 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3331 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3332 break; 3333 } 3334 } 3335 // Fall through. 3336 case IIK_Default: { 3337 InitializationKind InitKind 3338 = InitializationKind::CreateDefault(Constructor->getLocation()); 3339 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3340 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3341 break; 3342 } 3343 3344 case IIK_Move: 3345 case IIK_Copy: { 3346 bool Moving = ImplicitInitKind == IIK_Move; 3347 ParmVarDecl *Param = Constructor->getParamDecl(0); 3348 QualType ParamType = Param->getType().getNonReferenceType(); 3349 3350 Expr *CopyCtorArg = 3351 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3352 SourceLocation(), Param, false, 3353 Constructor->getLocation(), ParamType, 3354 VK_LValue, nullptr); 3355 3356 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3357 3358 // Cast to the base class to avoid ambiguities. 3359 QualType ArgTy = 3360 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3361 ParamType.getQualifiers()); 3362 3363 if (Moving) { 3364 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3365 } 3366 3367 CXXCastPath BasePath; 3368 BasePath.push_back(BaseSpec); 3369 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3370 CK_UncheckedDerivedToBase, 3371 Moving ? VK_XValue : VK_LValue, 3372 &BasePath).get(); 3373 3374 InitializationKind InitKind 3375 = InitializationKind::CreateDirect(Constructor->getLocation(), 3376 SourceLocation(), SourceLocation()); 3377 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3378 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3379 break; 3380 } 3381 } 3382 3383 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3384 if (BaseInit.isInvalid()) 3385 return true; 3386 3387 CXXBaseInit = 3388 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3389 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3390 SourceLocation()), 3391 BaseSpec->isVirtual(), 3392 SourceLocation(), 3393 BaseInit.getAs<Expr>(), 3394 SourceLocation(), 3395 SourceLocation()); 3396 3397 return false; 3398 } 3399 3400 static bool RefersToRValueRef(Expr *MemRef) { 3401 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3402 return Referenced->getType()->isRValueReferenceType(); 3403 } 3404 3405 static bool 3406 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3407 ImplicitInitializerKind ImplicitInitKind, 3408 FieldDecl *Field, IndirectFieldDecl *Indirect, 3409 CXXCtorInitializer *&CXXMemberInit) { 3410 if (Field->isInvalidDecl()) 3411 return true; 3412 3413 SourceLocation Loc = Constructor->getLocation(); 3414 3415 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3416 bool Moving = ImplicitInitKind == IIK_Move; 3417 ParmVarDecl *Param = Constructor->getParamDecl(0); 3418 QualType ParamType = Param->getType().getNonReferenceType(); 3419 3420 // Suppress copying zero-width bitfields. 3421 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3422 return false; 3423 3424 Expr *MemberExprBase = 3425 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3426 SourceLocation(), Param, false, 3427 Loc, ParamType, VK_LValue, nullptr); 3428 3429 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3430 3431 if (Moving) { 3432 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3433 } 3434 3435 // Build a reference to this field within the parameter. 3436 CXXScopeSpec SS; 3437 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3438 Sema::LookupMemberName); 3439 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3440 : cast<ValueDecl>(Field), AS_public); 3441 MemberLookup.resolveKind(); 3442 ExprResult CtorArg 3443 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3444 ParamType, Loc, 3445 /*IsArrow=*/false, 3446 SS, 3447 /*TemplateKWLoc=*/SourceLocation(), 3448 /*FirstQualifierInScope=*/nullptr, 3449 MemberLookup, 3450 /*TemplateArgs=*/nullptr); 3451 if (CtorArg.isInvalid()) 3452 return true; 3453 3454 // C++11 [class.copy]p15: 3455 // - if a member m has rvalue reference type T&&, it is direct-initialized 3456 // with static_cast<T&&>(x.m); 3457 if (RefersToRValueRef(CtorArg.get())) { 3458 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3459 } 3460 3461 // When the field we are copying is an array, create index variables for 3462 // each dimension of the array. We use these index variables to subscript 3463 // the source array, and other clients (e.g., CodeGen) will perform the 3464 // necessary iteration with these index variables. 3465 SmallVector<VarDecl *, 4> IndexVariables; 3466 QualType BaseType = Field->getType(); 3467 QualType SizeType = SemaRef.Context.getSizeType(); 3468 bool InitializingArray = false; 3469 while (const ConstantArrayType *Array 3470 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3471 InitializingArray = true; 3472 // Create the iteration variable for this array index. 3473 IdentifierInfo *IterationVarName = nullptr; 3474 { 3475 SmallString<8> Str; 3476 llvm::raw_svector_ostream OS(Str); 3477 OS << "__i" << IndexVariables.size(); 3478 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3479 } 3480 VarDecl *IterationVar 3481 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3482 IterationVarName, SizeType, 3483 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3484 SC_None); 3485 IndexVariables.push_back(IterationVar); 3486 3487 // Create a reference to the iteration variable. 3488 ExprResult IterationVarRef 3489 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3490 assert(!IterationVarRef.isInvalid() && 3491 "Reference to invented variable cannot fail!"); 3492 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 3493 assert(!IterationVarRef.isInvalid() && 3494 "Conversion of invented variable cannot fail!"); 3495 3496 // Subscript the array with this iteration variable. 3497 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 3498 IterationVarRef.get(), 3499 Loc); 3500 if (CtorArg.isInvalid()) 3501 return true; 3502 3503 BaseType = Array->getElementType(); 3504 } 3505 3506 // The array subscript expression is an lvalue, which is wrong for moving. 3507 if (Moving && InitializingArray) 3508 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3509 3510 // Construct the entity that we will be initializing. For an array, this 3511 // will be first element in the array, which may require several levels 3512 // of array-subscript entities. 3513 SmallVector<InitializedEntity, 4> Entities; 3514 Entities.reserve(1 + IndexVariables.size()); 3515 if (Indirect) 3516 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3517 else 3518 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3519 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3520 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3521 0, 3522 Entities.back())); 3523 3524 // Direct-initialize to use the copy constructor. 3525 InitializationKind InitKind = 3526 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3527 3528 Expr *CtorArgE = CtorArg.getAs<Expr>(); 3529 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3530 3531 ExprResult MemberInit 3532 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3533 MultiExprArg(&CtorArgE, 1)); 3534 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3535 if (MemberInit.isInvalid()) 3536 return true; 3537 3538 if (Indirect) { 3539 assert(IndexVariables.size() == 0 && 3540 "Indirect field improperly initialized"); 3541 CXXMemberInit 3542 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3543 Loc, Loc, 3544 MemberInit.getAs<Expr>(), 3545 Loc); 3546 } else 3547 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3548 Loc, MemberInit.getAs<Expr>(), 3549 Loc, 3550 IndexVariables.data(), 3551 IndexVariables.size()); 3552 return false; 3553 } 3554 3555 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3556 "Unhandled implicit init kind!"); 3557 3558 QualType FieldBaseElementType = 3559 SemaRef.Context.getBaseElementType(Field->getType()); 3560 3561 if (FieldBaseElementType->isRecordType()) { 3562 InitializedEntity InitEntity 3563 = Indirect? InitializedEntity::InitializeMember(Indirect) 3564 : InitializedEntity::InitializeMember(Field); 3565 InitializationKind InitKind = 3566 InitializationKind::CreateDefault(Loc); 3567 3568 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3569 ExprResult MemberInit = 3570 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3571 3572 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3573 if (MemberInit.isInvalid()) 3574 return true; 3575 3576 if (Indirect) 3577 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3578 Indirect, Loc, 3579 Loc, 3580 MemberInit.get(), 3581 Loc); 3582 else 3583 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3584 Field, Loc, Loc, 3585 MemberInit.get(), 3586 Loc); 3587 return false; 3588 } 3589 3590 if (!Field->getParent()->isUnion()) { 3591 if (FieldBaseElementType->isReferenceType()) { 3592 SemaRef.Diag(Constructor->getLocation(), 3593 diag::err_uninitialized_member_in_ctor) 3594 << (int)Constructor->isImplicit() 3595 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3596 << 0 << Field->getDeclName(); 3597 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3598 return true; 3599 } 3600 3601 if (FieldBaseElementType.isConstQualified()) { 3602 SemaRef.Diag(Constructor->getLocation(), 3603 diag::err_uninitialized_member_in_ctor) 3604 << (int)Constructor->isImplicit() 3605 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3606 << 1 << Field->getDeclName(); 3607 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3608 return true; 3609 } 3610 } 3611 3612 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3613 FieldBaseElementType->isObjCRetainableType() && 3614 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3615 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3616 // ARC: 3617 // Default-initialize Objective-C pointers to NULL. 3618 CXXMemberInit 3619 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3620 Loc, Loc, 3621 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3622 Loc); 3623 return false; 3624 } 3625 3626 // Nothing to initialize. 3627 CXXMemberInit = nullptr; 3628 return false; 3629 } 3630 3631 namespace { 3632 struct BaseAndFieldInfo { 3633 Sema &S; 3634 CXXConstructorDecl *Ctor; 3635 bool AnyErrorsInInits; 3636 ImplicitInitializerKind IIK; 3637 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3638 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3639 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3640 3641 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3642 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3643 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3644 if (Generated && Ctor->isCopyConstructor()) 3645 IIK = IIK_Copy; 3646 else if (Generated && Ctor->isMoveConstructor()) 3647 IIK = IIK_Move; 3648 else if (Ctor->getInheritedConstructor()) 3649 IIK = IIK_Inherit; 3650 else 3651 IIK = IIK_Default; 3652 } 3653 3654 bool isImplicitCopyOrMove() const { 3655 switch (IIK) { 3656 case IIK_Copy: 3657 case IIK_Move: 3658 return true; 3659 3660 case IIK_Default: 3661 case IIK_Inherit: 3662 return false; 3663 } 3664 3665 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3666 } 3667 3668 bool addFieldInitializer(CXXCtorInitializer *Init) { 3669 AllToInit.push_back(Init); 3670 3671 // Check whether this initializer makes the field "used". 3672 if (Init->getInit()->HasSideEffects(S.Context)) 3673 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3674 3675 return false; 3676 } 3677 3678 bool isInactiveUnionMember(FieldDecl *Field) { 3679 RecordDecl *Record = Field->getParent(); 3680 if (!Record->isUnion()) 3681 return false; 3682 3683 if (FieldDecl *Active = 3684 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3685 return Active != Field->getCanonicalDecl(); 3686 3687 // In an implicit copy or move constructor, ignore any in-class initializer. 3688 if (isImplicitCopyOrMove()) 3689 return true; 3690 3691 // If there's no explicit initialization, the field is active only if it 3692 // has an in-class initializer... 3693 if (Field->hasInClassInitializer()) 3694 return false; 3695 // ... or it's an anonymous struct or union whose class has an in-class 3696 // initializer. 3697 if (!Field->isAnonymousStructOrUnion()) 3698 return true; 3699 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3700 return !FieldRD->hasInClassInitializer(); 3701 } 3702 3703 /// \brief Determine whether the given field is, or is within, a union member 3704 /// that is inactive (because there was an initializer given for a different 3705 /// member of the union, or because the union was not initialized at all). 3706 bool isWithinInactiveUnionMember(FieldDecl *Field, 3707 IndirectFieldDecl *Indirect) { 3708 if (!Indirect) 3709 return isInactiveUnionMember(Field); 3710 3711 for (auto *C : Indirect->chain()) { 3712 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3713 if (Field && isInactiveUnionMember(Field)) 3714 return true; 3715 } 3716 return false; 3717 } 3718 }; 3719 } 3720 3721 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3722 /// array type. 3723 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3724 if (T->isIncompleteArrayType()) 3725 return true; 3726 3727 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3728 if (!ArrayT->getSize()) 3729 return true; 3730 3731 T = ArrayT->getElementType(); 3732 } 3733 3734 return false; 3735 } 3736 3737 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3738 FieldDecl *Field, 3739 IndirectFieldDecl *Indirect = nullptr) { 3740 if (Field->isInvalidDecl()) 3741 return false; 3742 3743 // Overwhelmingly common case: we have a direct initializer for this field. 3744 if (CXXCtorInitializer *Init = 3745 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3746 return Info.addFieldInitializer(Init); 3747 3748 // C++11 [class.base.init]p8: 3749 // if the entity is a non-static data member that has a 3750 // brace-or-equal-initializer and either 3751 // -- the constructor's class is a union and no other variant member of that 3752 // union is designated by a mem-initializer-id or 3753 // -- the constructor's class is not a union, and, if the entity is a member 3754 // of an anonymous union, no other member of that union is designated by 3755 // a mem-initializer-id, 3756 // the entity is initialized as specified in [dcl.init]. 3757 // 3758 // We also apply the same rules to handle anonymous structs within anonymous 3759 // unions. 3760 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3761 return false; 3762 3763 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3764 ExprResult DIE = 3765 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 3766 if (DIE.isInvalid()) 3767 return true; 3768 CXXCtorInitializer *Init; 3769 if (Indirect) 3770 Init = new (SemaRef.Context) 3771 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 3772 SourceLocation(), DIE.get(), SourceLocation()); 3773 else 3774 Init = new (SemaRef.Context) 3775 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 3776 SourceLocation(), DIE.get(), SourceLocation()); 3777 return Info.addFieldInitializer(Init); 3778 } 3779 3780 // Don't initialize incomplete or zero-length arrays. 3781 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3782 return false; 3783 3784 // Don't try to build an implicit initializer if there were semantic 3785 // errors in any of the initializers (and therefore we might be 3786 // missing some that the user actually wrote). 3787 if (Info.AnyErrorsInInits) 3788 return false; 3789 3790 CXXCtorInitializer *Init = nullptr; 3791 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3792 Indirect, Init)) 3793 return true; 3794 3795 if (!Init) 3796 return false; 3797 3798 return Info.addFieldInitializer(Init); 3799 } 3800 3801 bool 3802 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3803 CXXCtorInitializer *Initializer) { 3804 assert(Initializer->isDelegatingInitializer()); 3805 Constructor->setNumCtorInitializers(1); 3806 CXXCtorInitializer **initializer = 3807 new (Context) CXXCtorInitializer*[1]; 3808 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3809 Constructor->setCtorInitializers(initializer); 3810 3811 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3812 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3813 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3814 } 3815 3816 DelegatingCtorDecls.push_back(Constructor); 3817 3818 DiagnoseUninitializedFields(*this, Constructor); 3819 3820 return false; 3821 } 3822 3823 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3824 ArrayRef<CXXCtorInitializer *> Initializers) { 3825 if (Constructor->isDependentContext()) { 3826 // Just store the initializers as written, they will be checked during 3827 // instantiation. 3828 if (!Initializers.empty()) { 3829 Constructor->setNumCtorInitializers(Initializers.size()); 3830 CXXCtorInitializer **baseOrMemberInitializers = 3831 new (Context) CXXCtorInitializer*[Initializers.size()]; 3832 memcpy(baseOrMemberInitializers, Initializers.data(), 3833 Initializers.size() * sizeof(CXXCtorInitializer*)); 3834 Constructor->setCtorInitializers(baseOrMemberInitializers); 3835 } 3836 3837 // Let template instantiation know whether we had errors. 3838 if (AnyErrors) 3839 Constructor->setInvalidDecl(); 3840 3841 return false; 3842 } 3843 3844 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3845 3846 // We need to build the initializer AST according to order of construction 3847 // and not what user specified in the Initializers list. 3848 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3849 if (!ClassDecl) 3850 return true; 3851 3852 bool HadError = false; 3853 3854 for (unsigned i = 0; i < Initializers.size(); i++) { 3855 CXXCtorInitializer *Member = Initializers[i]; 3856 3857 if (Member->isBaseInitializer()) 3858 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3859 else { 3860 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3861 3862 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3863 for (auto *C : F->chain()) { 3864 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3865 if (FD && FD->getParent()->isUnion()) 3866 Info.ActiveUnionMember.insert(std::make_pair( 3867 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3868 } 3869 } else if (FieldDecl *FD = Member->getMember()) { 3870 if (FD->getParent()->isUnion()) 3871 Info.ActiveUnionMember.insert(std::make_pair( 3872 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3873 } 3874 } 3875 } 3876 3877 // Keep track of the direct virtual bases. 3878 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3879 for (auto &I : ClassDecl->bases()) { 3880 if (I.isVirtual()) 3881 DirectVBases.insert(&I); 3882 } 3883 3884 // Push virtual bases before others. 3885 for (auto &VBase : ClassDecl->vbases()) { 3886 if (CXXCtorInitializer *Value 3887 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3888 // [class.base.init]p7, per DR257: 3889 // A mem-initializer where the mem-initializer-id names a virtual base 3890 // class is ignored during execution of a constructor of any class that 3891 // is not the most derived class. 3892 if (ClassDecl->isAbstract()) { 3893 // FIXME: Provide a fixit to remove the base specifier. This requires 3894 // tracking the location of the associated comma for a base specifier. 3895 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3896 << VBase.getType() << ClassDecl; 3897 DiagnoseAbstractType(ClassDecl); 3898 } 3899 3900 Info.AllToInit.push_back(Value); 3901 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3902 // [class.base.init]p8, per DR257: 3903 // If a given [...] base class is not named by a mem-initializer-id 3904 // [...] and the entity is not a virtual base class of an abstract 3905 // class, then [...] the entity is default-initialized. 3906 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3907 CXXCtorInitializer *CXXBaseInit; 3908 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3909 &VBase, IsInheritedVirtualBase, 3910 CXXBaseInit)) { 3911 HadError = true; 3912 continue; 3913 } 3914 3915 Info.AllToInit.push_back(CXXBaseInit); 3916 } 3917 } 3918 3919 // Non-virtual bases. 3920 for (auto &Base : ClassDecl->bases()) { 3921 // Virtuals are in the virtual base list and already constructed. 3922 if (Base.isVirtual()) 3923 continue; 3924 3925 if (CXXCtorInitializer *Value 3926 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3927 Info.AllToInit.push_back(Value); 3928 } else if (!AnyErrors) { 3929 CXXCtorInitializer *CXXBaseInit; 3930 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3931 &Base, /*IsInheritedVirtualBase=*/false, 3932 CXXBaseInit)) { 3933 HadError = true; 3934 continue; 3935 } 3936 3937 Info.AllToInit.push_back(CXXBaseInit); 3938 } 3939 } 3940 3941 // Fields. 3942 for (auto *Mem : ClassDecl->decls()) { 3943 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 3944 // C++ [class.bit]p2: 3945 // A declaration for a bit-field that omits the identifier declares an 3946 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3947 // initialized. 3948 if (F->isUnnamedBitfield()) 3949 continue; 3950 3951 // If we're not generating the implicit copy/move constructor, then we'll 3952 // handle anonymous struct/union fields based on their individual 3953 // indirect fields. 3954 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3955 continue; 3956 3957 if (CollectFieldInitializer(*this, Info, F)) 3958 HadError = true; 3959 continue; 3960 } 3961 3962 // Beyond this point, we only consider default initialization. 3963 if (Info.isImplicitCopyOrMove()) 3964 continue; 3965 3966 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 3967 if (F->getType()->isIncompleteArrayType()) { 3968 assert(ClassDecl->hasFlexibleArrayMember() && 3969 "Incomplete array type is not valid"); 3970 continue; 3971 } 3972 3973 // Initialize each field of an anonymous struct individually. 3974 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3975 HadError = true; 3976 3977 continue; 3978 } 3979 } 3980 3981 unsigned NumInitializers = Info.AllToInit.size(); 3982 if (NumInitializers > 0) { 3983 Constructor->setNumCtorInitializers(NumInitializers); 3984 CXXCtorInitializer **baseOrMemberInitializers = 3985 new (Context) CXXCtorInitializer*[NumInitializers]; 3986 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3987 NumInitializers * sizeof(CXXCtorInitializer*)); 3988 Constructor->setCtorInitializers(baseOrMemberInitializers); 3989 3990 // Constructors implicitly reference the base and member 3991 // destructors. 3992 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3993 Constructor->getParent()); 3994 } 3995 3996 return HadError; 3997 } 3998 3999 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 4000 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 4001 const RecordDecl *RD = RT->getDecl(); 4002 if (RD->isAnonymousStructOrUnion()) { 4003 for (auto *Field : RD->fields()) 4004 PopulateKeysForFields(Field, IdealInits); 4005 return; 4006 } 4007 } 4008 IdealInits.push_back(Field->getCanonicalDecl()); 4009 } 4010 4011 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 4012 return Context.getCanonicalType(BaseType).getTypePtr(); 4013 } 4014 4015 static const void *GetKeyForMember(ASTContext &Context, 4016 CXXCtorInitializer *Member) { 4017 if (!Member->isAnyMemberInitializer()) 4018 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 4019 4020 return Member->getAnyMember()->getCanonicalDecl(); 4021 } 4022 4023 static void DiagnoseBaseOrMemInitializerOrder( 4024 Sema &SemaRef, const CXXConstructorDecl *Constructor, 4025 ArrayRef<CXXCtorInitializer *> Inits) { 4026 if (Constructor->getDeclContext()->isDependentContext()) 4027 return; 4028 4029 // Don't check initializers order unless the warning is enabled at the 4030 // location of at least one initializer. 4031 bool ShouldCheckOrder = false; 4032 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4033 CXXCtorInitializer *Init = Inits[InitIndex]; 4034 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 4035 Init->getSourceLocation())) { 4036 ShouldCheckOrder = true; 4037 break; 4038 } 4039 } 4040 if (!ShouldCheckOrder) 4041 return; 4042 4043 // Build the list of bases and members in the order that they'll 4044 // actually be initialized. The explicit initializers should be in 4045 // this same order but may be missing things. 4046 SmallVector<const void*, 32> IdealInitKeys; 4047 4048 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 4049 4050 // 1. Virtual bases. 4051 for (const auto &VBase : ClassDecl->vbases()) 4052 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 4053 4054 // 2. Non-virtual bases. 4055 for (const auto &Base : ClassDecl->bases()) { 4056 if (Base.isVirtual()) 4057 continue; 4058 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 4059 } 4060 4061 // 3. Direct fields. 4062 for (auto *Field : ClassDecl->fields()) { 4063 if (Field->isUnnamedBitfield()) 4064 continue; 4065 4066 PopulateKeysForFields(Field, IdealInitKeys); 4067 } 4068 4069 unsigned NumIdealInits = IdealInitKeys.size(); 4070 unsigned IdealIndex = 0; 4071 4072 CXXCtorInitializer *PrevInit = nullptr; 4073 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 4074 CXXCtorInitializer *Init = Inits[InitIndex]; 4075 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 4076 4077 // Scan forward to try to find this initializer in the idealized 4078 // initializers list. 4079 for (; IdealIndex != NumIdealInits; ++IdealIndex) 4080 if (InitKey == IdealInitKeys[IdealIndex]) 4081 break; 4082 4083 // If we didn't find this initializer, it must be because we 4084 // scanned past it on a previous iteration. That can only 4085 // happen if we're out of order; emit a warning. 4086 if (IdealIndex == NumIdealInits && PrevInit) { 4087 Sema::SemaDiagnosticBuilder D = 4088 SemaRef.Diag(PrevInit->getSourceLocation(), 4089 diag::warn_initializer_out_of_order); 4090 4091 if (PrevInit->isAnyMemberInitializer()) 4092 D << 0 << PrevInit->getAnyMember()->getDeclName(); 4093 else 4094 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 4095 4096 if (Init->isAnyMemberInitializer()) 4097 D << 0 << Init->getAnyMember()->getDeclName(); 4098 else 4099 D << 1 << Init->getTypeSourceInfo()->getType(); 4100 4101 // Move back to the initializer's location in the ideal list. 4102 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 4103 if (InitKey == IdealInitKeys[IdealIndex]) 4104 break; 4105 4106 assert(IdealIndex != NumIdealInits && 4107 "initializer not found in initializer list"); 4108 } 4109 4110 PrevInit = Init; 4111 } 4112 } 4113 4114 namespace { 4115 bool CheckRedundantInit(Sema &S, 4116 CXXCtorInitializer *Init, 4117 CXXCtorInitializer *&PrevInit) { 4118 if (!PrevInit) { 4119 PrevInit = Init; 4120 return false; 4121 } 4122 4123 if (FieldDecl *Field = Init->getAnyMember()) 4124 S.Diag(Init->getSourceLocation(), 4125 diag::err_multiple_mem_initialization) 4126 << Field->getDeclName() 4127 << Init->getSourceRange(); 4128 else { 4129 const Type *BaseClass = Init->getBaseClass(); 4130 assert(BaseClass && "neither field nor base"); 4131 S.Diag(Init->getSourceLocation(), 4132 diag::err_multiple_base_initialization) 4133 << QualType(BaseClass, 0) 4134 << Init->getSourceRange(); 4135 } 4136 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 4137 << 0 << PrevInit->getSourceRange(); 4138 4139 return true; 4140 } 4141 4142 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 4143 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 4144 4145 bool CheckRedundantUnionInit(Sema &S, 4146 CXXCtorInitializer *Init, 4147 RedundantUnionMap &Unions) { 4148 FieldDecl *Field = Init->getAnyMember(); 4149 RecordDecl *Parent = Field->getParent(); 4150 NamedDecl *Child = Field; 4151 4152 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4153 if (Parent->isUnion()) { 4154 UnionEntry &En = Unions[Parent]; 4155 if (En.first && En.first != Child) { 4156 S.Diag(Init->getSourceLocation(), 4157 diag::err_multiple_mem_union_initialization) 4158 << Field->getDeclName() 4159 << Init->getSourceRange(); 4160 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4161 << 0 << En.second->getSourceRange(); 4162 return true; 4163 } 4164 if (!En.first) { 4165 En.first = Child; 4166 En.second = Init; 4167 } 4168 if (!Parent->isAnonymousStructOrUnion()) 4169 return false; 4170 } 4171 4172 Child = Parent; 4173 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4174 } 4175 4176 return false; 4177 } 4178 } 4179 4180 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4181 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4182 SourceLocation ColonLoc, 4183 ArrayRef<CXXCtorInitializer*> MemInits, 4184 bool AnyErrors) { 4185 if (!ConstructorDecl) 4186 return; 4187 4188 AdjustDeclIfTemplate(ConstructorDecl); 4189 4190 CXXConstructorDecl *Constructor 4191 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 4192 4193 if (!Constructor) { 4194 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 4195 return; 4196 } 4197 4198 // Mapping for the duplicate initializers check. 4199 // For member initializers, this is keyed with a FieldDecl*. 4200 // For base initializers, this is keyed with a Type*. 4201 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 4202 4203 // Mapping for the inconsistent anonymous-union initializers check. 4204 RedundantUnionMap MemberUnions; 4205 4206 bool HadError = false; 4207 for (unsigned i = 0; i < MemInits.size(); i++) { 4208 CXXCtorInitializer *Init = MemInits[i]; 4209 4210 // Set the source order index. 4211 Init->setSourceOrder(i); 4212 4213 if (Init->isAnyMemberInitializer()) { 4214 const void *Key = GetKeyForMember(Context, Init); 4215 if (CheckRedundantInit(*this, Init, Members[Key]) || 4216 CheckRedundantUnionInit(*this, Init, MemberUnions)) 4217 HadError = true; 4218 } else if (Init->isBaseInitializer()) { 4219 const void *Key = GetKeyForMember(Context, Init); 4220 if (CheckRedundantInit(*this, Init, Members[Key])) 4221 HadError = true; 4222 } else { 4223 assert(Init->isDelegatingInitializer()); 4224 // This must be the only initializer 4225 if (MemInits.size() != 1) { 4226 Diag(Init->getSourceLocation(), 4227 diag::err_delegating_initializer_alone) 4228 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 4229 // We will treat this as being the only initializer. 4230 } 4231 SetDelegatingInitializer(Constructor, MemInits[i]); 4232 // Return immediately as the initializer is set. 4233 return; 4234 } 4235 } 4236 4237 if (HadError) 4238 return; 4239 4240 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 4241 4242 SetCtorInitializers(Constructor, AnyErrors, MemInits); 4243 4244 DiagnoseUninitializedFields(*this, Constructor); 4245 } 4246 4247 void 4248 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 4249 CXXRecordDecl *ClassDecl) { 4250 // Ignore dependent contexts. Also ignore unions, since their members never 4251 // have destructors implicitly called. 4252 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 4253 return; 4254 4255 // FIXME: all the access-control diagnostics are positioned on the 4256 // field/base declaration. That's probably good; that said, the 4257 // user might reasonably want to know why the destructor is being 4258 // emitted, and we currently don't say. 4259 4260 // Non-static data members. 4261 for (auto *Field : ClassDecl->fields()) { 4262 if (Field->isInvalidDecl()) 4263 continue; 4264 4265 // Don't destroy incomplete or zero-length arrays. 4266 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 4267 continue; 4268 4269 QualType FieldType = Context.getBaseElementType(Field->getType()); 4270 4271 const RecordType* RT = FieldType->getAs<RecordType>(); 4272 if (!RT) 4273 continue; 4274 4275 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4276 if (FieldClassDecl->isInvalidDecl()) 4277 continue; 4278 if (FieldClassDecl->hasIrrelevantDestructor()) 4279 continue; 4280 // The destructor for an implicit anonymous union member is never invoked. 4281 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 4282 continue; 4283 4284 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 4285 assert(Dtor && "No dtor found for FieldClassDecl!"); 4286 CheckDestructorAccess(Field->getLocation(), Dtor, 4287 PDiag(diag::err_access_dtor_field) 4288 << Field->getDeclName() 4289 << FieldType); 4290 4291 MarkFunctionReferenced(Location, Dtor); 4292 DiagnoseUseOfDecl(Dtor, Location); 4293 } 4294 4295 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 4296 4297 // Bases. 4298 for (const auto &Base : ClassDecl->bases()) { 4299 // Bases are always records in a well-formed non-dependent class. 4300 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4301 4302 // Remember direct virtual bases. 4303 if (Base.isVirtual()) 4304 DirectVirtualBases.insert(RT); 4305 4306 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4307 // If our base class is invalid, we probably can't get its dtor anyway. 4308 if (BaseClassDecl->isInvalidDecl()) 4309 continue; 4310 if (BaseClassDecl->hasIrrelevantDestructor()) 4311 continue; 4312 4313 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4314 assert(Dtor && "No dtor found for BaseClassDecl!"); 4315 4316 // FIXME: caret should be on the start of the class name 4317 CheckDestructorAccess(Base.getLocStart(), Dtor, 4318 PDiag(diag::err_access_dtor_base) 4319 << Base.getType() 4320 << Base.getSourceRange(), 4321 Context.getTypeDeclType(ClassDecl)); 4322 4323 MarkFunctionReferenced(Location, Dtor); 4324 DiagnoseUseOfDecl(Dtor, Location); 4325 } 4326 4327 // Virtual bases. 4328 for (const auto &VBase : ClassDecl->vbases()) { 4329 // Bases are always records in a well-formed non-dependent class. 4330 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4331 4332 // Ignore direct virtual bases. 4333 if (DirectVirtualBases.count(RT)) 4334 continue; 4335 4336 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4337 // If our base class is invalid, we probably can't get its dtor anyway. 4338 if (BaseClassDecl->isInvalidDecl()) 4339 continue; 4340 if (BaseClassDecl->hasIrrelevantDestructor()) 4341 continue; 4342 4343 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4344 assert(Dtor && "No dtor found for BaseClassDecl!"); 4345 if (CheckDestructorAccess( 4346 ClassDecl->getLocation(), Dtor, 4347 PDiag(diag::err_access_dtor_vbase) 4348 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4349 Context.getTypeDeclType(ClassDecl)) == 4350 AR_accessible) { 4351 CheckDerivedToBaseConversion( 4352 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4353 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4354 SourceRange(), DeclarationName(), nullptr); 4355 } 4356 4357 MarkFunctionReferenced(Location, Dtor); 4358 DiagnoseUseOfDecl(Dtor, Location); 4359 } 4360 } 4361 4362 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4363 if (!CDtorDecl) 4364 return; 4365 4366 if (CXXConstructorDecl *Constructor 4367 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4368 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4369 DiagnoseUninitializedFields(*this, Constructor); 4370 } 4371 } 4372 4373 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4374 unsigned DiagID, AbstractDiagSelID SelID) { 4375 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4376 unsigned DiagID; 4377 AbstractDiagSelID SelID; 4378 4379 public: 4380 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4381 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4382 4383 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4384 if (Suppressed) return; 4385 if (SelID == -1) 4386 S.Diag(Loc, DiagID) << T; 4387 else 4388 S.Diag(Loc, DiagID) << SelID << T; 4389 } 4390 } Diagnoser(DiagID, SelID); 4391 4392 return RequireNonAbstractType(Loc, T, Diagnoser); 4393 } 4394 4395 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4396 TypeDiagnoser &Diagnoser) { 4397 if (!getLangOpts().CPlusPlus) 4398 return false; 4399 4400 if (const ArrayType *AT = Context.getAsArrayType(T)) 4401 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4402 4403 if (const PointerType *PT = T->getAs<PointerType>()) { 4404 // Find the innermost pointer type. 4405 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4406 PT = T; 4407 4408 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4409 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4410 } 4411 4412 const RecordType *RT = T->getAs<RecordType>(); 4413 if (!RT) 4414 return false; 4415 4416 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4417 4418 // We can't answer whether something is abstract until it has a 4419 // definition. If it's currently being defined, we'll walk back 4420 // over all the declarations when we have a full definition. 4421 const CXXRecordDecl *Def = RD->getDefinition(); 4422 if (!Def || Def->isBeingDefined()) 4423 return false; 4424 4425 if (!RD->isAbstract()) 4426 return false; 4427 4428 Diagnoser.diagnose(*this, Loc, T); 4429 DiagnoseAbstractType(RD); 4430 4431 return true; 4432 } 4433 4434 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4435 // Check if we've already emitted the list of pure virtual functions 4436 // for this class. 4437 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4438 return; 4439 4440 // If the diagnostic is suppressed, don't emit the notes. We're only 4441 // going to emit them once, so try to attach them to a diagnostic we're 4442 // actually going to show. 4443 if (Diags.isLastDiagnosticIgnored()) 4444 return; 4445 4446 CXXFinalOverriderMap FinalOverriders; 4447 RD->getFinalOverriders(FinalOverriders); 4448 4449 // Keep a set of seen pure methods so we won't diagnose the same method 4450 // more than once. 4451 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4452 4453 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4454 MEnd = FinalOverriders.end(); 4455 M != MEnd; 4456 ++M) { 4457 for (OverridingMethods::iterator SO = M->second.begin(), 4458 SOEnd = M->second.end(); 4459 SO != SOEnd; ++SO) { 4460 // C++ [class.abstract]p4: 4461 // A class is abstract if it contains or inherits at least one 4462 // pure virtual function for which the final overrider is pure 4463 // virtual. 4464 4465 // 4466 if (SO->second.size() != 1) 4467 continue; 4468 4469 if (!SO->second.front().Method->isPure()) 4470 continue; 4471 4472 if (!SeenPureMethods.insert(SO->second.front().Method).second) 4473 continue; 4474 4475 Diag(SO->second.front().Method->getLocation(), 4476 diag::note_pure_virtual_function) 4477 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4478 } 4479 } 4480 4481 if (!PureVirtualClassDiagSet) 4482 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4483 PureVirtualClassDiagSet->insert(RD); 4484 } 4485 4486 namespace { 4487 struct AbstractUsageInfo { 4488 Sema &S; 4489 CXXRecordDecl *Record; 4490 CanQualType AbstractType; 4491 bool Invalid; 4492 4493 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4494 : S(S), Record(Record), 4495 AbstractType(S.Context.getCanonicalType( 4496 S.Context.getTypeDeclType(Record))), 4497 Invalid(false) {} 4498 4499 void DiagnoseAbstractType() { 4500 if (Invalid) return; 4501 S.DiagnoseAbstractType(Record); 4502 Invalid = true; 4503 } 4504 4505 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4506 }; 4507 4508 struct CheckAbstractUsage { 4509 AbstractUsageInfo &Info; 4510 const NamedDecl *Ctx; 4511 4512 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4513 : Info(Info), Ctx(Ctx) {} 4514 4515 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4516 switch (TL.getTypeLocClass()) { 4517 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4518 #define TYPELOC(CLASS, PARENT) \ 4519 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4520 #include "clang/AST/TypeLocNodes.def" 4521 } 4522 } 4523 4524 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4525 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4526 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4527 if (!TL.getParam(I)) 4528 continue; 4529 4530 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4531 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4532 } 4533 } 4534 4535 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4536 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4537 } 4538 4539 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4540 // Visit the type parameters from a permissive context. 4541 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4542 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4543 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4544 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4545 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4546 // TODO: other template argument types? 4547 } 4548 } 4549 4550 // Visit pointee types from a permissive context. 4551 #define CheckPolymorphic(Type) \ 4552 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4553 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4554 } 4555 CheckPolymorphic(PointerTypeLoc) 4556 CheckPolymorphic(ReferenceTypeLoc) 4557 CheckPolymorphic(MemberPointerTypeLoc) 4558 CheckPolymorphic(BlockPointerTypeLoc) 4559 CheckPolymorphic(AtomicTypeLoc) 4560 4561 /// Handle all the types we haven't given a more specific 4562 /// implementation for above. 4563 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4564 // Every other kind of type that we haven't called out already 4565 // that has an inner type is either (1) sugar or (2) contains that 4566 // inner type in some way as a subobject. 4567 if (TypeLoc Next = TL.getNextTypeLoc()) 4568 return Visit(Next, Sel); 4569 4570 // If there's no inner type and we're in a permissive context, 4571 // don't diagnose. 4572 if (Sel == Sema::AbstractNone) return; 4573 4574 // Check whether the type matches the abstract type. 4575 QualType T = TL.getType(); 4576 if (T->isArrayType()) { 4577 Sel = Sema::AbstractArrayType; 4578 T = Info.S.Context.getBaseElementType(T); 4579 } 4580 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4581 if (CT != Info.AbstractType) return; 4582 4583 // It matched; do some magic. 4584 if (Sel == Sema::AbstractArrayType) { 4585 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4586 << T << TL.getSourceRange(); 4587 } else { 4588 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4589 << Sel << T << TL.getSourceRange(); 4590 } 4591 Info.DiagnoseAbstractType(); 4592 } 4593 }; 4594 4595 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4596 Sema::AbstractDiagSelID Sel) { 4597 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4598 } 4599 4600 } 4601 4602 /// Check for invalid uses of an abstract type in a method declaration. 4603 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4604 CXXMethodDecl *MD) { 4605 // No need to do the check on definitions, which require that 4606 // the return/param types be complete. 4607 if (MD->doesThisDeclarationHaveABody()) 4608 return; 4609 4610 // For safety's sake, just ignore it if we don't have type source 4611 // information. This should never happen for non-implicit methods, 4612 // but... 4613 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4614 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4615 } 4616 4617 /// Check for invalid uses of an abstract type within a class definition. 4618 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4619 CXXRecordDecl *RD) { 4620 for (auto *D : RD->decls()) { 4621 if (D->isImplicit()) continue; 4622 4623 // Methods and method templates. 4624 if (isa<CXXMethodDecl>(D)) { 4625 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4626 } else if (isa<FunctionTemplateDecl>(D)) { 4627 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4628 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4629 4630 // Fields and static variables. 4631 } else if (isa<FieldDecl>(D)) { 4632 FieldDecl *FD = cast<FieldDecl>(D); 4633 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4634 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4635 } else if (isa<VarDecl>(D)) { 4636 VarDecl *VD = cast<VarDecl>(D); 4637 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4638 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4639 4640 // Nested classes and class templates. 4641 } else if (isa<CXXRecordDecl>(D)) { 4642 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4643 } else if (isa<ClassTemplateDecl>(D)) { 4644 CheckAbstractClassUsage(Info, 4645 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4646 } 4647 } 4648 } 4649 4650 /// \brief Check class-level dllimport/dllexport attribute. 4651 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) { 4652 Attr *ClassAttr = getDLLAttr(Class); 4653 4654 // MSVC inherits DLL attributes to partial class template specializations. 4655 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 4656 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 4657 if (Attr *TemplateAttr = 4658 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 4659 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext())); 4660 A->setInherited(true); 4661 ClassAttr = A; 4662 } 4663 } 4664 } 4665 4666 if (!ClassAttr) 4667 return; 4668 4669 if (!Class->isExternallyVisible()) { 4670 S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 4671 << Class << ClassAttr; 4672 return; 4673 } 4674 4675 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 4676 !ClassAttr->isInherited()) { 4677 // Diagnose dll attributes on members of class with dll attribute. 4678 for (Decl *Member : Class->decls()) { 4679 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 4680 continue; 4681 InheritableAttr *MemberAttr = getDLLAttr(Member); 4682 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 4683 continue; 4684 4685 S.Diag(MemberAttr->getLocation(), 4686 diag::err_attribute_dll_member_of_dll_class) 4687 << MemberAttr << ClassAttr; 4688 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 4689 Member->setInvalidDecl(); 4690 } 4691 } 4692 4693 if (Class->getDescribedClassTemplate()) 4694 // Don't inherit dll attribute until the template is instantiated. 4695 return; 4696 4697 // The class is either imported or exported. 4698 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 4699 const bool ClassImported = !ClassExported; 4700 4701 // Force declaration of implicit members so they can inherit the attribute. 4702 S.ForceDeclarationOfImplicitMembers(Class); 4703 4704 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 4705 // seem to be true in practice? 4706 4707 TemplateSpecializationKind TSK = 4708 Class->getTemplateSpecializationKind(); 4709 4710 for (Decl *Member : Class->decls()) { 4711 VarDecl *VD = dyn_cast<VarDecl>(Member); 4712 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 4713 4714 // Only methods and static fields inherit the attributes. 4715 if (!VD && !MD) 4716 continue; 4717 4718 if (MD) { 4719 // Don't process deleted methods. 4720 if (MD->isDeleted()) 4721 continue; 4722 4723 if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) { 4724 // Current MSVC versions don't export the move assignment operators, so 4725 // don't attempt to import them if we have a definition. 4726 continue; 4727 } 4728 4729 if (MD->isInlined() && ClassImported && 4730 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4731 // MinGW does not import inline functions. 4732 continue; 4733 } 4734 } 4735 4736 if (!getDLLAttr(Member)) { 4737 auto *NewAttr = 4738 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 4739 NewAttr->setInherited(true); 4740 Member->addAttr(NewAttr); 4741 } 4742 4743 if (MD && ClassExported) { 4744 if (MD->isUserProvided()) { 4745 // Instantiate non-default methods.. 4746 4747 // .. except for certain kinds of template specializations. 4748 if (TSK == TSK_ExplicitInstantiationDeclaration) 4749 continue; 4750 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 4751 continue; 4752 4753 S.MarkFunctionReferenced(Class->getLocation(), MD); 4754 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 4755 MD->isCopyAssignmentOperator() || 4756 MD->isMoveAssignmentOperator()) { 4757 // Instantiate non-trivial or explicitly defaulted methods, and the 4758 // copy assignment / move assignment operators. 4759 S.MarkFunctionReferenced(Class->getLocation(), MD); 4760 // Resolve its exception specification; CodeGen needs it. 4761 auto *FPT = MD->getType()->getAs<FunctionProtoType>(); 4762 S.ResolveExceptionSpec(Class->getLocation(), FPT); 4763 S.ActOnFinishInlineMethodDef(MD); 4764 } 4765 } 4766 } 4767 } 4768 4769 /// \brief Perform semantic checks on a class definition that has been 4770 /// completing, introducing implicitly-declared members, checking for 4771 /// abstract types, etc. 4772 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4773 if (!Record) 4774 return; 4775 4776 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4777 AbstractUsageInfo Info(*this, Record); 4778 CheckAbstractClassUsage(Info, Record); 4779 } 4780 4781 // If this is not an aggregate type and has no user-declared constructor, 4782 // complain about any non-static data members of reference or const scalar 4783 // type, since they will never get initializers. 4784 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4785 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4786 !Record->isLambda()) { 4787 bool Complained = false; 4788 for (const auto *F : Record->fields()) { 4789 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4790 continue; 4791 4792 if (F->getType()->isReferenceType() || 4793 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4794 if (!Complained) { 4795 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4796 << Record->getTagKind() << Record; 4797 Complained = true; 4798 } 4799 4800 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4801 << F->getType()->isReferenceType() 4802 << F->getDeclName(); 4803 } 4804 } 4805 } 4806 4807 if (Record->isDynamicClass() && !Record->isDependentType()) 4808 DynamicClasses.push_back(Record); 4809 4810 if (Record->getIdentifier()) { 4811 // C++ [class.mem]p13: 4812 // If T is the name of a class, then each of the following shall have a 4813 // name different from T: 4814 // - every member of every anonymous union that is a member of class T. 4815 // 4816 // C++ [class.mem]p14: 4817 // In addition, if class T has a user-declared constructor (12.1), every 4818 // non-static data member of class T shall have a name different from T. 4819 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4820 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4821 ++I) { 4822 NamedDecl *D = *I; 4823 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4824 isa<IndirectFieldDecl>(D)) { 4825 Diag(D->getLocation(), diag::err_member_name_of_class) 4826 << D->getDeclName(); 4827 break; 4828 } 4829 } 4830 } 4831 4832 // Warn if the class has virtual methods but non-virtual public destructor. 4833 if (Record->isPolymorphic() && !Record->isDependentType()) { 4834 CXXDestructorDecl *dtor = Record->getDestructor(); 4835 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 4836 !Record->hasAttr<FinalAttr>()) 4837 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4838 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4839 } 4840 4841 if (Record->isAbstract()) { 4842 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4843 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4844 << FA->isSpelledAsSealed(); 4845 DiagnoseAbstractType(Record); 4846 } 4847 } 4848 4849 bool HasMethodWithOverrideControl = false, 4850 HasOverridingMethodWithoutOverrideControl = false; 4851 if (!Record->isDependentType()) { 4852 for (auto *M : Record->methods()) { 4853 // See if a method overloads virtual methods in a base 4854 // class without overriding any. 4855 if (!M->isStatic()) 4856 DiagnoseHiddenVirtualMethods(M); 4857 if (M->hasAttr<OverrideAttr>()) 4858 HasMethodWithOverrideControl = true; 4859 else if (M->size_overridden_methods() > 0) 4860 HasOverridingMethodWithoutOverrideControl = true; 4861 // Check whether the explicitly-defaulted special members are valid. 4862 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4863 CheckExplicitlyDefaultedSpecialMember(M); 4864 4865 // For an explicitly defaulted or deleted special member, we defer 4866 // determining triviality until the class is complete. That time is now! 4867 if (!M->isImplicit() && !M->isUserProvided()) { 4868 CXXSpecialMember CSM = getSpecialMember(M); 4869 if (CSM != CXXInvalid) { 4870 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 4871 4872 // Inform the class that we've finished declaring this member. 4873 Record->finishedDefaultedOrDeletedMember(M); 4874 } 4875 } 4876 } 4877 } 4878 4879 if (HasMethodWithOverrideControl && 4880 HasOverridingMethodWithoutOverrideControl) { 4881 // At least one method has the 'override' control declared. 4882 // Diagnose all other overridden methods which do not have 'override' specified on them. 4883 for (auto *M : Record->methods()) 4884 DiagnoseAbsenceOfOverrideControl(M); 4885 } 4886 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4887 // function that is not a constructor declares that member function to be 4888 // const. [...] The class of which that function is a member shall be 4889 // a literal type. 4890 // 4891 // If the class has virtual bases, any constexpr members will already have 4892 // been diagnosed by the checks performed on the member declaration, so 4893 // suppress this (less useful) diagnostic. 4894 // 4895 // We delay this until we know whether an explicitly-defaulted (or deleted) 4896 // destructor for the class is trivial. 4897 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4898 !Record->isLiteral() && !Record->getNumVBases()) { 4899 for (const auto *M : Record->methods()) { 4900 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) { 4901 switch (Record->getTemplateSpecializationKind()) { 4902 case TSK_ImplicitInstantiation: 4903 case TSK_ExplicitInstantiationDeclaration: 4904 case TSK_ExplicitInstantiationDefinition: 4905 // If a template instantiates to a non-literal type, but its members 4906 // instantiate to constexpr functions, the template is technically 4907 // ill-formed, but we allow it for sanity. 4908 continue; 4909 4910 case TSK_Undeclared: 4911 case TSK_ExplicitSpecialization: 4912 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4913 diag::err_constexpr_method_non_literal); 4914 break; 4915 } 4916 4917 // Only produce one error per class. 4918 break; 4919 } 4920 } 4921 } 4922 4923 // ms_struct is a request to use the same ABI rules as MSVC. Check 4924 // whether this class uses any C++ features that are implemented 4925 // completely differently in MSVC, and if so, emit a diagnostic. 4926 // That diagnostic defaults to an error, but we allow projects to 4927 // map it down to a warning (or ignore it). It's a fairly common 4928 // practice among users of the ms_struct pragma to mass-annotate 4929 // headers, sweeping up a bunch of types that the project doesn't 4930 // really rely on MSVC-compatible layout for. We must therefore 4931 // support "ms_struct except for C++ stuff" as a secondary ABI. 4932 if (Record->isMsStruct(Context) && 4933 (Record->isPolymorphic() || Record->getNumBases())) { 4934 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 4935 } 4936 4937 // Declare inheriting constructors. We do this eagerly here because: 4938 // - The standard requires an eager diagnostic for conflicting inheriting 4939 // constructors from different classes. 4940 // - The lazy declaration of the other implicit constructors is so as to not 4941 // waste space and performance on classes that are not meant to be 4942 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4943 // have inheriting constructors. 4944 DeclareInheritingConstructors(Record); 4945 4946 checkDLLAttribute(*this, Record); 4947 } 4948 4949 /// Look up the special member function that would be called by a special 4950 /// member function for a subobject of class type. 4951 /// 4952 /// \param Class The class type of the subobject. 4953 /// \param CSM The kind of special member function. 4954 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 4955 /// \param ConstRHS True if this is a copy operation with a const object 4956 /// on its RHS, that is, if the argument to the outer special member 4957 /// function is 'const' and this is not a field marked 'mutable'. 4958 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 4959 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 4960 unsigned FieldQuals, bool ConstRHS) { 4961 unsigned LHSQuals = 0; 4962 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 4963 LHSQuals = FieldQuals; 4964 4965 unsigned RHSQuals = FieldQuals; 4966 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4967 RHSQuals = 0; 4968 else if (ConstRHS) 4969 RHSQuals |= Qualifiers::Const; 4970 4971 return S.LookupSpecialMember(Class, CSM, 4972 RHSQuals & Qualifiers::Const, 4973 RHSQuals & Qualifiers::Volatile, 4974 false, 4975 LHSQuals & Qualifiers::Const, 4976 LHSQuals & Qualifiers::Volatile); 4977 } 4978 4979 /// Is the special member function which would be selected to perform the 4980 /// specified operation on the specified class type a constexpr constructor? 4981 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4982 Sema::CXXSpecialMember CSM, 4983 unsigned Quals, bool ConstRHS) { 4984 Sema::SpecialMemberOverloadResult *SMOR = 4985 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 4986 if (!SMOR || !SMOR->getMethod()) 4987 // A constructor we wouldn't select can't be "involved in initializing" 4988 // anything. 4989 return true; 4990 return SMOR->getMethod()->isConstexpr(); 4991 } 4992 4993 /// Determine whether the specified special member function would be constexpr 4994 /// if it were implicitly defined. 4995 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4996 Sema::CXXSpecialMember CSM, 4997 bool ConstArg) { 4998 if (!S.getLangOpts().CPlusPlus11) 4999 return false; 5000 5001 // C++11 [dcl.constexpr]p4: 5002 // In the definition of a constexpr constructor [...] 5003 bool Ctor = true; 5004 switch (CSM) { 5005 case Sema::CXXDefaultConstructor: 5006 // Since default constructor lookup is essentially trivial (and cannot 5007 // involve, for instance, template instantiation), we compute whether a 5008 // defaulted default constructor is constexpr directly within CXXRecordDecl. 5009 // 5010 // This is important for performance; we need to know whether the default 5011 // constructor is constexpr to determine whether the type is a literal type. 5012 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 5013 5014 case Sema::CXXCopyConstructor: 5015 case Sema::CXXMoveConstructor: 5016 // For copy or move constructors, we need to perform overload resolution. 5017 break; 5018 5019 case Sema::CXXCopyAssignment: 5020 case Sema::CXXMoveAssignment: 5021 if (!S.getLangOpts().CPlusPlus14) 5022 return false; 5023 // In C++1y, we need to perform overload resolution. 5024 Ctor = false; 5025 break; 5026 5027 case Sema::CXXDestructor: 5028 case Sema::CXXInvalid: 5029 return false; 5030 } 5031 5032 // -- if the class is a non-empty union, or for each non-empty anonymous 5033 // union member of a non-union class, exactly one non-static data member 5034 // shall be initialized; [DR1359] 5035 // 5036 // If we squint, this is guaranteed, since exactly one non-static data member 5037 // will be initialized (if the constructor isn't deleted), we just don't know 5038 // which one. 5039 if (Ctor && ClassDecl->isUnion()) 5040 return true; 5041 5042 // -- the class shall not have any virtual base classes; 5043 if (Ctor && ClassDecl->getNumVBases()) 5044 return false; 5045 5046 // C++1y [class.copy]p26: 5047 // -- [the class] is a literal type, and 5048 if (!Ctor && !ClassDecl->isLiteral()) 5049 return false; 5050 5051 // -- every constructor involved in initializing [...] base class 5052 // sub-objects shall be a constexpr constructor; 5053 // -- the assignment operator selected to copy/move each direct base 5054 // class is a constexpr function, and 5055 for (const auto &B : ClassDecl->bases()) { 5056 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 5057 if (!BaseType) continue; 5058 5059 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 5060 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 5061 return false; 5062 } 5063 5064 // -- every constructor involved in initializing non-static data members 5065 // [...] shall be a constexpr constructor; 5066 // -- every non-static data member and base class sub-object shall be 5067 // initialized 5068 // -- for each non-static data member of X that is of class type (or array 5069 // thereof), the assignment operator selected to copy/move that member is 5070 // a constexpr function 5071 for (const auto *F : ClassDecl->fields()) { 5072 if (F->isInvalidDecl()) 5073 continue; 5074 QualType BaseType = S.Context.getBaseElementType(F->getType()); 5075 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 5076 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 5077 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 5078 BaseType.getCVRQualifiers(), 5079 ConstArg && !F->isMutable())) 5080 return false; 5081 } 5082 } 5083 5084 // All OK, it's constexpr! 5085 return true; 5086 } 5087 5088 static Sema::ImplicitExceptionSpecification 5089 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 5090 switch (S.getSpecialMember(MD)) { 5091 case Sema::CXXDefaultConstructor: 5092 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 5093 case Sema::CXXCopyConstructor: 5094 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 5095 case Sema::CXXCopyAssignment: 5096 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 5097 case Sema::CXXMoveConstructor: 5098 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 5099 case Sema::CXXMoveAssignment: 5100 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 5101 case Sema::CXXDestructor: 5102 return S.ComputeDefaultedDtorExceptionSpec(MD); 5103 case Sema::CXXInvalid: 5104 break; 5105 } 5106 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 5107 "only special members have implicit exception specs"); 5108 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 5109 } 5110 5111 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 5112 CXXMethodDecl *MD) { 5113 FunctionProtoType::ExtProtoInfo EPI; 5114 5115 // Build an exception specification pointing back at this member. 5116 EPI.ExceptionSpec.Type = EST_Unevaluated; 5117 EPI.ExceptionSpec.SourceDecl = MD; 5118 5119 // Set the calling convention to the default for C++ instance methods. 5120 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 5121 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5122 /*IsCXXMethod=*/true)); 5123 return EPI; 5124 } 5125 5126 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 5127 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 5128 if (FPT->getExceptionSpecType() != EST_Unevaluated) 5129 return; 5130 5131 // Evaluate the exception specification. 5132 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 5133 5134 // Update the type of the special member to use it. 5135 UpdateExceptionSpec(MD, ESI); 5136 5137 // A user-provided destructor can be defined outside the class. When that 5138 // happens, be sure to update the exception specification on both 5139 // declarations. 5140 const FunctionProtoType *CanonicalFPT = 5141 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 5142 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 5143 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 5144 } 5145 5146 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 5147 CXXRecordDecl *RD = MD->getParent(); 5148 CXXSpecialMember CSM = getSpecialMember(MD); 5149 5150 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 5151 "not an explicitly-defaulted special member"); 5152 5153 // Whether this was the first-declared instance of the constructor. 5154 // This affects whether we implicitly add an exception spec and constexpr. 5155 bool First = MD == MD->getCanonicalDecl(); 5156 5157 bool HadError = false; 5158 5159 // C++11 [dcl.fct.def.default]p1: 5160 // A function that is explicitly defaulted shall 5161 // -- be a special member function (checked elsewhere), 5162 // -- have the same type (except for ref-qualifiers, and except that a 5163 // copy operation can take a non-const reference) as an implicit 5164 // declaration, and 5165 // -- not have default arguments. 5166 unsigned ExpectedParams = 1; 5167 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 5168 ExpectedParams = 0; 5169 if (MD->getNumParams() != ExpectedParams) { 5170 // This also checks for default arguments: a copy or move constructor with a 5171 // default argument is classified as a default constructor, and assignment 5172 // operations and destructors can't have default arguments. 5173 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 5174 << CSM << MD->getSourceRange(); 5175 HadError = true; 5176 } else if (MD->isVariadic()) { 5177 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 5178 << CSM << MD->getSourceRange(); 5179 HadError = true; 5180 } 5181 5182 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 5183 5184 bool CanHaveConstParam = false; 5185 if (CSM == CXXCopyConstructor) 5186 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 5187 else if (CSM == CXXCopyAssignment) 5188 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 5189 5190 QualType ReturnType = Context.VoidTy; 5191 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 5192 // Check for return type matching. 5193 ReturnType = Type->getReturnType(); 5194 QualType ExpectedReturnType = 5195 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 5196 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 5197 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 5198 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 5199 HadError = true; 5200 } 5201 5202 // A defaulted special member cannot have cv-qualifiers. 5203 if (Type->getTypeQuals()) { 5204 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 5205 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 5206 HadError = true; 5207 } 5208 } 5209 5210 // Check for parameter type matching. 5211 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 5212 bool HasConstParam = false; 5213 if (ExpectedParams && ArgType->isReferenceType()) { 5214 // Argument must be reference to possibly-const T. 5215 QualType ReferentType = ArgType->getPointeeType(); 5216 HasConstParam = ReferentType.isConstQualified(); 5217 5218 if (ReferentType.isVolatileQualified()) { 5219 Diag(MD->getLocation(), 5220 diag::err_defaulted_special_member_volatile_param) << CSM; 5221 HadError = true; 5222 } 5223 5224 if (HasConstParam && !CanHaveConstParam) { 5225 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 5226 Diag(MD->getLocation(), 5227 diag::err_defaulted_special_member_copy_const_param) 5228 << (CSM == CXXCopyAssignment); 5229 // FIXME: Explain why this special member can't be const. 5230 } else { 5231 Diag(MD->getLocation(), 5232 diag::err_defaulted_special_member_move_const_param) 5233 << (CSM == CXXMoveAssignment); 5234 } 5235 HadError = true; 5236 } 5237 } else if (ExpectedParams) { 5238 // A copy assignment operator can take its argument by value, but a 5239 // defaulted one cannot. 5240 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 5241 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 5242 HadError = true; 5243 } 5244 5245 // C++11 [dcl.fct.def.default]p2: 5246 // An explicitly-defaulted function may be declared constexpr only if it 5247 // would have been implicitly declared as constexpr, 5248 // Do not apply this rule to members of class templates, since core issue 1358 5249 // makes such functions always instantiate to constexpr functions. For 5250 // functions which cannot be constexpr (for non-constructors in C++11 and for 5251 // destructors in C++1y), this is checked elsewhere. 5252 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 5253 HasConstParam); 5254 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 5255 : isa<CXXConstructorDecl>(MD)) && 5256 MD->isConstexpr() && !Constexpr && 5257 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 5258 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 5259 // FIXME: Explain why the special member can't be constexpr. 5260 HadError = true; 5261 } 5262 5263 // and may have an explicit exception-specification only if it is compatible 5264 // with the exception-specification on the implicit declaration. 5265 if (Type->hasExceptionSpec()) { 5266 // Delay the check if this is the first declaration of the special member, 5267 // since we may not have parsed some necessary in-class initializers yet. 5268 if (First) { 5269 // If the exception specification needs to be instantiated, do so now, 5270 // before we clobber it with an EST_Unevaluated specification below. 5271 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 5272 InstantiateExceptionSpec(MD->getLocStart(), MD); 5273 Type = MD->getType()->getAs<FunctionProtoType>(); 5274 } 5275 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 5276 } else 5277 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 5278 } 5279 5280 // If a function is explicitly defaulted on its first declaration, 5281 if (First) { 5282 // -- it is implicitly considered to be constexpr if the implicit 5283 // definition would be, 5284 MD->setConstexpr(Constexpr); 5285 5286 // -- it is implicitly considered to have the same exception-specification 5287 // as if it had been implicitly declared, 5288 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 5289 EPI.ExceptionSpec.Type = EST_Unevaluated; 5290 EPI.ExceptionSpec.SourceDecl = MD; 5291 MD->setType(Context.getFunctionType(ReturnType, 5292 llvm::makeArrayRef(&ArgType, 5293 ExpectedParams), 5294 EPI)); 5295 } 5296 5297 if (ShouldDeleteSpecialMember(MD, CSM)) { 5298 if (First) { 5299 SetDeclDeleted(MD, MD->getLocation()); 5300 } else { 5301 // C++11 [dcl.fct.def.default]p4: 5302 // [For a] user-provided explicitly-defaulted function [...] if such a 5303 // function is implicitly defined as deleted, the program is ill-formed. 5304 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 5305 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 5306 HadError = true; 5307 } 5308 } 5309 5310 if (HadError) 5311 MD->setInvalidDecl(); 5312 } 5313 5314 /// Check whether the exception specification provided for an 5315 /// explicitly-defaulted special member matches the exception specification 5316 /// that would have been generated for an implicit special member, per 5317 /// C++11 [dcl.fct.def.default]p2. 5318 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 5319 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 5320 // If the exception specification was explicitly specified but hadn't been 5321 // parsed when the method was defaulted, grab it now. 5322 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed) 5323 SpecifiedType = 5324 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 5325 5326 // Compute the implicit exception specification. 5327 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5328 /*IsCXXMethod=*/true); 5329 FunctionProtoType::ExtProtoInfo EPI(CC); 5330 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 5331 .getExceptionSpec(); 5332 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 5333 Context.getFunctionType(Context.VoidTy, None, EPI)); 5334 5335 // Ensure that it matches. 5336 CheckEquivalentExceptionSpec( 5337 PDiag(diag::err_incorrect_defaulted_exception_spec) 5338 << getSpecialMember(MD), PDiag(), 5339 ImplicitType, SourceLocation(), 5340 SpecifiedType, MD->getLocation()); 5341 } 5342 5343 void Sema::CheckDelayedMemberExceptionSpecs() { 5344 decltype(DelayedExceptionSpecChecks) Checks; 5345 decltype(DelayedDefaultedMemberExceptionSpecs) Specs; 5346 5347 std::swap(Checks, DelayedExceptionSpecChecks); 5348 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 5349 5350 // Perform any deferred checking of exception specifications for virtual 5351 // destructors. 5352 for (auto &Check : Checks) 5353 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 5354 5355 // Check that any explicitly-defaulted methods have exception specifications 5356 // compatible with their implicit exception specifications. 5357 for (auto &Spec : Specs) 5358 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second); 5359 } 5360 5361 namespace { 5362 struct SpecialMemberDeletionInfo { 5363 Sema &S; 5364 CXXMethodDecl *MD; 5365 Sema::CXXSpecialMember CSM; 5366 bool Diagnose; 5367 5368 // Properties of the special member, computed for convenience. 5369 bool IsConstructor, IsAssignment, IsMove, ConstArg; 5370 SourceLocation Loc; 5371 5372 bool AllFieldsAreConst; 5373 5374 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 5375 Sema::CXXSpecialMember CSM, bool Diagnose) 5376 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 5377 IsConstructor(false), IsAssignment(false), IsMove(false), 5378 ConstArg(false), Loc(MD->getLocation()), 5379 AllFieldsAreConst(true) { 5380 switch (CSM) { 5381 case Sema::CXXDefaultConstructor: 5382 case Sema::CXXCopyConstructor: 5383 IsConstructor = true; 5384 break; 5385 case Sema::CXXMoveConstructor: 5386 IsConstructor = true; 5387 IsMove = true; 5388 break; 5389 case Sema::CXXCopyAssignment: 5390 IsAssignment = true; 5391 break; 5392 case Sema::CXXMoveAssignment: 5393 IsAssignment = true; 5394 IsMove = true; 5395 break; 5396 case Sema::CXXDestructor: 5397 break; 5398 case Sema::CXXInvalid: 5399 llvm_unreachable("invalid special member kind"); 5400 } 5401 5402 if (MD->getNumParams()) { 5403 if (const ReferenceType *RT = 5404 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 5405 ConstArg = RT->getPointeeType().isConstQualified(); 5406 } 5407 } 5408 5409 bool inUnion() const { return MD->getParent()->isUnion(); } 5410 5411 /// Look up the corresponding special member in the given class. 5412 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5413 unsigned Quals, bool IsMutable) { 5414 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5415 ConstArg && !IsMutable); 5416 } 5417 5418 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5419 5420 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5421 bool shouldDeleteForField(FieldDecl *FD); 5422 bool shouldDeleteForAllConstMembers(); 5423 5424 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5425 unsigned Quals); 5426 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5427 Sema::SpecialMemberOverloadResult *SMOR, 5428 bool IsDtorCallInCtor); 5429 5430 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5431 }; 5432 } 5433 5434 /// Is the given special member inaccessible when used on the given 5435 /// sub-object. 5436 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5437 CXXMethodDecl *target) { 5438 /// If we're operating on a base class, the object type is the 5439 /// type of this special member. 5440 QualType objectTy; 5441 AccessSpecifier access = target->getAccess(); 5442 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5443 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5444 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5445 5446 // If we're operating on a field, the object type is the type of the field. 5447 } else { 5448 objectTy = S.Context.getTypeDeclType(target->getParent()); 5449 } 5450 5451 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5452 } 5453 5454 /// Check whether we should delete a special member due to the implicit 5455 /// definition containing a call to a special member of a subobject. 5456 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5457 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5458 bool IsDtorCallInCtor) { 5459 CXXMethodDecl *Decl = SMOR->getMethod(); 5460 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5461 5462 int DiagKind = -1; 5463 5464 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5465 DiagKind = !Decl ? 0 : 1; 5466 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5467 DiagKind = 2; 5468 else if (!isAccessible(Subobj, Decl)) 5469 DiagKind = 3; 5470 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5471 !Decl->isTrivial()) { 5472 // A member of a union must have a trivial corresponding special member. 5473 // As a weird special case, a destructor call from a union's constructor 5474 // must be accessible and non-deleted, but need not be trivial. Such a 5475 // destructor is never actually called, but is semantically checked as 5476 // if it were. 5477 DiagKind = 4; 5478 } 5479 5480 if (DiagKind == -1) 5481 return false; 5482 5483 if (Diagnose) { 5484 if (Field) { 5485 S.Diag(Field->getLocation(), 5486 diag::note_deleted_special_member_class_subobject) 5487 << CSM << MD->getParent() << /*IsField*/true 5488 << Field << DiagKind << IsDtorCallInCtor; 5489 } else { 5490 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5491 S.Diag(Base->getLocStart(), 5492 diag::note_deleted_special_member_class_subobject) 5493 << CSM << MD->getParent() << /*IsField*/false 5494 << Base->getType() << DiagKind << IsDtorCallInCtor; 5495 } 5496 5497 if (DiagKind == 1) 5498 S.NoteDeletedFunction(Decl); 5499 // FIXME: Explain inaccessibility if DiagKind == 3. 5500 } 5501 5502 return true; 5503 } 5504 5505 /// Check whether we should delete a special member function due to having a 5506 /// direct or virtual base class or non-static data member of class type M. 5507 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5508 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5509 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5510 bool IsMutable = Field && Field->isMutable(); 5511 5512 // C++11 [class.ctor]p5: 5513 // -- any direct or virtual base class, or non-static data member with no 5514 // brace-or-equal-initializer, has class type M (or array thereof) and 5515 // either M has no default constructor or overload resolution as applied 5516 // to M's default constructor results in an ambiguity or in a function 5517 // that is deleted or inaccessible 5518 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5519 // -- a direct or virtual base class B that cannot be copied/moved because 5520 // overload resolution, as applied to B's corresponding special member, 5521 // results in an ambiguity or a function that is deleted or inaccessible 5522 // from the defaulted special member 5523 // C++11 [class.dtor]p5: 5524 // -- any direct or virtual base class [...] has a type with a destructor 5525 // that is deleted or inaccessible 5526 if (!(CSM == Sema::CXXDefaultConstructor && 5527 Field && Field->hasInClassInitializer()) && 5528 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5529 false)) 5530 return true; 5531 5532 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5533 // -- any direct or virtual base class or non-static data member has a 5534 // type with a destructor that is deleted or inaccessible 5535 if (IsConstructor) { 5536 Sema::SpecialMemberOverloadResult *SMOR = 5537 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5538 false, false, false, false, false); 5539 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5540 return true; 5541 } 5542 5543 return false; 5544 } 5545 5546 /// Check whether we should delete a special member function due to the class 5547 /// having a particular direct or virtual base class. 5548 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5549 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5550 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5551 } 5552 5553 /// Check whether we should delete a special member function due to the class 5554 /// having a particular non-static data member. 5555 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5556 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5557 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5558 5559 if (CSM == Sema::CXXDefaultConstructor) { 5560 // For a default constructor, all references must be initialized in-class 5561 // and, if a union, it must have a non-const member. 5562 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5563 if (Diagnose) 5564 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5565 << MD->getParent() << FD << FieldType << /*Reference*/0; 5566 return true; 5567 } 5568 // C++11 [class.ctor]p5: any non-variant non-static data member of 5569 // const-qualified type (or array thereof) with no 5570 // brace-or-equal-initializer does not have a user-provided default 5571 // constructor. 5572 if (!inUnion() && FieldType.isConstQualified() && 5573 !FD->hasInClassInitializer() && 5574 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5575 if (Diagnose) 5576 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5577 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5578 return true; 5579 } 5580 5581 if (inUnion() && !FieldType.isConstQualified()) 5582 AllFieldsAreConst = false; 5583 } else if (CSM == Sema::CXXCopyConstructor) { 5584 // For a copy constructor, data members must not be of rvalue reference 5585 // type. 5586 if (FieldType->isRValueReferenceType()) { 5587 if (Diagnose) 5588 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5589 << MD->getParent() << FD << FieldType; 5590 return true; 5591 } 5592 } else if (IsAssignment) { 5593 // For an assignment operator, data members must not be of reference type. 5594 if (FieldType->isReferenceType()) { 5595 if (Diagnose) 5596 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5597 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5598 return true; 5599 } 5600 if (!FieldRecord && FieldType.isConstQualified()) { 5601 // C++11 [class.copy]p23: 5602 // -- a non-static data member of const non-class type (or array thereof) 5603 if (Diagnose) 5604 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5605 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5606 return true; 5607 } 5608 } 5609 5610 if (FieldRecord) { 5611 // Some additional restrictions exist on the variant members. 5612 if (!inUnion() && FieldRecord->isUnion() && 5613 FieldRecord->isAnonymousStructOrUnion()) { 5614 bool AllVariantFieldsAreConst = true; 5615 5616 // FIXME: Handle anonymous unions declared within anonymous unions. 5617 for (auto *UI : FieldRecord->fields()) { 5618 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5619 5620 if (!UnionFieldType.isConstQualified()) 5621 AllVariantFieldsAreConst = false; 5622 5623 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5624 if (UnionFieldRecord && 5625 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5626 UnionFieldType.getCVRQualifiers())) 5627 return true; 5628 } 5629 5630 // At least one member in each anonymous union must be non-const 5631 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5632 !FieldRecord->field_empty()) { 5633 if (Diagnose) 5634 S.Diag(FieldRecord->getLocation(), 5635 diag::note_deleted_default_ctor_all_const) 5636 << MD->getParent() << /*anonymous union*/1; 5637 return true; 5638 } 5639 5640 // Don't check the implicit member of the anonymous union type. 5641 // This is technically non-conformant, but sanity demands it. 5642 return false; 5643 } 5644 5645 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5646 FieldType.getCVRQualifiers())) 5647 return true; 5648 } 5649 5650 return false; 5651 } 5652 5653 /// C++11 [class.ctor] p5: 5654 /// A defaulted default constructor for a class X is defined as deleted if 5655 /// X is a union and all of its variant members are of const-qualified type. 5656 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5657 // This is a silly definition, because it gives an empty union a deleted 5658 // default constructor. Don't do that. 5659 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5660 !MD->getParent()->field_empty()) { 5661 if (Diagnose) 5662 S.Diag(MD->getParent()->getLocation(), 5663 diag::note_deleted_default_ctor_all_const) 5664 << MD->getParent() << /*not anonymous union*/0; 5665 return true; 5666 } 5667 return false; 5668 } 5669 5670 /// Determine whether a defaulted special member function should be defined as 5671 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5672 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5673 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5674 bool Diagnose) { 5675 if (MD->isInvalidDecl()) 5676 return false; 5677 CXXRecordDecl *RD = MD->getParent(); 5678 assert(!RD->isDependentType() && "do deletion after instantiation"); 5679 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5680 return false; 5681 5682 // C++11 [expr.lambda.prim]p19: 5683 // The closure type associated with a lambda-expression has a 5684 // deleted (8.4.3) default constructor and a deleted copy 5685 // assignment operator. 5686 if (RD->isLambda() && 5687 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5688 if (Diagnose) 5689 Diag(RD->getLocation(), diag::note_lambda_decl); 5690 return true; 5691 } 5692 5693 // For an anonymous struct or union, the copy and assignment special members 5694 // will never be used, so skip the check. For an anonymous union declared at 5695 // namespace scope, the constructor and destructor are used. 5696 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5697 RD->isAnonymousStructOrUnion()) 5698 return false; 5699 5700 // C++11 [class.copy]p7, p18: 5701 // If the class definition declares a move constructor or move assignment 5702 // operator, an implicitly declared copy constructor or copy assignment 5703 // operator is defined as deleted. 5704 if (MD->isImplicit() && 5705 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5706 CXXMethodDecl *UserDeclaredMove = nullptr; 5707 5708 // In Microsoft mode, a user-declared move only causes the deletion of the 5709 // corresponding copy operation, not both copy operations. 5710 if (RD->hasUserDeclaredMoveConstructor() && 5711 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5712 if (!Diagnose) return true; 5713 5714 // Find any user-declared move constructor. 5715 for (auto *I : RD->ctors()) { 5716 if (I->isMoveConstructor()) { 5717 UserDeclaredMove = I; 5718 break; 5719 } 5720 } 5721 assert(UserDeclaredMove); 5722 } else if (RD->hasUserDeclaredMoveAssignment() && 5723 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5724 if (!Diagnose) return true; 5725 5726 // Find any user-declared move assignment operator. 5727 for (auto *I : RD->methods()) { 5728 if (I->isMoveAssignmentOperator()) { 5729 UserDeclaredMove = I; 5730 break; 5731 } 5732 } 5733 assert(UserDeclaredMove); 5734 } 5735 5736 if (UserDeclaredMove) { 5737 Diag(UserDeclaredMove->getLocation(), 5738 diag::note_deleted_copy_user_declared_move) 5739 << (CSM == CXXCopyAssignment) << RD 5740 << UserDeclaredMove->isMoveAssignmentOperator(); 5741 return true; 5742 } 5743 } 5744 5745 // Do access control from the special member function 5746 ContextRAII MethodContext(*this, MD); 5747 5748 // C++11 [class.dtor]p5: 5749 // -- for a virtual destructor, lookup of the non-array deallocation function 5750 // results in an ambiguity or in a function that is deleted or inaccessible 5751 if (CSM == CXXDestructor && MD->isVirtual()) { 5752 FunctionDecl *OperatorDelete = nullptr; 5753 DeclarationName Name = 5754 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5755 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5756 OperatorDelete, false)) { 5757 if (Diagnose) 5758 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5759 return true; 5760 } 5761 } 5762 5763 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5764 5765 for (auto &BI : RD->bases()) 5766 if (!BI.isVirtual() && 5767 SMI.shouldDeleteForBase(&BI)) 5768 return true; 5769 5770 // Per DR1611, do not consider virtual bases of constructors of abstract 5771 // classes, since we are not going to construct them. 5772 if (!RD->isAbstract() || !SMI.IsConstructor) { 5773 for (auto &BI : RD->vbases()) 5774 if (SMI.shouldDeleteForBase(&BI)) 5775 return true; 5776 } 5777 5778 for (auto *FI : RD->fields()) 5779 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5780 SMI.shouldDeleteForField(FI)) 5781 return true; 5782 5783 if (SMI.shouldDeleteForAllConstMembers()) 5784 return true; 5785 5786 if (getLangOpts().CUDA) { 5787 // We should delete the special member in CUDA mode if target inference 5788 // failed. 5789 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 5790 Diagnose); 5791 } 5792 5793 return false; 5794 } 5795 5796 /// Perform lookup for a special member of the specified kind, and determine 5797 /// whether it is trivial. If the triviality can be determined without the 5798 /// lookup, skip it. This is intended for use when determining whether a 5799 /// special member of a containing object is trivial, and thus does not ever 5800 /// perform overload resolution for default constructors. 5801 /// 5802 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5803 /// member that was most likely to be intended to be trivial, if any. 5804 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5805 Sema::CXXSpecialMember CSM, unsigned Quals, 5806 bool ConstRHS, CXXMethodDecl **Selected) { 5807 if (Selected) 5808 *Selected = nullptr; 5809 5810 switch (CSM) { 5811 case Sema::CXXInvalid: 5812 llvm_unreachable("not a special member"); 5813 5814 case Sema::CXXDefaultConstructor: 5815 // C++11 [class.ctor]p5: 5816 // A default constructor is trivial if: 5817 // - all the [direct subobjects] have trivial default constructors 5818 // 5819 // Note, no overload resolution is performed in this case. 5820 if (RD->hasTrivialDefaultConstructor()) 5821 return true; 5822 5823 if (Selected) { 5824 // If there's a default constructor which could have been trivial, dig it 5825 // out. Otherwise, if there's any user-provided default constructor, point 5826 // to that as an example of why there's not a trivial one. 5827 CXXConstructorDecl *DefCtor = nullptr; 5828 if (RD->needsImplicitDefaultConstructor()) 5829 S.DeclareImplicitDefaultConstructor(RD); 5830 for (auto *CI : RD->ctors()) { 5831 if (!CI->isDefaultConstructor()) 5832 continue; 5833 DefCtor = CI; 5834 if (!DefCtor->isUserProvided()) 5835 break; 5836 } 5837 5838 *Selected = DefCtor; 5839 } 5840 5841 return false; 5842 5843 case Sema::CXXDestructor: 5844 // C++11 [class.dtor]p5: 5845 // A destructor is trivial if: 5846 // - all the direct [subobjects] have trivial destructors 5847 if (RD->hasTrivialDestructor()) 5848 return true; 5849 5850 if (Selected) { 5851 if (RD->needsImplicitDestructor()) 5852 S.DeclareImplicitDestructor(RD); 5853 *Selected = RD->getDestructor(); 5854 } 5855 5856 return false; 5857 5858 case Sema::CXXCopyConstructor: 5859 // C++11 [class.copy]p12: 5860 // A copy constructor is trivial if: 5861 // - the constructor selected to copy each direct [subobject] is trivial 5862 if (RD->hasTrivialCopyConstructor()) { 5863 if (Quals == Qualifiers::Const) 5864 // We must either select the trivial copy constructor or reach an 5865 // ambiguity; no need to actually perform overload resolution. 5866 return true; 5867 } else if (!Selected) { 5868 return false; 5869 } 5870 // In C++98, we are not supposed to perform overload resolution here, but we 5871 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5872 // cases like B as having a non-trivial copy constructor: 5873 // struct A { template<typename T> A(T&); }; 5874 // struct B { mutable A a; }; 5875 goto NeedOverloadResolution; 5876 5877 case Sema::CXXCopyAssignment: 5878 // C++11 [class.copy]p25: 5879 // A copy assignment operator is trivial if: 5880 // - the assignment operator selected to copy each direct [subobject] is 5881 // trivial 5882 if (RD->hasTrivialCopyAssignment()) { 5883 if (Quals == Qualifiers::Const) 5884 return true; 5885 } else if (!Selected) { 5886 return false; 5887 } 5888 // In C++98, we are not supposed to perform overload resolution here, but we 5889 // treat that as a language defect. 5890 goto NeedOverloadResolution; 5891 5892 case Sema::CXXMoveConstructor: 5893 case Sema::CXXMoveAssignment: 5894 NeedOverloadResolution: 5895 Sema::SpecialMemberOverloadResult *SMOR = 5896 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5897 5898 // The standard doesn't describe how to behave if the lookup is ambiguous. 5899 // We treat it as not making the member non-trivial, just like the standard 5900 // mandates for the default constructor. This should rarely matter, because 5901 // the member will also be deleted. 5902 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5903 return true; 5904 5905 if (!SMOR->getMethod()) { 5906 assert(SMOR->getKind() == 5907 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5908 return false; 5909 } 5910 5911 // We deliberately don't check if we found a deleted special member. We're 5912 // not supposed to! 5913 if (Selected) 5914 *Selected = SMOR->getMethod(); 5915 return SMOR->getMethod()->isTrivial(); 5916 } 5917 5918 llvm_unreachable("unknown special method kind"); 5919 } 5920 5921 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5922 for (auto *CI : RD->ctors()) 5923 if (!CI->isImplicit()) 5924 return CI; 5925 5926 // Look for constructor templates. 5927 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5928 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5929 if (CXXConstructorDecl *CD = 5930 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5931 return CD; 5932 } 5933 5934 return nullptr; 5935 } 5936 5937 /// The kind of subobject we are checking for triviality. The values of this 5938 /// enumeration are used in diagnostics. 5939 enum TrivialSubobjectKind { 5940 /// The subobject is a base class. 5941 TSK_BaseClass, 5942 /// The subobject is a non-static data member. 5943 TSK_Field, 5944 /// The object is actually the complete object. 5945 TSK_CompleteObject 5946 }; 5947 5948 /// Check whether the special member selected for a given type would be trivial. 5949 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5950 QualType SubType, bool ConstRHS, 5951 Sema::CXXSpecialMember CSM, 5952 TrivialSubobjectKind Kind, 5953 bool Diagnose) { 5954 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5955 if (!SubRD) 5956 return true; 5957 5958 CXXMethodDecl *Selected; 5959 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5960 ConstRHS, Diagnose ? &Selected : nullptr)) 5961 return true; 5962 5963 if (Diagnose) { 5964 if (ConstRHS) 5965 SubType.addConst(); 5966 5967 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5968 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5969 << Kind << SubType.getUnqualifiedType(); 5970 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5971 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5972 } else if (!Selected) 5973 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5974 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5975 else if (Selected->isUserProvided()) { 5976 if (Kind == TSK_CompleteObject) 5977 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5978 << Kind << SubType.getUnqualifiedType() << CSM; 5979 else { 5980 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5981 << Kind << SubType.getUnqualifiedType() << CSM; 5982 S.Diag(Selected->getLocation(), diag::note_declared_at); 5983 } 5984 } else { 5985 if (Kind != TSK_CompleteObject) 5986 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5987 << Kind << SubType.getUnqualifiedType() << CSM; 5988 5989 // Explain why the defaulted or deleted special member isn't trivial. 5990 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5991 } 5992 } 5993 5994 return false; 5995 } 5996 5997 /// Check whether the members of a class type allow a special member to be 5998 /// trivial. 5999 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 6000 Sema::CXXSpecialMember CSM, 6001 bool ConstArg, bool Diagnose) { 6002 for (const auto *FI : RD->fields()) { 6003 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 6004 continue; 6005 6006 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 6007 6008 // Pretend anonymous struct or union members are members of this class. 6009 if (FI->isAnonymousStructOrUnion()) { 6010 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 6011 CSM, ConstArg, Diagnose)) 6012 return false; 6013 continue; 6014 } 6015 6016 // C++11 [class.ctor]p5: 6017 // A default constructor is trivial if [...] 6018 // -- no non-static data member of its class has a 6019 // brace-or-equal-initializer 6020 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 6021 if (Diagnose) 6022 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 6023 return false; 6024 } 6025 6026 // Objective C ARC 4.3.5: 6027 // [...] nontrivally ownership-qualified types are [...] not trivially 6028 // default constructible, copy constructible, move constructible, copy 6029 // assignable, move assignable, or destructible [...] 6030 if (S.getLangOpts().ObjCAutoRefCount && 6031 FieldType.hasNonTrivialObjCLifetime()) { 6032 if (Diagnose) 6033 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 6034 << RD << FieldType.getObjCLifetime(); 6035 return false; 6036 } 6037 6038 bool ConstRHS = ConstArg && !FI->isMutable(); 6039 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 6040 CSM, TSK_Field, Diagnose)) 6041 return false; 6042 } 6043 6044 return true; 6045 } 6046 6047 /// Diagnose why the specified class does not have a trivial special member of 6048 /// the given kind. 6049 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 6050 QualType Ty = Context.getRecordType(RD); 6051 6052 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 6053 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 6054 TSK_CompleteObject, /*Diagnose*/true); 6055 } 6056 6057 /// Determine whether a defaulted or deleted special member function is trivial, 6058 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 6059 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 6060 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 6061 bool Diagnose) { 6062 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 6063 6064 CXXRecordDecl *RD = MD->getParent(); 6065 6066 bool ConstArg = false; 6067 6068 // C++11 [class.copy]p12, p25: [DR1593] 6069 // A [special member] is trivial if [...] its parameter-type-list is 6070 // equivalent to the parameter-type-list of an implicit declaration [...] 6071 switch (CSM) { 6072 case CXXDefaultConstructor: 6073 case CXXDestructor: 6074 // Trivial default constructors and destructors cannot have parameters. 6075 break; 6076 6077 case CXXCopyConstructor: 6078 case CXXCopyAssignment: { 6079 // Trivial copy operations always have const, non-volatile parameter types. 6080 ConstArg = true; 6081 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6082 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 6083 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 6084 if (Diagnose) 6085 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6086 << Param0->getSourceRange() << Param0->getType() 6087 << Context.getLValueReferenceType( 6088 Context.getRecordType(RD).withConst()); 6089 return false; 6090 } 6091 break; 6092 } 6093 6094 case CXXMoveConstructor: 6095 case CXXMoveAssignment: { 6096 // Trivial move operations always have non-cv-qualified parameters. 6097 const ParmVarDecl *Param0 = MD->getParamDecl(0); 6098 const RValueReferenceType *RT = 6099 Param0->getType()->getAs<RValueReferenceType>(); 6100 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 6101 if (Diagnose) 6102 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 6103 << Param0->getSourceRange() << Param0->getType() 6104 << Context.getRValueReferenceType(Context.getRecordType(RD)); 6105 return false; 6106 } 6107 break; 6108 } 6109 6110 case CXXInvalid: 6111 llvm_unreachable("not a special member"); 6112 } 6113 6114 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 6115 if (Diagnose) 6116 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 6117 diag::note_nontrivial_default_arg) 6118 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 6119 return false; 6120 } 6121 if (MD->isVariadic()) { 6122 if (Diagnose) 6123 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 6124 return false; 6125 } 6126 6127 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6128 // A copy/move [constructor or assignment operator] is trivial if 6129 // -- the [member] selected to copy/move each direct base class subobject 6130 // is trivial 6131 // 6132 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6133 // A [default constructor or destructor] is trivial if 6134 // -- all the direct base classes have trivial [default constructors or 6135 // destructors] 6136 for (const auto &BI : RD->bases()) 6137 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 6138 ConstArg, CSM, TSK_BaseClass, Diagnose)) 6139 return false; 6140 6141 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 6142 // A copy/move [constructor or assignment operator] for a class X is 6143 // trivial if 6144 // -- for each non-static data member of X that is of class type (or array 6145 // thereof), the constructor selected to copy/move that member is 6146 // trivial 6147 // 6148 // C++11 [class.copy]p12, C++11 [class.copy]p25: 6149 // A [default constructor or destructor] is trivial if 6150 // -- for all of the non-static data members of its class that are of class 6151 // type (or array thereof), each such class has a trivial [default 6152 // constructor or destructor] 6153 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 6154 return false; 6155 6156 // C++11 [class.dtor]p5: 6157 // A destructor is trivial if [...] 6158 // -- the destructor is not virtual 6159 if (CSM == CXXDestructor && MD->isVirtual()) { 6160 if (Diagnose) 6161 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 6162 return false; 6163 } 6164 6165 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 6166 // A [special member] for class X is trivial if [...] 6167 // -- class X has no virtual functions and no virtual base classes 6168 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 6169 if (!Diagnose) 6170 return false; 6171 6172 if (RD->getNumVBases()) { 6173 // Check for virtual bases. We already know that the corresponding 6174 // member in all bases is trivial, so vbases must all be direct. 6175 CXXBaseSpecifier &BS = *RD->vbases_begin(); 6176 assert(BS.isVirtual()); 6177 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 6178 return false; 6179 } 6180 6181 // Must have a virtual method. 6182 for (const auto *MI : RD->methods()) { 6183 if (MI->isVirtual()) { 6184 SourceLocation MLoc = MI->getLocStart(); 6185 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 6186 return false; 6187 } 6188 } 6189 6190 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 6191 } 6192 6193 // Looks like it's trivial! 6194 return true; 6195 } 6196 6197 /// \brief Data used with FindHiddenVirtualMethod 6198 namespace { 6199 struct FindHiddenVirtualMethodData { 6200 Sema *S; 6201 CXXMethodDecl *Method; 6202 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 6203 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6204 }; 6205 } 6206 6207 /// \brief Check whether any most overriden method from MD in Methods 6208 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 6209 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6210 if (MD->size_overridden_methods() == 0) 6211 return Methods.count(MD->getCanonicalDecl()); 6212 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6213 E = MD->end_overridden_methods(); 6214 I != E; ++I) 6215 if (CheckMostOverridenMethods(*I, Methods)) 6216 return true; 6217 return false; 6218 } 6219 6220 /// \brief Member lookup function that determines whether a given C++ 6221 /// method overloads virtual methods in a base class without overriding any, 6222 /// to be used with CXXRecordDecl::lookupInBases(). 6223 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 6224 CXXBasePath &Path, 6225 void *UserData) { 6226 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6227 6228 FindHiddenVirtualMethodData &Data 6229 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 6230 6231 DeclarationName Name = Data.Method->getDeclName(); 6232 assert(Name.getNameKind() == DeclarationName::Identifier); 6233 6234 bool foundSameNameMethod = false; 6235 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 6236 for (Path.Decls = BaseRecord->lookup(Name); 6237 !Path.Decls.empty(); 6238 Path.Decls = Path.Decls.slice(1)) { 6239 NamedDecl *D = Path.Decls.front(); 6240 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6241 MD = MD->getCanonicalDecl(); 6242 foundSameNameMethod = true; 6243 // Interested only in hidden virtual methods. 6244 if (!MD->isVirtual()) 6245 continue; 6246 // If the method we are checking overrides a method from its base 6247 // don't warn about the other overloaded methods. Clang deviates from GCC 6248 // by only diagnosing overloads of inherited virtual functions that do not 6249 // override any other virtual functions in the base. GCC's 6250 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 6251 // function from a base class. These cases may be better served by a 6252 // warning (not specific to virtual functions) on call sites when the call 6253 // would select a different function from the base class, were it visible. 6254 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 6255 if (!Data.S->IsOverload(Data.Method, MD, false)) 6256 return true; 6257 // Collect the overload only if its hidden. 6258 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 6259 overloadedMethods.push_back(MD); 6260 } 6261 } 6262 6263 if (foundSameNameMethod) 6264 Data.OverloadedMethods.append(overloadedMethods.begin(), 6265 overloadedMethods.end()); 6266 return foundSameNameMethod; 6267 } 6268 6269 /// \brief Add the most overriden methods from MD to Methods 6270 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 6271 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6272 if (MD->size_overridden_methods() == 0) 6273 Methods.insert(MD->getCanonicalDecl()); 6274 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6275 E = MD->end_overridden_methods(); 6276 I != E; ++I) 6277 AddMostOverridenMethods(*I, Methods); 6278 } 6279 6280 /// \brief Check if a method overloads virtual methods in a base class without 6281 /// overriding any. 6282 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 6283 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6284 if (!MD->getDeclName().isIdentifier()) 6285 return; 6286 6287 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 6288 /*bool RecordPaths=*/false, 6289 /*bool DetectVirtual=*/false); 6290 FindHiddenVirtualMethodData Data; 6291 Data.Method = MD; 6292 Data.S = this; 6293 6294 // Keep the base methods that were overriden or introduced in the subclass 6295 // by 'using' in a set. A base method not in this set is hidden. 6296 CXXRecordDecl *DC = MD->getParent(); 6297 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 6298 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 6299 NamedDecl *ND = *I; 6300 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 6301 ND = shad->getTargetDecl(); 6302 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6303 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 6304 } 6305 6306 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 6307 OverloadedMethods = Data.OverloadedMethods; 6308 } 6309 6310 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 6311 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6312 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 6313 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 6314 PartialDiagnostic PD = PDiag( 6315 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 6316 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 6317 Diag(overloadedMD->getLocation(), PD); 6318 } 6319 } 6320 6321 /// \brief Diagnose methods which overload virtual methods in a base class 6322 /// without overriding any. 6323 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 6324 if (MD->isInvalidDecl()) 6325 return; 6326 6327 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 6328 return; 6329 6330 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6331 FindHiddenVirtualMethods(MD, OverloadedMethods); 6332 if (!OverloadedMethods.empty()) { 6333 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 6334 << MD << (OverloadedMethods.size() > 1); 6335 6336 NoteHiddenVirtualMethods(MD, OverloadedMethods); 6337 } 6338 } 6339 6340 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 6341 Decl *TagDecl, 6342 SourceLocation LBrac, 6343 SourceLocation RBrac, 6344 AttributeList *AttrList) { 6345 if (!TagDecl) 6346 return; 6347 6348 AdjustDeclIfTemplate(TagDecl); 6349 6350 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6351 if (l->getKind() != AttributeList::AT_Visibility) 6352 continue; 6353 l->setInvalid(); 6354 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 6355 l->getName(); 6356 } 6357 6358 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 6359 // strict aliasing violation! 6360 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 6361 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 6362 6363 CheckCompletedCXXClass( 6364 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 6365 } 6366 6367 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 6368 /// special functions, such as the default constructor, copy 6369 /// constructor, or destructor, to the given C++ class (C++ 6370 /// [special]p1). This routine can only be executed just before the 6371 /// definition of the class is complete. 6372 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 6373 if (!ClassDecl->hasUserDeclaredConstructor()) 6374 ++ASTContext::NumImplicitDefaultConstructors; 6375 6376 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 6377 ++ASTContext::NumImplicitCopyConstructors; 6378 6379 // If the properties or semantics of the copy constructor couldn't be 6380 // determined while the class was being declared, force a declaration 6381 // of it now. 6382 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 6383 DeclareImplicitCopyConstructor(ClassDecl); 6384 } 6385 6386 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 6387 ++ASTContext::NumImplicitMoveConstructors; 6388 6389 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 6390 DeclareImplicitMoveConstructor(ClassDecl); 6391 } 6392 6393 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 6394 ++ASTContext::NumImplicitCopyAssignmentOperators; 6395 6396 // If we have a dynamic class, then the copy assignment operator may be 6397 // virtual, so we have to declare it immediately. This ensures that, e.g., 6398 // it shows up in the right place in the vtable and that we diagnose 6399 // problems with the implicit exception specification. 6400 if (ClassDecl->isDynamicClass() || 6401 ClassDecl->needsOverloadResolutionForCopyAssignment()) 6402 DeclareImplicitCopyAssignment(ClassDecl); 6403 } 6404 6405 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 6406 ++ASTContext::NumImplicitMoveAssignmentOperators; 6407 6408 // Likewise for the move assignment operator. 6409 if (ClassDecl->isDynamicClass() || 6410 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6411 DeclareImplicitMoveAssignment(ClassDecl); 6412 } 6413 6414 if (!ClassDecl->hasUserDeclaredDestructor()) { 6415 ++ASTContext::NumImplicitDestructors; 6416 6417 // If we have a dynamic class, then the destructor may be virtual, so we 6418 // have to declare the destructor immediately. This ensures that, e.g., it 6419 // shows up in the right place in the vtable and that we diagnose problems 6420 // with the implicit exception specification. 6421 if (ClassDecl->isDynamicClass() || 6422 ClassDecl->needsOverloadResolutionForDestructor()) 6423 DeclareImplicitDestructor(ClassDecl); 6424 } 6425 } 6426 6427 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6428 if (!D) 6429 return 0; 6430 6431 // The order of template parameters is not important here. All names 6432 // get added to the same scope. 6433 SmallVector<TemplateParameterList *, 4> ParameterLists; 6434 6435 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 6436 D = TD->getTemplatedDecl(); 6437 6438 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6439 ParameterLists.push_back(PSD->getTemplateParameters()); 6440 6441 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6442 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 6443 ParameterLists.push_back(DD->getTemplateParameterList(i)); 6444 6445 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6446 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 6447 ParameterLists.push_back(FTD->getTemplateParameters()); 6448 } 6449 } 6450 6451 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 6452 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 6453 ParameterLists.push_back(TD->getTemplateParameterList(i)); 6454 6455 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 6456 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 6457 ParameterLists.push_back(CTD->getTemplateParameters()); 6458 } 6459 } 6460 6461 unsigned Count = 0; 6462 for (TemplateParameterList *Params : ParameterLists) { 6463 if (Params->size() > 0) 6464 // Ignore explicit specializations; they don't contribute to the template 6465 // depth. 6466 ++Count; 6467 for (NamedDecl *Param : *Params) { 6468 if (Param->getDeclName()) { 6469 S->AddDecl(Param); 6470 IdResolver.AddDecl(Param); 6471 } 6472 } 6473 } 6474 6475 return Count; 6476 } 6477 6478 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6479 if (!RecordD) return; 6480 AdjustDeclIfTemplate(RecordD); 6481 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6482 PushDeclContext(S, Record); 6483 } 6484 6485 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6486 if (!RecordD) return; 6487 PopDeclContext(); 6488 } 6489 6490 /// This is used to implement the constant expression evaluation part of the 6491 /// attribute enable_if extension. There is nothing in standard C++ which would 6492 /// require reentering parameters. 6493 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6494 if (!Param) 6495 return; 6496 6497 S->AddDecl(Param); 6498 if (Param->getDeclName()) 6499 IdResolver.AddDecl(Param); 6500 } 6501 6502 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6503 /// parsing a top-level (non-nested) C++ class, and we are now 6504 /// parsing those parts of the given Method declaration that could 6505 /// not be parsed earlier (C++ [class.mem]p2), such as default 6506 /// arguments. This action should enter the scope of the given 6507 /// Method declaration as if we had just parsed the qualified method 6508 /// name. However, it should not bring the parameters into scope; 6509 /// that will be performed by ActOnDelayedCXXMethodParameter. 6510 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6511 } 6512 6513 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6514 /// C++ method declaration. We're (re-)introducing the given 6515 /// function parameter into scope for use in parsing later parts of 6516 /// the method declaration. For example, we could see an 6517 /// ActOnParamDefaultArgument event for this parameter. 6518 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6519 if (!ParamD) 6520 return; 6521 6522 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6523 6524 // If this parameter has an unparsed default argument, clear it out 6525 // to make way for the parsed default argument. 6526 if (Param->hasUnparsedDefaultArg()) 6527 Param->setDefaultArg(nullptr); 6528 6529 S->AddDecl(Param); 6530 if (Param->getDeclName()) 6531 IdResolver.AddDecl(Param); 6532 } 6533 6534 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6535 /// processing the delayed method declaration for Method. The method 6536 /// declaration is now considered finished. There may be a separate 6537 /// ActOnStartOfFunctionDef action later (not necessarily 6538 /// immediately!) for this method, if it was also defined inside the 6539 /// class body. 6540 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6541 if (!MethodD) 6542 return; 6543 6544 AdjustDeclIfTemplate(MethodD); 6545 6546 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6547 6548 // Now that we have our default arguments, check the constructor 6549 // again. It could produce additional diagnostics or affect whether 6550 // the class has implicitly-declared destructors, among other 6551 // things. 6552 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6553 CheckConstructor(Constructor); 6554 6555 // Check the default arguments, which we may have added. 6556 if (!Method->isInvalidDecl()) 6557 CheckCXXDefaultArguments(Method); 6558 } 6559 6560 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6561 /// the well-formedness of the constructor declarator @p D with type @p 6562 /// R. If there are any errors in the declarator, this routine will 6563 /// emit diagnostics and set the invalid bit to true. In any case, the type 6564 /// will be updated to reflect a well-formed type for the constructor and 6565 /// returned. 6566 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6567 StorageClass &SC) { 6568 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6569 6570 // C++ [class.ctor]p3: 6571 // A constructor shall not be virtual (10.3) or static (9.4). A 6572 // constructor can be invoked for a const, volatile or const 6573 // volatile object. A constructor shall not be declared const, 6574 // volatile, or const volatile (9.3.2). 6575 if (isVirtual) { 6576 if (!D.isInvalidType()) 6577 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6578 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6579 << SourceRange(D.getIdentifierLoc()); 6580 D.setInvalidType(); 6581 } 6582 if (SC == SC_Static) { 6583 if (!D.isInvalidType()) 6584 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6585 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6586 << SourceRange(D.getIdentifierLoc()); 6587 D.setInvalidType(); 6588 SC = SC_None; 6589 } 6590 6591 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6592 diagnoseIgnoredQualifiers( 6593 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 6594 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 6595 D.getDeclSpec().getRestrictSpecLoc(), 6596 D.getDeclSpec().getAtomicSpecLoc()); 6597 D.setInvalidType(); 6598 } 6599 6600 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6601 if (FTI.TypeQuals != 0) { 6602 if (FTI.TypeQuals & Qualifiers::Const) 6603 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6604 << "const" << SourceRange(D.getIdentifierLoc()); 6605 if (FTI.TypeQuals & Qualifiers::Volatile) 6606 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6607 << "volatile" << SourceRange(D.getIdentifierLoc()); 6608 if (FTI.TypeQuals & Qualifiers::Restrict) 6609 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6610 << "restrict" << SourceRange(D.getIdentifierLoc()); 6611 D.setInvalidType(); 6612 } 6613 6614 // C++0x [class.ctor]p4: 6615 // A constructor shall not be declared with a ref-qualifier. 6616 if (FTI.hasRefQualifier()) { 6617 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6618 << FTI.RefQualifierIsLValueRef 6619 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6620 D.setInvalidType(); 6621 } 6622 6623 // Rebuild the function type "R" without any type qualifiers (in 6624 // case any of the errors above fired) and with "void" as the 6625 // return type, since constructors don't have return types. 6626 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6627 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6628 return R; 6629 6630 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6631 EPI.TypeQuals = 0; 6632 EPI.RefQualifier = RQ_None; 6633 6634 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6635 } 6636 6637 /// CheckConstructor - Checks a fully-formed constructor for 6638 /// well-formedness, issuing any diagnostics required. Returns true if 6639 /// the constructor declarator is invalid. 6640 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6641 CXXRecordDecl *ClassDecl 6642 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6643 if (!ClassDecl) 6644 return Constructor->setInvalidDecl(); 6645 6646 // C++ [class.copy]p3: 6647 // A declaration of a constructor for a class X is ill-formed if 6648 // its first parameter is of type (optionally cv-qualified) X and 6649 // either there are no other parameters or else all other 6650 // parameters have default arguments. 6651 if (!Constructor->isInvalidDecl() && 6652 ((Constructor->getNumParams() == 1) || 6653 (Constructor->getNumParams() > 1 && 6654 Constructor->getParamDecl(1)->hasDefaultArg())) && 6655 Constructor->getTemplateSpecializationKind() 6656 != TSK_ImplicitInstantiation) { 6657 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6658 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6659 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6660 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6661 const char *ConstRef 6662 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6663 : " const &"; 6664 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6665 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6666 6667 // FIXME: Rather that making the constructor invalid, we should endeavor 6668 // to fix the type. 6669 Constructor->setInvalidDecl(); 6670 } 6671 } 6672 } 6673 6674 /// CheckDestructor - Checks a fully-formed destructor definition for 6675 /// well-formedness, issuing any diagnostics required. Returns true 6676 /// on error. 6677 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6678 CXXRecordDecl *RD = Destructor->getParent(); 6679 6680 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6681 SourceLocation Loc; 6682 6683 if (!Destructor->isImplicit()) 6684 Loc = Destructor->getLocation(); 6685 else 6686 Loc = RD->getLocation(); 6687 6688 // If we have a virtual destructor, look up the deallocation function 6689 FunctionDecl *OperatorDelete = nullptr; 6690 DeclarationName Name = 6691 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6692 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6693 return true; 6694 // If there's no class-specific operator delete, look up the global 6695 // non-array delete. 6696 if (!OperatorDelete) 6697 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6698 6699 MarkFunctionReferenced(Loc, OperatorDelete); 6700 6701 Destructor->setOperatorDelete(OperatorDelete); 6702 } 6703 6704 return false; 6705 } 6706 6707 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6708 /// the well-formednes of the destructor declarator @p D with type @p 6709 /// R. If there are any errors in the declarator, this routine will 6710 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6711 /// will be updated to reflect a well-formed type for the destructor and 6712 /// returned. 6713 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6714 StorageClass& SC) { 6715 // C++ [class.dtor]p1: 6716 // [...] A typedef-name that names a class is a class-name 6717 // (7.1.3); however, a typedef-name that names a class shall not 6718 // be used as the identifier in the declarator for a destructor 6719 // declaration. 6720 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6721 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6722 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6723 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6724 else if (const TemplateSpecializationType *TST = 6725 DeclaratorType->getAs<TemplateSpecializationType>()) 6726 if (TST->isTypeAlias()) 6727 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6728 << DeclaratorType << 1; 6729 6730 // C++ [class.dtor]p2: 6731 // A destructor is used to destroy objects of its class type. A 6732 // destructor takes no parameters, and no return type can be 6733 // specified for it (not even void). The address of a destructor 6734 // shall not be taken. A destructor shall not be static. A 6735 // destructor can be invoked for a const, volatile or const 6736 // volatile object. A destructor shall not be declared const, 6737 // volatile or const volatile (9.3.2). 6738 if (SC == SC_Static) { 6739 if (!D.isInvalidType()) 6740 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6741 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6742 << SourceRange(D.getIdentifierLoc()) 6743 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6744 6745 SC = SC_None; 6746 } 6747 if (!D.isInvalidType()) { 6748 // Destructors don't have return types, but the parser will 6749 // happily parse something like: 6750 // 6751 // class X { 6752 // float ~X(); 6753 // }; 6754 // 6755 // The return type will be eliminated later. 6756 if (D.getDeclSpec().hasTypeSpecifier()) 6757 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6758 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6759 << SourceRange(D.getIdentifierLoc()); 6760 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6761 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 6762 SourceLocation(), 6763 D.getDeclSpec().getConstSpecLoc(), 6764 D.getDeclSpec().getVolatileSpecLoc(), 6765 D.getDeclSpec().getRestrictSpecLoc(), 6766 D.getDeclSpec().getAtomicSpecLoc()); 6767 D.setInvalidType(); 6768 } 6769 } 6770 6771 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6772 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6773 if (FTI.TypeQuals & Qualifiers::Const) 6774 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6775 << "const" << SourceRange(D.getIdentifierLoc()); 6776 if (FTI.TypeQuals & Qualifiers::Volatile) 6777 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6778 << "volatile" << SourceRange(D.getIdentifierLoc()); 6779 if (FTI.TypeQuals & Qualifiers::Restrict) 6780 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6781 << "restrict" << SourceRange(D.getIdentifierLoc()); 6782 D.setInvalidType(); 6783 } 6784 6785 // C++0x [class.dtor]p2: 6786 // A destructor shall not be declared with a ref-qualifier. 6787 if (FTI.hasRefQualifier()) { 6788 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6789 << FTI.RefQualifierIsLValueRef 6790 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6791 D.setInvalidType(); 6792 } 6793 6794 // Make sure we don't have any parameters. 6795 if (FTIHasNonVoidParameters(FTI)) { 6796 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6797 6798 // Delete the parameters. 6799 FTI.freeParams(); 6800 D.setInvalidType(); 6801 } 6802 6803 // Make sure the destructor isn't variadic. 6804 if (FTI.isVariadic) { 6805 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6806 D.setInvalidType(); 6807 } 6808 6809 // Rebuild the function type "R" without any type qualifiers or 6810 // parameters (in case any of the errors above fired) and with 6811 // "void" as the return type, since destructors don't have return 6812 // types. 6813 if (!D.isInvalidType()) 6814 return R; 6815 6816 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6817 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6818 EPI.Variadic = false; 6819 EPI.TypeQuals = 0; 6820 EPI.RefQualifier = RQ_None; 6821 return Context.getFunctionType(Context.VoidTy, None, EPI); 6822 } 6823 6824 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6825 /// well-formednes of the conversion function declarator @p D with 6826 /// type @p R. If there are any errors in the declarator, this routine 6827 /// will emit diagnostics and return true. Otherwise, it will return 6828 /// false. Either way, the type @p R will be updated to reflect a 6829 /// well-formed type for the conversion operator. 6830 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6831 StorageClass& SC) { 6832 // C++ [class.conv.fct]p1: 6833 // Neither parameter types nor return type can be specified. The 6834 // type of a conversion function (8.3.5) is "function taking no 6835 // parameter returning conversion-type-id." 6836 if (SC == SC_Static) { 6837 if (!D.isInvalidType()) 6838 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6839 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6840 << D.getName().getSourceRange(); 6841 D.setInvalidType(); 6842 SC = SC_None; 6843 } 6844 6845 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6846 6847 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6848 // Conversion functions don't have return types, but the parser will 6849 // happily parse something like: 6850 // 6851 // class X { 6852 // float operator bool(); 6853 // }; 6854 // 6855 // The return type will be changed later anyway. 6856 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6857 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6858 << SourceRange(D.getIdentifierLoc()); 6859 D.setInvalidType(); 6860 } 6861 6862 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6863 6864 // Make sure we don't have any parameters. 6865 if (Proto->getNumParams() > 0) { 6866 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6867 6868 // Delete the parameters. 6869 D.getFunctionTypeInfo().freeParams(); 6870 D.setInvalidType(); 6871 } else if (Proto->isVariadic()) { 6872 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6873 D.setInvalidType(); 6874 } 6875 6876 // Diagnose "&operator bool()" and other such nonsense. This 6877 // is actually a gcc extension which we don't support. 6878 if (Proto->getReturnType() != ConvType) { 6879 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6880 << Proto->getReturnType(); 6881 D.setInvalidType(); 6882 ConvType = Proto->getReturnType(); 6883 } 6884 6885 // C++ [class.conv.fct]p4: 6886 // The conversion-type-id shall not represent a function type nor 6887 // an array type. 6888 if (ConvType->isArrayType()) { 6889 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6890 ConvType = Context.getPointerType(ConvType); 6891 D.setInvalidType(); 6892 } else if (ConvType->isFunctionType()) { 6893 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6894 ConvType = Context.getPointerType(ConvType); 6895 D.setInvalidType(); 6896 } 6897 6898 // Rebuild the function type "R" without any parameters (in case any 6899 // of the errors above fired) and with the conversion type as the 6900 // return type. 6901 if (D.isInvalidType()) 6902 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6903 6904 // C++0x explicit conversion operators. 6905 if (D.getDeclSpec().isExplicitSpecified()) 6906 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6907 getLangOpts().CPlusPlus11 ? 6908 diag::warn_cxx98_compat_explicit_conversion_functions : 6909 diag::ext_explicit_conversion_functions) 6910 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6911 } 6912 6913 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6914 /// the declaration of the given C++ conversion function. This routine 6915 /// is responsible for recording the conversion function in the C++ 6916 /// class, if possible. 6917 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6918 assert(Conversion && "Expected to receive a conversion function declaration"); 6919 6920 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6921 6922 // Make sure we aren't redeclaring the conversion function. 6923 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6924 6925 // C++ [class.conv.fct]p1: 6926 // [...] A conversion function is never used to convert a 6927 // (possibly cv-qualified) object to the (possibly cv-qualified) 6928 // same object type (or a reference to it), to a (possibly 6929 // cv-qualified) base class of that type (or a reference to it), 6930 // or to (possibly cv-qualified) void. 6931 // FIXME: Suppress this warning if the conversion function ends up being a 6932 // virtual function that overrides a virtual function in a base class. 6933 QualType ClassType 6934 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6935 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6936 ConvType = ConvTypeRef->getPointeeType(); 6937 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6938 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6939 /* Suppress diagnostics for instantiations. */; 6940 else if (ConvType->isRecordType()) { 6941 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6942 if (ConvType == ClassType) 6943 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6944 << ClassType; 6945 else if (IsDerivedFrom(ClassType, ConvType)) 6946 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6947 << ClassType << ConvType; 6948 } else if (ConvType->isVoidType()) { 6949 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6950 << ClassType << ConvType; 6951 } 6952 6953 if (FunctionTemplateDecl *ConversionTemplate 6954 = Conversion->getDescribedFunctionTemplate()) 6955 return ConversionTemplate; 6956 6957 return Conversion; 6958 } 6959 6960 //===----------------------------------------------------------------------===// 6961 // Namespace Handling 6962 //===----------------------------------------------------------------------===// 6963 6964 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6965 /// reopened. 6966 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6967 SourceLocation Loc, 6968 IdentifierInfo *II, bool *IsInline, 6969 NamespaceDecl *PrevNS) { 6970 assert(*IsInline != PrevNS->isInline()); 6971 6972 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6973 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6974 // inline namespaces, with the intention of bringing names into namespace std. 6975 // 6976 // We support this just well enough to get that case working; this is not 6977 // sufficient to support reopening namespaces as inline in general. 6978 if (*IsInline && II && II->getName().startswith("__atomic") && 6979 S.getSourceManager().isInSystemHeader(Loc)) { 6980 // Mark all prior declarations of the namespace as inline. 6981 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6982 NS = NS->getPreviousDecl()) 6983 NS->setInline(*IsInline); 6984 // Patch up the lookup table for the containing namespace. This isn't really 6985 // correct, but it's good enough for this particular case. 6986 for (auto *I : PrevNS->decls()) 6987 if (auto *ND = dyn_cast<NamedDecl>(I)) 6988 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6989 return; 6990 } 6991 6992 if (PrevNS->isInline()) 6993 // The user probably just forgot the 'inline', so suggest that it 6994 // be added back. 6995 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6996 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6997 else 6998 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 6999 7000 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 7001 *IsInline = PrevNS->isInline(); 7002 } 7003 7004 /// ActOnStartNamespaceDef - This is called at the start of a namespace 7005 /// definition. 7006 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 7007 SourceLocation InlineLoc, 7008 SourceLocation NamespaceLoc, 7009 SourceLocation IdentLoc, 7010 IdentifierInfo *II, 7011 SourceLocation LBrace, 7012 AttributeList *AttrList) { 7013 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 7014 // For anonymous namespace, take the location of the left brace. 7015 SourceLocation Loc = II ? IdentLoc : LBrace; 7016 bool IsInline = InlineLoc.isValid(); 7017 bool IsInvalid = false; 7018 bool IsStd = false; 7019 bool AddToKnown = false; 7020 Scope *DeclRegionScope = NamespcScope->getParent(); 7021 7022 NamespaceDecl *PrevNS = nullptr; 7023 if (II) { 7024 // C++ [namespace.def]p2: 7025 // The identifier in an original-namespace-definition shall not 7026 // have been previously defined in the declarative region in 7027 // which the original-namespace-definition appears. The 7028 // identifier in an original-namespace-definition is the name of 7029 // the namespace. Subsequently in that declarative region, it is 7030 // treated as an original-namespace-name. 7031 // 7032 // Since namespace names are unique in their scope, and we don't 7033 // look through using directives, just look for any ordinary names. 7034 7035 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 7036 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 7037 Decl::IDNS_Namespace; 7038 NamedDecl *PrevDecl = nullptr; 7039 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 7040 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 7041 ++I) { 7042 if ((*I)->getIdentifierNamespace() & IDNS) { 7043 PrevDecl = *I; 7044 break; 7045 } 7046 } 7047 7048 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 7049 7050 if (PrevNS) { 7051 // This is an extended namespace definition. 7052 if (IsInline != PrevNS->isInline()) 7053 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 7054 &IsInline, PrevNS); 7055 } else if (PrevDecl) { 7056 // This is an invalid name redefinition. 7057 Diag(Loc, diag::err_redefinition_different_kind) 7058 << II; 7059 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7060 IsInvalid = true; 7061 // Continue on to push Namespc as current DeclContext and return it. 7062 } else if (II->isStr("std") && 7063 CurContext->getRedeclContext()->isTranslationUnit()) { 7064 // This is the first "real" definition of the namespace "std", so update 7065 // our cache of the "std" namespace to point at this definition. 7066 PrevNS = getStdNamespace(); 7067 IsStd = true; 7068 AddToKnown = !IsInline; 7069 } else { 7070 // We've seen this namespace for the first time. 7071 AddToKnown = !IsInline; 7072 } 7073 } else { 7074 // Anonymous namespaces. 7075 7076 // Determine whether the parent already has an anonymous namespace. 7077 DeclContext *Parent = CurContext->getRedeclContext(); 7078 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7079 PrevNS = TU->getAnonymousNamespace(); 7080 } else { 7081 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 7082 PrevNS = ND->getAnonymousNamespace(); 7083 } 7084 7085 if (PrevNS && IsInline != PrevNS->isInline()) 7086 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 7087 &IsInline, PrevNS); 7088 } 7089 7090 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 7091 StartLoc, Loc, II, PrevNS); 7092 if (IsInvalid) 7093 Namespc->setInvalidDecl(); 7094 7095 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 7096 7097 // FIXME: Should we be merging attributes? 7098 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 7099 PushNamespaceVisibilityAttr(Attr, Loc); 7100 7101 if (IsStd) 7102 StdNamespace = Namespc; 7103 if (AddToKnown) 7104 KnownNamespaces[Namespc] = false; 7105 7106 if (II) { 7107 PushOnScopeChains(Namespc, DeclRegionScope); 7108 } else { 7109 // Link the anonymous namespace into its parent. 7110 DeclContext *Parent = CurContext->getRedeclContext(); 7111 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 7112 TU->setAnonymousNamespace(Namespc); 7113 } else { 7114 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 7115 } 7116 7117 CurContext->addDecl(Namespc); 7118 7119 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 7120 // behaves as if it were replaced by 7121 // namespace unique { /* empty body */ } 7122 // using namespace unique; 7123 // namespace unique { namespace-body } 7124 // where all occurrences of 'unique' in a translation unit are 7125 // replaced by the same identifier and this identifier differs 7126 // from all other identifiers in the entire program. 7127 7128 // We just create the namespace with an empty name and then add an 7129 // implicit using declaration, just like the standard suggests. 7130 // 7131 // CodeGen enforces the "universally unique" aspect by giving all 7132 // declarations semantically contained within an anonymous 7133 // namespace internal linkage. 7134 7135 if (!PrevNS) { 7136 UsingDirectiveDecl* UD 7137 = UsingDirectiveDecl::Create(Context, Parent, 7138 /* 'using' */ LBrace, 7139 /* 'namespace' */ SourceLocation(), 7140 /* qualifier */ NestedNameSpecifierLoc(), 7141 /* identifier */ SourceLocation(), 7142 Namespc, 7143 /* Ancestor */ Parent); 7144 UD->setImplicit(); 7145 Parent->addDecl(UD); 7146 } 7147 } 7148 7149 ActOnDocumentableDecl(Namespc); 7150 7151 // Although we could have an invalid decl (i.e. the namespace name is a 7152 // redefinition), push it as current DeclContext and try to continue parsing. 7153 // FIXME: We should be able to push Namespc here, so that the each DeclContext 7154 // for the namespace has the declarations that showed up in that particular 7155 // namespace definition. 7156 PushDeclContext(NamespcScope, Namespc); 7157 return Namespc; 7158 } 7159 7160 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 7161 /// is a namespace alias, returns the namespace it points to. 7162 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 7163 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 7164 return AD->getNamespace(); 7165 return dyn_cast_or_null<NamespaceDecl>(D); 7166 } 7167 7168 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 7169 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 7170 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 7171 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 7172 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 7173 Namespc->setRBraceLoc(RBrace); 7174 PopDeclContext(); 7175 if (Namespc->hasAttr<VisibilityAttr>()) 7176 PopPragmaVisibility(true, RBrace); 7177 } 7178 7179 CXXRecordDecl *Sema::getStdBadAlloc() const { 7180 return cast_or_null<CXXRecordDecl>( 7181 StdBadAlloc.get(Context.getExternalSource())); 7182 } 7183 7184 NamespaceDecl *Sema::getStdNamespace() const { 7185 return cast_or_null<NamespaceDecl>( 7186 StdNamespace.get(Context.getExternalSource())); 7187 } 7188 7189 /// \brief Retrieve the special "std" namespace, which may require us to 7190 /// implicitly define the namespace. 7191 NamespaceDecl *Sema::getOrCreateStdNamespace() { 7192 if (!StdNamespace) { 7193 // The "std" namespace has not yet been defined, so build one implicitly. 7194 StdNamespace = NamespaceDecl::Create(Context, 7195 Context.getTranslationUnitDecl(), 7196 /*Inline=*/false, 7197 SourceLocation(), SourceLocation(), 7198 &PP.getIdentifierTable().get("std"), 7199 /*PrevDecl=*/nullptr); 7200 getStdNamespace()->setImplicit(true); 7201 } 7202 7203 return getStdNamespace(); 7204 } 7205 7206 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 7207 assert(getLangOpts().CPlusPlus && 7208 "Looking for std::initializer_list outside of C++."); 7209 7210 // We're looking for implicit instantiations of 7211 // template <typename E> class std::initializer_list. 7212 7213 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 7214 return false; 7215 7216 ClassTemplateDecl *Template = nullptr; 7217 const TemplateArgument *Arguments = nullptr; 7218 7219 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7220 7221 ClassTemplateSpecializationDecl *Specialization = 7222 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 7223 if (!Specialization) 7224 return false; 7225 7226 Template = Specialization->getSpecializedTemplate(); 7227 Arguments = Specialization->getTemplateArgs().data(); 7228 } else if (const TemplateSpecializationType *TST = 7229 Ty->getAs<TemplateSpecializationType>()) { 7230 Template = dyn_cast_or_null<ClassTemplateDecl>( 7231 TST->getTemplateName().getAsTemplateDecl()); 7232 Arguments = TST->getArgs(); 7233 } 7234 if (!Template) 7235 return false; 7236 7237 if (!StdInitializerList) { 7238 // Haven't recognized std::initializer_list yet, maybe this is it. 7239 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 7240 if (TemplateClass->getIdentifier() != 7241 &PP.getIdentifierTable().get("initializer_list") || 7242 !getStdNamespace()->InEnclosingNamespaceSetOf( 7243 TemplateClass->getDeclContext())) 7244 return false; 7245 // This is a template called std::initializer_list, but is it the right 7246 // template? 7247 TemplateParameterList *Params = Template->getTemplateParameters(); 7248 if (Params->getMinRequiredArguments() != 1) 7249 return false; 7250 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 7251 return false; 7252 7253 // It's the right template. 7254 StdInitializerList = Template; 7255 } 7256 7257 if (Template != StdInitializerList) 7258 return false; 7259 7260 // This is an instance of std::initializer_list. Find the argument type. 7261 if (Element) 7262 *Element = Arguments[0].getAsType(); 7263 return true; 7264 } 7265 7266 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 7267 NamespaceDecl *Std = S.getStdNamespace(); 7268 if (!Std) { 7269 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7270 return nullptr; 7271 } 7272 7273 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 7274 Loc, Sema::LookupOrdinaryName); 7275 if (!S.LookupQualifiedName(Result, Std)) { 7276 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7277 return nullptr; 7278 } 7279 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 7280 if (!Template) { 7281 Result.suppressDiagnostics(); 7282 // We found something weird. Complain about the first thing we found. 7283 NamedDecl *Found = *Result.begin(); 7284 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 7285 return nullptr; 7286 } 7287 7288 // We found some template called std::initializer_list. Now verify that it's 7289 // correct. 7290 TemplateParameterList *Params = Template->getTemplateParameters(); 7291 if (Params->getMinRequiredArguments() != 1 || 7292 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 7293 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 7294 return nullptr; 7295 } 7296 7297 return Template; 7298 } 7299 7300 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 7301 if (!StdInitializerList) { 7302 StdInitializerList = LookupStdInitializerList(*this, Loc); 7303 if (!StdInitializerList) 7304 return QualType(); 7305 } 7306 7307 TemplateArgumentListInfo Args(Loc, Loc); 7308 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 7309 Context.getTrivialTypeSourceInfo(Element, 7310 Loc))); 7311 return Context.getCanonicalType( 7312 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 7313 } 7314 7315 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 7316 // C++ [dcl.init.list]p2: 7317 // A constructor is an initializer-list constructor if its first parameter 7318 // is of type std::initializer_list<E> or reference to possibly cv-qualified 7319 // std::initializer_list<E> for some type E, and either there are no other 7320 // parameters or else all other parameters have default arguments. 7321 if (Ctor->getNumParams() < 1 || 7322 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 7323 return false; 7324 7325 QualType ArgType = Ctor->getParamDecl(0)->getType(); 7326 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 7327 ArgType = RT->getPointeeType().getUnqualifiedType(); 7328 7329 return isStdInitializerList(ArgType, nullptr); 7330 } 7331 7332 /// \brief Determine whether a using statement is in a context where it will be 7333 /// apply in all contexts. 7334 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 7335 switch (CurContext->getDeclKind()) { 7336 case Decl::TranslationUnit: 7337 return true; 7338 case Decl::LinkageSpec: 7339 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 7340 default: 7341 return false; 7342 } 7343 } 7344 7345 namespace { 7346 7347 // Callback to only accept typo corrections that are namespaces. 7348 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 7349 public: 7350 bool ValidateCandidate(const TypoCorrection &candidate) override { 7351 if (NamedDecl *ND = candidate.getCorrectionDecl()) 7352 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 7353 return false; 7354 } 7355 }; 7356 7357 } 7358 7359 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 7360 CXXScopeSpec &SS, 7361 SourceLocation IdentLoc, 7362 IdentifierInfo *Ident) { 7363 R.clear(); 7364 if (TypoCorrection Corrected = 7365 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, 7366 llvm::make_unique<NamespaceValidatorCCC>(), 7367 Sema::CTK_ErrorRecovery)) { 7368 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 7369 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 7370 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 7371 Ident->getName().equals(CorrectedStr); 7372 S.diagnoseTypo(Corrected, 7373 S.PDiag(diag::err_using_directive_member_suggest) 7374 << Ident << DC << DroppedSpecifier << SS.getRange(), 7375 S.PDiag(diag::note_namespace_defined_here)); 7376 } else { 7377 S.diagnoseTypo(Corrected, 7378 S.PDiag(diag::err_using_directive_suggest) << Ident, 7379 S.PDiag(diag::note_namespace_defined_here)); 7380 } 7381 R.addDecl(Corrected.getCorrectionDecl()); 7382 return true; 7383 } 7384 return false; 7385 } 7386 7387 Decl *Sema::ActOnUsingDirective(Scope *S, 7388 SourceLocation UsingLoc, 7389 SourceLocation NamespcLoc, 7390 CXXScopeSpec &SS, 7391 SourceLocation IdentLoc, 7392 IdentifierInfo *NamespcName, 7393 AttributeList *AttrList) { 7394 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7395 assert(NamespcName && "Invalid NamespcName."); 7396 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7397 7398 // This can only happen along a recovery path. 7399 while (S->getFlags() & Scope::TemplateParamScope) 7400 S = S->getParent(); 7401 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7402 7403 UsingDirectiveDecl *UDir = nullptr; 7404 NestedNameSpecifier *Qualifier = nullptr; 7405 if (SS.isSet()) 7406 Qualifier = SS.getScopeRep(); 7407 7408 // Lookup namespace name. 7409 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7410 LookupParsedName(R, S, &SS); 7411 if (R.isAmbiguous()) 7412 return nullptr; 7413 7414 if (R.empty()) { 7415 R.clear(); 7416 // Allow "using namespace std;" or "using namespace ::std;" even if 7417 // "std" hasn't been defined yet, for GCC compatibility. 7418 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7419 NamespcName->isStr("std")) { 7420 Diag(IdentLoc, diag::ext_using_undefined_std); 7421 R.addDecl(getOrCreateStdNamespace()); 7422 R.resolveKind(); 7423 } 7424 // Otherwise, attempt typo correction. 7425 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7426 } 7427 7428 if (!R.empty()) { 7429 NamedDecl *Named = R.getFoundDecl(); 7430 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7431 && "expected namespace decl"); 7432 7433 // The use of a nested name specifier may trigger deprecation warnings. 7434 DiagnoseUseOfDecl(Named, IdentLoc); 7435 7436 // C++ [namespace.udir]p1: 7437 // A using-directive specifies that the names in the nominated 7438 // namespace can be used in the scope in which the 7439 // using-directive appears after the using-directive. During 7440 // unqualified name lookup (3.4.1), the names appear as if they 7441 // were declared in the nearest enclosing namespace which 7442 // contains both the using-directive and the nominated 7443 // namespace. [Note: in this context, "contains" means "contains 7444 // directly or indirectly". ] 7445 7446 // Find enclosing context containing both using-directive and 7447 // nominated namespace. 7448 NamespaceDecl *NS = getNamespaceDecl(Named); 7449 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7450 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7451 CommonAncestor = CommonAncestor->getParent(); 7452 7453 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7454 SS.getWithLocInContext(Context), 7455 IdentLoc, Named, CommonAncestor); 7456 7457 if (IsUsingDirectiveInToplevelContext(CurContext) && 7458 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7459 Diag(IdentLoc, diag::warn_using_directive_in_header); 7460 } 7461 7462 PushUsingDirective(S, UDir); 7463 } else { 7464 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7465 } 7466 7467 if (UDir) 7468 ProcessDeclAttributeList(S, UDir, AttrList); 7469 7470 return UDir; 7471 } 7472 7473 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7474 // If the scope has an associated entity and the using directive is at 7475 // namespace or translation unit scope, add the UsingDirectiveDecl into 7476 // its lookup structure so qualified name lookup can find it. 7477 DeclContext *Ctx = S->getEntity(); 7478 if (Ctx && !Ctx->isFunctionOrMethod()) 7479 Ctx->addDecl(UDir); 7480 else 7481 // Otherwise, it is at block scope. The using-directives will affect lookup 7482 // only to the end of the scope. 7483 S->PushUsingDirective(UDir); 7484 } 7485 7486 7487 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7488 AccessSpecifier AS, 7489 bool HasUsingKeyword, 7490 SourceLocation UsingLoc, 7491 CXXScopeSpec &SS, 7492 UnqualifiedId &Name, 7493 AttributeList *AttrList, 7494 bool HasTypenameKeyword, 7495 SourceLocation TypenameLoc) { 7496 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7497 7498 switch (Name.getKind()) { 7499 case UnqualifiedId::IK_ImplicitSelfParam: 7500 case UnqualifiedId::IK_Identifier: 7501 case UnqualifiedId::IK_OperatorFunctionId: 7502 case UnqualifiedId::IK_LiteralOperatorId: 7503 case UnqualifiedId::IK_ConversionFunctionId: 7504 break; 7505 7506 case UnqualifiedId::IK_ConstructorName: 7507 case UnqualifiedId::IK_ConstructorTemplateId: 7508 // C++11 inheriting constructors. 7509 Diag(Name.getLocStart(), 7510 getLangOpts().CPlusPlus11 ? 7511 diag::warn_cxx98_compat_using_decl_constructor : 7512 diag::err_using_decl_constructor) 7513 << SS.getRange(); 7514 7515 if (getLangOpts().CPlusPlus11) break; 7516 7517 return nullptr; 7518 7519 case UnqualifiedId::IK_DestructorName: 7520 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7521 << SS.getRange(); 7522 return nullptr; 7523 7524 case UnqualifiedId::IK_TemplateId: 7525 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7526 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7527 return nullptr; 7528 } 7529 7530 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7531 DeclarationName TargetName = TargetNameInfo.getName(); 7532 if (!TargetName) 7533 return nullptr; 7534 7535 // Warn about access declarations. 7536 if (!HasUsingKeyword) { 7537 Diag(Name.getLocStart(), 7538 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7539 : diag::warn_access_decl_deprecated) 7540 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7541 } 7542 7543 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7544 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7545 return nullptr; 7546 7547 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7548 TargetNameInfo, AttrList, 7549 /* IsInstantiation */ false, 7550 HasTypenameKeyword, TypenameLoc); 7551 if (UD) 7552 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7553 7554 return UD; 7555 } 7556 7557 /// \brief Determine whether a using declaration considers the given 7558 /// declarations as "equivalent", e.g., if they are redeclarations of 7559 /// the same entity or are both typedefs of the same type. 7560 static bool 7561 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7562 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7563 return true; 7564 7565 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7566 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7567 return Context.hasSameType(TD1->getUnderlyingType(), 7568 TD2->getUnderlyingType()); 7569 7570 return false; 7571 } 7572 7573 7574 /// Determines whether to create a using shadow decl for a particular 7575 /// decl, given the set of decls existing prior to this using lookup. 7576 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7577 const LookupResult &Previous, 7578 UsingShadowDecl *&PrevShadow) { 7579 // Diagnose finding a decl which is not from a base class of the 7580 // current class. We do this now because there are cases where this 7581 // function will silently decide not to build a shadow decl, which 7582 // will pre-empt further diagnostics. 7583 // 7584 // We don't need to do this in C++0x because we do the check once on 7585 // the qualifier. 7586 // 7587 // FIXME: diagnose the following if we care enough: 7588 // struct A { int foo; }; 7589 // struct B : A { using A::foo; }; 7590 // template <class T> struct C : A {}; 7591 // template <class T> struct D : C<T> { using B::foo; } // <--- 7592 // This is invalid (during instantiation) in C++03 because B::foo 7593 // resolves to the using decl in B, which is not a base class of D<T>. 7594 // We can't diagnose it immediately because C<T> is an unknown 7595 // specialization. The UsingShadowDecl in D<T> then points directly 7596 // to A::foo, which will look well-formed when we instantiate. 7597 // The right solution is to not collapse the shadow-decl chain. 7598 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7599 DeclContext *OrigDC = Orig->getDeclContext(); 7600 7601 // Handle enums and anonymous structs. 7602 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7603 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7604 while (OrigRec->isAnonymousStructOrUnion()) 7605 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7606 7607 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7608 if (OrigDC == CurContext) { 7609 Diag(Using->getLocation(), 7610 diag::err_using_decl_nested_name_specifier_is_current_class) 7611 << Using->getQualifierLoc().getSourceRange(); 7612 Diag(Orig->getLocation(), diag::note_using_decl_target); 7613 return true; 7614 } 7615 7616 Diag(Using->getQualifierLoc().getBeginLoc(), 7617 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7618 << Using->getQualifier() 7619 << cast<CXXRecordDecl>(CurContext) 7620 << Using->getQualifierLoc().getSourceRange(); 7621 Diag(Orig->getLocation(), diag::note_using_decl_target); 7622 return true; 7623 } 7624 } 7625 7626 if (Previous.empty()) return false; 7627 7628 NamedDecl *Target = Orig; 7629 if (isa<UsingShadowDecl>(Target)) 7630 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7631 7632 // If the target happens to be one of the previous declarations, we 7633 // don't have a conflict. 7634 // 7635 // FIXME: but we might be increasing its access, in which case we 7636 // should redeclare it. 7637 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7638 bool FoundEquivalentDecl = false; 7639 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7640 I != E; ++I) { 7641 NamedDecl *D = (*I)->getUnderlyingDecl(); 7642 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7643 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7644 PrevShadow = Shadow; 7645 FoundEquivalentDecl = true; 7646 } 7647 7648 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7649 } 7650 7651 if (FoundEquivalentDecl) 7652 return false; 7653 7654 if (FunctionDecl *FD = Target->getAsFunction()) { 7655 NamedDecl *OldDecl = nullptr; 7656 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7657 /*IsForUsingDecl*/ true)) { 7658 case Ovl_Overload: 7659 return false; 7660 7661 case Ovl_NonFunction: 7662 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7663 break; 7664 7665 // We found a decl with the exact signature. 7666 case Ovl_Match: 7667 // If we're in a record, we want to hide the target, so we 7668 // return true (without a diagnostic) to tell the caller not to 7669 // build a shadow decl. 7670 if (CurContext->isRecord()) 7671 return true; 7672 7673 // If we're not in a record, this is an error. 7674 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7675 break; 7676 } 7677 7678 Diag(Target->getLocation(), diag::note_using_decl_target); 7679 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7680 return true; 7681 } 7682 7683 // Target is not a function. 7684 7685 if (isa<TagDecl>(Target)) { 7686 // No conflict between a tag and a non-tag. 7687 if (!Tag) return false; 7688 7689 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7690 Diag(Target->getLocation(), diag::note_using_decl_target); 7691 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7692 return true; 7693 } 7694 7695 // No conflict between a tag and a non-tag. 7696 if (!NonTag) return false; 7697 7698 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7699 Diag(Target->getLocation(), diag::note_using_decl_target); 7700 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7701 return true; 7702 } 7703 7704 /// Builds a shadow declaration corresponding to a 'using' declaration. 7705 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7706 UsingDecl *UD, 7707 NamedDecl *Orig, 7708 UsingShadowDecl *PrevDecl) { 7709 7710 // If we resolved to another shadow declaration, just coalesce them. 7711 NamedDecl *Target = Orig; 7712 if (isa<UsingShadowDecl>(Target)) { 7713 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7714 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7715 } 7716 7717 UsingShadowDecl *Shadow 7718 = UsingShadowDecl::Create(Context, CurContext, 7719 UD->getLocation(), UD, Target); 7720 UD->addShadowDecl(Shadow); 7721 7722 Shadow->setAccess(UD->getAccess()); 7723 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7724 Shadow->setInvalidDecl(); 7725 7726 Shadow->setPreviousDecl(PrevDecl); 7727 7728 if (S) 7729 PushOnScopeChains(Shadow, S); 7730 else 7731 CurContext->addDecl(Shadow); 7732 7733 7734 return Shadow; 7735 } 7736 7737 /// Hides a using shadow declaration. This is required by the current 7738 /// using-decl implementation when a resolvable using declaration in a 7739 /// class is followed by a declaration which would hide or override 7740 /// one or more of the using decl's targets; for example: 7741 /// 7742 /// struct Base { void foo(int); }; 7743 /// struct Derived : Base { 7744 /// using Base::foo; 7745 /// void foo(int); 7746 /// }; 7747 /// 7748 /// The governing language is C++03 [namespace.udecl]p12: 7749 /// 7750 /// When a using-declaration brings names from a base class into a 7751 /// derived class scope, member functions in the derived class 7752 /// override and/or hide member functions with the same name and 7753 /// parameter types in a base class (rather than conflicting). 7754 /// 7755 /// There are two ways to implement this: 7756 /// (1) optimistically create shadow decls when they're not hidden 7757 /// by existing declarations, or 7758 /// (2) don't create any shadow decls (or at least don't make them 7759 /// visible) until we've fully parsed/instantiated the class. 7760 /// The problem with (1) is that we might have to retroactively remove 7761 /// a shadow decl, which requires several O(n) operations because the 7762 /// decl structures are (very reasonably) not designed for removal. 7763 /// (2) avoids this but is very fiddly and phase-dependent. 7764 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7765 if (Shadow->getDeclName().getNameKind() == 7766 DeclarationName::CXXConversionFunctionName) 7767 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7768 7769 // Remove it from the DeclContext... 7770 Shadow->getDeclContext()->removeDecl(Shadow); 7771 7772 // ...and the scope, if applicable... 7773 if (S) { 7774 S->RemoveDecl(Shadow); 7775 IdResolver.RemoveDecl(Shadow); 7776 } 7777 7778 // ...and the using decl. 7779 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7780 7781 // TODO: complain somehow if Shadow was used. It shouldn't 7782 // be possible for this to happen, because...? 7783 } 7784 7785 /// Find the base specifier for a base class with the given type. 7786 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7787 QualType DesiredBase, 7788 bool &AnyDependentBases) { 7789 // Check whether the named type is a direct base class. 7790 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7791 for (auto &Base : Derived->bases()) { 7792 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7793 if (CanonicalDesiredBase == BaseType) 7794 return &Base; 7795 if (BaseType->isDependentType()) 7796 AnyDependentBases = true; 7797 } 7798 return nullptr; 7799 } 7800 7801 namespace { 7802 class UsingValidatorCCC : public CorrectionCandidateCallback { 7803 public: 7804 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7805 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7806 : HasTypenameKeyword(HasTypenameKeyword), 7807 IsInstantiation(IsInstantiation), OldNNS(NNS), 7808 RequireMemberOf(RequireMemberOf) {} 7809 7810 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7811 NamedDecl *ND = Candidate.getCorrectionDecl(); 7812 7813 // Keywords are not valid here. 7814 if (!ND || isa<NamespaceDecl>(ND)) 7815 return false; 7816 7817 // Completely unqualified names are invalid for a 'using' declaration. 7818 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7819 return false; 7820 7821 if (RequireMemberOf) { 7822 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 7823 if (FoundRecord && FoundRecord->isInjectedClassName()) { 7824 // No-one ever wants a using-declaration to name an injected-class-name 7825 // of a base class, unless they're declaring an inheriting constructor. 7826 ASTContext &Ctx = ND->getASTContext(); 7827 if (!Ctx.getLangOpts().CPlusPlus11) 7828 return false; 7829 QualType FoundType = Ctx.getRecordType(FoundRecord); 7830 7831 // Check that the injected-class-name is named as a member of its own 7832 // type; we don't want to suggest 'using Derived::Base;', since that 7833 // means something else. 7834 NestedNameSpecifier *Specifier = 7835 Candidate.WillReplaceSpecifier() 7836 ? Candidate.getCorrectionSpecifier() 7837 : OldNNS; 7838 if (!Specifier->getAsType() || 7839 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 7840 return false; 7841 7842 // Check that this inheriting constructor declaration actually names a 7843 // direct base class of the current class. 7844 bool AnyDependentBases = false; 7845 if (!findDirectBaseWithType(RequireMemberOf, 7846 Ctx.getRecordType(FoundRecord), 7847 AnyDependentBases) && 7848 !AnyDependentBases) 7849 return false; 7850 } else { 7851 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 7852 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 7853 return false; 7854 7855 // FIXME: Check that the base class member is accessible? 7856 } 7857 } 7858 7859 if (isa<TypeDecl>(ND)) 7860 return HasTypenameKeyword || !IsInstantiation; 7861 7862 return !HasTypenameKeyword; 7863 } 7864 7865 private: 7866 bool HasTypenameKeyword; 7867 bool IsInstantiation; 7868 NestedNameSpecifier *OldNNS; 7869 CXXRecordDecl *RequireMemberOf; 7870 }; 7871 } // end anonymous namespace 7872 7873 /// Builds a using declaration. 7874 /// 7875 /// \param IsInstantiation - Whether this call arises from an 7876 /// instantiation of an unresolved using declaration. We treat 7877 /// the lookup differently for these declarations. 7878 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7879 SourceLocation UsingLoc, 7880 CXXScopeSpec &SS, 7881 DeclarationNameInfo NameInfo, 7882 AttributeList *AttrList, 7883 bool IsInstantiation, 7884 bool HasTypenameKeyword, 7885 SourceLocation TypenameLoc) { 7886 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7887 SourceLocation IdentLoc = NameInfo.getLoc(); 7888 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7889 7890 // FIXME: We ignore attributes for now. 7891 7892 if (SS.isEmpty()) { 7893 Diag(IdentLoc, diag::err_using_requires_qualname); 7894 return nullptr; 7895 } 7896 7897 // Do the redeclaration lookup in the current scope. 7898 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7899 ForRedeclaration); 7900 Previous.setHideTags(false); 7901 if (S) { 7902 LookupName(Previous, S); 7903 7904 // It is really dumb that we have to do this. 7905 LookupResult::Filter F = Previous.makeFilter(); 7906 while (F.hasNext()) { 7907 NamedDecl *D = F.next(); 7908 if (!isDeclInScope(D, CurContext, S)) 7909 F.erase(); 7910 // If we found a local extern declaration that's not ordinarily visible, 7911 // and this declaration is being added to a non-block scope, ignore it. 7912 // We're only checking for scope conflicts here, not also for violations 7913 // of the linkage rules. 7914 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 7915 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 7916 F.erase(); 7917 } 7918 F.done(); 7919 } else { 7920 assert(IsInstantiation && "no scope in non-instantiation"); 7921 assert(CurContext->isRecord() && "scope not record in instantiation"); 7922 LookupQualifiedName(Previous, CurContext); 7923 } 7924 7925 // Check for invalid redeclarations. 7926 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7927 SS, IdentLoc, Previous)) 7928 return nullptr; 7929 7930 // Check for bad qualifiers. 7931 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 7932 return nullptr; 7933 7934 DeclContext *LookupContext = computeDeclContext(SS); 7935 NamedDecl *D; 7936 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7937 if (!LookupContext) { 7938 if (HasTypenameKeyword) { 7939 // FIXME: not all declaration name kinds are legal here 7940 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7941 UsingLoc, TypenameLoc, 7942 QualifierLoc, 7943 IdentLoc, NameInfo.getName()); 7944 } else { 7945 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7946 QualifierLoc, NameInfo); 7947 } 7948 D->setAccess(AS); 7949 CurContext->addDecl(D); 7950 return D; 7951 } 7952 7953 auto Build = [&](bool Invalid) { 7954 UsingDecl *UD = 7955 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 7956 HasTypenameKeyword); 7957 UD->setAccess(AS); 7958 CurContext->addDecl(UD); 7959 UD->setInvalidDecl(Invalid); 7960 return UD; 7961 }; 7962 auto BuildInvalid = [&]{ return Build(true); }; 7963 auto BuildValid = [&]{ return Build(false); }; 7964 7965 if (RequireCompleteDeclContext(SS, LookupContext)) 7966 return BuildInvalid(); 7967 7968 // The normal rules do not apply to inheriting constructor declarations. 7969 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7970 UsingDecl *UD = BuildValid(); 7971 CheckInheritingConstructorUsingDecl(UD); 7972 return UD; 7973 } 7974 7975 // Otherwise, look up the target name. 7976 7977 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7978 7979 // Unlike most lookups, we don't always want to hide tag 7980 // declarations: tag names are visible through the using declaration 7981 // even if hidden by ordinary names, *except* in a dependent context 7982 // where it's important for the sanity of two-phase lookup. 7983 if (!IsInstantiation) 7984 R.setHideTags(false); 7985 7986 // For the purposes of this lookup, we have a base object type 7987 // equal to that of the current context. 7988 if (CurContext->isRecord()) { 7989 R.setBaseObjectType( 7990 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7991 } 7992 7993 LookupQualifiedName(R, LookupContext); 7994 7995 // Try to correct typos if possible. 7996 if (R.empty()) { 7997 if (TypoCorrection Corrected = CorrectTypo( 7998 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 7999 llvm::make_unique<UsingValidatorCCC>( 8000 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 8001 dyn_cast<CXXRecordDecl>(CurContext)), 8002 CTK_ErrorRecovery)) { 8003 // We reject any correction for which ND would be NULL. 8004 NamedDecl *ND = Corrected.getCorrectionDecl(); 8005 8006 // We reject candidates where DroppedSpecifier == true, hence the 8007 // literal '0' below. 8008 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 8009 << NameInfo.getName() << LookupContext << 0 8010 << SS.getRange()); 8011 8012 // If we corrected to an inheriting constructor, handle it as one. 8013 auto *RD = dyn_cast<CXXRecordDecl>(ND); 8014 if (RD && RD->isInjectedClassName()) { 8015 // Fix up the information we'll use to build the using declaration. 8016 if (Corrected.WillReplaceSpecifier()) { 8017 NestedNameSpecifierLocBuilder Builder; 8018 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 8019 QualifierLoc.getSourceRange()); 8020 QualifierLoc = Builder.getWithLocInContext(Context); 8021 } 8022 8023 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 8024 Context.getCanonicalType(Context.getRecordType(RD)))); 8025 NameInfo.setNamedTypeInfo(nullptr); 8026 8027 // Build it and process it as an inheriting constructor. 8028 UsingDecl *UD = BuildValid(); 8029 CheckInheritingConstructorUsingDecl(UD); 8030 return UD; 8031 } 8032 8033 // FIXME: Pick up all the declarations if we found an overloaded function. 8034 R.setLookupName(Corrected.getCorrection()); 8035 R.addDecl(ND); 8036 } else { 8037 Diag(IdentLoc, diag::err_no_member) 8038 << NameInfo.getName() << LookupContext << SS.getRange(); 8039 return BuildInvalid(); 8040 } 8041 } 8042 8043 if (R.isAmbiguous()) 8044 return BuildInvalid(); 8045 8046 if (HasTypenameKeyword) { 8047 // If we asked for a typename and got a non-type decl, error out. 8048 if (!R.getAsSingle<TypeDecl>()) { 8049 Diag(IdentLoc, diag::err_using_typename_non_type); 8050 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 8051 Diag((*I)->getUnderlyingDecl()->getLocation(), 8052 diag::note_using_decl_target); 8053 return BuildInvalid(); 8054 } 8055 } else { 8056 // If we asked for a non-typename and we got a type, error out, 8057 // but only if this is an instantiation of an unresolved using 8058 // decl. Otherwise just silently find the type name. 8059 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 8060 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 8061 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 8062 return BuildInvalid(); 8063 } 8064 } 8065 8066 // C++0x N2914 [namespace.udecl]p6: 8067 // A using-declaration shall not name a namespace. 8068 if (R.getAsSingle<NamespaceDecl>()) { 8069 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 8070 << SS.getRange(); 8071 return BuildInvalid(); 8072 } 8073 8074 UsingDecl *UD = BuildValid(); 8075 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8076 UsingShadowDecl *PrevDecl = nullptr; 8077 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 8078 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 8079 } 8080 8081 return UD; 8082 } 8083 8084 /// Additional checks for a using declaration referring to a constructor name. 8085 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 8086 assert(!UD->hasTypename() && "expecting a constructor name"); 8087 8088 const Type *SourceType = UD->getQualifier()->getAsType(); 8089 assert(SourceType && 8090 "Using decl naming constructor doesn't have type in scope spec."); 8091 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 8092 8093 // Check whether the named type is a direct base class. 8094 bool AnyDependentBases = false; 8095 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 8096 AnyDependentBases); 8097 if (!Base && !AnyDependentBases) { 8098 Diag(UD->getUsingLoc(), 8099 diag::err_using_decl_constructor_not_in_direct_base) 8100 << UD->getNameInfo().getSourceRange() 8101 << QualType(SourceType, 0) << TargetClass; 8102 UD->setInvalidDecl(); 8103 return true; 8104 } 8105 8106 if (Base) 8107 Base->setInheritConstructors(); 8108 8109 return false; 8110 } 8111 8112 /// Checks that the given using declaration is not an invalid 8113 /// redeclaration. Note that this is checking only for the using decl 8114 /// itself, not for any ill-formedness among the UsingShadowDecls. 8115 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 8116 bool HasTypenameKeyword, 8117 const CXXScopeSpec &SS, 8118 SourceLocation NameLoc, 8119 const LookupResult &Prev) { 8120 // C++03 [namespace.udecl]p8: 8121 // C++0x [namespace.udecl]p10: 8122 // A using-declaration is a declaration and can therefore be used 8123 // repeatedly where (and only where) multiple declarations are 8124 // allowed. 8125 // 8126 // That's in non-member contexts. 8127 if (!CurContext->getRedeclContext()->isRecord()) 8128 return false; 8129 8130 NestedNameSpecifier *Qual = SS.getScopeRep(); 8131 8132 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 8133 NamedDecl *D = *I; 8134 8135 bool DTypename; 8136 NestedNameSpecifier *DQual; 8137 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 8138 DTypename = UD->hasTypename(); 8139 DQual = UD->getQualifier(); 8140 } else if (UnresolvedUsingValueDecl *UD 8141 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 8142 DTypename = false; 8143 DQual = UD->getQualifier(); 8144 } else if (UnresolvedUsingTypenameDecl *UD 8145 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 8146 DTypename = true; 8147 DQual = UD->getQualifier(); 8148 } else continue; 8149 8150 // using decls differ if one says 'typename' and the other doesn't. 8151 // FIXME: non-dependent using decls? 8152 if (HasTypenameKeyword != DTypename) continue; 8153 8154 // using decls differ if they name different scopes (but note that 8155 // template instantiation can cause this check to trigger when it 8156 // didn't before instantiation). 8157 if (Context.getCanonicalNestedNameSpecifier(Qual) != 8158 Context.getCanonicalNestedNameSpecifier(DQual)) 8159 continue; 8160 8161 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 8162 Diag(D->getLocation(), diag::note_using_decl) << 1; 8163 return true; 8164 } 8165 8166 return false; 8167 } 8168 8169 8170 /// Checks that the given nested-name qualifier used in a using decl 8171 /// in the current context is appropriately related to the current 8172 /// scope. If an error is found, diagnoses it and returns true. 8173 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 8174 const CXXScopeSpec &SS, 8175 const DeclarationNameInfo &NameInfo, 8176 SourceLocation NameLoc) { 8177 DeclContext *NamedContext = computeDeclContext(SS); 8178 8179 if (!CurContext->isRecord()) { 8180 // C++03 [namespace.udecl]p3: 8181 // C++0x [namespace.udecl]p8: 8182 // A using-declaration for a class member shall be a member-declaration. 8183 8184 // If we weren't able to compute a valid scope, it must be a 8185 // dependent class scope. 8186 if (!NamedContext || NamedContext->isRecord()) { 8187 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext); 8188 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 8189 RD = nullptr; 8190 8191 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 8192 << SS.getRange(); 8193 8194 // If we have a complete, non-dependent source type, try to suggest a 8195 // way to get the same effect. 8196 if (!RD) 8197 return true; 8198 8199 // Find what this using-declaration was referring to. 8200 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8201 R.setHideTags(false); 8202 R.suppressDiagnostics(); 8203 LookupQualifiedName(R, RD); 8204 8205 if (R.getAsSingle<TypeDecl>()) { 8206 if (getLangOpts().CPlusPlus11) { 8207 // Convert 'using X::Y;' to 'using Y = X::Y;'. 8208 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 8209 << 0 // alias declaration 8210 << FixItHint::CreateInsertion(SS.getBeginLoc(), 8211 NameInfo.getName().getAsString() + 8212 " = "); 8213 } else { 8214 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 8215 SourceLocation InsertLoc = 8216 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 8217 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 8218 << 1 // typedef declaration 8219 << FixItHint::CreateReplacement(UsingLoc, "typedef") 8220 << FixItHint::CreateInsertion( 8221 InsertLoc, " " + NameInfo.getName().getAsString()); 8222 } 8223 } else if (R.getAsSingle<VarDecl>()) { 8224 // Don't provide a fixit outside C++11 mode; we don't want to suggest 8225 // repeating the type of the static data member here. 8226 FixItHint FixIt; 8227 if (getLangOpts().CPlusPlus11) { 8228 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 8229 FixIt = FixItHint::CreateReplacement( 8230 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 8231 } 8232 8233 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 8234 << 2 // reference declaration 8235 << FixIt; 8236 } 8237 return true; 8238 } 8239 8240 // Otherwise, everything is known to be fine. 8241 return false; 8242 } 8243 8244 // The current scope is a record. 8245 8246 // If the named context is dependent, we can't decide much. 8247 if (!NamedContext) { 8248 // FIXME: in C++0x, we can diagnose if we can prove that the 8249 // nested-name-specifier does not refer to a base class, which is 8250 // still possible in some cases. 8251 8252 // Otherwise we have to conservatively report that things might be 8253 // okay. 8254 return false; 8255 } 8256 8257 if (!NamedContext->isRecord()) { 8258 // Ideally this would point at the last name in the specifier, 8259 // but we don't have that level of source info. 8260 Diag(SS.getRange().getBegin(), 8261 diag::err_using_decl_nested_name_specifier_is_not_class) 8262 << SS.getScopeRep() << SS.getRange(); 8263 return true; 8264 } 8265 8266 if (!NamedContext->isDependentContext() && 8267 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 8268 return true; 8269 8270 if (getLangOpts().CPlusPlus11) { 8271 // C++0x [namespace.udecl]p3: 8272 // In a using-declaration used as a member-declaration, the 8273 // nested-name-specifier shall name a base class of the class 8274 // being defined. 8275 8276 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 8277 cast<CXXRecordDecl>(NamedContext))) { 8278 if (CurContext == NamedContext) { 8279 Diag(NameLoc, 8280 diag::err_using_decl_nested_name_specifier_is_current_class) 8281 << SS.getRange(); 8282 return true; 8283 } 8284 8285 Diag(SS.getRange().getBegin(), 8286 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8287 << SS.getScopeRep() 8288 << cast<CXXRecordDecl>(CurContext) 8289 << SS.getRange(); 8290 return true; 8291 } 8292 8293 return false; 8294 } 8295 8296 // C++03 [namespace.udecl]p4: 8297 // A using-declaration used as a member-declaration shall refer 8298 // to a member of a base class of the class being defined [etc.]. 8299 8300 // Salient point: SS doesn't have to name a base class as long as 8301 // lookup only finds members from base classes. Therefore we can 8302 // diagnose here only if we can prove that that can't happen, 8303 // i.e. if the class hierarchies provably don't intersect. 8304 8305 // TODO: it would be nice if "definitely valid" results were cached 8306 // in the UsingDecl and UsingShadowDecl so that these checks didn't 8307 // need to be repeated. 8308 8309 struct UserData { 8310 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 8311 8312 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 8313 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8314 Data->Bases.insert(Base); 8315 return true; 8316 } 8317 8318 bool hasDependentBases(const CXXRecordDecl *Class) { 8319 return !Class->forallBases(collect, this); 8320 } 8321 8322 /// Returns true if the base is dependent or is one of the 8323 /// accumulated base classes. 8324 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 8325 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8326 return !Data->Bases.count(Base); 8327 } 8328 8329 bool mightShareBases(const CXXRecordDecl *Class) { 8330 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 8331 } 8332 }; 8333 8334 UserData Data; 8335 8336 // Returns false if we find a dependent base. 8337 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 8338 return false; 8339 8340 // Returns false if the class has a dependent base or if it or one 8341 // of its bases is present in the base set of the current context. 8342 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 8343 return false; 8344 8345 Diag(SS.getRange().getBegin(), 8346 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8347 << SS.getScopeRep() 8348 << cast<CXXRecordDecl>(CurContext) 8349 << SS.getRange(); 8350 8351 return true; 8352 } 8353 8354 Decl *Sema::ActOnAliasDeclaration(Scope *S, 8355 AccessSpecifier AS, 8356 MultiTemplateParamsArg TemplateParamLists, 8357 SourceLocation UsingLoc, 8358 UnqualifiedId &Name, 8359 AttributeList *AttrList, 8360 TypeResult Type) { 8361 // Skip up to the relevant declaration scope. 8362 while (S->getFlags() & Scope::TemplateParamScope) 8363 S = S->getParent(); 8364 assert((S->getFlags() & Scope::DeclScope) && 8365 "got alias-declaration outside of declaration scope"); 8366 8367 if (Type.isInvalid()) 8368 return nullptr; 8369 8370 bool Invalid = false; 8371 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 8372 TypeSourceInfo *TInfo = nullptr; 8373 GetTypeFromParser(Type.get(), &TInfo); 8374 8375 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 8376 return nullptr; 8377 8378 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 8379 UPPC_DeclarationType)) { 8380 Invalid = true; 8381 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8382 TInfo->getTypeLoc().getBeginLoc()); 8383 } 8384 8385 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 8386 LookupName(Previous, S); 8387 8388 // Warn about shadowing the name of a template parameter. 8389 if (Previous.isSingleResult() && 8390 Previous.getFoundDecl()->isTemplateParameter()) { 8391 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8392 Previous.clear(); 8393 } 8394 8395 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8396 "name in alias declaration must be an identifier"); 8397 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8398 Name.StartLocation, 8399 Name.Identifier, TInfo); 8400 8401 NewTD->setAccess(AS); 8402 8403 if (Invalid) 8404 NewTD->setInvalidDecl(); 8405 8406 ProcessDeclAttributeList(S, NewTD, AttrList); 8407 8408 CheckTypedefForVariablyModifiedType(S, NewTD); 8409 Invalid |= NewTD->isInvalidDecl(); 8410 8411 bool Redeclaration = false; 8412 8413 NamedDecl *NewND; 8414 if (TemplateParamLists.size()) { 8415 TypeAliasTemplateDecl *OldDecl = nullptr; 8416 TemplateParameterList *OldTemplateParams = nullptr; 8417 8418 if (TemplateParamLists.size() != 1) { 8419 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8420 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8421 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8422 } 8423 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8424 8425 // Only consider previous declarations in the same scope. 8426 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8427 /*ExplicitInstantiationOrSpecialization*/false); 8428 if (!Previous.empty()) { 8429 Redeclaration = true; 8430 8431 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8432 if (!OldDecl && !Invalid) { 8433 Diag(UsingLoc, diag::err_redefinition_different_kind) 8434 << Name.Identifier; 8435 8436 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8437 if (OldD->getLocation().isValid()) 8438 Diag(OldD->getLocation(), diag::note_previous_definition); 8439 8440 Invalid = true; 8441 } 8442 8443 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8444 if (TemplateParameterListsAreEqual(TemplateParams, 8445 OldDecl->getTemplateParameters(), 8446 /*Complain=*/true, 8447 TPL_TemplateMatch)) 8448 OldTemplateParams = OldDecl->getTemplateParameters(); 8449 else 8450 Invalid = true; 8451 8452 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8453 if (!Invalid && 8454 !Context.hasSameType(OldTD->getUnderlyingType(), 8455 NewTD->getUnderlyingType())) { 8456 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8457 // but we can't reasonably accept it. 8458 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8459 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8460 if (OldTD->getLocation().isValid()) 8461 Diag(OldTD->getLocation(), diag::note_previous_definition); 8462 Invalid = true; 8463 } 8464 } 8465 } 8466 8467 // Merge any previous default template arguments into our parameters, 8468 // and check the parameter list. 8469 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8470 TPC_TypeAliasTemplate)) 8471 return nullptr; 8472 8473 TypeAliasTemplateDecl *NewDecl = 8474 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8475 Name.Identifier, TemplateParams, 8476 NewTD); 8477 NewTD->setDescribedAliasTemplate(NewDecl); 8478 8479 NewDecl->setAccess(AS); 8480 8481 if (Invalid) 8482 NewDecl->setInvalidDecl(); 8483 else if (OldDecl) 8484 NewDecl->setPreviousDecl(OldDecl); 8485 8486 NewND = NewDecl; 8487 } else { 8488 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8489 NewND = NewTD; 8490 } 8491 8492 if (!Redeclaration) 8493 PushOnScopeChains(NewND, S); 8494 8495 ActOnDocumentableDecl(NewND); 8496 return NewND; 8497 } 8498 8499 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 8500 SourceLocation AliasLoc, 8501 IdentifierInfo *Alias, CXXScopeSpec &SS, 8502 SourceLocation IdentLoc, 8503 IdentifierInfo *Ident) { 8504 8505 // Lookup the namespace name. 8506 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8507 LookupParsedName(R, S, &SS); 8508 8509 if (R.isAmbiguous()) 8510 return nullptr; 8511 8512 if (R.empty()) { 8513 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8514 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8515 return nullptr; 8516 } 8517 } 8518 assert(!R.isAmbiguous() && !R.empty()); 8519 8520 // Check if we have a previous declaration with the same name. 8521 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 8522 ForRedeclaration); 8523 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 8524 PrevDecl = nullptr; 8525 8526 NamedDecl *ND = R.getFoundDecl(); 8527 8528 if (PrevDecl) { 8529 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 8530 // We already have an alias with the same name that points to the same 8531 // namespace; check that it matches. 8532 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 8533 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 8534 << Alias; 8535 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias) 8536 << AD->getNamespace(); 8537 return nullptr; 8538 } 8539 } else { 8540 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) 8541 ? diag::err_redefinition 8542 : diag::err_redefinition_different_kind; 8543 Diag(AliasLoc, DiagID) << Alias; 8544 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8545 return nullptr; 8546 } 8547 } 8548 8549 // The use of a nested name specifier may trigger deprecation warnings. 8550 DiagnoseUseOfDecl(ND, IdentLoc); 8551 8552 NamespaceAliasDecl *AliasDecl = 8553 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8554 Alias, SS.getWithLocInContext(Context), 8555 IdentLoc, ND); 8556 if (PrevDecl) 8557 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl)); 8558 8559 PushOnScopeChains(AliasDecl, S); 8560 return AliasDecl; 8561 } 8562 8563 Sema::ImplicitExceptionSpecification 8564 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8565 CXXMethodDecl *MD) { 8566 CXXRecordDecl *ClassDecl = MD->getParent(); 8567 8568 // C++ [except.spec]p14: 8569 // An implicitly declared special member function (Clause 12) shall have an 8570 // exception-specification. [...] 8571 ImplicitExceptionSpecification ExceptSpec(*this); 8572 if (ClassDecl->isInvalidDecl()) 8573 return ExceptSpec; 8574 8575 // Direct base-class constructors. 8576 for (const auto &B : ClassDecl->bases()) { 8577 if (B.isVirtual()) // Handled below. 8578 continue; 8579 8580 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8581 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8582 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8583 // If this is a deleted function, add it anyway. This might be conformant 8584 // with the standard. This might not. I'm not sure. It might not matter. 8585 if (Constructor) 8586 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8587 } 8588 } 8589 8590 // Virtual base-class constructors. 8591 for (const auto &B : ClassDecl->vbases()) { 8592 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8593 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8594 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8595 // If this is a deleted function, add it anyway. This might be conformant 8596 // with the standard. This might not. I'm not sure. It might not matter. 8597 if (Constructor) 8598 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8599 } 8600 } 8601 8602 // Field constructors. 8603 for (const auto *F : ClassDecl->fields()) { 8604 if (F->hasInClassInitializer()) { 8605 if (Expr *E = F->getInClassInitializer()) 8606 ExceptSpec.CalledExpr(E); 8607 } else if (const RecordType *RecordTy 8608 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8609 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8610 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8611 // If this is a deleted function, add it anyway. This might be conformant 8612 // with the standard. This might not. I'm not sure. It might not matter. 8613 // In particular, the problem is that this function never gets called. It 8614 // might just be ill-formed because this function attempts to refer to 8615 // a deleted function here. 8616 if (Constructor) 8617 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8618 } 8619 } 8620 8621 return ExceptSpec; 8622 } 8623 8624 Sema::ImplicitExceptionSpecification 8625 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8626 CXXRecordDecl *ClassDecl = CD->getParent(); 8627 8628 // C++ [except.spec]p14: 8629 // An inheriting constructor [...] shall have an exception-specification. [...] 8630 ImplicitExceptionSpecification ExceptSpec(*this); 8631 if (ClassDecl->isInvalidDecl()) 8632 return ExceptSpec; 8633 8634 // Inherited constructor. 8635 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8636 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8637 // FIXME: Copying or moving the parameters could add extra exceptions to the 8638 // set, as could the default arguments for the inherited constructor. This 8639 // will be addressed when we implement the resolution of core issue 1351. 8640 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8641 8642 // Direct base-class constructors. 8643 for (const auto &B : ClassDecl->bases()) { 8644 if (B.isVirtual()) // Handled below. 8645 continue; 8646 8647 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8648 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8649 if (BaseClassDecl == InheritedDecl) 8650 continue; 8651 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8652 if (Constructor) 8653 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8654 } 8655 } 8656 8657 // Virtual base-class constructors. 8658 for (const auto &B : ClassDecl->vbases()) { 8659 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8660 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8661 if (BaseClassDecl == InheritedDecl) 8662 continue; 8663 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8664 if (Constructor) 8665 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8666 } 8667 } 8668 8669 // Field constructors. 8670 for (const auto *F : ClassDecl->fields()) { 8671 if (F->hasInClassInitializer()) { 8672 if (Expr *E = F->getInClassInitializer()) 8673 ExceptSpec.CalledExpr(E); 8674 } else if (const RecordType *RecordTy 8675 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8676 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8677 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8678 if (Constructor) 8679 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8680 } 8681 } 8682 8683 return ExceptSpec; 8684 } 8685 8686 namespace { 8687 /// RAII object to register a special member as being currently declared. 8688 struct DeclaringSpecialMember { 8689 Sema &S; 8690 Sema::SpecialMemberDecl D; 8691 bool WasAlreadyBeingDeclared; 8692 8693 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8694 : S(S), D(RD, CSM) { 8695 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 8696 if (WasAlreadyBeingDeclared) 8697 // This almost never happens, but if it does, ensure that our cache 8698 // doesn't contain a stale result. 8699 S.SpecialMemberCache.clear(); 8700 8701 // FIXME: Register a note to be produced if we encounter an error while 8702 // declaring the special member. 8703 } 8704 ~DeclaringSpecialMember() { 8705 if (!WasAlreadyBeingDeclared) 8706 S.SpecialMembersBeingDeclared.erase(D); 8707 } 8708 8709 /// \brief Are we already trying to declare this special member? 8710 bool isAlreadyBeingDeclared() const { 8711 return WasAlreadyBeingDeclared; 8712 } 8713 }; 8714 } 8715 8716 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8717 CXXRecordDecl *ClassDecl) { 8718 // C++ [class.ctor]p5: 8719 // A default constructor for a class X is a constructor of class X 8720 // that can be called without an argument. If there is no 8721 // user-declared constructor for class X, a default constructor is 8722 // implicitly declared. An implicitly-declared default constructor 8723 // is an inline public member of its class. 8724 assert(ClassDecl->needsImplicitDefaultConstructor() && 8725 "Should not build implicit default constructor!"); 8726 8727 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8728 if (DSM.isAlreadyBeingDeclared()) 8729 return nullptr; 8730 8731 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8732 CXXDefaultConstructor, 8733 false); 8734 8735 // Create the actual constructor declaration. 8736 CanQualType ClassType 8737 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8738 SourceLocation ClassLoc = ClassDecl->getLocation(); 8739 DeclarationName Name 8740 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8741 DeclarationNameInfo NameInfo(Name, ClassLoc); 8742 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8743 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8744 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8745 /*isImplicitlyDeclared=*/true, Constexpr); 8746 DefaultCon->setAccess(AS_public); 8747 DefaultCon->setDefaulted(); 8748 8749 if (getLangOpts().CUDA) { 8750 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 8751 DefaultCon, 8752 /* ConstRHS */ false, 8753 /* Diagnose */ false); 8754 } 8755 8756 // Build an exception specification pointing back at this constructor. 8757 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8758 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8759 8760 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8761 // constructors is easy to compute. 8762 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8763 8764 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8765 SetDeclDeleted(DefaultCon, ClassLoc); 8766 8767 // Note that we have declared this constructor. 8768 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8769 8770 if (Scope *S = getScopeForContext(ClassDecl)) 8771 PushOnScopeChains(DefaultCon, S, false); 8772 ClassDecl->addDecl(DefaultCon); 8773 8774 return DefaultCon; 8775 } 8776 8777 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8778 CXXConstructorDecl *Constructor) { 8779 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8780 !Constructor->doesThisDeclarationHaveABody() && 8781 !Constructor->isDeleted()) && 8782 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8783 8784 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8785 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8786 8787 SynthesizedFunctionScope Scope(*this, Constructor); 8788 DiagnosticErrorTrap Trap(Diags); 8789 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8790 Trap.hasErrorOccurred()) { 8791 Diag(CurrentLocation, diag::note_member_synthesized_at) 8792 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8793 Constructor->setInvalidDecl(); 8794 return; 8795 } 8796 8797 // The exception specification is needed because we are defining the 8798 // function. 8799 ResolveExceptionSpec(CurrentLocation, 8800 Constructor->getType()->castAs<FunctionProtoType>()); 8801 8802 SourceLocation Loc = Constructor->getLocEnd().isValid() 8803 ? Constructor->getLocEnd() 8804 : Constructor->getLocation(); 8805 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8806 8807 Constructor->markUsed(Context); 8808 MarkVTableUsed(CurrentLocation, ClassDecl); 8809 8810 if (ASTMutationListener *L = getASTMutationListener()) { 8811 L->CompletedImplicitDefinition(Constructor); 8812 } 8813 8814 DiagnoseUninitializedFields(*this, Constructor); 8815 } 8816 8817 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8818 // Perform any delayed checks on exception specifications. 8819 CheckDelayedMemberExceptionSpecs(); 8820 } 8821 8822 namespace { 8823 /// Information on inheriting constructors to declare. 8824 class InheritingConstructorInfo { 8825 public: 8826 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8827 : SemaRef(SemaRef), Derived(Derived) { 8828 // Mark the constructors that we already have in the derived class. 8829 // 8830 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8831 // unless there is a user-declared constructor with the same signature in 8832 // the class where the using-declaration appears. 8833 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8834 } 8835 8836 void inheritAll(CXXRecordDecl *RD) { 8837 visitAll(RD, &InheritingConstructorInfo::inherit); 8838 } 8839 8840 private: 8841 /// Information about an inheriting constructor. 8842 struct InheritingConstructor { 8843 InheritingConstructor() 8844 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 8845 8846 /// If \c true, a constructor with this signature is already declared 8847 /// in the derived class. 8848 bool DeclaredInDerived; 8849 8850 /// The constructor which is inherited. 8851 const CXXConstructorDecl *BaseCtor; 8852 8853 /// The derived constructor we declared. 8854 CXXConstructorDecl *DerivedCtor; 8855 }; 8856 8857 /// Inheriting constructors with a given canonical type. There can be at 8858 /// most one such non-template constructor, and any number of templated 8859 /// constructors. 8860 struct InheritingConstructorsForType { 8861 InheritingConstructor NonTemplate; 8862 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8863 Templates; 8864 8865 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8866 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8867 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8868 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8869 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8870 false, S.TPL_TemplateMatch)) 8871 return Templates[I].second; 8872 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8873 return Templates.back().second; 8874 } 8875 8876 return NonTemplate; 8877 } 8878 }; 8879 8880 /// Get or create the inheriting constructor record for a constructor. 8881 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8882 QualType CtorType) { 8883 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8884 .getEntry(SemaRef, Ctor); 8885 } 8886 8887 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8888 8889 /// Process all constructors for a class. 8890 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8891 for (const auto *Ctor : RD->ctors()) 8892 (this->*Callback)(Ctor); 8893 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8894 I(RD->decls_begin()), E(RD->decls_end()); 8895 I != E; ++I) { 8896 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8897 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8898 (this->*Callback)(CD); 8899 } 8900 } 8901 8902 /// Note that a constructor (or constructor template) was declared in Derived. 8903 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8904 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8905 } 8906 8907 /// Inherit a single constructor. 8908 void inherit(const CXXConstructorDecl *Ctor) { 8909 const FunctionProtoType *CtorType = 8910 Ctor->getType()->castAs<FunctionProtoType>(); 8911 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes(); 8912 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8913 8914 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8915 8916 // Core issue (no number yet): the ellipsis is always discarded. 8917 if (EPI.Variadic) { 8918 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8919 SemaRef.Diag(Ctor->getLocation(), 8920 diag::note_using_decl_constructor_ellipsis); 8921 EPI.Variadic = false; 8922 } 8923 8924 // Declare a constructor for each number of parameters. 8925 // 8926 // C++11 [class.inhctor]p1: 8927 // The candidate set of inherited constructors from the class X named in 8928 // the using-declaration consists of [... modulo defects ...] for each 8929 // constructor or constructor template of X, the set of constructors or 8930 // constructor templates that results from omitting any ellipsis parameter 8931 // specification and successively omitting parameters with a default 8932 // argument from the end of the parameter-type-list 8933 unsigned MinParams = minParamsToInherit(Ctor); 8934 unsigned Params = Ctor->getNumParams(); 8935 if (Params >= MinParams) { 8936 do 8937 declareCtor(UsingLoc, Ctor, 8938 SemaRef.Context.getFunctionType( 8939 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 8940 while (Params > MinParams && 8941 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8942 } 8943 } 8944 8945 /// Find the using-declaration which specified that we should inherit the 8946 /// constructors of \p Base. 8947 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8948 // No fancy lookup required; just look for the base constructor name 8949 // directly within the derived class. 8950 ASTContext &Context = SemaRef.Context; 8951 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8952 Context.getCanonicalType(Context.getRecordType(Base))); 8953 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8954 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8955 } 8956 8957 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8958 // C++11 [class.inhctor]p3: 8959 // [F]or each constructor template in the candidate set of inherited 8960 // constructors, a constructor template is implicitly declared 8961 if (Ctor->getDescribedFunctionTemplate()) 8962 return 0; 8963 8964 // For each non-template constructor in the candidate set of inherited 8965 // constructors other than a constructor having no parameters or a 8966 // copy/move constructor having a single parameter, a constructor is 8967 // implicitly declared [...] 8968 if (Ctor->getNumParams() == 0) 8969 return 1; 8970 if (Ctor->isCopyOrMoveConstructor()) 8971 return 2; 8972 8973 // Per discussion on core reflector, never inherit a constructor which 8974 // would become a default, copy, or move constructor of Derived either. 8975 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8976 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8977 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8978 } 8979 8980 /// Declare a single inheriting constructor, inheriting the specified 8981 /// constructor, with the given type. 8982 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8983 QualType DerivedType) { 8984 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8985 8986 // C++11 [class.inhctor]p3: 8987 // ... a constructor is implicitly declared with the same constructor 8988 // characteristics unless there is a user-declared constructor with 8989 // the same signature in the class where the using-declaration appears 8990 if (Entry.DeclaredInDerived) 8991 return; 8992 8993 // C++11 [class.inhctor]p7: 8994 // If two using-declarations declare inheriting constructors with the 8995 // same signature, the program is ill-formed 8996 if (Entry.DerivedCtor) { 8997 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8998 // Only diagnose this once per constructor. 8999 if (Entry.DerivedCtor->isInvalidDecl()) 9000 return; 9001 Entry.DerivedCtor->setInvalidDecl(); 9002 9003 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 9004 SemaRef.Diag(BaseCtor->getLocation(), 9005 diag::note_using_decl_constructor_conflict_current_ctor); 9006 SemaRef.Diag(Entry.BaseCtor->getLocation(), 9007 diag::note_using_decl_constructor_conflict_previous_ctor); 9008 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 9009 diag::note_using_decl_constructor_conflict_previous_using); 9010 } else { 9011 // Core issue (no number): if the same inheriting constructor is 9012 // produced by multiple base class constructors from the same base 9013 // class, the inheriting constructor is defined as deleted. 9014 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 9015 } 9016 9017 return; 9018 } 9019 9020 ASTContext &Context = SemaRef.Context; 9021 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 9022 Context.getCanonicalType(Context.getRecordType(Derived))); 9023 DeclarationNameInfo NameInfo(Name, UsingLoc); 9024 9025 TemplateParameterList *TemplateParams = nullptr; 9026 if (const FunctionTemplateDecl *FTD = 9027 BaseCtor->getDescribedFunctionTemplate()) { 9028 TemplateParams = FTD->getTemplateParameters(); 9029 // We're reusing template parameters from a different DeclContext. This 9030 // is questionable at best, but works out because the template depth in 9031 // both places is guaranteed to be 0. 9032 // FIXME: Rebuild the template parameters in the new context, and 9033 // transform the function type to refer to them. 9034 } 9035 9036 // Build type source info pointing at the using-declaration. This is 9037 // required by template instantiation. 9038 TypeSourceInfo *TInfo = 9039 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 9040 FunctionProtoTypeLoc ProtoLoc = 9041 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 9042 9043 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 9044 Context, Derived, UsingLoc, NameInfo, DerivedType, 9045 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 9046 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 9047 9048 // Build an unevaluated exception specification for this constructor. 9049 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 9050 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9051 EPI.ExceptionSpec.Type = EST_Unevaluated; 9052 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 9053 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 9054 FPT->getParamTypes(), EPI)); 9055 9056 // Build the parameter declarations. 9057 SmallVector<ParmVarDecl *, 16> ParamDecls; 9058 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 9059 TypeSourceInfo *TInfo = 9060 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 9061 ParmVarDecl *PD = ParmVarDecl::Create( 9062 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 9063 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 9064 PD->setScopeInfo(0, I); 9065 PD->setImplicit(); 9066 ParamDecls.push_back(PD); 9067 ProtoLoc.setParam(I, PD); 9068 } 9069 9070 // Set up the new constructor. 9071 DerivedCtor->setAccess(BaseCtor->getAccess()); 9072 DerivedCtor->setParams(ParamDecls); 9073 DerivedCtor->setInheritedConstructor(BaseCtor); 9074 if (BaseCtor->isDeleted()) 9075 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 9076 9077 // If this is a constructor template, build the template declaration. 9078 if (TemplateParams) { 9079 FunctionTemplateDecl *DerivedTemplate = 9080 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 9081 TemplateParams, DerivedCtor); 9082 DerivedTemplate->setAccess(BaseCtor->getAccess()); 9083 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 9084 Derived->addDecl(DerivedTemplate); 9085 } else { 9086 Derived->addDecl(DerivedCtor); 9087 } 9088 9089 Entry.BaseCtor = BaseCtor; 9090 Entry.DerivedCtor = DerivedCtor; 9091 } 9092 9093 Sema &SemaRef; 9094 CXXRecordDecl *Derived; 9095 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 9096 MapType Map; 9097 }; 9098 } 9099 9100 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 9101 // Defer declaring the inheriting constructors until the class is 9102 // instantiated. 9103 if (ClassDecl->isDependentContext()) 9104 return; 9105 9106 // Find base classes from which we might inherit constructors. 9107 SmallVector<CXXRecordDecl*, 4> InheritedBases; 9108 for (const auto &BaseIt : ClassDecl->bases()) 9109 if (BaseIt.getInheritConstructors()) 9110 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 9111 9112 // Go no further if we're not inheriting any constructors. 9113 if (InheritedBases.empty()) 9114 return; 9115 9116 // Declare the inherited constructors. 9117 InheritingConstructorInfo ICI(*this, ClassDecl); 9118 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 9119 ICI.inheritAll(InheritedBases[I]); 9120 } 9121 9122 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 9123 CXXConstructorDecl *Constructor) { 9124 CXXRecordDecl *ClassDecl = Constructor->getParent(); 9125 assert(Constructor->getInheritedConstructor() && 9126 !Constructor->doesThisDeclarationHaveABody() && 9127 !Constructor->isDeleted()); 9128 9129 SynthesizedFunctionScope Scope(*this, Constructor); 9130 DiagnosticErrorTrap Trap(Diags); 9131 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 9132 Trap.hasErrorOccurred()) { 9133 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 9134 << Context.getTagDeclType(ClassDecl); 9135 Constructor->setInvalidDecl(); 9136 return; 9137 } 9138 9139 SourceLocation Loc = Constructor->getLocation(); 9140 Constructor->setBody(new (Context) CompoundStmt(Loc)); 9141 9142 Constructor->markUsed(Context); 9143 MarkVTableUsed(CurrentLocation, ClassDecl); 9144 9145 if (ASTMutationListener *L = getASTMutationListener()) { 9146 L->CompletedImplicitDefinition(Constructor); 9147 } 9148 } 9149 9150 9151 Sema::ImplicitExceptionSpecification 9152 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 9153 CXXRecordDecl *ClassDecl = MD->getParent(); 9154 9155 // C++ [except.spec]p14: 9156 // An implicitly declared special member function (Clause 12) shall have 9157 // an exception-specification. 9158 ImplicitExceptionSpecification ExceptSpec(*this); 9159 if (ClassDecl->isInvalidDecl()) 9160 return ExceptSpec; 9161 9162 // Direct base-class destructors. 9163 for (const auto &B : ClassDecl->bases()) { 9164 if (B.isVirtual()) // Handled below. 9165 continue; 9166 9167 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9168 ExceptSpec.CalledDecl(B.getLocStart(), 9169 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9170 } 9171 9172 // Virtual base-class destructors. 9173 for (const auto &B : ClassDecl->vbases()) { 9174 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9175 ExceptSpec.CalledDecl(B.getLocStart(), 9176 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9177 } 9178 9179 // Field destructors. 9180 for (const auto *F : ClassDecl->fields()) { 9181 if (const RecordType *RecordTy 9182 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 9183 ExceptSpec.CalledDecl(F->getLocation(), 9184 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 9185 } 9186 9187 return ExceptSpec; 9188 } 9189 9190 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 9191 // C++ [class.dtor]p2: 9192 // If a class has no user-declared destructor, a destructor is 9193 // declared implicitly. An implicitly-declared destructor is an 9194 // inline public member of its class. 9195 assert(ClassDecl->needsImplicitDestructor()); 9196 9197 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 9198 if (DSM.isAlreadyBeingDeclared()) 9199 return nullptr; 9200 9201 // Create the actual destructor declaration. 9202 CanQualType ClassType 9203 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9204 SourceLocation ClassLoc = ClassDecl->getLocation(); 9205 DeclarationName Name 9206 = Context.DeclarationNames.getCXXDestructorName(ClassType); 9207 DeclarationNameInfo NameInfo(Name, ClassLoc); 9208 CXXDestructorDecl *Destructor 9209 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 9210 QualType(), nullptr, /*isInline=*/true, 9211 /*isImplicitlyDeclared=*/true); 9212 Destructor->setAccess(AS_public); 9213 Destructor->setDefaulted(); 9214 9215 if (getLangOpts().CUDA) { 9216 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 9217 Destructor, 9218 /* ConstRHS */ false, 9219 /* Diagnose */ false); 9220 } 9221 9222 // Build an exception specification pointing back at this destructor. 9223 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 9224 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9225 9226 AddOverriddenMethods(ClassDecl, Destructor); 9227 9228 // We don't need to use SpecialMemberIsTrivial here; triviality for 9229 // destructors is easy to compute. 9230 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 9231 9232 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 9233 SetDeclDeleted(Destructor, ClassLoc); 9234 9235 // Note that we have declared this destructor. 9236 ++ASTContext::NumImplicitDestructorsDeclared; 9237 9238 // Introduce this destructor into its scope. 9239 if (Scope *S = getScopeForContext(ClassDecl)) 9240 PushOnScopeChains(Destructor, S, false); 9241 ClassDecl->addDecl(Destructor); 9242 9243 return Destructor; 9244 } 9245 9246 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 9247 CXXDestructorDecl *Destructor) { 9248 assert((Destructor->isDefaulted() && 9249 !Destructor->doesThisDeclarationHaveABody() && 9250 !Destructor->isDeleted()) && 9251 "DefineImplicitDestructor - call it for implicit default dtor"); 9252 CXXRecordDecl *ClassDecl = Destructor->getParent(); 9253 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 9254 9255 if (Destructor->isInvalidDecl()) 9256 return; 9257 9258 SynthesizedFunctionScope Scope(*this, Destructor); 9259 9260 DiagnosticErrorTrap Trap(Diags); 9261 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9262 Destructor->getParent()); 9263 9264 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 9265 Diag(CurrentLocation, diag::note_member_synthesized_at) 9266 << CXXDestructor << Context.getTagDeclType(ClassDecl); 9267 9268 Destructor->setInvalidDecl(); 9269 return; 9270 } 9271 9272 // The exception specification is needed because we are defining the 9273 // function. 9274 ResolveExceptionSpec(CurrentLocation, 9275 Destructor->getType()->castAs<FunctionProtoType>()); 9276 9277 SourceLocation Loc = Destructor->getLocEnd().isValid() 9278 ? Destructor->getLocEnd() 9279 : Destructor->getLocation(); 9280 Destructor->setBody(new (Context) CompoundStmt(Loc)); 9281 Destructor->markUsed(Context); 9282 MarkVTableUsed(CurrentLocation, ClassDecl); 9283 9284 if (ASTMutationListener *L = getASTMutationListener()) { 9285 L->CompletedImplicitDefinition(Destructor); 9286 } 9287 } 9288 9289 /// \brief Perform any semantic analysis which needs to be delayed until all 9290 /// pending class member declarations have been parsed. 9291 void Sema::ActOnFinishCXXMemberDecls() { 9292 // If the context is an invalid C++ class, just suppress these checks. 9293 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 9294 if (Record->isInvalidDecl()) { 9295 DelayedDefaultedMemberExceptionSpecs.clear(); 9296 DelayedExceptionSpecChecks.clear(); 9297 return; 9298 } 9299 } 9300 } 9301 9302 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 9303 CXXDestructorDecl *Destructor) { 9304 assert(getLangOpts().CPlusPlus11 && 9305 "adjusting dtor exception specs was introduced in c++11"); 9306 9307 // C++11 [class.dtor]p3: 9308 // A declaration of a destructor that does not have an exception- 9309 // specification is implicitly considered to have the same exception- 9310 // specification as an implicit declaration. 9311 const FunctionProtoType *DtorType = Destructor->getType()-> 9312 getAs<FunctionProtoType>(); 9313 if (DtorType->hasExceptionSpec()) 9314 return; 9315 9316 // Replace the destructor's type, building off the existing one. Fortunately, 9317 // the only thing of interest in the destructor type is its extended info. 9318 // The return and arguments are fixed. 9319 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 9320 EPI.ExceptionSpec.Type = EST_Unevaluated; 9321 EPI.ExceptionSpec.SourceDecl = Destructor; 9322 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9323 9324 // FIXME: If the destructor has a body that could throw, and the newly created 9325 // spec doesn't allow exceptions, we should emit a warning, because this 9326 // change in behavior can break conforming C++03 programs at runtime. 9327 // However, we don't have a body or an exception specification yet, so it 9328 // needs to be done somewhere else. 9329 } 9330 9331 namespace { 9332 /// \brief An abstract base class for all helper classes used in building the 9333 // copy/move operators. These classes serve as factory functions and help us 9334 // avoid using the same Expr* in the AST twice. 9335 class ExprBuilder { 9336 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION; 9337 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION; 9338 9339 protected: 9340 static Expr *assertNotNull(Expr *E) { 9341 assert(E && "Expression construction must not fail."); 9342 return E; 9343 } 9344 9345 public: 9346 ExprBuilder() {} 9347 virtual ~ExprBuilder() {} 9348 9349 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 9350 }; 9351 9352 class RefBuilder: public ExprBuilder { 9353 VarDecl *Var; 9354 QualType VarType; 9355 9356 public: 9357 Expr *build(Sema &S, SourceLocation Loc) const override { 9358 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 9359 } 9360 9361 RefBuilder(VarDecl *Var, QualType VarType) 9362 : Var(Var), VarType(VarType) {} 9363 }; 9364 9365 class ThisBuilder: public ExprBuilder { 9366 public: 9367 Expr *build(Sema &S, SourceLocation Loc) const override { 9368 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 9369 } 9370 }; 9371 9372 class CastBuilder: public ExprBuilder { 9373 const ExprBuilder &Builder; 9374 QualType Type; 9375 ExprValueKind Kind; 9376 const CXXCastPath &Path; 9377 9378 public: 9379 Expr *build(Sema &S, SourceLocation Loc) const override { 9380 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 9381 CK_UncheckedDerivedToBase, Kind, 9382 &Path).get()); 9383 } 9384 9385 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 9386 const CXXCastPath &Path) 9387 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 9388 }; 9389 9390 class DerefBuilder: public ExprBuilder { 9391 const ExprBuilder &Builder; 9392 9393 public: 9394 Expr *build(Sema &S, SourceLocation Loc) const override { 9395 return assertNotNull( 9396 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 9397 } 9398 9399 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9400 }; 9401 9402 class MemberBuilder: public ExprBuilder { 9403 const ExprBuilder &Builder; 9404 QualType Type; 9405 CXXScopeSpec SS; 9406 bool IsArrow; 9407 LookupResult &MemberLookup; 9408 9409 public: 9410 Expr *build(Sema &S, SourceLocation Loc) const override { 9411 return assertNotNull(S.BuildMemberReferenceExpr( 9412 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9413 nullptr, MemberLookup, nullptr).get()); 9414 } 9415 9416 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9417 LookupResult &MemberLookup) 9418 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9419 MemberLookup(MemberLookup) {} 9420 }; 9421 9422 class MoveCastBuilder: public ExprBuilder { 9423 const ExprBuilder &Builder; 9424 9425 public: 9426 Expr *build(Sema &S, SourceLocation Loc) const override { 9427 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9428 } 9429 9430 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9431 }; 9432 9433 class LvalueConvBuilder: public ExprBuilder { 9434 const ExprBuilder &Builder; 9435 9436 public: 9437 Expr *build(Sema &S, SourceLocation Loc) const override { 9438 return assertNotNull( 9439 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9440 } 9441 9442 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9443 }; 9444 9445 class SubscriptBuilder: public ExprBuilder { 9446 const ExprBuilder &Base; 9447 const ExprBuilder &Index; 9448 9449 public: 9450 Expr *build(Sema &S, SourceLocation Loc) const override { 9451 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9452 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9453 } 9454 9455 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9456 : Base(Base), Index(Index) {} 9457 }; 9458 9459 } // end anonymous namespace 9460 9461 /// When generating a defaulted copy or move assignment operator, if a field 9462 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9463 /// do so. This optimization only applies for arrays of scalars, and for arrays 9464 /// of class type where the selected copy/move-assignment operator is trivial. 9465 static StmtResult 9466 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9467 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9468 // Compute the size of the memory buffer to be copied. 9469 QualType SizeType = S.Context.getSizeType(); 9470 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9471 S.Context.getTypeSizeInChars(T).getQuantity()); 9472 9473 // Take the address of the field references for "from" and "to". We 9474 // directly construct UnaryOperators here because semantic analysis 9475 // does not permit us to take the address of an xvalue. 9476 Expr *From = FromB.build(S, Loc); 9477 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9478 S.Context.getPointerType(From->getType()), 9479 VK_RValue, OK_Ordinary, Loc); 9480 Expr *To = ToB.build(S, Loc); 9481 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9482 S.Context.getPointerType(To->getType()), 9483 VK_RValue, OK_Ordinary, Loc); 9484 9485 const Type *E = T->getBaseElementTypeUnsafe(); 9486 bool NeedsCollectableMemCpy = 9487 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9488 9489 // Create a reference to the __builtin_objc_memmove_collectable function 9490 StringRef MemCpyName = NeedsCollectableMemCpy ? 9491 "__builtin_objc_memmove_collectable" : 9492 "__builtin_memcpy"; 9493 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9494 Sema::LookupOrdinaryName); 9495 S.LookupName(R, S.TUScope, true); 9496 9497 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9498 if (!MemCpy) 9499 // Something went horribly wrong earlier, and we will have complained 9500 // about it. 9501 return StmtError(); 9502 9503 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9504 VK_RValue, Loc, nullptr); 9505 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9506 9507 Expr *CallArgs[] = { 9508 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9509 }; 9510 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9511 Loc, CallArgs, Loc); 9512 9513 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9514 return Call.getAs<Stmt>(); 9515 } 9516 9517 /// \brief Builds a statement that copies/moves the given entity from \p From to 9518 /// \c To. 9519 /// 9520 /// This routine is used to copy/move the members of a class with an 9521 /// implicitly-declared copy/move assignment operator. When the entities being 9522 /// copied are arrays, this routine builds for loops to copy them. 9523 /// 9524 /// \param S The Sema object used for type-checking. 9525 /// 9526 /// \param Loc The location where the implicit copy/move is being generated. 9527 /// 9528 /// \param T The type of the expressions being copied/moved. Both expressions 9529 /// must have this type. 9530 /// 9531 /// \param To The expression we are copying/moving to. 9532 /// 9533 /// \param From The expression we are copying/moving from. 9534 /// 9535 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9536 /// Otherwise, it's a non-static member subobject. 9537 /// 9538 /// \param Copying Whether we're copying or moving. 9539 /// 9540 /// \param Depth Internal parameter recording the depth of the recursion. 9541 /// 9542 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9543 /// if a memcpy should be used instead. 9544 static StmtResult 9545 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9546 const ExprBuilder &To, const ExprBuilder &From, 9547 bool CopyingBaseSubobject, bool Copying, 9548 unsigned Depth = 0) { 9549 // C++11 [class.copy]p28: 9550 // Each subobject is assigned in the manner appropriate to its type: 9551 // 9552 // - if the subobject is of class type, as if by a call to operator= with 9553 // the subobject as the object expression and the corresponding 9554 // subobject of x as a single function argument (as if by explicit 9555 // qualification; that is, ignoring any possible virtual overriding 9556 // functions in more derived classes); 9557 // 9558 // C++03 [class.copy]p13: 9559 // - if the subobject is of class type, the copy assignment operator for 9560 // the class is used (as if by explicit qualification; that is, 9561 // ignoring any possible virtual overriding functions in more derived 9562 // classes); 9563 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9564 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9565 9566 // Look for operator=. 9567 DeclarationName Name 9568 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9569 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9570 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9571 9572 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9573 // operator. 9574 if (!S.getLangOpts().CPlusPlus11) { 9575 LookupResult::Filter F = OpLookup.makeFilter(); 9576 while (F.hasNext()) { 9577 NamedDecl *D = F.next(); 9578 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9579 if (Method->isCopyAssignmentOperator() || 9580 (!Copying && Method->isMoveAssignmentOperator())) 9581 continue; 9582 9583 F.erase(); 9584 } 9585 F.done(); 9586 } 9587 9588 // Suppress the protected check (C++ [class.protected]) for each of the 9589 // assignment operators we found. This strange dance is required when 9590 // we're assigning via a base classes's copy-assignment operator. To 9591 // ensure that we're getting the right base class subobject (without 9592 // ambiguities), we need to cast "this" to that subobject type; to 9593 // ensure that we don't go through the virtual call mechanism, we need 9594 // to qualify the operator= name with the base class (see below). However, 9595 // this means that if the base class has a protected copy assignment 9596 // operator, the protected member access check will fail. So, we 9597 // rewrite "protected" access to "public" access in this case, since we 9598 // know by construction that we're calling from a derived class. 9599 if (CopyingBaseSubobject) { 9600 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9601 L != LEnd; ++L) { 9602 if (L.getAccess() == AS_protected) 9603 L.setAccess(AS_public); 9604 } 9605 } 9606 9607 // Create the nested-name-specifier that will be used to qualify the 9608 // reference to operator=; this is required to suppress the virtual 9609 // call mechanism. 9610 CXXScopeSpec SS; 9611 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9612 SS.MakeTrivial(S.Context, 9613 NestedNameSpecifier::Create(S.Context, nullptr, false, 9614 CanonicalT), 9615 Loc); 9616 9617 // Create the reference to operator=. 9618 ExprResult OpEqualRef 9619 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9620 SS, /*TemplateKWLoc=*/SourceLocation(), 9621 /*FirstQualifierInScope=*/nullptr, 9622 OpLookup, 9623 /*TemplateArgs=*/nullptr, 9624 /*SuppressQualifierCheck=*/true); 9625 if (OpEqualRef.isInvalid()) 9626 return StmtError(); 9627 9628 // Build the call to the assignment operator. 9629 9630 Expr *FromInst = From.build(S, Loc); 9631 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9632 OpEqualRef.getAs<Expr>(), 9633 Loc, FromInst, Loc); 9634 if (Call.isInvalid()) 9635 return StmtError(); 9636 9637 // If we built a call to a trivial 'operator=' while copying an array, 9638 // bail out. We'll replace the whole shebang with a memcpy. 9639 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9640 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9641 return StmtResult((Stmt*)nullptr); 9642 9643 // Convert to an expression-statement, and clean up any produced 9644 // temporaries. 9645 return S.ActOnExprStmt(Call); 9646 } 9647 9648 // - if the subobject is of scalar type, the built-in assignment 9649 // operator is used. 9650 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9651 if (!ArrayTy) { 9652 ExprResult Assignment = S.CreateBuiltinBinOp( 9653 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9654 if (Assignment.isInvalid()) 9655 return StmtError(); 9656 return S.ActOnExprStmt(Assignment); 9657 } 9658 9659 // - if the subobject is an array, each element is assigned, in the 9660 // manner appropriate to the element type; 9661 9662 // Construct a loop over the array bounds, e.g., 9663 // 9664 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9665 // 9666 // that will copy each of the array elements. 9667 QualType SizeType = S.Context.getSizeType(); 9668 9669 // Create the iteration variable. 9670 IdentifierInfo *IterationVarName = nullptr; 9671 { 9672 SmallString<8> Str; 9673 llvm::raw_svector_ostream OS(Str); 9674 OS << "__i" << Depth; 9675 IterationVarName = &S.Context.Idents.get(OS.str()); 9676 } 9677 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9678 IterationVarName, SizeType, 9679 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9680 SC_None); 9681 9682 // Initialize the iteration variable to zero. 9683 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9684 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9685 9686 // Creates a reference to the iteration variable. 9687 RefBuilder IterationVarRef(IterationVar, SizeType); 9688 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9689 9690 // Create the DeclStmt that holds the iteration variable. 9691 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9692 9693 // Subscript the "from" and "to" expressions with the iteration variable. 9694 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9695 MoveCastBuilder FromIndexMove(FromIndexCopy); 9696 const ExprBuilder *FromIndex; 9697 if (Copying) 9698 FromIndex = &FromIndexCopy; 9699 else 9700 FromIndex = &FromIndexMove; 9701 9702 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9703 9704 // Build the copy/move for an individual element of the array. 9705 StmtResult Copy = 9706 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9707 ToIndex, *FromIndex, CopyingBaseSubobject, 9708 Copying, Depth + 1); 9709 // Bail out if copying fails or if we determined that we should use memcpy. 9710 if (Copy.isInvalid() || !Copy.get()) 9711 return Copy; 9712 9713 // Create the comparison against the array bound. 9714 llvm::APInt Upper 9715 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9716 Expr *Comparison 9717 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9718 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9719 BO_NE, S.Context.BoolTy, 9720 VK_RValue, OK_Ordinary, Loc, false); 9721 9722 // Create the pre-increment of the iteration variable. 9723 Expr *Increment 9724 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9725 SizeType, VK_LValue, OK_Ordinary, Loc); 9726 9727 // Construct the loop that copies all elements of this array. 9728 return S.ActOnForStmt(Loc, Loc, InitStmt, 9729 S.MakeFullExpr(Comparison), 9730 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9731 Loc, Copy.get()); 9732 } 9733 9734 static StmtResult 9735 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9736 const ExprBuilder &To, const ExprBuilder &From, 9737 bool CopyingBaseSubobject, bool Copying) { 9738 // Maybe we should use a memcpy? 9739 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9740 T.isTriviallyCopyableType(S.Context)) 9741 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9742 9743 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9744 CopyingBaseSubobject, 9745 Copying, 0)); 9746 9747 // If we ended up picking a trivial assignment operator for an array of a 9748 // non-trivially-copyable class type, just emit a memcpy. 9749 if (!Result.isInvalid() && !Result.get()) 9750 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9751 9752 return Result; 9753 } 9754 9755 Sema::ImplicitExceptionSpecification 9756 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9757 CXXRecordDecl *ClassDecl = MD->getParent(); 9758 9759 ImplicitExceptionSpecification ExceptSpec(*this); 9760 if (ClassDecl->isInvalidDecl()) 9761 return ExceptSpec; 9762 9763 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9764 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9765 unsigned ArgQuals = 9766 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9767 9768 // C++ [except.spec]p14: 9769 // An implicitly declared special member function (Clause 12) shall have an 9770 // exception-specification. [...] 9771 9772 // It is unspecified whether or not an implicit copy assignment operator 9773 // attempts to deduplicate calls to assignment operators of virtual bases are 9774 // made. As such, this exception specification is effectively unspecified. 9775 // Based on a similar decision made for constness in C++0x, we're erring on 9776 // the side of assuming such calls to be made regardless of whether they 9777 // actually happen. 9778 for (const auto &Base : ClassDecl->bases()) { 9779 if (Base.isVirtual()) 9780 continue; 9781 9782 CXXRecordDecl *BaseClassDecl 9783 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9784 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9785 ArgQuals, false, 0)) 9786 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9787 } 9788 9789 for (const auto &Base : ClassDecl->vbases()) { 9790 CXXRecordDecl *BaseClassDecl 9791 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9792 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9793 ArgQuals, false, 0)) 9794 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9795 } 9796 9797 for (const auto *Field : ClassDecl->fields()) { 9798 QualType FieldType = Context.getBaseElementType(Field->getType()); 9799 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9800 if (CXXMethodDecl *CopyAssign = 9801 LookupCopyingAssignment(FieldClassDecl, 9802 ArgQuals | FieldType.getCVRQualifiers(), 9803 false, 0)) 9804 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9805 } 9806 } 9807 9808 return ExceptSpec; 9809 } 9810 9811 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9812 // Note: The following rules are largely analoguous to the copy 9813 // constructor rules. Note that virtual bases are not taken into account 9814 // for determining the argument type of the operator. Note also that 9815 // operators taking an object instead of a reference are allowed. 9816 assert(ClassDecl->needsImplicitCopyAssignment()); 9817 9818 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9819 if (DSM.isAlreadyBeingDeclared()) 9820 return nullptr; 9821 9822 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9823 QualType RetType = Context.getLValueReferenceType(ArgType); 9824 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9825 if (Const) 9826 ArgType = ArgType.withConst(); 9827 ArgType = Context.getLValueReferenceType(ArgType); 9828 9829 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9830 CXXCopyAssignment, 9831 Const); 9832 9833 // An implicitly-declared copy assignment operator is an inline public 9834 // member of its class. 9835 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9836 SourceLocation ClassLoc = ClassDecl->getLocation(); 9837 DeclarationNameInfo NameInfo(Name, ClassLoc); 9838 CXXMethodDecl *CopyAssignment = 9839 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9840 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 9841 /*isInline=*/true, Constexpr, SourceLocation()); 9842 CopyAssignment->setAccess(AS_public); 9843 CopyAssignment->setDefaulted(); 9844 CopyAssignment->setImplicit(); 9845 9846 if (getLangOpts().CUDA) { 9847 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 9848 CopyAssignment, 9849 /* ConstRHS */ Const, 9850 /* Diagnose */ false); 9851 } 9852 9853 // Build an exception specification pointing back at this member. 9854 FunctionProtoType::ExtProtoInfo EPI = 9855 getImplicitMethodEPI(*this, CopyAssignment); 9856 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9857 9858 // Add the parameter to the operator. 9859 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9860 ClassLoc, ClassLoc, 9861 /*Id=*/nullptr, ArgType, 9862 /*TInfo=*/nullptr, SC_None, 9863 nullptr); 9864 CopyAssignment->setParams(FromParam); 9865 9866 AddOverriddenMethods(ClassDecl, CopyAssignment); 9867 9868 CopyAssignment->setTrivial( 9869 ClassDecl->needsOverloadResolutionForCopyAssignment() 9870 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9871 : ClassDecl->hasTrivialCopyAssignment()); 9872 9873 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9874 SetDeclDeleted(CopyAssignment, ClassLoc); 9875 9876 // Note that we have added this copy-assignment operator. 9877 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9878 9879 if (Scope *S = getScopeForContext(ClassDecl)) 9880 PushOnScopeChains(CopyAssignment, S, false); 9881 ClassDecl->addDecl(CopyAssignment); 9882 9883 return CopyAssignment; 9884 } 9885 9886 /// Diagnose an implicit copy operation for a class which is odr-used, but 9887 /// which is deprecated because the class has a user-declared copy constructor, 9888 /// copy assignment operator, or destructor. 9889 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 9890 SourceLocation UseLoc) { 9891 assert(CopyOp->isImplicit()); 9892 9893 CXXRecordDecl *RD = CopyOp->getParent(); 9894 CXXMethodDecl *UserDeclaredOperation = nullptr; 9895 9896 // In Microsoft mode, assignment operations don't affect constructors and 9897 // vice versa. 9898 if (RD->hasUserDeclaredDestructor()) { 9899 UserDeclaredOperation = RD->getDestructor(); 9900 } else if (!isa<CXXConstructorDecl>(CopyOp) && 9901 RD->hasUserDeclaredCopyConstructor() && 9902 !S.getLangOpts().MSVCCompat) { 9903 // Find any user-declared copy constructor. 9904 for (auto *I : RD->ctors()) { 9905 if (I->isCopyConstructor()) { 9906 UserDeclaredOperation = I; 9907 break; 9908 } 9909 } 9910 assert(UserDeclaredOperation); 9911 } else if (isa<CXXConstructorDecl>(CopyOp) && 9912 RD->hasUserDeclaredCopyAssignment() && 9913 !S.getLangOpts().MSVCCompat) { 9914 // Find any user-declared move assignment operator. 9915 for (auto *I : RD->methods()) { 9916 if (I->isCopyAssignmentOperator()) { 9917 UserDeclaredOperation = I; 9918 break; 9919 } 9920 } 9921 assert(UserDeclaredOperation); 9922 } 9923 9924 if (UserDeclaredOperation) { 9925 S.Diag(UserDeclaredOperation->getLocation(), 9926 diag::warn_deprecated_copy_operation) 9927 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 9928 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 9929 S.Diag(UseLoc, diag::note_member_synthesized_at) 9930 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 9931 : Sema::CXXCopyAssignment) 9932 << RD; 9933 } 9934 } 9935 9936 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 9937 CXXMethodDecl *CopyAssignOperator) { 9938 assert((CopyAssignOperator->isDefaulted() && 9939 CopyAssignOperator->isOverloadedOperator() && 9940 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 9941 !CopyAssignOperator->doesThisDeclarationHaveABody() && 9942 !CopyAssignOperator->isDeleted()) && 9943 "DefineImplicitCopyAssignment called for wrong function"); 9944 9945 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 9946 9947 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 9948 CopyAssignOperator->setInvalidDecl(); 9949 return; 9950 } 9951 9952 // C++11 [class.copy]p18: 9953 // The [definition of an implicitly declared copy assignment operator] is 9954 // deprecated if the class has a user-declared copy constructor or a 9955 // user-declared destructor. 9956 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 9957 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 9958 9959 CopyAssignOperator->markUsed(Context); 9960 9961 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 9962 DiagnosticErrorTrap Trap(Diags); 9963 9964 // C++0x [class.copy]p30: 9965 // The implicitly-defined or explicitly-defaulted copy assignment operator 9966 // for a non-union class X performs memberwise copy assignment of its 9967 // subobjects. The direct base classes of X are assigned first, in the 9968 // order of their declaration in the base-specifier-list, and then the 9969 // immediate non-static data members of X are assigned, in the order in 9970 // which they were declared in the class definition. 9971 9972 // The statements that form the synthesized function body. 9973 SmallVector<Stmt*, 8> Statements; 9974 9975 // The parameter for the "other" object, which we are copying from. 9976 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 9977 Qualifiers OtherQuals = Other->getType().getQualifiers(); 9978 QualType OtherRefType = Other->getType(); 9979 if (const LValueReferenceType *OtherRef 9980 = OtherRefType->getAs<LValueReferenceType>()) { 9981 OtherRefType = OtherRef->getPointeeType(); 9982 OtherQuals = OtherRefType.getQualifiers(); 9983 } 9984 9985 // Our location for everything implicitly-generated. 9986 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 9987 ? CopyAssignOperator->getLocEnd() 9988 : CopyAssignOperator->getLocation(); 9989 9990 // Builds a DeclRefExpr for the "other" object. 9991 RefBuilder OtherRef(Other, OtherRefType); 9992 9993 // Builds the "this" pointer. 9994 ThisBuilder This; 9995 9996 // Assign base classes. 9997 bool Invalid = false; 9998 for (auto &Base : ClassDecl->bases()) { 9999 // Form the assignment: 10000 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 10001 QualType BaseType = Base.getType().getUnqualifiedType(); 10002 if (!BaseType->isRecordType()) { 10003 Invalid = true; 10004 continue; 10005 } 10006 10007 CXXCastPath BasePath; 10008 BasePath.push_back(&Base); 10009 10010 // Construct the "from" expression, which is an implicit cast to the 10011 // appropriately-qualified base type. 10012 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 10013 VK_LValue, BasePath); 10014 10015 // Dereference "this". 10016 DerefBuilder DerefThis(This); 10017 CastBuilder To(DerefThis, 10018 Context.getCVRQualifiedType( 10019 BaseType, CopyAssignOperator->getTypeQualifiers()), 10020 VK_LValue, BasePath); 10021 10022 // Build the copy. 10023 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 10024 To, From, 10025 /*CopyingBaseSubobject=*/true, 10026 /*Copying=*/true); 10027 if (Copy.isInvalid()) { 10028 Diag(CurrentLocation, diag::note_member_synthesized_at) 10029 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10030 CopyAssignOperator->setInvalidDecl(); 10031 return; 10032 } 10033 10034 // Success! Record the copy. 10035 Statements.push_back(Copy.getAs<Expr>()); 10036 } 10037 10038 // Assign non-static members. 10039 for (auto *Field : ClassDecl->fields()) { 10040 if (Field->isUnnamedBitfield()) 10041 continue; 10042 10043 if (Field->isInvalidDecl()) { 10044 Invalid = true; 10045 continue; 10046 } 10047 10048 // Check for members of reference type; we can't copy those. 10049 if (Field->getType()->isReferenceType()) { 10050 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10051 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10052 Diag(Field->getLocation(), diag::note_declared_at); 10053 Diag(CurrentLocation, diag::note_member_synthesized_at) 10054 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10055 Invalid = true; 10056 continue; 10057 } 10058 10059 // Check for members of const-qualified, non-class type. 10060 QualType BaseType = Context.getBaseElementType(Field->getType()); 10061 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10062 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10063 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10064 Diag(Field->getLocation(), diag::note_declared_at); 10065 Diag(CurrentLocation, diag::note_member_synthesized_at) 10066 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10067 Invalid = true; 10068 continue; 10069 } 10070 10071 // Suppress assigning zero-width bitfields. 10072 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10073 continue; 10074 10075 QualType FieldType = Field->getType().getNonReferenceType(); 10076 if (FieldType->isIncompleteArrayType()) { 10077 assert(ClassDecl->hasFlexibleArrayMember() && 10078 "Incomplete array type is not valid"); 10079 continue; 10080 } 10081 10082 // Build references to the field in the object we're copying from and to. 10083 CXXScopeSpec SS; // Intentionally empty 10084 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10085 LookupMemberName); 10086 MemberLookup.addDecl(Field); 10087 MemberLookup.resolveKind(); 10088 10089 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 10090 10091 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 10092 10093 // Build the copy of this field. 10094 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 10095 To, From, 10096 /*CopyingBaseSubobject=*/false, 10097 /*Copying=*/true); 10098 if (Copy.isInvalid()) { 10099 Diag(CurrentLocation, diag::note_member_synthesized_at) 10100 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10101 CopyAssignOperator->setInvalidDecl(); 10102 return; 10103 } 10104 10105 // Success! Record the copy. 10106 Statements.push_back(Copy.getAs<Stmt>()); 10107 } 10108 10109 if (!Invalid) { 10110 // Add a "return *this;" 10111 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10112 10113 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10114 if (Return.isInvalid()) 10115 Invalid = true; 10116 else { 10117 Statements.push_back(Return.getAs<Stmt>()); 10118 10119 if (Trap.hasErrorOccurred()) { 10120 Diag(CurrentLocation, diag::note_member_synthesized_at) 10121 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 10122 Invalid = true; 10123 } 10124 } 10125 } 10126 10127 // The exception specification is needed because we are defining the 10128 // function. 10129 ResolveExceptionSpec(CurrentLocation, 10130 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 10131 10132 if (Invalid) { 10133 CopyAssignOperator->setInvalidDecl(); 10134 return; 10135 } 10136 10137 StmtResult Body; 10138 { 10139 CompoundScopeRAII CompoundScope(*this); 10140 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10141 /*isStmtExpr=*/false); 10142 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10143 } 10144 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 10145 10146 if (ASTMutationListener *L = getASTMutationListener()) { 10147 L->CompletedImplicitDefinition(CopyAssignOperator); 10148 } 10149 } 10150 10151 Sema::ImplicitExceptionSpecification 10152 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 10153 CXXRecordDecl *ClassDecl = MD->getParent(); 10154 10155 ImplicitExceptionSpecification ExceptSpec(*this); 10156 if (ClassDecl->isInvalidDecl()) 10157 return ExceptSpec; 10158 10159 // C++0x [except.spec]p14: 10160 // An implicitly declared special member function (Clause 12) shall have an 10161 // exception-specification. [...] 10162 10163 // It is unspecified whether or not an implicit move assignment operator 10164 // attempts to deduplicate calls to assignment operators of virtual bases are 10165 // made. As such, this exception specification is effectively unspecified. 10166 // Based on a similar decision made for constness in C++0x, we're erring on 10167 // the side of assuming such calls to be made regardless of whether they 10168 // actually happen. 10169 // Note that a move constructor is not implicitly declared when there are 10170 // virtual bases, but it can still be user-declared and explicitly defaulted. 10171 for (const auto &Base : ClassDecl->bases()) { 10172 if (Base.isVirtual()) 10173 continue; 10174 10175 CXXRecordDecl *BaseClassDecl 10176 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10177 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10178 0, false, 0)) 10179 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10180 } 10181 10182 for (const auto &Base : ClassDecl->vbases()) { 10183 CXXRecordDecl *BaseClassDecl 10184 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10185 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10186 0, false, 0)) 10187 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10188 } 10189 10190 for (const auto *Field : ClassDecl->fields()) { 10191 QualType FieldType = Context.getBaseElementType(Field->getType()); 10192 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10193 if (CXXMethodDecl *MoveAssign = 10194 LookupMovingAssignment(FieldClassDecl, 10195 FieldType.getCVRQualifiers(), 10196 false, 0)) 10197 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 10198 } 10199 } 10200 10201 return ExceptSpec; 10202 } 10203 10204 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 10205 assert(ClassDecl->needsImplicitMoveAssignment()); 10206 10207 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 10208 if (DSM.isAlreadyBeingDeclared()) 10209 return nullptr; 10210 10211 // Note: The following rules are largely analoguous to the move 10212 // constructor rules. 10213 10214 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10215 QualType RetType = Context.getLValueReferenceType(ArgType); 10216 ArgType = Context.getRValueReferenceType(ArgType); 10217 10218 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10219 CXXMoveAssignment, 10220 false); 10221 10222 // An implicitly-declared move assignment operator is an inline public 10223 // member of its class. 10224 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10225 SourceLocation ClassLoc = ClassDecl->getLocation(); 10226 DeclarationNameInfo NameInfo(Name, ClassLoc); 10227 CXXMethodDecl *MoveAssignment = 10228 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10229 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10230 /*isInline=*/true, Constexpr, SourceLocation()); 10231 MoveAssignment->setAccess(AS_public); 10232 MoveAssignment->setDefaulted(); 10233 MoveAssignment->setImplicit(); 10234 10235 if (getLangOpts().CUDA) { 10236 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 10237 MoveAssignment, 10238 /* ConstRHS */ false, 10239 /* Diagnose */ false); 10240 } 10241 10242 // Build an exception specification pointing back at this member. 10243 FunctionProtoType::ExtProtoInfo EPI = 10244 getImplicitMethodEPI(*this, MoveAssignment); 10245 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10246 10247 // Add the parameter to the operator. 10248 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 10249 ClassLoc, ClassLoc, 10250 /*Id=*/nullptr, ArgType, 10251 /*TInfo=*/nullptr, SC_None, 10252 nullptr); 10253 MoveAssignment->setParams(FromParam); 10254 10255 AddOverriddenMethods(ClassDecl, MoveAssignment); 10256 10257 MoveAssignment->setTrivial( 10258 ClassDecl->needsOverloadResolutionForMoveAssignment() 10259 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 10260 : ClassDecl->hasTrivialMoveAssignment()); 10261 10262 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 10263 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 10264 SetDeclDeleted(MoveAssignment, ClassLoc); 10265 } 10266 10267 // Note that we have added this copy-assignment operator. 10268 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 10269 10270 if (Scope *S = getScopeForContext(ClassDecl)) 10271 PushOnScopeChains(MoveAssignment, S, false); 10272 ClassDecl->addDecl(MoveAssignment); 10273 10274 return MoveAssignment; 10275 } 10276 10277 /// Check if we're implicitly defining a move assignment operator for a class 10278 /// with virtual bases. Such a move assignment might move-assign the virtual 10279 /// base multiple times. 10280 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 10281 SourceLocation CurrentLocation) { 10282 assert(!Class->isDependentContext() && "should not define dependent move"); 10283 10284 // Only a virtual base could get implicitly move-assigned multiple times. 10285 // Only a non-trivial move assignment can observe this. We only want to 10286 // diagnose if we implicitly define an assignment operator that assigns 10287 // two base classes, both of which move-assign the same virtual base. 10288 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 10289 Class->getNumBases() < 2) 10290 return; 10291 10292 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 10293 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 10294 VBaseMap VBases; 10295 10296 for (auto &BI : Class->bases()) { 10297 Worklist.push_back(&BI); 10298 while (!Worklist.empty()) { 10299 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 10300 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 10301 10302 // If the base has no non-trivial move assignment operators, 10303 // we don't care about moves from it. 10304 if (!Base->hasNonTrivialMoveAssignment()) 10305 continue; 10306 10307 // If there's nothing virtual here, skip it. 10308 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 10309 continue; 10310 10311 // If we're not actually going to call a move assignment for this base, 10312 // or the selected move assignment is trivial, skip it. 10313 Sema::SpecialMemberOverloadResult *SMOR = 10314 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 10315 /*ConstArg*/false, /*VolatileArg*/false, 10316 /*RValueThis*/true, /*ConstThis*/false, 10317 /*VolatileThis*/false); 10318 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 10319 !SMOR->getMethod()->isMoveAssignmentOperator()) 10320 continue; 10321 10322 if (BaseSpec->isVirtual()) { 10323 // We're going to move-assign this virtual base, and its move 10324 // assignment operator is not trivial. If this can happen for 10325 // multiple distinct direct bases of Class, diagnose it. (If it 10326 // only happens in one base, we'll diagnose it when synthesizing 10327 // that base class's move assignment operator.) 10328 CXXBaseSpecifier *&Existing = 10329 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 10330 .first->second; 10331 if (Existing && Existing != &BI) { 10332 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 10333 << Class << Base; 10334 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 10335 << (Base->getCanonicalDecl() == 10336 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10337 << Base << Existing->getType() << Existing->getSourceRange(); 10338 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 10339 << (Base->getCanonicalDecl() == 10340 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10341 << Base << BI.getType() << BaseSpec->getSourceRange(); 10342 10343 // Only diagnose each vbase once. 10344 Existing = nullptr; 10345 } 10346 } else { 10347 // Only walk over bases that have defaulted move assignment operators. 10348 // We assume that any user-provided move assignment operator handles 10349 // the multiple-moves-of-vbase case itself somehow. 10350 if (!SMOR->getMethod()->isDefaulted()) 10351 continue; 10352 10353 // We're going to move the base classes of Base. Add them to the list. 10354 for (auto &BI : Base->bases()) 10355 Worklist.push_back(&BI); 10356 } 10357 } 10358 } 10359 } 10360 10361 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 10362 CXXMethodDecl *MoveAssignOperator) { 10363 assert((MoveAssignOperator->isDefaulted() && 10364 MoveAssignOperator->isOverloadedOperator() && 10365 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 10366 !MoveAssignOperator->doesThisDeclarationHaveABody() && 10367 !MoveAssignOperator->isDeleted()) && 10368 "DefineImplicitMoveAssignment called for wrong function"); 10369 10370 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 10371 10372 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 10373 MoveAssignOperator->setInvalidDecl(); 10374 return; 10375 } 10376 10377 MoveAssignOperator->markUsed(Context); 10378 10379 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 10380 DiagnosticErrorTrap Trap(Diags); 10381 10382 // C++0x [class.copy]p28: 10383 // The implicitly-defined or move assignment operator for a non-union class 10384 // X performs memberwise move assignment of its subobjects. The direct base 10385 // classes of X are assigned first, in the order of their declaration in the 10386 // base-specifier-list, and then the immediate non-static data members of X 10387 // are assigned, in the order in which they were declared in the class 10388 // definition. 10389 10390 // Issue a warning if our implicit move assignment operator will move 10391 // from a virtual base more than once. 10392 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 10393 10394 // The statements that form the synthesized function body. 10395 SmallVector<Stmt*, 8> Statements; 10396 10397 // The parameter for the "other" object, which we are move from. 10398 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 10399 QualType OtherRefType = Other->getType()-> 10400 getAs<RValueReferenceType>()->getPointeeType(); 10401 assert(!OtherRefType.getQualifiers() && 10402 "Bad argument type of defaulted move assignment"); 10403 10404 // Our location for everything implicitly-generated. 10405 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 10406 ? MoveAssignOperator->getLocEnd() 10407 : MoveAssignOperator->getLocation(); 10408 10409 // Builds a reference to the "other" object. 10410 RefBuilder OtherRef(Other, OtherRefType); 10411 // Cast to rvalue. 10412 MoveCastBuilder MoveOther(OtherRef); 10413 10414 // Builds the "this" pointer. 10415 ThisBuilder This; 10416 10417 // Assign base classes. 10418 bool Invalid = false; 10419 for (auto &Base : ClassDecl->bases()) { 10420 // C++11 [class.copy]p28: 10421 // It is unspecified whether subobjects representing virtual base classes 10422 // are assigned more than once by the implicitly-defined copy assignment 10423 // operator. 10424 // FIXME: Do not assign to a vbase that will be assigned by some other base 10425 // class. For a move-assignment, this can result in the vbase being moved 10426 // multiple times. 10427 10428 // Form the assignment: 10429 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10430 QualType BaseType = Base.getType().getUnqualifiedType(); 10431 if (!BaseType->isRecordType()) { 10432 Invalid = true; 10433 continue; 10434 } 10435 10436 CXXCastPath BasePath; 10437 BasePath.push_back(&Base); 10438 10439 // Construct the "from" expression, which is an implicit cast to the 10440 // appropriately-qualified base type. 10441 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10442 10443 // Dereference "this". 10444 DerefBuilder DerefThis(This); 10445 10446 // Implicitly cast "this" to the appropriately-qualified base type. 10447 CastBuilder To(DerefThis, 10448 Context.getCVRQualifiedType( 10449 BaseType, MoveAssignOperator->getTypeQualifiers()), 10450 VK_LValue, BasePath); 10451 10452 // Build the move. 10453 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10454 To, From, 10455 /*CopyingBaseSubobject=*/true, 10456 /*Copying=*/false); 10457 if (Move.isInvalid()) { 10458 Diag(CurrentLocation, diag::note_member_synthesized_at) 10459 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10460 MoveAssignOperator->setInvalidDecl(); 10461 return; 10462 } 10463 10464 // Success! Record the move. 10465 Statements.push_back(Move.getAs<Expr>()); 10466 } 10467 10468 // Assign non-static members. 10469 for (auto *Field : ClassDecl->fields()) { 10470 if (Field->isUnnamedBitfield()) 10471 continue; 10472 10473 if (Field->isInvalidDecl()) { 10474 Invalid = true; 10475 continue; 10476 } 10477 10478 // Check for members of reference type; we can't move those. 10479 if (Field->getType()->isReferenceType()) { 10480 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10481 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10482 Diag(Field->getLocation(), diag::note_declared_at); 10483 Diag(CurrentLocation, diag::note_member_synthesized_at) 10484 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10485 Invalid = true; 10486 continue; 10487 } 10488 10489 // Check for members of const-qualified, non-class type. 10490 QualType BaseType = Context.getBaseElementType(Field->getType()); 10491 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10492 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10493 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10494 Diag(Field->getLocation(), diag::note_declared_at); 10495 Diag(CurrentLocation, diag::note_member_synthesized_at) 10496 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10497 Invalid = true; 10498 continue; 10499 } 10500 10501 // Suppress assigning zero-width bitfields. 10502 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10503 continue; 10504 10505 QualType FieldType = Field->getType().getNonReferenceType(); 10506 if (FieldType->isIncompleteArrayType()) { 10507 assert(ClassDecl->hasFlexibleArrayMember() && 10508 "Incomplete array type is not valid"); 10509 continue; 10510 } 10511 10512 // Build references to the field in the object we're copying from and to. 10513 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10514 LookupMemberName); 10515 MemberLookup.addDecl(Field); 10516 MemberLookup.resolveKind(); 10517 MemberBuilder From(MoveOther, OtherRefType, 10518 /*IsArrow=*/false, MemberLookup); 10519 MemberBuilder To(This, getCurrentThisType(), 10520 /*IsArrow=*/true, MemberLookup); 10521 10522 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10523 "Member reference with rvalue base must be rvalue except for reference " 10524 "members, which aren't allowed for move assignment."); 10525 10526 // Build the move of this field. 10527 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10528 To, From, 10529 /*CopyingBaseSubobject=*/false, 10530 /*Copying=*/false); 10531 if (Move.isInvalid()) { 10532 Diag(CurrentLocation, diag::note_member_synthesized_at) 10533 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10534 MoveAssignOperator->setInvalidDecl(); 10535 return; 10536 } 10537 10538 // Success! Record the copy. 10539 Statements.push_back(Move.getAs<Stmt>()); 10540 } 10541 10542 if (!Invalid) { 10543 // Add a "return *this;" 10544 ExprResult ThisObj = 10545 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10546 10547 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10548 if (Return.isInvalid()) 10549 Invalid = true; 10550 else { 10551 Statements.push_back(Return.getAs<Stmt>()); 10552 10553 if (Trap.hasErrorOccurred()) { 10554 Diag(CurrentLocation, diag::note_member_synthesized_at) 10555 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10556 Invalid = true; 10557 } 10558 } 10559 } 10560 10561 // The exception specification is needed because we are defining the 10562 // function. 10563 ResolveExceptionSpec(CurrentLocation, 10564 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 10565 10566 if (Invalid) { 10567 MoveAssignOperator->setInvalidDecl(); 10568 return; 10569 } 10570 10571 StmtResult Body; 10572 { 10573 CompoundScopeRAII CompoundScope(*this); 10574 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10575 /*isStmtExpr=*/false); 10576 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10577 } 10578 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10579 10580 if (ASTMutationListener *L = getASTMutationListener()) { 10581 L->CompletedImplicitDefinition(MoveAssignOperator); 10582 } 10583 } 10584 10585 Sema::ImplicitExceptionSpecification 10586 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10587 CXXRecordDecl *ClassDecl = MD->getParent(); 10588 10589 ImplicitExceptionSpecification ExceptSpec(*this); 10590 if (ClassDecl->isInvalidDecl()) 10591 return ExceptSpec; 10592 10593 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10594 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10595 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10596 10597 // C++ [except.spec]p14: 10598 // An implicitly declared special member function (Clause 12) shall have an 10599 // exception-specification. [...] 10600 for (const auto &Base : ClassDecl->bases()) { 10601 // Virtual bases are handled below. 10602 if (Base.isVirtual()) 10603 continue; 10604 10605 CXXRecordDecl *BaseClassDecl 10606 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10607 if (CXXConstructorDecl *CopyConstructor = 10608 LookupCopyingConstructor(BaseClassDecl, Quals)) 10609 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10610 } 10611 for (const auto &Base : ClassDecl->vbases()) { 10612 CXXRecordDecl *BaseClassDecl 10613 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10614 if (CXXConstructorDecl *CopyConstructor = 10615 LookupCopyingConstructor(BaseClassDecl, Quals)) 10616 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10617 } 10618 for (const auto *Field : ClassDecl->fields()) { 10619 QualType FieldType = Context.getBaseElementType(Field->getType()); 10620 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10621 if (CXXConstructorDecl *CopyConstructor = 10622 LookupCopyingConstructor(FieldClassDecl, 10623 Quals | FieldType.getCVRQualifiers())) 10624 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10625 } 10626 } 10627 10628 return ExceptSpec; 10629 } 10630 10631 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10632 CXXRecordDecl *ClassDecl) { 10633 // C++ [class.copy]p4: 10634 // If the class definition does not explicitly declare a copy 10635 // constructor, one is declared implicitly. 10636 assert(ClassDecl->needsImplicitCopyConstructor()); 10637 10638 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10639 if (DSM.isAlreadyBeingDeclared()) 10640 return nullptr; 10641 10642 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10643 QualType ArgType = ClassType; 10644 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10645 if (Const) 10646 ArgType = ArgType.withConst(); 10647 ArgType = Context.getLValueReferenceType(ArgType); 10648 10649 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10650 CXXCopyConstructor, 10651 Const); 10652 10653 DeclarationName Name 10654 = Context.DeclarationNames.getCXXConstructorName( 10655 Context.getCanonicalType(ClassType)); 10656 SourceLocation ClassLoc = ClassDecl->getLocation(); 10657 DeclarationNameInfo NameInfo(Name, ClassLoc); 10658 10659 // An implicitly-declared copy constructor is an inline public 10660 // member of its class. 10661 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10662 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10663 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10664 Constexpr); 10665 CopyConstructor->setAccess(AS_public); 10666 CopyConstructor->setDefaulted(); 10667 10668 if (getLangOpts().CUDA) { 10669 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 10670 CopyConstructor, 10671 /* ConstRHS */ Const, 10672 /* Diagnose */ false); 10673 } 10674 10675 // Build an exception specification pointing back at this member. 10676 FunctionProtoType::ExtProtoInfo EPI = 10677 getImplicitMethodEPI(*this, CopyConstructor); 10678 CopyConstructor->setType( 10679 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10680 10681 // Add the parameter to the constructor. 10682 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10683 ClassLoc, ClassLoc, 10684 /*IdentifierInfo=*/nullptr, 10685 ArgType, /*TInfo=*/nullptr, 10686 SC_None, nullptr); 10687 CopyConstructor->setParams(FromParam); 10688 10689 CopyConstructor->setTrivial( 10690 ClassDecl->needsOverloadResolutionForCopyConstructor() 10691 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10692 : ClassDecl->hasTrivialCopyConstructor()); 10693 10694 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10695 SetDeclDeleted(CopyConstructor, ClassLoc); 10696 10697 // Note that we have declared this constructor. 10698 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10699 10700 if (Scope *S = getScopeForContext(ClassDecl)) 10701 PushOnScopeChains(CopyConstructor, S, false); 10702 ClassDecl->addDecl(CopyConstructor); 10703 10704 return CopyConstructor; 10705 } 10706 10707 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10708 CXXConstructorDecl *CopyConstructor) { 10709 assert((CopyConstructor->isDefaulted() && 10710 CopyConstructor->isCopyConstructor() && 10711 !CopyConstructor->doesThisDeclarationHaveABody() && 10712 !CopyConstructor->isDeleted()) && 10713 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10714 10715 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10716 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10717 10718 // C++11 [class.copy]p7: 10719 // The [definition of an implicitly declared copy constructor] is 10720 // deprecated if the class has a user-declared copy assignment operator 10721 // or a user-declared destructor. 10722 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10723 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10724 10725 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10726 DiagnosticErrorTrap Trap(Diags); 10727 10728 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10729 Trap.hasErrorOccurred()) { 10730 Diag(CurrentLocation, diag::note_member_synthesized_at) 10731 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10732 CopyConstructor->setInvalidDecl(); 10733 } else { 10734 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10735 ? CopyConstructor->getLocEnd() 10736 : CopyConstructor->getLocation(); 10737 Sema::CompoundScopeRAII CompoundScope(*this); 10738 CopyConstructor->setBody( 10739 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10740 } 10741 10742 // The exception specification is needed because we are defining the 10743 // function. 10744 ResolveExceptionSpec(CurrentLocation, 10745 CopyConstructor->getType()->castAs<FunctionProtoType>()); 10746 10747 CopyConstructor->markUsed(Context); 10748 MarkVTableUsed(CurrentLocation, ClassDecl); 10749 10750 if (ASTMutationListener *L = getASTMutationListener()) { 10751 L->CompletedImplicitDefinition(CopyConstructor); 10752 } 10753 } 10754 10755 Sema::ImplicitExceptionSpecification 10756 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10757 CXXRecordDecl *ClassDecl = MD->getParent(); 10758 10759 // C++ [except.spec]p14: 10760 // An implicitly declared special member function (Clause 12) shall have an 10761 // exception-specification. [...] 10762 ImplicitExceptionSpecification ExceptSpec(*this); 10763 if (ClassDecl->isInvalidDecl()) 10764 return ExceptSpec; 10765 10766 // Direct base-class constructors. 10767 for (const auto &B : ClassDecl->bases()) { 10768 if (B.isVirtual()) // Handled below. 10769 continue; 10770 10771 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10772 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10773 CXXConstructorDecl *Constructor = 10774 LookupMovingConstructor(BaseClassDecl, 0); 10775 // If this is a deleted function, add it anyway. This might be conformant 10776 // with the standard. This might not. I'm not sure. It might not matter. 10777 if (Constructor) 10778 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10779 } 10780 } 10781 10782 // Virtual base-class constructors. 10783 for (const auto &B : ClassDecl->vbases()) { 10784 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10785 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10786 CXXConstructorDecl *Constructor = 10787 LookupMovingConstructor(BaseClassDecl, 0); 10788 // If this is a deleted function, add it anyway. This might be conformant 10789 // with the standard. This might not. I'm not sure. It might not matter. 10790 if (Constructor) 10791 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10792 } 10793 } 10794 10795 // Field constructors. 10796 for (const auto *F : ClassDecl->fields()) { 10797 QualType FieldType = Context.getBaseElementType(F->getType()); 10798 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10799 CXXConstructorDecl *Constructor = 10800 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10801 // If this is a deleted function, add it anyway. This might be conformant 10802 // with the standard. This might not. I'm not sure. It might not matter. 10803 // In particular, the problem is that this function never gets called. It 10804 // might just be ill-formed because this function attempts to refer to 10805 // a deleted function here. 10806 if (Constructor) 10807 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10808 } 10809 } 10810 10811 return ExceptSpec; 10812 } 10813 10814 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10815 CXXRecordDecl *ClassDecl) { 10816 assert(ClassDecl->needsImplicitMoveConstructor()); 10817 10818 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10819 if (DSM.isAlreadyBeingDeclared()) 10820 return nullptr; 10821 10822 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10823 QualType ArgType = Context.getRValueReferenceType(ClassType); 10824 10825 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10826 CXXMoveConstructor, 10827 false); 10828 10829 DeclarationName Name 10830 = Context.DeclarationNames.getCXXConstructorName( 10831 Context.getCanonicalType(ClassType)); 10832 SourceLocation ClassLoc = ClassDecl->getLocation(); 10833 DeclarationNameInfo NameInfo(Name, ClassLoc); 10834 10835 // C++11 [class.copy]p11: 10836 // An implicitly-declared copy/move constructor is an inline public 10837 // member of its class. 10838 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10839 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10840 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10841 Constexpr); 10842 MoveConstructor->setAccess(AS_public); 10843 MoveConstructor->setDefaulted(); 10844 10845 if (getLangOpts().CUDA) { 10846 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 10847 MoveConstructor, 10848 /* ConstRHS */ false, 10849 /* Diagnose */ false); 10850 } 10851 10852 // Build an exception specification pointing back at this member. 10853 FunctionProtoType::ExtProtoInfo EPI = 10854 getImplicitMethodEPI(*this, MoveConstructor); 10855 MoveConstructor->setType( 10856 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10857 10858 // Add the parameter to the constructor. 10859 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10860 ClassLoc, ClassLoc, 10861 /*IdentifierInfo=*/nullptr, 10862 ArgType, /*TInfo=*/nullptr, 10863 SC_None, nullptr); 10864 MoveConstructor->setParams(FromParam); 10865 10866 MoveConstructor->setTrivial( 10867 ClassDecl->needsOverloadResolutionForMoveConstructor() 10868 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10869 : ClassDecl->hasTrivialMoveConstructor()); 10870 10871 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10872 ClassDecl->setImplicitMoveConstructorIsDeleted(); 10873 SetDeclDeleted(MoveConstructor, ClassLoc); 10874 } 10875 10876 // Note that we have declared this constructor. 10877 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10878 10879 if (Scope *S = getScopeForContext(ClassDecl)) 10880 PushOnScopeChains(MoveConstructor, S, false); 10881 ClassDecl->addDecl(MoveConstructor); 10882 10883 return MoveConstructor; 10884 } 10885 10886 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 10887 CXXConstructorDecl *MoveConstructor) { 10888 assert((MoveConstructor->isDefaulted() && 10889 MoveConstructor->isMoveConstructor() && 10890 !MoveConstructor->doesThisDeclarationHaveABody() && 10891 !MoveConstructor->isDeleted()) && 10892 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 10893 10894 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 10895 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 10896 10897 SynthesizedFunctionScope Scope(*this, MoveConstructor); 10898 DiagnosticErrorTrap Trap(Diags); 10899 10900 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10901 Trap.hasErrorOccurred()) { 10902 Diag(CurrentLocation, diag::note_member_synthesized_at) 10903 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10904 MoveConstructor->setInvalidDecl(); 10905 } else { 10906 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 10907 ? MoveConstructor->getLocEnd() 10908 : MoveConstructor->getLocation(); 10909 Sema::CompoundScopeRAII CompoundScope(*this); 10910 MoveConstructor->setBody(ActOnCompoundStmt( 10911 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 10912 } 10913 10914 // The exception specification is needed because we are defining the 10915 // function. 10916 ResolveExceptionSpec(CurrentLocation, 10917 MoveConstructor->getType()->castAs<FunctionProtoType>()); 10918 10919 MoveConstructor->markUsed(Context); 10920 MarkVTableUsed(CurrentLocation, ClassDecl); 10921 10922 if (ASTMutationListener *L = getASTMutationListener()) { 10923 L->CompletedImplicitDefinition(MoveConstructor); 10924 } 10925 } 10926 10927 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10928 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10929 } 10930 10931 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10932 SourceLocation CurrentLocation, 10933 CXXConversionDecl *Conv) { 10934 CXXRecordDecl *Lambda = Conv->getParent(); 10935 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 10936 // If we are defining a specialization of a conversion to function-ptr 10937 // cache the deduced template arguments for this specialization 10938 // so that we can use them to retrieve the corresponding call-operator 10939 // and static-invoker. 10940 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 10941 10942 // Retrieve the corresponding call-operator specialization. 10943 if (Lambda->isGenericLambda()) { 10944 assert(Conv->isFunctionTemplateSpecialization()); 10945 FunctionTemplateDecl *CallOpTemplate = 10946 CallOp->getDescribedFunctionTemplate(); 10947 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 10948 void *InsertPos = nullptr; 10949 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 10950 DeducedTemplateArgs->asArray(), 10951 InsertPos); 10952 assert(CallOpSpec && 10953 "Conversion operator must have a corresponding call operator"); 10954 CallOp = cast<CXXMethodDecl>(CallOpSpec); 10955 } 10956 // Mark the call operator referenced (and add to pending instantiations 10957 // if necessary). 10958 // For both the conversion and static-invoker template specializations 10959 // we construct their body's in this function, so no need to add them 10960 // to the PendingInstantiations. 10961 MarkFunctionReferenced(CurrentLocation, CallOp); 10962 10963 SynthesizedFunctionScope Scope(*this, Conv); 10964 DiagnosticErrorTrap Trap(Diags); 10965 10966 // Retrieve the static invoker... 10967 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 10968 // ... and get the corresponding specialization for a generic lambda. 10969 if (Lambda->isGenericLambda()) { 10970 assert(DeducedTemplateArgs && 10971 "Must have deduced template arguments from Conversion Operator"); 10972 FunctionTemplateDecl *InvokeTemplate = 10973 Invoker->getDescribedFunctionTemplate(); 10974 void *InsertPos = nullptr; 10975 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 10976 DeducedTemplateArgs->asArray(), 10977 InsertPos); 10978 assert(InvokeSpec && 10979 "Must have a corresponding static invoker specialization"); 10980 Invoker = cast<CXXMethodDecl>(InvokeSpec); 10981 } 10982 // Construct the body of the conversion function { return __invoke; }. 10983 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 10984 VK_LValue, Conv->getLocation()).get(); 10985 assert(FunctionRef && "Can't refer to __invoke function?"); 10986 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 10987 Conv->setBody(new (Context) CompoundStmt(Context, Return, 10988 Conv->getLocation(), 10989 Conv->getLocation())); 10990 10991 Conv->markUsed(Context); 10992 Conv->setReferenced(); 10993 10994 // Fill in the __invoke function with a dummy implementation. IR generation 10995 // will fill in the actual details. 10996 Invoker->markUsed(Context); 10997 Invoker->setReferenced(); 10998 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 10999 11000 if (ASTMutationListener *L = getASTMutationListener()) { 11001 L->CompletedImplicitDefinition(Conv); 11002 L->CompletedImplicitDefinition(Invoker); 11003 } 11004 } 11005 11006 11007 11008 void Sema::DefineImplicitLambdaToBlockPointerConversion( 11009 SourceLocation CurrentLocation, 11010 CXXConversionDecl *Conv) 11011 { 11012 assert(!Conv->getParent()->isGenericLambda()); 11013 11014 Conv->markUsed(Context); 11015 11016 SynthesizedFunctionScope Scope(*this, Conv); 11017 DiagnosticErrorTrap Trap(Diags); 11018 11019 // Copy-initialize the lambda object as needed to capture it. 11020 Expr *This = ActOnCXXThis(CurrentLocation).get(); 11021 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 11022 11023 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 11024 Conv->getLocation(), 11025 Conv, DerefThis); 11026 11027 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 11028 // behavior. Note that only the general conversion function does this 11029 // (since it's unusable otherwise); in the case where we inline the 11030 // block literal, it has block literal lifetime semantics. 11031 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 11032 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 11033 CK_CopyAndAutoreleaseBlockObject, 11034 BuildBlock.get(), nullptr, VK_RValue); 11035 11036 if (BuildBlock.isInvalid()) { 11037 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11038 Conv->setInvalidDecl(); 11039 return; 11040 } 11041 11042 // Create the return statement that returns the block from the conversion 11043 // function. 11044 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 11045 if (Return.isInvalid()) { 11046 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 11047 Conv->setInvalidDecl(); 11048 return; 11049 } 11050 11051 // Set the body of the conversion function. 11052 Stmt *ReturnS = Return.get(); 11053 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 11054 Conv->getLocation(), 11055 Conv->getLocation())); 11056 11057 // We're done; notify the mutation listener, if any. 11058 if (ASTMutationListener *L = getASTMutationListener()) { 11059 L->CompletedImplicitDefinition(Conv); 11060 } 11061 } 11062 11063 /// \brief Determine whether the given list arguments contains exactly one 11064 /// "real" (non-default) argument. 11065 static bool hasOneRealArgument(MultiExprArg Args) { 11066 switch (Args.size()) { 11067 case 0: 11068 return false; 11069 11070 default: 11071 if (!Args[1]->isDefaultArgument()) 11072 return false; 11073 11074 // fall through 11075 case 1: 11076 return !Args[0]->isDefaultArgument(); 11077 } 11078 11079 return false; 11080 } 11081 11082 ExprResult 11083 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11084 CXXConstructorDecl *Constructor, 11085 MultiExprArg ExprArgs, 11086 bool HadMultipleCandidates, 11087 bool IsListInitialization, 11088 bool IsStdInitListInitialization, 11089 bool RequiresZeroInit, 11090 unsigned ConstructKind, 11091 SourceRange ParenRange) { 11092 bool Elidable = false; 11093 11094 // C++0x [class.copy]p34: 11095 // When certain criteria are met, an implementation is allowed to 11096 // omit the copy/move construction of a class object, even if the 11097 // copy/move constructor and/or destructor for the object have 11098 // side effects. [...] 11099 // - when a temporary class object that has not been bound to a 11100 // reference (12.2) would be copied/moved to a class object 11101 // with the same cv-unqualified type, the copy/move operation 11102 // can be omitted by constructing the temporary object 11103 // directly into the target of the omitted copy/move 11104 if (ConstructKind == CXXConstructExpr::CK_Complete && 11105 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 11106 Expr *SubExpr = ExprArgs[0]; 11107 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 11108 } 11109 11110 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 11111 Elidable, ExprArgs, HadMultipleCandidates, 11112 IsListInitialization, 11113 IsStdInitListInitialization, RequiresZeroInit, 11114 ConstructKind, ParenRange); 11115 } 11116 11117 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 11118 /// including handling of its default argument expressions. 11119 ExprResult 11120 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 11121 CXXConstructorDecl *Constructor, bool Elidable, 11122 MultiExprArg ExprArgs, 11123 bool HadMultipleCandidates, 11124 bool IsListInitialization, 11125 bool IsStdInitListInitialization, 11126 bool RequiresZeroInit, 11127 unsigned ConstructKind, 11128 SourceRange ParenRange) { 11129 MarkFunctionReferenced(ConstructLoc, Constructor); 11130 return CXXConstructExpr::Create( 11131 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 11132 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 11133 RequiresZeroInit, 11134 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 11135 ParenRange); 11136 } 11137 11138 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 11139 assert(Field->hasInClassInitializer()); 11140 11141 // If we already have the in-class initializer nothing needs to be done. 11142 if (Field->getInClassInitializer()) 11143 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11144 11145 // Maybe we haven't instantiated the in-class initializer. Go check the 11146 // pattern FieldDecl to see if it has one. 11147 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 11148 11149 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 11150 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 11151 DeclContext::lookup_result Lookup = 11152 ClassPattern->lookup(Field->getDeclName()); 11153 assert(Lookup.size() == 1); 11154 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]); 11155 if (InstantiateInClassInitializer(Loc, Field, Pattern, 11156 getTemplateInstantiationArgs(Field))) 11157 return ExprError(); 11158 return CXXDefaultInitExpr::Create(Context, Loc, Field); 11159 } 11160 11161 // DR1351: 11162 // If the brace-or-equal-initializer of a non-static data member 11163 // invokes a defaulted default constructor of its class or of an 11164 // enclosing class in a potentially evaluated subexpression, the 11165 // program is ill-formed. 11166 // 11167 // This resolution is unworkable: the exception specification of the 11168 // default constructor can be needed in an unevaluated context, in 11169 // particular, in the operand of a noexcept-expression, and we can be 11170 // unable to compute an exception specification for an enclosed class. 11171 // 11172 // Any attempt to resolve the exception specification of a defaulted default 11173 // constructor before the initializer is lexically complete will ultimately 11174 // come here at which point we can diagnose it. 11175 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 11176 if (OutermostClass == ParentRD) { 11177 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed) 11178 << ParentRD << Field; 11179 } else { 11180 Diag(Field->getLocEnd(), 11181 diag::err_in_class_initializer_not_yet_parsed_outer_class) 11182 << ParentRD << OutermostClass << Field; 11183 } 11184 11185 return ExprError(); 11186 } 11187 11188 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 11189 if (VD->isInvalidDecl()) return; 11190 11191 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 11192 if (ClassDecl->isInvalidDecl()) return; 11193 if (ClassDecl->hasIrrelevantDestructor()) return; 11194 if (ClassDecl->isDependentContext()) return; 11195 11196 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 11197 MarkFunctionReferenced(VD->getLocation(), Destructor); 11198 CheckDestructorAccess(VD->getLocation(), Destructor, 11199 PDiag(diag::err_access_dtor_var) 11200 << VD->getDeclName() 11201 << VD->getType()); 11202 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 11203 11204 if (Destructor->isTrivial()) return; 11205 if (!VD->hasGlobalStorage()) return; 11206 11207 // Emit warning for non-trivial dtor in global scope (a real global, 11208 // class-static, function-static). 11209 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 11210 11211 // TODO: this should be re-enabled for static locals by !CXAAtExit 11212 if (!VD->isStaticLocal()) 11213 Diag(VD->getLocation(), diag::warn_global_destructor); 11214 } 11215 11216 /// \brief Given a constructor and the set of arguments provided for the 11217 /// constructor, convert the arguments and add any required default arguments 11218 /// to form a proper call to this constructor. 11219 /// 11220 /// \returns true if an error occurred, false otherwise. 11221 bool 11222 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 11223 MultiExprArg ArgsPtr, 11224 SourceLocation Loc, 11225 SmallVectorImpl<Expr*> &ConvertedArgs, 11226 bool AllowExplicit, 11227 bool IsListInitialization) { 11228 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 11229 unsigned NumArgs = ArgsPtr.size(); 11230 Expr **Args = ArgsPtr.data(); 11231 11232 const FunctionProtoType *Proto 11233 = Constructor->getType()->getAs<FunctionProtoType>(); 11234 assert(Proto && "Constructor without a prototype?"); 11235 unsigned NumParams = Proto->getNumParams(); 11236 11237 // If too few arguments are available, we'll fill in the rest with defaults. 11238 if (NumArgs < NumParams) 11239 ConvertedArgs.reserve(NumParams); 11240 else 11241 ConvertedArgs.reserve(NumArgs); 11242 11243 VariadicCallType CallType = 11244 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 11245 SmallVector<Expr *, 8> AllArgs; 11246 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 11247 Proto, 0, 11248 llvm::makeArrayRef(Args, NumArgs), 11249 AllArgs, 11250 CallType, AllowExplicit, 11251 IsListInitialization); 11252 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 11253 11254 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 11255 11256 CheckConstructorCall(Constructor, 11257 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 11258 Proto, Loc); 11259 11260 return Invalid; 11261 } 11262 11263 static inline bool 11264 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 11265 const FunctionDecl *FnDecl) { 11266 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 11267 if (isa<NamespaceDecl>(DC)) { 11268 return SemaRef.Diag(FnDecl->getLocation(), 11269 diag::err_operator_new_delete_declared_in_namespace) 11270 << FnDecl->getDeclName(); 11271 } 11272 11273 if (isa<TranslationUnitDecl>(DC) && 11274 FnDecl->getStorageClass() == SC_Static) { 11275 return SemaRef.Diag(FnDecl->getLocation(), 11276 diag::err_operator_new_delete_declared_static) 11277 << FnDecl->getDeclName(); 11278 } 11279 11280 return false; 11281 } 11282 11283 static inline bool 11284 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 11285 CanQualType ExpectedResultType, 11286 CanQualType ExpectedFirstParamType, 11287 unsigned DependentParamTypeDiag, 11288 unsigned InvalidParamTypeDiag) { 11289 QualType ResultType = 11290 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 11291 11292 // Check that the result type is not dependent. 11293 if (ResultType->isDependentType()) 11294 return SemaRef.Diag(FnDecl->getLocation(), 11295 diag::err_operator_new_delete_dependent_result_type) 11296 << FnDecl->getDeclName() << ExpectedResultType; 11297 11298 // Check that the result type is what we expect. 11299 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 11300 return SemaRef.Diag(FnDecl->getLocation(), 11301 diag::err_operator_new_delete_invalid_result_type) 11302 << FnDecl->getDeclName() << ExpectedResultType; 11303 11304 // A function template must have at least 2 parameters. 11305 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 11306 return SemaRef.Diag(FnDecl->getLocation(), 11307 diag::err_operator_new_delete_template_too_few_parameters) 11308 << FnDecl->getDeclName(); 11309 11310 // The function decl must have at least 1 parameter. 11311 if (FnDecl->getNumParams() == 0) 11312 return SemaRef.Diag(FnDecl->getLocation(), 11313 diag::err_operator_new_delete_too_few_parameters) 11314 << FnDecl->getDeclName(); 11315 11316 // Check the first parameter type is not dependent. 11317 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 11318 if (FirstParamType->isDependentType()) 11319 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 11320 << FnDecl->getDeclName() << ExpectedFirstParamType; 11321 11322 // Check that the first parameter type is what we expect. 11323 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 11324 ExpectedFirstParamType) 11325 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 11326 << FnDecl->getDeclName() << ExpectedFirstParamType; 11327 11328 return false; 11329 } 11330 11331 static bool 11332 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 11333 // C++ [basic.stc.dynamic.allocation]p1: 11334 // A program is ill-formed if an allocation function is declared in a 11335 // namespace scope other than global scope or declared static in global 11336 // scope. 11337 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11338 return true; 11339 11340 CanQualType SizeTy = 11341 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 11342 11343 // C++ [basic.stc.dynamic.allocation]p1: 11344 // The return type shall be void*. The first parameter shall have type 11345 // std::size_t. 11346 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 11347 SizeTy, 11348 diag::err_operator_new_dependent_param_type, 11349 diag::err_operator_new_param_type)) 11350 return true; 11351 11352 // C++ [basic.stc.dynamic.allocation]p1: 11353 // The first parameter shall not have an associated default argument. 11354 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 11355 return SemaRef.Diag(FnDecl->getLocation(), 11356 diag::err_operator_new_default_arg) 11357 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 11358 11359 return false; 11360 } 11361 11362 static bool 11363 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 11364 // C++ [basic.stc.dynamic.deallocation]p1: 11365 // A program is ill-formed if deallocation functions are declared in a 11366 // namespace scope other than global scope or declared static in global 11367 // scope. 11368 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11369 return true; 11370 11371 // C++ [basic.stc.dynamic.deallocation]p2: 11372 // Each deallocation function shall return void and its first parameter 11373 // shall be void*. 11374 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 11375 SemaRef.Context.VoidPtrTy, 11376 diag::err_operator_delete_dependent_param_type, 11377 diag::err_operator_delete_param_type)) 11378 return true; 11379 11380 return false; 11381 } 11382 11383 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 11384 /// of this overloaded operator is well-formed. If so, returns false; 11385 /// otherwise, emits appropriate diagnostics and returns true. 11386 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 11387 assert(FnDecl && FnDecl->isOverloadedOperator() && 11388 "Expected an overloaded operator declaration"); 11389 11390 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 11391 11392 // C++ [over.oper]p5: 11393 // The allocation and deallocation functions, operator new, 11394 // operator new[], operator delete and operator delete[], are 11395 // described completely in 3.7.3. The attributes and restrictions 11396 // found in the rest of this subclause do not apply to them unless 11397 // explicitly stated in 3.7.3. 11398 if (Op == OO_Delete || Op == OO_Array_Delete) 11399 return CheckOperatorDeleteDeclaration(*this, FnDecl); 11400 11401 if (Op == OO_New || Op == OO_Array_New) 11402 return CheckOperatorNewDeclaration(*this, FnDecl); 11403 11404 // C++ [over.oper]p6: 11405 // An operator function shall either be a non-static member 11406 // function or be a non-member function and have at least one 11407 // parameter whose type is a class, a reference to a class, an 11408 // enumeration, or a reference to an enumeration. 11409 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 11410 if (MethodDecl->isStatic()) 11411 return Diag(FnDecl->getLocation(), 11412 diag::err_operator_overload_static) << FnDecl->getDeclName(); 11413 } else { 11414 bool ClassOrEnumParam = false; 11415 for (auto Param : FnDecl->params()) { 11416 QualType ParamType = Param->getType().getNonReferenceType(); 11417 if (ParamType->isDependentType() || ParamType->isRecordType() || 11418 ParamType->isEnumeralType()) { 11419 ClassOrEnumParam = true; 11420 break; 11421 } 11422 } 11423 11424 if (!ClassOrEnumParam) 11425 return Diag(FnDecl->getLocation(), 11426 diag::err_operator_overload_needs_class_or_enum) 11427 << FnDecl->getDeclName(); 11428 } 11429 11430 // C++ [over.oper]p8: 11431 // An operator function cannot have default arguments (8.3.6), 11432 // except where explicitly stated below. 11433 // 11434 // Only the function-call operator allows default arguments 11435 // (C++ [over.call]p1). 11436 if (Op != OO_Call) { 11437 for (auto Param : FnDecl->params()) { 11438 if (Param->hasDefaultArg()) 11439 return Diag(Param->getLocation(), 11440 diag::err_operator_overload_default_arg) 11441 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 11442 } 11443 } 11444 11445 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 11446 { false, false, false } 11447 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 11448 , { Unary, Binary, MemberOnly } 11449 #include "clang/Basic/OperatorKinds.def" 11450 }; 11451 11452 bool CanBeUnaryOperator = OperatorUses[Op][0]; 11453 bool CanBeBinaryOperator = OperatorUses[Op][1]; 11454 bool MustBeMemberOperator = OperatorUses[Op][2]; 11455 11456 // C++ [over.oper]p8: 11457 // [...] Operator functions cannot have more or fewer parameters 11458 // than the number required for the corresponding operator, as 11459 // described in the rest of this subclause. 11460 unsigned NumParams = FnDecl->getNumParams() 11461 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 11462 if (Op != OO_Call && 11463 ((NumParams == 1 && !CanBeUnaryOperator) || 11464 (NumParams == 2 && !CanBeBinaryOperator) || 11465 (NumParams < 1) || (NumParams > 2))) { 11466 // We have the wrong number of parameters. 11467 unsigned ErrorKind; 11468 if (CanBeUnaryOperator && CanBeBinaryOperator) { 11469 ErrorKind = 2; // 2 -> unary or binary. 11470 } else if (CanBeUnaryOperator) { 11471 ErrorKind = 0; // 0 -> unary 11472 } else { 11473 assert(CanBeBinaryOperator && 11474 "All non-call overloaded operators are unary or binary!"); 11475 ErrorKind = 1; // 1 -> binary 11476 } 11477 11478 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 11479 << FnDecl->getDeclName() << NumParams << ErrorKind; 11480 } 11481 11482 // Overloaded operators other than operator() cannot be variadic. 11483 if (Op != OO_Call && 11484 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 11485 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 11486 << FnDecl->getDeclName(); 11487 } 11488 11489 // Some operators must be non-static member functions. 11490 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 11491 return Diag(FnDecl->getLocation(), 11492 diag::err_operator_overload_must_be_member) 11493 << FnDecl->getDeclName(); 11494 } 11495 11496 // C++ [over.inc]p1: 11497 // The user-defined function called operator++ implements the 11498 // prefix and postfix ++ operator. If this function is a member 11499 // function with no parameters, or a non-member function with one 11500 // parameter of class or enumeration type, it defines the prefix 11501 // increment operator ++ for objects of that type. If the function 11502 // is a member function with one parameter (which shall be of type 11503 // int) or a non-member function with two parameters (the second 11504 // of which shall be of type int), it defines the postfix 11505 // increment operator ++ for objects of that type. 11506 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11507 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11508 QualType ParamType = LastParam->getType(); 11509 11510 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11511 !ParamType->isDependentType()) 11512 return Diag(LastParam->getLocation(), 11513 diag::err_operator_overload_post_incdec_must_be_int) 11514 << LastParam->getType() << (Op == OO_MinusMinus); 11515 } 11516 11517 return false; 11518 } 11519 11520 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11521 /// of this literal operator function is well-formed. If so, returns 11522 /// false; otherwise, emits appropriate diagnostics and returns true. 11523 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11524 if (isa<CXXMethodDecl>(FnDecl)) { 11525 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11526 << FnDecl->getDeclName(); 11527 return true; 11528 } 11529 11530 if (FnDecl->isExternC()) { 11531 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11532 return true; 11533 } 11534 11535 bool Valid = false; 11536 11537 // This might be the definition of a literal operator template. 11538 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11539 // This might be a specialization of a literal operator template. 11540 if (!TpDecl) 11541 TpDecl = FnDecl->getPrimaryTemplate(); 11542 11543 // template <char...> type operator "" name() and 11544 // template <class T, T...> type operator "" name() are the only valid 11545 // template signatures, and the only valid signatures with no parameters. 11546 if (TpDecl) { 11547 if (FnDecl->param_size() == 0) { 11548 // Must have one or two template parameters 11549 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11550 if (Params->size() == 1) { 11551 NonTypeTemplateParmDecl *PmDecl = 11552 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11553 11554 // The template parameter must be a char parameter pack. 11555 if (PmDecl && PmDecl->isTemplateParameterPack() && 11556 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11557 Valid = true; 11558 } else if (Params->size() == 2) { 11559 TemplateTypeParmDecl *PmType = 11560 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11561 NonTypeTemplateParmDecl *PmArgs = 11562 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11563 11564 // The second template parameter must be a parameter pack with the 11565 // first template parameter as its type. 11566 if (PmType && PmArgs && 11567 !PmType->isTemplateParameterPack() && 11568 PmArgs->isTemplateParameterPack()) { 11569 const TemplateTypeParmType *TArgs = 11570 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11571 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11572 TArgs->getIndex() == PmType->getIndex()) { 11573 Valid = true; 11574 if (ActiveTemplateInstantiations.empty()) 11575 Diag(FnDecl->getLocation(), 11576 diag::ext_string_literal_operator_template); 11577 } 11578 } 11579 } 11580 } 11581 } else if (FnDecl->param_size()) { 11582 // Check the first parameter 11583 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11584 11585 QualType T = (*Param)->getType().getUnqualifiedType(); 11586 11587 // unsigned long long int, long double, and any character type are allowed 11588 // as the only parameters. 11589 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11590 Context.hasSameType(T, Context.LongDoubleTy) || 11591 Context.hasSameType(T, Context.CharTy) || 11592 Context.hasSameType(T, Context.WideCharTy) || 11593 Context.hasSameType(T, Context.Char16Ty) || 11594 Context.hasSameType(T, Context.Char32Ty)) { 11595 if (++Param == FnDecl->param_end()) 11596 Valid = true; 11597 goto FinishedParams; 11598 } 11599 11600 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11601 const PointerType *PT = T->getAs<PointerType>(); 11602 if (!PT) 11603 goto FinishedParams; 11604 T = PT->getPointeeType(); 11605 if (!T.isConstQualified() || T.isVolatileQualified()) 11606 goto FinishedParams; 11607 T = T.getUnqualifiedType(); 11608 11609 // Move on to the second parameter; 11610 ++Param; 11611 11612 // If there is no second parameter, the first must be a const char * 11613 if (Param == FnDecl->param_end()) { 11614 if (Context.hasSameType(T, Context.CharTy)) 11615 Valid = true; 11616 goto FinishedParams; 11617 } 11618 11619 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11620 // are allowed as the first parameter to a two-parameter function 11621 if (!(Context.hasSameType(T, Context.CharTy) || 11622 Context.hasSameType(T, Context.WideCharTy) || 11623 Context.hasSameType(T, Context.Char16Ty) || 11624 Context.hasSameType(T, Context.Char32Ty))) 11625 goto FinishedParams; 11626 11627 // The second and final parameter must be an std::size_t 11628 T = (*Param)->getType().getUnqualifiedType(); 11629 if (Context.hasSameType(T, Context.getSizeType()) && 11630 ++Param == FnDecl->param_end()) 11631 Valid = true; 11632 } 11633 11634 // FIXME: This diagnostic is absolutely terrible. 11635 FinishedParams: 11636 if (!Valid) { 11637 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11638 << FnDecl->getDeclName(); 11639 return true; 11640 } 11641 11642 // A parameter-declaration-clause containing a default argument is not 11643 // equivalent to any of the permitted forms. 11644 for (auto Param : FnDecl->params()) { 11645 if (Param->hasDefaultArg()) { 11646 Diag(Param->getDefaultArgRange().getBegin(), 11647 diag::err_literal_operator_default_argument) 11648 << Param->getDefaultArgRange(); 11649 break; 11650 } 11651 } 11652 11653 StringRef LiteralName 11654 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11655 if (LiteralName[0] != '_') { 11656 // C++11 [usrlit.suffix]p1: 11657 // Literal suffix identifiers that do not start with an underscore 11658 // are reserved for future standardization. 11659 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11660 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11661 } 11662 11663 return false; 11664 } 11665 11666 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11667 /// linkage specification, including the language and (if present) 11668 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11669 /// language string literal. LBraceLoc, if valid, provides the location of 11670 /// the '{' brace. Otherwise, this linkage specification does not 11671 /// have any braces. 11672 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11673 Expr *LangStr, 11674 SourceLocation LBraceLoc) { 11675 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11676 if (!Lit->isAscii()) { 11677 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11678 << LangStr->getSourceRange(); 11679 return nullptr; 11680 } 11681 11682 StringRef Lang = Lit->getString(); 11683 LinkageSpecDecl::LanguageIDs Language; 11684 if (Lang == "C") 11685 Language = LinkageSpecDecl::lang_c; 11686 else if (Lang == "C++") 11687 Language = LinkageSpecDecl::lang_cxx; 11688 else { 11689 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11690 << LangStr->getSourceRange(); 11691 return nullptr; 11692 } 11693 11694 // FIXME: Add all the various semantics of linkage specifications 11695 11696 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11697 LangStr->getExprLoc(), Language, 11698 LBraceLoc.isValid()); 11699 CurContext->addDecl(D); 11700 PushDeclContext(S, D); 11701 return D; 11702 } 11703 11704 /// ActOnFinishLinkageSpecification - Complete the definition of 11705 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11706 /// valid, it's the position of the closing '}' brace in a linkage 11707 /// specification that uses braces. 11708 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11709 Decl *LinkageSpec, 11710 SourceLocation RBraceLoc) { 11711 if (RBraceLoc.isValid()) { 11712 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11713 LSDecl->setRBraceLoc(RBraceLoc); 11714 } 11715 PopDeclContext(); 11716 return LinkageSpec; 11717 } 11718 11719 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11720 AttributeList *AttrList, 11721 SourceLocation SemiLoc) { 11722 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11723 // Attribute declarations appertain to empty declaration so we handle 11724 // them here. 11725 if (AttrList) 11726 ProcessDeclAttributeList(S, ED, AttrList); 11727 11728 CurContext->addDecl(ED); 11729 return ED; 11730 } 11731 11732 /// \brief Perform semantic analysis for the variable declaration that 11733 /// occurs within a C++ catch clause, returning the newly-created 11734 /// variable. 11735 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11736 TypeSourceInfo *TInfo, 11737 SourceLocation StartLoc, 11738 SourceLocation Loc, 11739 IdentifierInfo *Name) { 11740 bool Invalid = false; 11741 QualType ExDeclType = TInfo->getType(); 11742 11743 // Arrays and functions decay. 11744 if (ExDeclType->isArrayType()) 11745 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11746 else if (ExDeclType->isFunctionType()) 11747 ExDeclType = Context.getPointerType(ExDeclType); 11748 11749 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11750 // The exception-declaration shall not denote a pointer or reference to an 11751 // incomplete type, other than [cv] void*. 11752 // N2844 forbids rvalue references. 11753 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11754 Diag(Loc, diag::err_catch_rvalue_ref); 11755 Invalid = true; 11756 } 11757 11758 QualType BaseType = ExDeclType; 11759 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11760 unsigned DK = diag::err_catch_incomplete; 11761 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11762 BaseType = Ptr->getPointeeType(); 11763 Mode = 1; 11764 DK = diag::err_catch_incomplete_ptr; 11765 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11766 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11767 BaseType = Ref->getPointeeType(); 11768 Mode = 2; 11769 DK = diag::err_catch_incomplete_ref; 11770 } 11771 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11772 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11773 Invalid = true; 11774 11775 if (!Invalid && !ExDeclType->isDependentType() && 11776 RequireNonAbstractType(Loc, ExDeclType, 11777 diag::err_abstract_type_in_decl, 11778 AbstractVariableType)) 11779 Invalid = true; 11780 11781 // Only the non-fragile NeXT runtime currently supports C++ catches 11782 // of ObjC types, and no runtime supports catching ObjC types by value. 11783 if (!Invalid && getLangOpts().ObjC1) { 11784 QualType T = ExDeclType; 11785 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11786 T = RT->getPointeeType(); 11787 11788 if (T->isObjCObjectType()) { 11789 Diag(Loc, diag::err_objc_object_catch); 11790 Invalid = true; 11791 } else if (T->isObjCObjectPointerType()) { 11792 // FIXME: should this be a test for macosx-fragile specifically? 11793 if (getLangOpts().ObjCRuntime.isFragile()) 11794 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11795 } 11796 } 11797 11798 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11799 ExDeclType, TInfo, SC_None); 11800 ExDecl->setExceptionVariable(true); 11801 11802 // In ARC, infer 'retaining' for variables of retainable type. 11803 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11804 Invalid = true; 11805 11806 if (!Invalid && !ExDeclType->isDependentType()) { 11807 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11808 // Insulate this from anything else we might currently be parsing. 11809 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11810 11811 // C++ [except.handle]p16: 11812 // The object declared in an exception-declaration or, if the 11813 // exception-declaration does not specify a name, a temporary (12.2) is 11814 // copy-initialized (8.5) from the exception object. [...] 11815 // The object is destroyed when the handler exits, after the destruction 11816 // of any automatic objects initialized within the handler. 11817 // 11818 // We just pretend to initialize the object with itself, then make sure 11819 // it can be destroyed later. 11820 QualType initType = ExDeclType; 11821 11822 InitializedEntity entity = 11823 InitializedEntity::InitializeVariable(ExDecl); 11824 InitializationKind initKind = 11825 InitializationKind::CreateCopy(Loc, SourceLocation()); 11826 11827 Expr *opaqueValue = 11828 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11829 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11830 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11831 if (result.isInvalid()) 11832 Invalid = true; 11833 else { 11834 // If the constructor used was non-trivial, set this as the 11835 // "initializer". 11836 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 11837 if (!construct->getConstructor()->isTrivial()) { 11838 Expr *init = MaybeCreateExprWithCleanups(construct); 11839 ExDecl->setInit(init); 11840 } 11841 11842 // And make sure it's destructable. 11843 FinalizeVarWithDestructor(ExDecl, recordType); 11844 } 11845 } 11846 } 11847 11848 if (Invalid) 11849 ExDecl->setInvalidDecl(); 11850 11851 return ExDecl; 11852 } 11853 11854 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11855 /// handler. 11856 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11857 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11858 bool Invalid = D.isInvalidType(); 11859 11860 // Check for unexpanded parameter packs. 11861 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11862 UPPC_ExceptionType)) { 11863 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11864 D.getIdentifierLoc()); 11865 Invalid = true; 11866 } 11867 11868 IdentifierInfo *II = D.getIdentifier(); 11869 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11870 LookupOrdinaryName, 11871 ForRedeclaration)) { 11872 // The scope should be freshly made just for us. There is just no way 11873 // it contains any previous declaration, except for function parameters in 11874 // a function-try-block's catch statement. 11875 assert(!S->isDeclScope(PrevDecl)); 11876 if (isDeclInScope(PrevDecl, CurContext, S)) { 11877 Diag(D.getIdentifierLoc(), diag::err_redefinition) 11878 << D.getIdentifier(); 11879 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11880 Invalid = true; 11881 } else if (PrevDecl->isTemplateParameter()) 11882 // Maybe we will complain about the shadowed template parameter. 11883 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11884 } 11885 11886 if (D.getCXXScopeSpec().isSet() && !Invalid) { 11887 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 11888 << D.getCXXScopeSpec().getRange(); 11889 Invalid = true; 11890 } 11891 11892 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 11893 D.getLocStart(), 11894 D.getIdentifierLoc(), 11895 D.getIdentifier()); 11896 if (Invalid) 11897 ExDecl->setInvalidDecl(); 11898 11899 // Add the exception declaration into this scope. 11900 if (II) 11901 PushOnScopeChains(ExDecl, S); 11902 else 11903 CurContext->addDecl(ExDecl); 11904 11905 ProcessDeclAttributes(S, ExDecl, D); 11906 return ExDecl; 11907 } 11908 11909 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11910 Expr *AssertExpr, 11911 Expr *AssertMessageExpr, 11912 SourceLocation RParenLoc) { 11913 StringLiteral *AssertMessage = 11914 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 11915 11916 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 11917 return nullptr; 11918 11919 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 11920 AssertMessage, RParenLoc, false); 11921 } 11922 11923 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11924 Expr *AssertExpr, 11925 StringLiteral *AssertMessage, 11926 SourceLocation RParenLoc, 11927 bool Failed) { 11928 assert(AssertExpr != nullptr && "Expected non-null condition"); 11929 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 11930 !Failed) { 11931 // In a static_assert-declaration, the constant-expression shall be a 11932 // constant expression that can be contextually converted to bool. 11933 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 11934 if (Converted.isInvalid()) 11935 Failed = true; 11936 11937 llvm::APSInt Cond; 11938 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 11939 diag::err_static_assert_expression_is_not_constant, 11940 /*AllowFold=*/false).isInvalid()) 11941 Failed = true; 11942 11943 if (!Failed && !Cond) { 11944 SmallString<256> MsgBuffer; 11945 llvm::raw_svector_ostream Msg(MsgBuffer); 11946 if (AssertMessage) 11947 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 11948 Diag(StaticAssertLoc, diag::err_static_assert_failed) 11949 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 11950 Failed = true; 11951 } 11952 } 11953 11954 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 11955 AssertExpr, AssertMessage, RParenLoc, 11956 Failed); 11957 11958 CurContext->addDecl(Decl); 11959 return Decl; 11960 } 11961 11962 /// \brief Perform semantic analysis of the given friend type declaration. 11963 /// 11964 /// \returns A friend declaration that. 11965 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 11966 SourceLocation FriendLoc, 11967 TypeSourceInfo *TSInfo) { 11968 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 11969 11970 QualType T = TSInfo->getType(); 11971 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 11972 11973 // C++03 [class.friend]p2: 11974 // An elaborated-type-specifier shall be used in a friend declaration 11975 // for a class.* 11976 // 11977 // * The class-key of the elaborated-type-specifier is required. 11978 if (!ActiveTemplateInstantiations.empty()) { 11979 // Do not complain about the form of friend template types during 11980 // template instantiation; we will already have complained when the 11981 // template was declared. 11982 } else { 11983 if (!T->isElaboratedTypeSpecifier()) { 11984 // If we evaluated the type to a record type, suggest putting 11985 // a tag in front. 11986 if (const RecordType *RT = T->getAs<RecordType>()) { 11987 RecordDecl *RD = RT->getDecl(); 11988 11989 SmallString<16> InsertionText(" "); 11990 InsertionText += RD->getKindName(); 11991 11992 Diag(TypeRange.getBegin(), 11993 getLangOpts().CPlusPlus11 ? 11994 diag::warn_cxx98_compat_unelaborated_friend_type : 11995 diag::ext_unelaborated_friend_type) 11996 << (unsigned) RD->getTagKind() 11997 << T 11998 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 11999 InsertionText); 12000 } else { 12001 Diag(FriendLoc, 12002 getLangOpts().CPlusPlus11 ? 12003 diag::warn_cxx98_compat_nonclass_type_friend : 12004 diag::ext_nonclass_type_friend) 12005 << T 12006 << TypeRange; 12007 } 12008 } else if (T->getAs<EnumType>()) { 12009 Diag(FriendLoc, 12010 getLangOpts().CPlusPlus11 ? 12011 diag::warn_cxx98_compat_enum_friend : 12012 diag::ext_enum_friend) 12013 << T 12014 << TypeRange; 12015 } 12016 12017 // C++11 [class.friend]p3: 12018 // A friend declaration that does not declare a function shall have one 12019 // of the following forms: 12020 // friend elaborated-type-specifier ; 12021 // friend simple-type-specifier ; 12022 // friend typename-specifier ; 12023 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 12024 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 12025 } 12026 12027 // If the type specifier in a friend declaration designates a (possibly 12028 // cv-qualified) class type, that class is declared as a friend; otherwise, 12029 // the friend declaration is ignored. 12030 return FriendDecl::Create(Context, CurContext, 12031 TSInfo->getTypeLoc().getLocStart(), TSInfo, 12032 FriendLoc); 12033 } 12034 12035 /// Handle a friend tag declaration where the scope specifier was 12036 /// templated. 12037 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 12038 unsigned TagSpec, SourceLocation TagLoc, 12039 CXXScopeSpec &SS, 12040 IdentifierInfo *Name, 12041 SourceLocation NameLoc, 12042 AttributeList *Attr, 12043 MultiTemplateParamsArg TempParamLists) { 12044 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 12045 12046 bool isExplicitSpecialization = false; 12047 bool Invalid = false; 12048 12049 if (TemplateParameterList *TemplateParams = 12050 MatchTemplateParametersToScopeSpecifier( 12051 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 12052 isExplicitSpecialization, Invalid)) { 12053 if (TemplateParams->size() > 0) { 12054 // This is a declaration of a class template. 12055 if (Invalid) 12056 return nullptr; 12057 12058 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 12059 NameLoc, Attr, TemplateParams, AS_public, 12060 /*ModulePrivateLoc=*/SourceLocation(), 12061 FriendLoc, TempParamLists.size() - 1, 12062 TempParamLists.data()).get(); 12063 } else { 12064 // The "template<>" header is extraneous. 12065 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 12066 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 12067 isExplicitSpecialization = true; 12068 } 12069 } 12070 12071 if (Invalid) return nullptr; 12072 12073 bool isAllExplicitSpecializations = true; 12074 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 12075 if (TempParamLists[I]->size()) { 12076 isAllExplicitSpecializations = false; 12077 break; 12078 } 12079 } 12080 12081 // FIXME: don't ignore attributes. 12082 12083 // If it's explicit specializations all the way down, just forget 12084 // about the template header and build an appropriate non-templated 12085 // friend. TODO: for source fidelity, remember the headers. 12086 if (isAllExplicitSpecializations) { 12087 if (SS.isEmpty()) { 12088 bool Owned = false; 12089 bool IsDependent = false; 12090 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 12091 Attr, AS_public, 12092 /*ModulePrivateLoc=*/SourceLocation(), 12093 MultiTemplateParamsArg(), Owned, IsDependent, 12094 /*ScopedEnumKWLoc=*/SourceLocation(), 12095 /*ScopedEnumUsesClassTag=*/false, 12096 /*UnderlyingType=*/TypeResult(), 12097 /*IsTypeSpecifier=*/false); 12098 } 12099 12100 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12101 ElaboratedTypeKeyword Keyword 12102 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12103 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 12104 *Name, NameLoc); 12105 if (T.isNull()) 12106 return nullptr; 12107 12108 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12109 if (isa<DependentNameType>(T)) { 12110 DependentNameTypeLoc TL = 12111 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12112 TL.setElaboratedKeywordLoc(TagLoc); 12113 TL.setQualifierLoc(QualifierLoc); 12114 TL.setNameLoc(NameLoc); 12115 } else { 12116 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 12117 TL.setElaboratedKeywordLoc(TagLoc); 12118 TL.setQualifierLoc(QualifierLoc); 12119 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 12120 } 12121 12122 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12123 TSI, FriendLoc, TempParamLists); 12124 Friend->setAccess(AS_public); 12125 CurContext->addDecl(Friend); 12126 return Friend; 12127 } 12128 12129 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 12130 12131 12132 12133 // Handle the case of a templated-scope friend class. e.g. 12134 // template <class T> class A<T>::B; 12135 // FIXME: we don't support these right now. 12136 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 12137 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 12138 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 12139 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 12140 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 12141 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 12142 TL.setElaboratedKeywordLoc(TagLoc); 12143 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 12144 TL.setNameLoc(NameLoc); 12145 12146 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 12147 TSI, FriendLoc, TempParamLists); 12148 Friend->setAccess(AS_public); 12149 Friend->setUnsupportedFriend(true); 12150 CurContext->addDecl(Friend); 12151 return Friend; 12152 } 12153 12154 12155 /// Handle a friend type declaration. This works in tandem with 12156 /// ActOnTag. 12157 /// 12158 /// Notes on friend class templates: 12159 /// 12160 /// We generally treat friend class declarations as if they were 12161 /// declaring a class. So, for example, the elaborated type specifier 12162 /// in a friend declaration is required to obey the restrictions of a 12163 /// class-head (i.e. no typedefs in the scope chain), template 12164 /// parameters are required to match up with simple template-ids, &c. 12165 /// However, unlike when declaring a template specialization, it's 12166 /// okay to refer to a template specialization without an empty 12167 /// template parameter declaration, e.g. 12168 /// friend class A<T>::B<unsigned>; 12169 /// We permit this as a special case; if there are any template 12170 /// parameters present at all, require proper matching, i.e. 12171 /// template <> template \<class T> friend class A<int>::B; 12172 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 12173 MultiTemplateParamsArg TempParams) { 12174 SourceLocation Loc = DS.getLocStart(); 12175 12176 assert(DS.isFriendSpecified()); 12177 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12178 12179 // Try to convert the decl specifier to a type. This works for 12180 // friend templates because ActOnTag never produces a ClassTemplateDecl 12181 // for a TUK_Friend. 12182 Declarator TheDeclarator(DS, Declarator::MemberContext); 12183 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 12184 QualType T = TSI->getType(); 12185 if (TheDeclarator.isInvalidType()) 12186 return nullptr; 12187 12188 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 12189 return nullptr; 12190 12191 // This is definitely an error in C++98. It's probably meant to 12192 // be forbidden in C++0x, too, but the specification is just 12193 // poorly written. 12194 // 12195 // The problem is with declarations like the following: 12196 // template <T> friend A<T>::foo; 12197 // where deciding whether a class C is a friend or not now hinges 12198 // on whether there exists an instantiation of A that causes 12199 // 'foo' to equal C. There are restrictions on class-heads 12200 // (which we declare (by fiat) elaborated friend declarations to 12201 // be) that makes this tractable. 12202 // 12203 // FIXME: handle "template <> friend class A<T>;", which 12204 // is possibly well-formed? Who even knows? 12205 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 12206 Diag(Loc, diag::err_tagless_friend_type_template) 12207 << DS.getSourceRange(); 12208 return nullptr; 12209 } 12210 12211 // C++98 [class.friend]p1: A friend of a class is a function 12212 // or class that is not a member of the class . . . 12213 // This is fixed in DR77, which just barely didn't make the C++03 12214 // deadline. It's also a very silly restriction that seriously 12215 // affects inner classes and which nobody else seems to implement; 12216 // thus we never diagnose it, not even in -pedantic. 12217 // 12218 // But note that we could warn about it: it's always useless to 12219 // friend one of your own members (it's not, however, worthless to 12220 // friend a member of an arbitrary specialization of your template). 12221 12222 Decl *D; 12223 if (unsigned NumTempParamLists = TempParams.size()) 12224 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 12225 NumTempParamLists, 12226 TempParams.data(), 12227 TSI, 12228 DS.getFriendSpecLoc()); 12229 else 12230 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 12231 12232 if (!D) 12233 return nullptr; 12234 12235 D->setAccess(AS_public); 12236 CurContext->addDecl(D); 12237 12238 return D; 12239 } 12240 12241 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 12242 MultiTemplateParamsArg TemplateParams) { 12243 const DeclSpec &DS = D.getDeclSpec(); 12244 12245 assert(DS.isFriendSpecified()); 12246 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12247 12248 SourceLocation Loc = D.getIdentifierLoc(); 12249 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12250 12251 // C++ [class.friend]p1 12252 // A friend of a class is a function or class.... 12253 // Note that this sees through typedefs, which is intended. 12254 // It *doesn't* see through dependent types, which is correct 12255 // according to [temp.arg.type]p3: 12256 // If a declaration acquires a function type through a 12257 // type dependent on a template-parameter and this causes 12258 // a declaration that does not use the syntactic form of a 12259 // function declarator to have a function type, the program 12260 // is ill-formed. 12261 if (!TInfo->getType()->isFunctionType()) { 12262 Diag(Loc, diag::err_unexpected_friend); 12263 12264 // It might be worthwhile to try to recover by creating an 12265 // appropriate declaration. 12266 return nullptr; 12267 } 12268 12269 // C++ [namespace.memdef]p3 12270 // - If a friend declaration in a non-local class first declares a 12271 // class or function, the friend class or function is a member 12272 // of the innermost enclosing namespace. 12273 // - The name of the friend is not found by simple name lookup 12274 // until a matching declaration is provided in that namespace 12275 // scope (either before or after the class declaration granting 12276 // friendship). 12277 // - If a friend function is called, its name may be found by the 12278 // name lookup that considers functions from namespaces and 12279 // classes associated with the types of the function arguments. 12280 // - When looking for a prior declaration of a class or a function 12281 // declared as a friend, scopes outside the innermost enclosing 12282 // namespace scope are not considered. 12283 12284 CXXScopeSpec &SS = D.getCXXScopeSpec(); 12285 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 12286 DeclarationName Name = NameInfo.getName(); 12287 assert(Name); 12288 12289 // Check for unexpanded parameter packs. 12290 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 12291 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 12292 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 12293 return nullptr; 12294 12295 // The context we found the declaration in, or in which we should 12296 // create the declaration. 12297 DeclContext *DC; 12298 Scope *DCScope = S; 12299 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12300 ForRedeclaration); 12301 12302 // There are five cases here. 12303 // - There's no scope specifier and we're in a local class. Only look 12304 // for functions declared in the immediately-enclosing block scope. 12305 // We recover from invalid scope qualifiers as if they just weren't there. 12306 FunctionDecl *FunctionContainingLocalClass = nullptr; 12307 if ((SS.isInvalid() || !SS.isSet()) && 12308 (FunctionContainingLocalClass = 12309 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 12310 // C++11 [class.friend]p11: 12311 // If a friend declaration appears in a local class and the name 12312 // specified is an unqualified name, a prior declaration is 12313 // looked up without considering scopes that are outside the 12314 // innermost enclosing non-class scope. For a friend function 12315 // declaration, if there is no prior declaration, the program is 12316 // ill-formed. 12317 12318 // Find the innermost enclosing non-class scope. This is the block 12319 // scope containing the local class definition (or for a nested class, 12320 // the outer local class). 12321 DCScope = S->getFnParent(); 12322 12323 // Look up the function name in the scope. 12324 Previous.clear(LookupLocalFriendName); 12325 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 12326 12327 if (!Previous.empty()) { 12328 // All possible previous declarations must have the same context: 12329 // either they were declared at block scope or they are members of 12330 // one of the enclosing local classes. 12331 DC = Previous.getRepresentativeDecl()->getDeclContext(); 12332 } else { 12333 // This is ill-formed, but provide the context that we would have 12334 // declared the function in, if we were permitted to, for error recovery. 12335 DC = FunctionContainingLocalClass; 12336 } 12337 adjustContextForLocalExternDecl(DC); 12338 12339 // C++ [class.friend]p6: 12340 // A function can be defined in a friend declaration of a class if and 12341 // only if the class is a non-local class (9.8), the function name is 12342 // unqualified, and the function has namespace scope. 12343 if (D.isFunctionDefinition()) { 12344 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 12345 } 12346 12347 // - There's no scope specifier, in which case we just go to the 12348 // appropriate scope and look for a function or function template 12349 // there as appropriate. 12350 } else if (SS.isInvalid() || !SS.isSet()) { 12351 // C++11 [namespace.memdef]p3: 12352 // If the name in a friend declaration is neither qualified nor 12353 // a template-id and the declaration is a function or an 12354 // elaborated-type-specifier, the lookup to determine whether 12355 // the entity has been previously declared shall not consider 12356 // any scopes outside the innermost enclosing namespace. 12357 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 12358 12359 // Find the appropriate context according to the above. 12360 DC = CurContext; 12361 12362 // Skip class contexts. If someone can cite chapter and verse 12363 // for this behavior, that would be nice --- it's what GCC and 12364 // EDG do, and it seems like a reasonable intent, but the spec 12365 // really only says that checks for unqualified existing 12366 // declarations should stop at the nearest enclosing namespace, 12367 // not that they should only consider the nearest enclosing 12368 // namespace. 12369 while (DC->isRecord()) 12370 DC = DC->getParent(); 12371 12372 DeclContext *LookupDC = DC; 12373 while (LookupDC->isTransparentContext()) 12374 LookupDC = LookupDC->getParent(); 12375 12376 while (true) { 12377 LookupQualifiedName(Previous, LookupDC); 12378 12379 if (!Previous.empty()) { 12380 DC = LookupDC; 12381 break; 12382 } 12383 12384 if (isTemplateId) { 12385 if (isa<TranslationUnitDecl>(LookupDC)) break; 12386 } else { 12387 if (LookupDC->isFileContext()) break; 12388 } 12389 LookupDC = LookupDC->getParent(); 12390 } 12391 12392 DCScope = getScopeForDeclContext(S, DC); 12393 12394 // - There's a non-dependent scope specifier, in which case we 12395 // compute it and do a previous lookup there for a function 12396 // or function template. 12397 } else if (!SS.getScopeRep()->isDependent()) { 12398 DC = computeDeclContext(SS); 12399 if (!DC) return nullptr; 12400 12401 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 12402 12403 LookupQualifiedName(Previous, DC); 12404 12405 // Ignore things found implicitly in the wrong scope. 12406 // TODO: better diagnostics for this case. Suggesting the right 12407 // qualified scope would be nice... 12408 LookupResult::Filter F = Previous.makeFilter(); 12409 while (F.hasNext()) { 12410 NamedDecl *D = F.next(); 12411 if (!DC->InEnclosingNamespaceSetOf( 12412 D->getDeclContext()->getRedeclContext())) 12413 F.erase(); 12414 } 12415 F.done(); 12416 12417 if (Previous.empty()) { 12418 D.setInvalidType(); 12419 Diag(Loc, diag::err_qualified_friend_not_found) 12420 << Name << TInfo->getType(); 12421 return nullptr; 12422 } 12423 12424 // C++ [class.friend]p1: A friend of a class is a function or 12425 // class that is not a member of the class . . . 12426 if (DC->Equals(CurContext)) 12427 Diag(DS.getFriendSpecLoc(), 12428 getLangOpts().CPlusPlus11 ? 12429 diag::warn_cxx98_compat_friend_is_member : 12430 diag::err_friend_is_member); 12431 12432 if (D.isFunctionDefinition()) { 12433 // C++ [class.friend]p6: 12434 // A function can be defined in a friend declaration of a class if and 12435 // only if the class is a non-local class (9.8), the function name is 12436 // unqualified, and the function has namespace scope. 12437 SemaDiagnosticBuilder DB 12438 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 12439 12440 DB << SS.getScopeRep(); 12441 if (DC->isFileContext()) 12442 DB << FixItHint::CreateRemoval(SS.getRange()); 12443 SS.clear(); 12444 } 12445 12446 // - There's a scope specifier that does not match any template 12447 // parameter lists, in which case we use some arbitrary context, 12448 // create a method or method template, and wait for instantiation. 12449 // - There's a scope specifier that does match some template 12450 // parameter lists, which we don't handle right now. 12451 } else { 12452 if (D.isFunctionDefinition()) { 12453 // C++ [class.friend]p6: 12454 // A function can be defined in a friend declaration of a class if and 12455 // only if the class is a non-local class (9.8), the function name is 12456 // unqualified, and the function has namespace scope. 12457 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 12458 << SS.getScopeRep(); 12459 } 12460 12461 DC = CurContext; 12462 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 12463 } 12464 12465 if (!DC->isRecord()) { 12466 // This implies that it has to be an operator or function. 12467 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 12468 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 12469 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 12470 Diag(Loc, diag::err_introducing_special_friend) << 12471 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 12472 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 12473 return nullptr; 12474 } 12475 } 12476 12477 // FIXME: This is an egregious hack to cope with cases where the scope stack 12478 // does not contain the declaration context, i.e., in an out-of-line 12479 // definition of a class. 12480 Scope FakeDCScope(S, Scope::DeclScope, Diags); 12481 if (!DCScope) { 12482 FakeDCScope.setEntity(DC); 12483 DCScope = &FakeDCScope; 12484 } 12485 12486 bool AddToScope = true; 12487 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 12488 TemplateParams, AddToScope); 12489 if (!ND) return nullptr; 12490 12491 assert(ND->getLexicalDeclContext() == CurContext); 12492 12493 // If we performed typo correction, we might have added a scope specifier 12494 // and changed the decl context. 12495 DC = ND->getDeclContext(); 12496 12497 // Add the function declaration to the appropriate lookup tables, 12498 // adjusting the redeclarations list as necessary. We don't 12499 // want to do this yet if the friending class is dependent. 12500 // 12501 // Also update the scope-based lookup if the target context's 12502 // lookup context is in lexical scope. 12503 if (!CurContext->isDependentContext()) { 12504 DC = DC->getRedeclContext(); 12505 DC->makeDeclVisibleInContext(ND); 12506 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12507 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12508 } 12509 12510 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12511 D.getIdentifierLoc(), ND, 12512 DS.getFriendSpecLoc()); 12513 FrD->setAccess(AS_public); 12514 CurContext->addDecl(FrD); 12515 12516 if (ND->isInvalidDecl()) { 12517 FrD->setInvalidDecl(); 12518 } else { 12519 if (DC->isRecord()) CheckFriendAccess(ND); 12520 12521 FunctionDecl *FD; 12522 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12523 FD = FTD->getTemplatedDecl(); 12524 else 12525 FD = cast<FunctionDecl>(ND); 12526 12527 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12528 // default argument expression, that declaration shall be a definition 12529 // and shall be the only declaration of the function or function 12530 // template in the translation unit. 12531 if (functionDeclHasDefaultArgument(FD)) { 12532 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12533 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12534 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12535 } else if (!D.isFunctionDefinition()) 12536 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12537 } 12538 12539 // Mark templated-scope function declarations as unsupported. 12540 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 12541 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 12542 << SS.getScopeRep() << SS.getRange() 12543 << cast<CXXRecordDecl>(CurContext); 12544 FrD->setUnsupportedFriend(true); 12545 } 12546 } 12547 12548 return ND; 12549 } 12550 12551 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12552 AdjustDeclIfTemplate(Dcl); 12553 12554 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12555 if (!Fn) { 12556 Diag(DelLoc, diag::err_deleted_non_function); 12557 return; 12558 } 12559 12560 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12561 // Don't consider the implicit declaration we generate for explicit 12562 // specializations. FIXME: Do not generate these implicit declarations. 12563 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12564 Prev->getPreviousDecl()) && 12565 !Prev->isDefined()) { 12566 Diag(DelLoc, diag::err_deleted_decl_not_first); 12567 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12568 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12569 : diag::note_previous_declaration); 12570 } 12571 // If the declaration wasn't the first, we delete the function anyway for 12572 // recovery. 12573 Fn = Fn->getCanonicalDecl(); 12574 } 12575 12576 // dllimport/dllexport cannot be deleted. 12577 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12578 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12579 Fn->setInvalidDecl(); 12580 } 12581 12582 if (Fn->isDeleted()) 12583 return; 12584 12585 // See if we're deleting a function which is already known to override a 12586 // non-deleted virtual function. 12587 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12588 bool IssuedDiagnostic = false; 12589 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12590 E = MD->end_overridden_methods(); 12591 I != E; ++I) { 12592 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12593 if (!IssuedDiagnostic) { 12594 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12595 IssuedDiagnostic = true; 12596 } 12597 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12598 } 12599 } 12600 } 12601 12602 // C++11 [basic.start.main]p3: 12603 // A program that defines main as deleted [...] is ill-formed. 12604 if (Fn->isMain()) 12605 Diag(DelLoc, diag::err_deleted_main); 12606 12607 Fn->setDeletedAsWritten(); 12608 } 12609 12610 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12611 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12612 12613 if (MD) { 12614 if (MD->getParent()->isDependentType()) { 12615 MD->setDefaulted(); 12616 MD->setExplicitlyDefaulted(); 12617 return; 12618 } 12619 12620 CXXSpecialMember Member = getSpecialMember(MD); 12621 if (Member == CXXInvalid) { 12622 if (!MD->isInvalidDecl()) 12623 Diag(DefaultLoc, diag::err_default_special_members); 12624 return; 12625 } 12626 12627 MD->setDefaulted(); 12628 MD->setExplicitlyDefaulted(); 12629 12630 // If this definition appears within the record, do the checking when 12631 // the record is complete. 12632 const FunctionDecl *Primary = MD; 12633 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12634 // Find the uninstantiated declaration that actually had the '= default' 12635 // on it. 12636 Pattern->isDefined(Primary); 12637 12638 // If the method was defaulted on its first declaration, we will have 12639 // already performed the checking in CheckCompletedCXXClass. Such a 12640 // declaration doesn't trigger an implicit definition. 12641 if (Primary == Primary->getCanonicalDecl()) 12642 return; 12643 12644 CheckExplicitlyDefaultedSpecialMember(MD); 12645 12646 if (MD->isInvalidDecl()) 12647 return; 12648 12649 switch (Member) { 12650 case CXXDefaultConstructor: 12651 DefineImplicitDefaultConstructor(DefaultLoc, 12652 cast<CXXConstructorDecl>(MD)); 12653 break; 12654 case CXXCopyConstructor: 12655 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12656 break; 12657 case CXXCopyAssignment: 12658 DefineImplicitCopyAssignment(DefaultLoc, MD); 12659 break; 12660 case CXXDestructor: 12661 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12662 break; 12663 case CXXMoveConstructor: 12664 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12665 break; 12666 case CXXMoveAssignment: 12667 DefineImplicitMoveAssignment(DefaultLoc, MD); 12668 break; 12669 case CXXInvalid: 12670 llvm_unreachable("Invalid special member."); 12671 } 12672 } else { 12673 Diag(DefaultLoc, diag::err_default_special_members); 12674 } 12675 } 12676 12677 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12678 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12679 Stmt *SubStmt = *CI; 12680 if (!SubStmt) 12681 continue; 12682 if (isa<ReturnStmt>(SubStmt)) 12683 Self.Diag(SubStmt->getLocStart(), 12684 diag::err_return_in_constructor_handler); 12685 if (!isa<Expr>(SubStmt)) 12686 SearchForReturnInStmt(Self, SubStmt); 12687 } 12688 } 12689 12690 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12691 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12692 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12693 SearchForReturnInStmt(*this, Handler); 12694 } 12695 } 12696 12697 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12698 const CXXMethodDecl *Old) { 12699 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12700 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12701 12702 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12703 12704 // If the calling conventions match, everything is fine 12705 if (NewCC == OldCC) 12706 return false; 12707 12708 // If the calling conventions mismatch because the new function is static, 12709 // suppress the calling convention mismatch error; the error about static 12710 // function override (err_static_overrides_virtual from 12711 // Sema::CheckFunctionDeclaration) is more clear. 12712 if (New->getStorageClass() == SC_Static) 12713 return false; 12714 12715 Diag(New->getLocation(), 12716 diag::err_conflicting_overriding_cc_attributes) 12717 << New->getDeclName() << New->getType() << Old->getType(); 12718 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12719 return true; 12720 } 12721 12722 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12723 const CXXMethodDecl *Old) { 12724 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12725 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12726 12727 if (Context.hasSameType(NewTy, OldTy) || 12728 NewTy->isDependentType() || OldTy->isDependentType()) 12729 return false; 12730 12731 // Check if the return types are covariant 12732 QualType NewClassTy, OldClassTy; 12733 12734 /// Both types must be pointers or references to classes. 12735 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12736 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12737 NewClassTy = NewPT->getPointeeType(); 12738 OldClassTy = OldPT->getPointeeType(); 12739 } 12740 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12741 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12742 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12743 NewClassTy = NewRT->getPointeeType(); 12744 OldClassTy = OldRT->getPointeeType(); 12745 } 12746 } 12747 } 12748 12749 // The return types aren't either both pointers or references to a class type. 12750 if (NewClassTy.isNull()) { 12751 Diag(New->getLocation(), 12752 diag::err_different_return_type_for_overriding_virtual_function) 12753 << New->getDeclName() << NewTy << OldTy 12754 << New->getReturnTypeSourceRange(); 12755 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12756 << Old->getReturnTypeSourceRange(); 12757 12758 return true; 12759 } 12760 12761 // C++ [class.virtual]p6: 12762 // If the return type of D::f differs from the return type of B::f, the 12763 // class type in the return type of D::f shall be complete at the point of 12764 // declaration of D::f or shall be the class type D. 12765 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12766 if (!RT->isBeingDefined() && 12767 RequireCompleteType(New->getLocation(), NewClassTy, 12768 diag::err_covariant_return_incomplete, 12769 New->getDeclName())) 12770 return true; 12771 } 12772 12773 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12774 // Check if the new class derives from the old class. 12775 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12776 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 12777 << New->getDeclName() << NewTy << OldTy 12778 << New->getReturnTypeSourceRange(); 12779 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12780 << Old->getReturnTypeSourceRange(); 12781 return true; 12782 } 12783 12784 // Check if we the conversion from derived to base is valid. 12785 if (CheckDerivedToBaseConversion( 12786 NewClassTy, OldClassTy, 12787 diag::err_covariant_return_inaccessible_base, 12788 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12789 New->getLocation(), New->getReturnTypeSourceRange(), 12790 New->getDeclName(), nullptr)) { 12791 // FIXME: this note won't trigger for delayed access control 12792 // diagnostics, and it's impossible to get an undelayed error 12793 // here from access control during the original parse because 12794 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12795 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12796 << Old->getReturnTypeSourceRange(); 12797 return true; 12798 } 12799 } 12800 12801 // The qualifiers of the return types must be the same. 12802 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12803 Diag(New->getLocation(), 12804 diag::err_covariant_return_type_different_qualifications) 12805 << New->getDeclName() << NewTy << OldTy 12806 << New->getReturnTypeSourceRange(); 12807 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12808 << Old->getReturnTypeSourceRange(); 12809 return true; 12810 }; 12811 12812 12813 // The new class type must have the same or less qualifiers as the old type. 12814 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12815 Diag(New->getLocation(), 12816 diag::err_covariant_return_type_class_type_more_qualified) 12817 << New->getDeclName() << NewTy << OldTy 12818 << New->getReturnTypeSourceRange(); 12819 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12820 << Old->getReturnTypeSourceRange(); 12821 return true; 12822 }; 12823 12824 return false; 12825 } 12826 12827 /// \brief Mark the given method pure. 12828 /// 12829 /// \param Method the method to be marked pure. 12830 /// 12831 /// \param InitRange the source range that covers the "0" initializer. 12832 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12833 SourceLocation EndLoc = InitRange.getEnd(); 12834 if (EndLoc.isValid()) 12835 Method->setRangeEnd(EndLoc); 12836 12837 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12838 Method->setPure(); 12839 return false; 12840 } 12841 12842 if (!Method->isInvalidDecl()) 12843 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12844 << Method->getDeclName() << InitRange; 12845 return true; 12846 } 12847 12848 /// \brief Determine whether the given declaration is a static data member. 12849 static bool isStaticDataMember(const Decl *D) { 12850 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12851 return Var->isStaticDataMember(); 12852 12853 return false; 12854 } 12855 12856 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12857 /// an initializer for the out-of-line declaration 'Dcl'. The scope 12858 /// is a fresh scope pushed for just this purpose. 12859 /// 12860 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12861 /// static data member of class X, names should be looked up in the scope of 12862 /// class X. 12863 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12864 // If there is no declaration, there was an error parsing it. 12865 if (!D || D->isInvalidDecl()) 12866 return; 12867 12868 // We will always have a nested name specifier here, but this declaration 12869 // might not be out of line if the specifier names the current namespace: 12870 // extern int n; 12871 // int ::n = 0; 12872 if (D->isOutOfLine()) 12873 EnterDeclaratorContext(S, D->getDeclContext()); 12874 12875 // If we are parsing the initializer for a static data member, push a 12876 // new expression evaluation context that is associated with this static 12877 // data member. 12878 if (isStaticDataMember(D)) 12879 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12880 } 12881 12882 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12883 /// initializer for the out-of-line declaration 'D'. 12884 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12885 // If there is no declaration, there was an error parsing it. 12886 if (!D || D->isInvalidDecl()) 12887 return; 12888 12889 if (isStaticDataMember(D)) 12890 PopExpressionEvaluationContext(); 12891 12892 if (D->isOutOfLine()) 12893 ExitDeclaratorContext(S); 12894 } 12895 12896 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 12897 /// C++ if/switch/while/for statement. 12898 /// e.g: "if (int x = f()) {...}" 12899 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 12900 // C++ 6.4p2: 12901 // The declarator shall not specify a function or an array. 12902 // The type-specifier-seq shall not contain typedef and shall not declare a 12903 // new class or enumeration. 12904 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 12905 "Parser allowed 'typedef' as storage class of condition decl."); 12906 12907 Decl *Dcl = ActOnDeclarator(S, D); 12908 if (!Dcl) 12909 return true; 12910 12911 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 12912 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 12913 << D.getSourceRange(); 12914 return true; 12915 } 12916 12917 return Dcl; 12918 } 12919 12920 void Sema::LoadExternalVTableUses() { 12921 if (!ExternalSource) 12922 return; 12923 12924 SmallVector<ExternalVTableUse, 4> VTables; 12925 ExternalSource->ReadUsedVTables(VTables); 12926 SmallVector<VTableUse, 4> NewUses; 12927 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 12928 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 12929 = VTablesUsed.find(VTables[I].Record); 12930 // Even if a definition wasn't required before, it may be required now. 12931 if (Pos != VTablesUsed.end()) { 12932 if (!Pos->second && VTables[I].DefinitionRequired) 12933 Pos->second = true; 12934 continue; 12935 } 12936 12937 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 12938 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 12939 } 12940 12941 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 12942 } 12943 12944 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 12945 bool DefinitionRequired) { 12946 // Ignore any vtable uses in unevaluated operands or for classes that do 12947 // not have a vtable. 12948 if (!Class->isDynamicClass() || Class->isDependentContext() || 12949 CurContext->isDependentContext() || isUnevaluatedContext()) 12950 return; 12951 12952 // Try to insert this class into the map. 12953 LoadExternalVTableUses(); 12954 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12955 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 12956 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 12957 if (!Pos.second) { 12958 // If we already had an entry, check to see if we are promoting this vtable 12959 // to required a definition. If so, we need to reappend to the VTableUses 12960 // list, since we may have already processed the first entry. 12961 if (DefinitionRequired && !Pos.first->second) { 12962 Pos.first->second = true; 12963 } else { 12964 // Otherwise, we can early exit. 12965 return; 12966 } 12967 } else { 12968 // The Microsoft ABI requires that we perform the destructor body 12969 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 12970 // the deleting destructor is emitted with the vtable, not with the 12971 // destructor definition as in the Itanium ABI. 12972 // If it has a definition, we do the check at that point instead. 12973 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12974 Class->hasUserDeclaredDestructor() && 12975 !Class->getDestructor()->isDefined() && 12976 !Class->getDestructor()->isDeleted()) { 12977 CXXDestructorDecl *DD = Class->getDestructor(); 12978 ContextRAII SavedContext(*this, DD); 12979 CheckDestructor(DD); 12980 } 12981 } 12982 12983 // Local classes need to have their virtual members marked 12984 // immediately. For all other classes, we mark their virtual members 12985 // at the end of the translation unit. 12986 if (Class->isLocalClass()) 12987 MarkVirtualMembersReferenced(Loc, Class); 12988 else 12989 VTableUses.push_back(std::make_pair(Class, Loc)); 12990 } 12991 12992 bool Sema::DefineUsedVTables() { 12993 LoadExternalVTableUses(); 12994 if (VTableUses.empty()) 12995 return false; 12996 12997 // Note: The VTableUses vector could grow as a result of marking 12998 // the members of a class as "used", so we check the size each 12999 // time through the loop and prefer indices (which are stable) to 13000 // iterators (which are not). 13001 bool DefinedAnything = false; 13002 for (unsigned I = 0; I != VTableUses.size(); ++I) { 13003 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 13004 if (!Class) 13005 continue; 13006 13007 SourceLocation Loc = VTableUses[I].second; 13008 13009 bool DefineVTable = true; 13010 13011 // If this class has a key function, but that key function is 13012 // defined in another translation unit, we don't need to emit the 13013 // vtable even though we're using it. 13014 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 13015 if (KeyFunction && !KeyFunction->hasBody()) { 13016 // The key function is in another translation unit. 13017 DefineVTable = false; 13018 TemplateSpecializationKind TSK = 13019 KeyFunction->getTemplateSpecializationKind(); 13020 assert(TSK != TSK_ExplicitInstantiationDefinition && 13021 TSK != TSK_ImplicitInstantiation && 13022 "Instantiations don't have key functions"); 13023 (void)TSK; 13024 } else if (!KeyFunction) { 13025 // If we have a class with no key function that is the subject 13026 // of an explicit instantiation declaration, suppress the 13027 // vtable; it will live with the explicit instantiation 13028 // definition. 13029 bool IsExplicitInstantiationDeclaration 13030 = Class->getTemplateSpecializationKind() 13031 == TSK_ExplicitInstantiationDeclaration; 13032 for (auto R : Class->redecls()) { 13033 TemplateSpecializationKind TSK 13034 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 13035 if (TSK == TSK_ExplicitInstantiationDeclaration) 13036 IsExplicitInstantiationDeclaration = true; 13037 else if (TSK == TSK_ExplicitInstantiationDefinition) { 13038 IsExplicitInstantiationDeclaration = false; 13039 break; 13040 } 13041 } 13042 13043 if (IsExplicitInstantiationDeclaration) 13044 DefineVTable = false; 13045 } 13046 13047 // The exception specifications for all virtual members may be needed even 13048 // if we are not providing an authoritative form of the vtable in this TU. 13049 // We may choose to emit it available_externally anyway. 13050 if (!DefineVTable) { 13051 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 13052 continue; 13053 } 13054 13055 // Mark all of the virtual members of this class as referenced, so 13056 // that we can build a vtable. Then, tell the AST consumer that a 13057 // vtable for this class is required. 13058 DefinedAnything = true; 13059 MarkVirtualMembersReferenced(Loc, Class); 13060 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 13061 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 13062 13063 // Optionally warn if we're emitting a weak vtable. 13064 if (Class->isExternallyVisible() && 13065 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 13066 const FunctionDecl *KeyFunctionDef = nullptr; 13067 if (!KeyFunction || 13068 (KeyFunction->hasBody(KeyFunctionDef) && 13069 KeyFunctionDef->isInlined())) 13070 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 13071 TSK_ExplicitInstantiationDefinition 13072 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 13073 << Class; 13074 } 13075 } 13076 VTableUses.clear(); 13077 13078 return DefinedAnything; 13079 } 13080 13081 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 13082 const CXXRecordDecl *RD) { 13083 for (const auto *I : RD->methods()) 13084 if (I->isVirtual() && !I->isPure()) 13085 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 13086 } 13087 13088 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 13089 const CXXRecordDecl *RD) { 13090 // Mark all functions which will appear in RD's vtable as used. 13091 CXXFinalOverriderMap FinalOverriders; 13092 RD->getFinalOverriders(FinalOverriders); 13093 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 13094 E = FinalOverriders.end(); 13095 I != E; ++I) { 13096 for (OverridingMethods::const_iterator OI = I->second.begin(), 13097 OE = I->second.end(); 13098 OI != OE; ++OI) { 13099 assert(OI->second.size() > 0 && "no final overrider"); 13100 CXXMethodDecl *Overrider = OI->second.front().Method; 13101 13102 // C++ [basic.def.odr]p2: 13103 // [...] A virtual member function is used if it is not pure. [...] 13104 if (!Overrider->isPure()) 13105 MarkFunctionReferenced(Loc, Overrider); 13106 } 13107 } 13108 13109 // Only classes that have virtual bases need a VTT. 13110 if (RD->getNumVBases() == 0) 13111 return; 13112 13113 for (const auto &I : RD->bases()) { 13114 const CXXRecordDecl *Base = 13115 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 13116 if (Base->getNumVBases() == 0) 13117 continue; 13118 MarkVirtualMembersReferenced(Loc, Base); 13119 } 13120 } 13121 13122 /// SetIvarInitializers - This routine builds initialization ASTs for the 13123 /// Objective-C implementation whose ivars need be initialized. 13124 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 13125 if (!getLangOpts().CPlusPlus) 13126 return; 13127 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 13128 SmallVector<ObjCIvarDecl*, 8> ivars; 13129 CollectIvarsToConstructOrDestruct(OID, ivars); 13130 if (ivars.empty()) 13131 return; 13132 SmallVector<CXXCtorInitializer*, 32> AllToInit; 13133 for (unsigned i = 0; i < ivars.size(); i++) { 13134 FieldDecl *Field = ivars[i]; 13135 if (Field->isInvalidDecl()) 13136 continue; 13137 13138 CXXCtorInitializer *Member; 13139 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 13140 InitializationKind InitKind = 13141 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 13142 13143 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 13144 ExprResult MemberInit = 13145 InitSeq.Perform(*this, InitEntity, InitKind, None); 13146 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 13147 // Note, MemberInit could actually come back empty if no initialization 13148 // is required (e.g., because it would call a trivial default constructor) 13149 if (!MemberInit.get() || MemberInit.isInvalid()) 13150 continue; 13151 13152 Member = 13153 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 13154 SourceLocation(), 13155 MemberInit.getAs<Expr>(), 13156 SourceLocation()); 13157 AllToInit.push_back(Member); 13158 13159 // Be sure that the destructor is accessible and is marked as referenced. 13160 if (const RecordType *RecordTy = 13161 Context.getBaseElementType(Field->getType()) 13162 ->getAs<RecordType>()) { 13163 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 13164 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 13165 MarkFunctionReferenced(Field->getLocation(), Destructor); 13166 CheckDestructorAccess(Field->getLocation(), Destructor, 13167 PDiag(diag::err_access_dtor_ivar) 13168 << Context.getBaseElementType(Field->getType())); 13169 } 13170 } 13171 } 13172 ObjCImplementation->setIvarInitializers(Context, 13173 AllToInit.data(), AllToInit.size()); 13174 } 13175 } 13176 13177 static 13178 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 13179 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 13180 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 13181 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 13182 Sema &S) { 13183 if (Ctor->isInvalidDecl()) 13184 return; 13185 13186 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 13187 13188 // Target may not be determinable yet, for instance if this is a dependent 13189 // call in an uninstantiated template. 13190 if (Target) { 13191 const FunctionDecl *FNTarget = nullptr; 13192 (void)Target->hasBody(FNTarget); 13193 Target = const_cast<CXXConstructorDecl*>( 13194 cast_or_null<CXXConstructorDecl>(FNTarget)); 13195 } 13196 13197 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 13198 // Avoid dereferencing a null pointer here. 13199 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 13200 13201 if (!Current.insert(Canonical).second) 13202 return; 13203 13204 // We know that beyond here, we aren't chaining into a cycle. 13205 if (!Target || !Target->isDelegatingConstructor() || 13206 Target->isInvalidDecl() || Valid.count(TCanonical)) { 13207 Valid.insert(Current.begin(), Current.end()); 13208 Current.clear(); 13209 // We've hit a cycle. 13210 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 13211 Current.count(TCanonical)) { 13212 // If we haven't diagnosed this cycle yet, do so now. 13213 if (!Invalid.count(TCanonical)) { 13214 S.Diag((*Ctor->init_begin())->getSourceLocation(), 13215 diag::warn_delegating_ctor_cycle) 13216 << Ctor; 13217 13218 // Don't add a note for a function delegating directly to itself. 13219 if (TCanonical != Canonical) 13220 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 13221 13222 CXXConstructorDecl *C = Target; 13223 while (C->getCanonicalDecl() != Canonical) { 13224 const FunctionDecl *FNTarget = nullptr; 13225 (void)C->getTargetConstructor()->hasBody(FNTarget); 13226 assert(FNTarget && "Ctor cycle through bodiless function"); 13227 13228 C = const_cast<CXXConstructorDecl*>( 13229 cast<CXXConstructorDecl>(FNTarget)); 13230 S.Diag(C->getLocation(), diag::note_which_delegates_to); 13231 } 13232 } 13233 13234 Invalid.insert(Current.begin(), Current.end()); 13235 Current.clear(); 13236 } else { 13237 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 13238 } 13239 } 13240 13241 13242 void Sema::CheckDelegatingCtorCycles() { 13243 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 13244 13245 for (DelegatingCtorDeclsType::iterator 13246 I = DelegatingCtorDecls.begin(ExternalSource), 13247 E = DelegatingCtorDecls.end(); 13248 I != E; ++I) 13249 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 13250 13251 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 13252 CE = Invalid.end(); 13253 CI != CE; ++CI) 13254 (*CI)->setInvalidDecl(); 13255 } 13256 13257 namespace { 13258 /// \brief AST visitor that finds references to the 'this' expression. 13259 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 13260 Sema &S; 13261 13262 public: 13263 explicit FindCXXThisExpr(Sema &S) : S(S) { } 13264 13265 bool VisitCXXThisExpr(CXXThisExpr *E) { 13266 S.Diag(E->getLocation(), diag::err_this_static_member_func) 13267 << E->isImplicit(); 13268 return false; 13269 } 13270 }; 13271 } 13272 13273 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 13274 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13275 if (!TSInfo) 13276 return false; 13277 13278 TypeLoc TL = TSInfo->getTypeLoc(); 13279 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13280 if (!ProtoTL) 13281 return false; 13282 13283 // C++11 [expr.prim.general]p3: 13284 // [The expression this] shall not appear before the optional 13285 // cv-qualifier-seq and it shall not appear within the declaration of a 13286 // static member function (although its type and value category are defined 13287 // within a static member function as they are within a non-static member 13288 // function). [ Note: this is because declaration matching does not occur 13289 // until the complete declarator is known. - end note ] 13290 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13291 FindCXXThisExpr Finder(*this); 13292 13293 // If the return type came after the cv-qualifier-seq, check it now. 13294 if (Proto->hasTrailingReturn() && 13295 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 13296 return true; 13297 13298 // Check the exception specification. 13299 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 13300 return true; 13301 13302 return checkThisInStaticMemberFunctionAttributes(Method); 13303 } 13304 13305 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 13306 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13307 if (!TSInfo) 13308 return false; 13309 13310 TypeLoc TL = TSInfo->getTypeLoc(); 13311 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13312 if (!ProtoTL) 13313 return false; 13314 13315 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13316 FindCXXThisExpr Finder(*this); 13317 13318 switch (Proto->getExceptionSpecType()) { 13319 case EST_Unparsed: 13320 case EST_Uninstantiated: 13321 case EST_Unevaluated: 13322 case EST_BasicNoexcept: 13323 case EST_DynamicNone: 13324 case EST_MSAny: 13325 case EST_None: 13326 break; 13327 13328 case EST_ComputedNoexcept: 13329 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 13330 return true; 13331 13332 case EST_Dynamic: 13333 for (const auto &E : Proto->exceptions()) { 13334 if (!Finder.TraverseType(E)) 13335 return true; 13336 } 13337 break; 13338 } 13339 13340 return false; 13341 } 13342 13343 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 13344 FindCXXThisExpr Finder(*this); 13345 13346 // Check attributes. 13347 for (const auto *A : Method->attrs()) { 13348 // FIXME: This should be emitted by tblgen. 13349 Expr *Arg = nullptr; 13350 ArrayRef<Expr *> Args; 13351 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 13352 Arg = G->getArg(); 13353 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 13354 Arg = G->getArg(); 13355 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 13356 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 13357 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 13358 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 13359 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 13360 Arg = ETLF->getSuccessValue(); 13361 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 13362 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 13363 Arg = STLF->getSuccessValue(); 13364 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 13365 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 13366 Arg = LR->getArg(); 13367 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 13368 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 13369 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 13370 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13371 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 13372 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13373 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 13374 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13375 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 13376 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13377 13378 if (Arg && !Finder.TraverseStmt(Arg)) 13379 return true; 13380 13381 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 13382 if (!Finder.TraverseStmt(Args[I])) 13383 return true; 13384 } 13385 } 13386 13387 return false; 13388 } 13389 13390 void Sema::checkExceptionSpecification( 13391 bool IsTopLevel, ExceptionSpecificationType EST, 13392 ArrayRef<ParsedType> DynamicExceptions, 13393 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 13394 SmallVectorImpl<QualType> &Exceptions, 13395 FunctionProtoType::ExceptionSpecInfo &ESI) { 13396 Exceptions.clear(); 13397 ESI.Type = EST; 13398 if (EST == EST_Dynamic) { 13399 Exceptions.reserve(DynamicExceptions.size()); 13400 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 13401 // FIXME: Preserve type source info. 13402 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 13403 13404 if (IsTopLevel) { 13405 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 13406 collectUnexpandedParameterPacks(ET, Unexpanded); 13407 if (!Unexpanded.empty()) { 13408 DiagnoseUnexpandedParameterPacks( 13409 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 13410 Unexpanded); 13411 continue; 13412 } 13413 } 13414 13415 // Check that the type is valid for an exception spec, and 13416 // drop it if not. 13417 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 13418 Exceptions.push_back(ET); 13419 } 13420 ESI.Exceptions = Exceptions; 13421 return; 13422 } 13423 13424 if (EST == EST_ComputedNoexcept) { 13425 // If an error occurred, there's no expression here. 13426 if (NoexceptExpr) { 13427 assert((NoexceptExpr->isTypeDependent() || 13428 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 13429 Context.BoolTy) && 13430 "Parser should have made sure that the expression is boolean"); 13431 if (IsTopLevel && NoexceptExpr && 13432 DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 13433 ESI.Type = EST_BasicNoexcept; 13434 return; 13435 } 13436 13437 if (!NoexceptExpr->isValueDependent()) 13438 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 13439 diag::err_noexcept_needs_constant_expression, 13440 /*AllowFold*/ false).get(); 13441 ESI.NoexceptExpr = NoexceptExpr; 13442 } 13443 return; 13444 } 13445 } 13446 13447 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 13448 ExceptionSpecificationType EST, 13449 SourceRange SpecificationRange, 13450 ArrayRef<ParsedType> DynamicExceptions, 13451 ArrayRef<SourceRange> DynamicExceptionRanges, 13452 Expr *NoexceptExpr) { 13453 if (!MethodD) 13454 return; 13455 13456 // Dig out the method we're referring to. 13457 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 13458 MethodD = FunTmpl->getTemplatedDecl(); 13459 13460 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 13461 if (!Method) 13462 return; 13463 13464 // Check the exception specification. 13465 llvm::SmallVector<QualType, 4> Exceptions; 13466 FunctionProtoType::ExceptionSpecInfo ESI; 13467 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 13468 DynamicExceptionRanges, NoexceptExpr, Exceptions, 13469 ESI); 13470 13471 // Update the exception specification on the function type. 13472 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 13473 13474 if (Method->isStatic()) 13475 checkThisInStaticMemberFunctionExceptionSpec(Method); 13476 13477 if (Method->isVirtual()) { 13478 // Check overrides, which we previously had to delay. 13479 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(), 13480 OEnd = Method->end_overridden_methods(); 13481 O != OEnd; ++O) 13482 CheckOverridingFunctionExceptionSpec(Method, *O); 13483 } 13484 } 13485 13486 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 13487 /// 13488 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 13489 SourceLocation DeclStart, 13490 Declarator &D, Expr *BitWidth, 13491 InClassInitStyle InitStyle, 13492 AccessSpecifier AS, 13493 AttributeList *MSPropertyAttr) { 13494 IdentifierInfo *II = D.getIdentifier(); 13495 if (!II) { 13496 Diag(DeclStart, diag::err_anonymous_property); 13497 return nullptr; 13498 } 13499 SourceLocation Loc = D.getIdentifierLoc(); 13500 13501 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13502 QualType T = TInfo->getType(); 13503 if (getLangOpts().CPlusPlus) { 13504 CheckExtraCXXDefaultArguments(D); 13505 13506 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13507 UPPC_DataMemberType)) { 13508 D.setInvalidType(); 13509 T = Context.IntTy; 13510 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13511 } 13512 } 13513 13514 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13515 13516 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13517 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13518 diag::err_invalid_thread) 13519 << DeclSpec::getSpecifierName(TSCS); 13520 13521 // Check to see if this name was declared as a member previously 13522 NamedDecl *PrevDecl = nullptr; 13523 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13524 LookupName(Previous, S); 13525 switch (Previous.getResultKind()) { 13526 case LookupResult::Found: 13527 case LookupResult::FoundUnresolvedValue: 13528 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13529 break; 13530 13531 case LookupResult::FoundOverloaded: 13532 PrevDecl = Previous.getRepresentativeDecl(); 13533 break; 13534 13535 case LookupResult::NotFound: 13536 case LookupResult::NotFoundInCurrentInstantiation: 13537 case LookupResult::Ambiguous: 13538 break; 13539 } 13540 13541 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13542 // Maybe we will complain about the shadowed template parameter. 13543 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13544 // Just pretend that we didn't see the previous declaration. 13545 PrevDecl = nullptr; 13546 } 13547 13548 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13549 PrevDecl = nullptr; 13550 13551 SourceLocation TSSL = D.getLocStart(); 13552 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13553 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13554 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13555 ProcessDeclAttributes(TUScope, NewPD, D); 13556 NewPD->setAccess(AS); 13557 13558 if (NewPD->isInvalidDecl()) 13559 Record->setInvalidDecl(); 13560 13561 if (D.getDeclSpec().isModulePrivateSpecified()) 13562 NewPD->setModulePrivate(); 13563 13564 if (NewPD->isInvalidDecl() && PrevDecl) { 13565 // Don't introduce NewFD into scope; there's already something 13566 // with the same name in the same scope. 13567 } else if (II) { 13568 PushOnScopeChains(NewPD, S); 13569 } else 13570 Record->addDecl(NewPD); 13571 13572 return NewPD; 13573 } 13574