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 "llvm/ADT/STLExtras.h" 40 #include "llvm/ADT/SmallString.h" 41 #include <map> 42 #include <set> 43 44 using namespace clang; 45 46 //===----------------------------------------------------------------------===// 47 // CheckDefaultArgumentVisitor 48 //===----------------------------------------------------------------------===// 49 50 namespace { 51 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 52 /// the default argument of a parameter to determine whether it 53 /// contains any ill-formed subexpressions. For example, this will 54 /// diagnose the use of local variables or parameters within the 55 /// default argument expression. 56 class CheckDefaultArgumentVisitor 57 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 58 Expr *DefaultArg; 59 Sema *S; 60 61 public: 62 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 63 : DefaultArg(defarg), S(s) {} 64 65 bool VisitExpr(Expr *Node); 66 bool VisitDeclRefExpr(DeclRefExpr *DRE); 67 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 68 bool VisitLambdaExpr(LambdaExpr *Lambda); 69 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 70 }; 71 72 /// VisitExpr - Visit all of the children of this expression. 73 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 74 bool IsInvalid = false; 75 for (Stmt::child_range I = Node->children(); I; ++I) 76 IsInvalid |= Visit(*I); 77 return IsInvalid; 78 } 79 80 /// VisitDeclRefExpr - Visit a reference to a declaration, to 81 /// determine whether this declaration can be used in the default 82 /// argument expression. 83 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 84 NamedDecl *Decl = DRE->getDecl(); 85 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 86 // C++ [dcl.fct.default]p9 87 // Default arguments are evaluated each time the function is 88 // called. The order of evaluation of function arguments is 89 // unspecified. Consequently, parameters of a function shall not 90 // be used in default argument expressions, even if they are not 91 // evaluated. Parameters of a function declared before a default 92 // argument expression are in scope and can hide namespace and 93 // class member names. 94 return S->Diag(DRE->getLocStart(), 95 diag::err_param_default_argument_references_param) 96 << Param->getDeclName() << DefaultArg->getSourceRange(); 97 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 98 // C++ [dcl.fct.default]p7 99 // Local variables shall not be used in default argument 100 // expressions. 101 if (VDecl->isLocalVarDecl()) 102 return S->Diag(DRE->getLocStart(), 103 diag::err_param_default_argument_references_local) 104 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 105 } 106 107 return false; 108 } 109 110 /// VisitCXXThisExpr - Visit a C++ "this" expression. 111 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 112 // C++ [dcl.fct.default]p8: 113 // The keyword this shall not be used in a default argument of a 114 // member function. 115 return S->Diag(ThisE->getLocStart(), 116 diag::err_param_default_argument_references_this) 117 << ThisE->getSourceRange(); 118 } 119 120 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 121 bool Invalid = false; 122 for (PseudoObjectExpr::semantics_iterator 123 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 124 Expr *E = *i; 125 126 // Look through bindings. 127 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 128 E = OVE->getSourceExpr(); 129 assert(E && "pseudo-object binding without source expression?"); 130 } 131 132 Invalid |= Visit(E); 133 } 134 return Invalid; 135 } 136 137 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 138 // C++11 [expr.lambda.prim]p13: 139 // A lambda-expression appearing in a default argument shall not 140 // implicitly or explicitly capture any entity. 141 if (Lambda->capture_begin() == Lambda->capture_end()) 142 return false; 143 144 return S->Diag(Lambda->getLocStart(), 145 diag::err_lambda_capture_default_arg); 146 } 147 } 148 149 void 150 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 151 const CXXMethodDecl *Method) { 152 // If we have an MSAny spec already, don't bother. 153 if (!Method || ComputedEST == EST_MSAny) 154 return; 155 156 const FunctionProtoType *Proto 157 = Method->getType()->getAs<FunctionProtoType>(); 158 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 159 if (!Proto) 160 return; 161 162 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 163 164 // If this function can throw any exceptions, make a note of that. 165 if (EST == EST_MSAny || EST == EST_None) { 166 ClearExceptions(); 167 ComputedEST = EST; 168 return; 169 } 170 171 // FIXME: If the call to this decl is using any of its default arguments, we 172 // need to search them for potentially-throwing calls. 173 174 // If this function has a basic noexcept, it doesn't affect the outcome. 175 if (EST == EST_BasicNoexcept) 176 return; 177 178 // If we have a throw-all spec at this point, ignore the function. 179 if (ComputedEST == EST_None) 180 return; 181 182 // If we're still at noexcept(true) and there's a nothrow() callee, 183 // change to that specification. 184 if (EST == EST_DynamicNone) { 185 if (ComputedEST == EST_BasicNoexcept) 186 ComputedEST = EST_DynamicNone; 187 return; 188 } 189 190 // Check out noexcept specs. 191 if (EST == EST_ComputedNoexcept) { 192 FunctionProtoType::NoexceptResult NR = 193 Proto->getNoexceptSpec(Self->Context); 194 assert(NR != FunctionProtoType::NR_NoNoexcept && 195 "Must have noexcept result for EST_ComputedNoexcept."); 196 assert(NR != FunctionProtoType::NR_Dependent && 197 "Should not generate implicit declarations for dependent cases, " 198 "and don't know how to handle them anyway."); 199 200 // noexcept(false) -> no spec on the new function 201 if (NR == FunctionProtoType::NR_Throw) { 202 ClearExceptions(); 203 ComputedEST = EST_None; 204 } 205 // noexcept(true) won't change anything either. 206 return; 207 } 208 209 assert(EST == EST_Dynamic && "EST case not considered earlier."); 210 assert(ComputedEST != EST_None && 211 "Shouldn't collect exceptions when throw-all is guaranteed."); 212 ComputedEST = EST_Dynamic; 213 // Record the exceptions in this function's exception specification. 214 for (const auto &E : Proto->exceptions()) 215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E))) 216 Exceptions.push_back(E); 217 } 218 219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 220 if (!E || ComputedEST == EST_MSAny) 221 return; 222 223 // FIXME: 224 // 225 // C++0x [except.spec]p14: 226 // [An] implicit exception-specification specifies the type-id T if and 227 // only if T is allowed by the exception-specification of a function directly 228 // invoked by f's implicit definition; f shall allow all exceptions if any 229 // function it directly invokes allows all exceptions, and f shall allow no 230 // exceptions if every function it directly invokes allows no exceptions. 231 // 232 // Note in particular that if an implicit exception-specification is generated 233 // for a function containing a throw-expression, that specification can still 234 // be noexcept(true). 235 // 236 // Note also that 'directly invoked' is not defined in the standard, and there 237 // is no indication that we should only consider potentially-evaluated calls. 238 // 239 // Ultimately we should implement the intent of the standard: the exception 240 // specification should be the set of exceptions which can be thrown by the 241 // implicit definition. For now, we assume that any non-nothrow expression can 242 // throw any exception. 243 244 if (Self->canThrow(E)) 245 ComputedEST = EST_None; 246 } 247 248 bool 249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 250 SourceLocation EqualLoc) { 251 if (RequireCompleteType(Param->getLocation(), Param->getType(), 252 diag::err_typecheck_decl_incomplete_type)) { 253 Param->setInvalidDecl(); 254 return true; 255 } 256 257 // C++ [dcl.fct.default]p5 258 // A default argument expression is implicitly converted (clause 259 // 4) to the parameter type. The default argument expression has 260 // the same semantic constraints as the initializer expression in 261 // a declaration of a variable of the parameter type, using the 262 // copy-initialization semantics (8.5). 263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 264 Param); 265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 266 EqualLoc); 267 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 269 if (Result.isInvalid()) 270 return true; 271 Arg = Result.getAs<Expr>(); 272 273 CheckCompletedExpr(Arg, EqualLoc); 274 Arg = MaybeCreateExprWithCleanups(Arg); 275 276 // Okay: add the default argument to the parameter 277 Param->setDefaultArg(Arg); 278 279 // We have already instantiated this parameter; provide each of the 280 // instantiations with the uninstantiated default argument. 281 UnparsedDefaultArgInstantiationsMap::iterator InstPos 282 = UnparsedDefaultArgInstantiations.find(Param); 283 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 286 287 // We're done tracking this parameter's instantiations. 288 UnparsedDefaultArgInstantiations.erase(InstPos); 289 } 290 291 return false; 292 } 293 294 /// ActOnParamDefaultArgument - Check whether the default argument 295 /// provided for a function parameter is well-formed. If so, attach it 296 /// to the parameter declaration. 297 void 298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 299 Expr *DefaultArg) { 300 if (!param || !DefaultArg) 301 return; 302 303 ParmVarDecl *Param = cast<ParmVarDecl>(param); 304 UnparsedDefaultArgLocs.erase(Param); 305 306 // Default arguments are only permitted in C++ 307 if (!getLangOpts().CPlusPlus) { 308 Diag(EqualLoc, diag::err_param_default_argument) 309 << DefaultArg->getSourceRange(); 310 Param->setInvalidDecl(); 311 return; 312 } 313 314 // Check for unexpanded parameter packs. 315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 316 Param->setInvalidDecl(); 317 return; 318 } 319 320 // Check that the default argument is well-formed 321 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 322 if (DefaultArgChecker.Visit(DefaultArg)) { 323 Param->setInvalidDecl(); 324 return; 325 } 326 327 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 328 } 329 330 /// ActOnParamUnparsedDefaultArgument - We've seen a default 331 /// argument for a function parameter, but we can't parse it yet 332 /// because we're inside a class definition. Note that this default 333 /// argument will be parsed later. 334 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 335 SourceLocation EqualLoc, 336 SourceLocation ArgLoc) { 337 if (!param) 338 return; 339 340 ParmVarDecl *Param = cast<ParmVarDecl>(param); 341 Param->setUnparsedDefaultArg(); 342 UnparsedDefaultArgLocs[Param] = ArgLoc; 343 } 344 345 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 346 /// the default argument for the parameter param failed. 347 void Sema::ActOnParamDefaultArgumentError(Decl *param, 348 SourceLocation EqualLoc) { 349 if (!param) 350 return; 351 352 ParmVarDecl *Param = cast<ParmVarDecl>(param); 353 Param->setInvalidDecl(); 354 UnparsedDefaultArgLocs.erase(Param); 355 Param->setDefaultArg(new(Context) 356 OpaqueValueExpr(EqualLoc, 357 Param->getType().getNonReferenceType(), 358 VK_RValue)); 359 } 360 361 /// CheckExtraCXXDefaultArguments - Check for any extra default 362 /// arguments in the declarator, which is not a function declaration 363 /// or definition and therefore is not permitted to have default 364 /// arguments. This routine should be invoked for every declarator 365 /// that is not a function declaration or definition. 366 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 367 // C++ [dcl.fct.default]p3 368 // A default argument expression shall be specified only in the 369 // parameter-declaration-clause of a function declaration or in a 370 // template-parameter (14.1). It shall not be specified for a 371 // parameter pack. If it is specified in a 372 // parameter-declaration-clause, it shall not occur within a 373 // declarator or abstract-declarator of a parameter-declaration. 374 bool MightBeFunction = D.isFunctionDeclarationContext(); 375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 376 DeclaratorChunk &chunk = D.getTypeObject(i); 377 if (chunk.Kind == DeclaratorChunk::Function) { 378 if (MightBeFunction) { 379 // This is a function declaration. It can have default arguments, but 380 // keep looking in case its return type is a function type with default 381 // arguments. 382 MightBeFunction = false; 383 continue; 384 } 385 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 386 ++argIdx) { 387 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 388 if (Param->hasUnparsedDefaultArg()) { 389 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens; 390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 391 << SourceRange((*Toks)[1].getLocation(), 392 Toks->back().getLocation()); 393 delete Toks; 394 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr; 395 } else if (Param->getDefaultArg()) { 396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 397 << Param->getDefaultArg()->getSourceRange(); 398 Param->setDefaultArg(nullptr); 399 } 400 } 401 } else if (chunk.Kind != DeclaratorChunk::Paren) { 402 MightBeFunction = false; 403 } 404 } 405 } 406 407 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 408 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 409 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 410 if (!PVD->hasDefaultArg()) 411 return false; 412 if (!PVD->hasInheritedDefaultArg()) 413 return true; 414 } 415 return false; 416 } 417 418 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 419 /// function, once we already know that they have the same 420 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 421 /// error, false otherwise. 422 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 423 Scope *S) { 424 bool Invalid = false; 425 426 // C++ [dcl.fct.default]p4: 427 // For non-template functions, default arguments can be added in 428 // later declarations of a function in the same 429 // scope. Declarations in different scopes have completely 430 // distinct sets of default arguments. That is, declarations in 431 // inner scopes do not acquire default arguments from 432 // declarations in outer scopes, and vice versa. In a given 433 // function declaration, all parameters subsequent to a 434 // parameter with a default argument shall have default 435 // arguments supplied in this or previous declarations. A 436 // default argument shall not be redefined by a later 437 // declaration (not even to the same value). 438 // 439 // C++ [dcl.fct.default]p6: 440 // Except for member functions of class templates, the default arguments 441 // in a member function definition that appears outside of the class 442 // definition are added to the set of default arguments provided by the 443 // member function declaration in the class definition. 444 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 445 ParmVarDecl *OldParam = Old->getParamDecl(p); 446 ParmVarDecl *NewParam = New->getParamDecl(p); 447 448 bool OldParamHasDfl = OldParam->hasDefaultArg(); 449 bool NewParamHasDfl = NewParam->hasDefaultArg(); 450 451 // The declaration context corresponding to the scope is the semantic 452 // parent, unless this is a local function declaration, in which case 453 // it is that surrounding function. 454 DeclContext *ScopeDC = New->isLocalExternDecl() 455 ? New->getLexicalDeclContext() 456 : New->getDeclContext(); 457 if (S && !isDeclInScope(Old, ScopeDC, S) && 458 !New->getDeclContext()->isRecord()) 459 // Ignore default parameters of old decl if they are not in 460 // the same scope and this is not an out-of-line definition of 461 // a member function. 462 OldParamHasDfl = false; 463 if (New->isLocalExternDecl() != Old->isLocalExternDecl()) 464 // If only one of these is a local function declaration, then they are 465 // declared in different scopes, even though isDeclInScope may think 466 // they're in the same scope. (If both are local, the scope check is 467 // sufficent, and if neither is local, then they are in the same scope.) 468 OldParamHasDfl = false; 469 470 if (OldParamHasDfl && NewParamHasDfl) { 471 472 unsigned DiagDefaultParamID = 473 diag::err_param_default_argument_redefinition; 474 475 // MSVC accepts that default parameters be redefined for member functions 476 // of template class. The new default parameter's value is ignored. 477 Invalid = true; 478 if (getLangOpts().MicrosoftExt) { 479 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 480 if (MD && MD->getParent()->getDescribedClassTemplate()) { 481 // Merge the old default argument into the new parameter. 482 NewParam->setHasInheritedDefaultArg(); 483 if (OldParam->hasUninstantiatedDefaultArg()) 484 NewParam->setUninstantiatedDefaultArg( 485 OldParam->getUninstantiatedDefaultArg()); 486 else 487 NewParam->setDefaultArg(OldParam->getInit()); 488 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 489 Invalid = false; 490 } 491 } 492 493 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 494 // hint here. Alternatively, we could walk the type-source information 495 // for NewParam to find the last source location in the type... but it 496 // isn't worth the effort right now. This is the kind of test case that 497 // is hard to get right: 498 // int f(int); 499 // void g(int (*fp)(int) = f); 500 // void g(int (*fp)(int) = &f); 501 Diag(NewParam->getLocation(), DiagDefaultParamID) 502 << NewParam->getDefaultArgRange(); 503 504 // Look for the function declaration where the default argument was 505 // actually written, which may be a declaration prior to Old. 506 for (FunctionDecl *Older = Old->getPreviousDecl(); 507 Older; Older = Older->getPreviousDecl()) { 508 if (!Older->getParamDecl(p)->hasDefaultArg()) 509 break; 510 511 OldParam = Older->getParamDecl(p); 512 } 513 514 Diag(OldParam->getLocation(), diag::note_previous_definition) 515 << OldParam->getDefaultArgRange(); 516 } else if (OldParamHasDfl) { 517 // Merge the old default argument into the new parameter. 518 // It's important to use getInit() here; getDefaultArg() 519 // strips off any top-level ExprWithCleanups. 520 NewParam->setHasInheritedDefaultArg(); 521 if (OldParam->hasUninstantiatedDefaultArg()) 522 NewParam->setUninstantiatedDefaultArg( 523 OldParam->getUninstantiatedDefaultArg()); 524 else 525 NewParam->setDefaultArg(OldParam->getInit()); 526 } else if (NewParamHasDfl) { 527 if (New->getDescribedFunctionTemplate()) { 528 // Paragraph 4, quoted above, only applies to non-template functions. 529 Diag(NewParam->getLocation(), 530 diag::err_param_default_argument_template_redecl) 531 << NewParam->getDefaultArgRange(); 532 Diag(Old->getLocation(), diag::note_template_prev_declaration) 533 << false; 534 } else if (New->getTemplateSpecializationKind() 535 != TSK_ImplicitInstantiation && 536 New->getTemplateSpecializationKind() != TSK_Undeclared) { 537 // C++ [temp.expr.spec]p21: 538 // Default function arguments shall not be specified in a declaration 539 // or a definition for one of the following explicit specializations: 540 // - the explicit specialization of a function template; 541 // - the explicit specialization of a member function template; 542 // - the explicit specialization of a member function of a class 543 // template where the class template specialization to which the 544 // member function specialization belongs is implicitly 545 // instantiated. 546 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 547 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 548 << New->getDeclName() 549 << NewParam->getDefaultArgRange(); 550 } else if (New->getDeclContext()->isDependentContext()) { 551 // C++ [dcl.fct.default]p6 (DR217): 552 // Default arguments for a member function of a class template shall 553 // be specified on the initial declaration of the member function 554 // within the class template. 555 // 556 // Reading the tea leaves a bit in DR217 and its reference to DR205 557 // leads me to the conclusion that one cannot add default function 558 // arguments for an out-of-line definition of a member function of a 559 // dependent type. 560 int WhichKind = 2; 561 if (CXXRecordDecl *Record 562 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 563 if (Record->getDescribedClassTemplate()) 564 WhichKind = 0; 565 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 566 WhichKind = 1; 567 else 568 WhichKind = 2; 569 } 570 571 Diag(NewParam->getLocation(), 572 diag::err_param_default_argument_member_template_redecl) 573 << WhichKind 574 << NewParam->getDefaultArgRange(); 575 } 576 } 577 } 578 579 // DR1344: If a default argument is added outside a class definition and that 580 // default argument makes the function a special member function, the program 581 // is ill-formed. This can only happen for constructors. 582 if (isa<CXXConstructorDecl>(New) && 583 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 584 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 585 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 586 if (NewSM != OldSM) { 587 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 588 assert(NewParam->hasDefaultArg()); 589 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 590 << NewParam->getDefaultArgRange() << NewSM; 591 Diag(Old->getLocation(), diag::note_previous_declaration); 592 } 593 } 594 595 const FunctionDecl *Def; 596 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 597 // template has a constexpr specifier then all its declarations shall 598 // contain the constexpr specifier. 599 if (New->isConstexpr() != Old->isConstexpr()) { 600 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 601 << New << New->isConstexpr(); 602 Diag(Old->getLocation(), diag::note_previous_declaration); 603 Invalid = true; 604 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) { 605 // C++11 [dcl.fcn.spec]p4: 606 // If the definition of a function appears in a translation unit before its 607 // first declaration as inline, the program is ill-formed. 608 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 609 Diag(Def->getLocation(), diag::note_previous_definition); 610 Invalid = true; 611 } 612 613 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 614 // argument expression, that declaration shall be a definition and shall be 615 // the only declaration of the function or function template in the 616 // translation unit. 617 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 618 functionDeclHasDefaultArgument(Old)) { 619 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 620 Diag(Old->getLocation(), diag::note_previous_declaration); 621 Invalid = true; 622 } 623 624 if (CheckEquivalentExceptionSpec(Old, New)) 625 Invalid = true; 626 627 return Invalid; 628 } 629 630 /// \brief Merge the exception specifications of two variable declarations. 631 /// 632 /// This is called when there's a redeclaration of a VarDecl. The function 633 /// checks if the redeclaration might have an exception specification and 634 /// validates compatibility and merges the specs if necessary. 635 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 636 // Shortcut if exceptions are disabled. 637 if (!getLangOpts().CXXExceptions) 638 return; 639 640 assert(Context.hasSameType(New->getType(), Old->getType()) && 641 "Should only be called if types are otherwise the same."); 642 643 QualType NewType = New->getType(); 644 QualType OldType = Old->getType(); 645 646 // We're only interested in pointers and references to functions, as well 647 // as pointers to member functions. 648 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 649 NewType = R->getPointeeType(); 650 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 651 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 652 NewType = P->getPointeeType(); 653 OldType = OldType->getAs<PointerType>()->getPointeeType(); 654 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 655 NewType = M->getPointeeType(); 656 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 657 } 658 659 if (!NewType->isFunctionProtoType()) 660 return; 661 662 // There's lots of special cases for functions. For function pointers, system 663 // libraries are hopefully not as broken so that we don't need these 664 // workarounds. 665 if (CheckEquivalentExceptionSpec( 666 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 667 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 668 New->setInvalidDecl(); 669 } 670 } 671 672 /// CheckCXXDefaultArguments - Verify that the default arguments for a 673 /// function declaration are well-formed according to C++ 674 /// [dcl.fct.default]. 675 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 676 unsigned NumParams = FD->getNumParams(); 677 unsigned p; 678 679 // Find first parameter with a default argument 680 for (p = 0; p < NumParams; ++p) { 681 ParmVarDecl *Param = FD->getParamDecl(p); 682 if (Param->hasDefaultArg()) 683 break; 684 } 685 686 // C++ [dcl.fct.default]p4: 687 // In a given function declaration, all parameters 688 // subsequent to a parameter with a default argument shall 689 // have default arguments supplied in this or previous 690 // declarations. A default argument shall not be redefined 691 // by a later declaration (not even to the same value). 692 unsigned LastMissingDefaultArg = 0; 693 for (; p < NumParams; ++p) { 694 ParmVarDecl *Param = FD->getParamDecl(p); 695 if (!Param->hasDefaultArg()) { 696 if (Param->isInvalidDecl()) 697 /* We already complained about this parameter. */; 698 else if (Param->getIdentifier()) 699 Diag(Param->getLocation(), 700 diag::err_param_default_argument_missing_name) 701 << Param->getIdentifier(); 702 else 703 Diag(Param->getLocation(), 704 diag::err_param_default_argument_missing); 705 706 LastMissingDefaultArg = p; 707 } 708 } 709 710 if (LastMissingDefaultArg > 0) { 711 // Some default arguments were missing. Clear out all of the 712 // default arguments up to (and including) the last missing 713 // default argument, so that we leave the function parameters 714 // in a semantically valid state. 715 for (p = 0; p <= LastMissingDefaultArg; ++p) { 716 ParmVarDecl *Param = FD->getParamDecl(p); 717 if (Param->hasDefaultArg()) { 718 Param->setDefaultArg(nullptr); 719 } 720 } 721 } 722 } 723 724 // CheckConstexprParameterTypes - Check whether a function's parameter types 725 // are all literal types. If so, return true. If not, produce a suitable 726 // diagnostic and return false. 727 static bool CheckConstexprParameterTypes(Sema &SemaRef, 728 const FunctionDecl *FD) { 729 unsigned ArgIndex = 0; 730 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 731 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 732 e = FT->param_type_end(); 733 i != e; ++i, ++ArgIndex) { 734 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 735 SourceLocation ParamLoc = PD->getLocation(); 736 if (!(*i)->isDependentType() && 737 SemaRef.RequireLiteralType(ParamLoc, *i, 738 diag::err_constexpr_non_literal_param, 739 ArgIndex+1, PD->getSourceRange(), 740 isa<CXXConstructorDecl>(FD))) 741 return false; 742 } 743 return true; 744 } 745 746 /// \brief Get diagnostic %select index for tag kind for 747 /// record diagnostic message. 748 /// WARNING: Indexes apply to particular diagnostics only! 749 /// 750 /// \returns diagnostic %select index. 751 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 752 switch (Tag) { 753 case TTK_Struct: return 0; 754 case TTK_Interface: return 1; 755 case TTK_Class: return 2; 756 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 757 } 758 } 759 760 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 761 // the requirements of a constexpr function definition or a constexpr 762 // constructor definition. If so, return true. If not, produce appropriate 763 // diagnostics and return false. 764 // 765 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 766 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 767 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 768 if (MD && MD->isInstance()) { 769 // C++11 [dcl.constexpr]p4: 770 // The definition of a constexpr constructor shall satisfy the following 771 // constraints: 772 // - the class shall not have any virtual base classes; 773 const CXXRecordDecl *RD = MD->getParent(); 774 if (RD->getNumVBases()) { 775 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 776 << isa<CXXConstructorDecl>(NewFD) 777 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 778 for (const auto &I : RD->vbases()) 779 Diag(I.getLocStart(), 780 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 781 return false; 782 } 783 } 784 785 if (!isa<CXXConstructorDecl>(NewFD)) { 786 // C++11 [dcl.constexpr]p3: 787 // The definition of a constexpr function shall satisfy the following 788 // constraints: 789 // - it shall not be virtual; 790 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 791 if (Method && Method->isVirtual()) { 792 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 793 794 // If it's not obvious why this function is virtual, find an overridden 795 // function which uses the 'virtual' keyword. 796 const CXXMethodDecl *WrittenVirtual = Method; 797 while (!WrittenVirtual->isVirtualAsWritten()) 798 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 799 if (WrittenVirtual != Method) 800 Diag(WrittenVirtual->getLocation(), 801 diag::note_overridden_virtual_function); 802 return false; 803 } 804 805 // - its return type shall be a literal type; 806 QualType RT = NewFD->getReturnType(); 807 if (!RT->isDependentType() && 808 RequireLiteralType(NewFD->getLocation(), RT, 809 diag::err_constexpr_non_literal_return)) 810 return false; 811 } 812 813 // - each of its parameter types shall be a literal type; 814 if (!CheckConstexprParameterTypes(*this, NewFD)) 815 return false; 816 817 return true; 818 } 819 820 /// Check the given declaration statement is legal within a constexpr function 821 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 822 /// 823 /// \return true if the body is OK (maybe only as an extension), false if we 824 /// have diagnosed a problem. 825 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 826 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 827 // C++11 [dcl.constexpr]p3 and p4: 828 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 829 // contain only 830 for (const auto *DclIt : DS->decls()) { 831 switch (DclIt->getKind()) { 832 case Decl::StaticAssert: 833 case Decl::Using: 834 case Decl::UsingShadow: 835 case Decl::UsingDirective: 836 case Decl::UnresolvedUsingTypename: 837 case Decl::UnresolvedUsingValue: 838 // - static_assert-declarations 839 // - using-declarations, 840 // - using-directives, 841 continue; 842 843 case Decl::Typedef: 844 case Decl::TypeAlias: { 845 // - typedef declarations and alias-declarations that do not define 846 // classes or enumerations, 847 const auto *TN = cast<TypedefNameDecl>(DclIt); 848 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 849 // Don't allow variably-modified types in constexpr functions. 850 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 851 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 852 << TL.getSourceRange() << TL.getType() 853 << isa<CXXConstructorDecl>(Dcl); 854 return false; 855 } 856 continue; 857 } 858 859 case Decl::Enum: 860 case Decl::CXXRecord: 861 // C++1y allows types to be defined, not just declared. 862 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 863 SemaRef.Diag(DS->getLocStart(), 864 SemaRef.getLangOpts().CPlusPlus14 865 ? diag::warn_cxx11_compat_constexpr_type_definition 866 : diag::ext_constexpr_type_definition) 867 << isa<CXXConstructorDecl>(Dcl); 868 continue; 869 870 case Decl::EnumConstant: 871 case Decl::IndirectField: 872 case Decl::ParmVar: 873 // These can only appear with other declarations which are banned in 874 // C++11 and permitted in C++1y, so ignore them. 875 continue; 876 877 case Decl::Var: { 878 // C++1y [dcl.constexpr]p3 allows anything except: 879 // a definition of a variable of non-literal type or of static or 880 // thread storage duration or for which no initialization is performed. 881 const auto *VD = cast<VarDecl>(DclIt); 882 if (VD->isThisDeclarationADefinition()) { 883 if (VD->isStaticLocal()) { 884 SemaRef.Diag(VD->getLocation(), 885 diag::err_constexpr_local_var_static) 886 << isa<CXXConstructorDecl>(Dcl) 887 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 888 return false; 889 } 890 if (!VD->getType()->isDependentType() && 891 SemaRef.RequireLiteralType( 892 VD->getLocation(), VD->getType(), 893 diag::err_constexpr_local_var_non_literal_type, 894 isa<CXXConstructorDecl>(Dcl))) 895 return false; 896 if (!VD->getType()->isDependentType() && 897 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 898 SemaRef.Diag(VD->getLocation(), 899 diag::err_constexpr_local_var_no_init) 900 << isa<CXXConstructorDecl>(Dcl); 901 return false; 902 } 903 } 904 SemaRef.Diag(VD->getLocation(), 905 SemaRef.getLangOpts().CPlusPlus14 906 ? diag::warn_cxx11_compat_constexpr_local_var 907 : diag::ext_constexpr_local_var) 908 << isa<CXXConstructorDecl>(Dcl); 909 continue; 910 } 911 912 case Decl::NamespaceAlias: 913 case Decl::Function: 914 // These are disallowed in C++11 and permitted in C++1y. Allow them 915 // everywhere as an extension. 916 if (!Cxx1yLoc.isValid()) 917 Cxx1yLoc = DS->getLocStart(); 918 continue; 919 920 default: 921 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 922 << isa<CXXConstructorDecl>(Dcl); 923 return false; 924 } 925 } 926 927 return true; 928 } 929 930 /// Check that the given field is initialized within a constexpr constructor. 931 /// 932 /// \param Dcl The constexpr constructor being checked. 933 /// \param Field The field being checked. This may be a member of an anonymous 934 /// struct or union nested within the class being checked. 935 /// \param Inits All declarations, including anonymous struct/union members and 936 /// indirect members, for which any initialization was provided. 937 /// \param Diagnosed Set to true if an error is produced. 938 static void CheckConstexprCtorInitializer(Sema &SemaRef, 939 const FunctionDecl *Dcl, 940 FieldDecl *Field, 941 llvm::SmallSet<Decl*, 16> &Inits, 942 bool &Diagnosed) { 943 if (Field->isInvalidDecl()) 944 return; 945 946 if (Field->isUnnamedBitfield()) 947 return; 948 949 // Anonymous unions with no variant members and empty anonymous structs do not 950 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 951 // indirect fields don't need initializing. 952 if (Field->isAnonymousStructOrUnion() && 953 (Field->getType()->isUnionType() 954 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 955 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 956 return; 957 958 if (!Inits.count(Field)) { 959 if (!Diagnosed) { 960 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 961 Diagnosed = true; 962 } 963 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 964 } else if (Field->isAnonymousStructOrUnion()) { 965 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 966 for (auto *I : RD->fields()) 967 // If an anonymous union contains an anonymous struct of which any member 968 // is initialized, all members must be initialized. 969 if (!RD->isUnion() || Inits.count(I)) 970 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 971 } 972 } 973 974 /// Check the provided statement is allowed in a constexpr function 975 /// definition. 976 static bool 977 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 978 SmallVectorImpl<SourceLocation> &ReturnStmts, 979 SourceLocation &Cxx1yLoc) { 980 // - its function-body shall be [...] a compound-statement that contains only 981 switch (S->getStmtClass()) { 982 case Stmt::NullStmtClass: 983 // - null statements, 984 return true; 985 986 case Stmt::DeclStmtClass: 987 // - static_assert-declarations 988 // - using-declarations, 989 // - using-directives, 990 // - typedef declarations and alias-declarations that do not define 991 // classes or enumerations, 992 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 993 return false; 994 return true; 995 996 case Stmt::ReturnStmtClass: 997 // - and exactly one return statement; 998 if (isa<CXXConstructorDecl>(Dcl)) { 999 // C++1y allows return statements in constexpr constructors. 1000 if (!Cxx1yLoc.isValid()) 1001 Cxx1yLoc = S->getLocStart(); 1002 return true; 1003 } 1004 1005 ReturnStmts.push_back(S->getLocStart()); 1006 return true; 1007 1008 case Stmt::CompoundStmtClass: { 1009 // C++1y allows compound-statements. 1010 if (!Cxx1yLoc.isValid()) 1011 Cxx1yLoc = S->getLocStart(); 1012 1013 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1014 for (auto *BodyIt : CompStmt->body()) { 1015 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1016 Cxx1yLoc)) 1017 return false; 1018 } 1019 return true; 1020 } 1021 1022 case Stmt::AttributedStmtClass: 1023 if (!Cxx1yLoc.isValid()) 1024 Cxx1yLoc = S->getLocStart(); 1025 return true; 1026 1027 case Stmt::IfStmtClass: { 1028 // C++1y allows if-statements. 1029 if (!Cxx1yLoc.isValid()) 1030 Cxx1yLoc = S->getLocStart(); 1031 1032 IfStmt *If = cast<IfStmt>(S); 1033 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1034 Cxx1yLoc)) 1035 return false; 1036 if (If->getElse() && 1037 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1038 Cxx1yLoc)) 1039 return false; 1040 return true; 1041 } 1042 1043 case Stmt::WhileStmtClass: 1044 case Stmt::DoStmtClass: 1045 case Stmt::ForStmtClass: 1046 case Stmt::CXXForRangeStmtClass: 1047 case Stmt::ContinueStmtClass: 1048 // C++1y allows all of these. We don't allow them as extensions in C++11, 1049 // because they don't make sense without variable mutation. 1050 if (!SemaRef.getLangOpts().CPlusPlus14) 1051 break; 1052 if (!Cxx1yLoc.isValid()) 1053 Cxx1yLoc = S->getLocStart(); 1054 for (Stmt::child_range Children = S->children(); Children; ++Children) 1055 if (*Children && 1056 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1057 Cxx1yLoc)) 1058 return false; 1059 return true; 1060 1061 case Stmt::SwitchStmtClass: 1062 case Stmt::CaseStmtClass: 1063 case Stmt::DefaultStmtClass: 1064 case Stmt::BreakStmtClass: 1065 // C++1y allows switch-statements, and since they don't need variable 1066 // mutation, we can reasonably allow them in C++11 as an extension. 1067 if (!Cxx1yLoc.isValid()) 1068 Cxx1yLoc = S->getLocStart(); 1069 for (Stmt::child_range Children = S->children(); Children; ++Children) 1070 if (*Children && 1071 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1072 Cxx1yLoc)) 1073 return false; 1074 return true; 1075 1076 default: 1077 if (!isa<Expr>(S)) 1078 break; 1079 1080 // C++1y allows expression-statements. 1081 if (!Cxx1yLoc.isValid()) 1082 Cxx1yLoc = S->getLocStart(); 1083 return true; 1084 } 1085 1086 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1087 << isa<CXXConstructorDecl>(Dcl); 1088 return false; 1089 } 1090 1091 /// Check the body for the given constexpr function declaration only contains 1092 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1093 /// 1094 /// \return true if the body is OK, false if we have diagnosed a problem. 1095 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1096 if (isa<CXXTryStmt>(Body)) { 1097 // C++11 [dcl.constexpr]p3: 1098 // The definition of a constexpr function shall satisfy the following 1099 // constraints: [...] 1100 // - its function-body shall be = delete, = default, or a 1101 // compound-statement 1102 // 1103 // C++11 [dcl.constexpr]p4: 1104 // In the definition of a constexpr constructor, [...] 1105 // - its function-body shall not be a function-try-block; 1106 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1107 << isa<CXXConstructorDecl>(Dcl); 1108 return false; 1109 } 1110 1111 SmallVector<SourceLocation, 4> ReturnStmts; 1112 1113 // - its function-body shall be [...] a compound-statement that contains only 1114 // [... list of cases ...] 1115 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1116 SourceLocation Cxx1yLoc; 1117 for (auto *BodyIt : CompBody->body()) { 1118 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1119 return false; 1120 } 1121 1122 if (Cxx1yLoc.isValid()) 1123 Diag(Cxx1yLoc, 1124 getLangOpts().CPlusPlus14 1125 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1126 : diag::ext_constexpr_body_invalid_stmt) 1127 << isa<CXXConstructorDecl>(Dcl); 1128 1129 if (const CXXConstructorDecl *Constructor 1130 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1131 const CXXRecordDecl *RD = Constructor->getParent(); 1132 // DR1359: 1133 // - every non-variant non-static data member and base class sub-object 1134 // shall be initialized; 1135 // DR1460: 1136 // - if the class is a union having variant members, exactly one of them 1137 // shall be initialized; 1138 if (RD->isUnion()) { 1139 if (Constructor->getNumCtorInitializers() == 0 && 1140 RD->hasVariantMembers()) { 1141 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1142 return false; 1143 } 1144 } else if (!Constructor->isDependentContext() && 1145 !Constructor->isDelegatingConstructor()) { 1146 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1147 1148 // Skip detailed checking if we have enough initializers, and we would 1149 // allow at most one initializer per member. 1150 bool AnyAnonStructUnionMembers = false; 1151 unsigned Fields = 0; 1152 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1153 E = RD->field_end(); I != E; ++I, ++Fields) { 1154 if (I->isAnonymousStructOrUnion()) { 1155 AnyAnonStructUnionMembers = true; 1156 break; 1157 } 1158 } 1159 // DR1460: 1160 // - if the class is a union-like class, but is not a union, for each of 1161 // its anonymous union members having variant members, exactly one of 1162 // them shall be initialized; 1163 if (AnyAnonStructUnionMembers || 1164 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1165 // Check initialization of non-static data members. Base classes are 1166 // always initialized so do not need to be checked. Dependent bases 1167 // might not have initializers in the member initializer list. 1168 llvm::SmallSet<Decl*, 16> Inits; 1169 for (const auto *I: Constructor->inits()) { 1170 if (FieldDecl *FD = I->getMember()) 1171 Inits.insert(FD); 1172 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1173 Inits.insert(ID->chain_begin(), ID->chain_end()); 1174 } 1175 1176 bool Diagnosed = false; 1177 for (auto *I : RD->fields()) 1178 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1179 if (Diagnosed) 1180 return false; 1181 } 1182 } 1183 } else { 1184 if (ReturnStmts.empty()) { 1185 // C++1y doesn't require constexpr functions to contain a 'return' 1186 // statement. We still do, unless the return type might be void, because 1187 // otherwise if there's no return statement, the function cannot 1188 // be used in a core constant expression. 1189 bool OK = getLangOpts().CPlusPlus14 && 1190 (Dcl->getReturnType()->isVoidType() || 1191 Dcl->getReturnType()->isDependentType()); 1192 Diag(Dcl->getLocation(), 1193 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1194 : diag::err_constexpr_body_no_return); 1195 return OK; 1196 } 1197 if (ReturnStmts.size() > 1) { 1198 Diag(ReturnStmts.back(), 1199 getLangOpts().CPlusPlus14 1200 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1201 : diag::ext_constexpr_body_multiple_return); 1202 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1203 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1204 } 1205 } 1206 1207 // C++11 [dcl.constexpr]p5: 1208 // if no function argument values exist such that the function invocation 1209 // substitution would produce a constant expression, the program is 1210 // ill-formed; no diagnostic required. 1211 // C++11 [dcl.constexpr]p3: 1212 // - every constructor call and implicit conversion used in initializing the 1213 // return value shall be one of those allowed in a constant expression. 1214 // C++11 [dcl.constexpr]p4: 1215 // - every constructor involved in initializing non-static data members and 1216 // base class sub-objects shall be a constexpr constructor. 1217 SmallVector<PartialDiagnosticAt, 8> Diags; 1218 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1219 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1220 << isa<CXXConstructorDecl>(Dcl); 1221 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1222 Diag(Diags[I].first, Diags[I].second); 1223 // Don't return false here: we allow this for compatibility in 1224 // system headers. 1225 } 1226 1227 return true; 1228 } 1229 1230 /// isCurrentClassName - Determine whether the identifier II is the 1231 /// name of the class type currently being defined. In the case of 1232 /// nested classes, this will only return true if II is the name of 1233 /// the innermost class. 1234 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1235 const CXXScopeSpec *SS) { 1236 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1237 1238 CXXRecordDecl *CurDecl; 1239 if (SS && SS->isSet() && !SS->isInvalid()) { 1240 DeclContext *DC = computeDeclContext(*SS, true); 1241 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1242 } else 1243 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1244 1245 if (CurDecl && CurDecl->getIdentifier()) 1246 return &II == CurDecl->getIdentifier(); 1247 return false; 1248 } 1249 1250 /// \brief Determine whether the identifier II is a typo for the name of 1251 /// the class type currently being defined. If so, update it to the identifier 1252 /// that should have been used. 1253 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1254 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1255 1256 if (!getLangOpts().SpellChecking) 1257 return false; 1258 1259 CXXRecordDecl *CurDecl; 1260 if (SS && SS->isSet() && !SS->isInvalid()) { 1261 DeclContext *DC = computeDeclContext(*SS, true); 1262 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1263 } else 1264 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1265 1266 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1267 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1268 < II->getLength()) { 1269 II = CurDecl->getIdentifier(); 1270 return true; 1271 } 1272 1273 return false; 1274 } 1275 1276 /// \brief Determine whether the given class is a base class of the given 1277 /// class, including looking at dependent bases. 1278 static bool findCircularInheritance(const CXXRecordDecl *Class, 1279 const CXXRecordDecl *Current) { 1280 SmallVector<const CXXRecordDecl*, 8> Queue; 1281 1282 Class = Class->getCanonicalDecl(); 1283 while (true) { 1284 for (const auto &I : Current->bases()) { 1285 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1286 if (!Base) 1287 continue; 1288 1289 Base = Base->getDefinition(); 1290 if (!Base) 1291 continue; 1292 1293 if (Base->getCanonicalDecl() == Class) 1294 return true; 1295 1296 Queue.push_back(Base); 1297 } 1298 1299 if (Queue.empty()) 1300 return false; 1301 1302 Current = Queue.pop_back_val(); 1303 } 1304 1305 return false; 1306 } 1307 1308 /// \brief Perform propagation of DLL attributes from a derived class to a 1309 /// templated base class for MS compatibility. 1310 static void propagateDLLAttrToBaseClassTemplate( 1311 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr, 1312 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 1313 if (getDLLAttr( 1314 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 1315 // If the base class template has a DLL attribute, don't try to change it. 1316 return; 1317 } 1318 1319 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 1320 // If the base class is not already specialized, we can do the propagation. 1321 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 1322 NewAttr->setInherited(true); 1323 BaseTemplateSpec->addAttr(NewAttr); 1324 return; 1325 } 1326 1327 bool DifferentAttribute = false; 1328 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) { 1329 if (!SpecializationAttr->isInherited()) { 1330 // The template has previously been specialized or instantiated with an 1331 // explicit attribute. We should not try to change it. 1332 return; 1333 } 1334 if (SpecializationAttr->getKind() == ClassAttr->getKind()) { 1335 // The specialization already has the right attribute. 1336 return; 1337 } 1338 DifferentAttribute = true; 1339 } 1340 1341 // The template was previously instantiated or explicitly specialized without 1342 // a dll attribute, or the template was previously instantiated with a 1343 // different inherited attribute. It's too late for us to change the 1344 // attribute, so warn that this is unsupported. 1345 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 1346 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute; 1347 S.Diag(ClassAttr->getLocation(), diag::note_attribute); 1348 if (BaseTemplateSpec->isExplicitSpecialization()) { 1349 S.Diag(BaseTemplateSpec->getLocation(), 1350 diag::note_template_class_explicit_specialization_was_here) 1351 << BaseTemplateSpec; 1352 } else { 1353 S.Diag(BaseTemplateSpec->getPointOfInstantiation(), 1354 diag::note_template_class_instantiation_was_here) 1355 << BaseTemplateSpec; 1356 } 1357 } 1358 1359 /// \brief Check the validity of a C++ base class specifier. 1360 /// 1361 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1362 /// and returns NULL otherwise. 1363 CXXBaseSpecifier * 1364 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1365 SourceRange SpecifierRange, 1366 bool Virtual, AccessSpecifier Access, 1367 TypeSourceInfo *TInfo, 1368 SourceLocation EllipsisLoc) { 1369 QualType BaseType = TInfo->getType(); 1370 1371 // C++ [class.union]p1: 1372 // A union shall not have base classes. 1373 if (Class->isUnion()) { 1374 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1375 << SpecifierRange; 1376 return nullptr; 1377 } 1378 1379 if (EllipsisLoc.isValid() && 1380 !TInfo->getType()->containsUnexpandedParameterPack()) { 1381 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1382 << TInfo->getTypeLoc().getSourceRange(); 1383 EllipsisLoc = SourceLocation(); 1384 } 1385 1386 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1387 1388 if (BaseType->isDependentType()) { 1389 // Make sure that we don't have circular inheritance among our dependent 1390 // bases. For non-dependent bases, the check for completeness below handles 1391 // this. 1392 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1393 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1394 ((BaseDecl = BaseDecl->getDefinition()) && 1395 findCircularInheritance(Class, BaseDecl))) { 1396 Diag(BaseLoc, diag::err_circular_inheritance) 1397 << BaseType << Context.getTypeDeclType(Class); 1398 1399 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1400 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1401 << BaseType; 1402 1403 return nullptr; 1404 } 1405 } 1406 1407 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1408 Class->getTagKind() == TTK_Class, 1409 Access, TInfo, EllipsisLoc); 1410 } 1411 1412 // Base specifiers must be record types. 1413 if (!BaseType->isRecordType()) { 1414 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1415 return nullptr; 1416 } 1417 1418 // C++ [class.union]p1: 1419 // A union shall not be used as a base class. 1420 if (BaseType->isUnionType()) { 1421 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1422 return nullptr; 1423 } 1424 1425 // For the MS ABI, propagate DLL attributes to base class templates. 1426 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1427 if (Attr *ClassAttr = getDLLAttr(Class)) { 1428 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1429 BaseType->getAsCXXRecordDecl())) { 1430 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr, 1431 BaseTemplate, BaseLoc); 1432 } 1433 } 1434 } 1435 1436 // C++ [class.derived]p2: 1437 // The class-name in a base-specifier shall not be an incompletely 1438 // defined class. 1439 if (RequireCompleteType(BaseLoc, BaseType, 1440 diag::err_incomplete_base_class, SpecifierRange)) { 1441 Class->setInvalidDecl(); 1442 return nullptr; 1443 } 1444 1445 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1446 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1447 assert(BaseDecl && "Record type has no declaration"); 1448 BaseDecl = BaseDecl->getDefinition(); 1449 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1450 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1451 assert(CXXBaseDecl && "Base type is not a C++ type"); 1452 1453 // A class which contains a flexible array member is not suitable for use as a 1454 // base class: 1455 // - If the layout determines that a base comes before another base, 1456 // the flexible array member would index into the subsequent base. 1457 // - If the layout determines that base comes before the derived class, 1458 // the flexible array member would index into the derived class. 1459 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1460 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1461 << CXXBaseDecl->getDeclName(); 1462 return nullptr; 1463 } 1464 1465 // C++ [class]p3: 1466 // If a class is marked final and it appears as a base-type-specifier in 1467 // base-clause, the program is ill-formed. 1468 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1469 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1470 << CXXBaseDecl->getDeclName() 1471 << FA->isSpelledAsSealed(); 1472 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 1473 << CXXBaseDecl->getDeclName() << FA->getRange(); 1474 return nullptr; 1475 } 1476 1477 if (BaseDecl->isInvalidDecl()) 1478 Class->setInvalidDecl(); 1479 1480 // Create the base specifier. 1481 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1482 Class->getTagKind() == TTK_Class, 1483 Access, TInfo, EllipsisLoc); 1484 } 1485 1486 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1487 /// one entry in the base class list of a class specifier, for 1488 /// example: 1489 /// class foo : public bar, virtual private baz { 1490 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1491 BaseResult 1492 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1493 ParsedAttributes &Attributes, 1494 bool Virtual, AccessSpecifier Access, 1495 ParsedType basetype, SourceLocation BaseLoc, 1496 SourceLocation EllipsisLoc) { 1497 if (!classdecl) 1498 return true; 1499 1500 AdjustDeclIfTemplate(classdecl); 1501 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1502 if (!Class) 1503 return true; 1504 1505 // We haven't yet attached the base specifiers. 1506 Class->setIsParsingBaseSpecifiers(); 1507 1508 // We do not support any C++11 attributes on base-specifiers yet. 1509 // Diagnose any attributes we see. 1510 if (!Attributes.empty()) { 1511 for (AttributeList *Attr = Attributes.getList(); Attr; 1512 Attr = Attr->getNext()) { 1513 if (Attr->isInvalid() || 1514 Attr->getKind() == AttributeList::IgnoredAttribute) 1515 continue; 1516 Diag(Attr->getLoc(), 1517 Attr->getKind() == AttributeList::UnknownAttribute 1518 ? diag::warn_unknown_attribute_ignored 1519 : diag::err_base_specifier_attribute) 1520 << Attr->getName(); 1521 } 1522 } 1523 1524 TypeSourceInfo *TInfo = nullptr; 1525 GetTypeFromParser(basetype, &TInfo); 1526 1527 if (EllipsisLoc.isInvalid() && 1528 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1529 UPPC_BaseType)) 1530 return true; 1531 1532 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1533 Virtual, Access, TInfo, 1534 EllipsisLoc)) 1535 return BaseSpec; 1536 else 1537 Class->setInvalidDecl(); 1538 1539 return true; 1540 } 1541 1542 /// \brief Performs the actual work of attaching the given base class 1543 /// specifiers to a C++ class. 1544 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1545 unsigned NumBases) { 1546 if (NumBases == 0) 1547 return false; 1548 1549 // Used to keep track of which base types we have already seen, so 1550 // that we can properly diagnose redundant direct base types. Note 1551 // that the key is always the unqualified canonical type of the base 1552 // class. 1553 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1554 1555 // Copy non-redundant base specifiers into permanent storage. 1556 unsigned NumGoodBases = 0; 1557 bool Invalid = false; 1558 for (unsigned idx = 0; idx < NumBases; ++idx) { 1559 QualType NewBaseType 1560 = Context.getCanonicalType(Bases[idx]->getType()); 1561 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1562 1563 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1564 if (KnownBase) { 1565 // C++ [class.mi]p3: 1566 // A class shall not be specified as a direct base class of a 1567 // derived class more than once. 1568 Diag(Bases[idx]->getLocStart(), 1569 diag::err_duplicate_base_class) 1570 << KnownBase->getType() 1571 << Bases[idx]->getSourceRange(); 1572 1573 // Delete the duplicate base class specifier; we're going to 1574 // overwrite its pointer later. 1575 Context.Deallocate(Bases[idx]); 1576 1577 Invalid = true; 1578 } else { 1579 // Okay, add this new base class. 1580 KnownBase = Bases[idx]; 1581 Bases[NumGoodBases++] = Bases[idx]; 1582 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1583 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1584 if (Class->isInterface() && 1585 (!RD->isInterface() || 1586 KnownBase->getAccessSpecifier() != AS_public)) { 1587 // The Microsoft extension __interface does not permit bases that 1588 // are not themselves public interfaces. 1589 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1590 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1591 << RD->getSourceRange(); 1592 Invalid = true; 1593 } 1594 if (RD->hasAttr<WeakAttr>()) 1595 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1596 } 1597 } 1598 } 1599 1600 // Attach the remaining base class specifiers to the derived class. 1601 Class->setBases(Bases, NumGoodBases); 1602 1603 // Delete the remaining (good) base class specifiers, since their 1604 // data has been copied into the CXXRecordDecl. 1605 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1606 Context.Deallocate(Bases[idx]); 1607 1608 return Invalid; 1609 } 1610 1611 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1612 /// class, after checking whether there are any duplicate base 1613 /// classes. 1614 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1615 unsigned NumBases) { 1616 if (!ClassDecl || !Bases || !NumBases) 1617 return; 1618 1619 AdjustDeclIfTemplate(ClassDecl); 1620 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1621 } 1622 1623 /// \brief Determine whether the type \p Derived is a C++ class that is 1624 /// derived from the type \p Base. 1625 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1626 if (!getLangOpts().CPlusPlus) 1627 return false; 1628 1629 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1630 if (!DerivedRD) 1631 return false; 1632 1633 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1634 if (!BaseRD) 1635 return false; 1636 1637 // If either the base or the derived type is invalid, don't try to 1638 // check whether one is derived from the other. 1639 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1640 return false; 1641 1642 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1643 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1644 } 1645 1646 /// \brief Determine whether the type \p Derived is a C++ class that is 1647 /// derived from the type \p Base. 1648 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1649 if (!getLangOpts().CPlusPlus) 1650 return false; 1651 1652 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1653 if (!DerivedRD) 1654 return false; 1655 1656 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1657 if (!BaseRD) 1658 return false; 1659 1660 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1661 } 1662 1663 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1664 CXXCastPath &BasePathArray) { 1665 assert(BasePathArray.empty() && "Base path array must be empty!"); 1666 assert(Paths.isRecordingPaths() && "Must record paths!"); 1667 1668 const CXXBasePath &Path = Paths.front(); 1669 1670 // We first go backward and check if we have a virtual base. 1671 // FIXME: It would be better if CXXBasePath had the base specifier for 1672 // the nearest virtual base. 1673 unsigned Start = 0; 1674 for (unsigned I = Path.size(); I != 0; --I) { 1675 if (Path[I - 1].Base->isVirtual()) { 1676 Start = I - 1; 1677 break; 1678 } 1679 } 1680 1681 // Now add all bases. 1682 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1683 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1684 } 1685 1686 /// \brief Determine whether the given base path includes a virtual 1687 /// base class. 1688 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1689 for (CXXCastPath::const_iterator B = BasePath.begin(), 1690 BEnd = BasePath.end(); 1691 B != BEnd; ++B) 1692 if ((*B)->isVirtual()) 1693 return true; 1694 1695 return false; 1696 } 1697 1698 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1699 /// conversion (where Derived and Base are class types) is 1700 /// well-formed, meaning that the conversion is unambiguous (and 1701 /// that all of the base classes are accessible). Returns true 1702 /// and emits a diagnostic if the code is ill-formed, returns false 1703 /// otherwise. Loc is the location where this routine should point to 1704 /// if there is an error, and Range is the source range to highlight 1705 /// if there is an error. 1706 bool 1707 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1708 unsigned InaccessibleBaseID, 1709 unsigned AmbigiousBaseConvID, 1710 SourceLocation Loc, SourceRange Range, 1711 DeclarationName Name, 1712 CXXCastPath *BasePath) { 1713 // First, determine whether the path from Derived to Base is 1714 // ambiguous. This is slightly more expensive than checking whether 1715 // the Derived to Base conversion exists, because here we need to 1716 // explore multiple paths to determine if there is an ambiguity. 1717 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1718 /*DetectVirtual=*/false); 1719 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1720 assert(DerivationOkay && 1721 "Can only be used with a derived-to-base conversion"); 1722 (void)DerivationOkay; 1723 1724 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1725 if (InaccessibleBaseID) { 1726 // Check that the base class can be accessed. 1727 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1728 InaccessibleBaseID)) { 1729 case AR_inaccessible: 1730 return true; 1731 case AR_accessible: 1732 case AR_dependent: 1733 case AR_delayed: 1734 break; 1735 } 1736 } 1737 1738 // Build a base path if necessary. 1739 if (BasePath) 1740 BuildBasePathArray(Paths, *BasePath); 1741 return false; 1742 } 1743 1744 if (AmbigiousBaseConvID) { 1745 // We know that the derived-to-base conversion is ambiguous, and 1746 // we're going to produce a diagnostic. Perform the derived-to-base 1747 // search just one more time to compute all of the possible paths so 1748 // that we can print them out. This is more expensive than any of 1749 // the previous derived-to-base checks we've done, but at this point 1750 // performance isn't as much of an issue. 1751 Paths.clear(); 1752 Paths.setRecordingPaths(true); 1753 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1754 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1755 (void)StillOkay; 1756 1757 // Build up a textual representation of the ambiguous paths, e.g., 1758 // D -> B -> A, that will be used to illustrate the ambiguous 1759 // conversions in the diagnostic. We only print one of the paths 1760 // to each base class subobject. 1761 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1762 1763 Diag(Loc, AmbigiousBaseConvID) 1764 << Derived << Base << PathDisplayStr << Range << Name; 1765 } 1766 return true; 1767 } 1768 1769 bool 1770 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1771 SourceLocation Loc, SourceRange Range, 1772 CXXCastPath *BasePath, 1773 bool IgnoreAccess) { 1774 return CheckDerivedToBaseConversion(Derived, Base, 1775 IgnoreAccess ? 0 1776 : diag::err_upcast_to_inaccessible_base, 1777 diag::err_ambiguous_derived_to_base_conv, 1778 Loc, Range, DeclarationName(), 1779 BasePath); 1780 } 1781 1782 1783 /// @brief Builds a string representing ambiguous paths from a 1784 /// specific derived class to different subobjects of the same base 1785 /// class. 1786 /// 1787 /// This function builds a string that can be used in error messages 1788 /// to show the different paths that one can take through the 1789 /// inheritance hierarchy to go from the derived class to different 1790 /// subobjects of a base class. The result looks something like this: 1791 /// @code 1792 /// struct D -> struct B -> struct A 1793 /// struct D -> struct C -> struct A 1794 /// @endcode 1795 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1796 std::string PathDisplayStr; 1797 std::set<unsigned> DisplayedPaths; 1798 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1799 Path != Paths.end(); ++Path) { 1800 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1801 // We haven't displayed a path to this particular base 1802 // class subobject yet. 1803 PathDisplayStr += "\n "; 1804 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1805 for (CXXBasePath::const_iterator Element = Path->begin(); 1806 Element != Path->end(); ++Element) 1807 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1808 } 1809 } 1810 1811 return PathDisplayStr; 1812 } 1813 1814 //===----------------------------------------------------------------------===// 1815 // C++ class member Handling 1816 //===----------------------------------------------------------------------===// 1817 1818 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1819 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1820 SourceLocation ASLoc, 1821 SourceLocation ColonLoc, 1822 AttributeList *Attrs) { 1823 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1824 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1825 ASLoc, ColonLoc); 1826 CurContext->addHiddenDecl(ASDecl); 1827 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1828 } 1829 1830 /// CheckOverrideControl - Check C++11 override control semantics. 1831 void Sema::CheckOverrideControl(NamedDecl *D) { 1832 if (D->isInvalidDecl()) 1833 return; 1834 1835 // We only care about "override" and "final" declarations. 1836 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1837 return; 1838 1839 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1840 1841 // We can't check dependent instance methods. 1842 if (MD && MD->isInstance() && 1843 (MD->getParent()->hasAnyDependentBases() || 1844 MD->getType()->isDependentType())) 1845 return; 1846 1847 if (MD && !MD->isVirtual()) { 1848 // If we have a non-virtual method, check if if hides a virtual method. 1849 // (In that case, it's most likely the method has the wrong type.) 1850 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1851 FindHiddenVirtualMethods(MD, OverloadedMethods); 1852 1853 if (!OverloadedMethods.empty()) { 1854 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1855 Diag(OA->getLocation(), 1856 diag::override_keyword_hides_virtual_member_function) 1857 << "override" << (OverloadedMethods.size() > 1); 1858 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1859 Diag(FA->getLocation(), 1860 diag::override_keyword_hides_virtual_member_function) 1861 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1862 << (OverloadedMethods.size() > 1); 1863 } 1864 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1865 MD->setInvalidDecl(); 1866 return; 1867 } 1868 // Fall through into the general case diagnostic. 1869 // FIXME: We might want to attempt typo correction here. 1870 } 1871 1872 if (!MD || !MD->isVirtual()) { 1873 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1874 Diag(OA->getLocation(), 1875 diag::override_keyword_only_allowed_on_virtual_member_functions) 1876 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1877 D->dropAttr<OverrideAttr>(); 1878 } 1879 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1880 Diag(FA->getLocation(), 1881 diag::override_keyword_only_allowed_on_virtual_member_functions) 1882 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1883 << FixItHint::CreateRemoval(FA->getLocation()); 1884 D->dropAttr<FinalAttr>(); 1885 } 1886 return; 1887 } 1888 1889 // C++11 [class.virtual]p5: 1890 // If a virtual function is marked with the virt-specifier override and 1891 // does not override a member function of a base class, the program is 1892 // ill-formed. 1893 bool HasOverriddenMethods = 1894 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1895 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1896 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1897 << MD->getDeclName(); 1898 } 1899 1900 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1901 /// function overrides a virtual member function marked 'final', according to 1902 /// C++11 [class.virtual]p4. 1903 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1904 const CXXMethodDecl *Old) { 1905 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1906 if (!FA) 1907 return false; 1908 1909 Diag(New->getLocation(), diag::err_final_function_overridden) 1910 << New->getDeclName() 1911 << FA->isSpelledAsSealed(); 1912 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1913 return true; 1914 } 1915 1916 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1917 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1918 // FIXME: Destruction of ObjC lifetime types has side-effects. 1919 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1920 return !RD->isCompleteDefinition() || 1921 !RD->hasTrivialDefaultConstructor() || 1922 !RD->hasTrivialDestructor(); 1923 return false; 1924 } 1925 1926 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1927 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 1928 if (it->isDeclspecPropertyAttribute()) 1929 return it; 1930 return nullptr; 1931 } 1932 1933 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1934 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1935 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1936 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1937 /// present (but parsing it has been deferred). 1938 NamedDecl * 1939 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1940 MultiTemplateParamsArg TemplateParameterLists, 1941 Expr *BW, const VirtSpecifiers &VS, 1942 InClassInitStyle InitStyle) { 1943 const DeclSpec &DS = D.getDeclSpec(); 1944 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1945 DeclarationName Name = NameInfo.getName(); 1946 SourceLocation Loc = NameInfo.getLoc(); 1947 1948 // For anonymous bitfields, the location should point to the type. 1949 if (Loc.isInvalid()) 1950 Loc = D.getLocStart(); 1951 1952 Expr *BitWidth = static_cast<Expr*>(BW); 1953 1954 assert(isa<CXXRecordDecl>(CurContext)); 1955 assert(!DS.isFriendSpecified()); 1956 1957 bool isFunc = D.isDeclarationOfFunction(); 1958 1959 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1960 // The Microsoft extension __interface only permits public member functions 1961 // and prohibits constructors, destructors, operators, non-public member 1962 // functions, static methods and data members. 1963 unsigned InvalidDecl; 1964 bool ShowDeclName = true; 1965 if (!isFunc) 1966 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1967 else if (AS != AS_public) 1968 InvalidDecl = 2; 1969 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1970 InvalidDecl = 3; 1971 else switch (Name.getNameKind()) { 1972 case DeclarationName::CXXConstructorName: 1973 InvalidDecl = 4; 1974 ShowDeclName = false; 1975 break; 1976 1977 case DeclarationName::CXXDestructorName: 1978 InvalidDecl = 5; 1979 ShowDeclName = false; 1980 break; 1981 1982 case DeclarationName::CXXOperatorName: 1983 case DeclarationName::CXXConversionFunctionName: 1984 InvalidDecl = 6; 1985 break; 1986 1987 default: 1988 InvalidDecl = 0; 1989 break; 1990 } 1991 1992 if (InvalidDecl) { 1993 if (ShowDeclName) 1994 Diag(Loc, diag::err_invalid_member_in_interface) 1995 << (InvalidDecl-1) << Name; 1996 else 1997 Diag(Loc, diag::err_invalid_member_in_interface) 1998 << (InvalidDecl-1) << ""; 1999 return nullptr; 2000 } 2001 } 2002 2003 // C++ 9.2p6: A member shall not be declared to have automatic storage 2004 // duration (auto, register) or with the extern storage-class-specifier. 2005 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2006 // data members and cannot be applied to names declared const or static, 2007 // and cannot be applied to reference members. 2008 switch (DS.getStorageClassSpec()) { 2009 case DeclSpec::SCS_unspecified: 2010 case DeclSpec::SCS_typedef: 2011 case DeclSpec::SCS_static: 2012 break; 2013 case DeclSpec::SCS_mutable: 2014 if (isFunc) { 2015 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2016 2017 // FIXME: It would be nicer if the keyword was ignored only for this 2018 // declarator. Otherwise we could get follow-up errors. 2019 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2020 } 2021 break; 2022 default: 2023 Diag(DS.getStorageClassSpecLoc(), 2024 diag::err_storageclass_invalid_for_member); 2025 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2026 break; 2027 } 2028 2029 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2030 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2031 !isFunc); 2032 2033 if (DS.isConstexprSpecified() && isInstField) { 2034 SemaDiagnosticBuilder B = 2035 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2036 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2037 if (InitStyle == ICIS_NoInit) { 2038 B << 0 << 0; 2039 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2040 B << FixItHint::CreateRemoval(ConstexprLoc); 2041 else { 2042 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2043 D.getMutableDeclSpec().ClearConstexprSpec(); 2044 const char *PrevSpec; 2045 unsigned DiagID; 2046 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2047 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2048 (void)Failed; 2049 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2050 } 2051 } else { 2052 B << 1; 2053 const char *PrevSpec; 2054 unsigned DiagID; 2055 if (D.getMutableDeclSpec().SetStorageClassSpec( 2056 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2057 Context.getPrintingPolicy())) { 2058 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2059 "This is the only DeclSpec that should fail to be applied"); 2060 B << 1; 2061 } else { 2062 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2063 isInstField = false; 2064 } 2065 } 2066 } 2067 2068 NamedDecl *Member; 2069 if (isInstField) { 2070 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2071 2072 // Data members must have identifiers for names. 2073 if (!Name.isIdentifier()) { 2074 Diag(Loc, diag::err_bad_variable_name) 2075 << Name; 2076 return nullptr; 2077 } 2078 2079 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2080 2081 // Member field could not be with "template" keyword. 2082 // So TemplateParameterLists should be empty in this case. 2083 if (TemplateParameterLists.size()) { 2084 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2085 if (TemplateParams->size()) { 2086 // There is no such thing as a member field template. 2087 Diag(D.getIdentifierLoc(), diag::err_template_member) 2088 << II 2089 << SourceRange(TemplateParams->getTemplateLoc(), 2090 TemplateParams->getRAngleLoc()); 2091 } else { 2092 // There is an extraneous 'template<>' for this member. 2093 Diag(TemplateParams->getTemplateLoc(), 2094 diag::err_template_member_noparams) 2095 << II 2096 << SourceRange(TemplateParams->getTemplateLoc(), 2097 TemplateParams->getRAngleLoc()); 2098 } 2099 return nullptr; 2100 } 2101 2102 if (SS.isSet() && !SS.isInvalid()) { 2103 // The user provided a superfluous scope specifier inside a class 2104 // definition: 2105 // 2106 // class X { 2107 // int X::member; 2108 // }; 2109 if (DeclContext *DC = computeDeclContext(SS, false)) 2110 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2111 else 2112 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2113 << Name << SS.getRange(); 2114 2115 SS.clear(); 2116 } 2117 2118 AttributeList *MSPropertyAttr = 2119 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2120 if (MSPropertyAttr) { 2121 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2122 BitWidth, InitStyle, AS, MSPropertyAttr); 2123 if (!Member) 2124 return nullptr; 2125 isInstField = false; 2126 } else { 2127 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2128 BitWidth, InitStyle, AS); 2129 assert(Member && "HandleField never returns null"); 2130 } 2131 } else { 2132 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2133 2134 Member = HandleDeclarator(S, D, TemplateParameterLists); 2135 if (!Member) 2136 return nullptr; 2137 2138 // Non-instance-fields can't have a bitfield. 2139 if (BitWidth) { 2140 if (Member->isInvalidDecl()) { 2141 // don't emit another diagnostic. 2142 } else if (isa<VarDecl>(Member)) { 2143 // C++ 9.6p3: A bit-field shall not be a static member. 2144 // "static member 'A' cannot be a bit-field" 2145 Diag(Loc, diag::err_static_not_bitfield) 2146 << Name << BitWidth->getSourceRange(); 2147 } else if (isa<TypedefDecl>(Member)) { 2148 // "typedef member 'x' cannot be a bit-field" 2149 Diag(Loc, diag::err_typedef_not_bitfield) 2150 << Name << BitWidth->getSourceRange(); 2151 } else { 2152 // A function typedef ("typedef int f(); f a;"). 2153 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2154 Diag(Loc, diag::err_not_integral_type_bitfield) 2155 << Name << cast<ValueDecl>(Member)->getType() 2156 << BitWidth->getSourceRange(); 2157 } 2158 2159 BitWidth = nullptr; 2160 Member->setInvalidDecl(); 2161 } 2162 2163 Member->setAccess(AS); 2164 2165 // If we have declared a member function template or static data member 2166 // template, set the access of the templated declaration as well. 2167 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2168 FunTmpl->getTemplatedDecl()->setAccess(AS); 2169 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2170 VarTmpl->getTemplatedDecl()->setAccess(AS); 2171 } 2172 2173 if (VS.isOverrideSpecified()) 2174 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2175 if (VS.isFinalSpecified()) 2176 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2177 VS.isFinalSpelledSealed())); 2178 2179 if (VS.getLastLocation().isValid()) { 2180 // Update the end location of a method that has a virt-specifiers. 2181 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2182 MD->setRangeEnd(VS.getLastLocation()); 2183 } 2184 2185 CheckOverrideControl(Member); 2186 2187 assert((Name || isInstField) && "No identifier for non-field ?"); 2188 2189 if (isInstField) { 2190 FieldDecl *FD = cast<FieldDecl>(Member); 2191 FieldCollector->Add(FD); 2192 2193 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 2194 // Remember all explicit private FieldDecls that have a name, no side 2195 // effects and are not part of a dependent type declaration. 2196 if (!FD->isImplicit() && FD->getDeclName() && 2197 FD->getAccess() == AS_private && 2198 !FD->hasAttr<UnusedAttr>() && 2199 !FD->getParent()->isDependentContext() && 2200 !InitializationHasSideEffects(*FD)) 2201 UnusedPrivateFields.insert(FD); 2202 } 2203 } 2204 2205 return Member; 2206 } 2207 2208 namespace { 2209 class UninitializedFieldVisitor 2210 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2211 Sema &S; 2212 // List of Decls to generate a warning on. Also remove Decls that become 2213 // initialized. 2214 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 2215 // Vector of decls to be removed from the Decl set prior to visiting the 2216 // nodes. These Decls may have been initialized in the prior initializer. 2217 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 2218 // If non-null, add a note to the warning pointing back to the constructor. 2219 const CXXConstructorDecl *Constructor; 2220 public: 2221 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2222 UninitializedFieldVisitor(Sema &S, 2223 llvm::SmallPtrSetImpl<ValueDecl*> &Decls) 2224 : Inherited(S.Context), S(S), Decls(Decls) { } 2225 2226 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 2227 bool AddressOf) { 2228 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2229 return; 2230 2231 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2232 // or union. 2233 MemberExpr *FieldME = ME; 2234 2235 bool AllPODFields = FieldME->getType().isPODType(S.Context); 2236 2237 Expr *Base = ME; 2238 while (isa<MemberExpr>(Base)) { 2239 ME = cast<MemberExpr>(Base); 2240 2241 if (isa<VarDecl>(ME->getMemberDecl())) 2242 return; 2243 2244 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2245 if (!FD->isAnonymousStructOrUnion()) 2246 FieldME = ME; 2247 2248 if (!FieldME->getType().isPODType(S.Context)) 2249 AllPODFields = false; 2250 2251 Base = ME->getBase()->IgnoreParenImpCasts(); 2252 } 2253 2254 if (!isa<CXXThisExpr>(Base)) 2255 return; 2256 2257 if (AddressOf && AllPODFields) 2258 return; 2259 2260 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2261 2262 if (!Decls.count(FoundVD)) 2263 return; 2264 2265 const bool IsReference = FoundVD->getType()->isReferenceType(); 2266 2267 // Prevent double warnings on use of unbounded references. 2268 if (CheckReferenceOnly && !IsReference) 2269 return; 2270 2271 unsigned diag = IsReference 2272 ? diag::warn_reference_field_is_uninit 2273 : diag::warn_field_is_uninit; 2274 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2275 if (Constructor) 2276 S.Diag(Constructor->getLocation(), 2277 diag::note_uninit_in_this_constructor) 2278 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2279 2280 } 2281 2282 void HandleValue(Expr *E, bool AddressOf) { 2283 E = E->IgnoreParens(); 2284 2285 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2286 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 2287 AddressOf /*AddressOf*/); 2288 return; 2289 } 2290 2291 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2292 Visit(CO->getCond()); 2293 HandleValue(CO->getTrueExpr(), AddressOf); 2294 HandleValue(CO->getFalseExpr(), AddressOf); 2295 return; 2296 } 2297 2298 if (BinaryConditionalOperator *BCO = 2299 dyn_cast<BinaryConditionalOperator>(E)) { 2300 Visit(BCO->getCond()); 2301 HandleValue(BCO->getFalseExpr(), AddressOf); 2302 return; 2303 } 2304 2305 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 2306 HandleValue(OVE->getSourceExpr(), AddressOf); 2307 return; 2308 } 2309 2310 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2311 switch (BO->getOpcode()) { 2312 default: 2313 break; 2314 case(BO_PtrMemD): 2315 case(BO_PtrMemI): 2316 HandleValue(BO->getLHS(), AddressOf); 2317 Visit(BO->getRHS()); 2318 return; 2319 case(BO_Comma): 2320 Visit(BO->getLHS()); 2321 HandleValue(BO->getRHS(), AddressOf); 2322 return; 2323 } 2324 } 2325 2326 Visit(E); 2327 } 2328 2329 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 2330 FieldDecl *Field) { 2331 // Remove Decls that may have been initialized in the previous 2332 // initializer. 2333 for (ValueDecl* VD : DeclsToRemove) 2334 Decls.erase(VD); 2335 2336 DeclsToRemove.clear(); 2337 Constructor = FieldConstructor; 2338 Visit(E); 2339 if (Field) 2340 Decls.erase(Field); 2341 } 2342 2343 void VisitMemberExpr(MemberExpr *ME) { 2344 // All uses of unbounded reference fields will warn. 2345 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 2346 } 2347 2348 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2349 if (E->getCastKind() == CK_LValueToRValue) { 2350 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2351 return; 2352 } 2353 2354 Inherited::VisitImplicitCastExpr(E); 2355 } 2356 2357 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2358 if (E->getConstructor()->isCopyConstructor()) { 2359 Expr *ArgExpr = E->getArg(0); 2360 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 2361 if (ILE->getNumInits() == 1) 2362 ArgExpr = ILE->getInit(0); 2363 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 2364 if (ICE->getCastKind() == CK_NoOp) 2365 ArgExpr = ICE->getSubExpr(); 2366 HandleValue(ArgExpr, false /*AddressOf*/); 2367 return; 2368 } 2369 Inherited::VisitCXXConstructExpr(E); 2370 } 2371 2372 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2373 Expr *Callee = E->getCallee(); 2374 if (isa<MemberExpr>(Callee)) { 2375 HandleValue(Callee, false /*AddressOf*/); 2376 return; 2377 } 2378 2379 Inherited::VisitCXXMemberCallExpr(E); 2380 } 2381 2382 void VisitCallExpr(CallExpr *E) { 2383 // Treat std::move as a use. 2384 if (E->getNumArgs() == 1) { 2385 if (FunctionDecl *FD = E->getDirectCallee()) { 2386 if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) { 2387 HandleValue(E->getArg(0), false /*AddressOf*/); 2388 return; 2389 } 2390 } 2391 } 2392 2393 Inherited::VisitCallExpr(E); 2394 } 2395 2396 void VisitBinaryOperator(BinaryOperator *E) { 2397 // If a field assignment is detected, remove the field from the 2398 // uninitiailized field set. 2399 if (E->getOpcode() == BO_Assign) 2400 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2401 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2402 if (!FD->getType()->isReferenceType()) 2403 DeclsToRemove.push_back(FD); 2404 2405 if (E->isCompoundAssignmentOp()) { 2406 HandleValue(E->getLHS(), false /*AddressOf*/); 2407 Visit(E->getRHS()); 2408 return; 2409 } 2410 2411 Inherited::VisitBinaryOperator(E); 2412 } 2413 2414 void VisitUnaryOperator(UnaryOperator *E) { 2415 if (E->isIncrementDecrementOp()) { 2416 HandleValue(E->getSubExpr(), false /*AddressOf*/); 2417 return; 2418 } 2419 if (E->getOpcode() == UO_AddrOf) { 2420 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 2421 HandleValue(ME->getBase(), true /*AddressOf*/); 2422 return; 2423 } 2424 } 2425 2426 Inherited::VisitUnaryOperator(E); 2427 } 2428 }; 2429 2430 // Diagnose value-uses of fields to initialize themselves, e.g. 2431 // foo(foo) 2432 // where foo is not also a parameter to the constructor. 2433 // Also diagnose across field uninitialized use such as 2434 // x(y), y(x) 2435 // TODO: implement -Wuninitialized and fold this into that framework. 2436 static void DiagnoseUninitializedFields( 2437 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2438 2439 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 2440 Constructor->getLocation())) { 2441 return; 2442 } 2443 2444 if (Constructor->isInvalidDecl()) 2445 return; 2446 2447 const CXXRecordDecl *RD = Constructor->getParent(); 2448 2449 // Holds fields that are uninitialized. 2450 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2451 2452 // At the beginning, all fields are uninitialized. 2453 for (auto *I : RD->decls()) { 2454 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2455 UninitializedFields.insert(FD); 2456 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2457 UninitializedFields.insert(IFD->getAnonField()); 2458 } 2459 } 2460 2461 if (UninitializedFields.empty()) 2462 return; 2463 2464 UninitializedFieldVisitor UninitializedChecker(SemaRef, 2465 UninitializedFields); 2466 2467 for (const auto *FieldInit : Constructor->inits()) { 2468 if (UninitializedFields.empty()) 2469 break; 2470 2471 Expr *InitExpr = FieldInit->getInit(); 2472 if (!InitExpr) 2473 continue; 2474 2475 if (CXXDefaultInitExpr *Default = 2476 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 2477 InitExpr = Default->getExpr(); 2478 if (!InitExpr) 2479 continue; 2480 // In class initializers will point to the constructor. 2481 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 2482 FieldInit->getAnyMember()); 2483 } else { 2484 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 2485 FieldInit->getAnyMember()); 2486 } 2487 } 2488 } 2489 } // namespace 2490 2491 /// \brief Enter a new C++ default initializer scope. After calling this, the 2492 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2493 /// parsing or instantiating the initializer failed. 2494 void Sema::ActOnStartCXXInClassMemberInitializer() { 2495 // Create a synthetic function scope to represent the call to the constructor 2496 // that notionally surrounds a use of this initializer. 2497 PushFunctionScope(); 2498 } 2499 2500 /// \brief This is invoked after parsing an in-class initializer for a 2501 /// non-static C++ class member, and after instantiating an in-class initializer 2502 /// in a class template. Such actions are deferred until the class is complete. 2503 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2504 SourceLocation InitLoc, 2505 Expr *InitExpr) { 2506 // Pop the notional constructor scope we created earlier. 2507 PopFunctionScopeInfo(nullptr, D); 2508 2509 FieldDecl *FD = cast<FieldDecl>(D); 2510 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2511 "must set init style when field is created"); 2512 2513 if (!InitExpr) { 2514 FD->setInvalidDecl(); 2515 FD->removeInClassInitializer(); 2516 return; 2517 } 2518 2519 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2520 FD->setInvalidDecl(); 2521 FD->removeInClassInitializer(); 2522 return; 2523 } 2524 2525 ExprResult Init = InitExpr; 2526 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2527 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2528 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2529 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2530 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2531 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2532 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2533 if (Init.isInvalid()) { 2534 FD->setInvalidDecl(); 2535 return; 2536 } 2537 } 2538 2539 // C++11 [class.base.init]p7: 2540 // The initialization of each base and member constitutes a 2541 // full-expression. 2542 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 2543 if (Init.isInvalid()) { 2544 FD->setInvalidDecl(); 2545 return; 2546 } 2547 2548 InitExpr = Init.get(); 2549 2550 FD->setInClassInitializer(InitExpr); 2551 } 2552 2553 /// \brief Find the direct and/or virtual base specifiers that 2554 /// correspond to the given base type, for use in base initialization 2555 /// within a constructor. 2556 static bool FindBaseInitializer(Sema &SemaRef, 2557 CXXRecordDecl *ClassDecl, 2558 QualType BaseType, 2559 const CXXBaseSpecifier *&DirectBaseSpec, 2560 const CXXBaseSpecifier *&VirtualBaseSpec) { 2561 // First, check for a direct base class. 2562 DirectBaseSpec = nullptr; 2563 for (const auto &Base : ClassDecl->bases()) { 2564 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2565 // We found a direct base of this type. That's what we're 2566 // initializing. 2567 DirectBaseSpec = &Base; 2568 break; 2569 } 2570 } 2571 2572 // Check for a virtual base class. 2573 // FIXME: We might be able to short-circuit this if we know in advance that 2574 // there are no virtual bases. 2575 VirtualBaseSpec = nullptr; 2576 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2577 // We haven't found a base yet; search the class hierarchy for a 2578 // virtual base class. 2579 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2580 /*DetectVirtual=*/false); 2581 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2582 BaseType, Paths)) { 2583 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2584 Path != Paths.end(); ++Path) { 2585 if (Path->back().Base->isVirtual()) { 2586 VirtualBaseSpec = Path->back().Base; 2587 break; 2588 } 2589 } 2590 } 2591 } 2592 2593 return DirectBaseSpec || VirtualBaseSpec; 2594 } 2595 2596 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2597 MemInitResult 2598 Sema::ActOnMemInitializer(Decl *ConstructorD, 2599 Scope *S, 2600 CXXScopeSpec &SS, 2601 IdentifierInfo *MemberOrBase, 2602 ParsedType TemplateTypeTy, 2603 const DeclSpec &DS, 2604 SourceLocation IdLoc, 2605 Expr *InitList, 2606 SourceLocation EllipsisLoc) { 2607 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2608 DS, IdLoc, InitList, 2609 EllipsisLoc); 2610 } 2611 2612 /// \brief Handle a C++ member initializer using parentheses syntax. 2613 MemInitResult 2614 Sema::ActOnMemInitializer(Decl *ConstructorD, 2615 Scope *S, 2616 CXXScopeSpec &SS, 2617 IdentifierInfo *MemberOrBase, 2618 ParsedType TemplateTypeTy, 2619 const DeclSpec &DS, 2620 SourceLocation IdLoc, 2621 SourceLocation LParenLoc, 2622 ArrayRef<Expr *> Args, 2623 SourceLocation RParenLoc, 2624 SourceLocation EllipsisLoc) { 2625 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2626 Args, RParenLoc); 2627 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2628 DS, IdLoc, List, EllipsisLoc); 2629 } 2630 2631 namespace { 2632 2633 // Callback to only accept typo corrections that can be a valid C++ member 2634 // intializer: either a non-static field member or a base class. 2635 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2636 public: 2637 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2638 : ClassDecl(ClassDecl) {} 2639 2640 bool ValidateCandidate(const TypoCorrection &candidate) override { 2641 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2642 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2643 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2644 return isa<TypeDecl>(ND); 2645 } 2646 return false; 2647 } 2648 2649 private: 2650 CXXRecordDecl *ClassDecl; 2651 }; 2652 2653 } 2654 2655 /// \brief Handle a C++ member initializer. 2656 MemInitResult 2657 Sema::BuildMemInitializer(Decl *ConstructorD, 2658 Scope *S, 2659 CXXScopeSpec &SS, 2660 IdentifierInfo *MemberOrBase, 2661 ParsedType TemplateTypeTy, 2662 const DeclSpec &DS, 2663 SourceLocation IdLoc, 2664 Expr *Init, 2665 SourceLocation EllipsisLoc) { 2666 if (!ConstructorD) 2667 return true; 2668 2669 AdjustDeclIfTemplate(ConstructorD); 2670 2671 CXXConstructorDecl *Constructor 2672 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2673 if (!Constructor) { 2674 // The user wrote a constructor initializer on a function that is 2675 // not a C++ constructor. Ignore the error for now, because we may 2676 // have more member initializers coming; we'll diagnose it just 2677 // once in ActOnMemInitializers. 2678 return true; 2679 } 2680 2681 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2682 2683 // C++ [class.base.init]p2: 2684 // Names in a mem-initializer-id are looked up in the scope of the 2685 // constructor's class and, if not found in that scope, are looked 2686 // up in the scope containing the constructor's definition. 2687 // [Note: if the constructor's class contains a member with the 2688 // same name as a direct or virtual base class of the class, a 2689 // mem-initializer-id naming the member or base class and composed 2690 // of a single identifier refers to the class member. A 2691 // mem-initializer-id for the hidden base class may be specified 2692 // using a qualified name. ] 2693 if (!SS.getScopeRep() && !TemplateTypeTy) { 2694 // Look for a member, first. 2695 DeclContext::lookup_result Result 2696 = ClassDecl->lookup(MemberOrBase); 2697 if (!Result.empty()) { 2698 ValueDecl *Member; 2699 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2700 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2701 if (EllipsisLoc.isValid()) 2702 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2703 << MemberOrBase 2704 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2705 2706 return BuildMemberInitializer(Member, Init, IdLoc); 2707 } 2708 } 2709 } 2710 // It didn't name a member, so see if it names a class. 2711 QualType BaseType; 2712 TypeSourceInfo *TInfo = nullptr; 2713 2714 if (TemplateTypeTy) { 2715 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2716 } else if (DS.getTypeSpecType() == TST_decltype) { 2717 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2718 } else { 2719 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2720 LookupParsedName(R, S, &SS); 2721 2722 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2723 if (!TyD) { 2724 if (R.isAmbiguous()) return true; 2725 2726 // We don't want access-control diagnostics here. 2727 R.suppressDiagnostics(); 2728 2729 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2730 bool NotUnknownSpecialization = false; 2731 DeclContext *DC = computeDeclContext(SS, false); 2732 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2733 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2734 2735 if (!NotUnknownSpecialization) { 2736 // When the scope specifier can refer to a member of an unknown 2737 // specialization, we take it as a type name. 2738 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2739 SS.getWithLocInContext(Context), 2740 *MemberOrBase, IdLoc); 2741 if (BaseType.isNull()) 2742 return true; 2743 2744 R.clear(); 2745 R.setLookupName(MemberOrBase); 2746 } 2747 } 2748 2749 // If no results were found, try to correct typos. 2750 TypoCorrection Corr; 2751 MemInitializerValidatorCCC Validator(ClassDecl); 2752 if (R.empty() && BaseType.isNull() && 2753 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2754 Validator, CTK_ErrorRecovery, ClassDecl))) { 2755 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2756 // We have found a non-static data member with a similar 2757 // name to what was typed; complain and initialize that 2758 // member. 2759 diagnoseTypo(Corr, 2760 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2761 << MemberOrBase << true); 2762 return BuildMemberInitializer(Member, Init, IdLoc); 2763 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2764 const CXXBaseSpecifier *DirectBaseSpec; 2765 const CXXBaseSpecifier *VirtualBaseSpec; 2766 if (FindBaseInitializer(*this, ClassDecl, 2767 Context.getTypeDeclType(Type), 2768 DirectBaseSpec, VirtualBaseSpec)) { 2769 // We have found a direct or virtual base class with a 2770 // similar name to what was typed; complain and initialize 2771 // that base class. 2772 diagnoseTypo(Corr, 2773 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2774 << MemberOrBase << false, 2775 PDiag() /*Suppress note, we provide our own.*/); 2776 2777 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2778 : VirtualBaseSpec; 2779 Diag(BaseSpec->getLocStart(), 2780 diag::note_base_class_specified_here) 2781 << BaseSpec->getType() 2782 << BaseSpec->getSourceRange(); 2783 2784 TyD = Type; 2785 } 2786 } 2787 } 2788 2789 if (!TyD && BaseType.isNull()) { 2790 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2791 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2792 return true; 2793 } 2794 } 2795 2796 if (BaseType.isNull()) { 2797 BaseType = Context.getTypeDeclType(TyD); 2798 if (SS.isSet()) 2799 // FIXME: preserve source range information 2800 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 2801 BaseType); 2802 } 2803 } 2804 2805 if (!TInfo) 2806 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2807 2808 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2809 } 2810 2811 /// Checks a member initializer expression for cases where reference (or 2812 /// pointer) members are bound to by-value parameters (or their addresses). 2813 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2814 Expr *Init, 2815 SourceLocation IdLoc) { 2816 QualType MemberTy = Member->getType(); 2817 2818 // We only handle pointers and references currently. 2819 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2820 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2821 return; 2822 2823 const bool IsPointer = MemberTy->isPointerType(); 2824 if (IsPointer) { 2825 if (const UnaryOperator *Op 2826 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2827 // The only case we're worried about with pointers requires taking the 2828 // address. 2829 if (Op->getOpcode() != UO_AddrOf) 2830 return; 2831 2832 Init = Op->getSubExpr(); 2833 } else { 2834 // We only handle address-of expression initializers for pointers. 2835 return; 2836 } 2837 } 2838 2839 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2840 // We only warn when referring to a non-reference parameter declaration. 2841 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2842 if (!Parameter || Parameter->getType()->isReferenceType()) 2843 return; 2844 2845 S.Diag(Init->getExprLoc(), 2846 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2847 : diag::warn_bind_ref_member_to_parameter) 2848 << Member << Parameter << Init->getSourceRange(); 2849 } else { 2850 // Other initializers are fine. 2851 return; 2852 } 2853 2854 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2855 << (unsigned)IsPointer; 2856 } 2857 2858 MemInitResult 2859 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2860 SourceLocation IdLoc) { 2861 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2862 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2863 assert((DirectMember || IndirectMember) && 2864 "Member must be a FieldDecl or IndirectFieldDecl"); 2865 2866 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2867 return true; 2868 2869 if (Member->isInvalidDecl()) 2870 return true; 2871 2872 MultiExprArg Args; 2873 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2874 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2875 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2876 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2877 } else { 2878 // Template instantiation doesn't reconstruct ParenListExprs for us. 2879 Args = Init; 2880 } 2881 2882 SourceRange InitRange = Init->getSourceRange(); 2883 2884 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2885 // Can't check initialization for a member of dependent type or when 2886 // any of the arguments are type-dependent expressions. 2887 DiscardCleanupsInEvaluationContext(); 2888 } else { 2889 bool InitList = false; 2890 if (isa<InitListExpr>(Init)) { 2891 InitList = true; 2892 Args = Init; 2893 } 2894 2895 // Initialize the member. 2896 InitializedEntity MemberEntity = 2897 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 2898 : InitializedEntity::InitializeMember(IndirectMember, 2899 nullptr); 2900 InitializationKind Kind = 2901 InitList ? InitializationKind::CreateDirectList(IdLoc) 2902 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2903 InitRange.getEnd()); 2904 2905 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 2906 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 2907 nullptr); 2908 if (MemberInit.isInvalid()) 2909 return true; 2910 2911 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 2912 2913 // C++11 [class.base.init]p7: 2914 // The initialization of each base and member constitutes a 2915 // full-expression. 2916 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2917 if (MemberInit.isInvalid()) 2918 return true; 2919 2920 Init = MemberInit.get(); 2921 } 2922 2923 if (DirectMember) { 2924 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2925 InitRange.getBegin(), Init, 2926 InitRange.getEnd()); 2927 } else { 2928 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2929 InitRange.getBegin(), Init, 2930 InitRange.getEnd()); 2931 } 2932 } 2933 2934 MemInitResult 2935 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2936 CXXRecordDecl *ClassDecl) { 2937 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2938 if (!LangOpts.CPlusPlus11) 2939 return Diag(NameLoc, diag::err_delegating_ctor) 2940 << TInfo->getTypeLoc().getLocalSourceRange(); 2941 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2942 2943 bool InitList = true; 2944 MultiExprArg Args = Init; 2945 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2946 InitList = false; 2947 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2948 } 2949 2950 SourceRange InitRange = Init->getSourceRange(); 2951 // Initialize the object. 2952 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2953 QualType(ClassDecl->getTypeForDecl(), 0)); 2954 InitializationKind Kind = 2955 InitList ? InitializationKind::CreateDirectList(NameLoc) 2956 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2957 InitRange.getEnd()); 2958 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 2959 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2960 Args, nullptr); 2961 if (DelegationInit.isInvalid()) 2962 return true; 2963 2964 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2965 "Delegating constructor with no target?"); 2966 2967 // C++11 [class.base.init]p7: 2968 // The initialization of each base and member constitutes a 2969 // full-expression. 2970 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2971 InitRange.getBegin()); 2972 if (DelegationInit.isInvalid()) 2973 return true; 2974 2975 // If we are in a dependent context, template instantiation will 2976 // perform this type-checking again. Just save the arguments that we 2977 // received in a ParenListExpr. 2978 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2979 // of the information that we have about the base 2980 // initializer. However, deconstructing the ASTs is a dicey process, 2981 // and this approach is far more likely to get the corner cases right. 2982 if (CurContext->isDependentContext()) 2983 DelegationInit = Init; 2984 2985 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2986 DelegationInit.getAs<Expr>(), 2987 InitRange.getEnd()); 2988 } 2989 2990 MemInitResult 2991 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2992 Expr *Init, CXXRecordDecl *ClassDecl, 2993 SourceLocation EllipsisLoc) { 2994 SourceLocation BaseLoc 2995 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2996 2997 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2998 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2999 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3000 3001 // C++ [class.base.init]p2: 3002 // [...] Unless the mem-initializer-id names a nonstatic data 3003 // member of the constructor's class or a direct or virtual base 3004 // of that class, the mem-initializer is ill-formed. A 3005 // mem-initializer-list can initialize a base class using any 3006 // name that denotes that base class type. 3007 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 3008 3009 SourceRange InitRange = Init->getSourceRange(); 3010 if (EllipsisLoc.isValid()) { 3011 // This is a pack expansion. 3012 if (!BaseType->containsUnexpandedParameterPack()) { 3013 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 3014 << SourceRange(BaseLoc, InitRange.getEnd()); 3015 3016 EllipsisLoc = SourceLocation(); 3017 } 3018 } else { 3019 // Check for any unexpanded parameter packs. 3020 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 3021 return true; 3022 3023 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 3024 return true; 3025 } 3026 3027 // Check for direct and virtual base classes. 3028 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 3029 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 3030 if (!Dependent) { 3031 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 3032 BaseType)) 3033 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 3034 3035 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 3036 VirtualBaseSpec); 3037 3038 // C++ [base.class.init]p2: 3039 // Unless the mem-initializer-id names a nonstatic data member of the 3040 // constructor's class or a direct or virtual base of that class, the 3041 // mem-initializer is ill-formed. 3042 if (!DirectBaseSpec && !VirtualBaseSpec) { 3043 // If the class has any dependent bases, then it's possible that 3044 // one of those types will resolve to the same type as 3045 // BaseType. Therefore, just treat this as a dependent base 3046 // class initialization. FIXME: Should we try to check the 3047 // initialization anyway? It seems odd. 3048 if (ClassDecl->hasAnyDependentBases()) 3049 Dependent = true; 3050 else 3051 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 3052 << BaseType << Context.getTypeDeclType(ClassDecl) 3053 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3054 } 3055 } 3056 3057 if (Dependent) { 3058 DiscardCleanupsInEvaluationContext(); 3059 3060 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3061 /*IsVirtual=*/false, 3062 InitRange.getBegin(), Init, 3063 InitRange.getEnd(), EllipsisLoc); 3064 } 3065 3066 // C++ [base.class.init]p2: 3067 // If a mem-initializer-id is ambiguous because it designates both 3068 // a direct non-virtual base class and an inherited virtual base 3069 // class, the mem-initializer is ill-formed. 3070 if (DirectBaseSpec && VirtualBaseSpec) 3071 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 3072 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3073 3074 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 3075 if (!BaseSpec) 3076 BaseSpec = VirtualBaseSpec; 3077 3078 // Initialize the base. 3079 bool InitList = true; 3080 MultiExprArg Args = Init; 3081 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3082 InitList = false; 3083 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3084 } 3085 3086 InitializedEntity BaseEntity = 3087 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 3088 InitializationKind Kind = 3089 InitList ? InitializationKind::CreateDirectList(BaseLoc) 3090 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 3091 InitRange.getEnd()); 3092 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 3093 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 3094 if (BaseInit.isInvalid()) 3095 return true; 3096 3097 // C++11 [class.base.init]p7: 3098 // The initialization of each base and member constitutes a 3099 // full-expression. 3100 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 3101 if (BaseInit.isInvalid()) 3102 return true; 3103 3104 // If we are in a dependent context, template instantiation will 3105 // perform this type-checking again. Just save the arguments that we 3106 // received in a ParenListExpr. 3107 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3108 // of the information that we have about the base 3109 // initializer. However, deconstructing the ASTs is a dicey process, 3110 // and this approach is far more likely to get the corner cases right. 3111 if (CurContext->isDependentContext()) 3112 BaseInit = Init; 3113 3114 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3115 BaseSpec->isVirtual(), 3116 InitRange.getBegin(), 3117 BaseInit.getAs<Expr>(), 3118 InitRange.getEnd(), EllipsisLoc); 3119 } 3120 3121 // Create a static_cast\<T&&>(expr). 3122 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 3123 if (T.isNull()) T = E->getType(); 3124 QualType TargetType = SemaRef.BuildReferenceType( 3125 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 3126 SourceLocation ExprLoc = E->getLocStart(); 3127 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 3128 TargetType, ExprLoc); 3129 3130 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 3131 SourceRange(ExprLoc, ExprLoc), 3132 E->getSourceRange()).get(); 3133 } 3134 3135 /// ImplicitInitializerKind - How an implicit base or member initializer should 3136 /// initialize its base or member. 3137 enum ImplicitInitializerKind { 3138 IIK_Default, 3139 IIK_Copy, 3140 IIK_Move, 3141 IIK_Inherit 3142 }; 3143 3144 static bool 3145 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3146 ImplicitInitializerKind ImplicitInitKind, 3147 CXXBaseSpecifier *BaseSpec, 3148 bool IsInheritedVirtualBase, 3149 CXXCtorInitializer *&CXXBaseInit) { 3150 InitializedEntity InitEntity 3151 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3152 IsInheritedVirtualBase); 3153 3154 ExprResult BaseInit; 3155 3156 switch (ImplicitInitKind) { 3157 case IIK_Inherit: { 3158 const CXXRecordDecl *Inherited = 3159 Constructor->getInheritedConstructor()->getParent(); 3160 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3161 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3162 // C++11 [class.inhctor]p8: 3163 // Each expression in the expression-list is of the form 3164 // static_cast<T&&>(p), where p is the name of the corresponding 3165 // constructor parameter and T is the declared type of p. 3166 SmallVector<Expr*, 16> Args; 3167 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3168 ParmVarDecl *PD = Constructor->getParamDecl(I); 3169 ExprResult ArgExpr = 3170 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3171 VK_LValue, SourceLocation()); 3172 if (ArgExpr.isInvalid()) 3173 return true; 3174 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType())); 3175 } 3176 3177 InitializationKind InitKind = InitializationKind::CreateDirect( 3178 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3179 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3180 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3181 break; 3182 } 3183 } 3184 // Fall through. 3185 case IIK_Default: { 3186 InitializationKind InitKind 3187 = InitializationKind::CreateDefault(Constructor->getLocation()); 3188 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3189 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3190 break; 3191 } 3192 3193 case IIK_Move: 3194 case IIK_Copy: { 3195 bool Moving = ImplicitInitKind == IIK_Move; 3196 ParmVarDecl *Param = Constructor->getParamDecl(0); 3197 QualType ParamType = Param->getType().getNonReferenceType(); 3198 3199 Expr *CopyCtorArg = 3200 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3201 SourceLocation(), Param, false, 3202 Constructor->getLocation(), ParamType, 3203 VK_LValue, nullptr); 3204 3205 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3206 3207 // Cast to the base class to avoid ambiguities. 3208 QualType ArgTy = 3209 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3210 ParamType.getQualifiers()); 3211 3212 if (Moving) { 3213 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3214 } 3215 3216 CXXCastPath BasePath; 3217 BasePath.push_back(BaseSpec); 3218 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3219 CK_UncheckedDerivedToBase, 3220 Moving ? VK_XValue : VK_LValue, 3221 &BasePath).get(); 3222 3223 InitializationKind InitKind 3224 = InitializationKind::CreateDirect(Constructor->getLocation(), 3225 SourceLocation(), SourceLocation()); 3226 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3227 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3228 break; 3229 } 3230 } 3231 3232 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3233 if (BaseInit.isInvalid()) 3234 return true; 3235 3236 CXXBaseInit = 3237 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3238 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3239 SourceLocation()), 3240 BaseSpec->isVirtual(), 3241 SourceLocation(), 3242 BaseInit.getAs<Expr>(), 3243 SourceLocation(), 3244 SourceLocation()); 3245 3246 return false; 3247 } 3248 3249 static bool RefersToRValueRef(Expr *MemRef) { 3250 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3251 return Referenced->getType()->isRValueReferenceType(); 3252 } 3253 3254 static bool 3255 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3256 ImplicitInitializerKind ImplicitInitKind, 3257 FieldDecl *Field, IndirectFieldDecl *Indirect, 3258 CXXCtorInitializer *&CXXMemberInit) { 3259 if (Field->isInvalidDecl()) 3260 return true; 3261 3262 SourceLocation Loc = Constructor->getLocation(); 3263 3264 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3265 bool Moving = ImplicitInitKind == IIK_Move; 3266 ParmVarDecl *Param = Constructor->getParamDecl(0); 3267 QualType ParamType = Param->getType().getNonReferenceType(); 3268 3269 // Suppress copying zero-width bitfields. 3270 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3271 return false; 3272 3273 Expr *MemberExprBase = 3274 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3275 SourceLocation(), Param, false, 3276 Loc, ParamType, VK_LValue, nullptr); 3277 3278 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3279 3280 if (Moving) { 3281 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3282 } 3283 3284 // Build a reference to this field within the parameter. 3285 CXXScopeSpec SS; 3286 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3287 Sema::LookupMemberName); 3288 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3289 : cast<ValueDecl>(Field), AS_public); 3290 MemberLookup.resolveKind(); 3291 ExprResult CtorArg 3292 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3293 ParamType, Loc, 3294 /*IsArrow=*/false, 3295 SS, 3296 /*TemplateKWLoc=*/SourceLocation(), 3297 /*FirstQualifierInScope=*/nullptr, 3298 MemberLookup, 3299 /*TemplateArgs=*/nullptr); 3300 if (CtorArg.isInvalid()) 3301 return true; 3302 3303 // C++11 [class.copy]p15: 3304 // - if a member m has rvalue reference type T&&, it is direct-initialized 3305 // with static_cast<T&&>(x.m); 3306 if (RefersToRValueRef(CtorArg.get())) { 3307 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3308 } 3309 3310 // When the field we are copying is an array, create index variables for 3311 // each dimension of the array. We use these index variables to subscript 3312 // the source array, and other clients (e.g., CodeGen) will perform the 3313 // necessary iteration with these index variables. 3314 SmallVector<VarDecl *, 4> IndexVariables; 3315 QualType BaseType = Field->getType(); 3316 QualType SizeType = SemaRef.Context.getSizeType(); 3317 bool InitializingArray = false; 3318 while (const ConstantArrayType *Array 3319 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3320 InitializingArray = true; 3321 // Create the iteration variable for this array index. 3322 IdentifierInfo *IterationVarName = nullptr; 3323 { 3324 SmallString<8> Str; 3325 llvm::raw_svector_ostream OS(Str); 3326 OS << "__i" << IndexVariables.size(); 3327 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3328 } 3329 VarDecl *IterationVar 3330 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3331 IterationVarName, SizeType, 3332 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3333 SC_None); 3334 IndexVariables.push_back(IterationVar); 3335 3336 // Create a reference to the iteration variable. 3337 ExprResult IterationVarRef 3338 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3339 assert(!IterationVarRef.isInvalid() && 3340 "Reference to invented variable cannot fail!"); 3341 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 3342 assert(!IterationVarRef.isInvalid() && 3343 "Conversion of invented variable cannot fail!"); 3344 3345 // Subscript the array with this iteration variable. 3346 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 3347 IterationVarRef.get(), 3348 Loc); 3349 if (CtorArg.isInvalid()) 3350 return true; 3351 3352 BaseType = Array->getElementType(); 3353 } 3354 3355 // The array subscript expression is an lvalue, which is wrong for moving. 3356 if (Moving && InitializingArray) 3357 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3358 3359 // Construct the entity that we will be initializing. For an array, this 3360 // will be first element in the array, which may require several levels 3361 // of array-subscript entities. 3362 SmallVector<InitializedEntity, 4> Entities; 3363 Entities.reserve(1 + IndexVariables.size()); 3364 if (Indirect) 3365 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3366 else 3367 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3368 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3369 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3370 0, 3371 Entities.back())); 3372 3373 // Direct-initialize to use the copy constructor. 3374 InitializationKind InitKind = 3375 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3376 3377 Expr *CtorArgE = CtorArg.getAs<Expr>(); 3378 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3379 3380 ExprResult MemberInit 3381 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3382 MultiExprArg(&CtorArgE, 1)); 3383 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3384 if (MemberInit.isInvalid()) 3385 return true; 3386 3387 if (Indirect) { 3388 assert(IndexVariables.size() == 0 && 3389 "Indirect field improperly initialized"); 3390 CXXMemberInit 3391 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3392 Loc, Loc, 3393 MemberInit.getAs<Expr>(), 3394 Loc); 3395 } else 3396 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3397 Loc, MemberInit.getAs<Expr>(), 3398 Loc, 3399 IndexVariables.data(), 3400 IndexVariables.size()); 3401 return false; 3402 } 3403 3404 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3405 "Unhandled implicit init kind!"); 3406 3407 QualType FieldBaseElementType = 3408 SemaRef.Context.getBaseElementType(Field->getType()); 3409 3410 if (FieldBaseElementType->isRecordType()) { 3411 InitializedEntity InitEntity 3412 = Indirect? InitializedEntity::InitializeMember(Indirect) 3413 : InitializedEntity::InitializeMember(Field); 3414 InitializationKind InitKind = 3415 InitializationKind::CreateDefault(Loc); 3416 3417 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3418 ExprResult MemberInit = 3419 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3420 3421 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3422 if (MemberInit.isInvalid()) 3423 return true; 3424 3425 if (Indirect) 3426 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3427 Indirect, Loc, 3428 Loc, 3429 MemberInit.get(), 3430 Loc); 3431 else 3432 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3433 Field, Loc, Loc, 3434 MemberInit.get(), 3435 Loc); 3436 return false; 3437 } 3438 3439 if (!Field->getParent()->isUnion()) { 3440 if (FieldBaseElementType->isReferenceType()) { 3441 SemaRef.Diag(Constructor->getLocation(), 3442 diag::err_uninitialized_member_in_ctor) 3443 << (int)Constructor->isImplicit() 3444 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3445 << 0 << Field->getDeclName(); 3446 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3447 return true; 3448 } 3449 3450 if (FieldBaseElementType.isConstQualified()) { 3451 SemaRef.Diag(Constructor->getLocation(), 3452 diag::err_uninitialized_member_in_ctor) 3453 << (int)Constructor->isImplicit() 3454 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3455 << 1 << Field->getDeclName(); 3456 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3457 return true; 3458 } 3459 } 3460 3461 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3462 FieldBaseElementType->isObjCRetainableType() && 3463 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3464 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3465 // ARC: 3466 // Default-initialize Objective-C pointers to NULL. 3467 CXXMemberInit 3468 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3469 Loc, Loc, 3470 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3471 Loc); 3472 return false; 3473 } 3474 3475 // Nothing to initialize. 3476 CXXMemberInit = nullptr; 3477 return false; 3478 } 3479 3480 namespace { 3481 struct BaseAndFieldInfo { 3482 Sema &S; 3483 CXXConstructorDecl *Ctor; 3484 bool AnyErrorsInInits; 3485 ImplicitInitializerKind IIK; 3486 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3487 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3488 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3489 3490 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3491 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3492 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3493 if (Generated && Ctor->isCopyConstructor()) 3494 IIK = IIK_Copy; 3495 else if (Generated && Ctor->isMoveConstructor()) 3496 IIK = IIK_Move; 3497 else if (Ctor->getInheritedConstructor()) 3498 IIK = IIK_Inherit; 3499 else 3500 IIK = IIK_Default; 3501 } 3502 3503 bool isImplicitCopyOrMove() const { 3504 switch (IIK) { 3505 case IIK_Copy: 3506 case IIK_Move: 3507 return true; 3508 3509 case IIK_Default: 3510 case IIK_Inherit: 3511 return false; 3512 } 3513 3514 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3515 } 3516 3517 bool addFieldInitializer(CXXCtorInitializer *Init) { 3518 AllToInit.push_back(Init); 3519 3520 // Check whether this initializer makes the field "used". 3521 if (Init->getInit()->HasSideEffects(S.Context)) 3522 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3523 3524 return false; 3525 } 3526 3527 bool isInactiveUnionMember(FieldDecl *Field) { 3528 RecordDecl *Record = Field->getParent(); 3529 if (!Record->isUnion()) 3530 return false; 3531 3532 if (FieldDecl *Active = 3533 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3534 return Active != Field->getCanonicalDecl(); 3535 3536 // In an implicit copy or move constructor, ignore any in-class initializer. 3537 if (isImplicitCopyOrMove()) 3538 return true; 3539 3540 // If there's no explicit initialization, the field is active only if it 3541 // has an in-class initializer... 3542 if (Field->hasInClassInitializer()) 3543 return false; 3544 // ... or it's an anonymous struct or union whose class has an in-class 3545 // initializer. 3546 if (!Field->isAnonymousStructOrUnion()) 3547 return true; 3548 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3549 return !FieldRD->hasInClassInitializer(); 3550 } 3551 3552 /// \brief Determine whether the given field is, or is within, a union member 3553 /// that is inactive (because there was an initializer given for a different 3554 /// member of the union, or because the union was not initialized at all). 3555 bool isWithinInactiveUnionMember(FieldDecl *Field, 3556 IndirectFieldDecl *Indirect) { 3557 if (!Indirect) 3558 return isInactiveUnionMember(Field); 3559 3560 for (auto *C : Indirect->chain()) { 3561 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3562 if (Field && isInactiveUnionMember(Field)) 3563 return true; 3564 } 3565 return false; 3566 } 3567 }; 3568 } 3569 3570 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3571 /// array type. 3572 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3573 if (T->isIncompleteArrayType()) 3574 return true; 3575 3576 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3577 if (!ArrayT->getSize()) 3578 return true; 3579 3580 T = ArrayT->getElementType(); 3581 } 3582 3583 return false; 3584 } 3585 3586 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3587 FieldDecl *Field, 3588 IndirectFieldDecl *Indirect = nullptr) { 3589 if (Field->isInvalidDecl()) 3590 return false; 3591 3592 // Overwhelmingly common case: we have a direct initializer for this field. 3593 if (CXXCtorInitializer *Init = 3594 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3595 return Info.addFieldInitializer(Init); 3596 3597 // C++11 [class.base.init]p8: 3598 // if the entity is a non-static data member that has a 3599 // brace-or-equal-initializer and either 3600 // -- the constructor's class is a union and no other variant member of that 3601 // union is designated by a mem-initializer-id or 3602 // -- the constructor's class is not a union, and, if the entity is a member 3603 // of an anonymous union, no other member of that union is designated by 3604 // a mem-initializer-id, 3605 // the entity is initialized as specified in [dcl.init]. 3606 // 3607 // We also apply the same rules to handle anonymous structs within anonymous 3608 // unions. 3609 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3610 return false; 3611 3612 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3613 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3614 Info.Ctor->getLocation(), Field); 3615 CXXCtorInitializer *Init; 3616 if (Indirect) 3617 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3618 SourceLocation(), 3619 SourceLocation(), DIE, 3620 SourceLocation()); 3621 else 3622 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3623 SourceLocation(), 3624 SourceLocation(), DIE, 3625 SourceLocation()); 3626 return Info.addFieldInitializer(Init); 3627 } 3628 3629 // Don't initialize incomplete or zero-length arrays. 3630 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3631 return false; 3632 3633 // Don't try to build an implicit initializer if there were semantic 3634 // errors in any of the initializers (and therefore we might be 3635 // missing some that the user actually wrote). 3636 if (Info.AnyErrorsInInits) 3637 return false; 3638 3639 CXXCtorInitializer *Init = nullptr; 3640 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3641 Indirect, Init)) 3642 return true; 3643 3644 if (!Init) 3645 return false; 3646 3647 return Info.addFieldInitializer(Init); 3648 } 3649 3650 bool 3651 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3652 CXXCtorInitializer *Initializer) { 3653 assert(Initializer->isDelegatingInitializer()); 3654 Constructor->setNumCtorInitializers(1); 3655 CXXCtorInitializer **initializer = 3656 new (Context) CXXCtorInitializer*[1]; 3657 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3658 Constructor->setCtorInitializers(initializer); 3659 3660 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3661 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3662 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3663 } 3664 3665 DelegatingCtorDecls.push_back(Constructor); 3666 3667 DiagnoseUninitializedFields(*this, Constructor); 3668 3669 return false; 3670 } 3671 3672 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3673 ArrayRef<CXXCtorInitializer *> Initializers) { 3674 if (Constructor->isDependentContext()) { 3675 // Just store the initializers as written, they will be checked during 3676 // instantiation. 3677 if (!Initializers.empty()) { 3678 Constructor->setNumCtorInitializers(Initializers.size()); 3679 CXXCtorInitializer **baseOrMemberInitializers = 3680 new (Context) CXXCtorInitializer*[Initializers.size()]; 3681 memcpy(baseOrMemberInitializers, Initializers.data(), 3682 Initializers.size() * sizeof(CXXCtorInitializer*)); 3683 Constructor->setCtorInitializers(baseOrMemberInitializers); 3684 } 3685 3686 // Let template instantiation know whether we had errors. 3687 if (AnyErrors) 3688 Constructor->setInvalidDecl(); 3689 3690 return false; 3691 } 3692 3693 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3694 3695 // We need to build the initializer AST according to order of construction 3696 // and not what user specified in the Initializers list. 3697 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3698 if (!ClassDecl) 3699 return true; 3700 3701 bool HadError = false; 3702 3703 for (unsigned i = 0; i < Initializers.size(); i++) { 3704 CXXCtorInitializer *Member = Initializers[i]; 3705 3706 if (Member->isBaseInitializer()) 3707 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3708 else { 3709 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3710 3711 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3712 for (auto *C : F->chain()) { 3713 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3714 if (FD && FD->getParent()->isUnion()) 3715 Info.ActiveUnionMember.insert(std::make_pair( 3716 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3717 } 3718 } else if (FieldDecl *FD = Member->getMember()) { 3719 if (FD->getParent()->isUnion()) 3720 Info.ActiveUnionMember.insert(std::make_pair( 3721 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3722 } 3723 } 3724 } 3725 3726 // Keep track of the direct virtual bases. 3727 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3728 for (auto &I : ClassDecl->bases()) { 3729 if (I.isVirtual()) 3730 DirectVBases.insert(&I); 3731 } 3732 3733 // Push virtual bases before others. 3734 for (auto &VBase : ClassDecl->vbases()) { 3735 if (CXXCtorInitializer *Value 3736 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3737 // [class.base.init]p7, per DR257: 3738 // A mem-initializer where the mem-initializer-id names a virtual base 3739 // class is ignored during execution of a constructor of any class that 3740 // is not the most derived class. 3741 if (ClassDecl->isAbstract()) { 3742 // FIXME: Provide a fixit to remove the base specifier. This requires 3743 // tracking the location of the associated comma for a base specifier. 3744 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3745 << VBase.getType() << ClassDecl; 3746 DiagnoseAbstractType(ClassDecl); 3747 } 3748 3749 Info.AllToInit.push_back(Value); 3750 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3751 // [class.base.init]p8, per DR257: 3752 // If a given [...] base class is not named by a mem-initializer-id 3753 // [...] and the entity is not a virtual base class of an abstract 3754 // class, then [...] the entity is default-initialized. 3755 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3756 CXXCtorInitializer *CXXBaseInit; 3757 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3758 &VBase, IsInheritedVirtualBase, 3759 CXXBaseInit)) { 3760 HadError = true; 3761 continue; 3762 } 3763 3764 Info.AllToInit.push_back(CXXBaseInit); 3765 } 3766 } 3767 3768 // Non-virtual bases. 3769 for (auto &Base : ClassDecl->bases()) { 3770 // Virtuals are in the virtual base list and already constructed. 3771 if (Base.isVirtual()) 3772 continue; 3773 3774 if (CXXCtorInitializer *Value 3775 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3776 Info.AllToInit.push_back(Value); 3777 } else if (!AnyErrors) { 3778 CXXCtorInitializer *CXXBaseInit; 3779 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3780 &Base, /*IsInheritedVirtualBase=*/false, 3781 CXXBaseInit)) { 3782 HadError = true; 3783 continue; 3784 } 3785 3786 Info.AllToInit.push_back(CXXBaseInit); 3787 } 3788 } 3789 3790 // Fields. 3791 for (auto *Mem : ClassDecl->decls()) { 3792 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 3793 // C++ [class.bit]p2: 3794 // A declaration for a bit-field that omits the identifier declares an 3795 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3796 // initialized. 3797 if (F->isUnnamedBitfield()) 3798 continue; 3799 3800 // If we're not generating the implicit copy/move constructor, then we'll 3801 // handle anonymous struct/union fields based on their individual 3802 // indirect fields. 3803 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3804 continue; 3805 3806 if (CollectFieldInitializer(*this, Info, F)) 3807 HadError = true; 3808 continue; 3809 } 3810 3811 // Beyond this point, we only consider default initialization. 3812 if (Info.isImplicitCopyOrMove()) 3813 continue; 3814 3815 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 3816 if (F->getType()->isIncompleteArrayType()) { 3817 assert(ClassDecl->hasFlexibleArrayMember() && 3818 "Incomplete array type is not valid"); 3819 continue; 3820 } 3821 3822 // Initialize each field of an anonymous struct individually. 3823 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3824 HadError = true; 3825 3826 continue; 3827 } 3828 } 3829 3830 unsigned NumInitializers = Info.AllToInit.size(); 3831 if (NumInitializers > 0) { 3832 Constructor->setNumCtorInitializers(NumInitializers); 3833 CXXCtorInitializer **baseOrMemberInitializers = 3834 new (Context) CXXCtorInitializer*[NumInitializers]; 3835 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3836 NumInitializers * sizeof(CXXCtorInitializer*)); 3837 Constructor->setCtorInitializers(baseOrMemberInitializers); 3838 3839 // Constructors implicitly reference the base and member 3840 // destructors. 3841 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3842 Constructor->getParent()); 3843 } 3844 3845 return HadError; 3846 } 3847 3848 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3849 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3850 const RecordDecl *RD = RT->getDecl(); 3851 if (RD->isAnonymousStructOrUnion()) { 3852 for (auto *Field : RD->fields()) 3853 PopulateKeysForFields(Field, IdealInits); 3854 return; 3855 } 3856 } 3857 IdealInits.push_back(Field->getCanonicalDecl()); 3858 } 3859 3860 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3861 return Context.getCanonicalType(BaseType).getTypePtr(); 3862 } 3863 3864 static const void *GetKeyForMember(ASTContext &Context, 3865 CXXCtorInitializer *Member) { 3866 if (!Member->isAnyMemberInitializer()) 3867 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3868 3869 return Member->getAnyMember()->getCanonicalDecl(); 3870 } 3871 3872 static void DiagnoseBaseOrMemInitializerOrder( 3873 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3874 ArrayRef<CXXCtorInitializer *> Inits) { 3875 if (Constructor->getDeclContext()->isDependentContext()) 3876 return; 3877 3878 // Don't check initializers order unless the warning is enabled at the 3879 // location of at least one initializer. 3880 bool ShouldCheckOrder = false; 3881 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3882 CXXCtorInitializer *Init = Inits[InitIndex]; 3883 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 3884 Init->getSourceLocation())) { 3885 ShouldCheckOrder = true; 3886 break; 3887 } 3888 } 3889 if (!ShouldCheckOrder) 3890 return; 3891 3892 // Build the list of bases and members in the order that they'll 3893 // actually be initialized. The explicit initializers should be in 3894 // this same order but may be missing things. 3895 SmallVector<const void*, 32> IdealInitKeys; 3896 3897 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3898 3899 // 1. Virtual bases. 3900 for (const auto &VBase : ClassDecl->vbases()) 3901 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 3902 3903 // 2. Non-virtual bases. 3904 for (const auto &Base : ClassDecl->bases()) { 3905 if (Base.isVirtual()) 3906 continue; 3907 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 3908 } 3909 3910 // 3. Direct fields. 3911 for (auto *Field : ClassDecl->fields()) { 3912 if (Field->isUnnamedBitfield()) 3913 continue; 3914 3915 PopulateKeysForFields(Field, IdealInitKeys); 3916 } 3917 3918 unsigned NumIdealInits = IdealInitKeys.size(); 3919 unsigned IdealIndex = 0; 3920 3921 CXXCtorInitializer *PrevInit = nullptr; 3922 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3923 CXXCtorInitializer *Init = Inits[InitIndex]; 3924 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3925 3926 // Scan forward to try to find this initializer in the idealized 3927 // initializers list. 3928 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3929 if (InitKey == IdealInitKeys[IdealIndex]) 3930 break; 3931 3932 // If we didn't find this initializer, it must be because we 3933 // scanned past it on a previous iteration. That can only 3934 // happen if we're out of order; emit a warning. 3935 if (IdealIndex == NumIdealInits && PrevInit) { 3936 Sema::SemaDiagnosticBuilder D = 3937 SemaRef.Diag(PrevInit->getSourceLocation(), 3938 diag::warn_initializer_out_of_order); 3939 3940 if (PrevInit->isAnyMemberInitializer()) 3941 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3942 else 3943 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3944 3945 if (Init->isAnyMemberInitializer()) 3946 D << 0 << Init->getAnyMember()->getDeclName(); 3947 else 3948 D << 1 << Init->getTypeSourceInfo()->getType(); 3949 3950 // Move back to the initializer's location in the ideal list. 3951 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3952 if (InitKey == IdealInitKeys[IdealIndex]) 3953 break; 3954 3955 assert(IdealIndex != NumIdealInits && 3956 "initializer not found in initializer list"); 3957 } 3958 3959 PrevInit = Init; 3960 } 3961 } 3962 3963 namespace { 3964 bool CheckRedundantInit(Sema &S, 3965 CXXCtorInitializer *Init, 3966 CXXCtorInitializer *&PrevInit) { 3967 if (!PrevInit) { 3968 PrevInit = Init; 3969 return false; 3970 } 3971 3972 if (FieldDecl *Field = Init->getAnyMember()) 3973 S.Diag(Init->getSourceLocation(), 3974 diag::err_multiple_mem_initialization) 3975 << Field->getDeclName() 3976 << Init->getSourceRange(); 3977 else { 3978 const Type *BaseClass = Init->getBaseClass(); 3979 assert(BaseClass && "neither field nor base"); 3980 S.Diag(Init->getSourceLocation(), 3981 diag::err_multiple_base_initialization) 3982 << QualType(BaseClass, 0) 3983 << Init->getSourceRange(); 3984 } 3985 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3986 << 0 << PrevInit->getSourceRange(); 3987 3988 return true; 3989 } 3990 3991 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3992 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3993 3994 bool CheckRedundantUnionInit(Sema &S, 3995 CXXCtorInitializer *Init, 3996 RedundantUnionMap &Unions) { 3997 FieldDecl *Field = Init->getAnyMember(); 3998 RecordDecl *Parent = Field->getParent(); 3999 NamedDecl *Child = Field; 4000 4001 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 4002 if (Parent->isUnion()) { 4003 UnionEntry &En = Unions[Parent]; 4004 if (En.first && En.first != Child) { 4005 S.Diag(Init->getSourceLocation(), 4006 diag::err_multiple_mem_union_initialization) 4007 << Field->getDeclName() 4008 << Init->getSourceRange(); 4009 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 4010 << 0 << En.second->getSourceRange(); 4011 return true; 4012 } 4013 if (!En.first) { 4014 En.first = Child; 4015 En.second = Init; 4016 } 4017 if (!Parent->isAnonymousStructOrUnion()) 4018 return false; 4019 } 4020 4021 Child = Parent; 4022 Parent = cast<RecordDecl>(Parent->getDeclContext()); 4023 } 4024 4025 return false; 4026 } 4027 } 4028 4029 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4030 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4031 SourceLocation ColonLoc, 4032 ArrayRef<CXXCtorInitializer*> MemInits, 4033 bool AnyErrors) { 4034 if (!ConstructorDecl) 4035 return; 4036 4037 AdjustDeclIfTemplate(ConstructorDecl); 4038 4039 CXXConstructorDecl *Constructor 4040 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 4041 4042 if (!Constructor) { 4043 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 4044 return; 4045 } 4046 4047 // Mapping for the duplicate initializers check. 4048 // For member initializers, this is keyed with a FieldDecl*. 4049 // For base initializers, this is keyed with a Type*. 4050 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 4051 4052 // Mapping for the inconsistent anonymous-union initializers check. 4053 RedundantUnionMap MemberUnions; 4054 4055 bool HadError = false; 4056 for (unsigned i = 0; i < MemInits.size(); i++) { 4057 CXXCtorInitializer *Init = MemInits[i]; 4058 4059 // Set the source order index. 4060 Init->setSourceOrder(i); 4061 4062 if (Init->isAnyMemberInitializer()) { 4063 const void *Key = GetKeyForMember(Context, Init); 4064 if (CheckRedundantInit(*this, Init, Members[Key]) || 4065 CheckRedundantUnionInit(*this, Init, MemberUnions)) 4066 HadError = true; 4067 } else if (Init->isBaseInitializer()) { 4068 const void *Key = GetKeyForMember(Context, Init); 4069 if (CheckRedundantInit(*this, Init, Members[Key])) 4070 HadError = true; 4071 } else { 4072 assert(Init->isDelegatingInitializer()); 4073 // This must be the only initializer 4074 if (MemInits.size() != 1) { 4075 Diag(Init->getSourceLocation(), 4076 diag::err_delegating_initializer_alone) 4077 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 4078 // We will treat this as being the only initializer. 4079 } 4080 SetDelegatingInitializer(Constructor, MemInits[i]); 4081 // Return immediately as the initializer is set. 4082 return; 4083 } 4084 } 4085 4086 if (HadError) 4087 return; 4088 4089 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 4090 4091 SetCtorInitializers(Constructor, AnyErrors, MemInits); 4092 4093 DiagnoseUninitializedFields(*this, Constructor); 4094 } 4095 4096 void 4097 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 4098 CXXRecordDecl *ClassDecl) { 4099 // Ignore dependent contexts. Also ignore unions, since their members never 4100 // have destructors implicitly called. 4101 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 4102 return; 4103 4104 // FIXME: all the access-control diagnostics are positioned on the 4105 // field/base declaration. That's probably good; that said, the 4106 // user might reasonably want to know why the destructor is being 4107 // emitted, and we currently don't say. 4108 4109 // Non-static data members. 4110 for (auto *Field : ClassDecl->fields()) { 4111 if (Field->isInvalidDecl()) 4112 continue; 4113 4114 // Don't destroy incomplete or zero-length arrays. 4115 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 4116 continue; 4117 4118 QualType FieldType = Context.getBaseElementType(Field->getType()); 4119 4120 const RecordType* RT = FieldType->getAs<RecordType>(); 4121 if (!RT) 4122 continue; 4123 4124 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4125 if (FieldClassDecl->isInvalidDecl()) 4126 continue; 4127 if (FieldClassDecl->hasIrrelevantDestructor()) 4128 continue; 4129 // The destructor for an implicit anonymous union member is never invoked. 4130 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 4131 continue; 4132 4133 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 4134 assert(Dtor && "No dtor found for FieldClassDecl!"); 4135 CheckDestructorAccess(Field->getLocation(), Dtor, 4136 PDiag(diag::err_access_dtor_field) 4137 << Field->getDeclName() 4138 << FieldType); 4139 4140 MarkFunctionReferenced(Location, Dtor); 4141 DiagnoseUseOfDecl(Dtor, Location); 4142 } 4143 4144 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 4145 4146 // Bases. 4147 for (const auto &Base : ClassDecl->bases()) { 4148 // Bases are always records in a well-formed non-dependent class. 4149 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4150 4151 // Remember direct virtual bases. 4152 if (Base.isVirtual()) 4153 DirectVirtualBases.insert(RT); 4154 4155 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4156 // If our base class is invalid, we probably can't get its dtor anyway. 4157 if (BaseClassDecl->isInvalidDecl()) 4158 continue; 4159 if (BaseClassDecl->hasIrrelevantDestructor()) 4160 continue; 4161 4162 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4163 assert(Dtor && "No dtor found for BaseClassDecl!"); 4164 4165 // FIXME: caret should be on the start of the class name 4166 CheckDestructorAccess(Base.getLocStart(), Dtor, 4167 PDiag(diag::err_access_dtor_base) 4168 << Base.getType() 4169 << Base.getSourceRange(), 4170 Context.getTypeDeclType(ClassDecl)); 4171 4172 MarkFunctionReferenced(Location, Dtor); 4173 DiagnoseUseOfDecl(Dtor, Location); 4174 } 4175 4176 // Virtual bases. 4177 for (const auto &VBase : ClassDecl->vbases()) { 4178 // Bases are always records in a well-formed non-dependent class. 4179 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4180 4181 // Ignore direct virtual bases. 4182 if (DirectVirtualBases.count(RT)) 4183 continue; 4184 4185 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4186 // If our base class is invalid, we probably can't get its dtor anyway. 4187 if (BaseClassDecl->isInvalidDecl()) 4188 continue; 4189 if (BaseClassDecl->hasIrrelevantDestructor()) 4190 continue; 4191 4192 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4193 assert(Dtor && "No dtor found for BaseClassDecl!"); 4194 if (CheckDestructorAccess( 4195 ClassDecl->getLocation(), Dtor, 4196 PDiag(diag::err_access_dtor_vbase) 4197 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4198 Context.getTypeDeclType(ClassDecl)) == 4199 AR_accessible) { 4200 CheckDerivedToBaseConversion( 4201 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4202 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4203 SourceRange(), DeclarationName(), nullptr); 4204 } 4205 4206 MarkFunctionReferenced(Location, Dtor); 4207 DiagnoseUseOfDecl(Dtor, Location); 4208 } 4209 } 4210 4211 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4212 if (!CDtorDecl) 4213 return; 4214 4215 if (CXXConstructorDecl *Constructor 4216 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4217 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4218 DiagnoseUninitializedFields(*this, Constructor); 4219 } 4220 } 4221 4222 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4223 unsigned DiagID, AbstractDiagSelID SelID) { 4224 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4225 unsigned DiagID; 4226 AbstractDiagSelID SelID; 4227 4228 public: 4229 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4230 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4231 4232 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4233 if (Suppressed) return; 4234 if (SelID == -1) 4235 S.Diag(Loc, DiagID) << T; 4236 else 4237 S.Diag(Loc, DiagID) << SelID << T; 4238 } 4239 } Diagnoser(DiagID, SelID); 4240 4241 return RequireNonAbstractType(Loc, T, Diagnoser); 4242 } 4243 4244 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4245 TypeDiagnoser &Diagnoser) { 4246 if (!getLangOpts().CPlusPlus) 4247 return false; 4248 4249 if (const ArrayType *AT = Context.getAsArrayType(T)) 4250 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4251 4252 if (const PointerType *PT = T->getAs<PointerType>()) { 4253 // Find the innermost pointer type. 4254 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4255 PT = T; 4256 4257 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4258 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4259 } 4260 4261 const RecordType *RT = T->getAs<RecordType>(); 4262 if (!RT) 4263 return false; 4264 4265 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4266 4267 // We can't answer whether something is abstract until it has a 4268 // definition. If it's currently being defined, we'll walk back 4269 // over all the declarations when we have a full definition. 4270 const CXXRecordDecl *Def = RD->getDefinition(); 4271 if (!Def || Def->isBeingDefined()) 4272 return false; 4273 4274 if (!RD->isAbstract()) 4275 return false; 4276 4277 Diagnoser.diagnose(*this, Loc, T); 4278 DiagnoseAbstractType(RD); 4279 4280 return true; 4281 } 4282 4283 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4284 // Check if we've already emitted the list of pure virtual functions 4285 // for this class. 4286 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4287 return; 4288 4289 // If the diagnostic is suppressed, don't emit the notes. We're only 4290 // going to emit them once, so try to attach them to a diagnostic we're 4291 // actually going to show. 4292 if (Diags.isLastDiagnosticIgnored()) 4293 return; 4294 4295 CXXFinalOverriderMap FinalOverriders; 4296 RD->getFinalOverriders(FinalOverriders); 4297 4298 // Keep a set of seen pure methods so we won't diagnose the same method 4299 // more than once. 4300 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4301 4302 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4303 MEnd = FinalOverriders.end(); 4304 M != MEnd; 4305 ++M) { 4306 for (OverridingMethods::iterator SO = M->second.begin(), 4307 SOEnd = M->second.end(); 4308 SO != SOEnd; ++SO) { 4309 // C++ [class.abstract]p4: 4310 // A class is abstract if it contains or inherits at least one 4311 // pure virtual function for which the final overrider is pure 4312 // virtual. 4313 4314 // 4315 if (SO->second.size() != 1) 4316 continue; 4317 4318 if (!SO->second.front().Method->isPure()) 4319 continue; 4320 4321 if (!SeenPureMethods.insert(SO->second.front().Method)) 4322 continue; 4323 4324 Diag(SO->second.front().Method->getLocation(), 4325 diag::note_pure_virtual_function) 4326 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4327 } 4328 } 4329 4330 if (!PureVirtualClassDiagSet) 4331 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4332 PureVirtualClassDiagSet->insert(RD); 4333 } 4334 4335 namespace { 4336 struct AbstractUsageInfo { 4337 Sema &S; 4338 CXXRecordDecl *Record; 4339 CanQualType AbstractType; 4340 bool Invalid; 4341 4342 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4343 : S(S), Record(Record), 4344 AbstractType(S.Context.getCanonicalType( 4345 S.Context.getTypeDeclType(Record))), 4346 Invalid(false) {} 4347 4348 void DiagnoseAbstractType() { 4349 if (Invalid) return; 4350 S.DiagnoseAbstractType(Record); 4351 Invalid = true; 4352 } 4353 4354 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4355 }; 4356 4357 struct CheckAbstractUsage { 4358 AbstractUsageInfo &Info; 4359 const NamedDecl *Ctx; 4360 4361 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4362 : Info(Info), Ctx(Ctx) {} 4363 4364 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4365 switch (TL.getTypeLocClass()) { 4366 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4367 #define TYPELOC(CLASS, PARENT) \ 4368 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4369 #include "clang/AST/TypeLocNodes.def" 4370 } 4371 } 4372 4373 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4374 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4375 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4376 if (!TL.getParam(I)) 4377 continue; 4378 4379 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4380 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4381 } 4382 } 4383 4384 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4385 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4386 } 4387 4388 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4389 // Visit the type parameters from a permissive context. 4390 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4391 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4392 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4393 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4394 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4395 // TODO: other template argument types? 4396 } 4397 } 4398 4399 // Visit pointee types from a permissive context. 4400 #define CheckPolymorphic(Type) \ 4401 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4402 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4403 } 4404 CheckPolymorphic(PointerTypeLoc) 4405 CheckPolymorphic(ReferenceTypeLoc) 4406 CheckPolymorphic(MemberPointerTypeLoc) 4407 CheckPolymorphic(BlockPointerTypeLoc) 4408 CheckPolymorphic(AtomicTypeLoc) 4409 4410 /// Handle all the types we haven't given a more specific 4411 /// implementation for above. 4412 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4413 // Every other kind of type that we haven't called out already 4414 // that has an inner type is either (1) sugar or (2) contains that 4415 // inner type in some way as a subobject. 4416 if (TypeLoc Next = TL.getNextTypeLoc()) 4417 return Visit(Next, Sel); 4418 4419 // If there's no inner type and we're in a permissive context, 4420 // don't diagnose. 4421 if (Sel == Sema::AbstractNone) return; 4422 4423 // Check whether the type matches the abstract type. 4424 QualType T = TL.getType(); 4425 if (T->isArrayType()) { 4426 Sel = Sema::AbstractArrayType; 4427 T = Info.S.Context.getBaseElementType(T); 4428 } 4429 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4430 if (CT != Info.AbstractType) return; 4431 4432 // It matched; do some magic. 4433 if (Sel == Sema::AbstractArrayType) { 4434 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4435 << T << TL.getSourceRange(); 4436 } else { 4437 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4438 << Sel << T << TL.getSourceRange(); 4439 } 4440 Info.DiagnoseAbstractType(); 4441 } 4442 }; 4443 4444 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4445 Sema::AbstractDiagSelID Sel) { 4446 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4447 } 4448 4449 } 4450 4451 /// Check for invalid uses of an abstract type in a method declaration. 4452 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4453 CXXMethodDecl *MD) { 4454 // No need to do the check on definitions, which require that 4455 // the return/param types be complete. 4456 if (MD->doesThisDeclarationHaveABody()) 4457 return; 4458 4459 // For safety's sake, just ignore it if we don't have type source 4460 // information. This should never happen for non-implicit methods, 4461 // but... 4462 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4463 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4464 } 4465 4466 /// Check for invalid uses of an abstract type within a class definition. 4467 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4468 CXXRecordDecl *RD) { 4469 for (auto *D : RD->decls()) { 4470 if (D->isImplicit()) continue; 4471 4472 // Methods and method templates. 4473 if (isa<CXXMethodDecl>(D)) { 4474 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4475 } else if (isa<FunctionTemplateDecl>(D)) { 4476 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4477 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4478 4479 // Fields and static variables. 4480 } else if (isa<FieldDecl>(D)) { 4481 FieldDecl *FD = cast<FieldDecl>(D); 4482 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4483 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4484 } else if (isa<VarDecl>(D)) { 4485 VarDecl *VD = cast<VarDecl>(D); 4486 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4487 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4488 4489 // Nested classes and class templates. 4490 } else if (isa<CXXRecordDecl>(D)) { 4491 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4492 } else if (isa<ClassTemplateDecl>(D)) { 4493 CheckAbstractClassUsage(Info, 4494 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4495 } 4496 } 4497 } 4498 4499 /// \brief Check class-level dllimport/dllexport attribute. 4500 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) { 4501 Attr *ClassAttr = getDLLAttr(Class); 4502 4503 // MSVC inherits DLL attributes to partial class template specializations. 4504 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 4505 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 4506 if (Attr *TemplateAttr = 4507 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 4508 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext())); 4509 A->setInherited(true); 4510 ClassAttr = A; 4511 } 4512 } 4513 } 4514 4515 if (!ClassAttr) 4516 return; 4517 4518 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 4519 !ClassAttr->isInherited()) { 4520 // Diagnose dll attributes on members of class with dll attribute. 4521 for (Decl *Member : Class->decls()) { 4522 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 4523 continue; 4524 InheritableAttr *MemberAttr = getDLLAttr(Member); 4525 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 4526 continue; 4527 4528 S.Diag(MemberAttr->getLocation(), 4529 diag::err_attribute_dll_member_of_dll_class) 4530 << MemberAttr << ClassAttr; 4531 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 4532 Member->setInvalidDecl(); 4533 } 4534 } 4535 4536 if (Class->getDescribedClassTemplate()) 4537 // Don't inherit dll attribute until the template is instantiated. 4538 return; 4539 4540 bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 4541 4542 // Force declaration of implicit members so they can inherit the attribute. 4543 S.ForceDeclarationOfImplicitMembers(Class); 4544 4545 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 4546 // seem to be true in practice? 4547 4548 TemplateSpecializationKind TSK = 4549 Class->getTemplateSpecializationKind(); 4550 4551 for (Decl *Member : Class->decls()) { 4552 VarDecl *VD = dyn_cast<VarDecl>(Member); 4553 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 4554 4555 // Only methods and static fields inherit the attributes. 4556 if (!VD && !MD) 4557 continue; 4558 4559 // Don't process deleted methods. 4560 if (MD && MD->isDeleted()) 4561 continue; 4562 4563 if (MD && MD->isMoveAssignmentOperator() && !ClassExported && 4564 MD->isInlined()) { 4565 // Current MSVC versions don't export the move assignment operators, so 4566 // don't attempt to import them if we have a definition. 4567 continue; 4568 } 4569 4570 if (!getDLLAttr(Member)) { 4571 auto *NewAttr = 4572 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 4573 NewAttr->setInherited(true); 4574 Member->addAttr(NewAttr); 4575 } 4576 4577 if (MD && ClassExported) { 4578 if (MD->isUserProvided()) { 4579 // Instantiate non-default methods.. 4580 4581 // .. except for certain kinds of template specializations. 4582 if (TSK == TSK_ExplicitInstantiationDeclaration) 4583 continue; 4584 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 4585 continue; 4586 4587 S.MarkFunctionReferenced(Class->getLocation(), MD); 4588 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 4589 MD->isCopyAssignmentOperator() || 4590 MD->isMoveAssignmentOperator()) { 4591 // Instantiate non-trivial or explicitly defaulted methods, and the 4592 // copy assignment / move assignment operators. 4593 S.MarkFunctionReferenced(Class->getLocation(), MD); 4594 // Resolve its exception specification; CodeGen needs it. 4595 auto *FPT = MD->getType()->getAs<FunctionProtoType>(); 4596 S.ResolveExceptionSpec(Class->getLocation(), FPT); 4597 S.ActOnFinishInlineMethodDef(MD); 4598 } 4599 } 4600 } 4601 } 4602 4603 /// \brief Perform semantic checks on a class definition that has been 4604 /// completing, introducing implicitly-declared members, checking for 4605 /// abstract types, etc. 4606 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4607 if (!Record) 4608 return; 4609 4610 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4611 AbstractUsageInfo Info(*this, Record); 4612 CheckAbstractClassUsage(Info, Record); 4613 } 4614 4615 // If this is not an aggregate type and has no user-declared constructor, 4616 // complain about any non-static data members of reference or const scalar 4617 // type, since they will never get initializers. 4618 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4619 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4620 !Record->isLambda()) { 4621 bool Complained = false; 4622 for (const auto *F : Record->fields()) { 4623 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4624 continue; 4625 4626 if (F->getType()->isReferenceType() || 4627 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4628 if (!Complained) { 4629 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4630 << Record->getTagKind() << Record; 4631 Complained = true; 4632 } 4633 4634 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4635 << F->getType()->isReferenceType() 4636 << F->getDeclName(); 4637 } 4638 } 4639 } 4640 4641 if (Record->isDynamicClass() && !Record->isDependentType()) 4642 DynamicClasses.push_back(Record); 4643 4644 if (Record->getIdentifier()) { 4645 // C++ [class.mem]p13: 4646 // If T is the name of a class, then each of the following shall have a 4647 // name different from T: 4648 // - every member of every anonymous union that is a member of class T. 4649 // 4650 // C++ [class.mem]p14: 4651 // In addition, if class T has a user-declared constructor (12.1), every 4652 // non-static data member of class T shall have a name different from T. 4653 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4654 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4655 ++I) { 4656 NamedDecl *D = *I; 4657 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4658 isa<IndirectFieldDecl>(D)) { 4659 Diag(D->getLocation(), diag::err_member_name_of_class) 4660 << D->getDeclName(); 4661 break; 4662 } 4663 } 4664 } 4665 4666 // Warn if the class has virtual methods but non-virtual public destructor. 4667 if (Record->isPolymorphic() && !Record->isDependentType()) { 4668 CXXDestructorDecl *dtor = Record->getDestructor(); 4669 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 4670 !Record->hasAttr<FinalAttr>()) 4671 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4672 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4673 } 4674 4675 if (Record->isAbstract()) { 4676 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4677 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4678 << FA->isSpelledAsSealed(); 4679 DiagnoseAbstractType(Record); 4680 } 4681 } 4682 4683 if (!Record->isDependentType()) { 4684 for (auto *M : Record->methods()) { 4685 // See if a method overloads virtual methods in a base 4686 // class without overriding any. 4687 if (!M->isStatic()) 4688 DiagnoseHiddenVirtualMethods(M); 4689 4690 // Check whether the explicitly-defaulted special members are valid. 4691 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4692 CheckExplicitlyDefaultedSpecialMember(M); 4693 4694 // For an explicitly defaulted or deleted special member, we defer 4695 // determining triviality until the class is complete. That time is now! 4696 if (!M->isImplicit() && !M->isUserProvided()) { 4697 CXXSpecialMember CSM = getSpecialMember(M); 4698 if (CSM != CXXInvalid) { 4699 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 4700 4701 // Inform the class that we've finished declaring this member. 4702 Record->finishedDefaultedOrDeletedMember(M); 4703 } 4704 } 4705 } 4706 } 4707 4708 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4709 // function that is not a constructor declares that member function to be 4710 // const. [...] The class of which that function is a member shall be 4711 // a literal type. 4712 // 4713 // If the class has virtual bases, any constexpr members will already have 4714 // been diagnosed by the checks performed on the member declaration, so 4715 // suppress this (less useful) diagnostic. 4716 // 4717 // We delay this until we know whether an explicitly-defaulted (or deleted) 4718 // destructor for the class is trivial. 4719 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4720 !Record->isLiteral() && !Record->getNumVBases()) { 4721 for (const auto *M : Record->methods()) { 4722 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) { 4723 switch (Record->getTemplateSpecializationKind()) { 4724 case TSK_ImplicitInstantiation: 4725 case TSK_ExplicitInstantiationDeclaration: 4726 case TSK_ExplicitInstantiationDefinition: 4727 // If a template instantiates to a non-literal type, but its members 4728 // instantiate to constexpr functions, the template is technically 4729 // ill-formed, but we allow it for sanity. 4730 continue; 4731 4732 case TSK_Undeclared: 4733 case TSK_ExplicitSpecialization: 4734 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4735 diag::err_constexpr_method_non_literal); 4736 break; 4737 } 4738 4739 // Only produce one error per class. 4740 break; 4741 } 4742 } 4743 } 4744 4745 // ms_struct is a request to use the same ABI rules as MSVC. Check 4746 // whether this class uses any C++ features that are implemented 4747 // completely differently in MSVC, and if so, emit a diagnostic. 4748 // That diagnostic defaults to an error, but we allow projects to 4749 // map it down to a warning (or ignore it). It's a fairly common 4750 // practice among users of the ms_struct pragma to mass-annotate 4751 // headers, sweeping up a bunch of types that the project doesn't 4752 // really rely on MSVC-compatible layout for. We must therefore 4753 // support "ms_struct except for C++ stuff" as a secondary ABI. 4754 if (Record->isMsStruct(Context) && 4755 (Record->isPolymorphic() || Record->getNumBases())) { 4756 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 4757 } 4758 4759 // Declare inheriting constructors. We do this eagerly here because: 4760 // - The standard requires an eager diagnostic for conflicting inheriting 4761 // constructors from different classes. 4762 // - The lazy declaration of the other implicit constructors is so as to not 4763 // waste space and performance on classes that are not meant to be 4764 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4765 // have inheriting constructors. 4766 DeclareInheritingConstructors(Record); 4767 4768 checkDLLAttribute(*this, Record); 4769 } 4770 4771 /// Look up the special member function that would be called by a special 4772 /// member function for a subobject of class type. 4773 /// 4774 /// \param Class The class type of the subobject. 4775 /// \param CSM The kind of special member function. 4776 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 4777 /// \param ConstRHS True if this is a copy operation with a const object 4778 /// on its RHS, that is, if the argument to the outer special member 4779 /// function is 'const' and this is not a field marked 'mutable'. 4780 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 4781 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 4782 unsigned FieldQuals, bool ConstRHS) { 4783 unsigned LHSQuals = 0; 4784 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 4785 LHSQuals = FieldQuals; 4786 4787 unsigned RHSQuals = FieldQuals; 4788 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4789 RHSQuals = 0; 4790 else if (ConstRHS) 4791 RHSQuals |= Qualifiers::Const; 4792 4793 return S.LookupSpecialMember(Class, CSM, 4794 RHSQuals & Qualifiers::Const, 4795 RHSQuals & Qualifiers::Volatile, 4796 false, 4797 LHSQuals & Qualifiers::Const, 4798 LHSQuals & Qualifiers::Volatile); 4799 } 4800 4801 /// Is the special member function which would be selected to perform the 4802 /// specified operation on the specified class type a constexpr constructor? 4803 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4804 Sema::CXXSpecialMember CSM, 4805 unsigned Quals, bool ConstRHS) { 4806 Sema::SpecialMemberOverloadResult *SMOR = 4807 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 4808 if (!SMOR || !SMOR->getMethod()) 4809 // A constructor we wouldn't select can't be "involved in initializing" 4810 // anything. 4811 return true; 4812 return SMOR->getMethod()->isConstexpr(); 4813 } 4814 4815 /// Determine whether the specified special member function would be constexpr 4816 /// if it were implicitly defined. 4817 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4818 Sema::CXXSpecialMember CSM, 4819 bool ConstArg) { 4820 if (!S.getLangOpts().CPlusPlus11) 4821 return false; 4822 4823 // C++11 [dcl.constexpr]p4: 4824 // In the definition of a constexpr constructor [...] 4825 bool Ctor = true; 4826 switch (CSM) { 4827 case Sema::CXXDefaultConstructor: 4828 // Since default constructor lookup is essentially trivial (and cannot 4829 // involve, for instance, template instantiation), we compute whether a 4830 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4831 // 4832 // This is important for performance; we need to know whether the default 4833 // constructor is constexpr to determine whether the type is a literal type. 4834 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4835 4836 case Sema::CXXCopyConstructor: 4837 case Sema::CXXMoveConstructor: 4838 // For copy or move constructors, we need to perform overload resolution. 4839 break; 4840 4841 case Sema::CXXCopyAssignment: 4842 case Sema::CXXMoveAssignment: 4843 if (!S.getLangOpts().CPlusPlus14) 4844 return false; 4845 // In C++1y, we need to perform overload resolution. 4846 Ctor = false; 4847 break; 4848 4849 case Sema::CXXDestructor: 4850 case Sema::CXXInvalid: 4851 return false; 4852 } 4853 4854 // -- if the class is a non-empty union, or for each non-empty anonymous 4855 // union member of a non-union class, exactly one non-static data member 4856 // shall be initialized; [DR1359] 4857 // 4858 // If we squint, this is guaranteed, since exactly one non-static data member 4859 // will be initialized (if the constructor isn't deleted), we just don't know 4860 // which one. 4861 if (Ctor && ClassDecl->isUnion()) 4862 return true; 4863 4864 // -- the class shall not have any virtual base classes; 4865 if (Ctor && ClassDecl->getNumVBases()) 4866 return false; 4867 4868 // C++1y [class.copy]p26: 4869 // -- [the class] is a literal type, and 4870 if (!Ctor && !ClassDecl->isLiteral()) 4871 return false; 4872 4873 // -- every constructor involved in initializing [...] base class 4874 // sub-objects shall be a constexpr constructor; 4875 // -- the assignment operator selected to copy/move each direct base 4876 // class is a constexpr function, and 4877 for (const auto &B : ClassDecl->bases()) { 4878 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 4879 if (!BaseType) continue; 4880 4881 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4882 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 4883 return false; 4884 } 4885 4886 // -- every constructor involved in initializing non-static data members 4887 // [...] shall be a constexpr constructor; 4888 // -- every non-static data member and base class sub-object shall be 4889 // initialized 4890 // -- for each non-static data member of X that is of class type (or array 4891 // thereof), the assignment operator selected to copy/move that member is 4892 // a constexpr function 4893 for (const auto *F : ClassDecl->fields()) { 4894 if (F->isInvalidDecl()) 4895 continue; 4896 QualType BaseType = S.Context.getBaseElementType(F->getType()); 4897 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 4898 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4899 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 4900 BaseType.getCVRQualifiers(), 4901 ConstArg && !F->isMutable())) 4902 return false; 4903 } 4904 } 4905 4906 // All OK, it's constexpr! 4907 return true; 4908 } 4909 4910 static Sema::ImplicitExceptionSpecification 4911 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4912 switch (S.getSpecialMember(MD)) { 4913 case Sema::CXXDefaultConstructor: 4914 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4915 case Sema::CXXCopyConstructor: 4916 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4917 case Sema::CXXCopyAssignment: 4918 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4919 case Sema::CXXMoveConstructor: 4920 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4921 case Sema::CXXMoveAssignment: 4922 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4923 case Sema::CXXDestructor: 4924 return S.ComputeDefaultedDtorExceptionSpec(MD); 4925 case Sema::CXXInvalid: 4926 break; 4927 } 4928 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4929 "only special members have implicit exception specs"); 4930 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4931 } 4932 4933 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 4934 CXXMethodDecl *MD) { 4935 FunctionProtoType::ExtProtoInfo EPI; 4936 4937 // Build an exception specification pointing back at this member. 4938 EPI.ExceptionSpec.Type = EST_Unevaluated; 4939 EPI.ExceptionSpec.SourceDecl = MD; 4940 4941 // Set the calling convention to the default for C++ instance methods. 4942 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 4943 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4944 /*IsCXXMethod=*/true)); 4945 return EPI; 4946 } 4947 4948 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4949 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4950 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4951 return; 4952 4953 // Evaluate the exception specification. 4954 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 4955 4956 // Update the type of the special member to use it. 4957 UpdateExceptionSpec(MD, ESI); 4958 4959 // A user-provided destructor can be defined outside the class. When that 4960 // happens, be sure to update the exception specification on both 4961 // declarations. 4962 const FunctionProtoType *CanonicalFPT = 4963 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4964 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4965 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 4966 } 4967 4968 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4969 CXXRecordDecl *RD = MD->getParent(); 4970 CXXSpecialMember CSM = getSpecialMember(MD); 4971 4972 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4973 "not an explicitly-defaulted special member"); 4974 4975 // Whether this was the first-declared instance of the constructor. 4976 // This affects whether we implicitly add an exception spec and constexpr. 4977 bool First = MD == MD->getCanonicalDecl(); 4978 4979 bool HadError = false; 4980 4981 // C++11 [dcl.fct.def.default]p1: 4982 // A function that is explicitly defaulted shall 4983 // -- be a special member function (checked elsewhere), 4984 // -- have the same type (except for ref-qualifiers, and except that a 4985 // copy operation can take a non-const reference) as an implicit 4986 // declaration, and 4987 // -- not have default arguments. 4988 unsigned ExpectedParams = 1; 4989 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4990 ExpectedParams = 0; 4991 if (MD->getNumParams() != ExpectedParams) { 4992 // This also checks for default arguments: a copy or move constructor with a 4993 // default argument is classified as a default constructor, and assignment 4994 // operations and destructors can't have default arguments. 4995 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4996 << CSM << MD->getSourceRange(); 4997 HadError = true; 4998 } else if (MD->isVariadic()) { 4999 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 5000 << CSM << MD->getSourceRange(); 5001 HadError = true; 5002 } 5003 5004 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 5005 5006 bool CanHaveConstParam = false; 5007 if (CSM == CXXCopyConstructor) 5008 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 5009 else if (CSM == CXXCopyAssignment) 5010 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 5011 5012 QualType ReturnType = Context.VoidTy; 5013 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 5014 // Check for return type matching. 5015 ReturnType = Type->getReturnType(); 5016 QualType ExpectedReturnType = 5017 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 5018 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 5019 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 5020 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 5021 HadError = true; 5022 } 5023 5024 // A defaulted special member cannot have cv-qualifiers. 5025 if (Type->getTypeQuals()) { 5026 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 5027 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 5028 HadError = true; 5029 } 5030 } 5031 5032 // Check for parameter type matching. 5033 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 5034 bool HasConstParam = false; 5035 if (ExpectedParams && ArgType->isReferenceType()) { 5036 // Argument must be reference to possibly-const T. 5037 QualType ReferentType = ArgType->getPointeeType(); 5038 HasConstParam = ReferentType.isConstQualified(); 5039 5040 if (ReferentType.isVolatileQualified()) { 5041 Diag(MD->getLocation(), 5042 diag::err_defaulted_special_member_volatile_param) << CSM; 5043 HadError = true; 5044 } 5045 5046 if (HasConstParam && !CanHaveConstParam) { 5047 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 5048 Diag(MD->getLocation(), 5049 diag::err_defaulted_special_member_copy_const_param) 5050 << (CSM == CXXCopyAssignment); 5051 // FIXME: Explain why this special member can't be const. 5052 } else { 5053 Diag(MD->getLocation(), 5054 diag::err_defaulted_special_member_move_const_param) 5055 << (CSM == CXXMoveAssignment); 5056 } 5057 HadError = true; 5058 } 5059 } else if (ExpectedParams) { 5060 // A copy assignment operator can take its argument by value, but a 5061 // defaulted one cannot. 5062 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 5063 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 5064 HadError = true; 5065 } 5066 5067 // C++11 [dcl.fct.def.default]p2: 5068 // An explicitly-defaulted function may be declared constexpr only if it 5069 // would have been implicitly declared as constexpr, 5070 // Do not apply this rule to members of class templates, since core issue 1358 5071 // makes such functions always instantiate to constexpr functions. For 5072 // functions which cannot be constexpr (for non-constructors in C++11 and for 5073 // destructors in C++1y), this is checked elsewhere. 5074 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 5075 HasConstParam); 5076 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 5077 : isa<CXXConstructorDecl>(MD)) && 5078 MD->isConstexpr() && !Constexpr && 5079 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 5080 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 5081 // FIXME: Explain why the special member can't be constexpr. 5082 HadError = true; 5083 } 5084 5085 // and may have an explicit exception-specification only if it is compatible 5086 // with the exception-specification on the implicit declaration. 5087 if (Type->hasExceptionSpec()) { 5088 // Delay the check if this is the first declaration of the special member, 5089 // since we may not have parsed some necessary in-class initializers yet. 5090 if (First) { 5091 // If the exception specification needs to be instantiated, do so now, 5092 // before we clobber it with an EST_Unevaluated specification below. 5093 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 5094 InstantiateExceptionSpec(MD->getLocStart(), MD); 5095 Type = MD->getType()->getAs<FunctionProtoType>(); 5096 } 5097 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 5098 } else 5099 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 5100 } 5101 5102 // If a function is explicitly defaulted on its first declaration, 5103 if (First) { 5104 // -- it is implicitly considered to be constexpr if the implicit 5105 // definition would be, 5106 MD->setConstexpr(Constexpr); 5107 5108 // -- it is implicitly considered to have the same exception-specification 5109 // as if it had been implicitly declared, 5110 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 5111 EPI.ExceptionSpec.Type = EST_Unevaluated; 5112 EPI.ExceptionSpec.SourceDecl = MD; 5113 MD->setType(Context.getFunctionType(ReturnType, 5114 llvm::makeArrayRef(&ArgType, 5115 ExpectedParams), 5116 EPI)); 5117 } 5118 5119 if (ShouldDeleteSpecialMember(MD, CSM)) { 5120 if (First) { 5121 SetDeclDeleted(MD, MD->getLocation()); 5122 } else { 5123 // C++11 [dcl.fct.def.default]p4: 5124 // [For a] user-provided explicitly-defaulted function [...] if such a 5125 // function is implicitly defined as deleted, the program is ill-formed. 5126 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 5127 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 5128 HadError = true; 5129 } 5130 } 5131 5132 if (HadError) 5133 MD->setInvalidDecl(); 5134 } 5135 5136 /// Check whether the exception specification provided for an 5137 /// explicitly-defaulted special member matches the exception specification 5138 /// that would have been generated for an implicit special member, per 5139 /// C++11 [dcl.fct.def.default]p2. 5140 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 5141 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 5142 // Compute the implicit exception specification. 5143 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5144 /*IsCXXMethod=*/true); 5145 FunctionProtoType::ExtProtoInfo EPI(CC); 5146 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 5147 .getExceptionSpec(); 5148 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 5149 Context.getFunctionType(Context.VoidTy, None, EPI)); 5150 5151 // Ensure that it matches. 5152 CheckEquivalentExceptionSpec( 5153 PDiag(diag::err_incorrect_defaulted_exception_spec) 5154 << getSpecialMember(MD), PDiag(), 5155 ImplicitType, SourceLocation(), 5156 SpecifiedType, MD->getLocation()); 5157 } 5158 5159 void Sema::CheckDelayedMemberExceptionSpecs() { 5160 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>, 5161 2> Checks; 5162 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs; 5163 5164 std::swap(Checks, DelayedDestructorExceptionSpecChecks); 5165 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 5166 5167 // Perform any deferred checking of exception specifications for virtual 5168 // destructors. 5169 for (unsigned i = 0, e = Checks.size(); i != e; ++i) { 5170 const CXXDestructorDecl *Dtor = Checks[i].first; 5171 assert(!Dtor->getParent()->isDependentType() && 5172 "Should not ever add destructors of templates into the list."); 5173 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second); 5174 } 5175 5176 // Check that any explicitly-defaulted methods have exception specifications 5177 // compatible with their implicit exception specifications. 5178 for (unsigned I = 0, N = Specs.size(); I != N; ++I) 5179 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first, 5180 Specs[I].second); 5181 } 5182 5183 namespace { 5184 struct SpecialMemberDeletionInfo { 5185 Sema &S; 5186 CXXMethodDecl *MD; 5187 Sema::CXXSpecialMember CSM; 5188 bool Diagnose; 5189 5190 // Properties of the special member, computed for convenience. 5191 bool IsConstructor, IsAssignment, IsMove, ConstArg; 5192 SourceLocation Loc; 5193 5194 bool AllFieldsAreConst; 5195 5196 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 5197 Sema::CXXSpecialMember CSM, bool Diagnose) 5198 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 5199 IsConstructor(false), IsAssignment(false), IsMove(false), 5200 ConstArg(false), Loc(MD->getLocation()), 5201 AllFieldsAreConst(true) { 5202 switch (CSM) { 5203 case Sema::CXXDefaultConstructor: 5204 case Sema::CXXCopyConstructor: 5205 IsConstructor = true; 5206 break; 5207 case Sema::CXXMoveConstructor: 5208 IsConstructor = true; 5209 IsMove = true; 5210 break; 5211 case Sema::CXXCopyAssignment: 5212 IsAssignment = true; 5213 break; 5214 case Sema::CXXMoveAssignment: 5215 IsAssignment = true; 5216 IsMove = true; 5217 break; 5218 case Sema::CXXDestructor: 5219 break; 5220 case Sema::CXXInvalid: 5221 llvm_unreachable("invalid special member kind"); 5222 } 5223 5224 if (MD->getNumParams()) { 5225 if (const ReferenceType *RT = 5226 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 5227 ConstArg = RT->getPointeeType().isConstQualified(); 5228 } 5229 } 5230 5231 bool inUnion() const { return MD->getParent()->isUnion(); } 5232 5233 /// Look up the corresponding special member in the given class. 5234 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5235 unsigned Quals, bool IsMutable) { 5236 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5237 ConstArg && !IsMutable); 5238 } 5239 5240 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5241 5242 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5243 bool shouldDeleteForField(FieldDecl *FD); 5244 bool shouldDeleteForAllConstMembers(); 5245 5246 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5247 unsigned Quals); 5248 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5249 Sema::SpecialMemberOverloadResult *SMOR, 5250 bool IsDtorCallInCtor); 5251 5252 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5253 }; 5254 } 5255 5256 /// Is the given special member inaccessible when used on the given 5257 /// sub-object. 5258 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5259 CXXMethodDecl *target) { 5260 /// If we're operating on a base class, the object type is the 5261 /// type of this special member. 5262 QualType objectTy; 5263 AccessSpecifier access = target->getAccess(); 5264 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5265 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5266 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5267 5268 // If we're operating on a field, the object type is the type of the field. 5269 } else { 5270 objectTy = S.Context.getTypeDeclType(target->getParent()); 5271 } 5272 5273 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5274 } 5275 5276 /// Check whether we should delete a special member due to the implicit 5277 /// definition containing a call to a special member of a subobject. 5278 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5279 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5280 bool IsDtorCallInCtor) { 5281 CXXMethodDecl *Decl = SMOR->getMethod(); 5282 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5283 5284 int DiagKind = -1; 5285 5286 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5287 DiagKind = !Decl ? 0 : 1; 5288 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5289 DiagKind = 2; 5290 else if (!isAccessible(Subobj, Decl)) 5291 DiagKind = 3; 5292 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5293 !Decl->isTrivial()) { 5294 // A member of a union must have a trivial corresponding special member. 5295 // As a weird special case, a destructor call from a union's constructor 5296 // must be accessible and non-deleted, but need not be trivial. Such a 5297 // destructor is never actually called, but is semantically checked as 5298 // if it were. 5299 DiagKind = 4; 5300 } 5301 5302 if (DiagKind == -1) 5303 return false; 5304 5305 if (Diagnose) { 5306 if (Field) { 5307 S.Diag(Field->getLocation(), 5308 diag::note_deleted_special_member_class_subobject) 5309 << CSM << MD->getParent() << /*IsField*/true 5310 << Field << DiagKind << IsDtorCallInCtor; 5311 } else { 5312 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5313 S.Diag(Base->getLocStart(), 5314 diag::note_deleted_special_member_class_subobject) 5315 << CSM << MD->getParent() << /*IsField*/false 5316 << Base->getType() << DiagKind << IsDtorCallInCtor; 5317 } 5318 5319 if (DiagKind == 1) 5320 S.NoteDeletedFunction(Decl); 5321 // FIXME: Explain inaccessibility if DiagKind == 3. 5322 } 5323 5324 return true; 5325 } 5326 5327 /// Check whether we should delete a special member function due to having a 5328 /// direct or virtual base class or non-static data member of class type M. 5329 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5330 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5331 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5332 bool IsMutable = Field && Field->isMutable(); 5333 5334 // C++11 [class.ctor]p5: 5335 // -- any direct or virtual base class, or non-static data member with no 5336 // brace-or-equal-initializer, has class type M (or array thereof) and 5337 // either M has no default constructor or overload resolution as applied 5338 // to M's default constructor results in an ambiguity or in a function 5339 // that is deleted or inaccessible 5340 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5341 // -- a direct or virtual base class B that cannot be copied/moved because 5342 // overload resolution, as applied to B's corresponding special member, 5343 // results in an ambiguity or a function that is deleted or inaccessible 5344 // from the defaulted special member 5345 // C++11 [class.dtor]p5: 5346 // -- any direct or virtual base class [...] has a type with a destructor 5347 // that is deleted or inaccessible 5348 if (!(CSM == Sema::CXXDefaultConstructor && 5349 Field && Field->hasInClassInitializer()) && 5350 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5351 false)) 5352 return true; 5353 5354 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5355 // -- any direct or virtual base class or non-static data member has a 5356 // type with a destructor that is deleted or inaccessible 5357 if (IsConstructor) { 5358 Sema::SpecialMemberOverloadResult *SMOR = 5359 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5360 false, false, false, false, false); 5361 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5362 return true; 5363 } 5364 5365 return false; 5366 } 5367 5368 /// Check whether we should delete a special member function due to the class 5369 /// having a particular direct or virtual base class. 5370 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5371 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5372 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5373 } 5374 5375 /// Check whether we should delete a special member function due to the class 5376 /// having a particular non-static data member. 5377 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5378 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5379 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5380 5381 if (CSM == Sema::CXXDefaultConstructor) { 5382 // For a default constructor, all references must be initialized in-class 5383 // and, if a union, it must have a non-const member. 5384 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5385 if (Diagnose) 5386 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5387 << MD->getParent() << FD << FieldType << /*Reference*/0; 5388 return true; 5389 } 5390 // C++11 [class.ctor]p5: any non-variant non-static data member of 5391 // const-qualified type (or array thereof) with no 5392 // brace-or-equal-initializer does not have a user-provided default 5393 // constructor. 5394 if (!inUnion() && FieldType.isConstQualified() && 5395 !FD->hasInClassInitializer() && 5396 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5397 if (Diagnose) 5398 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5399 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5400 return true; 5401 } 5402 5403 if (inUnion() && !FieldType.isConstQualified()) 5404 AllFieldsAreConst = false; 5405 } else if (CSM == Sema::CXXCopyConstructor) { 5406 // For a copy constructor, data members must not be of rvalue reference 5407 // type. 5408 if (FieldType->isRValueReferenceType()) { 5409 if (Diagnose) 5410 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5411 << MD->getParent() << FD << FieldType; 5412 return true; 5413 } 5414 } else if (IsAssignment) { 5415 // For an assignment operator, data members must not be of reference type. 5416 if (FieldType->isReferenceType()) { 5417 if (Diagnose) 5418 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5419 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5420 return true; 5421 } 5422 if (!FieldRecord && FieldType.isConstQualified()) { 5423 // C++11 [class.copy]p23: 5424 // -- a non-static data member of const non-class type (or array thereof) 5425 if (Diagnose) 5426 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5427 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5428 return true; 5429 } 5430 } 5431 5432 if (FieldRecord) { 5433 // Some additional restrictions exist on the variant members. 5434 if (!inUnion() && FieldRecord->isUnion() && 5435 FieldRecord->isAnonymousStructOrUnion()) { 5436 bool AllVariantFieldsAreConst = true; 5437 5438 // FIXME: Handle anonymous unions declared within anonymous unions. 5439 for (auto *UI : FieldRecord->fields()) { 5440 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5441 5442 if (!UnionFieldType.isConstQualified()) 5443 AllVariantFieldsAreConst = false; 5444 5445 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5446 if (UnionFieldRecord && 5447 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5448 UnionFieldType.getCVRQualifiers())) 5449 return true; 5450 } 5451 5452 // At least one member in each anonymous union must be non-const 5453 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5454 !FieldRecord->field_empty()) { 5455 if (Diagnose) 5456 S.Diag(FieldRecord->getLocation(), 5457 diag::note_deleted_default_ctor_all_const) 5458 << MD->getParent() << /*anonymous union*/1; 5459 return true; 5460 } 5461 5462 // Don't check the implicit member of the anonymous union type. 5463 // This is technically non-conformant, but sanity demands it. 5464 return false; 5465 } 5466 5467 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5468 FieldType.getCVRQualifiers())) 5469 return true; 5470 } 5471 5472 return false; 5473 } 5474 5475 /// C++11 [class.ctor] p5: 5476 /// A defaulted default constructor for a class X is defined as deleted if 5477 /// X is a union and all of its variant members are of const-qualified type. 5478 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5479 // This is a silly definition, because it gives an empty union a deleted 5480 // default constructor. Don't do that. 5481 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5482 !MD->getParent()->field_empty()) { 5483 if (Diagnose) 5484 S.Diag(MD->getParent()->getLocation(), 5485 diag::note_deleted_default_ctor_all_const) 5486 << MD->getParent() << /*not anonymous union*/0; 5487 return true; 5488 } 5489 return false; 5490 } 5491 5492 /// Determine whether a defaulted special member function should be defined as 5493 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5494 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5495 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5496 bool Diagnose) { 5497 if (MD->isInvalidDecl()) 5498 return false; 5499 CXXRecordDecl *RD = MD->getParent(); 5500 assert(!RD->isDependentType() && "do deletion after instantiation"); 5501 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5502 return false; 5503 5504 // C++11 [expr.lambda.prim]p19: 5505 // The closure type associated with a lambda-expression has a 5506 // deleted (8.4.3) default constructor and a deleted copy 5507 // assignment operator. 5508 if (RD->isLambda() && 5509 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5510 if (Diagnose) 5511 Diag(RD->getLocation(), diag::note_lambda_decl); 5512 return true; 5513 } 5514 5515 // For an anonymous struct or union, the copy and assignment special members 5516 // will never be used, so skip the check. For an anonymous union declared at 5517 // namespace scope, the constructor and destructor are used. 5518 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5519 RD->isAnonymousStructOrUnion()) 5520 return false; 5521 5522 // C++11 [class.copy]p7, p18: 5523 // If the class definition declares a move constructor or move assignment 5524 // operator, an implicitly declared copy constructor or copy assignment 5525 // operator is defined as deleted. 5526 if (MD->isImplicit() && 5527 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5528 CXXMethodDecl *UserDeclaredMove = nullptr; 5529 5530 // In Microsoft mode, a user-declared move only causes the deletion of the 5531 // corresponding copy operation, not both copy operations. 5532 if (RD->hasUserDeclaredMoveConstructor() && 5533 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5534 if (!Diagnose) return true; 5535 5536 // Find any user-declared move constructor. 5537 for (auto *I : RD->ctors()) { 5538 if (I->isMoveConstructor()) { 5539 UserDeclaredMove = I; 5540 break; 5541 } 5542 } 5543 assert(UserDeclaredMove); 5544 } else if (RD->hasUserDeclaredMoveAssignment() && 5545 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5546 if (!Diagnose) return true; 5547 5548 // Find any user-declared move assignment operator. 5549 for (auto *I : RD->methods()) { 5550 if (I->isMoveAssignmentOperator()) { 5551 UserDeclaredMove = I; 5552 break; 5553 } 5554 } 5555 assert(UserDeclaredMove); 5556 } 5557 5558 if (UserDeclaredMove) { 5559 Diag(UserDeclaredMove->getLocation(), 5560 diag::note_deleted_copy_user_declared_move) 5561 << (CSM == CXXCopyAssignment) << RD 5562 << UserDeclaredMove->isMoveAssignmentOperator(); 5563 return true; 5564 } 5565 } 5566 5567 // Do access control from the special member function 5568 ContextRAII MethodContext(*this, MD); 5569 5570 // C++11 [class.dtor]p5: 5571 // -- for a virtual destructor, lookup of the non-array deallocation function 5572 // results in an ambiguity or in a function that is deleted or inaccessible 5573 if (CSM == CXXDestructor && MD->isVirtual()) { 5574 FunctionDecl *OperatorDelete = nullptr; 5575 DeclarationName Name = 5576 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5577 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5578 OperatorDelete, false)) { 5579 if (Diagnose) 5580 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5581 return true; 5582 } 5583 } 5584 5585 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5586 5587 for (auto &BI : RD->bases()) 5588 if (!BI.isVirtual() && 5589 SMI.shouldDeleteForBase(&BI)) 5590 return true; 5591 5592 // Per DR1611, do not consider virtual bases of constructors of abstract 5593 // classes, since we are not going to construct them. 5594 if (!RD->isAbstract() || !SMI.IsConstructor) { 5595 for (auto &BI : RD->vbases()) 5596 if (SMI.shouldDeleteForBase(&BI)) 5597 return true; 5598 } 5599 5600 for (auto *FI : RD->fields()) 5601 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5602 SMI.shouldDeleteForField(FI)) 5603 return true; 5604 5605 if (SMI.shouldDeleteForAllConstMembers()) 5606 return true; 5607 5608 if (getLangOpts().CUDA) { 5609 // We should delete the special member in CUDA mode if target inference 5610 // failed. 5611 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 5612 Diagnose); 5613 } 5614 5615 return false; 5616 } 5617 5618 /// Perform lookup for a special member of the specified kind, and determine 5619 /// whether it is trivial. If the triviality can be determined without the 5620 /// lookup, skip it. This is intended for use when determining whether a 5621 /// special member of a containing object is trivial, and thus does not ever 5622 /// perform overload resolution for default constructors. 5623 /// 5624 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5625 /// member that was most likely to be intended to be trivial, if any. 5626 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5627 Sema::CXXSpecialMember CSM, unsigned Quals, 5628 bool ConstRHS, CXXMethodDecl **Selected) { 5629 if (Selected) 5630 *Selected = nullptr; 5631 5632 switch (CSM) { 5633 case Sema::CXXInvalid: 5634 llvm_unreachable("not a special member"); 5635 5636 case Sema::CXXDefaultConstructor: 5637 // C++11 [class.ctor]p5: 5638 // A default constructor is trivial if: 5639 // - all the [direct subobjects] have trivial default constructors 5640 // 5641 // Note, no overload resolution is performed in this case. 5642 if (RD->hasTrivialDefaultConstructor()) 5643 return true; 5644 5645 if (Selected) { 5646 // If there's a default constructor which could have been trivial, dig it 5647 // out. Otherwise, if there's any user-provided default constructor, point 5648 // to that as an example of why there's not a trivial one. 5649 CXXConstructorDecl *DefCtor = nullptr; 5650 if (RD->needsImplicitDefaultConstructor()) 5651 S.DeclareImplicitDefaultConstructor(RD); 5652 for (auto *CI : RD->ctors()) { 5653 if (!CI->isDefaultConstructor()) 5654 continue; 5655 DefCtor = CI; 5656 if (!DefCtor->isUserProvided()) 5657 break; 5658 } 5659 5660 *Selected = DefCtor; 5661 } 5662 5663 return false; 5664 5665 case Sema::CXXDestructor: 5666 // C++11 [class.dtor]p5: 5667 // A destructor is trivial if: 5668 // - all the direct [subobjects] have trivial destructors 5669 if (RD->hasTrivialDestructor()) 5670 return true; 5671 5672 if (Selected) { 5673 if (RD->needsImplicitDestructor()) 5674 S.DeclareImplicitDestructor(RD); 5675 *Selected = RD->getDestructor(); 5676 } 5677 5678 return false; 5679 5680 case Sema::CXXCopyConstructor: 5681 // C++11 [class.copy]p12: 5682 // A copy constructor is trivial if: 5683 // - the constructor selected to copy each direct [subobject] is trivial 5684 if (RD->hasTrivialCopyConstructor()) { 5685 if (Quals == Qualifiers::Const) 5686 // We must either select the trivial copy constructor or reach an 5687 // ambiguity; no need to actually perform overload resolution. 5688 return true; 5689 } else if (!Selected) { 5690 return false; 5691 } 5692 // In C++98, we are not supposed to perform overload resolution here, but we 5693 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5694 // cases like B as having a non-trivial copy constructor: 5695 // struct A { template<typename T> A(T&); }; 5696 // struct B { mutable A a; }; 5697 goto NeedOverloadResolution; 5698 5699 case Sema::CXXCopyAssignment: 5700 // C++11 [class.copy]p25: 5701 // A copy assignment operator is trivial if: 5702 // - the assignment operator selected to copy each direct [subobject] is 5703 // trivial 5704 if (RD->hasTrivialCopyAssignment()) { 5705 if (Quals == Qualifiers::Const) 5706 return true; 5707 } else if (!Selected) { 5708 return false; 5709 } 5710 // In C++98, we are not supposed to perform overload resolution here, but we 5711 // treat that as a language defect. 5712 goto NeedOverloadResolution; 5713 5714 case Sema::CXXMoveConstructor: 5715 case Sema::CXXMoveAssignment: 5716 NeedOverloadResolution: 5717 Sema::SpecialMemberOverloadResult *SMOR = 5718 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5719 5720 // The standard doesn't describe how to behave if the lookup is ambiguous. 5721 // We treat it as not making the member non-trivial, just like the standard 5722 // mandates for the default constructor. This should rarely matter, because 5723 // the member will also be deleted. 5724 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5725 return true; 5726 5727 if (!SMOR->getMethod()) { 5728 assert(SMOR->getKind() == 5729 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5730 return false; 5731 } 5732 5733 // We deliberately don't check if we found a deleted special member. We're 5734 // not supposed to! 5735 if (Selected) 5736 *Selected = SMOR->getMethod(); 5737 return SMOR->getMethod()->isTrivial(); 5738 } 5739 5740 llvm_unreachable("unknown special method kind"); 5741 } 5742 5743 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5744 for (auto *CI : RD->ctors()) 5745 if (!CI->isImplicit()) 5746 return CI; 5747 5748 // Look for constructor templates. 5749 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5750 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5751 if (CXXConstructorDecl *CD = 5752 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5753 return CD; 5754 } 5755 5756 return nullptr; 5757 } 5758 5759 /// The kind of subobject we are checking for triviality. The values of this 5760 /// enumeration are used in diagnostics. 5761 enum TrivialSubobjectKind { 5762 /// The subobject is a base class. 5763 TSK_BaseClass, 5764 /// The subobject is a non-static data member. 5765 TSK_Field, 5766 /// The object is actually the complete object. 5767 TSK_CompleteObject 5768 }; 5769 5770 /// Check whether the special member selected for a given type would be trivial. 5771 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5772 QualType SubType, bool ConstRHS, 5773 Sema::CXXSpecialMember CSM, 5774 TrivialSubobjectKind Kind, 5775 bool Diagnose) { 5776 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5777 if (!SubRD) 5778 return true; 5779 5780 CXXMethodDecl *Selected; 5781 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5782 ConstRHS, Diagnose ? &Selected : nullptr)) 5783 return true; 5784 5785 if (Diagnose) { 5786 if (ConstRHS) 5787 SubType.addConst(); 5788 5789 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5790 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5791 << Kind << SubType.getUnqualifiedType(); 5792 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5793 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5794 } else if (!Selected) 5795 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5796 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5797 else if (Selected->isUserProvided()) { 5798 if (Kind == TSK_CompleteObject) 5799 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5800 << Kind << SubType.getUnqualifiedType() << CSM; 5801 else { 5802 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5803 << Kind << SubType.getUnqualifiedType() << CSM; 5804 S.Diag(Selected->getLocation(), diag::note_declared_at); 5805 } 5806 } else { 5807 if (Kind != TSK_CompleteObject) 5808 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5809 << Kind << SubType.getUnqualifiedType() << CSM; 5810 5811 // Explain why the defaulted or deleted special member isn't trivial. 5812 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5813 } 5814 } 5815 5816 return false; 5817 } 5818 5819 /// Check whether the members of a class type allow a special member to be 5820 /// trivial. 5821 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5822 Sema::CXXSpecialMember CSM, 5823 bool ConstArg, bool Diagnose) { 5824 for (const auto *FI : RD->fields()) { 5825 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5826 continue; 5827 5828 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5829 5830 // Pretend anonymous struct or union members are members of this class. 5831 if (FI->isAnonymousStructOrUnion()) { 5832 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5833 CSM, ConstArg, Diagnose)) 5834 return false; 5835 continue; 5836 } 5837 5838 // C++11 [class.ctor]p5: 5839 // A default constructor is trivial if [...] 5840 // -- no non-static data member of its class has a 5841 // brace-or-equal-initializer 5842 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5843 if (Diagnose) 5844 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 5845 return false; 5846 } 5847 5848 // Objective C ARC 4.3.5: 5849 // [...] nontrivally ownership-qualified types are [...] not trivially 5850 // default constructible, copy constructible, move constructible, copy 5851 // assignable, move assignable, or destructible [...] 5852 if (S.getLangOpts().ObjCAutoRefCount && 5853 FieldType.hasNonTrivialObjCLifetime()) { 5854 if (Diagnose) 5855 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5856 << RD << FieldType.getObjCLifetime(); 5857 return false; 5858 } 5859 5860 bool ConstRHS = ConstArg && !FI->isMutable(); 5861 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 5862 CSM, TSK_Field, Diagnose)) 5863 return false; 5864 } 5865 5866 return true; 5867 } 5868 5869 /// Diagnose why the specified class does not have a trivial special member of 5870 /// the given kind. 5871 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5872 QualType Ty = Context.getRecordType(RD); 5873 5874 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 5875 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 5876 TSK_CompleteObject, /*Diagnose*/true); 5877 } 5878 5879 /// Determine whether a defaulted or deleted special member function is trivial, 5880 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5881 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5882 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5883 bool Diagnose) { 5884 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5885 5886 CXXRecordDecl *RD = MD->getParent(); 5887 5888 bool ConstArg = false; 5889 5890 // C++11 [class.copy]p12, p25: [DR1593] 5891 // A [special member] is trivial if [...] its parameter-type-list is 5892 // equivalent to the parameter-type-list of an implicit declaration [...] 5893 switch (CSM) { 5894 case CXXDefaultConstructor: 5895 case CXXDestructor: 5896 // Trivial default constructors and destructors cannot have parameters. 5897 break; 5898 5899 case CXXCopyConstructor: 5900 case CXXCopyAssignment: { 5901 // Trivial copy operations always have const, non-volatile parameter types. 5902 ConstArg = true; 5903 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5904 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5905 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5906 if (Diagnose) 5907 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5908 << Param0->getSourceRange() << Param0->getType() 5909 << Context.getLValueReferenceType( 5910 Context.getRecordType(RD).withConst()); 5911 return false; 5912 } 5913 break; 5914 } 5915 5916 case CXXMoveConstructor: 5917 case CXXMoveAssignment: { 5918 // Trivial move operations always have non-cv-qualified parameters. 5919 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5920 const RValueReferenceType *RT = 5921 Param0->getType()->getAs<RValueReferenceType>(); 5922 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5923 if (Diagnose) 5924 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5925 << Param0->getSourceRange() << Param0->getType() 5926 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5927 return false; 5928 } 5929 break; 5930 } 5931 5932 case CXXInvalid: 5933 llvm_unreachable("not a special member"); 5934 } 5935 5936 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5937 if (Diagnose) 5938 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5939 diag::note_nontrivial_default_arg) 5940 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5941 return false; 5942 } 5943 if (MD->isVariadic()) { 5944 if (Diagnose) 5945 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5946 return false; 5947 } 5948 5949 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5950 // A copy/move [constructor or assignment operator] is trivial if 5951 // -- the [member] selected to copy/move each direct base class subobject 5952 // is trivial 5953 // 5954 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5955 // A [default constructor or destructor] is trivial if 5956 // -- all the direct base classes have trivial [default constructors or 5957 // destructors] 5958 for (const auto &BI : RD->bases()) 5959 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 5960 ConstArg, CSM, TSK_BaseClass, Diagnose)) 5961 return false; 5962 5963 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5964 // A copy/move [constructor or assignment operator] for a class X is 5965 // trivial if 5966 // -- for each non-static data member of X that is of class type (or array 5967 // thereof), the constructor selected to copy/move that member is 5968 // trivial 5969 // 5970 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5971 // A [default constructor or destructor] is trivial if 5972 // -- for all of the non-static data members of its class that are of class 5973 // type (or array thereof), each such class has a trivial [default 5974 // constructor or destructor] 5975 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5976 return false; 5977 5978 // C++11 [class.dtor]p5: 5979 // A destructor is trivial if [...] 5980 // -- the destructor is not virtual 5981 if (CSM == CXXDestructor && MD->isVirtual()) { 5982 if (Diagnose) 5983 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5984 return false; 5985 } 5986 5987 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5988 // A [special member] for class X is trivial if [...] 5989 // -- class X has no virtual functions and no virtual base classes 5990 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5991 if (!Diagnose) 5992 return false; 5993 5994 if (RD->getNumVBases()) { 5995 // Check for virtual bases. We already know that the corresponding 5996 // member in all bases is trivial, so vbases must all be direct. 5997 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5998 assert(BS.isVirtual()); 5999 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 6000 return false; 6001 } 6002 6003 // Must have a virtual method. 6004 for (const auto *MI : RD->methods()) { 6005 if (MI->isVirtual()) { 6006 SourceLocation MLoc = MI->getLocStart(); 6007 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 6008 return false; 6009 } 6010 } 6011 6012 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 6013 } 6014 6015 // Looks like it's trivial! 6016 return true; 6017 } 6018 6019 /// \brief Data used with FindHiddenVirtualMethod 6020 namespace { 6021 struct FindHiddenVirtualMethodData { 6022 Sema *S; 6023 CXXMethodDecl *Method; 6024 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 6025 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6026 }; 6027 } 6028 6029 /// \brief Check whether any most overriden method from MD in Methods 6030 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 6031 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6032 if (MD->size_overridden_methods() == 0) 6033 return Methods.count(MD->getCanonicalDecl()); 6034 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6035 E = MD->end_overridden_methods(); 6036 I != E; ++I) 6037 if (CheckMostOverridenMethods(*I, Methods)) 6038 return true; 6039 return false; 6040 } 6041 6042 /// \brief Member lookup function that determines whether a given C++ 6043 /// method overloads virtual methods in a base class without overriding any, 6044 /// to be used with CXXRecordDecl::lookupInBases(). 6045 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 6046 CXXBasePath &Path, 6047 void *UserData) { 6048 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6049 6050 FindHiddenVirtualMethodData &Data 6051 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 6052 6053 DeclarationName Name = Data.Method->getDeclName(); 6054 assert(Name.getNameKind() == DeclarationName::Identifier); 6055 6056 bool foundSameNameMethod = false; 6057 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 6058 for (Path.Decls = BaseRecord->lookup(Name); 6059 !Path.Decls.empty(); 6060 Path.Decls = Path.Decls.slice(1)) { 6061 NamedDecl *D = Path.Decls.front(); 6062 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6063 MD = MD->getCanonicalDecl(); 6064 foundSameNameMethod = true; 6065 // Interested only in hidden virtual methods. 6066 if (!MD->isVirtual()) 6067 continue; 6068 // If the method we are checking overrides a method from its base 6069 // don't warn about the other overloaded methods. Clang deviates from GCC 6070 // by only diagnosing overloads of inherited virtual functions that do not 6071 // override any other virtual functions in the base. GCC's 6072 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 6073 // function from a base class. These cases may be better served by a 6074 // warning (not specific to virtual functions) on call sites when the call 6075 // would select a different function from the base class, were it visible. 6076 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 6077 if (!Data.S->IsOverload(Data.Method, MD, false)) 6078 return true; 6079 // Collect the overload only if its hidden. 6080 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 6081 overloadedMethods.push_back(MD); 6082 } 6083 } 6084 6085 if (foundSameNameMethod) 6086 Data.OverloadedMethods.append(overloadedMethods.begin(), 6087 overloadedMethods.end()); 6088 return foundSameNameMethod; 6089 } 6090 6091 /// \brief Add the most overriden methods from MD to Methods 6092 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 6093 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6094 if (MD->size_overridden_methods() == 0) 6095 Methods.insert(MD->getCanonicalDecl()); 6096 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6097 E = MD->end_overridden_methods(); 6098 I != E; ++I) 6099 AddMostOverridenMethods(*I, Methods); 6100 } 6101 6102 /// \brief Check if a method overloads virtual methods in a base class without 6103 /// overriding any. 6104 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 6105 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6106 if (!MD->getDeclName().isIdentifier()) 6107 return; 6108 6109 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 6110 /*bool RecordPaths=*/false, 6111 /*bool DetectVirtual=*/false); 6112 FindHiddenVirtualMethodData Data; 6113 Data.Method = MD; 6114 Data.S = this; 6115 6116 // Keep the base methods that were overriden or introduced in the subclass 6117 // by 'using' in a set. A base method not in this set is hidden. 6118 CXXRecordDecl *DC = MD->getParent(); 6119 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 6120 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 6121 NamedDecl *ND = *I; 6122 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 6123 ND = shad->getTargetDecl(); 6124 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6125 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 6126 } 6127 6128 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 6129 OverloadedMethods = Data.OverloadedMethods; 6130 } 6131 6132 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 6133 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6134 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 6135 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 6136 PartialDiagnostic PD = PDiag( 6137 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 6138 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 6139 Diag(overloadedMD->getLocation(), PD); 6140 } 6141 } 6142 6143 /// \brief Diagnose methods which overload virtual methods in a base class 6144 /// without overriding any. 6145 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 6146 if (MD->isInvalidDecl()) 6147 return; 6148 6149 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 6150 return; 6151 6152 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6153 FindHiddenVirtualMethods(MD, OverloadedMethods); 6154 if (!OverloadedMethods.empty()) { 6155 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 6156 << MD << (OverloadedMethods.size() > 1); 6157 6158 NoteHiddenVirtualMethods(MD, OverloadedMethods); 6159 } 6160 } 6161 6162 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 6163 Decl *TagDecl, 6164 SourceLocation LBrac, 6165 SourceLocation RBrac, 6166 AttributeList *AttrList) { 6167 if (!TagDecl) 6168 return; 6169 6170 AdjustDeclIfTemplate(TagDecl); 6171 6172 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6173 if (l->getKind() != AttributeList::AT_Visibility) 6174 continue; 6175 l->setInvalid(); 6176 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 6177 l->getName(); 6178 } 6179 6180 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 6181 // strict aliasing violation! 6182 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 6183 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 6184 6185 CheckCompletedCXXClass( 6186 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 6187 } 6188 6189 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 6190 /// special functions, such as the default constructor, copy 6191 /// constructor, or destructor, to the given C++ class (C++ 6192 /// [special]p1). This routine can only be executed just before the 6193 /// definition of the class is complete. 6194 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 6195 if (!ClassDecl->hasUserDeclaredConstructor()) 6196 ++ASTContext::NumImplicitDefaultConstructors; 6197 6198 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 6199 ++ASTContext::NumImplicitCopyConstructors; 6200 6201 // If the properties or semantics of the copy constructor couldn't be 6202 // determined while the class was being declared, force a declaration 6203 // of it now. 6204 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 6205 DeclareImplicitCopyConstructor(ClassDecl); 6206 } 6207 6208 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 6209 ++ASTContext::NumImplicitMoveConstructors; 6210 6211 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 6212 DeclareImplicitMoveConstructor(ClassDecl); 6213 } 6214 6215 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 6216 ++ASTContext::NumImplicitCopyAssignmentOperators; 6217 6218 // If we have a dynamic class, then the copy assignment operator may be 6219 // virtual, so we have to declare it immediately. This ensures that, e.g., 6220 // it shows up in the right place in the vtable and that we diagnose 6221 // problems with the implicit exception specification. 6222 if (ClassDecl->isDynamicClass() || 6223 ClassDecl->needsOverloadResolutionForCopyAssignment()) 6224 DeclareImplicitCopyAssignment(ClassDecl); 6225 } 6226 6227 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 6228 ++ASTContext::NumImplicitMoveAssignmentOperators; 6229 6230 // Likewise for the move assignment operator. 6231 if (ClassDecl->isDynamicClass() || 6232 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6233 DeclareImplicitMoveAssignment(ClassDecl); 6234 } 6235 6236 if (!ClassDecl->hasUserDeclaredDestructor()) { 6237 ++ASTContext::NumImplicitDestructors; 6238 6239 // If we have a dynamic class, then the destructor may be virtual, so we 6240 // have to declare the destructor immediately. This ensures that, e.g., it 6241 // shows up in the right place in the vtable and that we diagnose problems 6242 // with the implicit exception specification. 6243 if (ClassDecl->isDynamicClass() || 6244 ClassDecl->needsOverloadResolutionForDestructor()) 6245 DeclareImplicitDestructor(ClassDecl); 6246 } 6247 } 6248 6249 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6250 if (!D) 6251 return 0; 6252 6253 // The order of template parameters is not important here. All names 6254 // get added to the same scope. 6255 SmallVector<TemplateParameterList *, 4> ParameterLists; 6256 6257 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 6258 D = TD->getTemplatedDecl(); 6259 6260 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6261 ParameterLists.push_back(PSD->getTemplateParameters()); 6262 6263 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6264 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 6265 ParameterLists.push_back(DD->getTemplateParameterList(i)); 6266 6267 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6268 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 6269 ParameterLists.push_back(FTD->getTemplateParameters()); 6270 } 6271 } 6272 6273 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 6274 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 6275 ParameterLists.push_back(TD->getTemplateParameterList(i)); 6276 6277 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 6278 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 6279 ParameterLists.push_back(CTD->getTemplateParameters()); 6280 } 6281 } 6282 6283 unsigned Count = 0; 6284 for (TemplateParameterList *Params : ParameterLists) { 6285 if (Params->size() > 0) 6286 // Ignore explicit specializations; they don't contribute to the template 6287 // depth. 6288 ++Count; 6289 for (NamedDecl *Param : *Params) { 6290 if (Param->getDeclName()) { 6291 S->AddDecl(Param); 6292 IdResolver.AddDecl(Param); 6293 } 6294 } 6295 } 6296 6297 return Count; 6298 } 6299 6300 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6301 if (!RecordD) return; 6302 AdjustDeclIfTemplate(RecordD); 6303 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6304 PushDeclContext(S, Record); 6305 } 6306 6307 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6308 if (!RecordD) return; 6309 PopDeclContext(); 6310 } 6311 6312 /// This is used to implement the constant expression evaluation part of the 6313 /// attribute enable_if extension. There is nothing in standard C++ which would 6314 /// require reentering parameters. 6315 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6316 if (!Param) 6317 return; 6318 6319 S->AddDecl(Param); 6320 if (Param->getDeclName()) 6321 IdResolver.AddDecl(Param); 6322 } 6323 6324 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6325 /// parsing a top-level (non-nested) C++ class, and we are now 6326 /// parsing those parts of the given Method declaration that could 6327 /// not be parsed earlier (C++ [class.mem]p2), such as default 6328 /// arguments. This action should enter the scope of the given 6329 /// Method declaration as if we had just parsed the qualified method 6330 /// name. However, it should not bring the parameters into scope; 6331 /// that will be performed by ActOnDelayedCXXMethodParameter. 6332 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6333 } 6334 6335 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6336 /// C++ method declaration. We're (re-)introducing the given 6337 /// function parameter into scope for use in parsing later parts of 6338 /// the method declaration. For example, we could see an 6339 /// ActOnParamDefaultArgument event for this parameter. 6340 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6341 if (!ParamD) 6342 return; 6343 6344 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6345 6346 // If this parameter has an unparsed default argument, clear it out 6347 // to make way for the parsed default argument. 6348 if (Param->hasUnparsedDefaultArg()) 6349 Param->setDefaultArg(nullptr); 6350 6351 S->AddDecl(Param); 6352 if (Param->getDeclName()) 6353 IdResolver.AddDecl(Param); 6354 } 6355 6356 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6357 /// processing the delayed method declaration for Method. The method 6358 /// declaration is now considered finished. There may be a separate 6359 /// ActOnStartOfFunctionDef action later (not necessarily 6360 /// immediately!) for this method, if it was also defined inside the 6361 /// class body. 6362 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6363 if (!MethodD) 6364 return; 6365 6366 AdjustDeclIfTemplate(MethodD); 6367 6368 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6369 6370 // Now that we have our default arguments, check the constructor 6371 // again. It could produce additional diagnostics or affect whether 6372 // the class has implicitly-declared destructors, among other 6373 // things. 6374 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6375 CheckConstructor(Constructor); 6376 6377 // Check the default arguments, which we may have added. 6378 if (!Method->isInvalidDecl()) 6379 CheckCXXDefaultArguments(Method); 6380 } 6381 6382 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6383 /// the well-formedness of the constructor declarator @p D with type @p 6384 /// R. If there are any errors in the declarator, this routine will 6385 /// emit diagnostics and set the invalid bit to true. In any case, the type 6386 /// will be updated to reflect a well-formed type for the constructor and 6387 /// returned. 6388 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6389 StorageClass &SC) { 6390 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6391 6392 // C++ [class.ctor]p3: 6393 // A constructor shall not be virtual (10.3) or static (9.4). A 6394 // constructor can be invoked for a const, volatile or const 6395 // volatile object. A constructor shall not be declared const, 6396 // volatile, or const volatile (9.3.2). 6397 if (isVirtual) { 6398 if (!D.isInvalidType()) 6399 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6400 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6401 << SourceRange(D.getIdentifierLoc()); 6402 D.setInvalidType(); 6403 } 6404 if (SC == SC_Static) { 6405 if (!D.isInvalidType()) 6406 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6407 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6408 << SourceRange(D.getIdentifierLoc()); 6409 D.setInvalidType(); 6410 SC = SC_None; 6411 } 6412 6413 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6414 diagnoseIgnoredQualifiers( 6415 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 6416 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 6417 D.getDeclSpec().getRestrictSpecLoc(), 6418 D.getDeclSpec().getAtomicSpecLoc()); 6419 D.setInvalidType(); 6420 } 6421 6422 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6423 if (FTI.TypeQuals != 0) { 6424 if (FTI.TypeQuals & Qualifiers::Const) 6425 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6426 << "const" << SourceRange(D.getIdentifierLoc()); 6427 if (FTI.TypeQuals & Qualifiers::Volatile) 6428 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6429 << "volatile" << SourceRange(D.getIdentifierLoc()); 6430 if (FTI.TypeQuals & Qualifiers::Restrict) 6431 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6432 << "restrict" << SourceRange(D.getIdentifierLoc()); 6433 D.setInvalidType(); 6434 } 6435 6436 // C++0x [class.ctor]p4: 6437 // A constructor shall not be declared with a ref-qualifier. 6438 if (FTI.hasRefQualifier()) { 6439 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6440 << FTI.RefQualifierIsLValueRef 6441 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6442 D.setInvalidType(); 6443 } 6444 6445 // Rebuild the function type "R" without any type qualifiers (in 6446 // case any of the errors above fired) and with "void" as the 6447 // return type, since constructors don't have return types. 6448 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6449 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6450 return R; 6451 6452 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6453 EPI.TypeQuals = 0; 6454 EPI.RefQualifier = RQ_None; 6455 6456 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6457 } 6458 6459 /// CheckConstructor - Checks a fully-formed constructor for 6460 /// well-formedness, issuing any diagnostics required. Returns true if 6461 /// the constructor declarator is invalid. 6462 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6463 CXXRecordDecl *ClassDecl 6464 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6465 if (!ClassDecl) 6466 return Constructor->setInvalidDecl(); 6467 6468 // C++ [class.copy]p3: 6469 // A declaration of a constructor for a class X is ill-formed if 6470 // its first parameter is of type (optionally cv-qualified) X and 6471 // either there are no other parameters or else all other 6472 // parameters have default arguments. 6473 if (!Constructor->isInvalidDecl() && 6474 ((Constructor->getNumParams() == 1) || 6475 (Constructor->getNumParams() > 1 && 6476 Constructor->getParamDecl(1)->hasDefaultArg())) && 6477 Constructor->getTemplateSpecializationKind() 6478 != TSK_ImplicitInstantiation) { 6479 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6480 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6481 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6482 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6483 const char *ConstRef 6484 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6485 : " const &"; 6486 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6487 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6488 6489 // FIXME: Rather that making the constructor invalid, we should endeavor 6490 // to fix the type. 6491 Constructor->setInvalidDecl(); 6492 } 6493 } 6494 } 6495 6496 /// CheckDestructor - Checks a fully-formed destructor definition for 6497 /// well-formedness, issuing any diagnostics required. Returns true 6498 /// on error. 6499 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6500 CXXRecordDecl *RD = Destructor->getParent(); 6501 6502 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6503 SourceLocation Loc; 6504 6505 if (!Destructor->isImplicit()) 6506 Loc = Destructor->getLocation(); 6507 else 6508 Loc = RD->getLocation(); 6509 6510 // If we have a virtual destructor, look up the deallocation function 6511 FunctionDecl *OperatorDelete = nullptr; 6512 DeclarationName Name = 6513 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6514 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6515 return true; 6516 // If there's no class-specific operator delete, look up the global 6517 // non-array delete. 6518 if (!OperatorDelete) 6519 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6520 6521 MarkFunctionReferenced(Loc, OperatorDelete); 6522 6523 Destructor->setOperatorDelete(OperatorDelete); 6524 } 6525 6526 return false; 6527 } 6528 6529 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6530 /// the well-formednes of the destructor declarator @p D with type @p 6531 /// R. If there are any errors in the declarator, this routine will 6532 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6533 /// will be updated to reflect a well-formed type for the destructor and 6534 /// returned. 6535 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6536 StorageClass& SC) { 6537 // C++ [class.dtor]p1: 6538 // [...] A typedef-name that names a class is a class-name 6539 // (7.1.3); however, a typedef-name that names a class shall not 6540 // be used as the identifier in the declarator for a destructor 6541 // declaration. 6542 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6543 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6544 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6545 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6546 else if (const TemplateSpecializationType *TST = 6547 DeclaratorType->getAs<TemplateSpecializationType>()) 6548 if (TST->isTypeAlias()) 6549 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6550 << DeclaratorType << 1; 6551 6552 // C++ [class.dtor]p2: 6553 // A destructor is used to destroy objects of its class type. A 6554 // destructor takes no parameters, and no return type can be 6555 // specified for it (not even void). The address of a destructor 6556 // shall not be taken. A destructor shall not be static. A 6557 // destructor can be invoked for a const, volatile or const 6558 // volatile object. A destructor shall not be declared const, 6559 // volatile or const volatile (9.3.2). 6560 if (SC == SC_Static) { 6561 if (!D.isInvalidType()) 6562 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6563 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6564 << SourceRange(D.getIdentifierLoc()) 6565 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6566 6567 SC = SC_None; 6568 } 6569 if (!D.isInvalidType()) { 6570 // Destructors don't have return types, but the parser will 6571 // happily parse something like: 6572 // 6573 // class X { 6574 // float ~X(); 6575 // }; 6576 // 6577 // The return type will be eliminated later. 6578 if (D.getDeclSpec().hasTypeSpecifier()) 6579 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6580 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6581 << SourceRange(D.getIdentifierLoc()); 6582 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6583 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 6584 SourceLocation(), 6585 D.getDeclSpec().getConstSpecLoc(), 6586 D.getDeclSpec().getVolatileSpecLoc(), 6587 D.getDeclSpec().getRestrictSpecLoc(), 6588 D.getDeclSpec().getAtomicSpecLoc()); 6589 D.setInvalidType(); 6590 } 6591 } 6592 6593 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6594 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6595 if (FTI.TypeQuals & Qualifiers::Const) 6596 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6597 << "const" << SourceRange(D.getIdentifierLoc()); 6598 if (FTI.TypeQuals & Qualifiers::Volatile) 6599 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6600 << "volatile" << SourceRange(D.getIdentifierLoc()); 6601 if (FTI.TypeQuals & Qualifiers::Restrict) 6602 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6603 << "restrict" << SourceRange(D.getIdentifierLoc()); 6604 D.setInvalidType(); 6605 } 6606 6607 // C++0x [class.dtor]p2: 6608 // A destructor shall not be declared with a ref-qualifier. 6609 if (FTI.hasRefQualifier()) { 6610 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6611 << FTI.RefQualifierIsLValueRef 6612 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6613 D.setInvalidType(); 6614 } 6615 6616 // Make sure we don't have any parameters. 6617 if (FTIHasNonVoidParameters(FTI)) { 6618 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6619 6620 // Delete the parameters. 6621 FTI.freeParams(); 6622 D.setInvalidType(); 6623 } 6624 6625 // Make sure the destructor isn't variadic. 6626 if (FTI.isVariadic) { 6627 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6628 D.setInvalidType(); 6629 } 6630 6631 // Rebuild the function type "R" without any type qualifiers or 6632 // parameters (in case any of the errors above fired) and with 6633 // "void" as the return type, since destructors don't have return 6634 // types. 6635 if (!D.isInvalidType()) 6636 return R; 6637 6638 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6639 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6640 EPI.Variadic = false; 6641 EPI.TypeQuals = 0; 6642 EPI.RefQualifier = RQ_None; 6643 return Context.getFunctionType(Context.VoidTy, None, EPI); 6644 } 6645 6646 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6647 /// well-formednes of the conversion function declarator @p D with 6648 /// type @p R. If there are any errors in the declarator, this routine 6649 /// will emit diagnostics and return true. Otherwise, it will return 6650 /// false. Either way, the type @p R will be updated to reflect a 6651 /// well-formed type for the conversion operator. 6652 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6653 StorageClass& SC) { 6654 // C++ [class.conv.fct]p1: 6655 // Neither parameter types nor return type can be specified. The 6656 // type of a conversion function (8.3.5) is "function taking no 6657 // parameter returning conversion-type-id." 6658 if (SC == SC_Static) { 6659 if (!D.isInvalidType()) 6660 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6661 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6662 << D.getName().getSourceRange(); 6663 D.setInvalidType(); 6664 SC = SC_None; 6665 } 6666 6667 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6668 6669 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6670 // Conversion functions don't have return types, but the parser will 6671 // happily parse something like: 6672 // 6673 // class X { 6674 // float operator bool(); 6675 // }; 6676 // 6677 // The return type will be changed later anyway. 6678 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6679 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6680 << SourceRange(D.getIdentifierLoc()); 6681 D.setInvalidType(); 6682 } 6683 6684 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6685 6686 // Make sure we don't have any parameters. 6687 if (Proto->getNumParams() > 0) { 6688 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6689 6690 // Delete the parameters. 6691 D.getFunctionTypeInfo().freeParams(); 6692 D.setInvalidType(); 6693 } else if (Proto->isVariadic()) { 6694 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6695 D.setInvalidType(); 6696 } 6697 6698 // Diagnose "&operator bool()" and other such nonsense. This 6699 // is actually a gcc extension which we don't support. 6700 if (Proto->getReturnType() != ConvType) { 6701 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6702 << Proto->getReturnType(); 6703 D.setInvalidType(); 6704 ConvType = Proto->getReturnType(); 6705 } 6706 6707 // C++ [class.conv.fct]p4: 6708 // The conversion-type-id shall not represent a function type nor 6709 // an array type. 6710 if (ConvType->isArrayType()) { 6711 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6712 ConvType = Context.getPointerType(ConvType); 6713 D.setInvalidType(); 6714 } else if (ConvType->isFunctionType()) { 6715 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6716 ConvType = Context.getPointerType(ConvType); 6717 D.setInvalidType(); 6718 } 6719 6720 // Rebuild the function type "R" without any parameters (in case any 6721 // of the errors above fired) and with the conversion type as the 6722 // return type. 6723 if (D.isInvalidType()) 6724 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6725 6726 // C++0x explicit conversion operators. 6727 if (D.getDeclSpec().isExplicitSpecified()) 6728 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6729 getLangOpts().CPlusPlus11 ? 6730 diag::warn_cxx98_compat_explicit_conversion_functions : 6731 diag::ext_explicit_conversion_functions) 6732 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6733 } 6734 6735 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6736 /// the declaration of the given C++ conversion function. This routine 6737 /// is responsible for recording the conversion function in the C++ 6738 /// class, if possible. 6739 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6740 assert(Conversion && "Expected to receive a conversion function declaration"); 6741 6742 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6743 6744 // Make sure we aren't redeclaring the conversion function. 6745 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6746 6747 // C++ [class.conv.fct]p1: 6748 // [...] A conversion function is never used to convert a 6749 // (possibly cv-qualified) object to the (possibly cv-qualified) 6750 // same object type (or a reference to it), to a (possibly 6751 // cv-qualified) base class of that type (or a reference to it), 6752 // or to (possibly cv-qualified) void. 6753 // FIXME: Suppress this warning if the conversion function ends up being a 6754 // virtual function that overrides a virtual function in a base class. 6755 QualType ClassType 6756 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6757 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6758 ConvType = ConvTypeRef->getPointeeType(); 6759 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6760 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6761 /* Suppress diagnostics for instantiations. */; 6762 else if (ConvType->isRecordType()) { 6763 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6764 if (ConvType == ClassType) 6765 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6766 << ClassType; 6767 else if (IsDerivedFrom(ClassType, ConvType)) 6768 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6769 << ClassType << ConvType; 6770 } else if (ConvType->isVoidType()) { 6771 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6772 << ClassType << ConvType; 6773 } 6774 6775 if (FunctionTemplateDecl *ConversionTemplate 6776 = Conversion->getDescribedFunctionTemplate()) 6777 return ConversionTemplate; 6778 6779 return Conversion; 6780 } 6781 6782 //===----------------------------------------------------------------------===// 6783 // Namespace Handling 6784 //===----------------------------------------------------------------------===// 6785 6786 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6787 /// reopened. 6788 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6789 SourceLocation Loc, 6790 IdentifierInfo *II, bool *IsInline, 6791 NamespaceDecl *PrevNS) { 6792 assert(*IsInline != PrevNS->isInline()); 6793 6794 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6795 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6796 // inline namespaces, with the intention of bringing names into namespace std. 6797 // 6798 // We support this just well enough to get that case working; this is not 6799 // sufficient to support reopening namespaces as inline in general. 6800 if (*IsInline && II && II->getName().startswith("__atomic") && 6801 S.getSourceManager().isInSystemHeader(Loc)) { 6802 // Mark all prior declarations of the namespace as inline. 6803 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6804 NS = NS->getPreviousDecl()) 6805 NS->setInline(*IsInline); 6806 // Patch up the lookup table for the containing namespace. This isn't really 6807 // correct, but it's good enough for this particular case. 6808 for (auto *I : PrevNS->decls()) 6809 if (auto *ND = dyn_cast<NamedDecl>(I)) 6810 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6811 return; 6812 } 6813 6814 if (PrevNS->isInline()) 6815 // The user probably just forgot the 'inline', so suggest that it 6816 // be added back. 6817 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6818 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6819 else 6820 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 6821 6822 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6823 *IsInline = PrevNS->isInline(); 6824 } 6825 6826 /// ActOnStartNamespaceDef - This is called at the start of a namespace 6827 /// definition. 6828 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6829 SourceLocation InlineLoc, 6830 SourceLocation NamespaceLoc, 6831 SourceLocation IdentLoc, 6832 IdentifierInfo *II, 6833 SourceLocation LBrace, 6834 AttributeList *AttrList) { 6835 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6836 // For anonymous namespace, take the location of the left brace. 6837 SourceLocation Loc = II ? IdentLoc : LBrace; 6838 bool IsInline = InlineLoc.isValid(); 6839 bool IsInvalid = false; 6840 bool IsStd = false; 6841 bool AddToKnown = false; 6842 Scope *DeclRegionScope = NamespcScope->getParent(); 6843 6844 NamespaceDecl *PrevNS = nullptr; 6845 if (II) { 6846 // C++ [namespace.def]p2: 6847 // The identifier in an original-namespace-definition shall not 6848 // have been previously defined in the declarative region in 6849 // which the original-namespace-definition appears. The 6850 // identifier in an original-namespace-definition is the name of 6851 // the namespace. Subsequently in that declarative region, it is 6852 // treated as an original-namespace-name. 6853 // 6854 // Since namespace names are unique in their scope, and we don't 6855 // look through using directives, just look for any ordinary names. 6856 6857 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6858 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6859 Decl::IDNS_Namespace; 6860 NamedDecl *PrevDecl = nullptr; 6861 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6862 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6863 ++I) { 6864 if ((*I)->getIdentifierNamespace() & IDNS) { 6865 PrevDecl = *I; 6866 break; 6867 } 6868 } 6869 6870 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6871 6872 if (PrevNS) { 6873 // This is an extended namespace definition. 6874 if (IsInline != PrevNS->isInline()) 6875 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6876 &IsInline, PrevNS); 6877 } else if (PrevDecl) { 6878 // This is an invalid name redefinition. 6879 Diag(Loc, diag::err_redefinition_different_kind) 6880 << II; 6881 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6882 IsInvalid = true; 6883 // Continue on to push Namespc as current DeclContext and return it. 6884 } else if (II->isStr("std") && 6885 CurContext->getRedeclContext()->isTranslationUnit()) { 6886 // This is the first "real" definition of the namespace "std", so update 6887 // our cache of the "std" namespace to point at this definition. 6888 PrevNS = getStdNamespace(); 6889 IsStd = true; 6890 AddToKnown = !IsInline; 6891 } else { 6892 // We've seen this namespace for the first time. 6893 AddToKnown = !IsInline; 6894 } 6895 } else { 6896 // Anonymous namespaces. 6897 6898 // Determine whether the parent already has an anonymous namespace. 6899 DeclContext *Parent = CurContext->getRedeclContext(); 6900 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6901 PrevNS = TU->getAnonymousNamespace(); 6902 } else { 6903 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6904 PrevNS = ND->getAnonymousNamespace(); 6905 } 6906 6907 if (PrevNS && IsInline != PrevNS->isInline()) 6908 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6909 &IsInline, PrevNS); 6910 } 6911 6912 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6913 StartLoc, Loc, II, PrevNS); 6914 if (IsInvalid) 6915 Namespc->setInvalidDecl(); 6916 6917 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6918 6919 // FIXME: Should we be merging attributes? 6920 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6921 PushNamespaceVisibilityAttr(Attr, Loc); 6922 6923 if (IsStd) 6924 StdNamespace = Namespc; 6925 if (AddToKnown) 6926 KnownNamespaces[Namespc] = false; 6927 6928 if (II) { 6929 PushOnScopeChains(Namespc, DeclRegionScope); 6930 } else { 6931 // Link the anonymous namespace into its parent. 6932 DeclContext *Parent = CurContext->getRedeclContext(); 6933 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6934 TU->setAnonymousNamespace(Namespc); 6935 } else { 6936 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6937 } 6938 6939 CurContext->addDecl(Namespc); 6940 6941 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6942 // behaves as if it were replaced by 6943 // namespace unique { /* empty body */ } 6944 // using namespace unique; 6945 // namespace unique { namespace-body } 6946 // where all occurrences of 'unique' in a translation unit are 6947 // replaced by the same identifier and this identifier differs 6948 // from all other identifiers in the entire program. 6949 6950 // We just create the namespace with an empty name and then add an 6951 // implicit using declaration, just like the standard suggests. 6952 // 6953 // CodeGen enforces the "universally unique" aspect by giving all 6954 // declarations semantically contained within an anonymous 6955 // namespace internal linkage. 6956 6957 if (!PrevNS) { 6958 UsingDirectiveDecl* UD 6959 = UsingDirectiveDecl::Create(Context, Parent, 6960 /* 'using' */ LBrace, 6961 /* 'namespace' */ SourceLocation(), 6962 /* qualifier */ NestedNameSpecifierLoc(), 6963 /* identifier */ SourceLocation(), 6964 Namespc, 6965 /* Ancestor */ Parent); 6966 UD->setImplicit(); 6967 Parent->addDecl(UD); 6968 } 6969 } 6970 6971 ActOnDocumentableDecl(Namespc); 6972 6973 // Although we could have an invalid decl (i.e. the namespace name is a 6974 // redefinition), push it as current DeclContext and try to continue parsing. 6975 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6976 // for the namespace has the declarations that showed up in that particular 6977 // namespace definition. 6978 PushDeclContext(NamespcScope, Namespc); 6979 return Namespc; 6980 } 6981 6982 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6983 /// is a namespace alias, returns the namespace it points to. 6984 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6985 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6986 return AD->getNamespace(); 6987 return dyn_cast_or_null<NamespaceDecl>(D); 6988 } 6989 6990 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 6991 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6992 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6993 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6994 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6995 Namespc->setRBraceLoc(RBrace); 6996 PopDeclContext(); 6997 if (Namespc->hasAttr<VisibilityAttr>()) 6998 PopPragmaVisibility(true, RBrace); 6999 } 7000 7001 CXXRecordDecl *Sema::getStdBadAlloc() const { 7002 return cast_or_null<CXXRecordDecl>( 7003 StdBadAlloc.get(Context.getExternalSource())); 7004 } 7005 7006 NamespaceDecl *Sema::getStdNamespace() const { 7007 return cast_or_null<NamespaceDecl>( 7008 StdNamespace.get(Context.getExternalSource())); 7009 } 7010 7011 /// \brief Retrieve the special "std" namespace, which may require us to 7012 /// implicitly define the namespace. 7013 NamespaceDecl *Sema::getOrCreateStdNamespace() { 7014 if (!StdNamespace) { 7015 // The "std" namespace has not yet been defined, so build one implicitly. 7016 StdNamespace = NamespaceDecl::Create(Context, 7017 Context.getTranslationUnitDecl(), 7018 /*Inline=*/false, 7019 SourceLocation(), SourceLocation(), 7020 &PP.getIdentifierTable().get("std"), 7021 /*PrevDecl=*/nullptr); 7022 getStdNamespace()->setImplicit(true); 7023 } 7024 7025 return getStdNamespace(); 7026 } 7027 7028 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 7029 assert(getLangOpts().CPlusPlus && 7030 "Looking for std::initializer_list outside of C++."); 7031 7032 // We're looking for implicit instantiations of 7033 // template <typename E> class std::initializer_list. 7034 7035 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 7036 return false; 7037 7038 ClassTemplateDecl *Template = nullptr; 7039 const TemplateArgument *Arguments = nullptr; 7040 7041 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7042 7043 ClassTemplateSpecializationDecl *Specialization = 7044 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 7045 if (!Specialization) 7046 return false; 7047 7048 Template = Specialization->getSpecializedTemplate(); 7049 Arguments = Specialization->getTemplateArgs().data(); 7050 } else if (const TemplateSpecializationType *TST = 7051 Ty->getAs<TemplateSpecializationType>()) { 7052 Template = dyn_cast_or_null<ClassTemplateDecl>( 7053 TST->getTemplateName().getAsTemplateDecl()); 7054 Arguments = TST->getArgs(); 7055 } 7056 if (!Template) 7057 return false; 7058 7059 if (!StdInitializerList) { 7060 // Haven't recognized std::initializer_list yet, maybe this is it. 7061 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 7062 if (TemplateClass->getIdentifier() != 7063 &PP.getIdentifierTable().get("initializer_list") || 7064 !getStdNamespace()->InEnclosingNamespaceSetOf( 7065 TemplateClass->getDeclContext())) 7066 return false; 7067 // This is a template called std::initializer_list, but is it the right 7068 // template? 7069 TemplateParameterList *Params = Template->getTemplateParameters(); 7070 if (Params->getMinRequiredArguments() != 1) 7071 return false; 7072 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 7073 return false; 7074 7075 // It's the right template. 7076 StdInitializerList = Template; 7077 } 7078 7079 if (Template != StdInitializerList) 7080 return false; 7081 7082 // This is an instance of std::initializer_list. Find the argument type. 7083 if (Element) 7084 *Element = Arguments[0].getAsType(); 7085 return true; 7086 } 7087 7088 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 7089 NamespaceDecl *Std = S.getStdNamespace(); 7090 if (!Std) { 7091 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7092 return nullptr; 7093 } 7094 7095 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 7096 Loc, Sema::LookupOrdinaryName); 7097 if (!S.LookupQualifiedName(Result, Std)) { 7098 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7099 return nullptr; 7100 } 7101 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 7102 if (!Template) { 7103 Result.suppressDiagnostics(); 7104 // We found something weird. Complain about the first thing we found. 7105 NamedDecl *Found = *Result.begin(); 7106 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 7107 return nullptr; 7108 } 7109 7110 // We found some template called std::initializer_list. Now verify that it's 7111 // correct. 7112 TemplateParameterList *Params = Template->getTemplateParameters(); 7113 if (Params->getMinRequiredArguments() != 1 || 7114 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 7115 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 7116 return nullptr; 7117 } 7118 7119 return Template; 7120 } 7121 7122 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 7123 if (!StdInitializerList) { 7124 StdInitializerList = LookupStdInitializerList(*this, Loc); 7125 if (!StdInitializerList) 7126 return QualType(); 7127 } 7128 7129 TemplateArgumentListInfo Args(Loc, Loc); 7130 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 7131 Context.getTrivialTypeSourceInfo(Element, 7132 Loc))); 7133 return Context.getCanonicalType( 7134 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 7135 } 7136 7137 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 7138 // C++ [dcl.init.list]p2: 7139 // A constructor is an initializer-list constructor if its first parameter 7140 // is of type std::initializer_list<E> or reference to possibly cv-qualified 7141 // std::initializer_list<E> for some type E, and either there are no other 7142 // parameters or else all other parameters have default arguments. 7143 if (Ctor->getNumParams() < 1 || 7144 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 7145 return false; 7146 7147 QualType ArgType = Ctor->getParamDecl(0)->getType(); 7148 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 7149 ArgType = RT->getPointeeType().getUnqualifiedType(); 7150 7151 return isStdInitializerList(ArgType, nullptr); 7152 } 7153 7154 /// \brief Determine whether a using statement is in a context where it will be 7155 /// apply in all contexts. 7156 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 7157 switch (CurContext->getDeclKind()) { 7158 case Decl::TranslationUnit: 7159 return true; 7160 case Decl::LinkageSpec: 7161 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 7162 default: 7163 return false; 7164 } 7165 } 7166 7167 namespace { 7168 7169 // Callback to only accept typo corrections that are namespaces. 7170 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 7171 public: 7172 bool ValidateCandidate(const TypoCorrection &candidate) override { 7173 if (NamedDecl *ND = candidate.getCorrectionDecl()) 7174 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 7175 return false; 7176 } 7177 }; 7178 7179 } 7180 7181 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 7182 CXXScopeSpec &SS, 7183 SourceLocation IdentLoc, 7184 IdentifierInfo *Ident) { 7185 NamespaceValidatorCCC Validator; 7186 R.clear(); 7187 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 7188 R.getLookupKind(), Sc, &SS, 7189 Validator, 7190 Sema::CTK_ErrorRecovery)) { 7191 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 7192 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 7193 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 7194 Ident->getName().equals(CorrectedStr); 7195 S.diagnoseTypo(Corrected, 7196 S.PDiag(diag::err_using_directive_member_suggest) 7197 << Ident << DC << DroppedSpecifier << SS.getRange(), 7198 S.PDiag(diag::note_namespace_defined_here)); 7199 } else { 7200 S.diagnoseTypo(Corrected, 7201 S.PDiag(diag::err_using_directive_suggest) << Ident, 7202 S.PDiag(diag::note_namespace_defined_here)); 7203 } 7204 R.addDecl(Corrected.getCorrectionDecl()); 7205 return true; 7206 } 7207 return false; 7208 } 7209 7210 Decl *Sema::ActOnUsingDirective(Scope *S, 7211 SourceLocation UsingLoc, 7212 SourceLocation NamespcLoc, 7213 CXXScopeSpec &SS, 7214 SourceLocation IdentLoc, 7215 IdentifierInfo *NamespcName, 7216 AttributeList *AttrList) { 7217 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7218 assert(NamespcName && "Invalid NamespcName."); 7219 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7220 7221 // This can only happen along a recovery path. 7222 while (S->getFlags() & Scope::TemplateParamScope) 7223 S = S->getParent(); 7224 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7225 7226 UsingDirectiveDecl *UDir = nullptr; 7227 NestedNameSpecifier *Qualifier = nullptr; 7228 if (SS.isSet()) 7229 Qualifier = SS.getScopeRep(); 7230 7231 // Lookup namespace name. 7232 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7233 LookupParsedName(R, S, &SS); 7234 if (R.isAmbiguous()) 7235 return nullptr; 7236 7237 if (R.empty()) { 7238 R.clear(); 7239 // Allow "using namespace std;" or "using namespace ::std;" even if 7240 // "std" hasn't been defined yet, for GCC compatibility. 7241 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7242 NamespcName->isStr("std")) { 7243 Diag(IdentLoc, diag::ext_using_undefined_std); 7244 R.addDecl(getOrCreateStdNamespace()); 7245 R.resolveKind(); 7246 } 7247 // Otherwise, attempt typo correction. 7248 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7249 } 7250 7251 if (!R.empty()) { 7252 NamedDecl *Named = R.getFoundDecl(); 7253 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7254 && "expected namespace decl"); 7255 // C++ [namespace.udir]p1: 7256 // A using-directive specifies that the names in the nominated 7257 // namespace can be used in the scope in which the 7258 // using-directive appears after the using-directive. During 7259 // unqualified name lookup (3.4.1), the names appear as if they 7260 // were declared in the nearest enclosing namespace which 7261 // contains both the using-directive and the nominated 7262 // namespace. [Note: in this context, "contains" means "contains 7263 // directly or indirectly". ] 7264 7265 // Find enclosing context containing both using-directive and 7266 // nominated namespace. 7267 NamespaceDecl *NS = getNamespaceDecl(Named); 7268 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7269 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7270 CommonAncestor = CommonAncestor->getParent(); 7271 7272 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7273 SS.getWithLocInContext(Context), 7274 IdentLoc, Named, CommonAncestor); 7275 7276 if (IsUsingDirectiveInToplevelContext(CurContext) && 7277 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7278 Diag(IdentLoc, diag::warn_using_directive_in_header); 7279 } 7280 7281 PushUsingDirective(S, UDir); 7282 } else { 7283 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7284 } 7285 7286 if (UDir) 7287 ProcessDeclAttributeList(S, UDir, AttrList); 7288 7289 return UDir; 7290 } 7291 7292 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7293 // If the scope has an associated entity and the using directive is at 7294 // namespace or translation unit scope, add the UsingDirectiveDecl into 7295 // its lookup structure so qualified name lookup can find it. 7296 DeclContext *Ctx = S->getEntity(); 7297 if (Ctx && !Ctx->isFunctionOrMethod()) 7298 Ctx->addDecl(UDir); 7299 else 7300 // Otherwise, it is at block scope. The using-directives will affect lookup 7301 // only to the end of the scope. 7302 S->PushUsingDirective(UDir); 7303 } 7304 7305 7306 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7307 AccessSpecifier AS, 7308 bool HasUsingKeyword, 7309 SourceLocation UsingLoc, 7310 CXXScopeSpec &SS, 7311 UnqualifiedId &Name, 7312 AttributeList *AttrList, 7313 bool HasTypenameKeyword, 7314 SourceLocation TypenameLoc) { 7315 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7316 7317 switch (Name.getKind()) { 7318 case UnqualifiedId::IK_ImplicitSelfParam: 7319 case UnqualifiedId::IK_Identifier: 7320 case UnqualifiedId::IK_OperatorFunctionId: 7321 case UnqualifiedId::IK_LiteralOperatorId: 7322 case UnqualifiedId::IK_ConversionFunctionId: 7323 break; 7324 7325 case UnqualifiedId::IK_ConstructorName: 7326 case UnqualifiedId::IK_ConstructorTemplateId: 7327 // C++11 inheriting constructors. 7328 Diag(Name.getLocStart(), 7329 getLangOpts().CPlusPlus11 ? 7330 diag::warn_cxx98_compat_using_decl_constructor : 7331 diag::err_using_decl_constructor) 7332 << SS.getRange(); 7333 7334 if (getLangOpts().CPlusPlus11) break; 7335 7336 return nullptr; 7337 7338 case UnqualifiedId::IK_DestructorName: 7339 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7340 << SS.getRange(); 7341 return nullptr; 7342 7343 case UnqualifiedId::IK_TemplateId: 7344 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7345 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7346 return nullptr; 7347 } 7348 7349 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7350 DeclarationName TargetName = TargetNameInfo.getName(); 7351 if (!TargetName) 7352 return nullptr; 7353 7354 // Warn about access declarations. 7355 if (!HasUsingKeyword) { 7356 Diag(Name.getLocStart(), 7357 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7358 : diag::warn_access_decl_deprecated) 7359 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7360 } 7361 7362 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7363 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7364 return nullptr; 7365 7366 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7367 TargetNameInfo, AttrList, 7368 /* IsInstantiation */ false, 7369 HasTypenameKeyword, TypenameLoc); 7370 if (UD) 7371 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7372 7373 return UD; 7374 } 7375 7376 /// \brief Determine whether a using declaration considers the given 7377 /// declarations as "equivalent", e.g., if they are redeclarations of 7378 /// the same entity or are both typedefs of the same type. 7379 static bool 7380 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7381 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7382 return true; 7383 7384 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7385 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7386 return Context.hasSameType(TD1->getUnderlyingType(), 7387 TD2->getUnderlyingType()); 7388 7389 return false; 7390 } 7391 7392 7393 /// Determines whether to create a using shadow decl for a particular 7394 /// decl, given the set of decls existing prior to this using lookup. 7395 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7396 const LookupResult &Previous, 7397 UsingShadowDecl *&PrevShadow) { 7398 // Diagnose finding a decl which is not from a base class of the 7399 // current class. We do this now because there are cases where this 7400 // function will silently decide not to build a shadow decl, which 7401 // will pre-empt further diagnostics. 7402 // 7403 // We don't need to do this in C++0x because we do the check once on 7404 // the qualifier. 7405 // 7406 // FIXME: diagnose the following if we care enough: 7407 // struct A { int foo; }; 7408 // struct B : A { using A::foo; }; 7409 // template <class T> struct C : A {}; 7410 // template <class T> struct D : C<T> { using B::foo; } // <--- 7411 // This is invalid (during instantiation) in C++03 because B::foo 7412 // resolves to the using decl in B, which is not a base class of D<T>. 7413 // We can't diagnose it immediately because C<T> is an unknown 7414 // specialization. The UsingShadowDecl in D<T> then points directly 7415 // to A::foo, which will look well-formed when we instantiate. 7416 // The right solution is to not collapse the shadow-decl chain. 7417 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7418 DeclContext *OrigDC = Orig->getDeclContext(); 7419 7420 // Handle enums and anonymous structs. 7421 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7422 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7423 while (OrigRec->isAnonymousStructOrUnion()) 7424 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7425 7426 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7427 if (OrigDC == CurContext) { 7428 Diag(Using->getLocation(), 7429 diag::err_using_decl_nested_name_specifier_is_current_class) 7430 << Using->getQualifierLoc().getSourceRange(); 7431 Diag(Orig->getLocation(), diag::note_using_decl_target); 7432 return true; 7433 } 7434 7435 Diag(Using->getQualifierLoc().getBeginLoc(), 7436 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7437 << Using->getQualifier() 7438 << cast<CXXRecordDecl>(CurContext) 7439 << Using->getQualifierLoc().getSourceRange(); 7440 Diag(Orig->getLocation(), diag::note_using_decl_target); 7441 return true; 7442 } 7443 } 7444 7445 if (Previous.empty()) return false; 7446 7447 NamedDecl *Target = Orig; 7448 if (isa<UsingShadowDecl>(Target)) 7449 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7450 7451 // If the target happens to be one of the previous declarations, we 7452 // don't have a conflict. 7453 // 7454 // FIXME: but we might be increasing its access, in which case we 7455 // should redeclare it. 7456 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7457 bool FoundEquivalentDecl = false; 7458 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7459 I != E; ++I) { 7460 NamedDecl *D = (*I)->getUnderlyingDecl(); 7461 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7462 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7463 PrevShadow = Shadow; 7464 FoundEquivalentDecl = true; 7465 } 7466 7467 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7468 } 7469 7470 if (FoundEquivalentDecl) 7471 return false; 7472 7473 if (FunctionDecl *FD = Target->getAsFunction()) { 7474 NamedDecl *OldDecl = nullptr; 7475 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7476 /*IsForUsingDecl*/ true)) { 7477 case Ovl_Overload: 7478 return false; 7479 7480 case Ovl_NonFunction: 7481 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7482 break; 7483 7484 // We found a decl with the exact signature. 7485 case Ovl_Match: 7486 // If we're in a record, we want to hide the target, so we 7487 // return true (without a diagnostic) to tell the caller not to 7488 // build a shadow decl. 7489 if (CurContext->isRecord()) 7490 return true; 7491 7492 // If we're not in a record, this is an error. 7493 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7494 break; 7495 } 7496 7497 Diag(Target->getLocation(), diag::note_using_decl_target); 7498 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7499 return true; 7500 } 7501 7502 // Target is not a function. 7503 7504 if (isa<TagDecl>(Target)) { 7505 // No conflict between a tag and a non-tag. 7506 if (!Tag) return false; 7507 7508 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7509 Diag(Target->getLocation(), diag::note_using_decl_target); 7510 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7511 return true; 7512 } 7513 7514 // No conflict between a tag and a non-tag. 7515 if (!NonTag) return false; 7516 7517 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7518 Diag(Target->getLocation(), diag::note_using_decl_target); 7519 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7520 return true; 7521 } 7522 7523 /// Builds a shadow declaration corresponding to a 'using' declaration. 7524 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7525 UsingDecl *UD, 7526 NamedDecl *Orig, 7527 UsingShadowDecl *PrevDecl) { 7528 7529 // If we resolved to another shadow declaration, just coalesce them. 7530 NamedDecl *Target = Orig; 7531 if (isa<UsingShadowDecl>(Target)) { 7532 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7533 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7534 } 7535 7536 UsingShadowDecl *Shadow 7537 = UsingShadowDecl::Create(Context, CurContext, 7538 UD->getLocation(), UD, Target); 7539 UD->addShadowDecl(Shadow); 7540 7541 Shadow->setAccess(UD->getAccess()); 7542 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7543 Shadow->setInvalidDecl(); 7544 7545 Shadow->setPreviousDecl(PrevDecl); 7546 7547 if (S) 7548 PushOnScopeChains(Shadow, S); 7549 else 7550 CurContext->addDecl(Shadow); 7551 7552 7553 return Shadow; 7554 } 7555 7556 /// Hides a using shadow declaration. This is required by the current 7557 /// using-decl implementation when a resolvable using declaration in a 7558 /// class is followed by a declaration which would hide or override 7559 /// one or more of the using decl's targets; for example: 7560 /// 7561 /// struct Base { void foo(int); }; 7562 /// struct Derived : Base { 7563 /// using Base::foo; 7564 /// void foo(int); 7565 /// }; 7566 /// 7567 /// The governing language is C++03 [namespace.udecl]p12: 7568 /// 7569 /// When a using-declaration brings names from a base class into a 7570 /// derived class scope, member functions in the derived class 7571 /// override and/or hide member functions with the same name and 7572 /// parameter types in a base class (rather than conflicting). 7573 /// 7574 /// There are two ways to implement this: 7575 /// (1) optimistically create shadow decls when they're not hidden 7576 /// by existing declarations, or 7577 /// (2) don't create any shadow decls (or at least don't make them 7578 /// visible) until we've fully parsed/instantiated the class. 7579 /// The problem with (1) is that we might have to retroactively remove 7580 /// a shadow decl, which requires several O(n) operations because the 7581 /// decl structures are (very reasonably) not designed for removal. 7582 /// (2) avoids this but is very fiddly and phase-dependent. 7583 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7584 if (Shadow->getDeclName().getNameKind() == 7585 DeclarationName::CXXConversionFunctionName) 7586 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7587 7588 // Remove it from the DeclContext... 7589 Shadow->getDeclContext()->removeDecl(Shadow); 7590 7591 // ...and the scope, if applicable... 7592 if (S) { 7593 S->RemoveDecl(Shadow); 7594 IdResolver.RemoveDecl(Shadow); 7595 } 7596 7597 // ...and the using decl. 7598 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7599 7600 // TODO: complain somehow if Shadow was used. It shouldn't 7601 // be possible for this to happen, because...? 7602 } 7603 7604 /// Find the base specifier for a base class with the given type. 7605 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7606 QualType DesiredBase, 7607 bool &AnyDependentBases) { 7608 // Check whether the named type is a direct base class. 7609 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7610 for (auto &Base : Derived->bases()) { 7611 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7612 if (CanonicalDesiredBase == BaseType) 7613 return &Base; 7614 if (BaseType->isDependentType()) 7615 AnyDependentBases = true; 7616 } 7617 return nullptr; 7618 } 7619 7620 namespace { 7621 class UsingValidatorCCC : public CorrectionCandidateCallback { 7622 public: 7623 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7624 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7625 : HasTypenameKeyword(HasTypenameKeyword), 7626 IsInstantiation(IsInstantiation), OldNNS(NNS), 7627 RequireMemberOf(RequireMemberOf) {} 7628 7629 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7630 NamedDecl *ND = Candidate.getCorrectionDecl(); 7631 7632 // Keywords are not valid here. 7633 if (!ND || isa<NamespaceDecl>(ND)) 7634 return false; 7635 7636 // Completely unqualified names are invalid for a 'using' declaration. 7637 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7638 return false; 7639 7640 if (RequireMemberOf) { 7641 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 7642 if (FoundRecord && FoundRecord->isInjectedClassName()) { 7643 // No-one ever wants a using-declaration to name an injected-class-name 7644 // of a base class, unless they're declaring an inheriting constructor. 7645 ASTContext &Ctx = ND->getASTContext(); 7646 if (!Ctx.getLangOpts().CPlusPlus11) 7647 return false; 7648 QualType FoundType = Ctx.getRecordType(FoundRecord); 7649 7650 // Check that the injected-class-name is named as a member of its own 7651 // type; we don't want to suggest 'using Derived::Base;', since that 7652 // means something else. 7653 NestedNameSpecifier *Specifier = 7654 Candidate.WillReplaceSpecifier() 7655 ? Candidate.getCorrectionSpecifier() 7656 : OldNNS; 7657 if (!Specifier->getAsType() || 7658 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 7659 return false; 7660 7661 // Check that this inheriting constructor declaration actually names a 7662 // direct base class of the current class. 7663 bool AnyDependentBases = false; 7664 if (!findDirectBaseWithType(RequireMemberOf, 7665 Ctx.getRecordType(FoundRecord), 7666 AnyDependentBases) && 7667 !AnyDependentBases) 7668 return false; 7669 } else { 7670 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 7671 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 7672 return false; 7673 7674 // FIXME: Check that the base class member is accessible? 7675 } 7676 } 7677 7678 if (isa<TypeDecl>(ND)) 7679 return HasTypenameKeyword || !IsInstantiation; 7680 7681 return !HasTypenameKeyword; 7682 } 7683 7684 private: 7685 bool HasTypenameKeyword; 7686 bool IsInstantiation; 7687 NestedNameSpecifier *OldNNS; 7688 CXXRecordDecl *RequireMemberOf; 7689 }; 7690 } // end anonymous namespace 7691 7692 /// Builds a using declaration. 7693 /// 7694 /// \param IsInstantiation - Whether this call arises from an 7695 /// instantiation of an unresolved using declaration. We treat 7696 /// the lookup differently for these declarations. 7697 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7698 SourceLocation UsingLoc, 7699 CXXScopeSpec &SS, 7700 DeclarationNameInfo NameInfo, 7701 AttributeList *AttrList, 7702 bool IsInstantiation, 7703 bool HasTypenameKeyword, 7704 SourceLocation TypenameLoc) { 7705 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7706 SourceLocation IdentLoc = NameInfo.getLoc(); 7707 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7708 7709 // FIXME: We ignore attributes for now. 7710 7711 if (SS.isEmpty()) { 7712 Diag(IdentLoc, diag::err_using_requires_qualname); 7713 return nullptr; 7714 } 7715 7716 // Do the redeclaration lookup in the current scope. 7717 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7718 ForRedeclaration); 7719 Previous.setHideTags(false); 7720 if (S) { 7721 LookupName(Previous, S); 7722 7723 // It is really dumb that we have to do this. 7724 LookupResult::Filter F = Previous.makeFilter(); 7725 while (F.hasNext()) { 7726 NamedDecl *D = F.next(); 7727 if (!isDeclInScope(D, CurContext, S)) 7728 F.erase(); 7729 // If we found a local extern declaration that's not ordinarily visible, 7730 // and this declaration is being added to a non-block scope, ignore it. 7731 // We're only checking for scope conflicts here, not also for violations 7732 // of the linkage rules. 7733 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 7734 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 7735 F.erase(); 7736 } 7737 F.done(); 7738 } else { 7739 assert(IsInstantiation && "no scope in non-instantiation"); 7740 assert(CurContext->isRecord() && "scope not record in instantiation"); 7741 LookupQualifiedName(Previous, CurContext); 7742 } 7743 7744 // Check for invalid redeclarations. 7745 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7746 SS, IdentLoc, Previous)) 7747 return nullptr; 7748 7749 // Check for bad qualifiers. 7750 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 7751 return nullptr; 7752 7753 DeclContext *LookupContext = computeDeclContext(SS); 7754 NamedDecl *D; 7755 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7756 if (!LookupContext) { 7757 if (HasTypenameKeyword) { 7758 // FIXME: not all declaration name kinds are legal here 7759 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7760 UsingLoc, TypenameLoc, 7761 QualifierLoc, 7762 IdentLoc, NameInfo.getName()); 7763 } else { 7764 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7765 QualifierLoc, NameInfo); 7766 } 7767 D->setAccess(AS); 7768 CurContext->addDecl(D); 7769 return D; 7770 } 7771 7772 auto Build = [&](bool Invalid) { 7773 UsingDecl *UD = 7774 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 7775 HasTypenameKeyword); 7776 UD->setAccess(AS); 7777 CurContext->addDecl(UD); 7778 UD->setInvalidDecl(Invalid); 7779 return UD; 7780 }; 7781 auto BuildInvalid = [&]{ return Build(true); }; 7782 auto BuildValid = [&]{ return Build(false); }; 7783 7784 if (RequireCompleteDeclContext(SS, LookupContext)) 7785 return BuildInvalid(); 7786 7787 // The normal rules do not apply to inheriting constructor declarations. 7788 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7789 UsingDecl *UD = BuildValid(); 7790 CheckInheritingConstructorUsingDecl(UD); 7791 return UD; 7792 } 7793 7794 // Otherwise, look up the target name. 7795 7796 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7797 7798 // Unlike most lookups, we don't always want to hide tag 7799 // declarations: tag names are visible through the using declaration 7800 // even if hidden by ordinary names, *except* in a dependent context 7801 // where it's important for the sanity of two-phase lookup. 7802 if (!IsInstantiation) 7803 R.setHideTags(false); 7804 7805 // For the purposes of this lookup, we have a base object type 7806 // equal to that of the current context. 7807 if (CurContext->isRecord()) { 7808 R.setBaseObjectType( 7809 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7810 } 7811 7812 LookupQualifiedName(R, LookupContext); 7813 7814 // Try to correct typos if possible. 7815 if (R.empty()) { 7816 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 7817 dyn_cast<CXXRecordDecl>(CurContext)); 7818 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(), 7819 R.getLookupKind(), S, &SS, CCC, 7820 CTK_ErrorRecovery)){ 7821 // We reject any correction for which ND would be NULL. 7822 NamedDecl *ND = Corrected.getCorrectionDecl(); 7823 7824 // We reject candidates where DroppedSpecifier == true, hence the 7825 // literal '0' below. 7826 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 7827 << NameInfo.getName() << LookupContext << 0 7828 << SS.getRange()); 7829 7830 // If we corrected to an inheriting constructor, handle it as one. 7831 auto *RD = dyn_cast<CXXRecordDecl>(ND); 7832 if (RD && RD->isInjectedClassName()) { 7833 // Fix up the information we'll use to build the using declaration. 7834 if (Corrected.WillReplaceSpecifier()) { 7835 NestedNameSpecifierLocBuilder Builder; 7836 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 7837 QualifierLoc.getSourceRange()); 7838 QualifierLoc = Builder.getWithLocInContext(Context); 7839 } 7840 7841 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 7842 Context.getCanonicalType(Context.getRecordType(RD)))); 7843 NameInfo.setNamedTypeInfo(nullptr); 7844 7845 // Build it and process it as an inheriting constructor. 7846 UsingDecl *UD = BuildValid(); 7847 CheckInheritingConstructorUsingDecl(UD); 7848 return UD; 7849 } 7850 7851 // FIXME: Pick up all the declarations if we found an overloaded function. 7852 R.setLookupName(Corrected.getCorrection()); 7853 R.addDecl(ND); 7854 } else { 7855 Diag(IdentLoc, diag::err_no_member) 7856 << NameInfo.getName() << LookupContext << SS.getRange(); 7857 return BuildInvalid(); 7858 } 7859 } 7860 7861 if (R.isAmbiguous()) 7862 return BuildInvalid(); 7863 7864 if (HasTypenameKeyword) { 7865 // If we asked for a typename and got a non-type decl, error out. 7866 if (!R.getAsSingle<TypeDecl>()) { 7867 Diag(IdentLoc, diag::err_using_typename_non_type); 7868 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7869 Diag((*I)->getUnderlyingDecl()->getLocation(), 7870 diag::note_using_decl_target); 7871 return BuildInvalid(); 7872 } 7873 } else { 7874 // If we asked for a non-typename and we got a type, error out, 7875 // but only if this is an instantiation of an unresolved using 7876 // decl. Otherwise just silently find the type name. 7877 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7878 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7879 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7880 return BuildInvalid(); 7881 } 7882 } 7883 7884 // C++0x N2914 [namespace.udecl]p6: 7885 // A using-declaration shall not name a namespace. 7886 if (R.getAsSingle<NamespaceDecl>()) { 7887 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7888 << SS.getRange(); 7889 return BuildInvalid(); 7890 } 7891 7892 UsingDecl *UD = BuildValid(); 7893 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7894 UsingShadowDecl *PrevDecl = nullptr; 7895 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 7896 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 7897 } 7898 7899 return UD; 7900 } 7901 7902 /// Additional checks for a using declaration referring to a constructor name. 7903 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7904 assert(!UD->hasTypename() && "expecting a constructor name"); 7905 7906 const Type *SourceType = UD->getQualifier()->getAsType(); 7907 assert(SourceType && 7908 "Using decl naming constructor doesn't have type in scope spec."); 7909 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7910 7911 // Check whether the named type is a direct base class. 7912 bool AnyDependentBases = false; 7913 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 7914 AnyDependentBases); 7915 if (!Base && !AnyDependentBases) { 7916 Diag(UD->getUsingLoc(), 7917 diag::err_using_decl_constructor_not_in_direct_base) 7918 << UD->getNameInfo().getSourceRange() 7919 << QualType(SourceType, 0) << TargetClass; 7920 UD->setInvalidDecl(); 7921 return true; 7922 } 7923 7924 if (Base) 7925 Base->setInheritConstructors(); 7926 7927 return false; 7928 } 7929 7930 /// Checks that the given using declaration is not an invalid 7931 /// redeclaration. Note that this is checking only for the using decl 7932 /// itself, not for any ill-formedness among the UsingShadowDecls. 7933 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7934 bool HasTypenameKeyword, 7935 const CXXScopeSpec &SS, 7936 SourceLocation NameLoc, 7937 const LookupResult &Prev) { 7938 // C++03 [namespace.udecl]p8: 7939 // C++0x [namespace.udecl]p10: 7940 // A using-declaration is a declaration and can therefore be used 7941 // repeatedly where (and only where) multiple declarations are 7942 // allowed. 7943 // 7944 // That's in non-member contexts. 7945 if (!CurContext->getRedeclContext()->isRecord()) 7946 return false; 7947 7948 NestedNameSpecifier *Qual = SS.getScopeRep(); 7949 7950 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7951 NamedDecl *D = *I; 7952 7953 bool DTypename; 7954 NestedNameSpecifier *DQual; 7955 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7956 DTypename = UD->hasTypename(); 7957 DQual = UD->getQualifier(); 7958 } else if (UnresolvedUsingValueDecl *UD 7959 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7960 DTypename = false; 7961 DQual = UD->getQualifier(); 7962 } else if (UnresolvedUsingTypenameDecl *UD 7963 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7964 DTypename = true; 7965 DQual = UD->getQualifier(); 7966 } else continue; 7967 7968 // using decls differ if one says 'typename' and the other doesn't. 7969 // FIXME: non-dependent using decls? 7970 if (HasTypenameKeyword != DTypename) continue; 7971 7972 // using decls differ if they name different scopes (but note that 7973 // template instantiation can cause this check to trigger when it 7974 // didn't before instantiation). 7975 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7976 Context.getCanonicalNestedNameSpecifier(DQual)) 7977 continue; 7978 7979 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7980 Diag(D->getLocation(), diag::note_using_decl) << 1; 7981 return true; 7982 } 7983 7984 return false; 7985 } 7986 7987 7988 /// Checks that the given nested-name qualifier used in a using decl 7989 /// in the current context is appropriately related to the current 7990 /// scope. If an error is found, diagnoses it and returns true. 7991 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7992 const CXXScopeSpec &SS, 7993 const DeclarationNameInfo &NameInfo, 7994 SourceLocation NameLoc) { 7995 DeclContext *NamedContext = computeDeclContext(SS); 7996 7997 if (!CurContext->isRecord()) { 7998 // C++03 [namespace.udecl]p3: 7999 // C++0x [namespace.udecl]p8: 8000 // A using-declaration for a class member shall be a member-declaration. 8001 8002 // If we weren't able to compute a valid scope, it must be a 8003 // dependent class scope. 8004 if (!NamedContext || NamedContext->isRecord()) { 8005 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext); 8006 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 8007 RD = nullptr; 8008 8009 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 8010 << SS.getRange(); 8011 8012 // If we have a complete, non-dependent source type, try to suggest a 8013 // way to get the same effect. 8014 if (!RD) 8015 return true; 8016 8017 // Find what this using-declaration was referring to. 8018 LookupResult R(*this, NameInfo, LookupOrdinaryName); 8019 R.setHideTags(false); 8020 R.suppressDiagnostics(); 8021 LookupQualifiedName(R, RD); 8022 8023 if (R.getAsSingle<TypeDecl>()) { 8024 if (getLangOpts().CPlusPlus11) { 8025 // Convert 'using X::Y;' to 'using Y = X::Y;'. 8026 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 8027 << 0 // alias declaration 8028 << FixItHint::CreateInsertion(SS.getBeginLoc(), 8029 NameInfo.getName().getAsString() + 8030 " = "); 8031 } else { 8032 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 8033 SourceLocation InsertLoc = 8034 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 8035 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 8036 << 1 // typedef declaration 8037 << FixItHint::CreateReplacement(UsingLoc, "typedef") 8038 << FixItHint::CreateInsertion( 8039 InsertLoc, " " + NameInfo.getName().getAsString()); 8040 } 8041 } else if (R.getAsSingle<VarDecl>()) { 8042 // Don't provide a fixit outside C++11 mode; we don't want to suggest 8043 // repeating the type of the static data member here. 8044 FixItHint FixIt; 8045 if (getLangOpts().CPlusPlus11) { 8046 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 8047 FixIt = FixItHint::CreateReplacement( 8048 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 8049 } 8050 8051 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 8052 << 2 // reference declaration 8053 << FixIt; 8054 } 8055 return true; 8056 } 8057 8058 // Otherwise, everything is known to be fine. 8059 return false; 8060 } 8061 8062 // The current scope is a record. 8063 8064 // If the named context is dependent, we can't decide much. 8065 if (!NamedContext) { 8066 // FIXME: in C++0x, we can diagnose if we can prove that the 8067 // nested-name-specifier does not refer to a base class, which is 8068 // still possible in some cases. 8069 8070 // Otherwise we have to conservatively report that things might be 8071 // okay. 8072 return false; 8073 } 8074 8075 if (!NamedContext->isRecord()) { 8076 // Ideally this would point at the last name in the specifier, 8077 // but we don't have that level of source info. 8078 Diag(SS.getRange().getBegin(), 8079 diag::err_using_decl_nested_name_specifier_is_not_class) 8080 << SS.getScopeRep() << SS.getRange(); 8081 return true; 8082 } 8083 8084 if (!NamedContext->isDependentContext() && 8085 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 8086 return true; 8087 8088 if (getLangOpts().CPlusPlus11) { 8089 // C++0x [namespace.udecl]p3: 8090 // In a using-declaration used as a member-declaration, the 8091 // nested-name-specifier shall name a base class of the class 8092 // being defined. 8093 8094 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 8095 cast<CXXRecordDecl>(NamedContext))) { 8096 if (CurContext == NamedContext) { 8097 Diag(NameLoc, 8098 diag::err_using_decl_nested_name_specifier_is_current_class) 8099 << SS.getRange(); 8100 return true; 8101 } 8102 8103 Diag(SS.getRange().getBegin(), 8104 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8105 << SS.getScopeRep() 8106 << cast<CXXRecordDecl>(CurContext) 8107 << SS.getRange(); 8108 return true; 8109 } 8110 8111 return false; 8112 } 8113 8114 // C++03 [namespace.udecl]p4: 8115 // A using-declaration used as a member-declaration shall refer 8116 // to a member of a base class of the class being defined [etc.]. 8117 8118 // Salient point: SS doesn't have to name a base class as long as 8119 // lookup only finds members from base classes. Therefore we can 8120 // diagnose here only if we can prove that that can't happen, 8121 // i.e. if the class hierarchies provably don't intersect. 8122 8123 // TODO: it would be nice if "definitely valid" results were cached 8124 // in the UsingDecl and UsingShadowDecl so that these checks didn't 8125 // need to be repeated. 8126 8127 struct UserData { 8128 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 8129 8130 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 8131 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8132 Data->Bases.insert(Base); 8133 return true; 8134 } 8135 8136 bool hasDependentBases(const CXXRecordDecl *Class) { 8137 return !Class->forallBases(collect, this); 8138 } 8139 8140 /// Returns true if the base is dependent or is one of the 8141 /// accumulated base classes. 8142 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 8143 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8144 return !Data->Bases.count(Base); 8145 } 8146 8147 bool mightShareBases(const CXXRecordDecl *Class) { 8148 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 8149 } 8150 }; 8151 8152 UserData Data; 8153 8154 // Returns false if we find a dependent base. 8155 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 8156 return false; 8157 8158 // Returns false if the class has a dependent base or if it or one 8159 // of its bases is present in the base set of the current context. 8160 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 8161 return false; 8162 8163 Diag(SS.getRange().getBegin(), 8164 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8165 << SS.getScopeRep() 8166 << cast<CXXRecordDecl>(CurContext) 8167 << SS.getRange(); 8168 8169 return true; 8170 } 8171 8172 Decl *Sema::ActOnAliasDeclaration(Scope *S, 8173 AccessSpecifier AS, 8174 MultiTemplateParamsArg TemplateParamLists, 8175 SourceLocation UsingLoc, 8176 UnqualifiedId &Name, 8177 AttributeList *AttrList, 8178 TypeResult Type) { 8179 // Skip up to the relevant declaration scope. 8180 while (S->getFlags() & Scope::TemplateParamScope) 8181 S = S->getParent(); 8182 assert((S->getFlags() & Scope::DeclScope) && 8183 "got alias-declaration outside of declaration scope"); 8184 8185 if (Type.isInvalid()) 8186 return nullptr; 8187 8188 bool Invalid = false; 8189 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 8190 TypeSourceInfo *TInfo = nullptr; 8191 GetTypeFromParser(Type.get(), &TInfo); 8192 8193 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 8194 return nullptr; 8195 8196 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 8197 UPPC_DeclarationType)) { 8198 Invalid = true; 8199 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8200 TInfo->getTypeLoc().getBeginLoc()); 8201 } 8202 8203 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 8204 LookupName(Previous, S); 8205 8206 // Warn about shadowing the name of a template parameter. 8207 if (Previous.isSingleResult() && 8208 Previous.getFoundDecl()->isTemplateParameter()) { 8209 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8210 Previous.clear(); 8211 } 8212 8213 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8214 "name in alias declaration must be an identifier"); 8215 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8216 Name.StartLocation, 8217 Name.Identifier, TInfo); 8218 8219 NewTD->setAccess(AS); 8220 8221 if (Invalid) 8222 NewTD->setInvalidDecl(); 8223 8224 ProcessDeclAttributeList(S, NewTD, AttrList); 8225 8226 CheckTypedefForVariablyModifiedType(S, NewTD); 8227 Invalid |= NewTD->isInvalidDecl(); 8228 8229 bool Redeclaration = false; 8230 8231 NamedDecl *NewND; 8232 if (TemplateParamLists.size()) { 8233 TypeAliasTemplateDecl *OldDecl = nullptr; 8234 TemplateParameterList *OldTemplateParams = nullptr; 8235 8236 if (TemplateParamLists.size() != 1) { 8237 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8238 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8239 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8240 } 8241 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8242 8243 // Only consider previous declarations in the same scope. 8244 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8245 /*ExplicitInstantiationOrSpecialization*/false); 8246 if (!Previous.empty()) { 8247 Redeclaration = true; 8248 8249 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8250 if (!OldDecl && !Invalid) { 8251 Diag(UsingLoc, diag::err_redefinition_different_kind) 8252 << Name.Identifier; 8253 8254 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8255 if (OldD->getLocation().isValid()) 8256 Diag(OldD->getLocation(), diag::note_previous_definition); 8257 8258 Invalid = true; 8259 } 8260 8261 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8262 if (TemplateParameterListsAreEqual(TemplateParams, 8263 OldDecl->getTemplateParameters(), 8264 /*Complain=*/true, 8265 TPL_TemplateMatch)) 8266 OldTemplateParams = OldDecl->getTemplateParameters(); 8267 else 8268 Invalid = true; 8269 8270 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8271 if (!Invalid && 8272 !Context.hasSameType(OldTD->getUnderlyingType(), 8273 NewTD->getUnderlyingType())) { 8274 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8275 // but we can't reasonably accept it. 8276 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8277 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8278 if (OldTD->getLocation().isValid()) 8279 Diag(OldTD->getLocation(), diag::note_previous_definition); 8280 Invalid = true; 8281 } 8282 } 8283 } 8284 8285 // Merge any previous default template arguments into our parameters, 8286 // and check the parameter list. 8287 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8288 TPC_TypeAliasTemplate)) 8289 return nullptr; 8290 8291 TypeAliasTemplateDecl *NewDecl = 8292 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8293 Name.Identifier, TemplateParams, 8294 NewTD); 8295 NewTD->setDescribedAliasTemplate(NewDecl); 8296 8297 NewDecl->setAccess(AS); 8298 8299 if (Invalid) 8300 NewDecl->setInvalidDecl(); 8301 else if (OldDecl) 8302 NewDecl->setPreviousDecl(OldDecl); 8303 8304 NewND = NewDecl; 8305 } else { 8306 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8307 NewND = NewTD; 8308 } 8309 8310 if (!Redeclaration) 8311 PushOnScopeChains(NewND, S); 8312 8313 ActOnDocumentableDecl(NewND); 8314 return NewND; 8315 } 8316 8317 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 8318 SourceLocation AliasLoc, 8319 IdentifierInfo *Alias, CXXScopeSpec &SS, 8320 SourceLocation IdentLoc, 8321 IdentifierInfo *Ident) { 8322 8323 // Lookup the namespace name. 8324 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8325 LookupParsedName(R, S, &SS); 8326 8327 if (R.isAmbiguous()) 8328 return nullptr; 8329 8330 if (R.empty()) { 8331 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8332 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8333 return nullptr; 8334 } 8335 } 8336 assert(!R.isAmbiguous() && !R.empty()); 8337 8338 // Check if we have a previous declaration with the same name. 8339 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 8340 ForRedeclaration); 8341 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 8342 PrevDecl = nullptr; 8343 8344 if (PrevDecl) { 8345 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 8346 // We already have an alias with the same name that points to the same 8347 // namespace; check that it matches. 8348 if (!AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) { 8349 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 8350 << Alias; 8351 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias) 8352 << AD->getNamespace(); 8353 return nullptr; 8354 } 8355 } else { 8356 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) 8357 ? diag::err_redefinition 8358 : diag::err_redefinition_different_kind; 8359 Diag(AliasLoc, DiagID) << Alias; 8360 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8361 return nullptr; 8362 } 8363 } 8364 8365 NamespaceAliasDecl *AliasDecl = 8366 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8367 Alias, SS.getWithLocInContext(Context), 8368 IdentLoc, R.getFoundDecl()); 8369 if (PrevDecl) 8370 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl)); 8371 8372 PushOnScopeChains(AliasDecl, S); 8373 return AliasDecl; 8374 } 8375 8376 Sema::ImplicitExceptionSpecification 8377 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8378 CXXMethodDecl *MD) { 8379 CXXRecordDecl *ClassDecl = MD->getParent(); 8380 8381 // C++ [except.spec]p14: 8382 // An implicitly declared special member function (Clause 12) shall have an 8383 // exception-specification. [...] 8384 ImplicitExceptionSpecification ExceptSpec(*this); 8385 if (ClassDecl->isInvalidDecl()) 8386 return ExceptSpec; 8387 8388 // Direct base-class constructors. 8389 for (const auto &B : ClassDecl->bases()) { 8390 if (B.isVirtual()) // Handled below. 8391 continue; 8392 8393 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8394 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8395 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8396 // If this is a deleted function, add it anyway. This might be conformant 8397 // with the standard. This might not. I'm not sure. It might not matter. 8398 if (Constructor) 8399 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8400 } 8401 } 8402 8403 // Virtual base-class constructors. 8404 for (const auto &B : ClassDecl->vbases()) { 8405 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8406 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8407 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8408 // If this is a deleted function, add it anyway. This might be conformant 8409 // with the standard. This might not. I'm not sure. It might not matter. 8410 if (Constructor) 8411 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8412 } 8413 } 8414 8415 // Field constructors. 8416 for (const auto *F : ClassDecl->fields()) { 8417 if (F->hasInClassInitializer()) { 8418 if (Expr *E = F->getInClassInitializer()) 8419 ExceptSpec.CalledExpr(E); 8420 else if (!F->isInvalidDecl()) 8421 // DR1351: 8422 // If the brace-or-equal-initializer of a non-static data member 8423 // invokes a defaulted default constructor of its class or of an 8424 // enclosing class in a potentially evaluated subexpression, the 8425 // program is ill-formed. 8426 // 8427 // This resolution is unworkable: the exception specification of the 8428 // default constructor can be needed in an unevaluated context, in 8429 // particular, in the operand of a noexcept-expression, and we can be 8430 // unable to compute an exception specification for an enclosed class. 8431 // 8432 // We do not allow an in-class initializer to require the evaluation 8433 // of the exception specification for any in-class initializer whose 8434 // definition is not lexically complete. 8435 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 8436 } else if (const RecordType *RecordTy 8437 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8438 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8439 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8440 // If this is a deleted function, add it anyway. This might be conformant 8441 // with the standard. This might not. I'm not sure. It might not matter. 8442 // In particular, the problem is that this function never gets called. It 8443 // might just be ill-formed because this function attempts to refer to 8444 // a deleted function here. 8445 if (Constructor) 8446 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8447 } 8448 } 8449 8450 return ExceptSpec; 8451 } 8452 8453 Sema::ImplicitExceptionSpecification 8454 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8455 CXXRecordDecl *ClassDecl = CD->getParent(); 8456 8457 // C++ [except.spec]p14: 8458 // An inheriting constructor [...] shall have an exception-specification. [...] 8459 ImplicitExceptionSpecification ExceptSpec(*this); 8460 if (ClassDecl->isInvalidDecl()) 8461 return ExceptSpec; 8462 8463 // Inherited constructor. 8464 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8465 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8466 // FIXME: Copying or moving the parameters could add extra exceptions to the 8467 // set, as could the default arguments for the inherited constructor. This 8468 // will be addressed when we implement the resolution of core issue 1351. 8469 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8470 8471 // Direct base-class constructors. 8472 for (const auto &B : ClassDecl->bases()) { 8473 if (B.isVirtual()) // Handled below. 8474 continue; 8475 8476 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8477 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8478 if (BaseClassDecl == InheritedDecl) 8479 continue; 8480 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8481 if (Constructor) 8482 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8483 } 8484 } 8485 8486 // Virtual base-class constructors. 8487 for (const auto &B : ClassDecl->vbases()) { 8488 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8489 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8490 if (BaseClassDecl == InheritedDecl) 8491 continue; 8492 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8493 if (Constructor) 8494 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8495 } 8496 } 8497 8498 // Field constructors. 8499 for (const auto *F : ClassDecl->fields()) { 8500 if (F->hasInClassInitializer()) { 8501 if (Expr *E = F->getInClassInitializer()) 8502 ExceptSpec.CalledExpr(E); 8503 else if (!F->isInvalidDecl()) 8504 Diag(CD->getLocation(), 8505 diag::err_in_class_initializer_references_def_ctor) << CD; 8506 } else if (const RecordType *RecordTy 8507 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8508 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8509 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8510 if (Constructor) 8511 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8512 } 8513 } 8514 8515 return ExceptSpec; 8516 } 8517 8518 namespace { 8519 /// RAII object to register a special member as being currently declared. 8520 struct DeclaringSpecialMember { 8521 Sema &S; 8522 Sema::SpecialMemberDecl D; 8523 bool WasAlreadyBeingDeclared; 8524 8525 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8526 : S(S), D(RD, CSM) { 8527 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 8528 if (WasAlreadyBeingDeclared) 8529 // This almost never happens, but if it does, ensure that our cache 8530 // doesn't contain a stale result. 8531 S.SpecialMemberCache.clear(); 8532 8533 // FIXME: Register a note to be produced if we encounter an error while 8534 // declaring the special member. 8535 } 8536 ~DeclaringSpecialMember() { 8537 if (!WasAlreadyBeingDeclared) 8538 S.SpecialMembersBeingDeclared.erase(D); 8539 } 8540 8541 /// \brief Are we already trying to declare this special member? 8542 bool isAlreadyBeingDeclared() const { 8543 return WasAlreadyBeingDeclared; 8544 } 8545 }; 8546 } 8547 8548 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8549 CXXRecordDecl *ClassDecl) { 8550 // C++ [class.ctor]p5: 8551 // A default constructor for a class X is a constructor of class X 8552 // that can be called without an argument. If there is no 8553 // user-declared constructor for class X, a default constructor is 8554 // implicitly declared. An implicitly-declared default constructor 8555 // is an inline public member of its class. 8556 assert(ClassDecl->needsImplicitDefaultConstructor() && 8557 "Should not build implicit default constructor!"); 8558 8559 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8560 if (DSM.isAlreadyBeingDeclared()) 8561 return nullptr; 8562 8563 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8564 CXXDefaultConstructor, 8565 false); 8566 8567 // Create the actual constructor declaration. 8568 CanQualType ClassType 8569 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8570 SourceLocation ClassLoc = ClassDecl->getLocation(); 8571 DeclarationName Name 8572 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8573 DeclarationNameInfo NameInfo(Name, ClassLoc); 8574 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8575 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8576 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8577 /*isImplicitlyDeclared=*/true, Constexpr); 8578 DefaultCon->setAccess(AS_public); 8579 DefaultCon->setDefaulted(); 8580 8581 if (getLangOpts().CUDA) { 8582 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 8583 DefaultCon, 8584 /* ConstRHS */ false, 8585 /* Diagnose */ false); 8586 } 8587 8588 // Build an exception specification pointing back at this constructor. 8589 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8590 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8591 8592 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8593 // constructors is easy to compute. 8594 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8595 8596 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8597 SetDeclDeleted(DefaultCon, ClassLoc); 8598 8599 // Note that we have declared this constructor. 8600 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8601 8602 if (Scope *S = getScopeForContext(ClassDecl)) 8603 PushOnScopeChains(DefaultCon, S, false); 8604 ClassDecl->addDecl(DefaultCon); 8605 8606 return DefaultCon; 8607 } 8608 8609 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8610 CXXConstructorDecl *Constructor) { 8611 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8612 !Constructor->doesThisDeclarationHaveABody() && 8613 !Constructor->isDeleted()) && 8614 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8615 8616 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8617 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8618 8619 SynthesizedFunctionScope Scope(*this, Constructor); 8620 DiagnosticErrorTrap Trap(Diags); 8621 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8622 Trap.hasErrorOccurred()) { 8623 Diag(CurrentLocation, diag::note_member_synthesized_at) 8624 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8625 Constructor->setInvalidDecl(); 8626 return; 8627 } 8628 8629 // The exception specification is needed because we are defining the 8630 // function. 8631 ResolveExceptionSpec(CurrentLocation, 8632 Constructor->getType()->castAs<FunctionProtoType>()); 8633 8634 SourceLocation Loc = Constructor->getLocEnd().isValid() 8635 ? Constructor->getLocEnd() 8636 : Constructor->getLocation(); 8637 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8638 8639 Constructor->markUsed(Context); 8640 MarkVTableUsed(CurrentLocation, ClassDecl); 8641 8642 if (ASTMutationListener *L = getASTMutationListener()) { 8643 L->CompletedImplicitDefinition(Constructor); 8644 } 8645 8646 DiagnoseUninitializedFields(*this, Constructor); 8647 } 8648 8649 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8650 // Perform any delayed checks on exception specifications. 8651 CheckDelayedMemberExceptionSpecs(); 8652 } 8653 8654 namespace { 8655 /// Information on inheriting constructors to declare. 8656 class InheritingConstructorInfo { 8657 public: 8658 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8659 : SemaRef(SemaRef), Derived(Derived) { 8660 // Mark the constructors that we already have in the derived class. 8661 // 8662 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8663 // unless there is a user-declared constructor with the same signature in 8664 // the class where the using-declaration appears. 8665 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8666 } 8667 8668 void inheritAll(CXXRecordDecl *RD) { 8669 visitAll(RD, &InheritingConstructorInfo::inherit); 8670 } 8671 8672 private: 8673 /// Information about an inheriting constructor. 8674 struct InheritingConstructor { 8675 InheritingConstructor() 8676 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 8677 8678 /// If \c true, a constructor with this signature is already declared 8679 /// in the derived class. 8680 bool DeclaredInDerived; 8681 8682 /// The constructor which is inherited. 8683 const CXXConstructorDecl *BaseCtor; 8684 8685 /// The derived constructor we declared. 8686 CXXConstructorDecl *DerivedCtor; 8687 }; 8688 8689 /// Inheriting constructors with a given canonical type. There can be at 8690 /// most one such non-template constructor, and any number of templated 8691 /// constructors. 8692 struct InheritingConstructorsForType { 8693 InheritingConstructor NonTemplate; 8694 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8695 Templates; 8696 8697 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8698 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8699 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8700 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8701 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8702 false, S.TPL_TemplateMatch)) 8703 return Templates[I].second; 8704 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8705 return Templates.back().second; 8706 } 8707 8708 return NonTemplate; 8709 } 8710 }; 8711 8712 /// Get or create the inheriting constructor record for a constructor. 8713 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8714 QualType CtorType) { 8715 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8716 .getEntry(SemaRef, Ctor); 8717 } 8718 8719 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8720 8721 /// Process all constructors for a class. 8722 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8723 for (const auto *Ctor : RD->ctors()) 8724 (this->*Callback)(Ctor); 8725 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8726 I(RD->decls_begin()), E(RD->decls_end()); 8727 I != E; ++I) { 8728 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8729 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8730 (this->*Callback)(CD); 8731 } 8732 } 8733 8734 /// Note that a constructor (or constructor template) was declared in Derived. 8735 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8736 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8737 } 8738 8739 /// Inherit a single constructor. 8740 void inherit(const CXXConstructorDecl *Ctor) { 8741 const FunctionProtoType *CtorType = 8742 Ctor->getType()->castAs<FunctionProtoType>(); 8743 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes(); 8744 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8745 8746 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8747 8748 // Core issue (no number yet): the ellipsis is always discarded. 8749 if (EPI.Variadic) { 8750 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8751 SemaRef.Diag(Ctor->getLocation(), 8752 diag::note_using_decl_constructor_ellipsis); 8753 EPI.Variadic = false; 8754 } 8755 8756 // Declare a constructor for each number of parameters. 8757 // 8758 // C++11 [class.inhctor]p1: 8759 // The candidate set of inherited constructors from the class X named in 8760 // the using-declaration consists of [... modulo defects ...] for each 8761 // constructor or constructor template of X, the set of constructors or 8762 // constructor templates that results from omitting any ellipsis parameter 8763 // specification and successively omitting parameters with a default 8764 // argument from the end of the parameter-type-list 8765 unsigned MinParams = minParamsToInherit(Ctor); 8766 unsigned Params = Ctor->getNumParams(); 8767 if (Params >= MinParams) { 8768 do 8769 declareCtor(UsingLoc, Ctor, 8770 SemaRef.Context.getFunctionType( 8771 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 8772 while (Params > MinParams && 8773 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8774 } 8775 } 8776 8777 /// Find the using-declaration which specified that we should inherit the 8778 /// constructors of \p Base. 8779 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8780 // No fancy lookup required; just look for the base constructor name 8781 // directly within the derived class. 8782 ASTContext &Context = SemaRef.Context; 8783 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8784 Context.getCanonicalType(Context.getRecordType(Base))); 8785 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8786 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8787 } 8788 8789 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8790 // C++11 [class.inhctor]p3: 8791 // [F]or each constructor template in the candidate set of inherited 8792 // constructors, a constructor template is implicitly declared 8793 if (Ctor->getDescribedFunctionTemplate()) 8794 return 0; 8795 8796 // For each non-template constructor in the candidate set of inherited 8797 // constructors other than a constructor having no parameters or a 8798 // copy/move constructor having a single parameter, a constructor is 8799 // implicitly declared [...] 8800 if (Ctor->getNumParams() == 0) 8801 return 1; 8802 if (Ctor->isCopyOrMoveConstructor()) 8803 return 2; 8804 8805 // Per discussion on core reflector, never inherit a constructor which 8806 // would become a default, copy, or move constructor of Derived either. 8807 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8808 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8809 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8810 } 8811 8812 /// Declare a single inheriting constructor, inheriting the specified 8813 /// constructor, with the given type. 8814 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8815 QualType DerivedType) { 8816 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8817 8818 // C++11 [class.inhctor]p3: 8819 // ... a constructor is implicitly declared with the same constructor 8820 // characteristics unless there is a user-declared constructor with 8821 // the same signature in the class where the using-declaration appears 8822 if (Entry.DeclaredInDerived) 8823 return; 8824 8825 // C++11 [class.inhctor]p7: 8826 // If two using-declarations declare inheriting constructors with the 8827 // same signature, the program is ill-formed 8828 if (Entry.DerivedCtor) { 8829 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8830 // Only diagnose this once per constructor. 8831 if (Entry.DerivedCtor->isInvalidDecl()) 8832 return; 8833 Entry.DerivedCtor->setInvalidDecl(); 8834 8835 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8836 SemaRef.Diag(BaseCtor->getLocation(), 8837 diag::note_using_decl_constructor_conflict_current_ctor); 8838 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8839 diag::note_using_decl_constructor_conflict_previous_ctor); 8840 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8841 diag::note_using_decl_constructor_conflict_previous_using); 8842 } else { 8843 // Core issue (no number): if the same inheriting constructor is 8844 // produced by multiple base class constructors from the same base 8845 // class, the inheriting constructor is defined as deleted. 8846 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8847 } 8848 8849 return; 8850 } 8851 8852 ASTContext &Context = SemaRef.Context; 8853 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8854 Context.getCanonicalType(Context.getRecordType(Derived))); 8855 DeclarationNameInfo NameInfo(Name, UsingLoc); 8856 8857 TemplateParameterList *TemplateParams = nullptr; 8858 if (const FunctionTemplateDecl *FTD = 8859 BaseCtor->getDescribedFunctionTemplate()) { 8860 TemplateParams = FTD->getTemplateParameters(); 8861 // We're reusing template parameters from a different DeclContext. This 8862 // is questionable at best, but works out because the template depth in 8863 // both places is guaranteed to be 0. 8864 // FIXME: Rebuild the template parameters in the new context, and 8865 // transform the function type to refer to them. 8866 } 8867 8868 // Build type source info pointing at the using-declaration. This is 8869 // required by template instantiation. 8870 TypeSourceInfo *TInfo = 8871 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8872 FunctionProtoTypeLoc ProtoLoc = 8873 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8874 8875 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8876 Context, Derived, UsingLoc, NameInfo, DerivedType, 8877 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8878 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8879 8880 // Build an unevaluated exception specification for this constructor. 8881 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8882 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8883 EPI.ExceptionSpec.Type = EST_Unevaluated; 8884 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 8885 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 8886 FPT->getParamTypes(), EPI)); 8887 8888 // Build the parameter declarations. 8889 SmallVector<ParmVarDecl *, 16> ParamDecls; 8890 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 8891 TypeSourceInfo *TInfo = 8892 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 8893 ParmVarDecl *PD = ParmVarDecl::Create( 8894 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 8895 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 8896 PD->setScopeInfo(0, I); 8897 PD->setImplicit(); 8898 ParamDecls.push_back(PD); 8899 ProtoLoc.setParam(I, PD); 8900 } 8901 8902 // Set up the new constructor. 8903 DerivedCtor->setAccess(BaseCtor->getAccess()); 8904 DerivedCtor->setParams(ParamDecls); 8905 DerivedCtor->setInheritedConstructor(BaseCtor); 8906 if (BaseCtor->isDeleted()) 8907 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8908 8909 // If this is a constructor template, build the template declaration. 8910 if (TemplateParams) { 8911 FunctionTemplateDecl *DerivedTemplate = 8912 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8913 TemplateParams, DerivedCtor); 8914 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8915 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8916 Derived->addDecl(DerivedTemplate); 8917 } else { 8918 Derived->addDecl(DerivedCtor); 8919 } 8920 8921 Entry.BaseCtor = BaseCtor; 8922 Entry.DerivedCtor = DerivedCtor; 8923 } 8924 8925 Sema &SemaRef; 8926 CXXRecordDecl *Derived; 8927 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8928 MapType Map; 8929 }; 8930 } 8931 8932 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8933 // Defer declaring the inheriting constructors until the class is 8934 // instantiated. 8935 if (ClassDecl->isDependentContext()) 8936 return; 8937 8938 // Find base classes from which we might inherit constructors. 8939 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8940 for (const auto &BaseIt : ClassDecl->bases()) 8941 if (BaseIt.getInheritConstructors()) 8942 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 8943 8944 // Go no further if we're not inheriting any constructors. 8945 if (InheritedBases.empty()) 8946 return; 8947 8948 // Declare the inherited constructors. 8949 InheritingConstructorInfo ICI(*this, ClassDecl); 8950 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8951 ICI.inheritAll(InheritedBases[I]); 8952 } 8953 8954 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8955 CXXConstructorDecl *Constructor) { 8956 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8957 assert(Constructor->getInheritedConstructor() && 8958 !Constructor->doesThisDeclarationHaveABody() && 8959 !Constructor->isDeleted()); 8960 8961 SynthesizedFunctionScope Scope(*this, Constructor); 8962 DiagnosticErrorTrap Trap(Diags); 8963 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8964 Trap.hasErrorOccurred()) { 8965 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8966 << Context.getTagDeclType(ClassDecl); 8967 Constructor->setInvalidDecl(); 8968 return; 8969 } 8970 8971 SourceLocation Loc = Constructor->getLocation(); 8972 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8973 8974 Constructor->markUsed(Context); 8975 MarkVTableUsed(CurrentLocation, ClassDecl); 8976 8977 if (ASTMutationListener *L = getASTMutationListener()) { 8978 L->CompletedImplicitDefinition(Constructor); 8979 } 8980 } 8981 8982 8983 Sema::ImplicitExceptionSpecification 8984 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8985 CXXRecordDecl *ClassDecl = MD->getParent(); 8986 8987 // C++ [except.spec]p14: 8988 // An implicitly declared special member function (Clause 12) shall have 8989 // an exception-specification. 8990 ImplicitExceptionSpecification ExceptSpec(*this); 8991 if (ClassDecl->isInvalidDecl()) 8992 return ExceptSpec; 8993 8994 // Direct base-class destructors. 8995 for (const auto &B : ClassDecl->bases()) { 8996 if (B.isVirtual()) // Handled below. 8997 continue; 8998 8999 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9000 ExceptSpec.CalledDecl(B.getLocStart(), 9001 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9002 } 9003 9004 // Virtual base-class destructors. 9005 for (const auto &B : ClassDecl->vbases()) { 9006 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 9007 ExceptSpec.CalledDecl(B.getLocStart(), 9008 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 9009 } 9010 9011 // Field destructors. 9012 for (const auto *F : ClassDecl->fields()) { 9013 if (const RecordType *RecordTy 9014 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 9015 ExceptSpec.CalledDecl(F->getLocation(), 9016 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 9017 } 9018 9019 return ExceptSpec; 9020 } 9021 9022 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 9023 // C++ [class.dtor]p2: 9024 // If a class has no user-declared destructor, a destructor is 9025 // declared implicitly. An implicitly-declared destructor is an 9026 // inline public member of its class. 9027 assert(ClassDecl->needsImplicitDestructor()); 9028 9029 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 9030 if (DSM.isAlreadyBeingDeclared()) 9031 return nullptr; 9032 9033 // Create the actual destructor declaration. 9034 CanQualType ClassType 9035 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9036 SourceLocation ClassLoc = ClassDecl->getLocation(); 9037 DeclarationName Name 9038 = Context.DeclarationNames.getCXXDestructorName(ClassType); 9039 DeclarationNameInfo NameInfo(Name, ClassLoc); 9040 CXXDestructorDecl *Destructor 9041 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 9042 QualType(), nullptr, /*isInline=*/true, 9043 /*isImplicitlyDeclared=*/true); 9044 Destructor->setAccess(AS_public); 9045 Destructor->setDefaulted(); 9046 9047 if (getLangOpts().CUDA) { 9048 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 9049 Destructor, 9050 /* ConstRHS */ false, 9051 /* Diagnose */ false); 9052 } 9053 9054 // Build an exception specification pointing back at this destructor. 9055 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 9056 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9057 9058 AddOverriddenMethods(ClassDecl, Destructor); 9059 9060 // We don't need to use SpecialMemberIsTrivial here; triviality for 9061 // destructors is easy to compute. 9062 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 9063 9064 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 9065 SetDeclDeleted(Destructor, ClassLoc); 9066 9067 // Note that we have declared this destructor. 9068 ++ASTContext::NumImplicitDestructorsDeclared; 9069 9070 // Introduce this destructor into its scope. 9071 if (Scope *S = getScopeForContext(ClassDecl)) 9072 PushOnScopeChains(Destructor, S, false); 9073 ClassDecl->addDecl(Destructor); 9074 9075 return Destructor; 9076 } 9077 9078 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 9079 CXXDestructorDecl *Destructor) { 9080 assert((Destructor->isDefaulted() && 9081 !Destructor->doesThisDeclarationHaveABody() && 9082 !Destructor->isDeleted()) && 9083 "DefineImplicitDestructor - call it for implicit default dtor"); 9084 CXXRecordDecl *ClassDecl = Destructor->getParent(); 9085 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 9086 9087 if (Destructor->isInvalidDecl()) 9088 return; 9089 9090 SynthesizedFunctionScope Scope(*this, Destructor); 9091 9092 DiagnosticErrorTrap Trap(Diags); 9093 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9094 Destructor->getParent()); 9095 9096 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 9097 Diag(CurrentLocation, diag::note_member_synthesized_at) 9098 << CXXDestructor << Context.getTagDeclType(ClassDecl); 9099 9100 Destructor->setInvalidDecl(); 9101 return; 9102 } 9103 9104 // The exception specification is needed because we are defining the 9105 // function. 9106 ResolveExceptionSpec(CurrentLocation, 9107 Destructor->getType()->castAs<FunctionProtoType>()); 9108 9109 SourceLocation Loc = Destructor->getLocEnd().isValid() 9110 ? Destructor->getLocEnd() 9111 : Destructor->getLocation(); 9112 Destructor->setBody(new (Context) CompoundStmt(Loc)); 9113 Destructor->markUsed(Context); 9114 MarkVTableUsed(CurrentLocation, ClassDecl); 9115 9116 if (ASTMutationListener *L = getASTMutationListener()) { 9117 L->CompletedImplicitDefinition(Destructor); 9118 } 9119 } 9120 9121 /// \brief Perform any semantic analysis which needs to be delayed until all 9122 /// pending class member declarations have been parsed. 9123 void Sema::ActOnFinishCXXMemberDecls() { 9124 // If the context is an invalid C++ class, just suppress these checks. 9125 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 9126 if (Record->isInvalidDecl()) { 9127 DelayedDefaultedMemberExceptionSpecs.clear(); 9128 DelayedDestructorExceptionSpecChecks.clear(); 9129 return; 9130 } 9131 } 9132 } 9133 9134 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 9135 CXXDestructorDecl *Destructor) { 9136 assert(getLangOpts().CPlusPlus11 && 9137 "adjusting dtor exception specs was introduced in c++11"); 9138 9139 // C++11 [class.dtor]p3: 9140 // A declaration of a destructor that does not have an exception- 9141 // specification is implicitly considered to have the same exception- 9142 // specification as an implicit declaration. 9143 const FunctionProtoType *DtorType = Destructor->getType()-> 9144 getAs<FunctionProtoType>(); 9145 if (DtorType->hasExceptionSpec()) 9146 return; 9147 9148 // Replace the destructor's type, building off the existing one. Fortunately, 9149 // the only thing of interest in the destructor type is its extended info. 9150 // The return and arguments are fixed. 9151 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 9152 EPI.ExceptionSpec.Type = EST_Unevaluated; 9153 EPI.ExceptionSpec.SourceDecl = Destructor; 9154 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9155 9156 // FIXME: If the destructor has a body that could throw, and the newly created 9157 // spec doesn't allow exceptions, we should emit a warning, because this 9158 // change in behavior can break conforming C++03 programs at runtime. 9159 // However, we don't have a body or an exception specification yet, so it 9160 // needs to be done somewhere else. 9161 } 9162 9163 namespace { 9164 /// \brief An abstract base class for all helper classes used in building the 9165 // copy/move operators. These classes serve as factory functions and help us 9166 // avoid using the same Expr* in the AST twice. 9167 class ExprBuilder { 9168 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION; 9169 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION; 9170 9171 protected: 9172 static Expr *assertNotNull(Expr *E) { 9173 assert(E && "Expression construction must not fail."); 9174 return E; 9175 } 9176 9177 public: 9178 ExprBuilder() {} 9179 virtual ~ExprBuilder() {} 9180 9181 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 9182 }; 9183 9184 class RefBuilder: public ExprBuilder { 9185 VarDecl *Var; 9186 QualType VarType; 9187 9188 public: 9189 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9190 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 9191 } 9192 9193 RefBuilder(VarDecl *Var, QualType VarType) 9194 : Var(Var), VarType(VarType) {} 9195 }; 9196 9197 class ThisBuilder: public ExprBuilder { 9198 public: 9199 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9200 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 9201 } 9202 }; 9203 9204 class CastBuilder: public ExprBuilder { 9205 const ExprBuilder &Builder; 9206 QualType Type; 9207 ExprValueKind Kind; 9208 const CXXCastPath &Path; 9209 9210 public: 9211 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9212 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 9213 CK_UncheckedDerivedToBase, Kind, 9214 &Path).get()); 9215 } 9216 9217 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 9218 const CXXCastPath &Path) 9219 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 9220 }; 9221 9222 class DerefBuilder: public ExprBuilder { 9223 const ExprBuilder &Builder; 9224 9225 public: 9226 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9227 return assertNotNull( 9228 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 9229 } 9230 9231 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9232 }; 9233 9234 class MemberBuilder: public ExprBuilder { 9235 const ExprBuilder &Builder; 9236 QualType Type; 9237 CXXScopeSpec SS; 9238 bool IsArrow; 9239 LookupResult &MemberLookup; 9240 9241 public: 9242 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9243 return assertNotNull(S.BuildMemberReferenceExpr( 9244 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9245 nullptr, MemberLookup, nullptr).get()); 9246 } 9247 9248 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9249 LookupResult &MemberLookup) 9250 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9251 MemberLookup(MemberLookup) {} 9252 }; 9253 9254 class MoveCastBuilder: public ExprBuilder { 9255 const ExprBuilder &Builder; 9256 9257 public: 9258 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9259 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9260 } 9261 9262 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9263 }; 9264 9265 class LvalueConvBuilder: public ExprBuilder { 9266 const ExprBuilder &Builder; 9267 9268 public: 9269 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9270 return assertNotNull( 9271 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9272 } 9273 9274 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9275 }; 9276 9277 class SubscriptBuilder: public ExprBuilder { 9278 const ExprBuilder &Base; 9279 const ExprBuilder &Index; 9280 9281 public: 9282 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9283 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9284 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9285 } 9286 9287 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9288 : Base(Base), Index(Index) {} 9289 }; 9290 9291 } // end anonymous namespace 9292 9293 /// When generating a defaulted copy or move assignment operator, if a field 9294 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9295 /// do so. This optimization only applies for arrays of scalars, and for arrays 9296 /// of class type where the selected copy/move-assignment operator is trivial. 9297 static StmtResult 9298 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9299 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9300 // Compute the size of the memory buffer to be copied. 9301 QualType SizeType = S.Context.getSizeType(); 9302 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9303 S.Context.getTypeSizeInChars(T).getQuantity()); 9304 9305 // Take the address of the field references for "from" and "to". We 9306 // directly construct UnaryOperators here because semantic analysis 9307 // does not permit us to take the address of an xvalue. 9308 Expr *From = FromB.build(S, Loc); 9309 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9310 S.Context.getPointerType(From->getType()), 9311 VK_RValue, OK_Ordinary, Loc); 9312 Expr *To = ToB.build(S, Loc); 9313 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9314 S.Context.getPointerType(To->getType()), 9315 VK_RValue, OK_Ordinary, Loc); 9316 9317 const Type *E = T->getBaseElementTypeUnsafe(); 9318 bool NeedsCollectableMemCpy = 9319 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9320 9321 // Create a reference to the __builtin_objc_memmove_collectable function 9322 StringRef MemCpyName = NeedsCollectableMemCpy ? 9323 "__builtin_objc_memmove_collectable" : 9324 "__builtin_memcpy"; 9325 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9326 Sema::LookupOrdinaryName); 9327 S.LookupName(R, S.TUScope, true); 9328 9329 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9330 if (!MemCpy) 9331 // Something went horribly wrong earlier, and we will have complained 9332 // about it. 9333 return StmtError(); 9334 9335 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9336 VK_RValue, Loc, nullptr); 9337 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9338 9339 Expr *CallArgs[] = { 9340 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9341 }; 9342 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9343 Loc, CallArgs, Loc); 9344 9345 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9346 return Call.getAs<Stmt>(); 9347 } 9348 9349 /// \brief Builds a statement that copies/moves the given entity from \p From to 9350 /// \c To. 9351 /// 9352 /// This routine is used to copy/move the members of a class with an 9353 /// implicitly-declared copy/move assignment operator. When the entities being 9354 /// copied are arrays, this routine builds for loops to copy them. 9355 /// 9356 /// \param S The Sema object used for type-checking. 9357 /// 9358 /// \param Loc The location where the implicit copy/move is being generated. 9359 /// 9360 /// \param T The type of the expressions being copied/moved. Both expressions 9361 /// must have this type. 9362 /// 9363 /// \param To The expression we are copying/moving to. 9364 /// 9365 /// \param From The expression we are copying/moving from. 9366 /// 9367 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9368 /// Otherwise, it's a non-static member subobject. 9369 /// 9370 /// \param Copying Whether we're copying or moving. 9371 /// 9372 /// \param Depth Internal parameter recording the depth of the recursion. 9373 /// 9374 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9375 /// if a memcpy should be used instead. 9376 static StmtResult 9377 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9378 const ExprBuilder &To, const ExprBuilder &From, 9379 bool CopyingBaseSubobject, bool Copying, 9380 unsigned Depth = 0) { 9381 // C++11 [class.copy]p28: 9382 // Each subobject is assigned in the manner appropriate to its type: 9383 // 9384 // - if the subobject is of class type, as if by a call to operator= with 9385 // the subobject as the object expression and the corresponding 9386 // subobject of x as a single function argument (as if by explicit 9387 // qualification; that is, ignoring any possible virtual overriding 9388 // functions in more derived classes); 9389 // 9390 // C++03 [class.copy]p13: 9391 // - if the subobject is of class type, the copy assignment operator for 9392 // the class is used (as if by explicit qualification; that is, 9393 // ignoring any possible virtual overriding functions in more derived 9394 // classes); 9395 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9396 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9397 9398 // Look for operator=. 9399 DeclarationName Name 9400 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9401 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9402 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9403 9404 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9405 // operator. 9406 if (!S.getLangOpts().CPlusPlus11) { 9407 LookupResult::Filter F = OpLookup.makeFilter(); 9408 while (F.hasNext()) { 9409 NamedDecl *D = F.next(); 9410 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9411 if (Method->isCopyAssignmentOperator() || 9412 (!Copying && Method->isMoveAssignmentOperator())) 9413 continue; 9414 9415 F.erase(); 9416 } 9417 F.done(); 9418 } 9419 9420 // Suppress the protected check (C++ [class.protected]) for each of the 9421 // assignment operators we found. This strange dance is required when 9422 // we're assigning via a base classes's copy-assignment operator. To 9423 // ensure that we're getting the right base class subobject (without 9424 // ambiguities), we need to cast "this" to that subobject type; to 9425 // ensure that we don't go through the virtual call mechanism, we need 9426 // to qualify the operator= name with the base class (see below). However, 9427 // this means that if the base class has a protected copy assignment 9428 // operator, the protected member access check will fail. So, we 9429 // rewrite "protected" access to "public" access in this case, since we 9430 // know by construction that we're calling from a derived class. 9431 if (CopyingBaseSubobject) { 9432 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9433 L != LEnd; ++L) { 9434 if (L.getAccess() == AS_protected) 9435 L.setAccess(AS_public); 9436 } 9437 } 9438 9439 // Create the nested-name-specifier that will be used to qualify the 9440 // reference to operator=; this is required to suppress the virtual 9441 // call mechanism. 9442 CXXScopeSpec SS; 9443 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9444 SS.MakeTrivial(S.Context, 9445 NestedNameSpecifier::Create(S.Context, nullptr, false, 9446 CanonicalT), 9447 Loc); 9448 9449 // Create the reference to operator=. 9450 ExprResult OpEqualRef 9451 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9452 SS, /*TemplateKWLoc=*/SourceLocation(), 9453 /*FirstQualifierInScope=*/nullptr, 9454 OpLookup, 9455 /*TemplateArgs=*/nullptr, 9456 /*SuppressQualifierCheck=*/true); 9457 if (OpEqualRef.isInvalid()) 9458 return StmtError(); 9459 9460 // Build the call to the assignment operator. 9461 9462 Expr *FromInst = From.build(S, Loc); 9463 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9464 OpEqualRef.getAs<Expr>(), 9465 Loc, FromInst, Loc); 9466 if (Call.isInvalid()) 9467 return StmtError(); 9468 9469 // If we built a call to a trivial 'operator=' while copying an array, 9470 // bail out. We'll replace the whole shebang with a memcpy. 9471 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9472 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9473 return StmtResult((Stmt*)nullptr); 9474 9475 // Convert to an expression-statement, and clean up any produced 9476 // temporaries. 9477 return S.ActOnExprStmt(Call); 9478 } 9479 9480 // - if the subobject is of scalar type, the built-in assignment 9481 // operator is used. 9482 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9483 if (!ArrayTy) { 9484 ExprResult Assignment = S.CreateBuiltinBinOp( 9485 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9486 if (Assignment.isInvalid()) 9487 return StmtError(); 9488 return S.ActOnExprStmt(Assignment); 9489 } 9490 9491 // - if the subobject is an array, each element is assigned, in the 9492 // manner appropriate to the element type; 9493 9494 // Construct a loop over the array bounds, e.g., 9495 // 9496 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9497 // 9498 // that will copy each of the array elements. 9499 QualType SizeType = S.Context.getSizeType(); 9500 9501 // Create the iteration variable. 9502 IdentifierInfo *IterationVarName = nullptr; 9503 { 9504 SmallString<8> Str; 9505 llvm::raw_svector_ostream OS(Str); 9506 OS << "__i" << Depth; 9507 IterationVarName = &S.Context.Idents.get(OS.str()); 9508 } 9509 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9510 IterationVarName, SizeType, 9511 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9512 SC_None); 9513 9514 // Initialize the iteration variable to zero. 9515 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9516 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9517 9518 // Creates a reference to the iteration variable. 9519 RefBuilder IterationVarRef(IterationVar, SizeType); 9520 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9521 9522 // Create the DeclStmt that holds the iteration variable. 9523 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9524 9525 // Subscript the "from" and "to" expressions with the iteration variable. 9526 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9527 MoveCastBuilder FromIndexMove(FromIndexCopy); 9528 const ExprBuilder *FromIndex; 9529 if (Copying) 9530 FromIndex = &FromIndexCopy; 9531 else 9532 FromIndex = &FromIndexMove; 9533 9534 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9535 9536 // Build the copy/move for an individual element of the array. 9537 StmtResult Copy = 9538 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9539 ToIndex, *FromIndex, CopyingBaseSubobject, 9540 Copying, Depth + 1); 9541 // Bail out if copying fails or if we determined that we should use memcpy. 9542 if (Copy.isInvalid() || !Copy.get()) 9543 return Copy; 9544 9545 // Create the comparison against the array bound. 9546 llvm::APInt Upper 9547 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9548 Expr *Comparison 9549 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9550 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9551 BO_NE, S.Context.BoolTy, 9552 VK_RValue, OK_Ordinary, Loc, false); 9553 9554 // Create the pre-increment of the iteration variable. 9555 Expr *Increment 9556 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9557 SizeType, VK_LValue, OK_Ordinary, Loc); 9558 9559 // Construct the loop that copies all elements of this array. 9560 return S.ActOnForStmt(Loc, Loc, InitStmt, 9561 S.MakeFullExpr(Comparison), 9562 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9563 Loc, Copy.get()); 9564 } 9565 9566 static StmtResult 9567 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9568 const ExprBuilder &To, const ExprBuilder &From, 9569 bool CopyingBaseSubobject, bool Copying) { 9570 // Maybe we should use a memcpy? 9571 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9572 T.isTriviallyCopyableType(S.Context)) 9573 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9574 9575 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9576 CopyingBaseSubobject, 9577 Copying, 0)); 9578 9579 // If we ended up picking a trivial assignment operator for an array of a 9580 // non-trivially-copyable class type, just emit a memcpy. 9581 if (!Result.isInvalid() && !Result.get()) 9582 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9583 9584 return Result; 9585 } 9586 9587 Sema::ImplicitExceptionSpecification 9588 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9589 CXXRecordDecl *ClassDecl = MD->getParent(); 9590 9591 ImplicitExceptionSpecification ExceptSpec(*this); 9592 if (ClassDecl->isInvalidDecl()) 9593 return ExceptSpec; 9594 9595 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9596 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9597 unsigned ArgQuals = 9598 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9599 9600 // C++ [except.spec]p14: 9601 // An implicitly declared special member function (Clause 12) shall have an 9602 // exception-specification. [...] 9603 9604 // It is unspecified whether or not an implicit copy assignment operator 9605 // attempts to deduplicate calls to assignment operators of virtual bases are 9606 // made. As such, this exception specification is effectively unspecified. 9607 // Based on a similar decision made for constness in C++0x, we're erring on 9608 // the side of assuming such calls to be made regardless of whether they 9609 // actually happen. 9610 for (const auto &Base : ClassDecl->bases()) { 9611 if (Base.isVirtual()) 9612 continue; 9613 9614 CXXRecordDecl *BaseClassDecl 9615 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9616 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9617 ArgQuals, false, 0)) 9618 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9619 } 9620 9621 for (const auto &Base : ClassDecl->vbases()) { 9622 CXXRecordDecl *BaseClassDecl 9623 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9624 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9625 ArgQuals, false, 0)) 9626 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9627 } 9628 9629 for (const auto *Field : ClassDecl->fields()) { 9630 QualType FieldType = Context.getBaseElementType(Field->getType()); 9631 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9632 if (CXXMethodDecl *CopyAssign = 9633 LookupCopyingAssignment(FieldClassDecl, 9634 ArgQuals | FieldType.getCVRQualifiers(), 9635 false, 0)) 9636 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9637 } 9638 } 9639 9640 return ExceptSpec; 9641 } 9642 9643 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9644 // Note: The following rules are largely analoguous to the copy 9645 // constructor rules. Note that virtual bases are not taken into account 9646 // for determining the argument type of the operator. Note also that 9647 // operators taking an object instead of a reference are allowed. 9648 assert(ClassDecl->needsImplicitCopyAssignment()); 9649 9650 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9651 if (DSM.isAlreadyBeingDeclared()) 9652 return nullptr; 9653 9654 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9655 QualType RetType = Context.getLValueReferenceType(ArgType); 9656 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9657 if (Const) 9658 ArgType = ArgType.withConst(); 9659 ArgType = Context.getLValueReferenceType(ArgType); 9660 9661 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9662 CXXCopyAssignment, 9663 Const); 9664 9665 // An implicitly-declared copy assignment operator is an inline public 9666 // member of its class. 9667 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9668 SourceLocation ClassLoc = ClassDecl->getLocation(); 9669 DeclarationNameInfo NameInfo(Name, ClassLoc); 9670 CXXMethodDecl *CopyAssignment = 9671 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9672 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 9673 /*isInline=*/true, Constexpr, SourceLocation()); 9674 CopyAssignment->setAccess(AS_public); 9675 CopyAssignment->setDefaulted(); 9676 CopyAssignment->setImplicit(); 9677 9678 if (getLangOpts().CUDA) { 9679 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 9680 CopyAssignment, 9681 /* ConstRHS */ Const, 9682 /* Diagnose */ false); 9683 } 9684 9685 // Build an exception specification pointing back at this member. 9686 FunctionProtoType::ExtProtoInfo EPI = 9687 getImplicitMethodEPI(*this, CopyAssignment); 9688 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9689 9690 // Add the parameter to the operator. 9691 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9692 ClassLoc, ClassLoc, 9693 /*Id=*/nullptr, ArgType, 9694 /*TInfo=*/nullptr, SC_None, 9695 nullptr); 9696 CopyAssignment->setParams(FromParam); 9697 9698 AddOverriddenMethods(ClassDecl, CopyAssignment); 9699 9700 CopyAssignment->setTrivial( 9701 ClassDecl->needsOverloadResolutionForCopyAssignment() 9702 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9703 : ClassDecl->hasTrivialCopyAssignment()); 9704 9705 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9706 SetDeclDeleted(CopyAssignment, ClassLoc); 9707 9708 // Note that we have added this copy-assignment operator. 9709 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9710 9711 if (Scope *S = getScopeForContext(ClassDecl)) 9712 PushOnScopeChains(CopyAssignment, S, false); 9713 ClassDecl->addDecl(CopyAssignment); 9714 9715 return CopyAssignment; 9716 } 9717 9718 /// Diagnose an implicit copy operation for a class which is odr-used, but 9719 /// which is deprecated because the class has a user-declared copy constructor, 9720 /// copy assignment operator, or destructor. 9721 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 9722 SourceLocation UseLoc) { 9723 assert(CopyOp->isImplicit()); 9724 9725 CXXRecordDecl *RD = CopyOp->getParent(); 9726 CXXMethodDecl *UserDeclaredOperation = nullptr; 9727 9728 // In Microsoft mode, assignment operations don't affect constructors and 9729 // vice versa. 9730 if (RD->hasUserDeclaredDestructor()) { 9731 UserDeclaredOperation = RD->getDestructor(); 9732 } else if (!isa<CXXConstructorDecl>(CopyOp) && 9733 RD->hasUserDeclaredCopyConstructor() && 9734 !S.getLangOpts().MSVCCompat) { 9735 // Find any user-declared copy constructor. 9736 for (auto *I : RD->ctors()) { 9737 if (I->isCopyConstructor()) { 9738 UserDeclaredOperation = I; 9739 break; 9740 } 9741 } 9742 assert(UserDeclaredOperation); 9743 } else if (isa<CXXConstructorDecl>(CopyOp) && 9744 RD->hasUserDeclaredCopyAssignment() && 9745 !S.getLangOpts().MSVCCompat) { 9746 // Find any user-declared move assignment operator. 9747 for (auto *I : RD->methods()) { 9748 if (I->isCopyAssignmentOperator()) { 9749 UserDeclaredOperation = I; 9750 break; 9751 } 9752 } 9753 assert(UserDeclaredOperation); 9754 } 9755 9756 if (UserDeclaredOperation) { 9757 S.Diag(UserDeclaredOperation->getLocation(), 9758 diag::warn_deprecated_copy_operation) 9759 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 9760 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 9761 S.Diag(UseLoc, diag::note_member_synthesized_at) 9762 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 9763 : Sema::CXXCopyAssignment) 9764 << RD; 9765 } 9766 } 9767 9768 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 9769 CXXMethodDecl *CopyAssignOperator) { 9770 assert((CopyAssignOperator->isDefaulted() && 9771 CopyAssignOperator->isOverloadedOperator() && 9772 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 9773 !CopyAssignOperator->doesThisDeclarationHaveABody() && 9774 !CopyAssignOperator->isDeleted()) && 9775 "DefineImplicitCopyAssignment called for wrong function"); 9776 9777 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 9778 9779 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 9780 CopyAssignOperator->setInvalidDecl(); 9781 return; 9782 } 9783 9784 // C++11 [class.copy]p18: 9785 // The [definition of an implicitly declared copy assignment operator] is 9786 // deprecated if the class has a user-declared copy constructor or a 9787 // user-declared destructor. 9788 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 9789 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 9790 9791 CopyAssignOperator->markUsed(Context); 9792 9793 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 9794 DiagnosticErrorTrap Trap(Diags); 9795 9796 // C++0x [class.copy]p30: 9797 // The implicitly-defined or explicitly-defaulted copy assignment operator 9798 // for a non-union class X performs memberwise copy assignment of its 9799 // subobjects. The direct base classes of X are assigned first, in the 9800 // order of their declaration in the base-specifier-list, and then the 9801 // immediate non-static data members of X are assigned, in the order in 9802 // which they were declared in the class definition. 9803 9804 // The statements that form the synthesized function body. 9805 SmallVector<Stmt*, 8> Statements; 9806 9807 // The parameter for the "other" object, which we are copying from. 9808 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 9809 Qualifiers OtherQuals = Other->getType().getQualifiers(); 9810 QualType OtherRefType = Other->getType(); 9811 if (const LValueReferenceType *OtherRef 9812 = OtherRefType->getAs<LValueReferenceType>()) { 9813 OtherRefType = OtherRef->getPointeeType(); 9814 OtherQuals = OtherRefType.getQualifiers(); 9815 } 9816 9817 // Our location for everything implicitly-generated. 9818 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 9819 ? CopyAssignOperator->getLocEnd() 9820 : CopyAssignOperator->getLocation(); 9821 9822 // Builds a DeclRefExpr for the "other" object. 9823 RefBuilder OtherRef(Other, OtherRefType); 9824 9825 // Builds the "this" pointer. 9826 ThisBuilder This; 9827 9828 // Assign base classes. 9829 bool Invalid = false; 9830 for (auto &Base : ClassDecl->bases()) { 9831 // Form the assignment: 9832 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 9833 QualType BaseType = Base.getType().getUnqualifiedType(); 9834 if (!BaseType->isRecordType()) { 9835 Invalid = true; 9836 continue; 9837 } 9838 9839 CXXCastPath BasePath; 9840 BasePath.push_back(&Base); 9841 9842 // Construct the "from" expression, which is an implicit cast to the 9843 // appropriately-qualified base type. 9844 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 9845 VK_LValue, BasePath); 9846 9847 // Dereference "this". 9848 DerefBuilder DerefThis(This); 9849 CastBuilder To(DerefThis, 9850 Context.getCVRQualifiedType( 9851 BaseType, CopyAssignOperator->getTypeQualifiers()), 9852 VK_LValue, BasePath); 9853 9854 // Build the copy. 9855 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 9856 To, From, 9857 /*CopyingBaseSubobject=*/true, 9858 /*Copying=*/true); 9859 if (Copy.isInvalid()) { 9860 Diag(CurrentLocation, diag::note_member_synthesized_at) 9861 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9862 CopyAssignOperator->setInvalidDecl(); 9863 return; 9864 } 9865 9866 // Success! Record the copy. 9867 Statements.push_back(Copy.getAs<Expr>()); 9868 } 9869 9870 // Assign non-static members. 9871 for (auto *Field : ClassDecl->fields()) { 9872 if (Field->isUnnamedBitfield()) 9873 continue; 9874 9875 if (Field->isInvalidDecl()) { 9876 Invalid = true; 9877 continue; 9878 } 9879 9880 // Check for members of reference type; we can't copy those. 9881 if (Field->getType()->isReferenceType()) { 9882 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9883 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9884 Diag(Field->getLocation(), diag::note_declared_at); 9885 Diag(CurrentLocation, diag::note_member_synthesized_at) 9886 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9887 Invalid = true; 9888 continue; 9889 } 9890 9891 // Check for members of const-qualified, non-class type. 9892 QualType BaseType = Context.getBaseElementType(Field->getType()); 9893 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9894 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9895 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9896 Diag(Field->getLocation(), diag::note_declared_at); 9897 Diag(CurrentLocation, diag::note_member_synthesized_at) 9898 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9899 Invalid = true; 9900 continue; 9901 } 9902 9903 // Suppress assigning zero-width bitfields. 9904 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9905 continue; 9906 9907 QualType FieldType = Field->getType().getNonReferenceType(); 9908 if (FieldType->isIncompleteArrayType()) { 9909 assert(ClassDecl->hasFlexibleArrayMember() && 9910 "Incomplete array type is not valid"); 9911 continue; 9912 } 9913 9914 // Build references to the field in the object we're copying from and to. 9915 CXXScopeSpec SS; // Intentionally empty 9916 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9917 LookupMemberName); 9918 MemberLookup.addDecl(Field); 9919 MemberLookup.resolveKind(); 9920 9921 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 9922 9923 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 9924 9925 // Build the copy of this field. 9926 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 9927 To, From, 9928 /*CopyingBaseSubobject=*/false, 9929 /*Copying=*/true); 9930 if (Copy.isInvalid()) { 9931 Diag(CurrentLocation, diag::note_member_synthesized_at) 9932 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9933 CopyAssignOperator->setInvalidDecl(); 9934 return; 9935 } 9936 9937 // Success! Record the copy. 9938 Statements.push_back(Copy.getAs<Stmt>()); 9939 } 9940 9941 if (!Invalid) { 9942 // Add a "return *this;" 9943 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9944 9945 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 9946 if (Return.isInvalid()) 9947 Invalid = true; 9948 else { 9949 Statements.push_back(Return.getAs<Stmt>()); 9950 9951 if (Trap.hasErrorOccurred()) { 9952 Diag(CurrentLocation, diag::note_member_synthesized_at) 9953 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9954 Invalid = true; 9955 } 9956 } 9957 } 9958 9959 // The exception specification is needed because we are defining the 9960 // function. 9961 ResolveExceptionSpec(CurrentLocation, 9962 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 9963 9964 if (Invalid) { 9965 CopyAssignOperator->setInvalidDecl(); 9966 return; 9967 } 9968 9969 StmtResult Body; 9970 { 9971 CompoundScopeRAII CompoundScope(*this); 9972 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9973 /*isStmtExpr=*/false); 9974 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9975 } 9976 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 9977 9978 if (ASTMutationListener *L = getASTMutationListener()) { 9979 L->CompletedImplicitDefinition(CopyAssignOperator); 9980 } 9981 } 9982 9983 Sema::ImplicitExceptionSpecification 9984 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9985 CXXRecordDecl *ClassDecl = MD->getParent(); 9986 9987 ImplicitExceptionSpecification ExceptSpec(*this); 9988 if (ClassDecl->isInvalidDecl()) 9989 return ExceptSpec; 9990 9991 // C++0x [except.spec]p14: 9992 // An implicitly declared special member function (Clause 12) shall have an 9993 // exception-specification. [...] 9994 9995 // It is unspecified whether or not an implicit move assignment operator 9996 // attempts to deduplicate calls to assignment operators of virtual bases are 9997 // made. As such, this exception specification is effectively unspecified. 9998 // Based on a similar decision made for constness in C++0x, we're erring on 9999 // the side of assuming such calls to be made regardless of whether they 10000 // actually happen. 10001 // Note that a move constructor is not implicitly declared when there are 10002 // virtual bases, but it can still be user-declared and explicitly defaulted. 10003 for (const auto &Base : ClassDecl->bases()) { 10004 if (Base.isVirtual()) 10005 continue; 10006 10007 CXXRecordDecl *BaseClassDecl 10008 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10009 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10010 0, false, 0)) 10011 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10012 } 10013 10014 for (const auto &Base : ClassDecl->vbases()) { 10015 CXXRecordDecl *BaseClassDecl 10016 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10017 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 10018 0, false, 0)) 10019 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 10020 } 10021 10022 for (const auto *Field : ClassDecl->fields()) { 10023 QualType FieldType = Context.getBaseElementType(Field->getType()); 10024 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10025 if (CXXMethodDecl *MoveAssign = 10026 LookupMovingAssignment(FieldClassDecl, 10027 FieldType.getCVRQualifiers(), 10028 false, 0)) 10029 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 10030 } 10031 } 10032 10033 return ExceptSpec; 10034 } 10035 10036 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 10037 assert(ClassDecl->needsImplicitMoveAssignment()); 10038 10039 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 10040 if (DSM.isAlreadyBeingDeclared()) 10041 return nullptr; 10042 10043 // Note: The following rules are largely analoguous to the move 10044 // constructor rules. 10045 10046 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10047 QualType RetType = Context.getLValueReferenceType(ArgType); 10048 ArgType = Context.getRValueReferenceType(ArgType); 10049 10050 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10051 CXXMoveAssignment, 10052 false); 10053 10054 // An implicitly-declared move assignment operator is an inline public 10055 // member of its class. 10056 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10057 SourceLocation ClassLoc = ClassDecl->getLocation(); 10058 DeclarationNameInfo NameInfo(Name, ClassLoc); 10059 CXXMethodDecl *MoveAssignment = 10060 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10061 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10062 /*isInline=*/true, Constexpr, SourceLocation()); 10063 MoveAssignment->setAccess(AS_public); 10064 MoveAssignment->setDefaulted(); 10065 MoveAssignment->setImplicit(); 10066 10067 if (getLangOpts().CUDA) { 10068 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 10069 MoveAssignment, 10070 /* ConstRHS */ false, 10071 /* Diagnose */ false); 10072 } 10073 10074 // Build an exception specification pointing back at this member. 10075 FunctionProtoType::ExtProtoInfo EPI = 10076 getImplicitMethodEPI(*this, MoveAssignment); 10077 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10078 10079 // Add the parameter to the operator. 10080 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 10081 ClassLoc, ClassLoc, 10082 /*Id=*/nullptr, ArgType, 10083 /*TInfo=*/nullptr, SC_None, 10084 nullptr); 10085 MoveAssignment->setParams(FromParam); 10086 10087 AddOverriddenMethods(ClassDecl, MoveAssignment); 10088 10089 MoveAssignment->setTrivial( 10090 ClassDecl->needsOverloadResolutionForMoveAssignment() 10091 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 10092 : ClassDecl->hasTrivialMoveAssignment()); 10093 10094 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 10095 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 10096 SetDeclDeleted(MoveAssignment, ClassLoc); 10097 } 10098 10099 // Note that we have added this copy-assignment operator. 10100 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 10101 10102 if (Scope *S = getScopeForContext(ClassDecl)) 10103 PushOnScopeChains(MoveAssignment, S, false); 10104 ClassDecl->addDecl(MoveAssignment); 10105 10106 return MoveAssignment; 10107 } 10108 10109 /// Check if we're implicitly defining a move assignment operator for a class 10110 /// with virtual bases. Such a move assignment might move-assign the virtual 10111 /// base multiple times. 10112 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 10113 SourceLocation CurrentLocation) { 10114 assert(!Class->isDependentContext() && "should not define dependent move"); 10115 10116 // Only a virtual base could get implicitly move-assigned multiple times. 10117 // Only a non-trivial move assignment can observe this. We only want to 10118 // diagnose if we implicitly define an assignment operator that assigns 10119 // two base classes, both of which move-assign the same virtual base. 10120 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 10121 Class->getNumBases() < 2) 10122 return; 10123 10124 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 10125 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 10126 VBaseMap VBases; 10127 10128 for (auto &BI : Class->bases()) { 10129 Worklist.push_back(&BI); 10130 while (!Worklist.empty()) { 10131 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 10132 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 10133 10134 // If the base has no non-trivial move assignment operators, 10135 // we don't care about moves from it. 10136 if (!Base->hasNonTrivialMoveAssignment()) 10137 continue; 10138 10139 // If there's nothing virtual here, skip it. 10140 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 10141 continue; 10142 10143 // If we're not actually going to call a move assignment for this base, 10144 // or the selected move assignment is trivial, skip it. 10145 Sema::SpecialMemberOverloadResult *SMOR = 10146 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 10147 /*ConstArg*/false, /*VolatileArg*/false, 10148 /*RValueThis*/true, /*ConstThis*/false, 10149 /*VolatileThis*/false); 10150 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 10151 !SMOR->getMethod()->isMoveAssignmentOperator()) 10152 continue; 10153 10154 if (BaseSpec->isVirtual()) { 10155 // We're going to move-assign this virtual base, and its move 10156 // assignment operator is not trivial. If this can happen for 10157 // multiple distinct direct bases of Class, diagnose it. (If it 10158 // only happens in one base, we'll diagnose it when synthesizing 10159 // that base class's move assignment operator.) 10160 CXXBaseSpecifier *&Existing = 10161 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 10162 .first->second; 10163 if (Existing && Existing != &BI) { 10164 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 10165 << Class << Base; 10166 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 10167 << (Base->getCanonicalDecl() == 10168 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10169 << Base << Existing->getType() << Existing->getSourceRange(); 10170 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 10171 << (Base->getCanonicalDecl() == 10172 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10173 << Base << BI.getType() << BaseSpec->getSourceRange(); 10174 10175 // Only diagnose each vbase once. 10176 Existing = nullptr; 10177 } 10178 } else { 10179 // Only walk over bases that have defaulted move assignment operators. 10180 // We assume that any user-provided move assignment operator handles 10181 // the multiple-moves-of-vbase case itself somehow. 10182 if (!SMOR->getMethod()->isDefaulted()) 10183 continue; 10184 10185 // We're going to move the base classes of Base. Add them to the list. 10186 for (auto &BI : Base->bases()) 10187 Worklist.push_back(&BI); 10188 } 10189 } 10190 } 10191 } 10192 10193 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 10194 CXXMethodDecl *MoveAssignOperator) { 10195 assert((MoveAssignOperator->isDefaulted() && 10196 MoveAssignOperator->isOverloadedOperator() && 10197 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 10198 !MoveAssignOperator->doesThisDeclarationHaveABody() && 10199 !MoveAssignOperator->isDeleted()) && 10200 "DefineImplicitMoveAssignment called for wrong function"); 10201 10202 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 10203 10204 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 10205 MoveAssignOperator->setInvalidDecl(); 10206 return; 10207 } 10208 10209 MoveAssignOperator->markUsed(Context); 10210 10211 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 10212 DiagnosticErrorTrap Trap(Diags); 10213 10214 // C++0x [class.copy]p28: 10215 // The implicitly-defined or move assignment operator for a non-union class 10216 // X performs memberwise move assignment of its subobjects. The direct base 10217 // classes of X are assigned first, in the order of their declaration in the 10218 // base-specifier-list, and then the immediate non-static data members of X 10219 // are assigned, in the order in which they were declared in the class 10220 // definition. 10221 10222 // Issue a warning if our implicit move assignment operator will move 10223 // from a virtual base more than once. 10224 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 10225 10226 // The statements that form the synthesized function body. 10227 SmallVector<Stmt*, 8> Statements; 10228 10229 // The parameter for the "other" object, which we are move from. 10230 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 10231 QualType OtherRefType = Other->getType()-> 10232 getAs<RValueReferenceType>()->getPointeeType(); 10233 assert(!OtherRefType.getQualifiers() && 10234 "Bad argument type of defaulted move assignment"); 10235 10236 // Our location for everything implicitly-generated. 10237 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 10238 ? MoveAssignOperator->getLocEnd() 10239 : MoveAssignOperator->getLocation(); 10240 10241 // Builds a reference to the "other" object. 10242 RefBuilder OtherRef(Other, OtherRefType); 10243 // Cast to rvalue. 10244 MoveCastBuilder MoveOther(OtherRef); 10245 10246 // Builds the "this" pointer. 10247 ThisBuilder This; 10248 10249 // Assign base classes. 10250 bool Invalid = false; 10251 for (auto &Base : ClassDecl->bases()) { 10252 // C++11 [class.copy]p28: 10253 // It is unspecified whether subobjects representing virtual base classes 10254 // are assigned more than once by the implicitly-defined copy assignment 10255 // operator. 10256 // FIXME: Do not assign to a vbase that will be assigned by some other base 10257 // class. For a move-assignment, this can result in the vbase being moved 10258 // multiple times. 10259 10260 // Form the assignment: 10261 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10262 QualType BaseType = Base.getType().getUnqualifiedType(); 10263 if (!BaseType->isRecordType()) { 10264 Invalid = true; 10265 continue; 10266 } 10267 10268 CXXCastPath BasePath; 10269 BasePath.push_back(&Base); 10270 10271 // Construct the "from" expression, which is an implicit cast to the 10272 // appropriately-qualified base type. 10273 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10274 10275 // Dereference "this". 10276 DerefBuilder DerefThis(This); 10277 10278 // Implicitly cast "this" to the appropriately-qualified base type. 10279 CastBuilder To(DerefThis, 10280 Context.getCVRQualifiedType( 10281 BaseType, MoveAssignOperator->getTypeQualifiers()), 10282 VK_LValue, BasePath); 10283 10284 // Build the move. 10285 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10286 To, From, 10287 /*CopyingBaseSubobject=*/true, 10288 /*Copying=*/false); 10289 if (Move.isInvalid()) { 10290 Diag(CurrentLocation, diag::note_member_synthesized_at) 10291 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10292 MoveAssignOperator->setInvalidDecl(); 10293 return; 10294 } 10295 10296 // Success! Record the move. 10297 Statements.push_back(Move.getAs<Expr>()); 10298 } 10299 10300 // Assign non-static members. 10301 for (auto *Field : ClassDecl->fields()) { 10302 if (Field->isUnnamedBitfield()) 10303 continue; 10304 10305 if (Field->isInvalidDecl()) { 10306 Invalid = true; 10307 continue; 10308 } 10309 10310 // Check for members of reference type; we can't move those. 10311 if (Field->getType()->isReferenceType()) { 10312 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10313 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10314 Diag(Field->getLocation(), diag::note_declared_at); 10315 Diag(CurrentLocation, diag::note_member_synthesized_at) 10316 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10317 Invalid = true; 10318 continue; 10319 } 10320 10321 // Check for members of const-qualified, non-class type. 10322 QualType BaseType = Context.getBaseElementType(Field->getType()); 10323 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10324 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10325 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10326 Diag(Field->getLocation(), diag::note_declared_at); 10327 Diag(CurrentLocation, diag::note_member_synthesized_at) 10328 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10329 Invalid = true; 10330 continue; 10331 } 10332 10333 // Suppress assigning zero-width bitfields. 10334 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10335 continue; 10336 10337 QualType FieldType = Field->getType().getNonReferenceType(); 10338 if (FieldType->isIncompleteArrayType()) { 10339 assert(ClassDecl->hasFlexibleArrayMember() && 10340 "Incomplete array type is not valid"); 10341 continue; 10342 } 10343 10344 // Build references to the field in the object we're copying from and to. 10345 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10346 LookupMemberName); 10347 MemberLookup.addDecl(Field); 10348 MemberLookup.resolveKind(); 10349 MemberBuilder From(MoveOther, OtherRefType, 10350 /*IsArrow=*/false, MemberLookup); 10351 MemberBuilder To(This, getCurrentThisType(), 10352 /*IsArrow=*/true, MemberLookup); 10353 10354 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10355 "Member reference with rvalue base must be rvalue except for reference " 10356 "members, which aren't allowed for move assignment."); 10357 10358 // Build the move of this field. 10359 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10360 To, From, 10361 /*CopyingBaseSubobject=*/false, 10362 /*Copying=*/false); 10363 if (Move.isInvalid()) { 10364 Diag(CurrentLocation, diag::note_member_synthesized_at) 10365 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10366 MoveAssignOperator->setInvalidDecl(); 10367 return; 10368 } 10369 10370 // Success! Record the copy. 10371 Statements.push_back(Move.getAs<Stmt>()); 10372 } 10373 10374 if (!Invalid) { 10375 // Add a "return *this;" 10376 ExprResult ThisObj = 10377 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10378 10379 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10380 if (Return.isInvalid()) 10381 Invalid = true; 10382 else { 10383 Statements.push_back(Return.getAs<Stmt>()); 10384 10385 if (Trap.hasErrorOccurred()) { 10386 Diag(CurrentLocation, diag::note_member_synthesized_at) 10387 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10388 Invalid = true; 10389 } 10390 } 10391 } 10392 10393 // The exception specification is needed because we are defining the 10394 // function. 10395 ResolveExceptionSpec(CurrentLocation, 10396 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 10397 10398 if (Invalid) { 10399 MoveAssignOperator->setInvalidDecl(); 10400 return; 10401 } 10402 10403 StmtResult Body; 10404 { 10405 CompoundScopeRAII CompoundScope(*this); 10406 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10407 /*isStmtExpr=*/false); 10408 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10409 } 10410 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10411 10412 if (ASTMutationListener *L = getASTMutationListener()) { 10413 L->CompletedImplicitDefinition(MoveAssignOperator); 10414 } 10415 } 10416 10417 Sema::ImplicitExceptionSpecification 10418 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10419 CXXRecordDecl *ClassDecl = MD->getParent(); 10420 10421 ImplicitExceptionSpecification ExceptSpec(*this); 10422 if (ClassDecl->isInvalidDecl()) 10423 return ExceptSpec; 10424 10425 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10426 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10427 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10428 10429 // C++ [except.spec]p14: 10430 // An implicitly declared special member function (Clause 12) shall have an 10431 // exception-specification. [...] 10432 for (const auto &Base : ClassDecl->bases()) { 10433 // Virtual bases are handled below. 10434 if (Base.isVirtual()) 10435 continue; 10436 10437 CXXRecordDecl *BaseClassDecl 10438 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10439 if (CXXConstructorDecl *CopyConstructor = 10440 LookupCopyingConstructor(BaseClassDecl, Quals)) 10441 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10442 } 10443 for (const auto &Base : ClassDecl->vbases()) { 10444 CXXRecordDecl *BaseClassDecl 10445 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10446 if (CXXConstructorDecl *CopyConstructor = 10447 LookupCopyingConstructor(BaseClassDecl, Quals)) 10448 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10449 } 10450 for (const auto *Field : ClassDecl->fields()) { 10451 QualType FieldType = Context.getBaseElementType(Field->getType()); 10452 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10453 if (CXXConstructorDecl *CopyConstructor = 10454 LookupCopyingConstructor(FieldClassDecl, 10455 Quals | FieldType.getCVRQualifiers())) 10456 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10457 } 10458 } 10459 10460 return ExceptSpec; 10461 } 10462 10463 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10464 CXXRecordDecl *ClassDecl) { 10465 // C++ [class.copy]p4: 10466 // If the class definition does not explicitly declare a copy 10467 // constructor, one is declared implicitly. 10468 assert(ClassDecl->needsImplicitCopyConstructor()); 10469 10470 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10471 if (DSM.isAlreadyBeingDeclared()) 10472 return nullptr; 10473 10474 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10475 QualType ArgType = ClassType; 10476 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10477 if (Const) 10478 ArgType = ArgType.withConst(); 10479 ArgType = Context.getLValueReferenceType(ArgType); 10480 10481 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10482 CXXCopyConstructor, 10483 Const); 10484 10485 DeclarationName Name 10486 = Context.DeclarationNames.getCXXConstructorName( 10487 Context.getCanonicalType(ClassType)); 10488 SourceLocation ClassLoc = ClassDecl->getLocation(); 10489 DeclarationNameInfo NameInfo(Name, ClassLoc); 10490 10491 // An implicitly-declared copy constructor is an inline public 10492 // member of its class. 10493 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10494 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10495 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10496 Constexpr); 10497 CopyConstructor->setAccess(AS_public); 10498 CopyConstructor->setDefaulted(); 10499 10500 if (getLangOpts().CUDA) { 10501 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 10502 CopyConstructor, 10503 /* ConstRHS */ Const, 10504 /* Diagnose */ false); 10505 } 10506 10507 // Build an exception specification pointing back at this member. 10508 FunctionProtoType::ExtProtoInfo EPI = 10509 getImplicitMethodEPI(*this, CopyConstructor); 10510 CopyConstructor->setType( 10511 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10512 10513 // Add the parameter to the constructor. 10514 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10515 ClassLoc, ClassLoc, 10516 /*IdentifierInfo=*/nullptr, 10517 ArgType, /*TInfo=*/nullptr, 10518 SC_None, nullptr); 10519 CopyConstructor->setParams(FromParam); 10520 10521 CopyConstructor->setTrivial( 10522 ClassDecl->needsOverloadResolutionForCopyConstructor() 10523 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10524 : ClassDecl->hasTrivialCopyConstructor()); 10525 10526 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10527 SetDeclDeleted(CopyConstructor, ClassLoc); 10528 10529 // Note that we have declared this constructor. 10530 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10531 10532 if (Scope *S = getScopeForContext(ClassDecl)) 10533 PushOnScopeChains(CopyConstructor, S, false); 10534 ClassDecl->addDecl(CopyConstructor); 10535 10536 return CopyConstructor; 10537 } 10538 10539 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10540 CXXConstructorDecl *CopyConstructor) { 10541 assert((CopyConstructor->isDefaulted() && 10542 CopyConstructor->isCopyConstructor() && 10543 !CopyConstructor->doesThisDeclarationHaveABody() && 10544 !CopyConstructor->isDeleted()) && 10545 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10546 10547 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10548 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10549 10550 // C++11 [class.copy]p7: 10551 // The [definition of an implicitly declared copy constructor] is 10552 // deprecated if the class has a user-declared copy assignment operator 10553 // or a user-declared destructor. 10554 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10555 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10556 10557 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10558 DiagnosticErrorTrap Trap(Diags); 10559 10560 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10561 Trap.hasErrorOccurred()) { 10562 Diag(CurrentLocation, diag::note_member_synthesized_at) 10563 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10564 CopyConstructor->setInvalidDecl(); 10565 } else { 10566 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10567 ? CopyConstructor->getLocEnd() 10568 : CopyConstructor->getLocation(); 10569 Sema::CompoundScopeRAII CompoundScope(*this); 10570 CopyConstructor->setBody( 10571 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10572 } 10573 10574 // The exception specification is needed because we are defining the 10575 // function. 10576 ResolveExceptionSpec(CurrentLocation, 10577 CopyConstructor->getType()->castAs<FunctionProtoType>()); 10578 10579 CopyConstructor->markUsed(Context); 10580 MarkVTableUsed(CurrentLocation, ClassDecl); 10581 10582 if (ASTMutationListener *L = getASTMutationListener()) { 10583 L->CompletedImplicitDefinition(CopyConstructor); 10584 } 10585 } 10586 10587 Sema::ImplicitExceptionSpecification 10588 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10589 CXXRecordDecl *ClassDecl = MD->getParent(); 10590 10591 // C++ [except.spec]p14: 10592 // An implicitly declared special member function (Clause 12) shall have an 10593 // exception-specification. [...] 10594 ImplicitExceptionSpecification ExceptSpec(*this); 10595 if (ClassDecl->isInvalidDecl()) 10596 return ExceptSpec; 10597 10598 // Direct base-class constructors. 10599 for (const auto &B : ClassDecl->bases()) { 10600 if (B.isVirtual()) // Handled below. 10601 continue; 10602 10603 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10604 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10605 CXXConstructorDecl *Constructor = 10606 LookupMovingConstructor(BaseClassDecl, 0); 10607 // If this is a deleted function, add it anyway. This might be conformant 10608 // with the standard. This might not. I'm not sure. It might not matter. 10609 if (Constructor) 10610 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10611 } 10612 } 10613 10614 // Virtual base-class constructors. 10615 for (const auto &B : ClassDecl->vbases()) { 10616 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10617 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10618 CXXConstructorDecl *Constructor = 10619 LookupMovingConstructor(BaseClassDecl, 0); 10620 // If this is a deleted function, add it anyway. This might be conformant 10621 // with the standard. This might not. I'm not sure. It might not matter. 10622 if (Constructor) 10623 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10624 } 10625 } 10626 10627 // Field constructors. 10628 for (const auto *F : ClassDecl->fields()) { 10629 QualType FieldType = Context.getBaseElementType(F->getType()); 10630 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10631 CXXConstructorDecl *Constructor = 10632 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10633 // If this is a deleted function, add it anyway. This might be conformant 10634 // with the standard. This might not. I'm not sure. It might not matter. 10635 // In particular, the problem is that this function never gets called. It 10636 // might just be ill-formed because this function attempts to refer to 10637 // a deleted function here. 10638 if (Constructor) 10639 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10640 } 10641 } 10642 10643 return ExceptSpec; 10644 } 10645 10646 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10647 CXXRecordDecl *ClassDecl) { 10648 assert(ClassDecl->needsImplicitMoveConstructor()); 10649 10650 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10651 if (DSM.isAlreadyBeingDeclared()) 10652 return nullptr; 10653 10654 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10655 QualType ArgType = Context.getRValueReferenceType(ClassType); 10656 10657 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10658 CXXMoveConstructor, 10659 false); 10660 10661 DeclarationName Name 10662 = Context.DeclarationNames.getCXXConstructorName( 10663 Context.getCanonicalType(ClassType)); 10664 SourceLocation ClassLoc = ClassDecl->getLocation(); 10665 DeclarationNameInfo NameInfo(Name, ClassLoc); 10666 10667 // C++11 [class.copy]p11: 10668 // An implicitly-declared copy/move constructor is an inline public 10669 // member of its class. 10670 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10671 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10672 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10673 Constexpr); 10674 MoveConstructor->setAccess(AS_public); 10675 MoveConstructor->setDefaulted(); 10676 10677 if (getLangOpts().CUDA) { 10678 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 10679 MoveConstructor, 10680 /* ConstRHS */ false, 10681 /* Diagnose */ false); 10682 } 10683 10684 // Build an exception specification pointing back at this member. 10685 FunctionProtoType::ExtProtoInfo EPI = 10686 getImplicitMethodEPI(*this, MoveConstructor); 10687 MoveConstructor->setType( 10688 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10689 10690 // Add the parameter to the constructor. 10691 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10692 ClassLoc, ClassLoc, 10693 /*IdentifierInfo=*/nullptr, 10694 ArgType, /*TInfo=*/nullptr, 10695 SC_None, nullptr); 10696 MoveConstructor->setParams(FromParam); 10697 10698 MoveConstructor->setTrivial( 10699 ClassDecl->needsOverloadResolutionForMoveConstructor() 10700 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10701 : ClassDecl->hasTrivialMoveConstructor()); 10702 10703 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10704 ClassDecl->setImplicitMoveConstructorIsDeleted(); 10705 SetDeclDeleted(MoveConstructor, ClassLoc); 10706 } 10707 10708 // Note that we have declared this constructor. 10709 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10710 10711 if (Scope *S = getScopeForContext(ClassDecl)) 10712 PushOnScopeChains(MoveConstructor, S, false); 10713 ClassDecl->addDecl(MoveConstructor); 10714 10715 return MoveConstructor; 10716 } 10717 10718 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 10719 CXXConstructorDecl *MoveConstructor) { 10720 assert((MoveConstructor->isDefaulted() && 10721 MoveConstructor->isMoveConstructor() && 10722 !MoveConstructor->doesThisDeclarationHaveABody() && 10723 !MoveConstructor->isDeleted()) && 10724 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 10725 10726 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 10727 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 10728 10729 SynthesizedFunctionScope Scope(*this, MoveConstructor); 10730 DiagnosticErrorTrap Trap(Diags); 10731 10732 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10733 Trap.hasErrorOccurred()) { 10734 Diag(CurrentLocation, diag::note_member_synthesized_at) 10735 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10736 MoveConstructor->setInvalidDecl(); 10737 } else { 10738 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 10739 ? MoveConstructor->getLocEnd() 10740 : MoveConstructor->getLocation(); 10741 Sema::CompoundScopeRAII CompoundScope(*this); 10742 MoveConstructor->setBody(ActOnCompoundStmt( 10743 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 10744 } 10745 10746 // The exception specification is needed because we are defining the 10747 // function. 10748 ResolveExceptionSpec(CurrentLocation, 10749 MoveConstructor->getType()->castAs<FunctionProtoType>()); 10750 10751 MoveConstructor->markUsed(Context); 10752 MarkVTableUsed(CurrentLocation, ClassDecl); 10753 10754 if (ASTMutationListener *L = getASTMutationListener()) { 10755 L->CompletedImplicitDefinition(MoveConstructor); 10756 } 10757 } 10758 10759 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10760 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10761 } 10762 10763 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10764 SourceLocation CurrentLocation, 10765 CXXConversionDecl *Conv) { 10766 CXXRecordDecl *Lambda = Conv->getParent(); 10767 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 10768 // If we are defining a specialization of a conversion to function-ptr 10769 // cache the deduced template arguments for this specialization 10770 // so that we can use them to retrieve the corresponding call-operator 10771 // and static-invoker. 10772 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 10773 10774 // Retrieve the corresponding call-operator specialization. 10775 if (Lambda->isGenericLambda()) { 10776 assert(Conv->isFunctionTemplateSpecialization()); 10777 FunctionTemplateDecl *CallOpTemplate = 10778 CallOp->getDescribedFunctionTemplate(); 10779 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 10780 void *InsertPos = nullptr; 10781 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 10782 DeducedTemplateArgs->asArray(), 10783 InsertPos); 10784 assert(CallOpSpec && 10785 "Conversion operator must have a corresponding call operator"); 10786 CallOp = cast<CXXMethodDecl>(CallOpSpec); 10787 } 10788 // Mark the call operator referenced (and add to pending instantiations 10789 // if necessary). 10790 // For both the conversion and static-invoker template specializations 10791 // we construct their body's in this function, so no need to add them 10792 // to the PendingInstantiations. 10793 MarkFunctionReferenced(CurrentLocation, CallOp); 10794 10795 SynthesizedFunctionScope Scope(*this, Conv); 10796 DiagnosticErrorTrap Trap(Diags); 10797 10798 // Retrieve the static invoker... 10799 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 10800 // ... and get the corresponding specialization for a generic lambda. 10801 if (Lambda->isGenericLambda()) { 10802 assert(DeducedTemplateArgs && 10803 "Must have deduced template arguments from Conversion Operator"); 10804 FunctionTemplateDecl *InvokeTemplate = 10805 Invoker->getDescribedFunctionTemplate(); 10806 void *InsertPos = nullptr; 10807 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 10808 DeducedTemplateArgs->asArray(), 10809 InsertPos); 10810 assert(InvokeSpec && 10811 "Must have a corresponding static invoker specialization"); 10812 Invoker = cast<CXXMethodDecl>(InvokeSpec); 10813 } 10814 // Construct the body of the conversion function { return __invoke; }. 10815 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 10816 VK_LValue, Conv->getLocation()).get(); 10817 assert(FunctionRef && "Can't refer to __invoke function?"); 10818 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 10819 Conv->setBody(new (Context) CompoundStmt(Context, Return, 10820 Conv->getLocation(), 10821 Conv->getLocation())); 10822 10823 Conv->markUsed(Context); 10824 Conv->setReferenced(); 10825 10826 // Fill in the __invoke function with a dummy implementation. IR generation 10827 // will fill in the actual details. 10828 Invoker->markUsed(Context); 10829 Invoker->setReferenced(); 10830 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 10831 10832 if (ASTMutationListener *L = getASTMutationListener()) { 10833 L->CompletedImplicitDefinition(Conv); 10834 L->CompletedImplicitDefinition(Invoker); 10835 } 10836 } 10837 10838 10839 10840 void Sema::DefineImplicitLambdaToBlockPointerConversion( 10841 SourceLocation CurrentLocation, 10842 CXXConversionDecl *Conv) 10843 { 10844 assert(!Conv->getParent()->isGenericLambda()); 10845 10846 Conv->markUsed(Context); 10847 10848 SynthesizedFunctionScope Scope(*this, Conv); 10849 DiagnosticErrorTrap Trap(Diags); 10850 10851 // Copy-initialize the lambda object as needed to capture it. 10852 Expr *This = ActOnCXXThis(CurrentLocation).get(); 10853 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 10854 10855 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 10856 Conv->getLocation(), 10857 Conv, DerefThis); 10858 10859 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 10860 // behavior. Note that only the general conversion function does this 10861 // (since it's unusable otherwise); in the case where we inline the 10862 // block literal, it has block literal lifetime semantics. 10863 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 10864 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 10865 CK_CopyAndAutoreleaseBlockObject, 10866 BuildBlock.get(), nullptr, VK_RValue); 10867 10868 if (BuildBlock.isInvalid()) { 10869 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10870 Conv->setInvalidDecl(); 10871 return; 10872 } 10873 10874 // Create the return statement that returns the block from the conversion 10875 // function. 10876 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 10877 if (Return.isInvalid()) { 10878 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10879 Conv->setInvalidDecl(); 10880 return; 10881 } 10882 10883 // Set the body of the conversion function. 10884 Stmt *ReturnS = Return.get(); 10885 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 10886 Conv->getLocation(), 10887 Conv->getLocation())); 10888 10889 // We're done; notify the mutation listener, if any. 10890 if (ASTMutationListener *L = getASTMutationListener()) { 10891 L->CompletedImplicitDefinition(Conv); 10892 } 10893 } 10894 10895 /// \brief Determine whether the given list arguments contains exactly one 10896 /// "real" (non-default) argument. 10897 static bool hasOneRealArgument(MultiExprArg Args) { 10898 switch (Args.size()) { 10899 case 0: 10900 return false; 10901 10902 default: 10903 if (!Args[1]->isDefaultArgument()) 10904 return false; 10905 10906 // fall through 10907 case 1: 10908 return !Args[0]->isDefaultArgument(); 10909 } 10910 10911 return false; 10912 } 10913 10914 ExprResult 10915 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10916 CXXConstructorDecl *Constructor, 10917 MultiExprArg ExprArgs, 10918 bool HadMultipleCandidates, 10919 bool IsListInitialization, 10920 bool IsStdInitListInitialization, 10921 bool RequiresZeroInit, 10922 unsigned ConstructKind, 10923 SourceRange ParenRange) { 10924 bool Elidable = false; 10925 10926 // C++0x [class.copy]p34: 10927 // When certain criteria are met, an implementation is allowed to 10928 // omit the copy/move construction of a class object, even if the 10929 // copy/move constructor and/or destructor for the object have 10930 // side effects. [...] 10931 // - when a temporary class object that has not been bound to a 10932 // reference (12.2) would be copied/moved to a class object 10933 // with the same cv-unqualified type, the copy/move operation 10934 // can be omitted by constructing the temporary object 10935 // directly into the target of the omitted copy/move 10936 if (ConstructKind == CXXConstructExpr::CK_Complete && 10937 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10938 Expr *SubExpr = ExprArgs[0]; 10939 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10940 } 10941 10942 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10943 Elidable, ExprArgs, HadMultipleCandidates, 10944 IsListInitialization, 10945 IsStdInitListInitialization, RequiresZeroInit, 10946 ConstructKind, ParenRange); 10947 } 10948 10949 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 10950 /// including handling of its default argument expressions. 10951 ExprResult 10952 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10953 CXXConstructorDecl *Constructor, bool Elidable, 10954 MultiExprArg ExprArgs, 10955 bool HadMultipleCandidates, 10956 bool IsListInitialization, 10957 bool IsStdInitListInitialization, 10958 bool RequiresZeroInit, 10959 unsigned ConstructKind, 10960 SourceRange ParenRange) { 10961 MarkFunctionReferenced(ConstructLoc, Constructor); 10962 return CXXConstructExpr::Create( 10963 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 10964 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 10965 RequiresZeroInit, 10966 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10967 ParenRange); 10968 } 10969 10970 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10971 if (VD->isInvalidDecl()) return; 10972 10973 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10974 if (ClassDecl->isInvalidDecl()) return; 10975 if (ClassDecl->hasIrrelevantDestructor()) return; 10976 if (ClassDecl->isDependentContext()) return; 10977 10978 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10979 MarkFunctionReferenced(VD->getLocation(), Destructor); 10980 CheckDestructorAccess(VD->getLocation(), Destructor, 10981 PDiag(diag::err_access_dtor_var) 10982 << VD->getDeclName() 10983 << VD->getType()); 10984 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10985 10986 if (Destructor->isTrivial()) return; 10987 if (!VD->hasGlobalStorage()) return; 10988 10989 // Emit warning for non-trivial dtor in global scope (a real global, 10990 // class-static, function-static). 10991 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10992 10993 // TODO: this should be re-enabled for static locals by !CXAAtExit 10994 if (!VD->isStaticLocal()) 10995 Diag(VD->getLocation(), diag::warn_global_destructor); 10996 } 10997 10998 /// \brief Given a constructor and the set of arguments provided for the 10999 /// constructor, convert the arguments and add any required default arguments 11000 /// to form a proper call to this constructor. 11001 /// 11002 /// \returns true if an error occurred, false otherwise. 11003 bool 11004 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 11005 MultiExprArg ArgsPtr, 11006 SourceLocation Loc, 11007 SmallVectorImpl<Expr*> &ConvertedArgs, 11008 bool AllowExplicit, 11009 bool IsListInitialization) { 11010 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 11011 unsigned NumArgs = ArgsPtr.size(); 11012 Expr **Args = ArgsPtr.data(); 11013 11014 const FunctionProtoType *Proto 11015 = Constructor->getType()->getAs<FunctionProtoType>(); 11016 assert(Proto && "Constructor without a prototype?"); 11017 unsigned NumParams = Proto->getNumParams(); 11018 11019 // If too few arguments are available, we'll fill in the rest with defaults. 11020 if (NumArgs < NumParams) 11021 ConvertedArgs.reserve(NumParams); 11022 else 11023 ConvertedArgs.reserve(NumArgs); 11024 11025 VariadicCallType CallType = 11026 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 11027 SmallVector<Expr *, 8> AllArgs; 11028 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 11029 Proto, 0, 11030 llvm::makeArrayRef(Args, NumArgs), 11031 AllArgs, 11032 CallType, AllowExplicit, 11033 IsListInitialization); 11034 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 11035 11036 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 11037 11038 CheckConstructorCall(Constructor, 11039 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 11040 Proto, Loc); 11041 11042 return Invalid; 11043 } 11044 11045 static inline bool 11046 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 11047 const FunctionDecl *FnDecl) { 11048 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 11049 if (isa<NamespaceDecl>(DC)) { 11050 return SemaRef.Diag(FnDecl->getLocation(), 11051 diag::err_operator_new_delete_declared_in_namespace) 11052 << FnDecl->getDeclName(); 11053 } 11054 11055 if (isa<TranslationUnitDecl>(DC) && 11056 FnDecl->getStorageClass() == SC_Static) { 11057 return SemaRef.Diag(FnDecl->getLocation(), 11058 diag::err_operator_new_delete_declared_static) 11059 << FnDecl->getDeclName(); 11060 } 11061 11062 return false; 11063 } 11064 11065 static inline bool 11066 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 11067 CanQualType ExpectedResultType, 11068 CanQualType ExpectedFirstParamType, 11069 unsigned DependentParamTypeDiag, 11070 unsigned InvalidParamTypeDiag) { 11071 QualType ResultType = 11072 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 11073 11074 // Check that the result type is not dependent. 11075 if (ResultType->isDependentType()) 11076 return SemaRef.Diag(FnDecl->getLocation(), 11077 diag::err_operator_new_delete_dependent_result_type) 11078 << FnDecl->getDeclName() << ExpectedResultType; 11079 11080 // Check that the result type is what we expect. 11081 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 11082 return SemaRef.Diag(FnDecl->getLocation(), 11083 diag::err_operator_new_delete_invalid_result_type) 11084 << FnDecl->getDeclName() << ExpectedResultType; 11085 11086 // A function template must have at least 2 parameters. 11087 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 11088 return SemaRef.Diag(FnDecl->getLocation(), 11089 diag::err_operator_new_delete_template_too_few_parameters) 11090 << FnDecl->getDeclName(); 11091 11092 // The function decl must have at least 1 parameter. 11093 if (FnDecl->getNumParams() == 0) 11094 return SemaRef.Diag(FnDecl->getLocation(), 11095 diag::err_operator_new_delete_too_few_parameters) 11096 << FnDecl->getDeclName(); 11097 11098 // Check the first parameter type is not dependent. 11099 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 11100 if (FirstParamType->isDependentType()) 11101 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 11102 << FnDecl->getDeclName() << ExpectedFirstParamType; 11103 11104 // Check that the first parameter type is what we expect. 11105 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 11106 ExpectedFirstParamType) 11107 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 11108 << FnDecl->getDeclName() << ExpectedFirstParamType; 11109 11110 return false; 11111 } 11112 11113 static bool 11114 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 11115 // C++ [basic.stc.dynamic.allocation]p1: 11116 // A program is ill-formed if an allocation function is declared in a 11117 // namespace scope other than global scope or declared static in global 11118 // scope. 11119 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11120 return true; 11121 11122 CanQualType SizeTy = 11123 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 11124 11125 // C++ [basic.stc.dynamic.allocation]p1: 11126 // The return type shall be void*. The first parameter shall have type 11127 // std::size_t. 11128 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 11129 SizeTy, 11130 diag::err_operator_new_dependent_param_type, 11131 diag::err_operator_new_param_type)) 11132 return true; 11133 11134 // C++ [basic.stc.dynamic.allocation]p1: 11135 // The first parameter shall not have an associated default argument. 11136 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 11137 return SemaRef.Diag(FnDecl->getLocation(), 11138 diag::err_operator_new_default_arg) 11139 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 11140 11141 return false; 11142 } 11143 11144 static bool 11145 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 11146 // C++ [basic.stc.dynamic.deallocation]p1: 11147 // A program is ill-formed if deallocation functions are declared in a 11148 // namespace scope other than global scope or declared static in global 11149 // scope. 11150 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11151 return true; 11152 11153 // C++ [basic.stc.dynamic.deallocation]p2: 11154 // Each deallocation function shall return void and its first parameter 11155 // shall be void*. 11156 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 11157 SemaRef.Context.VoidPtrTy, 11158 diag::err_operator_delete_dependent_param_type, 11159 diag::err_operator_delete_param_type)) 11160 return true; 11161 11162 return false; 11163 } 11164 11165 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 11166 /// of this overloaded operator is well-formed. If so, returns false; 11167 /// otherwise, emits appropriate diagnostics and returns true. 11168 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 11169 assert(FnDecl && FnDecl->isOverloadedOperator() && 11170 "Expected an overloaded operator declaration"); 11171 11172 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 11173 11174 // C++ [over.oper]p5: 11175 // The allocation and deallocation functions, operator new, 11176 // operator new[], operator delete and operator delete[], are 11177 // described completely in 3.7.3. The attributes and restrictions 11178 // found in the rest of this subclause do not apply to them unless 11179 // explicitly stated in 3.7.3. 11180 if (Op == OO_Delete || Op == OO_Array_Delete) 11181 return CheckOperatorDeleteDeclaration(*this, FnDecl); 11182 11183 if (Op == OO_New || Op == OO_Array_New) 11184 return CheckOperatorNewDeclaration(*this, FnDecl); 11185 11186 // C++ [over.oper]p6: 11187 // An operator function shall either be a non-static member 11188 // function or be a non-member function and have at least one 11189 // parameter whose type is a class, a reference to a class, an 11190 // enumeration, or a reference to an enumeration. 11191 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 11192 if (MethodDecl->isStatic()) 11193 return Diag(FnDecl->getLocation(), 11194 diag::err_operator_overload_static) << FnDecl->getDeclName(); 11195 } else { 11196 bool ClassOrEnumParam = false; 11197 for (auto Param : FnDecl->params()) { 11198 QualType ParamType = Param->getType().getNonReferenceType(); 11199 if (ParamType->isDependentType() || ParamType->isRecordType() || 11200 ParamType->isEnumeralType()) { 11201 ClassOrEnumParam = true; 11202 break; 11203 } 11204 } 11205 11206 if (!ClassOrEnumParam) 11207 return Diag(FnDecl->getLocation(), 11208 diag::err_operator_overload_needs_class_or_enum) 11209 << FnDecl->getDeclName(); 11210 } 11211 11212 // C++ [over.oper]p8: 11213 // An operator function cannot have default arguments (8.3.6), 11214 // except where explicitly stated below. 11215 // 11216 // Only the function-call operator allows default arguments 11217 // (C++ [over.call]p1). 11218 if (Op != OO_Call) { 11219 for (auto Param : FnDecl->params()) { 11220 if (Param->hasDefaultArg()) 11221 return Diag(Param->getLocation(), 11222 diag::err_operator_overload_default_arg) 11223 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 11224 } 11225 } 11226 11227 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 11228 { false, false, false } 11229 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 11230 , { Unary, Binary, MemberOnly } 11231 #include "clang/Basic/OperatorKinds.def" 11232 }; 11233 11234 bool CanBeUnaryOperator = OperatorUses[Op][0]; 11235 bool CanBeBinaryOperator = OperatorUses[Op][1]; 11236 bool MustBeMemberOperator = OperatorUses[Op][2]; 11237 11238 // C++ [over.oper]p8: 11239 // [...] Operator functions cannot have more or fewer parameters 11240 // than the number required for the corresponding operator, as 11241 // described in the rest of this subclause. 11242 unsigned NumParams = FnDecl->getNumParams() 11243 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 11244 if (Op != OO_Call && 11245 ((NumParams == 1 && !CanBeUnaryOperator) || 11246 (NumParams == 2 && !CanBeBinaryOperator) || 11247 (NumParams < 1) || (NumParams > 2))) { 11248 // We have the wrong number of parameters. 11249 unsigned ErrorKind; 11250 if (CanBeUnaryOperator && CanBeBinaryOperator) { 11251 ErrorKind = 2; // 2 -> unary or binary. 11252 } else if (CanBeUnaryOperator) { 11253 ErrorKind = 0; // 0 -> unary 11254 } else { 11255 assert(CanBeBinaryOperator && 11256 "All non-call overloaded operators are unary or binary!"); 11257 ErrorKind = 1; // 1 -> binary 11258 } 11259 11260 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 11261 << FnDecl->getDeclName() << NumParams << ErrorKind; 11262 } 11263 11264 // Overloaded operators other than operator() cannot be variadic. 11265 if (Op != OO_Call && 11266 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 11267 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 11268 << FnDecl->getDeclName(); 11269 } 11270 11271 // Some operators must be non-static member functions. 11272 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 11273 return Diag(FnDecl->getLocation(), 11274 diag::err_operator_overload_must_be_member) 11275 << FnDecl->getDeclName(); 11276 } 11277 11278 // C++ [over.inc]p1: 11279 // The user-defined function called operator++ implements the 11280 // prefix and postfix ++ operator. If this function is a member 11281 // function with no parameters, or a non-member function with one 11282 // parameter of class or enumeration type, it defines the prefix 11283 // increment operator ++ for objects of that type. If the function 11284 // is a member function with one parameter (which shall be of type 11285 // int) or a non-member function with two parameters (the second 11286 // of which shall be of type int), it defines the postfix 11287 // increment operator ++ for objects of that type. 11288 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11289 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11290 QualType ParamType = LastParam->getType(); 11291 11292 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11293 !ParamType->isDependentType()) 11294 return Diag(LastParam->getLocation(), 11295 diag::err_operator_overload_post_incdec_must_be_int) 11296 << LastParam->getType() << (Op == OO_MinusMinus); 11297 } 11298 11299 return false; 11300 } 11301 11302 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11303 /// of this literal operator function is well-formed. If so, returns 11304 /// false; otherwise, emits appropriate diagnostics and returns true. 11305 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11306 if (isa<CXXMethodDecl>(FnDecl)) { 11307 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11308 << FnDecl->getDeclName(); 11309 return true; 11310 } 11311 11312 if (FnDecl->isExternC()) { 11313 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11314 return true; 11315 } 11316 11317 bool Valid = false; 11318 11319 // This might be the definition of a literal operator template. 11320 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11321 // This might be a specialization of a literal operator template. 11322 if (!TpDecl) 11323 TpDecl = FnDecl->getPrimaryTemplate(); 11324 11325 // template <char...> type operator "" name() and 11326 // template <class T, T...> type operator "" name() are the only valid 11327 // template signatures, and the only valid signatures with no parameters. 11328 if (TpDecl) { 11329 if (FnDecl->param_size() == 0) { 11330 // Must have one or two template parameters 11331 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11332 if (Params->size() == 1) { 11333 NonTypeTemplateParmDecl *PmDecl = 11334 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11335 11336 // The template parameter must be a char parameter pack. 11337 if (PmDecl && PmDecl->isTemplateParameterPack() && 11338 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11339 Valid = true; 11340 } else if (Params->size() == 2) { 11341 TemplateTypeParmDecl *PmType = 11342 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11343 NonTypeTemplateParmDecl *PmArgs = 11344 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11345 11346 // The second template parameter must be a parameter pack with the 11347 // first template parameter as its type. 11348 if (PmType && PmArgs && 11349 !PmType->isTemplateParameterPack() && 11350 PmArgs->isTemplateParameterPack()) { 11351 const TemplateTypeParmType *TArgs = 11352 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11353 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11354 TArgs->getIndex() == PmType->getIndex()) { 11355 Valid = true; 11356 if (ActiveTemplateInstantiations.empty()) 11357 Diag(FnDecl->getLocation(), 11358 diag::ext_string_literal_operator_template); 11359 } 11360 } 11361 } 11362 } 11363 } else if (FnDecl->param_size()) { 11364 // Check the first parameter 11365 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11366 11367 QualType T = (*Param)->getType().getUnqualifiedType(); 11368 11369 // unsigned long long int, long double, and any character type are allowed 11370 // as the only parameters. 11371 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11372 Context.hasSameType(T, Context.LongDoubleTy) || 11373 Context.hasSameType(T, Context.CharTy) || 11374 Context.hasSameType(T, Context.WideCharTy) || 11375 Context.hasSameType(T, Context.Char16Ty) || 11376 Context.hasSameType(T, Context.Char32Ty)) { 11377 if (++Param == FnDecl->param_end()) 11378 Valid = true; 11379 goto FinishedParams; 11380 } 11381 11382 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11383 const PointerType *PT = T->getAs<PointerType>(); 11384 if (!PT) 11385 goto FinishedParams; 11386 T = PT->getPointeeType(); 11387 if (!T.isConstQualified() || T.isVolatileQualified()) 11388 goto FinishedParams; 11389 T = T.getUnqualifiedType(); 11390 11391 // Move on to the second parameter; 11392 ++Param; 11393 11394 // If there is no second parameter, the first must be a const char * 11395 if (Param == FnDecl->param_end()) { 11396 if (Context.hasSameType(T, Context.CharTy)) 11397 Valid = true; 11398 goto FinishedParams; 11399 } 11400 11401 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11402 // are allowed as the first parameter to a two-parameter function 11403 if (!(Context.hasSameType(T, Context.CharTy) || 11404 Context.hasSameType(T, Context.WideCharTy) || 11405 Context.hasSameType(T, Context.Char16Ty) || 11406 Context.hasSameType(T, Context.Char32Ty))) 11407 goto FinishedParams; 11408 11409 // The second and final parameter must be an std::size_t 11410 T = (*Param)->getType().getUnqualifiedType(); 11411 if (Context.hasSameType(T, Context.getSizeType()) && 11412 ++Param == FnDecl->param_end()) 11413 Valid = true; 11414 } 11415 11416 // FIXME: This diagnostic is absolutely terrible. 11417 FinishedParams: 11418 if (!Valid) { 11419 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11420 << FnDecl->getDeclName(); 11421 return true; 11422 } 11423 11424 // A parameter-declaration-clause containing a default argument is not 11425 // equivalent to any of the permitted forms. 11426 for (auto Param : FnDecl->params()) { 11427 if (Param->hasDefaultArg()) { 11428 Diag(Param->getDefaultArgRange().getBegin(), 11429 diag::err_literal_operator_default_argument) 11430 << Param->getDefaultArgRange(); 11431 break; 11432 } 11433 } 11434 11435 StringRef LiteralName 11436 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11437 if (LiteralName[0] != '_') { 11438 // C++11 [usrlit.suffix]p1: 11439 // Literal suffix identifiers that do not start with an underscore 11440 // are reserved for future standardization. 11441 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11442 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11443 } 11444 11445 return false; 11446 } 11447 11448 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11449 /// linkage specification, including the language and (if present) 11450 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11451 /// language string literal. LBraceLoc, if valid, provides the location of 11452 /// the '{' brace. Otherwise, this linkage specification does not 11453 /// have any braces. 11454 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11455 Expr *LangStr, 11456 SourceLocation LBraceLoc) { 11457 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11458 if (!Lit->isAscii()) { 11459 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11460 << LangStr->getSourceRange(); 11461 return nullptr; 11462 } 11463 11464 StringRef Lang = Lit->getString(); 11465 LinkageSpecDecl::LanguageIDs Language; 11466 if (Lang == "C") 11467 Language = LinkageSpecDecl::lang_c; 11468 else if (Lang == "C++") 11469 Language = LinkageSpecDecl::lang_cxx; 11470 else { 11471 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11472 << LangStr->getSourceRange(); 11473 return nullptr; 11474 } 11475 11476 // FIXME: Add all the various semantics of linkage specifications 11477 11478 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11479 LangStr->getExprLoc(), Language, 11480 LBraceLoc.isValid()); 11481 CurContext->addDecl(D); 11482 PushDeclContext(S, D); 11483 return D; 11484 } 11485 11486 /// ActOnFinishLinkageSpecification - Complete the definition of 11487 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11488 /// valid, it's the position of the closing '}' brace in a linkage 11489 /// specification that uses braces. 11490 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11491 Decl *LinkageSpec, 11492 SourceLocation RBraceLoc) { 11493 if (RBraceLoc.isValid()) { 11494 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11495 LSDecl->setRBraceLoc(RBraceLoc); 11496 } 11497 PopDeclContext(); 11498 return LinkageSpec; 11499 } 11500 11501 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11502 AttributeList *AttrList, 11503 SourceLocation SemiLoc) { 11504 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11505 // Attribute declarations appertain to empty declaration so we handle 11506 // them here. 11507 if (AttrList) 11508 ProcessDeclAttributeList(S, ED, AttrList); 11509 11510 CurContext->addDecl(ED); 11511 return ED; 11512 } 11513 11514 /// \brief Perform semantic analysis for the variable declaration that 11515 /// occurs within a C++ catch clause, returning the newly-created 11516 /// variable. 11517 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11518 TypeSourceInfo *TInfo, 11519 SourceLocation StartLoc, 11520 SourceLocation Loc, 11521 IdentifierInfo *Name) { 11522 bool Invalid = false; 11523 QualType ExDeclType = TInfo->getType(); 11524 11525 // Arrays and functions decay. 11526 if (ExDeclType->isArrayType()) 11527 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11528 else if (ExDeclType->isFunctionType()) 11529 ExDeclType = Context.getPointerType(ExDeclType); 11530 11531 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11532 // The exception-declaration shall not denote a pointer or reference to an 11533 // incomplete type, other than [cv] void*. 11534 // N2844 forbids rvalue references. 11535 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11536 Diag(Loc, diag::err_catch_rvalue_ref); 11537 Invalid = true; 11538 } 11539 11540 QualType BaseType = ExDeclType; 11541 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11542 unsigned DK = diag::err_catch_incomplete; 11543 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11544 BaseType = Ptr->getPointeeType(); 11545 Mode = 1; 11546 DK = diag::err_catch_incomplete_ptr; 11547 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11548 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11549 BaseType = Ref->getPointeeType(); 11550 Mode = 2; 11551 DK = diag::err_catch_incomplete_ref; 11552 } 11553 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11554 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11555 Invalid = true; 11556 11557 if (!Invalid && !ExDeclType->isDependentType() && 11558 RequireNonAbstractType(Loc, ExDeclType, 11559 diag::err_abstract_type_in_decl, 11560 AbstractVariableType)) 11561 Invalid = true; 11562 11563 // Only the non-fragile NeXT runtime currently supports C++ catches 11564 // of ObjC types, and no runtime supports catching ObjC types by value. 11565 if (!Invalid && getLangOpts().ObjC1) { 11566 QualType T = ExDeclType; 11567 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11568 T = RT->getPointeeType(); 11569 11570 if (T->isObjCObjectType()) { 11571 Diag(Loc, diag::err_objc_object_catch); 11572 Invalid = true; 11573 } else if (T->isObjCObjectPointerType()) { 11574 // FIXME: should this be a test for macosx-fragile specifically? 11575 if (getLangOpts().ObjCRuntime.isFragile()) 11576 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11577 } 11578 } 11579 11580 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11581 ExDeclType, TInfo, SC_None); 11582 ExDecl->setExceptionVariable(true); 11583 11584 // In ARC, infer 'retaining' for variables of retainable type. 11585 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11586 Invalid = true; 11587 11588 if (!Invalid && !ExDeclType->isDependentType()) { 11589 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11590 // Insulate this from anything else we might currently be parsing. 11591 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11592 11593 // C++ [except.handle]p16: 11594 // The object declared in an exception-declaration or, if the 11595 // exception-declaration does not specify a name, a temporary (12.2) is 11596 // copy-initialized (8.5) from the exception object. [...] 11597 // The object is destroyed when the handler exits, after the destruction 11598 // of any automatic objects initialized within the handler. 11599 // 11600 // We just pretend to initialize the object with itself, then make sure 11601 // it can be destroyed later. 11602 QualType initType = ExDeclType; 11603 11604 InitializedEntity entity = 11605 InitializedEntity::InitializeVariable(ExDecl); 11606 InitializationKind initKind = 11607 InitializationKind::CreateCopy(Loc, SourceLocation()); 11608 11609 Expr *opaqueValue = 11610 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11611 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11612 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11613 if (result.isInvalid()) 11614 Invalid = true; 11615 else { 11616 // If the constructor used was non-trivial, set this as the 11617 // "initializer". 11618 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 11619 if (!construct->getConstructor()->isTrivial()) { 11620 Expr *init = MaybeCreateExprWithCleanups(construct); 11621 ExDecl->setInit(init); 11622 } 11623 11624 // And make sure it's destructable. 11625 FinalizeVarWithDestructor(ExDecl, recordType); 11626 } 11627 } 11628 } 11629 11630 if (Invalid) 11631 ExDecl->setInvalidDecl(); 11632 11633 return ExDecl; 11634 } 11635 11636 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11637 /// handler. 11638 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11639 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11640 bool Invalid = D.isInvalidType(); 11641 11642 // Check for unexpanded parameter packs. 11643 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11644 UPPC_ExceptionType)) { 11645 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11646 D.getIdentifierLoc()); 11647 Invalid = true; 11648 } 11649 11650 IdentifierInfo *II = D.getIdentifier(); 11651 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11652 LookupOrdinaryName, 11653 ForRedeclaration)) { 11654 // The scope should be freshly made just for us. There is just no way 11655 // it contains any previous declaration, except for function parameters in 11656 // a function-try-block's catch statement. 11657 assert(!S->isDeclScope(PrevDecl)); 11658 if (isDeclInScope(PrevDecl, CurContext, S)) { 11659 Diag(D.getIdentifierLoc(), diag::err_redefinition) 11660 << D.getIdentifier(); 11661 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11662 Invalid = true; 11663 } else if (PrevDecl->isTemplateParameter()) 11664 // Maybe we will complain about the shadowed template parameter. 11665 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11666 } 11667 11668 if (D.getCXXScopeSpec().isSet() && !Invalid) { 11669 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 11670 << D.getCXXScopeSpec().getRange(); 11671 Invalid = true; 11672 } 11673 11674 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 11675 D.getLocStart(), 11676 D.getIdentifierLoc(), 11677 D.getIdentifier()); 11678 if (Invalid) 11679 ExDecl->setInvalidDecl(); 11680 11681 // Add the exception declaration into this scope. 11682 if (II) 11683 PushOnScopeChains(ExDecl, S); 11684 else 11685 CurContext->addDecl(ExDecl); 11686 11687 ProcessDeclAttributes(S, ExDecl, D); 11688 return ExDecl; 11689 } 11690 11691 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11692 Expr *AssertExpr, 11693 Expr *AssertMessageExpr, 11694 SourceLocation RParenLoc) { 11695 StringLiteral *AssertMessage = 11696 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 11697 11698 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 11699 return nullptr; 11700 11701 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 11702 AssertMessage, RParenLoc, false); 11703 } 11704 11705 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11706 Expr *AssertExpr, 11707 StringLiteral *AssertMessage, 11708 SourceLocation RParenLoc, 11709 bool Failed) { 11710 assert(AssertExpr != nullptr && "Expected non-null condition"); 11711 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 11712 !Failed) { 11713 // In a static_assert-declaration, the constant-expression shall be a 11714 // constant expression that can be contextually converted to bool. 11715 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 11716 if (Converted.isInvalid()) 11717 Failed = true; 11718 11719 llvm::APSInt Cond; 11720 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 11721 diag::err_static_assert_expression_is_not_constant, 11722 /*AllowFold=*/false).isInvalid()) 11723 Failed = true; 11724 11725 if (!Failed && !Cond) { 11726 SmallString<256> MsgBuffer; 11727 llvm::raw_svector_ostream Msg(MsgBuffer); 11728 if (AssertMessage) 11729 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 11730 Diag(StaticAssertLoc, diag::err_static_assert_failed) 11731 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 11732 Failed = true; 11733 } 11734 } 11735 11736 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 11737 AssertExpr, AssertMessage, RParenLoc, 11738 Failed); 11739 11740 CurContext->addDecl(Decl); 11741 return Decl; 11742 } 11743 11744 /// \brief Perform semantic analysis of the given friend type declaration. 11745 /// 11746 /// \returns A friend declaration that. 11747 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 11748 SourceLocation FriendLoc, 11749 TypeSourceInfo *TSInfo) { 11750 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 11751 11752 QualType T = TSInfo->getType(); 11753 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 11754 11755 // C++03 [class.friend]p2: 11756 // An elaborated-type-specifier shall be used in a friend declaration 11757 // for a class.* 11758 // 11759 // * The class-key of the elaborated-type-specifier is required. 11760 if (!ActiveTemplateInstantiations.empty()) { 11761 // Do not complain about the form of friend template types during 11762 // template instantiation; we will already have complained when the 11763 // template was declared. 11764 } else { 11765 if (!T->isElaboratedTypeSpecifier()) { 11766 // If we evaluated the type to a record type, suggest putting 11767 // a tag in front. 11768 if (const RecordType *RT = T->getAs<RecordType>()) { 11769 RecordDecl *RD = RT->getDecl(); 11770 11771 SmallString<16> InsertionText(" "); 11772 InsertionText += RD->getKindName(); 11773 11774 Diag(TypeRange.getBegin(), 11775 getLangOpts().CPlusPlus11 ? 11776 diag::warn_cxx98_compat_unelaborated_friend_type : 11777 diag::ext_unelaborated_friend_type) 11778 << (unsigned) RD->getTagKind() 11779 << T 11780 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 11781 InsertionText); 11782 } else { 11783 Diag(FriendLoc, 11784 getLangOpts().CPlusPlus11 ? 11785 diag::warn_cxx98_compat_nonclass_type_friend : 11786 diag::ext_nonclass_type_friend) 11787 << T 11788 << TypeRange; 11789 } 11790 } else if (T->getAs<EnumType>()) { 11791 Diag(FriendLoc, 11792 getLangOpts().CPlusPlus11 ? 11793 diag::warn_cxx98_compat_enum_friend : 11794 diag::ext_enum_friend) 11795 << T 11796 << TypeRange; 11797 } 11798 11799 // C++11 [class.friend]p3: 11800 // A friend declaration that does not declare a function shall have one 11801 // of the following forms: 11802 // friend elaborated-type-specifier ; 11803 // friend simple-type-specifier ; 11804 // friend typename-specifier ; 11805 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 11806 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 11807 } 11808 11809 // If the type specifier in a friend declaration designates a (possibly 11810 // cv-qualified) class type, that class is declared as a friend; otherwise, 11811 // the friend declaration is ignored. 11812 return FriendDecl::Create(Context, CurContext, 11813 TSInfo->getTypeLoc().getLocStart(), TSInfo, 11814 FriendLoc); 11815 } 11816 11817 /// Handle a friend tag declaration where the scope specifier was 11818 /// templated. 11819 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 11820 unsigned TagSpec, SourceLocation TagLoc, 11821 CXXScopeSpec &SS, 11822 IdentifierInfo *Name, 11823 SourceLocation NameLoc, 11824 AttributeList *Attr, 11825 MultiTemplateParamsArg TempParamLists) { 11826 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11827 11828 bool isExplicitSpecialization = false; 11829 bool Invalid = false; 11830 11831 if (TemplateParameterList *TemplateParams = 11832 MatchTemplateParametersToScopeSpecifier( 11833 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 11834 isExplicitSpecialization, Invalid)) { 11835 if (TemplateParams->size() > 0) { 11836 // This is a declaration of a class template. 11837 if (Invalid) 11838 return nullptr; 11839 11840 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 11841 NameLoc, Attr, TemplateParams, AS_public, 11842 /*ModulePrivateLoc=*/SourceLocation(), 11843 FriendLoc, TempParamLists.size() - 1, 11844 TempParamLists.data()).get(); 11845 } else { 11846 // The "template<>" header is extraneous. 11847 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11848 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11849 isExplicitSpecialization = true; 11850 } 11851 } 11852 11853 if (Invalid) return nullptr; 11854 11855 bool isAllExplicitSpecializations = true; 11856 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 11857 if (TempParamLists[I]->size()) { 11858 isAllExplicitSpecializations = false; 11859 break; 11860 } 11861 } 11862 11863 // FIXME: don't ignore attributes. 11864 11865 // If it's explicit specializations all the way down, just forget 11866 // about the template header and build an appropriate non-templated 11867 // friend. TODO: for source fidelity, remember the headers. 11868 if (isAllExplicitSpecializations) { 11869 if (SS.isEmpty()) { 11870 bool Owned = false; 11871 bool IsDependent = false; 11872 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 11873 Attr, AS_public, 11874 /*ModulePrivateLoc=*/SourceLocation(), 11875 MultiTemplateParamsArg(), Owned, IsDependent, 11876 /*ScopedEnumKWLoc=*/SourceLocation(), 11877 /*ScopedEnumUsesClassTag=*/false, 11878 /*UnderlyingType=*/TypeResult(), 11879 /*IsTypeSpecifier=*/false); 11880 } 11881 11882 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11883 ElaboratedTypeKeyword Keyword 11884 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11885 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 11886 *Name, NameLoc); 11887 if (T.isNull()) 11888 return nullptr; 11889 11890 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11891 if (isa<DependentNameType>(T)) { 11892 DependentNameTypeLoc TL = 11893 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11894 TL.setElaboratedKeywordLoc(TagLoc); 11895 TL.setQualifierLoc(QualifierLoc); 11896 TL.setNameLoc(NameLoc); 11897 } else { 11898 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11899 TL.setElaboratedKeywordLoc(TagLoc); 11900 TL.setQualifierLoc(QualifierLoc); 11901 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 11902 } 11903 11904 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11905 TSI, FriendLoc, TempParamLists); 11906 Friend->setAccess(AS_public); 11907 CurContext->addDecl(Friend); 11908 return Friend; 11909 } 11910 11911 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 11912 11913 11914 11915 // Handle the case of a templated-scope friend class. e.g. 11916 // template <class T> class A<T>::B; 11917 // FIXME: we don't support these right now. 11918 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 11919 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 11920 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11921 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 11922 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11923 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11924 TL.setElaboratedKeywordLoc(TagLoc); 11925 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11926 TL.setNameLoc(NameLoc); 11927 11928 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11929 TSI, FriendLoc, TempParamLists); 11930 Friend->setAccess(AS_public); 11931 Friend->setUnsupportedFriend(true); 11932 CurContext->addDecl(Friend); 11933 return Friend; 11934 } 11935 11936 11937 /// Handle a friend type declaration. This works in tandem with 11938 /// ActOnTag. 11939 /// 11940 /// Notes on friend class templates: 11941 /// 11942 /// We generally treat friend class declarations as if they were 11943 /// declaring a class. So, for example, the elaborated type specifier 11944 /// in a friend declaration is required to obey the restrictions of a 11945 /// class-head (i.e. no typedefs in the scope chain), template 11946 /// parameters are required to match up with simple template-ids, &c. 11947 /// However, unlike when declaring a template specialization, it's 11948 /// okay to refer to a template specialization without an empty 11949 /// template parameter declaration, e.g. 11950 /// friend class A<T>::B<unsigned>; 11951 /// We permit this as a special case; if there are any template 11952 /// parameters present at all, require proper matching, i.e. 11953 /// template <> template \<class T> friend class A<int>::B; 11954 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 11955 MultiTemplateParamsArg TempParams) { 11956 SourceLocation Loc = DS.getLocStart(); 11957 11958 assert(DS.isFriendSpecified()); 11959 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11960 11961 // Try to convert the decl specifier to a type. This works for 11962 // friend templates because ActOnTag never produces a ClassTemplateDecl 11963 // for a TUK_Friend. 11964 Declarator TheDeclarator(DS, Declarator::MemberContext); 11965 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11966 QualType T = TSI->getType(); 11967 if (TheDeclarator.isInvalidType()) 11968 return nullptr; 11969 11970 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11971 return nullptr; 11972 11973 // This is definitely an error in C++98. It's probably meant to 11974 // be forbidden in C++0x, too, but the specification is just 11975 // poorly written. 11976 // 11977 // The problem is with declarations like the following: 11978 // template <T> friend A<T>::foo; 11979 // where deciding whether a class C is a friend or not now hinges 11980 // on whether there exists an instantiation of A that causes 11981 // 'foo' to equal C. There are restrictions on class-heads 11982 // (which we declare (by fiat) elaborated friend declarations to 11983 // be) that makes this tractable. 11984 // 11985 // FIXME: handle "template <> friend class A<T>;", which 11986 // is possibly well-formed? Who even knows? 11987 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11988 Diag(Loc, diag::err_tagless_friend_type_template) 11989 << DS.getSourceRange(); 11990 return nullptr; 11991 } 11992 11993 // C++98 [class.friend]p1: A friend of a class is a function 11994 // or class that is not a member of the class . . . 11995 // This is fixed in DR77, which just barely didn't make the C++03 11996 // deadline. It's also a very silly restriction that seriously 11997 // affects inner classes and which nobody else seems to implement; 11998 // thus we never diagnose it, not even in -pedantic. 11999 // 12000 // But note that we could warn about it: it's always useless to 12001 // friend one of your own members (it's not, however, worthless to 12002 // friend a member of an arbitrary specialization of your template). 12003 12004 Decl *D; 12005 if (unsigned NumTempParamLists = TempParams.size()) 12006 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 12007 NumTempParamLists, 12008 TempParams.data(), 12009 TSI, 12010 DS.getFriendSpecLoc()); 12011 else 12012 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 12013 12014 if (!D) 12015 return nullptr; 12016 12017 D->setAccess(AS_public); 12018 CurContext->addDecl(D); 12019 12020 return D; 12021 } 12022 12023 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 12024 MultiTemplateParamsArg TemplateParams) { 12025 const DeclSpec &DS = D.getDeclSpec(); 12026 12027 assert(DS.isFriendSpecified()); 12028 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 12029 12030 SourceLocation Loc = D.getIdentifierLoc(); 12031 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12032 12033 // C++ [class.friend]p1 12034 // A friend of a class is a function or class.... 12035 // Note that this sees through typedefs, which is intended. 12036 // It *doesn't* see through dependent types, which is correct 12037 // according to [temp.arg.type]p3: 12038 // If a declaration acquires a function type through a 12039 // type dependent on a template-parameter and this causes 12040 // a declaration that does not use the syntactic form of a 12041 // function declarator to have a function type, the program 12042 // is ill-formed. 12043 if (!TInfo->getType()->isFunctionType()) { 12044 Diag(Loc, diag::err_unexpected_friend); 12045 12046 // It might be worthwhile to try to recover by creating an 12047 // appropriate declaration. 12048 return nullptr; 12049 } 12050 12051 // C++ [namespace.memdef]p3 12052 // - If a friend declaration in a non-local class first declares a 12053 // class or function, the friend class or function is a member 12054 // of the innermost enclosing namespace. 12055 // - The name of the friend is not found by simple name lookup 12056 // until a matching declaration is provided in that namespace 12057 // scope (either before or after the class declaration granting 12058 // friendship). 12059 // - If a friend function is called, its name may be found by the 12060 // name lookup that considers functions from namespaces and 12061 // classes associated with the types of the function arguments. 12062 // - When looking for a prior declaration of a class or a function 12063 // declared as a friend, scopes outside the innermost enclosing 12064 // namespace scope are not considered. 12065 12066 CXXScopeSpec &SS = D.getCXXScopeSpec(); 12067 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 12068 DeclarationName Name = NameInfo.getName(); 12069 assert(Name); 12070 12071 // Check for unexpanded parameter packs. 12072 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 12073 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 12074 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 12075 return nullptr; 12076 12077 // The context we found the declaration in, or in which we should 12078 // create the declaration. 12079 DeclContext *DC; 12080 Scope *DCScope = S; 12081 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12082 ForRedeclaration); 12083 12084 // There are five cases here. 12085 // - There's no scope specifier and we're in a local class. Only look 12086 // for functions declared in the immediately-enclosing block scope. 12087 // We recover from invalid scope qualifiers as if they just weren't there. 12088 FunctionDecl *FunctionContainingLocalClass = nullptr; 12089 if ((SS.isInvalid() || !SS.isSet()) && 12090 (FunctionContainingLocalClass = 12091 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 12092 // C++11 [class.friend]p11: 12093 // If a friend declaration appears in a local class and the name 12094 // specified is an unqualified name, a prior declaration is 12095 // looked up without considering scopes that are outside the 12096 // innermost enclosing non-class scope. For a friend function 12097 // declaration, if there is no prior declaration, the program is 12098 // ill-formed. 12099 12100 // Find the innermost enclosing non-class scope. This is the block 12101 // scope containing the local class definition (or for a nested class, 12102 // the outer local class). 12103 DCScope = S->getFnParent(); 12104 12105 // Look up the function name in the scope. 12106 Previous.clear(LookupLocalFriendName); 12107 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 12108 12109 if (!Previous.empty()) { 12110 // All possible previous declarations must have the same context: 12111 // either they were declared at block scope or they are members of 12112 // one of the enclosing local classes. 12113 DC = Previous.getRepresentativeDecl()->getDeclContext(); 12114 } else { 12115 // This is ill-formed, but provide the context that we would have 12116 // declared the function in, if we were permitted to, for error recovery. 12117 DC = FunctionContainingLocalClass; 12118 } 12119 adjustContextForLocalExternDecl(DC); 12120 12121 // C++ [class.friend]p6: 12122 // A function can be defined in a friend declaration of a class if and 12123 // only if the class is a non-local class (9.8), the function name is 12124 // unqualified, and the function has namespace scope. 12125 if (D.isFunctionDefinition()) { 12126 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 12127 } 12128 12129 // - There's no scope specifier, in which case we just go to the 12130 // appropriate scope and look for a function or function template 12131 // there as appropriate. 12132 } else if (SS.isInvalid() || !SS.isSet()) { 12133 // C++11 [namespace.memdef]p3: 12134 // If the name in a friend declaration is neither qualified nor 12135 // a template-id and the declaration is a function or an 12136 // elaborated-type-specifier, the lookup to determine whether 12137 // the entity has been previously declared shall not consider 12138 // any scopes outside the innermost enclosing namespace. 12139 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 12140 12141 // Find the appropriate context according to the above. 12142 DC = CurContext; 12143 12144 // Skip class contexts. If someone can cite chapter and verse 12145 // for this behavior, that would be nice --- it's what GCC and 12146 // EDG do, and it seems like a reasonable intent, but the spec 12147 // really only says that checks for unqualified existing 12148 // declarations should stop at the nearest enclosing namespace, 12149 // not that they should only consider the nearest enclosing 12150 // namespace. 12151 while (DC->isRecord()) 12152 DC = DC->getParent(); 12153 12154 DeclContext *LookupDC = DC; 12155 while (LookupDC->isTransparentContext()) 12156 LookupDC = LookupDC->getParent(); 12157 12158 while (true) { 12159 LookupQualifiedName(Previous, LookupDC); 12160 12161 if (!Previous.empty()) { 12162 DC = LookupDC; 12163 break; 12164 } 12165 12166 if (isTemplateId) { 12167 if (isa<TranslationUnitDecl>(LookupDC)) break; 12168 } else { 12169 if (LookupDC->isFileContext()) break; 12170 } 12171 LookupDC = LookupDC->getParent(); 12172 } 12173 12174 DCScope = getScopeForDeclContext(S, DC); 12175 12176 // - There's a non-dependent scope specifier, in which case we 12177 // compute it and do a previous lookup there for a function 12178 // or function template. 12179 } else if (!SS.getScopeRep()->isDependent()) { 12180 DC = computeDeclContext(SS); 12181 if (!DC) return nullptr; 12182 12183 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 12184 12185 LookupQualifiedName(Previous, DC); 12186 12187 // Ignore things found implicitly in the wrong scope. 12188 // TODO: better diagnostics for this case. Suggesting the right 12189 // qualified scope would be nice... 12190 LookupResult::Filter F = Previous.makeFilter(); 12191 while (F.hasNext()) { 12192 NamedDecl *D = F.next(); 12193 if (!DC->InEnclosingNamespaceSetOf( 12194 D->getDeclContext()->getRedeclContext())) 12195 F.erase(); 12196 } 12197 F.done(); 12198 12199 if (Previous.empty()) { 12200 D.setInvalidType(); 12201 Diag(Loc, diag::err_qualified_friend_not_found) 12202 << Name << TInfo->getType(); 12203 return nullptr; 12204 } 12205 12206 // C++ [class.friend]p1: A friend of a class is a function or 12207 // class that is not a member of the class . . . 12208 if (DC->Equals(CurContext)) 12209 Diag(DS.getFriendSpecLoc(), 12210 getLangOpts().CPlusPlus11 ? 12211 diag::warn_cxx98_compat_friend_is_member : 12212 diag::err_friend_is_member); 12213 12214 if (D.isFunctionDefinition()) { 12215 // C++ [class.friend]p6: 12216 // A function can be defined in a friend declaration of a class if and 12217 // only if the class is a non-local class (9.8), the function name is 12218 // unqualified, and the function has namespace scope. 12219 SemaDiagnosticBuilder DB 12220 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 12221 12222 DB << SS.getScopeRep(); 12223 if (DC->isFileContext()) 12224 DB << FixItHint::CreateRemoval(SS.getRange()); 12225 SS.clear(); 12226 } 12227 12228 // - There's a scope specifier that does not match any template 12229 // parameter lists, in which case we use some arbitrary context, 12230 // create a method or method template, and wait for instantiation. 12231 // - There's a scope specifier that does match some template 12232 // parameter lists, which we don't handle right now. 12233 } else { 12234 if (D.isFunctionDefinition()) { 12235 // C++ [class.friend]p6: 12236 // A function can be defined in a friend declaration of a class if and 12237 // only if the class is a non-local class (9.8), the function name is 12238 // unqualified, and the function has namespace scope. 12239 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 12240 << SS.getScopeRep(); 12241 } 12242 12243 DC = CurContext; 12244 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 12245 } 12246 12247 if (!DC->isRecord()) { 12248 // This implies that it has to be an operator or function. 12249 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 12250 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 12251 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 12252 Diag(Loc, diag::err_introducing_special_friend) << 12253 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 12254 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 12255 return nullptr; 12256 } 12257 } 12258 12259 // FIXME: This is an egregious hack to cope with cases where the scope stack 12260 // does not contain the declaration context, i.e., in an out-of-line 12261 // definition of a class. 12262 Scope FakeDCScope(S, Scope::DeclScope, Diags); 12263 if (!DCScope) { 12264 FakeDCScope.setEntity(DC); 12265 DCScope = &FakeDCScope; 12266 } 12267 12268 bool AddToScope = true; 12269 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 12270 TemplateParams, AddToScope); 12271 if (!ND) return nullptr; 12272 12273 assert(ND->getLexicalDeclContext() == CurContext); 12274 12275 // If we performed typo correction, we might have added a scope specifier 12276 // and changed the decl context. 12277 DC = ND->getDeclContext(); 12278 12279 // Add the function declaration to the appropriate lookup tables, 12280 // adjusting the redeclarations list as necessary. We don't 12281 // want to do this yet if the friending class is dependent. 12282 // 12283 // Also update the scope-based lookup if the target context's 12284 // lookup context is in lexical scope. 12285 if (!CurContext->isDependentContext()) { 12286 DC = DC->getRedeclContext(); 12287 DC->makeDeclVisibleInContext(ND); 12288 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12289 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12290 } 12291 12292 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12293 D.getIdentifierLoc(), ND, 12294 DS.getFriendSpecLoc()); 12295 FrD->setAccess(AS_public); 12296 CurContext->addDecl(FrD); 12297 12298 if (ND->isInvalidDecl()) { 12299 FrD->setInvalidDecl(); 12300 } else { 12301 if (DC->isRecord()) CheckFriendAccess(ND); 12302 12303 FunctionDecl *FD; 12304 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12305 FD = FTD->getTemplatedDecl(); 12306 else 12307 FD = cast<FunctionDecl>(ND); 12308 12309 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12310 // default argument expression, that declaration shall be a definition 12311 // and shall be the only declaration of the function or function 12312 // template in the translation unit. 12313 if (functionDeclHasDefaultArgument(FD)) { 12314 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12315 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12316 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12317 } else if (!D.isFunctionDefinition()) 12318 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12319 } 12320 12321 // Mark templated-scope function declarations as unsupported. 12322 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 12323 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 12324 << SS.getScopeRep() << SS.getRange() 12325 << cast<CXXRecordDecl>(CurContext); 12326 FrD->setUnsupportedFriend(true); 12327 } 12328 } 12329 12330 return ND; 12331 } 12332 12333 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12334 AdjustDeclIfTemplate(Dcl); 12335 12336 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12337 if (!Fn) { 12338 Diag(DelLoc, diag::err_deleted_non_function); 12339 return; 12340 } 12341 12342 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12343 // Don't consider the implicit declaration we generate for explicit 12344 // specializations. FIXME: Do not generate these implicit declarations. 12345 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12346 Prev->getPreviousDecl()) && 12347 !Prev->isDefined()) { 12348 Diag(DelLoc, diag::err_deleted_decl_not_first); 12349 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12350 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12351 : diag::note_previous_declaration); 12352 } 12353 // If the declaration wasn't the first, we delete the function anyway for 12354 // recovery. 12355 Fn = Fn->getCanonicalDecl(); 12356 } 12357 12358 // dllimport/dllexport cannot be deleted. 12359 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12360 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12361 Fn->setInvalidDecl(); 12362 } 12363 12364 if (Fn->isDeleted()) 12365 return; 12366 12367 // See if we're deleting a function which is already known to override a 12368 // non-deleted virtual function. 12369 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12370 bool IssuedDiagnostic = false; 12371 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12372 E = MD->end_overridden_methods(); 12373 I != E; ++I) { 12374 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12375 if (!IssuedDiagnostic) { 12376 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12377 IssuedDiagnostic = true; 12378 } 12379 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12380 } 12381 } 12382 } 12383 12384 // C++11 [basic.start.main]p3: 12385 // A program that defines main as deleted [...] is ill-formed. 12386 if (Fn->isMain()) 12387 Diag(DelLoc, diag::err_deleted_main); 12388 12389 Fn->setDeletedAsWritten(); 12390 } 12391 12392 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12393 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12394 12395 if (MD) { 12396 if (MD->getParent()->isDependentType()) { 12397 MD->setDefaulted(); 12398 MD->setExplicitlyDefaulted(); 12399 return; 12400 } 12401 12402 CXXSpecialMember Member = getSpecialMember(MD); 12403 if (Member == CXXInvalid) { 12404 if (!MD->isInvalidDecl()) 12405 Diag(DefaultLoc, diag::err_default_special_members); 12406 return; 12407 } 12408 12409 MD->setDefaulted(); 12410 MD->setExplicitlyDefaulted(); 12411 12412 // If this definition appears within the record, do the checking when 12413 // the record is complete. 12414 const FunctionDecl *Primary = MD; 12415 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12416 // Find the uninstantiated declaration that actually had the '= default' 12417 // on it. 12418 Pattern->isDefined(Primary); 12419 12420 // If the method was defaulted on its first declaration, we will have 12421 // already performed the checking in CheckCompletedCXXClass. Such a 12422 // declaration doesn't trigger an implicit definition. 12423 if (Primary == Primary->getCanonicalDecl()) 12424 return; 12425 12426 CheckExplicitlyDefaultedSpecialMember(MD); 12427 12428 if (MD->isInvalidDecl()) 12429 return; 12430 12431 switch (Member) { 12432 case CXXDefaultConstructor: 12433 DefineImplicitDefaultConstructor(DefaultLoc, 12434 cast<CXXConstructorDecl>(MD)); 12435 break; 12436 case CXXCopyConstructor: 12437 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12438 break; 12439 case CXXCopyAssignment: 12440 DefineImplicitCopyAssignment(DefaultLoc, MD); 12441 break; 12442 case CXXDestructor: 12443 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12444 break; 12445 case CXXMoveConstructor: 12446 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12447 break; 12448 case CXXMoveAssignment: 12449 DefineImplicitMoveAssignment(DefaultLoc, MD); 12450 break; 12451 case CXXInvalid: 12452 llvm_unreachable("Invalid special member."); 12453 } 12454 } else { 12455 Diag(DefaultLoc, diag::err_default_special_members); 12456 } 12457 } 12458 12459 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12460 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12461 Stmt *SubStmt = *CI; 12462 if (!SubStmt) 12463 continue; 12464 if (isa<ReturnStmt>(SubStmt)) 12465 Self.Diag(SubStmt->getLocStart(), 12466 diag::err_return_in_constructor_handler); 12467 if (!isa<Expr>(SubStmt)) 12468 SearchForReturnInStmt(Self, SubStmt); 12469 } 12470 } 12471 12472 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12473 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12474 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12475 SearchForReturnInStmt(*this, Handler); 12476 } 12477 } 12478 12479 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12480 const CXXMethodDecl *Old) { 12481 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12482 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12483 12484 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12485 12486 // If the calling conventions match, everything is fine 12487 if (NewCC == OldCC) 12488 return false; 12489 12490 // If the calling conventions mismatch because the new function is static, 12491 // suppress the calling convention mismatch error; the error about static 12492 // function override (err_static_overrides_virtual from 12493 // Sema::CheckFunctionDeclaration) is more clear. 12494 if (New->getStorageClass() == SC_Static) 12495 return false; 12496 12497 Diag(New->getLocation(), 12498 diag::err_conflicting_overriding_cc_attributes) 12499 << New->getDeclName() << New->getType() << Old->getType(); 12500 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12501 return true; 12502 } 12503 12504 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12505 const CXXMethodDecl *Old) { 12506 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12507 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12508 12509 if (Context.hasSameType(NewTy, OldTy) || 12510 NewTy->isDependentType() || OldTy->isDependentType()) 12511 return false; 12512 12513 // Check if the return types are covariant 12514 QualType NewClassTy, OldClassTy; 12515 12516 /// Both types must be pointers or references to classes. 12517 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12518 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12519 NewClassTy = NewPT->getPointeeType(); 12520 OldClassTy = OldPT->getPointeeType(); 12521 } 12522 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12523 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12524 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12525 NewClassTy = NewRT->getPointeeType(); 12526 OldClassTy = OldRT->getPointeeType(); 12527 } 12528 } 12529 } 12530 12531 // The return types aren't either both pointers or references to a class type. 12532 if (NewClassTy.isNull()) { 12533 Diag(New->getLocation(), 12534 diag::err_different_return_type_for_overriding_virtual_function) 12535 << New->getDeclName() << NewTy << OldTy 12536 << New->getReturnTypeSourceRange(); 12537 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12538 << Old->getReturnTypeSourceRange(); 12539 12540 return true; 12541 } 12542 12543 // C++ [class.virtual]p6: 12544 // If the return type of D::f differs from the return type of B::f, the 12545 // class type in the return type of D::f shall be complete at the point of 12546 // declaration of D::f or shall be the class type D. 12547 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12548 if (!RT->isBeingDefined() && 12549 RequireCompleteType(New->getLocation(), NewClassTy, 12550 diag::err_covariant_return_incomplete, 12551 New->getDeclName())) 12552 return true; 12553 } 12554 12555 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12556 // Check if the new class derives from the old class. 12557 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12558 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 12559 << New->getDeclName() << NewTy << OldTy 12560 << New->getReturnTypeSourceRange(); 12561 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12562 << Old->getReturnTypeSourceRange(); 12563 return true; 12564 } 12565 12566 // Check if we the conversion from derived to base is valid. 12567 if (CheckDerivedToBaseConversion( 12568 NewClassTy, OldClassTy, 12569 diag::err_covariant_return_inaccessible_base, 12570 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12571 New->getLocation(), New->getReturnTypeSourceRange(), 12572 New->getDeclName(), nullptr)) { 12573 // FIXME: this note won't trigger for delayed access control 12574 // diagnostics, and it's impossible to get an undelayed error 12575 // here from access control during the original parse because 12576 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12577 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12578 << Old->getReturnTypeSourceRange(); 12579 return true; 12580 } 12581 } 12582 12583 // The qualifiers of the return types must be the same. 12584 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12585 Diag(New->getLocation(), 12586 diag::err_covariant_return_type_different_qualifications) 12587 << New->getDeclName() << NewTy << OldTy 12588 << New->getReturnTypeSourceRange(); 12589 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12590 << Old->getReturnTypeSourceRange(); 12591 return true; 12592 }; 12593 12594 12595 // The new class type must have the same or less qualifiers as the old type. 12596 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12597 Diag(New->getLocation(), 12598 diag::err_covariant_return_type_class_type_more_qualified) 12599 << New->getDeclName() << NewTy << OldTy 12600 << New->getReturnTypeSourceRange(); 12601 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12602 << Old->getReturnTypeSourceRange(); 12603 return true; 12604 }; 12605 12606 return false; 12607 } 12608 12609 /// \brief Mark the given method pure. 12610 /// 12611 /// \param Method the method to be marked pure. 12612 /// 12613 /// \param InitRange the source range that covers the "0" initializer. 12614 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12615 SourceLocation EndLoc = InitRange.getEnd(); 12616 if (EndLoc.isValid()) 12617 Method->setRangeEnd(EndLoc); 12618 12619 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12620 Method->setPure(); 12621 return false; 12622 } 12623 12624 if (!Method->isInvalidDecl()) 12625 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12626 << Method->getDeclName() << InitRange; 12627 return true; 12628 } 12629 12630 /// \brief Determine whether the given declaration is a static data member. 12631 static bool isStaticDataMember(const Decl *D) { 12632 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12633 return Var->isStaticDataMember(); 12634 12635 return false; 12636 } 12637 12638 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12639 /// an initializer for the out-of-line declaration 'Dcl'. The scope 12640 /// is a fresh scope pushed for just this purpose. 12641 /// 12642 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12643 /// static data member of class X, names should be looked up in the scope of 12644 /// class X. 12645 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12646 // If there is no declaration, there was an error parsing it. 12647 if (!D || D->isInvalidDecl()) 12648 return; 12649 12650 // We will always have a nested name specifier here, but this declaration 12651 // might not be out of line if the specifier names the current namespace: 12652 // extern int n; 12653 // int ::n = 0; 12654 if (D->isOutOfLine()) 12655 EnterDeclaratorContext(S, D->getDeclContext()); 12656 12657 // If we are parsing the initializer for a static data member, push a 12658 // new expression evaluation context that is associated with this static 12659 // data member. 12660 if (isStaticDataMember(D)) 12661 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12662 } 12663 12664 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12665 /// initializer for the out-of-line declaration 'D'. 12666 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12667 // If there is no declaration, there was an error parsing it. 12668 if (!D || D->isInvalidDecl()) 12669 return; 12670 12671 if (isStaticDataMember(D)) 12672 PopExpressionEvaluationContext(); 12673 12674 if (D->isOutOfLine()) 12675 ExitDeclaratorContext(S); 12676 } 12677 12678 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 12679 /// C++ if/switch/while/for statement. 12680 /// e.g: "if (int x = f()) {...}" 12681 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 12682 // C++ 6.4p2: 12683 // The declarator shall not specify a function or an array. 12684 // The type-specifier-seq shall not contain typedef and shall not declare a 12685 // new class or enumeration. 12686 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 12687 "Parser allowed 'typedef' as storage class of condition decl."); 12688 12689 Decl *Dcl = ActOnDeclarator(S, D); 12690 if (!Dcl) 12691 return true; 12692 12693 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 12694 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 12695 << D.getSourceRange(); 12696 return true; 12697 } 12698 12699 return Dcl; 12700 } 12701 12702 void Sema::LoadExternalVTableUses() { 12703 if (!ExternalSource) 12704 return; 12705 12706 SmallVector<ExternalVTableUse, 4> VTables; 12707 ExternalSource->ReadUsedVTables(VTables); 12708 SmallVector<VTableUse, 4> NewUses; 12709 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 12710 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 12711 = VTablesUsed.find(VTables[I].Record); 12712 // Even if a definition wasn't required before, it may be required now. 12713 if (Pos != VTablesUsed.end()) { 12714 if (!Pos->second && VTables[I].DefinitionRequired) 12715 Pos->second = true; 12716 continue; 12717 } 12718 12719 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 12720 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 12721 } 12722 12723 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 12724 } 12725 12726 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 12727 bool DefinitionRequired) { 12728 // Ignore any vtable uses in unevaluated operands or for classes that do 12729 // not have a vtable. 12730 if (!Class->isDynamicClass() || Class->isDependentContext() || 12731 CurContext->isDependentContext() || isUnevaluatedContext()) 12732 return; 12733 12734 // Try to insert this class into the map. 12735 LoadExternalVTableUses(); 12736 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12737 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 12738 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 12739 if (!Pos.second) { 12740 // If we already had an entry, check to see if we are promoting this vtable 12741 // to required a definition. If so, we need to reappend to the VTableUses 12742 // list, since we may have already processed the first entry. 12743 if (DefinitionRequired && !Pos.first->second) { 12744 Pos.first->second = true; 12745 } else { 12746 // Otherwise, we can early exit. 12747 return; 12748 } 12749 } else { 12750 // The Microsoft ABI requires that we perform the destructor body 12751 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 12752 // the deleting destructor is emitted with the vtable, not with the 12753 // destructor definition as in the Itanium ABI. 12754 // If it has a definition, we do the check at that point instead. 12755 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12756 Class->hasUserDeclaredDestructor() && 12757 !Class->getDestructor()->isDefined() && 12758 !Class->getDestructor()->isDeleted()) { 12759 CXXDestructorDecl *DD = Class->getDestructor(); 12760 ContextRAII SavedContext(*this, DD); 12761 CheckDestructor(DD); 12762 } 12763 } 12764 12765 // Local classes need to have their virtual members marked 12766 // immediately. For all other classes, we mark their virtual members 12767 // at the end of the translation unit. 12768 if (Class->isLocalClass()) 12769 MarkVirtualMembersReferenced(Loc, Class); 12770 else 12771 VTableUses.push_back(std::make_pair(Class, Loc)); 12772 } 12773 12774 bool Sema::DefineUsedVTables() { 12775 LoadExternalVTableUses(); 12776 if (VTableUses.empty()) 12777 return false; 12778 12779 // Note: The VTableUses vector could grow as a result of marking 12780 // the members of a class as "used", so we check the size each 12781 // time through the loop and prefer indices (which are stable) to 12782 // iterators (which are not). 12783 bool DefinedAnything = false; 12784 for (unsigned I = 0; I != VTableUses.size(); ++I) { 12785 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 12786 if (!Class) 12787 continue; 12788 12789 SourceLocation Loc = VTableUses[I].second; 12790 12791 bool DefineVTable = true; 12792 12793 // If this class has a key function, but that key function is 12794 // defined in another translation unit, we don't need to emit the 12795 // vtable even though we're using it. 12796 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 12797 if (KeyFunction && !KeyFunction->hasBody()) { 12798 // The key function is in another translation unit. 12799 DefineVTable = false; 12800 TemplateSpecializationKind TSK = 12801 KeyFunction->getTemplateSpecializationKind(); 12802 assert(TSK != TSK_ExplicitInstantiationDefinition && 12803 TSK != TSK_ImplicitInstantiation && 12804 "Instantiations don't have key functions"); 12805 (void)TSK; 12806 } else if (!KeyFunction) { 12807 // If we have a class with no key function that is the subject 12808 // of an explicit instantiation declaration, suppress the 12809 // vtable; it will live with the explicit instantiation 12810 // definition. 12811 bool IsExplicitInstantiationDeclaration 12812 = Class->getTemplateSpecializationKind() 12813 == TSK_ExplicitInstantiationDeclaration; 12814 for (auto R : Class->redecls()) { 12815 TemplateSpecializationKind TSK 12816 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 12817 if (TSK == TSK_ExplicitInstantiationDeclaration) 12818 IsExplicitInstantiationDeclaration = true; 12819 else if (TSK == TSK_ExplicitInstantiationDefinition) { 12820 IsExplicitInstantiationDeclaration = false; 12821 break; 12822 } 12823 } 12824 12825 if (IsExplicitInstantiationDeclaration) 12826 DefineVTable = false; 12827 } 12828 12829 // The exception specifications for all virtual members may be needed even 12830 // if we are not providing an authoritative form of the vtable in this TU. 12831 // We may choose to emit it available_externally anyway. 12832 if (!DefineVTable) { 12833 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 12834 continue; 12835 } 12836 12837 // Mark all of the virtual members of this class as referenced, so 12838 // that we can build a vtable. Then, tell the AST consumer that a 12839 // vtable for this class is required. 12840 DefinedAnything = true; 12841 MarkVirtualMembersReferenced(Loc, Class); 12842 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12843 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 12844 12845 // Optionally warn if we're emitting a weak vtable. 12846 if (Class->isExternallyVisible() && 12847 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 12848 const FunctionDecl *KeyFunctionDef = nullptr; 12849 if (!KeyFunction || 12850 (KeyFunction->hasBody(KeyFunctionDef) && 12851 KeyFunctionDef->isInlined())) 12852 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 12853 TSK_ExplicitInstantiationDefinition 12854 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 12855 << Class; 12856 } 12857 } 12858 VTableUses.clear(); 12859 12860 return DefinedAnything; 12861 } 12862 12863 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 12864 const CXXRecordDecl *RD) { 12865 for (const auto *I : RD->methods()) 12866 if (I->isVirtual() && !I->isPure()) 12867 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 12868 } 12869 12870 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 12871 const CXXRecordDecl *RD) { 12872 // Mark all functions which will appear in RD's vtable as used. 12873 CXXFinalOverriderMap FinalOverriders; 12874 RD->getFinalOverriders(FinalOverriders); 12875 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 12876 E = FinalOverriders.end(); 12877 I != E; ++I) { 12878 for (OverridingMethods::const_iterator OI = I->second.begin(), 12879 OE = I->second.end(); 12880 OI != OE; ++OI) { 12881 assert(OI->second.size() > 0 && "no final overrider"); 12882 CXXMethodDecl *Overrider = OI->second.front().Method; 12883 12884 // C++ [basic.def.odr]p2: 12885 // [...] A virtual member function is used if it is not pure. [...] 12886 if (!Overrider->isPure()) 12887 MarkFunctionReferenced(Loc, Overrider); 12888 } 12889 } 12890 12891 // Only classes that have virtual bases need a VTT. 12892 if (RD->getNumVBases() == 0) 12893 return; 12894 12895 for (const auto &I : RD->bases()) { 12896 const CXXRecordDecl *Base = 12897 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 12898 if (Base->getNumVBases() == 0) 12899 continue; 12900 MarkVirtualMembersReferenced(Loc, Base); 12901 } 12902 } 12903 12904 /// SetIvarInitializers - This routine builds initialization ASTs for the 12905 /// Objective-C implementation whose ivars need be initialized. 12906 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 12907 if (!getLangOpts().CPlusPlus) 12908 return; 12909 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 12910 SmallVector<ObjCIvarDecl*, 8> ivars; 12911 CollectIvarsToConstructOrDestruct(OID, ivars); 12912 if (ivars.empty()) 12913 return; 12914 SmallVector<CXXCtorInitializer*, 32> AllToInit; 12915 for (unsigned i = 0; i < ivars.size(); i++) { 12916 FieldDecl *Field = ivars[i]; 12917 if (Field->isInvalidDecl()) 12918 continue; 12919 12920 CXXCtorInitializer *Member; 12921 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 12922 InitializationKind InitKind = 12923 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 12924 12925 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 12926 ExprResult MemberInit = 12927 InitSeq.Perform(*this, InitEntity, InitKind, None); 12928 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 12929 // Note, MemberInit could actually come back empty if no initialization 12930 // is required (e.g., because it would call a trivial default constructor) 12931 if (!MemberInit.get() || MemberInit.isInvalid()) 12932 continue; 12933 12934 Member = 12935 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 12936 SourceLocation(), 12937 MemberInit.getAs<Expr>(), 12938 SourceLocation()); 12939 AllToInit.push_back(Member); 12940 12941 // Be sure that the destructor is accessible and is marked as referenced. 12942 if (const RecordType *RecordTy 12943 = Context.getBaseElementType(Field->getType()) 12944 ->getAs<RecordType>()) { 12945 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 12946 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 12947 MarkFunctionReferenced(Field->getLocation(), Destructor); 12948 CheckDestructorAccess(Field->getLocation(), Destructor, 12949 PDiag(diag::err_access_dtor_ivar) 12950 << Context.getBaseElementType(Field->getType())); 12951 } 12952 } 12953 } 12954 ObjCImplementation->setIvarInitializers(Context, 12955 AllToInit.data(), AllToInit.size()); 12956 } 12957 } 12958 12959 static 12960 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 12961 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 12962 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 12963 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 12964 Sema &S) { 12965 if (Ctor->isInvalidDecl()) 12966 return; 12967 12968 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 12969 12970 // Target may not be determinable yet, for instance if this is a dependent 12971 // call in an uninstantiated template. 12972 if (Target) { 12973 const FunctionDecl *FNTarget = nullptr; 12974 (void)Target->hasBody(FNTarget); 12975 Target = const_cast<CXXConstructorDecl*>( 12976 cast_or_null<CXXConstructorDecl>(FNTarget)); 12977 } 12978 12979 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 12980 // Avoid dereferencing a null pointer here. 12981 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 12982 12983 if (!Current.insert(Canonical)) 12984 return; 12985 12986 // We know that beyond here, we aren't chaining into a cycle. 12987 if (!Target || !Target->isDelegatingConstructor() || 12988 Target->isInvalidDecl() || Valid.count(TCanonical)) { 12989 Valid.insert(Current.begin(), Current.end()); 12990 Current.clear(); 12991 // We've hit a cycle. 12992 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 12993 Current.count(TCanonical)) { 12994 // If we haven't diagnosed this cycle yet, do so now. 12995 if (!Invalid.count(TCanonical)) { 12996 S.Diag((*Ctor->init_begin())->getSourceLocation(), 12997 diag::warn_delegating_ctor_cycle) 12998 << Ctor; 12999 13000 // Don't add a note for a function delegating directly to itself. 13001 if (TCanonical != Canonical) 13002 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 13003 13004 CXXConstructorDecl *C = Target; 13005 while (C->getCanonicalDecl() != Canonical) { 13006 const FunctionDecl *FNTarget = nullptr; 13007 (void)C->getTargetConstructor()->hasBody(FNTarget); 13008 assert(FNTarget && "Ctor cycle through bodiless function"); 13009 13010 C = const_cast<CXXConstructorDecl*>( 13011 cast<CXXConstructorDecl>(FNTarget)); 13012 S.Diag(C->getLocation(), diag::note_which_delegates_to); 13013 } 13014 } 13015 13016 Invalid.insert(Current.begin(), Current.end()); 13017 Current.clear(); 13018 } else { 13019 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 13020 } 13021 } 13022 13023 13024 void Sema::CheckDelegatingCtorCycles() { 13025 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 13026 13027 for (DelegatingCtorDeclsType::iterator 13028 I = DelegatingCtorDecls.begin(ExternalSource), 13029 E = DelegatingCtorDecls.end(); 13030 I != E; ++I) 13031 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 13032 13033 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 13034 CE = Invalid.end(); 13035 CI != CE; ++CI) 13036 (*CI)->setInvalidDecl(); 13037 } 13038 13039 namespace { 13040 /// \brief AST visitor that finds references to the 'this' expression. 13041 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 13042 Sema &S; 13043 13044 public: 13045 explicit FindCXXThisExpr(Sema &S) : S(S) { } 13046 13047 bool VisitCXXThisExpr(CXXThisExpr *E) { 13048 S.Diag(E->getLocation(), diag::err_this_static_member_func) 13049 << E->isImplicit(); 13050 return false; 13051 } 13052 }; 13053 } 13054 13055 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 13056 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13057 if (!TSInfo) 13058 return false; 13059 13060 TypeLoc TL = TSInfo->getTypeLoc(); 13061 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13062 if (!ProtoTL) 13063 return false; 13064 13065 // C++11 [expr.prim.general]p3: 13066 // [The expression this] shall not appear before the optional 13067 // cv-qualifier-seq and it shall not appear within the declaration of a 13068 // static member function (although its type and value category are defined 13069 // within a static member function as they are within a non-static member 13070 // function). [ Note: this is because declaration matching does not occur 13071 // until the complete declarator is known. - end note ] 13072 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13073 FindCXXThisExpr Finder(*this); 13074 13075 // If the return type came after the cv-qualifier-seq, check it now. 13076 if (Proto->hasTrailingReturn() && 13077 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 13078 return true; 13079 13080 // Check the exception specification. 13081 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 13082 return true; 13083 13084 return checkThisInStaticMemberFunctionAttributes(Method); 13085 } 13086 13087 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 13088 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13089 if (!TSInfo) 13090 return false; 13091 13092 TypeLoc TL = TSInfo->getTypeLoc(); 13093 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13094 if (!ProtoTL) 13095 return false; 13096 13097 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13098 FindCXXThisExpr Finder(*this); 13099 13100 switch (Proto->getExceptionSpecType()) { 13101 case EST_Uninstantiated: 13102 case EST_Unevaluated: 13103 case EST_BasicNoexcept: 13104 case EST_DynamicNone: 13105 case EST_MSAny: 13106 case EST_None: 13107 break; 13108 13109 case EST_ComputedNoexcept: 13110 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 13111 return true; 13112 13113 case EST_Dynamic: 13114 for (const auto &E : Proto->exceptions()) { 13115 if (!Finder.TraverseType(E)) 13116 return true; 13117 } 13118 break; 13119 } 13120 13121 return false; 13122 } 13123 13124 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 13125 FindCXXThisExpr Finder(*this); 13126 13127 // Check attributes. 13128 for (const auto *A : Method->attrs()) { 13129 // FIXME: This should be emitted by tblgen. 13130 Expr *Arg = nullptr; 13131 ArrayRef<Expr *> Args; 13132 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 13133 Arg = G->getArg(); 13134 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 13135 Arg = G->getArg(); 13136 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 13137 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 13138 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 13139 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 13140 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 13141 Arg = ETLF->getSuccessValue(); 13142 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 13143 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 13144 Arg = STLF->getSuccessValue(); 13145 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 13146 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 13147 Arg = LR->getArg(); 13148 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 13149 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 13150 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 13151 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13152 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 13153 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13154 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 13155 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13156 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 13157 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13158 13159 if (Arg && !Finder.TraverseStmt(Arg)) 13160 return true; 13161 13162 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 13163 if (!Finder.TraverseStmt(Args[I])) 13164 return true; 13165 } 13166 } 13167 13168 return false; 13169 } 13170 13171 void 13172 Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 13173 ArrayRef<ParsedType> DynamicExceptions, 13174 ArrayRef<SourceRange> DynamicExceptionRanges, 13175 Expr *NoexceptExpr, 13176 SmallVectorImpl<QualType> &Exceptions, 13177 FunctionProtoType::ExceptionSpecInfo &ESI) { 13178 Exceptions.clear(); 13179 ESI.Type = EST; 13180 if (EST == EST_Dynamic) { 13181 Exceptions.reserve(DynamicExceptions.size()); 13182 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 13183 // FIXME: Preserve type source info. 13184 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 13185 13186 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 13187 collectUnexpandedParameterPacks(ET, Unexpanded); 13188 if (!Unexpanded.empty()) { 13189 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 13190 UPPC_ExceptionType, 13191 Unexpanded); 13192 continue; 13193 } 13194 13195 // Check that the type is valid for an exception spec, and 13196 // drop it if not. 13197 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 13198 Exceptions.push_back(ET); 13199 } 13200 ESI.Exceptions = Exceptions; 13201 return; 13202 } 13203 13204 if (EST == EST_ComputedNoexcept) { 13205 // If an error occurred, there's no expression here. 13206 if (NoexceptExpr) { 13207 assert((NoexceptExpr->isTypeDependent() || 13208 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 13209 Context.BoolTy) && 13210 "Parser should have made sure that the expression is boolean"); 13211 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 13212 ESI.Type = EST_BasicNoexcept; 13213 return; 13214 } 13215 13216 if (!NoexceptExpr->isValueDependent()) 13217 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 13218 diag::err_noexcept_needs_constant_expression, 13219 /*AllowFold*/ false).get(); 13220 ESI.NoexceptExpr = NoexceptExpr; 13221 } 13222 return; 13223 } 13224 } 13225 13226 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 13227 /// 13228 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 13229 SourceLocation DeclStart, 13230 Declarator &D, Expr *BitWidth, 13231 InClassInitStyle InitStyle, 13232 AccessSpecifier AS, 13233 AttributeList *MSPropertyAttr) { 13234 IdentifierInfo *II = D.getIdentifier(); 13235 if (!II) { 13236 Diag(DeclStart, diag::err_anonymous_property); 13237 return nullptr; 13238 } 13239 SourceLocation Loc = D.getIdentifierLoc(); 13240 13241 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13242 QualType T = TInfo->getType(); 13243 if (getLangOpts().CPlusPlus) { 13244 CheckExtraCXXDefaultArguments(D); 13245 13246 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13247 UPPC_DataMemberType)) { 13248 D.setInvalidType(); 13249 T = Context.IntTy; 13250 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13251 } 13252 } 13253 13254 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13255 13256 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13257 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13258 diag::err_invalid_thread) 13259 << DeclSpec::getSpecifierName(TSCS); 13260 13261 // Check to see if this name was declared as a member previously 13262 NamedDecl *PrevDecl = nullptr; 13263 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13264 LookupName(Previous, S); 13265 switch (Previous.getResultKind()) { 13266 case LookupResult::Found: 13267 case LookupResult::FoundUnresolvedValue: 13268 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13269 break; 13270 13271 case LookupResult::FoundOverloaded: 13272 PrevDecl = Previous.getRepresentativeDecl(); 13273 break; 13274 13275 case LookupResult::NotFound: 13276 case LookupResult::NotFoundInCurrentInstantiation: 13277 case LookupResult::Ambiguous: 13278 break; 13279 } 13280 13281 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13282 // Maybe we will complain about the shadowed template parameter. 13283 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13284 // Just pretend that we didn't see the previous declaration. 13285 PrevDecl = nullptr; 13286 } 13287 13288 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13289 PrevDecl = nullptr; 13290 13291 SourceLocation TSSL = D.getLocStart(); 13292 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13293 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13294 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13295 ProcessDeclAttributes(TUScope, NewPD, D); 13296 NewPD->setAccess(AS); 13297 13298 if (NewPD->isInvalidDecl()) 13299 Record->setInvalidDecl(); 13300 13301 if (D.getDeclSpec().isModulePrivateSpecified()) 13302 NewPD->setModulePrivate(); 13303 13304 if (NewPD->isInvalidDecl() && PrevDecl) { 13305 // Don't introduce NewFD into scope; there's already something 13306 // with the same name in the same scope. 13307 } else if (II) { 13308 PushOnScopeChains(NewPD, S); 13309 } else 13310 Record->addDecl(NewPD); 13311 13312 return NewPD; 13313 } 13314