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, Param->getType(), VK_RValue)); 357 } 358 359 /// CheckExtraCXXDefaultArguments - Check for any extra default 360 /// arguments in the declarator, which is not a function declaration 361 /// or definition and therefore is not permitted to have default 362 /// arguments. This routine should be invoked for every declarator 363 /// that is not a function declaration or definition. 364 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 365 // C++ [dcl.fct.default]p3 366 // A default argument expression shall be specified only in the 367 // parameter-declaration-clause of a function declaration or in a 368 // template-parameter (14.1). It shall not be specified for a 369 // parameter pack. If it is specified in a 370 // parameter-declaration-clause, it shall not occur within a 371 // declarator or abstract-declarator of a parameter-declaration. 372 bool MightBeFunction = D.isFunctionDeclarationContext(); 373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 374 DeclaratorChunk &chunk = D.getTypeObject(i); 375 if (chunk.Kind == DeclaratorChunk::Function) { 376 if (MightBeFunction) { 377 // This is a function declaration. It can have default arguments, but 378 // keep looking in case its return type is a function type with default 379 // arguments. 380 MightBeFunction = false; 381 continue; 382 } 383 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 384 ++argIdx) { 385 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 386 if (Param->hasUnparsedDefaultArg()) { 387 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens; 388 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 389 << SourceRange((*Toks)[1].getLocation(), 390 Toks->back().getLocation()); 391 delete Toks; 392 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr; 393 } else if (Param->getDefaultArg()) { 394 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 395 << Param->getDefaultArg()->getSourceRange(); 396 Param->setDefaultArg(nullptr); 397 } 398 } 399 } else if (chunk.Kind != DeclaratorChunk::Paren) { 400 MightBeFunction = false; 401 } 402 } 403 } 404 405 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 406 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 407 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 408 if (!PVD->hasDefaultArg()) 409 return false; 410 if (!PVD->hasInheritedDefaultArg()) 411 return true; 412 } 413 return false; 414 } 415 416 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 417 /// function, once we already know that they have the same 418 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 419 /// error, false otherwise. 420 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 421 Scope *S) { 422 bool Invalid = false; 423 424 // C++ [dcl.fct.default]p4: 425 // For non-template functions, default arguments can be added in 426 // later declarations of a function in the same 427 // scope. Declarations in different scopes have completely 428 // distinct sets of default arguments. That is, declarations in 429 // inner scopes do not acquire default arguments from 430 // declarations in outer scopes, and vice versa. In a given 431 // function declaration, all parameters subsequent to a 432 // parameter with a default argument shall have default 433 // arguments supplied in this or previous declarations. A 434 // default argument shall not be redefined by a later 435 // declaration (not even to the same value). 436 // 437 // C++ [dcl.fct.default]p6: 438 // Except for member functions of class templates, the default arguments 439 // in a member function definition that appears outside of the class 440 // definition are added to the set of default arguments provided by the 441 // member function declaration in the class definition. 442 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 443 ParmVarDecl *OldParam = Old->getParamDecl(p); 444 ParmVarDecl *NewParam = New->getParamDecl(p); 445 446 bool OldParamHasDfl = OldParam->hasDefaultArg(); 447 bool NewParamHasDfl = NewParam->hasDefaultArg(); 448 449 // The declaration context corresponding to the scope is the semantic 450 // parent, unless this is a local function declaration, in which case 451 // it is that surrounding function. 452 DeclContext *ScopeDC = New->isLocalExternDecl() 453 ? New->getLexicalDeclContext() 454 : New->getDeclContext(); 455 if (S && !isDeclInScope(Old, ScopeDC, S) && 456 !New->getDeclContext()->isRecord()) 457 // Ignore default parameters of old decl if they are not in 458 // the same scope and this is not an out-of-line definition of 459 // a member function. 460 OldParamHasDfl = false; 461 if (New->isLocalExternDecl() != Old->isLocalExternDecl()) 462 // If only one of these is a local function declaration, then they are 463 // declared in different scopes, even though isDeclInScope may think 464 // they're in the same scope. (If both are local, the scope check is 465 // sufficent, and if neither is local, then they are in the same scope.) 466 OldParamHasDfl = false; 467 468 if (OldParamHasDfl && NewParamHasDfl) { 469 470 unsigned DiagDefaultParamID = 471 diag::err_param_default_argument_redefinition; 472 473 // MSVC accepts that default parameters be redefined for member functions 474 // of template class. The new default parameter's value is ignored. 475 Invalid = true; 476 if (getLangOpts().MicrosoftExt) { 477 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 478 if (MD && MD->getParent()->getDescribedClassTemplate()) { 479 // Merge the old default argument into the new parameter. 480 NewParam->setHasInheritedDefaultArg(); 481 if (OldParam->hasUninstantiatedDefaultArg()) 482 NewParam->setUninstantiatedDefaultArg( 483 OldParam->getUninstantiatedDefaultArg()); 484 else 485 NewParam->setDefaultArg(OldParam->getInit()); 486 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 487 Invalid = false; 488 } 489 } 490 491 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 492 // hint here. Alternatively, we could walk the type-source information 493 // for NewParam to find the last source location in the type... but it 494 // isn't worth the effort right now. This is the kind of test case that 495 // is hard to get right: 496 // int f(int); 497 // void g(int (*fp)(int) = f); 498 // void g(int (*fp)(int) = &f); 499 Diag(NewParam->getLocation(), DiagDefaultParamID) 500 << NewParam->getDefaultArgRange(); 501 502 // Look for the function declaration where the default argument was 503 // actually written, which may be a declaration prior to Old. 504 for (FunctionDecl *Older = Old->getPreviousDecl(); 505 Older; Older = Older->getPreviousDecl()) { 506 if (!Older->getParamDecl(p)->hasDefaultArg()) 507 break; 508 509 OldParam = Older->getParamDecl(p); 510 } 511 512 Diag(OldParam->getLocation(), diag::note_previous_definition) 513 << OldParam->getDefaultArgRange(); 514 } else if (OldParamHasDfl) { 515 // Merge the old default argument into the new parameter. 516 // It's important to use getInit() here; getDefaultArg() 517 // strips off any top-level ExprWithCleanups. 518 NewParam->setHasInheritedDefaultArg(); 519 if (OldParam->hasUninstantiatedDefaultArg()) 520 NewParam->setUninstantiatedDefaultArg( 521 OldParam->getUninstantiatedDefaultArg()); 522 else 523 NewParam->setDefaultArg(OldParam->getInit()); 524 } else if (NewParamHasDfl) { 525 if (New->getDescribedFunctionTemplate()) { 526 // Paragraph 4, quoted above, only applies to non-template functions. 527 Diag(NewParam->getLocation(), 528 diag::err_param_default_argument_template_redecl) 529 << NewParam->getDefaultArgRange(); 530 Diag(Old->getLocation(), diag::note_template_prev_declaration) 531 << false; 532 } else if (New->getTemplateSpecializationKind() 533 != TSK_ImplicitInstantiation && 534 New->getTemplateSpecializationKind() != TSK_Undeclared) { 535 // C++ [temp.expr.spec]p21: 536 // Default function arguments shall not be specified in a declaration 537 // or a definition for one of the following explicit specializations: 538 // - the explicit specialization of a function template; 539 // - the explicit specialization of a member function template; 540 // - the explicit specialization of a member function of a class 541 // template where the class template specialization to which the 542 // member function specialization belongs is implicitly 543 // instantiated. 544 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 545 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 546 << New->getDeclName() 547 << NewParam->getDefaultArgRange(); 548 } else if (New->getDeclContext()->isDependentContext()) { 549 // C++ [dcl.fct.default]p6 (DR217): 550 // Default arguments for a member function of a class template shall 551 // be specified on the initial declaration of the member function 552 // within the class template. 553 // 554 // Reading the tea leaves a bit in DR217 and its reference to DR205 555 // leads me to the conclusion that one cannot add default function 556 // arguments for an out-of-line definition of a member function of a 557 // dependent type. 558 int WhichKind = 2; 559 if (CXXRecordDecl *Record 560 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 561 if (Record->getDescribedClassTemplate()) 562 WhichKind = 0; 563 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 564 WhichKind = 1; 565 else 566 WhichKind = 2; 567 } 568 569 Diag(NewParam->getLocation(), 570 diag::err_param_default_argument_member_template_redecl) 571 << WhichKind 572 << NewParam->getDefaultArgRange(); 573 } 574 } 575 } 576 577 // DR1344: If a default argument is added outside a class definition and that 578 // default argument makes the function a special member function, the program 579 // is ill-formed. This can only happen for constructors. 580 if (isa<CXXConstructorDecl>(New) && 581 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 582 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 583 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 584 if (NewSM != OldSM) { 585 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 586 assert(NewParam->hasDefaultArg()); 587 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 588 << NewParam->getDefaultArgRange() << NewSM; 589 Diag(Old->getLocation(), diag::note_previous_declaration); 590 } 591 } 592 593 const FunctionDecl *Def; 594 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 595 // template has a constexpr specifier then all its declarations shall 596 // contain the constexpr specifier. 597 if (New->isConstexpr() != Old->isConstexpr()) { 598 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 599 << New << New->isConstexpr(); 600 Diag(Old->getLocation(), diag::note_previous_declaration); 601 Invalid = true; 602 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) { 603 // C++11 [dcl.fcn.spec]p4: 604 // If the definition of a function appears in a translation unit before its 605 // first declaration as inline, the program is ill-formed. 606 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 607 Diag(Def->getLocation(), diag::note_previous_definition); 608 Invalid = true; 609 } 610 611 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 612 // argument expression, that declaration shall be a definition and shall be 613 // the only declaration of the function or function template in the 614 // translation unit. 615 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 616 functionDeclHasDefaultArgument(Old)) { 617 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 618 Diag(Old->getLocation(), diag::note_previous_declaration); 619 Invalid = true; 620 } 621 622 if (CheckEquivalentExceptionSpec(Old, New)) 623 Invalid = true; 624 625 return Invalid; 626 } 627 628 /// \brief Merge the exception specifications of two variable declarations. 629 /// 630 /// This is called when there's a redeclaration of a VarDecl. The function 631 /// checks if the redeclaration might have an exception specification and 632 /// validates compatibility and merges the specs if necessary. 633 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 634 // Shortcut if exceptions are disabled. 635 if (!getLangOpts().CXXExceptions) 636 return; 637 638 assert(Context.hasSameType(New->getType(), Old->getType()) && 639 "Should only be called if types are otherwise the same."); 640 641 QualType NewType = New->getType(); 642 QualType OldType = Old->getType(); 643 644 // We're only interested in pointers and references to functions, as well 645 // as pointers to member functions. 646 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 647 NewType = R->getPointeeType(); 648 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 649 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 650 NewType = P->getPointeeType(); 651 OldType = OldType->getAs<PointerType>()->getPointeeType(); 652 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 653 NewType = M->getPointeeType(); 654 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 655 } 656 657 if (!NewType->isFunctionProtoType()) 658 return; 659 660 // There's lots of special cases for functions. For function pointers, system 661 // libraries are hopefully not as broken so that we don't need these 662 // workarounds. 663 if (CheckEquivalentExceptionSpec( 664 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 665 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 666 New->setInvalidDecl(); 667 } 668 } 669 670 /// CheckCXXDefaultArguments - Verify that the default arguments for a 671 /// function declaration are well-formed according to C++ 672 /// [dcl.fct.default]. 673 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 674 unsigned NumParams = FD->getNumParams(); 675 unsigned p; 676 677 // Find first parameter with a default argument 678 for (p = 0; p < NumParams; ++p) { 679 ParmVarDecl *Param = FD->getParamDecl(p); 680 if (Param->hasDefaultArg()) 681 break; 682 } 683 684 // C++ [dcl.fct.default]p4: 685 // In a given function declaration, all parameters 686 // subsequent to a parameter with a default argument shall 687 // have default arguments supplied in this or previous 688 // declarations. A default argument shall not be redefined 689 // by a later declaration (not even to the same value). 690 unsigned LastMissingDefaultArg = 0; 691 for (; p < NumParams; ++p) { 692 ParmVarDecl *Param = FD->getParamDecl(p); 693 if (!Param->hasDefaultArg()) { 694 if (Param->isInvalidDecl()) 695 /* We already complained about this parameter. */; 696 else if (Param->getIdentifier()) 697 Diag(Param->getLocation(), 698 diag::err_param_default_argument_missing_name) 699 << Param->getIdentifier(); 700 else 701 Diag(Param->getLocation(), 702 diag::err_param_default_argument_missing); 703 704 LastMissingDefaultArg = p; 705 } 706 } 707 708 if (LastMissingDefaultArg > 0) { 709 // Some default arguments were missing. Clear out all of the 710 // default arguments up to (and including) the last missing 711 // default argument, so that we leave the function parameters 712 // in a semantically valid state. 713 for (p = 0; p <= LastMissingDefaultArg; ++p) { 714 ParmVarDecl *Param = FD->getParamDecl(p); 715 if (Param->hasDefaultArg()) { 716 Param->setDefaultArg(nullptr); 717 } 718 } 719 } 720 } 721 722 // CheckConstexprParameterTypes - Check whether a function's parameter types 723 // are all literal types. If so, return true. If not, produce a suitable 724 // diagnostic and return false. 725 static bool CheckConstexprParameterTypes(Sema &SemaRef, 726 const FunctionDecl *FD) { 727 unsigned ArgIndex = 0; 728 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 729 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 730 e = FT->param_type_end(); 731 i != e; ++i, ++ArgIndex) { 732 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 733 SourceLocation ParamLoc = PD->getLocation(); 734 if (!(*i)->isDependentType() && 735 SemaRef.RequireLiteralType(ParamLoc, *i, 736 diag::err_constexpr_non_literal_param, 737 ArgIndex+1, PD->getSourceRange(), 738 isa<CXXConstructorDecl>(FD))) 739 return false; 740 } 741 return true; 742 } 743 744 /// \brief Get diagnostic %select index for tag kind for 745 /// record diagnostic message. 746 /// WARNING: Indexes apply to particular diagnostics only! 747 /// 748 /// \returns diagnostic %select index. 749 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 750 switch (Tag) { 751 case TTK_Struct: return 0; 752 case TTK_Interface: return 1; 753 case TTK_Class: return 2; 754 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 755 } 756 } 757 758 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 759 // the requirements of a constexpr function definition or a constexpr 760 // constructor definition. If so, return true. If not, produce appropriate 761 // diagnostics and return false. 762 // 763 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 764 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 765 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 766 if (MD && MD->isInstance()) { 767 // C++11 [dcl.constexpr]p4: 768 // The definition of a constexpr constructor shall satisfy the following 769 // constraints: 770 // - the class shall not have any virtual base classes; 771 const CXXRecordDecl *RD = MD->getParent(); 772 if (RD->getNumVBases()) { 773 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 774 << isa<CXXConstructorDecl>(NewFD) 775 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 776 for (const auto &I : RD->vbases()) 777 Diag(I.getLocStart(), 778 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 779 return false; 780 } 781 } 782 783 if (!isa<CXXConstructorDecl>(NewFD)) { 784 // C++11 [dcl.constexpr]p3: 785 // The definition of a constexpr function shall satisfy the following 786 // constraints: 787 // - it shall not be virtual; 788 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 789 if (Method && Method->isVirtual()) { 790 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 791 792 // If it's not obvious why this function is virtual, find an overridden 793 // function which uses the 'virtual' keyword. 794 const CXXMethodDecl *WrittenVirtual = Method; 795 while (!WrittenVirtual->isVirtualAsWritten()) 796 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 797 if (WrittenVirtual != Method) 798 Diag(WrittenVirtual->getLocation(), 799 diag::note_overridden_virtual_function); 800 return false; 801 } 802 803 // - its return type shall be a literal type; 804 QualType RT = NewFD->getReturnType(); 805 if (!RT->isDependentType() && 806 RequireLiteralType(NewFD->getLocation(), RT, 807 diag::err_constexpr_non_literal_return)) 808 return false; 809 } 810 811 // - each of its parameter types shall be a literal type; 812 if (!CheckConstexprParameterTypes(*this, NewFD)) 813 return false; 814 815 return true; 816 } 817 818 /// Check the given declaration statement is legal within a constexpr function 819 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 820 /// 821 /// \return true if the body is OK (maybe only as an extension), false if we 822 /// have diagnosed a problem. 823 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 824 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 825 // C++11 [dcl.constexpr]p3 and p4: 826 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 827 // contain only 828 for (const auto *DclIt : DS->decls()) { 829 switch (DclIt->getKind()) { 830 case Decl::StaticAssert: 831 case Decl::Using: 832 case Decl::UsingShadow: 833 case Decl::UsingDirective: 834 case Decl::UnresolvedUsingTypename: 835 case Decl::UnresolvedUsingValue: 836 // - static_assert-declarations 837 // - using-declarations, 838 // - using-directives, 839 continue; 840 841 case Decl::Typedef: 842 case Decl::TypeAlias: { 843 // - typedef declarations and alias-declarations that do not define 844 // classes or enumerations, 845 const auto *TN = cast<TypedefNameDecl>(DclIt); 846 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 847 // Don't allow variably-modified types in constexpr functions. 848 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 849 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 850 << TL.getSourceRange() << TL.getType() 851 << isa<CXXConstructorDecl>(Dcl); 852 return false; 853 } 854 continue; 855 } 856 857 case Decl::Enum: 858 case Decl::CXXRecord: 859 // C++1y allows types to be defined, not just declared. 860 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 861 SemaRef.Diag(DS->getLocStart(), 862 SemaRef.getLangOpts().CPlusPlus14 863 ? diag::warn_cxx11_compat_constexpr_type_definition 864 : diag::ext_constexpr_type_definition) 865 << isa<CXXConstructorDecl>(Dcl); 866 continue; 867 868 case Decl::EnumConstant: 869 case Decl::IndirectField: 870 case Decl::ParmVar: 871 // These can only appear with other declarations which are banned in 872 // C++11 and permitted in C++1y, so ignore them. 873 continue; 874 875 case Decl::Var: { 876 // C++1y [dcl.constexpr]p3 allows anything except: 877 // a definition of a variable of non-literal type or of static or 878 // thread storage duration or for which no initialization is performed. 879 const auto *VD = cast<VarDecl>(DclIt); 880 if (VD->isThisDeclarationADefinition()) { 881 if (VD->isStaticLocal()) { 882 SemaRef.Diag(VD->getLocation(), 883 diag::err_constexpr_local_var_static) 884 << isa<CXXConstructorDecl>(Dcl) 885 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 886 return false; 887 } 888 if (!VD->getType()->isDependentType() && 889 SemaRef.RequireLiteralType( 890 VD->getLocation(), VD->getType(), 891 diag::err_constexpr_local_var_non_literal_type, 892 isa<CXXConstructorDecl>(Dcl))) 893 return false; 894 if (!VD->getType()->isDependentType() && 895 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 896 SemaRef.Diag(VD->getLocation(), 897 diag::err_constexpr_local_var_no_init) 898 << isa<CXXConstructorDecl>(Dcl); 899 return false; 900 } 901 } 902 SemaRef.Diag(VD->getLocation(), 903 SemaRef.getLangOpts().CPlusPlus14 904 ? diag::warn_cxx11_compat_constexpr_local_var 905 : diag::ext_constexpr_local_var) 906 << isa<CXXConstructorDecl>(Dcl); 907 continue; 908 } 909 910 case Decl::NamespaceAlias: 911 case Decl::Function: 912 // These are disallowed in C++11 and permitted in C++1y. Allow them 913 // everywhere as an extension. 914 if (!Cxx1yLoc.isValid()) 915 Cxx1yLoc = DS->getLocStart(); 916 continue; 917 918 default: 919 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 920 << isa<CXXConstructorDecl>(Dcl); 921 return false; 922 } 923 } 924 925 return true; 926 } 927 928 /// Check that the given field is initialized within a constexpr constructor. 929 /// 930 /// \param Dcl The constexpr constructor being checked. 931 /// \param Field The field being checked. This may be a member of an anonymous 932 /// struct or union nested within the class being checked. 933 /// \param Inits All declarations, including anonymous struct/union members and 934 /// indirect members, for which any initialization was provided. 935 /// \param Diagnosed Set to true if an error is produced. 936 static void CheckConstexprCtorInitializer(Sema &SemaRef, 937 const FunctionDecl *Dcl, 938 FieldDecl *Field, 939 llvm::SmallSet<Decl*, 16> &Inits, 940 bool &Diagnosed) { 941 if (Field->isInvalidDecl()) 942 return; 943 944 if (Field->isUnnamedBitfield()) 945 return; 946 947 // Anonymous unions with no variant members and empty anonymous structs do not 948 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 949 // indirect fields don't need initializing. 950 if (Field->isAnonymousStructOrUnion() && 951 (Field->getType()->isUnionType() 952 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 953 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 954 return; 955 956 if (!Inits.count(Field)) { 957 if (!Diagnosed) { 958 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 959 Diagnosed = true; 960 } 961 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 962 } else if (Field->isAnonymousStructOrUnion()) { 963 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 964 for (auto *I : RD->fields()) 965 // If an anonymous union contains an anonymous struct of which any member 966 // is initialized, all members must be initialized. 967 if (!RD->isUnion() || Inits.count(I)) 968 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 969 } 970 } 971 972 /// Check the provided statement is allowed in a constexpr function 973 /// definition. 974 static bool 975 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 976 SmallVectorImpl<SourceLocation> &ReturnStmts, 977 SourceLocation &Cxx1yLoc) { 978 // - its function-body shall be [...] a compound-statement that contains only 979 switch (S->getStmtClass()) { 980 case Stmt::NullStmtClass: 981 // - null statements, 982 return true; 983 984 case Stmt::DeclStmtClass: 985 // - static_assert-declarations 986 // - using-declarations, 987 // - using-directives, 988 // - typedef declarations and alias-declarations that do not define 989 // classes or enumerations, 990 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 991 return false; 992 return true; 993 994 case Stmt::ReturnStmtClass: 995 // - and exactly one return statement; 996 if (isa<CXXConstructorDecl>(Dcl)) { 997 // C++1y allows return statements in constexpr constructors. 998 if (!Cxx1yLoc.isValid()) 999 Cxx1yLoc = S->getLocStart(); 1000 return true; 1001 } 1002 1003 ReturnStmts.push_back(S->getLocStart()); 1004 return true; 1005 1006 case Stmt::CompoundStmtClass: { 1007 // C++1y allows compound-statements. 1008 if (!Cxx1yLoc.isValid()) 1009 Cxx1yLoc = S->getLocStart(); 1010 1011 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1012 for (auto *BodyIt : CompStmt->body()) { 1013 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1014 Cxx1yLoc)) 1015 return false; 1016 } 1017 return true; 1018 } 1019 1020 case Stmt::AttributedStmtClass: 1021 if (!Cxx1yLoc.isValid()) 1022 Cxx1yLoc = S->getLocStart(); 1023 return true; 1024 1025 case Stmt::IfStmtClass: { 1026 // C++1y allows if-statements. 1027 if (!Cxx1yLoc.isValid()) 1028 Cxx1yLoc = S->getLocStart(); 1029 1030 IfStmt *If = cast<IfStmt>(S); 1031 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1032 Cxx1yLoc)) 1033 return false; 1034 if (If->getElse() && 1035 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1036 Cxx1yLoc)) 1037 return false; 1038 return true; 1039 } 1040 1041 case Stmt::WhileStmtClass: 1042 case Stmt::DoStmtClass: 1043 case Stmt::ForStmtClass: 1044 case Stmt::CXXForRangeStmtClass: 1045 case Stmt::ContinueStmtClass: 1046 // C++1y allows all of these. We don't allow them as extensions in C++11, 1047 // because they don't make sense without variable mutation. 1048 if (!SemaRef.getLangOpts().CPlusPlus14) 1049 break; 1050 if (!Cxx1yLoc.isValid()) 1051 Cxx1yLoc = S->getLocStart(); 1052 for (Stmt::child_range Children = S->children(); Children; ++Children) 1053 if (*Children && 1054 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1055 Cxx1yLoc)) 1056 return false; 1057 return true; 1058 1059 case Stmt::SwitchStmtClass: 1060 case Stmt::CaseStmtClass: 1061 case Stmt::DefaultStmtClass: 1062 case Stmt::BreakStmtClass: 1063 // C++1y allows switch-statements, and since they don't need variable 1064 // mutation, we can reasonably allow them in C++11 as an extension. 1065 if (!Cxx1yLoc.isValid()) 1066 Cxx1yLoc = S->getLocStart(); 1067 for (Stmt::child_range Children = S->children(); Children; ++Children) 1068 if (*Children && 1069 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1070 Cxx1yLoc)) 1071 return false; 1072 return true; 1073 1074 default: 1075 if (!isa<Expr>(S)) 1076 break; 1077 1078 // C++1y allows expression-statements. 1079 if (!Cxx1yLoc.isValid()) 1080 Cxx1yLoc = S->getLocStart(); 1081 return true; 1082 } 1083 1084 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1085 << isa<CXXConstructorDecl>(Dcl); 1086 return false; 1087 } 1088 1089 /// Check the body for the given constexpr function declaration only contains 1090 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1091 /// 1092 /// \return true if the body is OK, false if we have diagnosed a problem. 1093 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1094 if (isa<CXXTryStmt>(Body)) { 1095 // C++11 [dcl.constexpr]p3: 1096 // The definition of a constexpr function shall satisfy the following 1097 // constraints: [...] 1098 // - its function-body shall be = delete, = default, or a 1099 // compound-statement 1100 // 1101 // C++11 [dcl.constexpr]p4: 1102 // In the definition of a constexpr constructor, [...] 1103 // - its function-body shall not be a function-try-block; 1104 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1105 << isa<CXXConstructorDecl>(Dcl); 1106 return false; 1107 } 1108 1109 SmallVector<SourceLocation, 4> ReturnStmts; 1110 1111 // - its function-body shall be [...] a compound-statement that contains only 1112 // [... list of cases ...] 1113 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1114 SourceLocation Cxx1yLoc; 1115 for (auto *BodyIt : CompBody->body()) { 1116 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1117 return false; 1118 } 1119 1120 if (Cxx1yLoc.isValid()) 1121 Diag(Cxx1yLoc, 1122 getLangOpts().CPlusPlus14 1123 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1124 : diag::ext_constexpr_body_invalid_stmt) 1125 << isa<CXXConstructorDecl>(Dcl); 1126 1127 if (const CXXConstructorDecl *Constructor 1128 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1129 const CXXRecordDecl *RD = Constructor->getParent(); 1130 // DR1359: 1131 // - every non-variant non-static data member and base class sub-object 1132 // shall be initialized; 1133 // DR1460: 1134 // - if the class is a union having variant members, exactly one of them 1135 // shall be initialized; 1136 if (RD->isUnion()) { 1137 if (Constructor->getNumCtorInitializers() == 0 && 1138 RD->hasVariantMembers()) { 1139 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1140 return false; 1141 } 1142 } else if (!Constructor->isDependentContext() && 1143 !Constructor->isDelegatingConstructor()) { 1144 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1145 1146 // Skip detailed checking if we have enough initializers, and we would 1147 // allow at most one initializer per member. 1148 bool AnyAnonStructUnionMembers = false; 1149 unsigned Fields = 0; 1150 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1151 E = RD->field_end(); I != E; ++I, ++Fields) { 1152 if (I->isAnonymousStructOrUnion()) { 1153 AnyAnonStructUnionMembers = true; 1154 break; 1155 } 1156 } 1157 // DR1460: 1158 // - if the class is a union-like class, but is not a union, for each of 1159 // its anonymous union members having variant members, exactly one of 1160 // them shall be initialized; 1161 if (AnyAnonStructUnionMembers || 1162 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1163 // Check initialization of non-static data members. Base classes are 1164 // always initialized so do not need to be checked. Dependent bases 1165 // might not have initializers in the member initializer list. 1166 llvm::SmallSet<Decl*, 16> Inits; 1167 for (const auto *I: Constructor->inits()) { 1168 if (FieldDecl *FD = I->getMember()) 1169 Inits.insert(FD); 1170 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1171 Inits.insert(ID->chain_begin(), ID->chain_end()); 1172 } 1173 1174 bool Diagnosed = false; 1175 for (auto *I : RD->fields()) 1176 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1177 if (Diagnosed) 1178 return false; 1179 } 1180 } 1181 } else { 1182 if (ReturnStmts.empty()) { 1183 // C++1y doesn't require constexpr functions to contain a 'return' 1184 // statement. We still do, unless the return type might be void, because 1185 // otherwise if there's no return statement, the function cannot 1186 // be used in a core constant expression. 1187 bool OK = getLangOpts().CPlusPlus14 && 1188 (Dcl->getReturnType()->isVoidType() || 1189 Dcl->getReturnType()->isDependentType()); 1190 Diag(Dcl->getLocation(), 1191 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1192 : diag::err_constexpr_body_no_return); 1193 return OK; 1194 } 1195 if (ReturnStmts.size() > 1) { 1196 Diag(ReturnStmts.back(), 1197 getLangOpts().CPlusPlus14 1198 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1199 : diag::ext_constexpr_body_multiple_return); 1200 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1201 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1202 } 1203 } 1204 1205 // C++11 [dcl.constexpr]p5: 1206 // if no function argument values exist such that the function invocation 1207 // substitution would produce a constant expression, the program is 1208 // ill-formed; no diagnostic required. 1209 // C++11 [dcl.constexpr]p3: 1210 // - every constructor call and implicit conversion used in initializing the 1211 // return value shall be one of those allowed in a constant expression. 1212 // C++11 [dcl.constexpr]p4: 1213 // - every constructor involved in initializing non-static data members and 1214 // base class sub-objects shall be a constexpr constructor. 1215 SmallVector<PartialDiagnosticAt, 8> Diags; 1216 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1217 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1218 << isa<CXXConstructorDecl>(Dcl); 1219 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1220 Diag(Diags[I].first, Diags[I].second); 1221 // Don't return false here: we allow this for compatibility in 1222 // system headers. 1223 } 1224 1225 return true; 1226 } 1227 1228 /// isCurrentClassName - Determine whether the identifier II is the 1229 /// name of the class type currently being defined. In the case of 1230 /// nested classes, this will only return true if II is the name of 1231 /// the innermost class. 1232 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1233 const CXXScopeSpec *SS) { 1234 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1235 1236 CXXRecordDecl *CurDecl; 1237 if (SS && SS->isSet() && !SS->isInvalid()) { 1238 DeclContext *DC = computeDeclContext(*SS, true); 1239 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1240 } else 1241 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1242 1243 if (CurDecl && CurDecl->getIdentifier()) 1244 return &II == CurDecl->getIdentifier(); 1245 return false; 1246 } 1247 1248 /// \brief Determine whether the identifier II is a typo for the name of 1249 /// the class type currently being defined. If so, update it to the identifier 1250 /// that should have been used. 1251 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1252 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1253 1254 if (!getLangOpts().SpellChecking) 1255 return false; 1256 1257 CXXRecordDecl *CurDecl; 1258 if (SS && SS->isSet() && !SS->isInvalid()) { 1259 DeclContext *DC = computeDeclContext(*SS, true); 1260 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1261 } else 1262 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1263 1264 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1265 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1266 < II->getLength()) { 1267 II = CurDecl->getIdentifier(); 1268 return true; 1269 } 1270 1271 return false; 1272 } 1273 1274 /// \brief Determine whether the given class is a base class of the given 1275 /// class, including looking at dependent bases. 1276 static bool findCircularInheritance(const CXXRecordDecl *Class, 1277 const CXXRecordDecl *Current) { 1278 SmallVector<const CXXRecordDecl*, 8> Queue; 1279 1280 Class = Class->getCanonicalDecl(); 1281 while (true) { 1282 for (const auto &I : Current->bases()) { 1283 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1284 if (!Base) 1285 continue; 1286 1287 Base = Base->getDefinition(); 1288 if (!Base) 1289 continue; 1290 1291 if (Base->getCanonicalDecl() == Class) 1292 return true; 1293 1294 Queue.push_back(Base); 1295 } 1296 1297 if (Queue.empty()) 1298 return false; 1299 1300 Current = Queue.pop_back_val(); 1301 } 1302 1303 return false; 1304 } 1305 1306 /// \brief Perform propagation of DLL attributes from a derived class to a 1307 /// templated base class for MS compatibility. 1308 static void propagateDLLAttrToBaseClassTemplate( 1309 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr, 1310 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 1311 if (getDLLAttr( 1312 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 1313 // If the base class template has a DLL attribute, don't try to change it. 1314 return; 1315 } 1316 1317 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 1318 // If the base class is not already specialized, we can do the propagation. 1319 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 1320 NewAttr->setInherited(true); 1321 BaseTemplateSpec->addAttr(NewAttr); 1322 return; 1323 } 1324 1325 bool DifferentAttribute = false; 1326 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) { 1327 if (!SpecializationAttr->isInherited()) { 1328 // The template has previously been specialized or instantiated with an 1329 // explicit attribute. We should not try to change it. 1330 return; 1331 } 1332 if (SpecializationAttr->getKind() == ClassAttr->getKind()) { 1333 // The specialization already has the right attribute. 1334 return; 1335 } 1336 DifferentAttribute = true; 1337 } 1338 1339 // The template was previously instantiated or explicitly specialized without 1340 // a dll attribute, or the template was previously instantiated with a 1341 // different inherited attribute. It's too late for us to change the 1342 // attribute, so warn that this is unsupported. 1343 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 1344 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute; 1345 S.Diag(ClassAttr->getLocation(), diag::note_attribute); 1346 if (BaseTemplateSpec->isExplicitSpecialization()) { 1347 S.Diag(BaseTemplateSpec->getLocation(), 1348 diag::note_template_class_explicit_specialization_was_here) 1349 << BaseTemplateSpec; 1350 } else { 1351 S.Diag(BaseTemplateSpec->getPointOfInstantiation(), 1352 diag::note_template_class_instantiation_was_here) 1353 << BaseTemplateSpec; 1354 } 1355 } 1356 1357 /// \brief Check the validity of a C++ base class specifier. 1358 /// 1359 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1360 /// and returns NULL otherwise. 1361 CXXBaseSpecifier * 1362 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1363 SourceRange SpecifierRange, 1364 bool Virtual, AccessSpecifier Access, 1365 TypeSourceInfo *TInfo, 1366 SourceLocation EllipsisLoc) { 1367 QualType BaseType = TInfo->getType(); 1368 1369 // C++ [class.union]p1: 1370 // A union shall not have base classes. 1371 if (Class->isUnion()) { 1372 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1373 << SpecifierRange; 1374 return nullptr; 1375 } 1376 1377 if (EllipsisLoc.isValid() && 1378 !TInfo->getType()->containsUnexpandedParameterPack()) { 1379 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1380 << TInfo->getTypeLoc().getSourceRange(); 1381 EllipsisLoc = SourceLocation(); 1382 } 1383 1384 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1385 1386 if (BaseType->isDependentType()) { 1387 // Make sure that we don't have circular inheritance among our dependent 1388 // bases. For non-dependent bases, the check for completeness below handles 1389 // this. 1390 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1391 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1392 ((BaseDecl = BaseDecl->getDefinition()) && 1393 findCircularInheritance(Class, BaseDecl))) { 1394 Diag(BaseLoc, diag::err_circular_inheritance) 1395 << BaseType << Context.getTypeDeclType(Class); 1396 1397 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1398 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1399 << BaseType; 1400 1401 return nullptr; 1402 } 1403 } 1404 1405 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1406 Class->getTagKind() == TTK_Class, 1407 Access, TInfo, EllipsisLoc); 1408 } 1409 1410 // Base specifiers must be record types. 1411 if (!BaseType->isRecordType()) { 1412 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1413 return nullptr; 1414 } 1415 1416 // C++ [class.union]p1: 1417 // A union shall not be used as a base class. 1418 if (BaseType->isUnionType()) { 1419 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1420 return nullptr; 1421 } 1422 1423 // For the MS ABI, propagate DLL attributes to base class templates. 1424 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1425 if (Attr *ClassAttr = getDLLAttr(Class)) { 1426 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 1427 BaseType->getAsCXXRecordDecl())) { 1428 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr, 1429 BaseTemplate, BaseLoc); 1430 } 1431 } 1432 } 1433 1434 // C++ [class.derived]p2: 1435 // The class-name in a base-specifier shall not be an incompletely 1436 // defined class. 1437 if (RequireCompleteType(BaseLoc, BaseType, 1438 diag::err_incomplete_base_class, SpecifierRange)) { 1439 Class->setInvalidDecl(); 1440 return nullptr; 1441 } 1442 1443 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1444 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1445 assert(BaseDecl && "Record type has no declaration"); 1446 BaseDecl = BaseDecl->getDefinition(); 1447 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1448 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1449 assert(CXXBaseDecl && "Base type is not a C++ type"); 1450 1451 // A class which contains a flexible array member is not suitable for use as a 1452 // base class: 1453 // - If the layout determines that a base comes before another base, 1454 // the flexible array member would index into the subsequent base. 1455 // - If the layout determines that base comes before the derived class, 1456 // the flexible array member would index into the derived class. 1457 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1458 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1459 << CXXBaseDecl->getDeclName(); 1460 return nullptr; 1461 } 1462 1463 // C++ [class]p3: 1464 // If a class is marked final and it appears as a base-type-specifier in 1465 // base-clause, the program is ill-formed. 1466 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1467 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1468 << CXXBaseDecl->getDeclName() 1469 << FA->isSpelledAsSealed(); 1470 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 1471 << CXXBaseDecl->getDeclName() << FA->getRange(); 1472 return nullptr; 1473 } 1474 1475 if (BaseDecl->isInvalidDecl()) 1476 Class->setInvalidDecl(); 1477 1478 // Create the base specifier. 1479 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1480 Class->getTagKind() == TTK_Class, 1481 Access, TInfo, EllipsisLoc); 1482 } 1483 1484 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1485 /// one entry in the base class list of a class specifier, for 1486 /// example: 1487 /// class foo : public bar, virtual private baz { 1488 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1489 BaseResult 1490 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1491 ParsedAttributes &Attributes, 1492 bool Virtual, AccessSpecifier Access, 1493 ParsedType basetype, SourceLocation BaseLoc, 1494 SourceLocation EllipsisLoc) { 1495 if (!classdecl) 1496 return true; 1497 1498 AdjustDeclIfTemplate(classdecl); 1499 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1500 if (!Class) 1501 return true; 1502 1503 // We haven't yet attached the base specifiers. 1504 Class->setIsParsingBaseSpecifiers(); 1505 1506 // We do not support any C++11 attributes on base-specifiers yet. 1507 // Diagnose any attributes we see. 1508 if (!Attributes.empty()) { 1509 for (AttributeList *Attr = Attributes.getList(); Attr; 1510 Attr = Attr->getNext()) { 1511 if (Attr->isInvalid() || 1512 Attr->getKind() == AttributeList::IgnoredAttribute) 1513 continue; 1514 Diag(Attr->getLoc(), 1515 Attr->getKind() == AttributeList::UnknownAttribute 1516 ? diag::warn_unknown_attribute_ignored 1517 : diag::err_base_specifier_attribute) 1518 << Attr->getName(); 1519 } 1520 } 1521 1522 TypeSourceInfo *TInfo = nullptr; 1523 GetTypeFromParser(basetype, &TInfo); 1524 1525 if (EllipsisLoc.isInvalid() && 1526 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1527 UPPC_BaseType)) 1528 return true; 1529 1530 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1531 Virtual, Access, TInfo, 1532 EllipsisLoc)) 1533 return BaseSpec; 1534 else 1535 Class->setInvalidDecl(); 1536 1537 return true; 1538 } 1539 1540 /// \brief Performs the actual work of attaching the given base class 1541 /// specifiers to a C++ class. 1542 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1543 unsigned NumBases) { 1544 if (NumBases == 0) 1545 return false; 1546 1547 // Used to keep track of which base types we have already seen, so 1548 // that we can properly diagnose redundant direct base types. Note 1549 // that the key is always the unqualified canonical type of the base 1550 // class. 1551 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1552 1553 // Copy non-redundant base specifiers into permanent storage. 1554 unsigned NumGoodBases = 0; 1555 bool Invalid = false; 1556 for (unsigned idx = 0; idx < NumBases; ++idx) { 1557 QualType NewBaseType 1558 = Context.getCanonicalType(Bases[idx]->getType()); 1559 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1560 1561 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1562 if (KnownBase) { 1563 // C++ [class.mi]p3: 1564 // A class shall not be specified as a direct base class of a 1565 // derived class more than once. 1566 Diag(Bases[idx]->getLocStart(), 1567 diag::err_duplicate_base_class) 1568 << KnownBase->getType() 1569 << Bases[idx]->getSourceRange(); 1570 1571 // Delete the duplicate base class specifier; we're going to 1572 // overwrite its pointer later. 1573 Context.Deallocate(Bases[idx]); 1574 1575 Invalid = true; 1576 } else { 1577 // Okay, add this new base class. 1578 KnownBase = Bases[idx]; 1579 Bases[NumGoodBases++] = Bases[idx]; 1580 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1581 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1582 if (Class->isInterface() && 1583 (!RD->isInterface() || 1584 KnownBase->getAccessSpecifier() != AS_public)) { 1585 // The Microsoft extension __interface does not permit bases that 1586 // are not themselves public interfaces. 1587 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1588 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1589 << RD->getSourceRange(); 1590 Invalid = true; 1591 } 1592 if (RD->hasAttr<WeakAttr>()) 1593 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1594 } 1595 } 1596 } 1597 1598 // Attach the remaining base class specifiers to the derived class. 1599 Class->setBases(Bases, NumGoodBases); 1600 1601 // Delete the remaining (good) base class specifiers, since their 1602 // data has been copied into the CXXRecordDecl. 1603 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1604 Context.Deallocate(Bases[idx]); 1605 1606 return Invalid; 1607 } 1608 1609 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1610 /// class, after checking whether there are any duplicate base 1611 /// classes. 1612 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1613 unsigned NumBases) { 1614 if (!ClassDecl || !Bases || !NumBases) 1615 return; 1616 1617 AdjustDeclIfTemplate(ClassDecl); 1618 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1619 } 1620 1621 /// \brief Determine whether the type \p Derived is a C++ class that is 1622 /// derived from the type \p Base. 1623 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1624 if (!getLangOpts().CPlusPlus) 1625 return false; 1626 1627 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1628 if (!DerivedRD) 1629 return false; 1630 1631 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1632 if (!BaseRD) 1633 return false; 1634 1635 // If either the base or the derived type is invalid, don't try to 1636 // check whether one is derived from the other. 1637 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1638 return false; 1639 1640 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1641 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1642 } 1643 1644 /// \brief Determine whether the type \p Derived is a C++ class that is 1645 /// derived from the type \p Base. 1646 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1647 if (!getLangOpts().CPlusPlus) 1648 return false; 1649 1650 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1651 if (!DerivedRD) 1652 return false; 1653 1654 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1655 if (!BaseRD) 1656 return false; 1657 1658 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1659 } 1660 1661 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1662 CXXCastPath &BasePathArray) { 1663 assert(BasePathArray.empty() && "Base path array must be empty!"); 1664 assert(Paths.isRecordingPaths() && "Must record paths!"); 1665 1666 const CXXBasePath &Path = Paths.front(); 1667 1668 // We first go backward and check if we have a virtual base. 1669 // FIXME: It would be better if CXXBasePath had the base specifier for 1670 // the nearest virtual base. 1671 unsigned Start = 0; 1672 for (unsigned I = Path.size(); I != 0; --I) { 1673 if (Path[I - 1].Base->isVirtual()) { 1674 Start = I - 1; 1675 break; 1676 } 1677 } 1678 1679 // Now add all bases. 1680 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1681 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1682 } 1683 1684 /// \brief Determine whether the given base path includes a virtual 1685 /// base class. 1686 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1687 for (CXXCastPath::const_iterator B = BasePath.begin(), 1688 BEnd = BasePath.end(); 1689 B != BEnd; ++B) 1690 if ((*B)->isVirtual()) 1691 return true; 1692 1693 return false; 1694 } 1695 1696 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1697 /// conversion (where Derived and Base are class types) is 1698 /// well-formed, meaning that the conversion is unambiguous (and 1699 /// that all of the base classes are accessible). Returns true 1700 /// and emits a diagnostic if the code is ill-formed, returns false 1701 /// otherwise. Loc is the location where this routine should point to 1702 /// if there is an error, and Range is the source range to highlight 1703 /// if there is an error. 1704 bool 1705 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1706 unsigned InaccessibleBaseID, 1707 unsigned AmbigiousBaseConvID, 1708 SourceLocation Loc, SourceRange Range, 1709 DeclarationName Name, 1710 CXXCastPath *BasePath) { 1711 // First, determine whether the path from Derived to Base is 1712 // ambiguous. This is slightly more expensive than checking whether 1713 // the Derived to Base conversion exists, because here we need to 1714 // explore multiple paths to determine if there is an ambiguity. 1715 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1716 /*DetectVirtual=*/false); 1717 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1718 assert(DerivationOkay && 1719 "Can only be used with a derived-to-base conversion"); 1720 (void)DerivationOkay; 1721 1722 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1723 if (InaccessibleBaseID) { 1724 // Check that the base class can be accessed. 1725 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1726 InaccessibleBaseID)) { 1727 case AR_inaccessible: 1728 return true; 1729 case AR_accessible: 1730 case AR_dependent: 1731 case AR_delayed: 1732 break; 1733 } 1734 } 1735 1736 // Build a base path if necessary. 1737 if (BasePath) 1738 BuildBasePathArray(Paths, *BasePath); 1739 return false; 1740 } 1741 1742 if (AmbigiousBaseConvID) { 1743 // We know that the derived-to-base conversion is ambiguous, and 1744 // we're going to produce a diagnostic. Perform the derived-to-base 1745 // search just one more time to compute all of the possible paths so 1746 // that we can print them out. This is more expensive than any of 1747 // the previous derived-to-base checks we've done, but at this point 1748 // performance isn't as much of an issue. 1749 Paths.clear(); 1750 Paths.setRecordingPaths(true); 1751 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1752 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1753 (void)StillOkay; 1754 1755 // Build up a textual representation of the ambiguous paths, e.g., 1756 // D -> B -> A, that will be used to illustrate the ambiguous 1757 // conversions in the diagnostic. We only print one of the paths 1758 // to each base class subobject. 1759 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1760 1761 Diag(Loc, AmbigiousBaseConvID) 1762 << Derived << Base << PathDisplayStr << Range << Name; 1763 } 1764 return true; 1765 } 1766 1767 bool 1768 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1769 SourceLocation Loc, SourceRange Range, 1770 CXXCastPath *BasePath, 1771 bool IgnoreAccess) { 1772 return CheckDerivedToBaseConversion(Derived, Base, 1773 IgnoreAccess ? 0 1774 : diag::err_upcast_to_inaccessible_base, 1775 diag::err_ambiguous_derived_to_base_conv, 1776 Loc, Range, DeclarationName(), 1777 BasePath); 1778 } 1779 1780 1781 /// @brief Builds a string representing ambiguous paths from a 1782 /// specific derived class to different subobjects of the same base 1783 /// class. 1784 /// 1785 /// This function builds a string that can be used in error messages 1786 /// to show the different paths that one can take through the 1787 /// inheritance hierarchy to go from the derived class to different 1788 /// subobjects of a base class. The result looks something like this: 1789 /// @code 1790 /// struct D -> struct B -> struct A 1791 /// struct D -> struct C -> struct A 1792 /// @endcode 1793 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1794 std::string PathDisplayStr; 1795 std::set<unsigned> DisplayedPaths; 1796 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1797 Path != Paths.end(); ++Path) { 1798 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1799 // We haven't displayed a path to this particular base 1800 // class subobject yet. 1801 PathDisplayStr += "\n "; 1802 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1803 for (CXXBasePath::const_iterator Element = Path->begin(); 1804 Element != Path->end(); ++Element) 1805 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1806 } 1807 } 1808 1809 return PathDisplayStr; 1810 } 1811 1812 //===----------------------------------------------------------------------===// 1813 // C++ class member Handling 1814 //===----------------------------------------------------------------------===// 1815 1816 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1817 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1818 SourceLocation ASLoc, 1819 SourceLocation ColonLoc, 1820 AttributeList *Attrs) { 1821 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1822 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1823 ASLoc, ColonLoc); 1824 CurContext->addHiddenDecl(ASDecl); 1825 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1826 } 1827 1828 /// CheckOverrideControl - Check C++11 override control semantics. 1829 void Sema::CheckOverrideControl(NamedDecl *D) { 1830 if (D->isInvalidDecl()) 1831 return; 1832 1833 // We only care about "override" and "final" declarations. 1834 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1835 return; 1836 1837 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1838 1839 // We can't check dependent instance methods. 1840 if (MD && MD->isInstance() && 1841 (MD->getParent()->hasAnyDependentBases() || 1842 MD->getType()->isDependentType())) 1843 return; 1844 1845 if (MD && !MD->isVirtual()) { 1846 // If we have a non-virtual method, check if if hides a virtual method. 1847 // (In that case, it's most likely the method has the wrong type.) 1848 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1849 FindHiddenVirtualMethods(MD, OverloadedMethods); 1850 1851 if (!OverloadedMethods.empty()) { 1852 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1853 Diag(OA->getLocation(), 1854 diag::override_keyword_hides_virtual_member_function) 1855 << "override" << (OverloadedMethods.size() > 1); 1856 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1857 Diag(FA->getLocation(), 1858 diag::override_keyword_hides_virtual_member_function) 1859 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1860 << (OverloadedMethods.size() > 1); 1861 } 1862 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1863 MD->setInvalidDecl(); 1864 return; 1865 } 1866 // Fall through into the general case diagnostic. 1867 // FIXME: We might want to attempt typo correction here. 1868 } 1869 1870 if (!MD || !MD->isVirtual()) { 1871 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1872 Diag(OA->getLocation(), 1873 diag::override_keyword_only_allowed_on_virtual_member_functions) 1874 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1875 D->dropAttr<OverrideAttr>(); 1876 } 1877 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1878 Diag(FA->getLocation(), 1879 diag::override_keyword_only_allowed_on_virtual_member_functions) 1880 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1881 << FixItHint::CreateRemoval(FA->getLocation()); 1882 D->dropAttr<FinalAttr>(); 1883 } 1884 return; 1885 } 1886 1887 // C++11 [class.virtual]p5: 1888 // If a virtual function is marked with the virt-specifier override and 1889 // does not override a member function of a base class, the program is 1890 // ill-formed. 1891 bool HasOverriddenMethods = 1892 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1893 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1894 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1895 << MD->getDeclName(); 1896 } 1897 1898 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1899 /// function overrides a virtual member function marked 'final', according to 1900 /// C++11 [class.virtual]p4. 1901 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1902 const CXXMethodDecl *Old) { 1903 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1904 if (!FA) 1905 return false; 1906 1907 Diag(New->getLocation(), diag::err_final_function_overridden) 1908 << New->getDeclName() 1909 << FA->isSpelledAsSealed(); 1910 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1911 return true; 1912 } 1913 1914 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1915 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1916 // FIXME: Destruction of ObjC lifetime types has side-effects. 1917 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1918 return !RD->isCompleteDefinition() || 1919 !RD->hasTrivialDefaultConstructor() || 1920 !RD->hasTrivialDestructor(); 1921 return false; 1922 } 1923 1924 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1925 for (AttributeList *it = list; it != nullptr; it = it->getNext()) 1926 if (it->isDeclspecPropertyAttribute()) 1927 return it; 1928 return nullptr; 1929 } 1930 1931 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1932 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1933 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1934 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1935 /// present (but parsing it has been deferred). 1936 NamedDecl * 1937 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1938 MultiTemplateParamsArg TemplateParameterLists, 1939 Expr *BW, const VirtSpecifiers &VS, 1940 InClassInitStyle InitStyle) { 1941 const DeclSpec &DS = D.getDeclSpec(); 1942 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1943 DeclarationName Name = NameInfo.getName(); 1944 SourceLocation Loc = NameInfo.getLoc(); 1945 1946 // For anonymous bitfields, the location should point to the type. 1947 if (Loc.isInvalid()) 1948 Loc = D.getLocStart(); 1949 1950 Expr *BitWidth = static_cast<Expr*>(BW); 1951 1952 assert(isa<CXXRecordDecl>(CurContext)); 1953 assert(!DS.isFriendSpecified()); 1954 1955 bool isFunc = D.isDeclarationOfFunction(); 1956 1957 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1958 // The Microsoft extension __interface only permits public member functions 1959 // and prohibits constructors, destructors, operators, non-public member 1960 // functions, static methods and data members. 1961 unsigned InvalidDecl; 1962 bool ShowDeclName = true; 1963 if (!isFunc) 1964 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1965 else if (AS != AS_public) 1966 InvalidDecl = 2; 1967 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1968 InvalidDecl = 3; 1969 else switch (Name.getNameKind()) { 1970 case DeclarationName::CXXConstructorName: 1971 InvalidDecl = 4; 1972 ShowDeclName = false; 1973 break; 1974 1975 case DeclarationName::CXXDestructorName: 1976 InvalidDecl = 5; 1977 ShowDeclName = false; 1978 break; 1979 1980 case DeclarationName::CXXOperatorName: 1981 case DeclarationName::CXXConversionFunctionName: 1982 InvalidDecl = 6; 1983 break; 1984 1985 default: 1986 InvalidDecl = 0; 1987 break; 1988 } 1989 1990 if (InvalidDecl) { 1991 if (ShowDeclName) 1992 Diag(Loc, diag::err_invalid_member_in_interface) 1993 << (InvalidDecl-1) << Name; 1994 else 1995 Diag(Loc, diag::err_invalid_member_in_interface) 1996 << (InvalidDecl-1) << ""; 1997 return nullptr; 1998 } 1999 } 2000 2001 // C++ 9.2p6: A member shall not be declared to have automatic storage 2002 // duration (auto, register) or with the extern storage-class-specifier. 2003 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 2004 // data members and cannot be applied to names declared const or static, 2005 // and cannot be applied to reference members. 2006 switch (DS.getStorageClassSpec()) { 2007 case DeclSpec::SCS_unspecified: 2008 case DeclSpec::SCS_typedef: 2009 case DeclSpec::SCS_static: 2010 break; 2011 case DeclSpec::SCS_mutable: 2012 if (isFunc) { 2013 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 2014 2015 // FIXME: It would be nicer if the keyword was ignored only for this 2016 // declarator. Otherwise we could get follow-up errors. 2017 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2018 } 2019 break; 2020 default: 2021 Diag(DS.getStorageClassSpecLoc(), 2022 diag::err_storageclass_invalid_for_member); 2023 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2024 break; 2025 } 2026 2027 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 2028 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 2029 !isFunc); 2030 2031 if (DS.isConstexprSpecified() && isInstField) { 2032 SemaDiagnosticBuilder B = 2033 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 2034 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 2035 if (InitStyle == ICIS_NoInit) { 2036 B << 0 << 0; 2037 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 2038 B << FixItHint::CreateRemoval(ConstexprLoc); 2039 else { 2040 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 2041 D.getMutableDeclSpec().ClearConstexprSpec(); 2042 const char *PrevSpec; 2043 unsigned DiagID; 2044 bool Failed = D.getMutableDeclSpec().SetTypeQual( 2045 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 2046 (void)Failed; 2047 assert(!Failed && "Making a constexpr member const shouldn't fail"); 2048 } 2049 } else { 2050 B << 1; 2051 const char *PrevSpec; 2052 unsigned DiagID; 2053 if (D.getMutableDeclSpec().SetStorageClassSpec( 2054 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 2055 Context.getPrintingPolicy())) { 2056 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 2057 "This is the only DeclSpec that should fail to be applied"); 2058 B << 1; 2059 } else { 2060 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 2061 isInstField = false; 2062 } 2063 } 2064 } 2065 2066 NamedDecl *Member; 2067 if (isInstField) { 2068 CXXScopeSpec &SS = D.getCXXScopeSpec(); 2069 2070 // Data members must have identifiers for names. 2071 if (!Name.isIdentifier()) { 2072 Diag(Loc, diag::err_bad_variable_name) 2073 << Name; 2074 return nullptr; 2075 } 2076 2077 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2078 2079 // Member field could not be with "template" keyword. 2080 // So TemplateParameterLists should be empty in this case. 2081 if (TemplateParameterLists.size()) { 2082 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2083 if (TemplateParams->size()) { 2084 // There is no such thing as a member field template. 2085 Diag(D.getIdentifierLoc(), diag::err_template_member) 2086 << II 2087 << SourceRange(TemplateParams->getTemplateLoc(), 2088 TemplateParams->getRAngleLoc()); 2089 } else { 2090 // There is an extraneous 'template<>' for this member. 2091 Diag(TemplateParams->getTemplateLoc(), 2092 diag::err_template_member_noparams) 2093 << II 2094 << SourceRange(TemplateParams->getTemplateLoc(), 2095 TemplateParams->getRAngleLoc()); 2096 } 2097 return nullptr; 2098 } 2099 2100 if (SS.isSet() && !SS.isInvalid()) { 2101 // The user provided a superfluous scope specifier inside a class 2102 // definition: 2103 // 2104 // class X { 2105 // int X::member; 2106 // }; 2107 if (DeclContext *DC = computeDeclContext(SS, false)) 2108 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2109 else 2110 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2111 << Name << SS.getRange(); 2112 2113 SS.clear(); 2114 } 2115 2116 AttributeList *MSPropertyAttr = 2117 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2118 if (MSPropertyAttr) { 2119 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2120 BitWidth, InitStyle, AS, MSPropertyAttr); 2121 if (!Member) 2122 return nullptr; 2123 isInstField = false; 2124 } else { 2125 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2126 BitWidth, InitStyle, AS); 2127 assert(Member && "HandleField never returns null"); 2128 } 2129 } else { 2130 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2131 2132 Member = HandleDeclarator(S, D, TemplateParameterLists); 2133 if (!Member) 2134 return nullptr; 2135 2136 // Non-instance-fields can't have a bitfield. 2137 if (BitWidth) { 2138 if (Member->isInvalidDecl()) { 2139 // don't emit another diagnostic. 2140 } else if (isa<VarDecl>(Member)) { 2141 // C++ 9.6p3: A bit-field shall not be a static member. 2142 // "static member 'A' cannot be a bit-field" 2143 Diag(Loc, diag::err_static_not_bitfield) 2144 << Name << BitWidth->getSourceRange(); 2145 } else if (isa<TypedefDecl>(Member)) { 2146 // "typedef member 'x' cannot be a bit-field" 2147 Diag(Loc, diag::err_typedef_not_bitfield) 2148 << Name << BitWidth->getSourceRange(); 2149 } else { 2150 // A function typedef ("typedef int f(); f a;"). 2151 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2152 Diag(Loc, diag::err_not_integral_type_bitfield) 2153 << Name << cast<ValueDecl>(Member)->getType() 2154 << BitWidth->getSourceRange(); 2155 } 2156 2157 BitWidth = nullptr; 2158 Member->setInvalidDecl(); 2159 } 2160 2161 Member->setAccess(AS); 2162 2163 // If we have declared a member function template or static data member 2164 // template, set the access of the templated declaration as well. 2165 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2166 FunTmpl->getTemplatedDecl()->setAccess(AS); 2167 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2168 VarTmpl->getTemplatedDecl()->setAccess(AS); 2169 } 2170 2171 if (VS.isOverrideSpecified()) 2172 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2173 if (VS.isFinalSpecified()) 2174 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2175 VS.isFinalSpelledSealed())); 2176 2177 if (VS.getLastLocation().isValid()) { 2178 // Update the end location of a method that has a virt-specifiers. 2179 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2180 MD->setRangeEnd(VS.getLastLocation()); 2181 } 2182 2183 CheckOverrideControl(Member); 2184 2185 assert((Name || isInstField) && "No identifier for non-field ?"); 2186 2187 if (isInstField) { 2188 FieldDecl *FD = cast<FieldDecl>(Member); 2189 FieldCollector->Add(FD); 2190 2191 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 2192 // Remember all explicit private FieldDecls that have a name, no side 2193 // effects and are not part of a dependent type declaration. 2194 if (!FD->isImplicit() && FD->getDeclName() && 2195 FD->getAccess() == AS_private && 2196 !FD->hasAttr<UnusedAttr>() && 2197 !FD->getParent()->isDependentContext() && 2198 !InitializationHasSideEffects(*FD)) 2199 UnusedPrivateFields.insert(FD); 2200 } 2201 } 2202 2203 return Member; 2204 } 2205 2206 namespace { 2207 class UninitializedFieldVisitor 2208 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2209 Sema &S; 2210 // List of Decls to generate a warning on. Also remove Decls that become 2211 // initialized. 2212 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 2213 // Vector of decls to be removed from the Decl set prior to visiting the 2214 // nodes. These Decls may have been initialized in the prior initializer. 2215 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 2216 // If non-null, add a note to the warning pointing back to the constructor. 2217 const CXXConstructorDecl *Constructor; 2218 public: 2219 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2220 UninitializedFieldVisitor(Sema &S, 2221 llvm::SmallPtrSetImpl<ValueDecl*> &Decls) 2222 : Inherited(S.Context), S(S), Decls(Decls) { } 2223 2224 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) { 2225 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2226 return; 2227 2228 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2229 // or union. 2230 MemberExpr *FieldME = ME; 2231 2232 Expr *Base = ME; 2233 while (isa<MemberExpr>(Base)) { 2234 ME = cast<MemberExpr>(Base); 2235 2236 if (isa<VarDecl>(ME->getMemberDecl())) 2237 return; 2238 2239 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2240 if (!FD->isAnonymousStructOrUnion()) 2241 FieldME = ME; 2242 2243 Base = ME->getBase(); 2244 } 2245 2246 if (!isa<CXXThisExpr>(Base)) 2247 return; 2248 2249 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2250 2251 if (!Decls.count(FoundVD)) 2252 return; 2253 2254 const bool IsReference = FoundVD->getType()->isReferenceType(); 2255 2256 // Prevent double warnings on use of unbounded references. 2257 if (IsReference != CheckReferenceOnly) 2258 return; 2259 2260 unsigned diag = IsReference 2261 ? diag::warn_reference_field_is_uninit 2262 : diag::warn_field_is_uninit; 2263 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2264 if (Constructor) 2265 S.Diag(Constructor->getLocation(), 2266 diag::note_uninit_in_this_constructor) 2267 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2268 2269 } 2270 2271 void HandleValue(Expr *E) { 2272 E = E->IgnoreParens(); 2273 2274 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2275 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2276 return; 2277 } 2278 2279 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2280 HandleValue(CO->getTrueExpr()); 2281 HandleValue(CO->getFalseExpr()); 2282 return; 2283 } 2284 2285 if (BinaryConditionalOperator *BCO = 2286 dyn_cast<BinaryConditionalOperator>(E)) { 2287 HandleValue(BCO->getFalseExpr()); 2288 return; 2289 } 2290 2291 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 2292 HandleValue(OVE->getSourceExpr()); 2293 return; 2294 } 2295 2296 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2297 switch (BO->getOpcode()) { 2298 default: 2299 return; 2300 case(BO_PtrMemD): 2301 case(BO_PtrMemI): 2302 HandleValue(BO->getLHS()); 2303 return; 2304 case(BO_Comma): 2305 HandleValue(BO->getRHS()); 2306 return; 2307 } 2308 } 2309 } 2310 2311 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 2312 FieldDecl *Field) { 2313 // Remove Decls that may have been initialized in the previous 2314 // initializer. 2315 for (ValueDecl* VD : DeclsToRemove) 2316 Decls.erase(VD); 2317 2318 DeclsToRemove.clear(); 2319 Constructor = FieldConstructor; 2320 Visit(E); 2321 if (Field) 2322 Decls.erase(Field); 2323 } 2324 2325 void VisitMemberExpr(MemberExpr *ME) { 2326 // All uses of unbounded reference fields will warn. 2327 HandleMemberExpr(ME, true /*CheckReferenceOnly*/); 2328 2329 Inherited::VisitMemberExpr(ME); 2330 } 2331 2332 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2333 if (E->getCastKind() == CK_LValueToRValue) 2334 HandleValue(E->getSubExpr()); 2335 2336 Inherited::VisitImplicitCastExpr(E); 2337 } 2338 2339 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2340 if (E->getConstructor()->isCopyConstructor()) { 2341 Expr *ArgExpr = E->getArg(0); 2342 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) { 2343 if (ICE->getCastKind() == CK_NoOp) { 2344 ArgExpr = ICE->getSubExpr(); 2345 } 2346 } 2347 2348 if (MemberExpr *ME = dyn_cast<MemberExpr>(ArgExpr)) { 2349 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2350 } 2351 } 2352 Inherited::VisitCXXConstructExpr(E); 2353 } 2354 2355 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2356 Expr *Callee = E->getCallee(); 2357 if (isa<MemberExpr>(Callee)) 2358 HandleValue(Callee); 2359 2360 Inherited::VisitCXXMemberCallExpr(E); 2361 } 2362 2363 void VisitCallExpr(CallExpr *E) { 2364 // Treat std::move as a use. 2365 if (E->getNumArgs() == 1) { 2366 if (FunctionDecl *FD = E->getDirectCallee()) { 2367 if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) { 2368 HandleValue(E->getArg(0)); 2369 } 2370 } 2371 } 2372 2373 Inherited::VisitCallExpr(E); 2374 } 2375 2376 void VisitBinaryOperator(BinaryOperator *E) { 2377 // If a field assignment is detected, remove the field from the 2378 // uninitiailized field set. 2379 if (E->getOpcode() == BO_Assign) 2380 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2381 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2382 if (!FD->getType()->isReferenceType()) 2383 DeclsToRemove.push_back(FD); 2384 2385 if (E->isCompoundAssignmentOp()) { 2386 HandleValue(E->getLHS()); 2387 } 2388 2389 Inherited::VisitBinaryOperator(E); 2390 } 2391 2392 void VisitUnaryOperator(UnaryOperator *E) { 2393 if (E->isIncrementDecrementOp()) 2394 HandleValue(E->getSubExpr()); 2395 2396 Inherited::VisitUnaryOperator(E); 2397 } 2398 }; 2399 2400 // Diagnose value-uses of fields to initialize themselves, e.g. 2401 // foo(foo) 2402 // where foo is not also a parameter to the constructor. 2403 // Also diagnose across field uninitialized use such as 2404 // x(y), y(x) 2405 // TODO: implement -Wuninitialized and fold this into that framework. 2406 static void DiagnoseUninitializedFields( 2407 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2408 2409 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 2410 Constructor->getLocation())) { 2411 return; 2412 } 2413 2414 if (Constructor->isInvalidDecl()) 2415 return; 2416 2417 const CXXRecordDecl *RD = Constructor->getParent(); 2418 2419 // Holds fields that are uninitialized. 2420 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2421 2422 // At the beginning, all fields are uninitialized. 2423 for (auto *I : RD->decls()) { 2424 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2425 UninitializedFields.insert(FD); 2426 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2427 UninitializedFields.insert(IFD->getAnonField()); 2428 } 2429 } 2430 2431 if (UninitializedFields.empty()) 2432 return; 2433 2434 UninitializedFieldVisitor UninitializedChecker(SemaRef, 2435 UninitializedFields); 2436 2437 for (const auto *FieldInit : Constructor->inits()) { 2438 if (UninitializedFields.empty()) 2439 break; 2440 2441 Expr *InitExpr = FieldInit->getInit(); 2442 if (!InitExpr) 2443 continue; 2444 2445 if (CXXDefaultInitExpr *Default = 2446 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 2447 InitExpr = Default->getExpr(); 2448 if (!InitExpr) 2449 continue; 2450 // In class initializers will point to the constructor. 2451 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 2452 FieldInit->getAnyMember()); 2453 } else { 2454 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 2455 FieldInit->getAnyMember()); 2456 } 2457 } 2458 } 2459 } // namespace 2460 2461 /// \brief Enter a new C++ default initializer scope. After calling this, the 2462 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2463 /// parsing or instantiating the initializer failed. 2464 void Sema::ActOnStartCXXInClassMemberInitializer() { 2465 // Create a synthetic function scope to represent the call to the constructor 2466 // that notionally surrounds a use of this initializer. 2467 PushFunctionScope(); 2468 } 2469 2470 /// \brief This is invoked after parsing an in-class initializer for a 2471 /// non-static C++ class member, and after instantiating an in-class initializer 2472 /// in a class template. Such actions are deferred until the class is complete. 2473 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2474 SourceLocation InitLoc, 2475 Expr *InitExpr) { 2476 // Pop the notional constructor scope we created earlier. 2477 PopFunctionScopeInfo(nullptr, D); 2478 2479 FieldDecl *FD = cast<FieldDecl>(D); 2480 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2481 "must set init style when field is created"); 2482 2483 if (!InitExpr) { 2484 FD->setInvalidDecl(); 2485 FD->removeInClassInitializer(); 2486 return; 2487 } 2488 2489 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2490 FD->setInvalidDecl(); 2491 FD->removeInClassInitializer(); 2492 return; 2493 } 2494 2495 ExprResult Init = InitExpr; 2496 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2497 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2498 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2499 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2500 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2501 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2502 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2503 if (Init.isInvalid()) { 2504 FD->setInvalidDecl(); 2505 return; 2506 } 2507 } 2508 2509 // C++11 [class.base.init]p7: 2510 // The initialization of each base and member constitutes a 2511 // full-expression. 2512 Init = ActOnFinishFullExpr(Init.get(), InitLoc); 2513 if (Init.isInvalid()) { 2514 FD->setInvalidDecl(); 2515 return; 2516 } 2517 2518 InitExpr = Init.get(); 2519 2520 FD->setInClassInitializer(InitExpr); 2521 } 2522 2523 /// \brief Find the direct and/or virtual base specifiers that 2524 /// correspond to the given base type, for use in base initialization 2525 /// within a constructor. 2526 static bool FindBaseInitializer(Sema &SemaRef, 2527 CXXRecordDecl *ClassDecl, 2528 QualType BaseType, 2529 const CXXBaseSpecifier *&DirectBaseSpec, 2530 const CXXBaseSpecifier *&VirtualBaseSpec) { 2531 // First, check for a direct base class. 2532 DirectBaseSpec = nullptr; 2533 for (const auto &Base : ClassDecl->bases()) { 2534 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2535 // We found a direct base of this type. That's what we're 2536 // initializing. 2537 DirectBaseSpec = &Base; 2538 break; 2539 } 2540 } 2541 2542 // Check for a virtual base class. 2543 // FIXME: We might be able to short-circuit this if we know in advance that 2544 // there are no virtual bases. 2545 VirtualBaseSpec = nullptr; 2546 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2547 // We haven't found a base yet; search the class hierarchy for a 2548 // virtual base class. 2549 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2550 /*DetectVirtual=*/false); 2551 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2552 BaseType, Paths)) { 2553 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2554 Path != Paths.end(); ++Path) { 2555 if (Path->back().Base->isVirtual()) { 2556 VirtualBaseSpec = Path->back().Base; 2557 break; 2558 } 2559 } 2560 } 2561 } 2562 2563 return DirectBaseSpec || VirtualBaseSpec; 2564 } 2565 2566 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2567 MemInitResult 2568 Sema::ActOnMemInitializer(Decl *ConstructorD, 2569 Scope *S, 2570 CXXScopeSpec &SS, 2571 IdentifierInfo *MemberOrBase, 2572 ParsedType TemplateTypeTy, 2573 const DeclSpec &DS, 2574 SourceLocation IdLoc, 2575 Expr *InitList, 2576 SourceLocation EllipsisLoc) { 2577 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2578 DS, IdLoc, InitList, 2579 EllipsisLoc); 2580 } 2581 2582 /// \brief Handle a C++ member initializer using parentheses syntax. 2583 MemInitResult 2584 Sema::ActOnMemInitializer(Decl *ConstructorD, 2585 Scope *S, 2586 CXXScopeSpec &SS, 2587 IdentifierInfo *MemberOrBase, 2588 ParsedType TemplateTypeTy, 2589 const DeclSpec &DS, 2590 SourceLocation IdLoc, 2591 SourceLocation LParenLoc, 2592 ArrayRef<Expr *> Args, 2593 SourceLocation RParenLoc, 2594 SourceLocation EllipsisLoc) { 2595 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2596 Args, RParenLoc); 2597 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2598 DS, IdLoc, List, EllipsisLoc); 2599 } 2600 2601 namespace { 2602 2603 // Callback to only accept typo corrections that can be a valid C++ member 2604 // intializer: either a non-static field member or a base class. 2605 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2606 public: 2607 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2608 : ClassDecl(ClassDecl) {} 2609 2610 bool ValidateCandidate(const TypoCorrection &candidate) override { 2611 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2612 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2613 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2614 return isa<TypeDecl>(ND); 2615 } 2616 return false; 2617 } 2618 2619 private: 2620 CXXRecordDecl *ClassDecl; 2621 }; 2622 2623 } 2624 2625 /// \brief Handle a C++ member initializer. 2626 MemInitResult 2627 Sema::BuildMemInitializer(Decl *ConstructorD, 2628 Scope *S, 2629 CXXScopeSpec &SS, 2630 IdentifierInfo *MemberOrBase, 2631 ParsedType TemplateTypeTy, 2632 const DeclSpec &DS, 2633 SourceLocation IdLoc, 2634 Expr *Init, 2635 SourceLocation EllipsisLoc) { 2636 if (!ConstructorD) 2637 return true; 2638 2639 AdjustDeclIfTemplate(ConstructorD); 2640 2641 CXXConstructorDecl *Constructor 2642 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2643 if (!Constructor) { 2644 // The user wrote a constructor initializer on a function that is 2645 // not a C++ constructor. Ignore the error for now, because we may 2646 // have more member initializers coming; we'll diagnose it just 2647 // once in ActOnMemInitializers. 2648 return true; 2649 } 2650 2651 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2652 2653 // C++ [class.base.init]p2: 2654 // Names in a mem-initializer-id are looked up in the scope of the 2655 // constructor's class and, if not found in that scope, are looked 2656 // up in the scope containing the constructor's definition. 2657 // [Note: if the constructor's class contains a member with the 2658 // same name as a direct or virtual base class of the class, a 2659 // mem-initializer-id naming the member or base class and composed 2660 // of a single identifier refers to the class member. A 2661 // mem-initializer-id for the hidden base class may be specified 2662 // using a qualified name. ] 2663 if (!SS.getScopeRep() && !TemplateTypeTy) { 2664 // Look for a member, first. 2665 DeclContext::lookup_result Result 2666 = ClassDecl->lookup(MemberOrBase); 2667 if (!Result.empty()) { 2668 ValueDecl *Member; 2669 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2670 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2671 if (EllipsisLoc.isValid()) 2672 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2673 << MemberOrBase 2674 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2675 2676 return BuildMemberInitializer(Member, Init, IdLoc); 2677 } 2678 } 2679 } 2680 // It didn't name a member, so see if it names a class. 2681 QualType BaseType; 2682 TypeSourceInfo *TInfo = nullptr; 2683 2684 if (TemplateTypeTy) { 2685 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2686 } else if (DS.getTypeSpecType() == TST_decltype) { 2687 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2688 } else { 2689 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2690 LookupParsedName(R, S, &SS); 2691 2692 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2693 if (!TyD) { 2694 if (R.isAmbiguous()) return true; 2695 2696 // We don't want access-control diagnostics here. 2697 R.suppressDiagnostics(); 2698 2699 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2700 bool NotUnknownSpecialization = false; 2701 DeclContext *DC = computeDeclContext(SS, false); 2702 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2703 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2704 2705 if (!NotUnknownSpecialization) { 2706 // When the scope specifier can refer to a member of an unknown 2707 // specialization, we take it as a type name. 2708 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2709 SS.getWithLocInContext(Context), 2710 *MemberOrBase, IdLoc); 2711 if (BaseType.isNull()) 2712 return true; 2713 2714 R.clear(); 2715 R.setLookupName(MemberOrBase); 2716 } 2717 } 2718 2719 // If no results were found, try to correct typos. 2720 TypoCorrection Corr; 2721 MemInitializerValidatorCCC Validator(ClassDecl); 2722 if (R.empty() && BaseType.isNull() && 2723 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2724 Validator, CTK_ErrorRecovery, ClassDecl))) { 2725 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2726 // We have found a non-static data member with a similar 2727 // name to what was typed; complain and initialize that 2728 // member. 2729 diagnoseTypo(Corr, 2730 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2731 << MemberOrBase << true); 2732 return BuildMemberInitializer(Member, Init, IdLoc); 2733 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2734 const CXXBaseSpecifier *DirectBaseSpec; 2735 const CXXBaseSpecifier *VirtualBaseSpec; 2736 if (FindBaseInitializer(*this, ClassDecl, 2737 Context.getTypeDeclType(Type), 2738 DirectBaseSpec, VirtualBaseSpec)) { 2739 // We have found a direct or virtual base class with a 2740 // similar name to what was typed; complain and initialize 2741 // that base class. 2742 diagnoseTypo(Corr, 2743 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2744 << MemberOrBase << false, 2745 PDiag() /*Suppress note, we provide our own.*/); 2746 2747 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2748 : VirtualBaseSpec; 2749 Diag(BaseSpec->getLocStart(), 2750 diag::note_base_class_specified_here) 2751 << BaseSpec->getType() 2752 << BaseSpec->getSourceRange(); 2753 2754 TyD = Type; 2755 } 2756 } 2757 } 2758 2759 if (!TyD && BaseType.isNull()) { 2760 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2761 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2762 return true; 2763 } 2764 } 2765 2766 if (BaseType.isNull()) { 2767 BaseType = Context.getTypeDeclType(TyD); 2768 if (SS.isSet()) 2769 // FIXME: preserve source range information 2770 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 2771 BaseType); 2772 } 2773 } 2774 2775 if (!TInfo) 2776 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2777 2778 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2779 } 2780 2781 /// Checks a member initializer expression for cases where reference (or 2782 /// pointer) members are bound to by-value parameters (or their addresses). 2783 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2784 Expr *Init, 2785 SourceLocation IdLoc) { 2786 QualType MemberTy = Member->getType(); 2787 2788 // We only handle pointers and references currently. 2789 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2790 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2791 return; 2792 2793 const bool IsPointer = MemberTy->isPointerType(); 2794 if (IsPointer) { 2795 if (const UnaryOperator *Op 2796 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2797 // The only case we're worried about with pointers requires taking the 2798 // address. 2799 if (Op->getOpcode() != UO_AddrOf) 2800 return; 2801 2802 Init = Op->getSubExpr(); 2803 } else { 2804 // We only handle address-of expression initializers for pointers. 2805 return; 2806 } 2807 } 2808 2809 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2810 // We only warn when referring to a non-reference parameter declaration. 2811 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2812 if (!Parameter || Parameter->getType()->isReferenceType()) 2813 return; 2814 2815 S.Diag(Init->getExprLoc(), 2816 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2817 : diag::warn_bind_ref_member_to_parameter) 2818 << Member << Parameter << Init->getSourceRange(); 2819 } else { 2820 // Other initializers are fine. 2821 return; 2822 } 2823 2824 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2825 << (unsigned)IsPointer; 2826 } 2827 2828 MemInitResult 2829 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2830 SourceLocation IdLoc) { 2831 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2832 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2833 assert((DirectMember || IndirectMember) && 2834 "Member must be a FieldDecl or IndirectFieldDecl"); 2835 2836 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2837 return true; 2838 2839 if (Member->isInvalidDecl()) 2840 return true; 2841 2842 MultiExprArg Args; 2843 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2844 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2845 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2846 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2847 } else { 2848 // Template instantiation doesn't reconstruct ParenListExprs for us. 2849 Args = Init; 2850 } 2851 2852 SourceRange InitRange = Init->getSourceRange(); 2853 2854 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2855 // Can't check initialization for a member of dependent type or when 2856 // any of the arguments are type-dependent expressions. 2857 DiscardCleanupsInEvaluationContext(); 2858 } else { 2859 bool InitList = false; 2860 if (isa<InitListExpr>(Init)) { 2861 InitList = true; 2862 Args = Init; 2863 } 2864 2865 // Initialize the member. 2866 InitializedEntity MemberEntity = 2867 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 2868 : InitializedEntity::InitializeMember(IndirectMember, 2869 nullptr); 2870 InitializationKind Kind = 2871 InitList ? InitializationKind::CreateDirectList(IdLoc) 2872 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2873 InitRange.getEnd()); 2874 2875 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 2876 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 2877 nullptr); 2878 if (MemberInit.isInvalid()) 2879 return true; 2880 2881 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 2882 2883 // C++11 [class.base.init]p7: 2884 // The initialization of each base and member constitutes a 2885 // full-expression. 2886 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2887 if (MemberInit.isInvalid()) 2888 return true; 2889 2890 Init = MemberInit.get(); 2891 } 2892 2893 if (DirectMember) { 2894 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2895 InitRange.getBegin(), Init, 2896 InitRange.getEnd()); 2897 } else { 2898 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2899 InitRange.getBegin(), Init, 2900 InitRange.getEnd()); 2901 } 2902 } 2903 2904 MemInitResult 2905 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2906 CXXRecordDecl *ClassDecl) { 2907 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2908 if (!LangOpts.CPlusPlus11) 2909 return Diag(NameLoc, diag::err_delegating_ctor) 2910 << TInfo->getTypeLoc().getLocalSourceRange(); 2911 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2912 2913 bool InitList = true; 2914 MultiExprArg Args = Init; 2915 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2916 InitList = false; 2917 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2918 } 2919 2920 SourceRange InitRange = Init->getSourceRange(); 2921 // Initialize the object. 2922 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2923 QualType(ClassDecl->getTypeForDecl(), 0)); 2924 InitializationKind Kind = 2925 InitList ? InitializationKind::CreateDirectList(NameLoc) 2926 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2927 InitRange.getEnd()); 2928 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 2929 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2930 Args, nullptr); 2931 if (DelegationInit.isInvalid()) 2932 return true; 2933 2934 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2935 "Delegating constructor with no target?"); 2936 2937 // C++11 [class.base.init]p7: 2938 // The initialization of each base and member constitutes a 2939 // full-expression. 2940 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2941 InitRange.getBegin()); 2942 if (DelegationInit.isInvalid()) 2943 return true; 2944 2945 // If we are in a dependent context, template instantiation will 2946 // perform this type-checking again. Just save the arguments that we 2947 // received in a ParenListExpr. 2948 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2949 // of the information that we have about the base 2950 // initializer. However, deconstructing the ASTs is a dicey process, 2951 // and this approach is far more likely to get the corner cases right. 2952 if (CurContext->isDependentContext()) 2953 DelegationInit = Init; 2954 2955 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2956 DelegationInit.getAs<Expr>(), 2957 InitRange.getEnd()); 2958 } 2959 2960 MemInitResult 2961 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2962 Expr *Init, CXXRecordDecl *ClassDecl, 2963 SourceLocation EllipsisLoc) { 2964 SourceLocation BaseLoc 2965 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2966 2967 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2968 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2969 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2970 2971 // C++ [class.base.init]p2: 2972 // [...] Unless the mem-initializer-id names a nonstatic data 2973 // member of the constructor's class or a direct or virtual base 2974 // of that class, the mem-initializer is ill-formed. A 2975 // mem-initializer-list can initialize a base class using any 2976 // name that denotes that base class type. 2977 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2978 2979 SourceRange InitRange = Init->getSourceRange(); 2980 if (EllipsisLoc.isValid()) { 2981 // This is a pack expansion. 2982 if (!BaseType->containsUnexpandedParameterPack()) { 2983 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2984 << SourceRange(BaseLoc, InitRange.getEnd()); 2985 2986 EllipsisLoc = SourceLocation(); 2987 } 2988 } else { 2989 // Check for any unexpanded parameter packs. 2990 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2991 return true; 2992 2993 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2994 return true; 2995 } 2996 2997 // Check for direct and virtual base classes. 2998 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 2999 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 3000 if (!Dependent) { 3001 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 3002 BaseType)) 3003 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 3004 3005 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 3006 VirtualBaseSpec); 3007 3008 // C++ [base.class.init]p2: 3009 // Unless the mem-initializer-id names a nonstatic data member of the 3010 // constructor's class or a direct or virtual base of that class, the 3011 // mem-initializer is ill-formed. 3012 if (!DirectBaseSpec && !VirtualBaseSpec) { 3013 // If the class has any dependent bases, then it's possible that 3014 // one of those types will resolve to the same type as 3015 // BaseType. Therefore, just treat this as a dependent base 3016 // class initialization. FIXME: Should we try to check the 3017 // initialization anyway? It seems odd. 3018 if (ClassDecl->hasAnyDependentBases()) 3019 Dependent = true; 3020 else 3021 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 3022 << BaseType << Context.getTypeDeclType(ClassDecl) 3023 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3024 } 3025 } 3026 3027 if (Dependent) { 3028 DiscardCleanupsInEvaluationContext(); 3029 3030 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3031 /*IsVirtual=*/false, 3032 InitRange.getBegin(), Init, 3033 InitRange.getEnd(), EllipsisLoc); 3034 } 3035 3036 // C++ [base.class.init]p2: 3037 // If a mem-initializer-id is ambiguous because it designates both 3038 // a direct non-virtual base class and an inherited virtual base 3039 // class, the mem-initializer is ill-formed. 3040 if (DirectBaseSpec && VirtualBaseSpec) 3041 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 3042 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 3043 3044 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 3045 if (!BaseSpec) 3046 BaseSpec = VirtualBaseSpec; 3047 3048 // Initialize the base. 3049 bool InitList = true; 3050 MultiExprArg Args = Init; 3051 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 3052 InitList = false; 3053 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 3054 } 3055 3056 InitializedEntity BaseEntity = 3057 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 3058 InitializationKind Kind = 3059 InitList ? InitializationKind::CreateDirectList(BaseLoc) 3060 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 3061 InitRange.getEnd()); 3062 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 3063 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 3064 if (BaseInit.isInvalid()) 3065 return true; 3066 3067 // C++11 [class.base.init]p7: 3068 // The initialization of each base and member constitutes a 3069 // full-expression. 3070 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 3071 if (BaseInit.isInvalid()) 3072 return true; 3073 3074 // If we are in a dependent context, template instantiation will 3075 // perform this type-checking again. Just save the arguments that we 3076 // received in a ParenListExpr. 3077 // FIXME: This isn't quite ideal, since our ASTs don't capture all 3078 // of the information that we have about the base 3079 // initializer. However, deconstructing the ASTs is a dicey process, 3080 // and this approach is far more likely to get the corner cases right. 3081 if (CurContext->isDependentContext()) 3082 BaseInit = Init; 3083 3084 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 3085 BaseSpec->isVirtual(), 3086 InitRange.getBegin(), 3087 BaseInit.getAs<Expr>(), 3088 InitRange.getEnd(), EllipsisLoc); 3089 } 3090 3091 // Create a static_cast\<T&&>(expr). 3092 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 3093 if (T.isNull()) T = E->getType(); 3094 QualType TargetType = SemaRef.BuildReferenceType( 3095 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 3096 SourceLocation ExprLoc = E->getLocStart(); 3097 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 3098 TargetType, ExprLoc); 3099 3100 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 3101 SourceRange(ExprLoc, ExprLoc), 3102 E->getSourceRange()).get(); 3103 } 3104 3105 /// ImplicitInitializerKind - How an implicit base or member initializer should 3106 /// initialize its base or member. 3107 enum ImplicitInitializerKind { 3108 IIK_Default, 3109 IIK_Copy, 3110 IIK_Move, 3111 IIK_Inherit 3112 }; 3113 3114 static bool 3115 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3116 ImplicitInitializerKind ImplicitInitKind, 3117 CXXBaseSpecifier *BaseSpec, 3118 bool IsInheritedVirtualBase, 3119 CXXCtorInitializer *&CXXBaseInit) { 3120 InitializedEntity InitEntity 3121 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3122 IsInheritedVirtualBase); 3123 3124 ExprResult BaseInit; 3125 3126 switch (ImplicitInitKind) { 3127 case IIK_Inherit: { 3128 const CXXRecordDecl *Inherited = 3129 Constructor->getInheritedConstructor()->getParent(); 3130 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3131 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3132 // C++11 [class.inhctor]p8: 3133 // Each expression in the expression-list is of the form 3134 // static_cast<T&&>(p), where p is the name of the corresponding 3135 // constructor parameter and T is the declared type of p. 3136 SmallVector<Expr*, 16> Args; 3137 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3138 ParmVarDecl *PD = Constructor->getParamDecl(I); 3139 ExprResult ArgExpr = 3140 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3141 VK_LValue, SourceLocation()); 3142 if (ArgExpr.isInvalid()) 3143 return true; 3144 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType())); 3145 } 3146 3147 InitializationKind InitKind = InitializationKind::CreateDirect( 3148 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3149 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3150 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3151 break; 3152 } 3153 } 3154 // Fall through. 3155 case IIK_Default: { 3156 InitializationKind InitKind 3157 = InitializationKind::CreateDefault(Constructor->getLocation()); 3158 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3159 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3160 break; 3161 } 3162 3163 case IIK_Move: 3164 case IIK_Copy: { 3165 bool Moving = ImplicitInitKind == IIK_Move; 3166 ParmVarDecl *Param = Constructor->getParamDecl(0); 3167 QualType ParamType = Param->getType().getNonReferenceType(); 3168 3169 Expr *CopyCtorArg = 3170 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3171 SourceLocation(), Param, false, 3172 Constructor->getLocation(), ParamType, 3173 VK_LValue, nullptr); 3174 3175 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3176 3177 // Cast to the base class to avoid ambiguities. 3178 QualType ArgTy = 3179 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3180 ParamType.getQualifiers()); 3181 3182 if (Moving) { 3183 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3184 } 3185 3186 CXXCastPath BasePath; 3187 BasePath.push_back(BaseSpec); 3188 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3189 CK_UncheckedDerivedToBase, 3190 Moving ? VK_XValue : VK_LValue, 3191 &BasePath).get(); 3192 3193 InitializationKind InitKind 3194 = InitializationKind::CreateDirect(Constructor->getLocation(), 3195 SourceLocation(), SourceLocation()); 3196 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3197 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3198 break; 3199 } 3200 } 3201 3202 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3203 if (BaseInit.isInvalid()) 3204 return true; 3205 3206 CXXBaseInit = 3207 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3208 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3209 SourceLocation()), 3210 BaseSpec->isVirtual(), 3211 SourceLocation(), 3212 BaseInit.getAs<Expr>(), 3213 SourceLocation(), 3214 SourceLocation()); 3215 3216 return false; 3217 } 3218 3219 static bool RefersToRValueRef(Expr *MemRef) { 3220 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3221 return Referenced->getType()->isRValueReferenceType(); 3222 } 3223 3224 static bool 3225 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3226 ImplicitInitializerKind ImplicitInitKind, 3227 FieldDecl *Field, IndirectFieldDecl *Indirect, 3228 CXXCtorInitializer *&CXXMemberInit) { 3229 if (Field->isInvalidDecl()) 3230 return true; 3231 3232 SourceLocation Loc = Constructor->getLocation(); 3233 3234 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3235 bool Moving = ImplicitInitKind == IIK_Move; 3236 ParmVarDecl *Param = Constructor->getParamDecl(0); 3237 QualType ParamType = Param->getType().getNonReferenceType(); 3238 3239 // Suppress copying zero-width bitfields. 3240 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3241 return false; 3242 3243 Expr *MemberExprBase = 3244 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3245 SourceLocation(), Param, false, 3246 Loc, ParamType, VK_LValue, nullptr); 3247 3248 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3249 3250 if (Moving) { 3251 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3252 } 3253 3254 // Build a reference to this field within the parameter. 3255 CXXScopeSpec SS; 3256 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3257 Sema::LookupMemberName); 3258 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3259 : cast<ValueDecl>(Field), AS_public); 3260 MemberLookup.resolveKind(); 3261 ExprResult CtorArg 3262 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3263 ParamType, Loc, 3264 /*IsArrow=*/false, 3265 SS, 3266 /*TemplateKWLoc=*/SourceLocation(), 3267 /*FirstQualifierInScope=*/nullptr, 3268 MemberLookup, 3269 /*TemplateArgs=*/nullptr); 3270 if (CtorArg.isInvalid()) 3271 return true; 3272 3273 // C++11 [class.copy]p15: 3274 // - if a member m has rvalue reference type T&&, it is direct-initialized 3275 // with static_cast<T&&>(x.m); 3276 if (RefersToRValueRef(CtorArg.get())) { 3277 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3278 } 3279 3280 // When the field we are copying is an array, create index variables for 3281 // each dimension of the array. We use these index variables to subscript 3282 // the source array, and other clients (e.g., CodeGen) will perform the 3283 // necessary iteration with these index variables. 3284 SmallVector<VarDecl *, 4> IndexVariables; 3285 QualType BaseType = Field->getType(); 3286 QualType SizeType = SemaRef.Context.getSizeType(); 3287 bool InitializingArray = false; 3288 while (const ConstantArrayType *Array 3289 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3290 InitializingArray = true; 3291 // Create the iteration variable for this array index. 3292 IdentifierInfo *IterationVarName = nullptr; 3293 { 3294 SmallString<8> Str; 3295 llvm::raw_svector_ostream OS(Str); 3296 OS << "__i" << IndexVariables.size(); 3297 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3298 } 3299 VarDecl *IterationVar 3300 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3301 IterationVarName, SizeType, 3302 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3303 SC_None); 3304 IndexVariables.push_back(IterationVar); 3305 3306 // Create a reference to the iteration variable. 3307 ExprResult IterationVarRef 3308 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3309 assert(!IterationVarRef.isInvalid() && 3310 "Reference to invented variable cannot fail!"); 3311 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get()); 3312 assert(!IterationVarRef.isInvalid() && 3313 "Conversion of invented variable cannot fail!"); 3314 3315 // Subscript the array with this iteration variable. 3316 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc, 3317 IterationVarRef.get(), 3318 Loc); 3319 if (CtorArg.isInvalid()) 3320 return true; 3321 3322 BaseType = Array->getElementType(); 3323 } 3324 3325 // The array subscript expression is an lvalue, which is wrong for moving. 3326 if (Moving && InitializingArray) 3327 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 3328 3329 // Construct the entity that we will be initializing. For an array, this 3330 // will be first element in the array, which may require several levels 3331 // of array-subscript entities. 3332 SmallVector<InitializedEntity, 4> Entities; 3333 Entities.reserve(1 + IndexVariables.size()); 3334 if (Indirect) 3335 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3336 else 3337 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3338 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3339 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3340 0, 3341 Entities.back())); 3342 3343 // Direct-initialize to use the copy constructor. 3344 InitializationKind InitKind = 3345 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3346 3347 Expr *CtorArgE = CtorArg.getAs<Expr>(); 3348 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3349 3350 ExprResult MemberInit 3351 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3352 MultiExprArg(&CtorArgE, 1)); 3353 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3354 if (MemberInit.isInvalid()) 3355 return true; 3356 3357 if (Indirect) { 3358 assert(IndexVariables.size() == 0 && 3359 "Indirect field improperly initialized"); 3360 CXXMemberInit 3361 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3362 Loc, Loc, 3363 MemberInit.getAs<Expr>(), 3364 Loc); 3365 } else 3366 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3367 Loc, MemberInit.getAs<Expr>(), 3368 Loc, 3369 IndexVariables.data(), 3370 IndexVariables.size()); 3371 return false; 3372 } 3373 3374 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3375 "Unhandled implicit init kind!"); 3376 3377 QualType FieldBaseElementType = 3378 SemaRef.Context.getBaseElementType(Field->getType()); 3379 3380 if (FieldBaseElementType->isRecordType()) { 3381 InitializedEntity InitEntity 3382 = Indirect? InitializedEntity::InitializeMember(Indirect) 3383 : InitializedEntity::InitializeMember(Field); 3384 InitializationKind InitKind = 3385 InitializationKind::CreateDefault(Loc); 3386 3387 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3388 ExprResult MemberInit = 3389 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3390 3391 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3392 if (MemberInit.isInvalid()) 3393 return true; 3394 3395 if (Indirect) 3396 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3397 Indirect, Loc, 3398 Loc, 3399 MemberInit.get(), 3400 Loc); 3401 else 3402 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3403 Field, Loc, Loc, 3404 MemberInit.get(), 3405 Loc); 3406 return false; 3407 } 3408 3409 if (!Field->getParent()->isUnion()) { 3410 if (FieldBaseElementType->isReferenceType()) { 3411 SemaRef.Diag(Constructor->getLocation(), 3412 diag::err_uninitialized_member_in_ctor) 3413 << (int)Constructor->isImplicit() 3414 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3415 << 0 << Field->getDeclName(); 3416 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3417 return true; 3418 } 3419 3420 if (FieldBaseElementType.isConstQualified()) { 3421 SemaRef.Diag(Constructor->getLocation(), 3422 diag::err_uninitialized_member_in_ctor) 3423 << (int)Constructor->isImplicit() 3424 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3425 << 1 << Field->getDeclName(); 3426 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3427 return true; 3428 } 3429 } 3430 3431 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3432 FieldBaseElementType->isObjCRetainableType() && 3433 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3434 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3435 // ARC: 3436 // Default-initialize Objective-C pointers to NULL. 3437 CXXMemberInit 3438 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3439 Loc, Loc, 3440 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3441 Loc); 3442 return false; 3443 } 3444 3445 // Nothing to initialize. 3446 CXXMemberInit = nullptr; 3447 return false; 3448 } 3449 3450 namespace { 3451 struct BaseAndFieldInfo { 3452 Sema &S; 3453 CXXConstructorDecl *Ctor; 3454 bool AnyErrorsInInits; 3455 ImplicitInitializerKind IIK; 3456 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3457 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3458 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3459 3460 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3461 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3462 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3463 if (Generated && Ctor->isCopyConstructor()) 3464 IIK = IIK_Copy; 3465 else if (Generated && Ctor->isMoveConstructor()) 3466 IIK = IIK_Move; 3467 else if (Ctor->getInheritedConstructor()) 3468 IIK = IIK_Inherit; 3469 else 3470 IIK = IIK_Default; 3471 } 3472 3473 bool isImplicitCopyOrMove() const { 3474 switch (IIK) { 3475 case IIK_Copy: 3476 case IIK_Move: 3477 return true; 3478 3479 case IIK_Default: 3480 case IIK_Inherit: 3481 return false; 3482 } 3483 3484 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3485 } 3486 3487 bool addFieldInitializer(CXXCtorInitializer *Init) { 3488 AllToInit.push_back(Init); 3489 3490 // Check whether this initializer makes the field "used". 3491 if (Init->getInit()->HasSideEffects(S.Context)) 3492 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3493 3494 return false; 3495 } 3496 3497 bool isInactiveUnionMember(FieldDecl *Field) { 3498 RecordDecl *Record = Field->getParent(); 3499 if (!Record->isUnion()) 3500 return false; 3501 3502 if (FieldDecl *Active = 3503 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3504 return Active != Field->getCanonicalDecl(); 3505 3506 // In an implicit copy or move constructor, ignore any in-class initializer. 3507 if (isImplicitCopyOrMove()) 3508 return true; 3509 3510 // If there's no explicit initialization, the field is active only if it 3511 // has an in-class initializer... 3512 if (Field->hasInClassInitializer()) 3513 return false; 3514 // ... or it's an anonymous struct or union whose class has an in-class 3515 // initializer. 3516 if (!Field->isAnonymousStructOrUnion()) 3517 return true; 3518 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3519 return !FieldRD->hasInClassInitializer(); 3520 } 3521 3522 /// \brief Determine whether the given field is, or is within, a union member 3523 /// that is inactive (because there was an initializer given for a different 3524 /// member of the union, or because the union was not initialized at all). 3525 bool isWithinInactiveUnionMember(FieldDecl *Field, 3526 IndirectFieldDecl *Indirect) { 3527 if (!Indirect) 3528 return isInactiveUnionMember(Field); 3529 3530 for (auto *C : Indirect->chain()) { 3531 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3532 if (Field && isInactiveUnionMember(Field)) 3533 return true; 3534 } 3535 return false; 3536 } 3537 }; 3538 } 3539 3540 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3541 /// array type. 3542 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3543 if (T->isIncompleteArrayType()) 3544 return true; 3545 3546 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3547 if (!ArrayT->getSize()) 3548 return true; 3549 3550 T = ArrayT->getElementType(); 3551 } 3552 3553 return false; 3554 } 3555 3556 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3557 FieldDecl *Field, 3558 IndirectFieldDecl *Indirect = nullptr) { 3559 if (Field->isInvalidDecl()) 3560 return false; 3561 3562 // Overwhelmingly common case: we have a direct initializer for this field. 3563 if (CXXCtorInitializer *Init = 3564 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3565 return Info.addFieldInitializer(Init); 3566 3567 // C++11 [class.base.init]p8: 3568 // if the entity is a non-static data member that has a 3569 // brace-or-equal-initializer and either 3570 // -- the constructor's class is a union and no other variant member of that 3571 // union is designated by a mem-initializer-id or 3572 // -- the constructor's class is not a union, and, if the entity is a member 3573 // of an anonymous union, no other member of that union is designated by 3574 // a mem-initializer-id, 3575 // the entity is initialized as specified in [dcl.init]. 3576 // 3577 // We also apply the same rules to handle anonymous structs within anonymous 3578 // unions. 3579 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3580 return false; 3581 3582 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3583 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3584 Info.Ctor->getLocation(), Field); 3585 CXXCtorInitializer *Init; 3586 if (Indirect) 3587 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3588 SourceLocation(), 3589 SourceLocation(), DIE, 3590 SourceLocation()); 3591 else 3592 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3593 SourceLocation(), 3594 SourceLocation(), DIE, 3595 SourceLocation()); 3596 return Info.addFieldInitializer(Init); 3597 } 3598 3599 // Don't initialize incomplete or zero-length arrays. 3600 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3601 return false; 3602 3603 // Don't try to build an implicit initializer if there were semantic 3604 // errors in any of the initializers (and therefore we might be 3605 // missing some that the user actually wrote). 3606 if (Info.AnyErrorsInInits) 3607 return false; 3608 3609 CXXCtorInitializer *Init = nullptr; 3610 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3611 Indirect, Init)) 3612 return true; 3613 3614 if (!Init) 3615 return false; 3616 3617 return Info.addFieldInitializer(Init); 3618 } 3619 3620 bool 3621 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3622 CXXCtorInitializer *Initializer) { 3623 assert(Initializer->isDelegatingInitializer()); 3624 Constructor->setNumCtorInitializers(1); 3625 CXXCtorInitializer **initializer = 3626 new (Context) CXXCtorInitializer*[1]; 3627 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3628 Constructor->setCtorInitializers(initializer); 3629 3630 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3631 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3632 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3633 } 3634 3635 DelegatingCtorDecls.push_back(Constructor); 3636 3637 DiagnoseUninitializedFields(*this, Constructor); 3638 3639 return false; 3640 } 3641 3642 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3643 ArrayRef<CXXCtorInitializer *> Initializers) { 3644 if (Constructor->isDependentContext()) { 3645 // Just store the initializers as written, they will be checked during 3646 // instantiation. 3647 if (!Initializers.empty()) { 3648 Constructor->setNumCtorInitializers(Initializers.size()); 3649 CXXCtorInitializer **baseOrMemberInitializers = 3650 new (Context) CXXCtorInitializer*[Initializers.size()]; 3651 memcpy(baseOrMemberInitializers, Initializers.data(), 3652 Initializers.size() * sizeof(CXXCtorInitializer*)); 3653 Constructor->setCtorInitializers(baseOrMemberInitializers); 3654 } 3655 3656 // Let template instantiation know whether we had errors. 3657 if (AnyErrors) 3658 Constructor->setInvalidDecl(); 3659 3660 return false; 3661 } 3662 3663 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3664 3665 // We need to build the initializer AST according to order of construction 3666 // and not what user specified in the Initializers list. 3667 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3668 if (!ClassDecl) 3669 return true; 3670 3671 bool HadError = false; 3672 3673 for (unsigned i = 0; i < Initializers.size(); i++) { 3674 CXXCtorInitializer *Member = Initializers[i]; 3675 3676 if (Member->isBaseInitializer()) 3677 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3678 else { 3679 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3680 3681 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3682 for (auto *C : F->chain()) { 3683 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3684 if (FD && FD->getParent()->isUnion()) 3685 Info.ActiveUnionMember.insert(std::make_pair( 3686 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3687 } 3688 } else if (FieldDecl *FD = Member->getMember()) { 3689 if (FD->getParent()->isUnion()) 3690 Info.ActiveUnionMember.insert(std::make_pair( 3691 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3692 } 3693 } 3694 } 3695 3696 // Keep track of the direct virtual bases. 3697 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3698 for (auto &I : ClassDecl->bases()) { 3699 if (I.isVirtual()) 3700 DirectVBases.insert(&I); 3701 } 3702 3703 // Push virtual bases before others. 3704 for (auto &VBase : ClassDecl->vbases()) { 3705 if (CXXCtorInitializer *Value 3706 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3707 // [class.base.init]p7, per DR257: 3708 // A mem-initializer where the mem-initializer-id names a virtual base 3709 // class is ignored during execution of a constructor of any class that 3710 // is not the most derived class. 3711 if (ClassDecl->isAbstract()) { 3712 // FIXME: Provide a fixit to remove the base specifier. This requires 3713 // tracking the location of the associated comma for a base specifier. 3714 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3715 << VBase.getType() << ClassDecl; 3716 DiagnoseAbstractType(ClassDecl); 3717 } 3718 3719 Info.AllToInit.push_back(Value); 3720 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3721 // [class.base.init]p8, per DR257: 3722 // If a given [...] base class is not named by a mem-initializer-id 3723 // [...] and the entity is not a virtual base class of an abstract 3724 // class, then [...] the entity is default-initialized. 3725 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3726 CXXCtorInitializer *CXXBaseInit; 3727 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3728 &VBase, IsInheritedVirtualBase, 3729 CXXBaseInit)) { 3730 HadError = true; 3731 continue; 3732 } 3733 3734 Info.AllToInit.push_back(CXXBaseInit); 3735 } 3736 } 3737 3738 // Non-virtual bases. 3739 for (auto &Base : ClassDecl->bases()) { 3740 // Virtuals are in the virtual base list and already constructed. 3741 if (Base.isVirtual()) 3742 continue; 3743 3744 if (CXXCtorInitializer *Value 3745 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3746 Info.AllToInit.push_back(Value); 3747 } else if (!AnyErrors) { 3748 CXXCtorInitializer *CXXBaseInit; 3749 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3750 &Base, /*IsInheritedVirtualBase=*/false, 3751 CXXBaseInit)) { 3752 HadError = true; 3753 continue; 3754 } 3755 3756 Info.AllToInit.push_back(CXXBaseInit); 3757 } 3758 } 3759 3760 // Fields. 3761 for (auto *Mem : ClassDecl->decls()) { 3762 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 3763 // C++ [class.bit]p2: 3764 // A declaration for a bit-field that omits the identifier declares an 3765 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3766 // initialized. 3767 if (F->isUnnamedBitfield()) 3768 continue; 3769 3770 // If we're not generating the implicit copy/move constructor, then we'll 3771 // handle anonymous struct/union fields based on their individual 3772 // indirect fields. 3773 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3774 continue; 3775 3776 if (CollectFieldInitializer(*this, Info, F)) 3777 HadError = true; 3778 continue; 3779 } 3780 3781 // Beyond this point, we only consider default initialization. 3782 if (Info.isImplicitCopyOrMove()) 3783 continue; 3784 3785 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 3786 if (F->getType()->isIncompleteArrayType()) { 3787 assert(ClassDecl->hasFlexibleArrayMember() && 3788 "Incomplete array type is not valid"); 3789 continue; 3790 } 3791 3792 // Initialize each field of an anonymous struct individually. 3793 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3794 HadError = true; 3795 3796 continue; 3797 } 3798 } 3799 3800 unsigned NumInitializers = Info.AllToInit.size(); 3801 if (NumInitializers > 0) { 3802 Constructor->setNumCtorInitializers(NumInitializers); 3803 CXXCtorInitializer **baseOrMemberInitializers = 3804 new (Context) CXXCtorInitializer*[NumInitializers]; 3805 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3806 NumInitializers * sizeof(CXXCtorInitializer*)); 3807 Constructor->setCtorInitializers(baseOrMemberInitializers); 3808 3809 // Constructors implicitly reference the base and member 3810 // destructors. 3811 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3812 Constructor->getParent()); 3813 } 3814 3815 return HadError; 3816 } 3817 3818 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3819 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3820 const RecordDecl *RD = RT->getDecl(); 3821 if (RD->isAnonymousStructOrUnion()) { 3822 for (auto *Field : RD->fields()) 3823 PopulateKeysForFields(Field, IdealInits); 3824 return; 3825 } 3826 } 3827 IdealInits.push_back(Field->getCanonicalDecl()); 3828 } 3829 3830 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3831 return Context.getCanonicalType(BaseType).getTypePtr(); 3832 } 3833 3834 static const void *GetKeyForMember(ASTContext &Context, 3835 CXXCtorInitializer *Member) { 3836 if (!Member->isAnyMemberInitializer()) 3837 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3838 3839 return Member->getAnyMember()->getCanonicalDecl(); 3840 } 3841 3842 static void DiagnoseBaseOrMemInitializerOrder( 3843 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3844 ArrayRef<CXXCtorInitializer *> Inits) { 3845 if (Constructor->getDeclContext()->isDependentContext()) 3846 return; 3847 3848 // Don't check initializers order unless the warning is enabled at the 3849 // location of at least one initializer. 3850 bool ShouldCheckOrder = false; 3851 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3852 CXXCtorInitializer *Init = Inits[InitIndex]; 3853 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 3854 Init->getSourceLocation())) { 3855 ShouldCheckOrder = true; 3856 break; 3857 } 3858 } 3859 if (!ShouldCheckOrder) 3860 return; 3861 3862 // Build the list of bases and members in the order that they'll 3863 // actually be initialized. The explicit initializers should be in 3864 // this same order but may be missing things. 3865 SmallVector<const void*, 32> IdealInitKeys; 3866 3867 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3868 3869 // 1. Virtual bases. 3870 for (const auto &VBase : ClassDecl->vbases()) 3871 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 3872 3873 // 2. Non-virtual bases. 3874 for (const auto &Base : ClassDecl->bases()) { 3875 if (Base.isVirtual()) 3876 continue; 3877 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 3878 } 3879 3880 // 3. Direct fields. 3881 for (auto *Field : ClassDecl->fields()) { 3882 if (Field->isUnnamedBitfield()) 3883 continue; 3884 3885 PopulateKeysForFields(Field, IdealInitKeys); 3886 } 3887 3888 unsigned NumIdealInits = IdealInitKeys.size(); 3889 unsigned IdealIndex = 0; 3890 3891 CXXCtorInitializer *PrevInit = nullptr; 3892 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3893 CXXCtorInitializer *Init = Inits[InitIndex]; 3894 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3895 3896 // Scan forward to try to find this initializer in the idealized 3897 // initializers list. 3898 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3899 if (InitKey == IdealInitKeys[IdealIndex]) 3900 break; 3901 3902 // If we didn't find this initializer, it must be because we 3903 // scanned past it on a previous iteration. That can only 3904 // happen if we're out of order; emit a warning. 3905 if (IdealIndex == NumIdealInits && PrevInit) { 3906 Sema::SemaDiagnosticBuilder D = 3907 SemaRef.Diag(PrevInit->getSourceLocation(), 3908 diag::warn_initializer_out_of_order); 3909 3910 if (PrevInit->isAnyMemberInitializer()) 3911 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3912 else 3913 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3914 3915 if (Init->isAnyMemberInitializer()) 3916 D << 0 << Init->getAnyMember()->getDeclName(); 3917 else 3918 D << 1 << Init->getTypeSourceInfo()->getType(); 3919 3920 // Move back to the initializer's location in the ideal list. 3921 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3922 if (InitKey == IdealInitKeys[IdealIndex]) 3923 break; 3924 3925 assert(IdealIndex != NumIdealInits && 3926 "initializer not found in initializer list"); 3927 } 3928 3929 PrevInit = Init; 3930 } 3931 } 3932 3933 namespace { 3934 bool CheckRedundantInit(Sema &S, 3935 CXXCtorInitializer *Init, 3936 CXXCtorInitializer *&PrevInit) { 3937 if (!PrevInit) { 3938 PrevInit = Init; 3939 return false; 3940 } 3941 3942 if (FieldDecl *Field = Init->getAnyMember()) 3943 S.Diag(Init->getSourceLocation(), 3944 diag::err_multiple_mem_initialization) 3945 << Field->getDeclName() 3946 << Init->getSourceRange(); 3947 else { 3948 const Type *BaseClass = Init->getBaseClass(); 3949 assert(BaseClass && "neither field nor base"); 3950 S.Diag(Init->getSourceLocation(), 3951 diag::err_multiple_base_initialization) 3952 << QualType(BaseClass, 0) 3953 << Init->getSourceRange(); 3954 } 3955 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3956 << 0 << PrevInit->getSourceRange(); 3957 3958 return true; 3959 } 3960 3961 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3962 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3963 3964 bool CheckRedundantUnionInit(Sema &S, 3965 CXXCtorInitializer *Init, 3966 RedundantUnionMap &Unions) { 3967 FieldDecl *Field = Init->getAnyMember(); 3968 RecordDecl *Parent = Field->getParent(); 3969 NamedDecl *Child = Field; 3970 3971 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3972 if (Parent->isUnion()) { 3973 UnionEntry &En = Unions[Parent]; 3974 if (En.first && En.first != Child) { 3975 S.Diag(Init->getSourceLocation(), 3976 diag::err_multiple_mem_union_initialization) 3977 << Field->getDeclName() 3978 << Init->getSourceRange(); 3979 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3980 << 0 << En.second->getSourceRange(); 3981 return true; 3982 } 3983 if (!En.first) { 3984 En.first = Child; 3985 En.second = Init; 3986 } 3987 if (!Parent->isAnonymousStructOrUnion()) 3988 return false; 3989 } 3990 3991 Child = Parent; 3992 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3993 } 3994 3995 return false; 3996 } 3997 } 3998 3999 /// ActOnMemInitializers - Handle the member initializers for a constructor. 4000 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 4001 SourceLocation ColonLoc, 4002 ArrayRef<CXXCtorInitializer*> MemInits, 4003 bool AnyErrors) { 4004 if (!ConstructorDecl) 4005 return; 4006 4007 AdjustDeclIfTemplate(ConstructorDecl); 4008 4009 CXXConstructorDecl *Constructor 4010 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 4011 4012 if (!Constructor) { 4013 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 4014 return; 4015 } 4016 4017 // Mapping for the duplicate initializers check. 4018 // For member initializers, this is keyed with a FieldDecl*. 4019 // For base initializers, this is keyed with a Type*. 4020 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 4021 4022 // Mapping for the inconsistent anonymous-union initializers check. 4023 RedundantUnionMap MemberUnions; 4024 4025 bool HadError = false; 4026 for (unsigned i = 0; i < MemInits.size(); i++) { 4027 CXXCtorInitializer *Init = MemInits[i]; 4028 4029 // Set the source order index. 4030 Init->setSourceOrder(i); 4031 4032 if (Init->isAnyMemberInitializer()) { 4033 const void *Key = GetKeyForMember(Context, Init); 4034 if (CheckRedundantInit(*this, Init, Members[Key]) || 4035 CheckRedundantUnionInit(*this, Init, MemberUnions)) 4036 HadError = true; 4037 } else if (Init->isBaseInitializer()) { 4038 const void *Key = GetKeyForMember(Context, Init); 4039 if (CheckRedundantInit(*this, Init, Members[Key])) 4040 HadError = true; 4041 } else { 4042 assert(Init->isDelegatingInitializer()); 4043 // This must be the only initializer 4044 if (MemInits.size() != 1) { 4045 Diag(Init->getSourceLocation(), 4046 diag::err_delegating_initializer_alone) 4047 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 4048 // We will treat this as being the only initializer. 4049 } 4050 SetDelegatingInitializer(Constructor, MemInits[i]); 4051 // Return immediately as the initializer is set. 4052 return; 4053 } 4054 } 4055 4056 if (HadError) 4057 return; 4058 4059 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 4060 4061 SetCtorInitializers(Constructor, AnyErrors, MemInits); 4062 4063 DiagnoseUninitializedFields(*this, Constructor); 4064 } 4065 4066 void 4067 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 4068 CXXRecordDecl *ClassDecl) { 4069 // Ignore dependent contexts. Also ignore unions, since their members never 4070 // have destructors implicitly called. 4071 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 4072 return; 4073 4074 // FIXME: all the access-control diagnostics are positioned on the 4075 // field/base declaration. That's probably good; that said, the 4076 // user might reasonably want to know why the destructor is being 4077 // emitted, and we currently don't say. 4078 4079 // Non-static data members. 4080 for (auto *Field : ClassDecl->fields()) { 4081 if (Field->isInvalidDecl()) 4082 continue; 4083 4084 // Don't destroy incomplete or zero-length arrays. 4085 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 4086 continue; 4087 4088 QualType FieldType = Context.getBaseElementType(Field->getType()); 4089 4090 const RecordType* RT = FieldType->getAs<RecordType>(); 4091 if (!RT) 4092 continue; 4093 4094 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4095 if (FieldClassDecl->isInvalidDecl()) 4096 continue; 4097 if (FieldClassDecl->hasIrrelevantDestructor()) 4098 continue; 4099 // The destructor for an implicit anonymous union member is never invoked. 4100 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 4101 continue; 4102 4103 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 4104 assert(Dtor && "No dtor found for FieldClassDecl!"); 4105 CheckDestructorAccess(Field->getLocation(), Dtor, 4106 PDiag(diag::err_access_dtor_field) 4107 << Field->getDeclName() 4108 << FieldType); 4109 4110 MarkFunctionReferenced(Location, Dtor); 4111 DiagnoseUseOfDecl(Dtor, Location); 4112 } 4113 4114 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 4115 4116 // Bases. 4117 for (const auto &Base : ClassDecl->bases()) { 4118 // Bases are always records in a well-formed non-dependent class. 4119 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4120 4121 // Remember direct virtual bases. 4122 if (Base.isVirtual()) 4123 DirectVirtualBases.insert(RT); 4124 4125 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4126 // If our base class is invalid, we probably can't get its dtor anyway. 4127 if (BaseClassDecl->isInvalidDecl()) 4128 continue; 4129 if (BaseClassDecl->hasIrrelevantDestructor()) 4130 continue; 4131 4132 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4133 assert(Dtor && "No dtor found for BaseClassDecl!"); 4134 4135 // FIXME: caret should be on the start of the class name 4136 CheckDestructorAccess(Base.getLocStart(), Dtor, 4137 PDiag(diag::err_access_dtor_base) 4138 << Base.getType() 4139 << Base.getSourceRange(), 4140 Context.getTypeDeclType(ClassDecl)); 4141 4142 MarkFunctionReferenced(Location, Dtor); 4143 DiagnoseUseOfDecl(Dtor, Location); 4144 } 4145 4146 // Virtual bases. 4147 for (const auto &VBase : ClassDecl->vbases()) { 4148 // Bases are always records in a well-formed non-dependent class. 4149 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4150 4151 // Ignore direct virtual bases. 4152 if (DirectVirtualBases.count(RT)) 4153 continue; 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 if (CheckDestructorAccess( 4165 ClassDecl->getLocation(), Dtor, 4166 PDiag(diag::err_access_dtor_vbase) 4167 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4168 Context.getTypeDeclType(ClassDecl)) == 4169 AR_accessible) { 4170 CheckDerivedToBaseConversion( 4171 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4172 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4173 SourceRange(), DeclarationName(), nullptr); 4174 } 4175 4176 MarkFunctionReferenced(Location, Dtor); 4177 DiagnoseUseOfDecl(Dtor, Location); 4178 } 4179 } 4180 4181 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4182 if (!CDtorDecl) 4183 return; 4184 4185 if (CXXConstructorDecl *Constructor 4186 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4187 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4188 DiagnoseUninitializedFields(*this, Constructor); 4189 } 4190 } 4191 4192 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4193 unsigned DiagID, AbstractDiagSelID SelID) { 4194 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4195 unsigned DiagID; 4196 AbstractDiagSelID SelID; 4197 4198 public: 4199 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4200 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4201 4202 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4203 if (Suppressed) return; 4204 if (SelID == -1) 4205 S.Diag(Loc, DiagID) << T; 4206 else 4207 S.Diag(Loc, DiagID) << SelID << T; 4208 } 4209 } Diagnoser(DiagID, SelID); 4210 4211 return RequireNonAbstractType(Loc, T, Diagnoser); 4212 } 4213 4214 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4215 TypeDiagnoser &Diagnoser) { 4216 if (!getLangOpts().CPlusPlus) 4217 return false; 4218 4219 if (const ArrayType *AT = Context.getAsArrayType(T)) 4220 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4221 4222 if (const PointerType *PT = T->getAs<PointerType>()) { 4223 // Find the innermost pointer type. 4224 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4225 PT = T; 4226 4227 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4228 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4229 } 4230 4231 const RecordType *RT = T->getAs<RecordType>(); 4232 if (!RT) 4233 return false; 4234 4235 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4236 4237 // We can't answer whether something is abstract until it has a 4238 // definition. If it's currently being defined, we'll walk back 4239 // over all the declarations when we have a full definition. 4240 const CXXRecordDecl *Def = RD->getDefinition(); 4241 if (!Def || Def->isBeingDefined()) 4242 return false; 4243 4244 if (!RD->isAbstract()) 4245 return false; 4246 4247 Diagnoser.diagnose(*this, Loc, T); 4248 DiagnoseAbstractType(RD); 4249 4250 return true; 4251 } 4252 4253 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4254 // Check if we've already emitted the list of pure virtual functions 4255 // for this class. 4256 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4257 return; 4258 4259 // If the diagnostic is suppressed, don't emit the notes. We're only 4260 // going to emit them once, so try to attach them to a diagnostic we're 4261 // actually going to show. 4262 if (Diags.isLastDiagnosticIgnored()) 4263 return; 4264 4265 CXXFinalOverriderMap FinalOverriders; 4266 RD->getFinalOverriders(FinalOverriders); 4267 4268 // Keep a set of seen pure methods so we won't diagnose the same method 4269 // more than once. 4270 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4271 4272 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4273 MEnd = FinalOverriders.end(); 4274 M != MEnd; 4275 ++M) { 4276 for (OverridingMethods::iterator SO = M->second.begin(), 4277 SOEnd = M->second.end(); 4278 SO != SOEnd; ++SO) { 4279 // C++ [class.abstract]p4: 4280 // A class is abstract if it contains or inherits at least one 4281 // pure virtual function for which the final overrider is pure 4282 // virtual. 4283 4284 // 4285 if (SO->second.size() != 1) 4286 continue; 4287 4288 if (!SO->second.front().Method->isPure()) 4289 continue; 4290 4291 if (!SeenPureMethods.insert(SO->second.front().Method)) 4292 continue; 4293 4294 Diag(SO->second.front().Method->getLocation(), 4295 diag::note_pure_virtual_function) 4296 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4297 } 4298 } 4299 4300 if (!PureVirtualClassDiagSet) 4301 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4302 PureVirtualClassDiagSet->insert(RD); 4303 } 4304 4305 namespace { 4306 struct AbstractUsageInfo { 4307 Sema &S; 4308 CXXRecordDecl *Record; 4309 CanQualType AbstractType; 4310 bool Invalid; 4311 4312 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4313 : S(S), Record(Record), 4314 AbstractType(S.Context.getCanonicalType( 4315 S.Context.getTypeDeclType(Record))), 4316 Invalid(false) {} 4317 4318 void DiagnoseAbstractType() { 4319 if (Invalid) return; 4320 S.DiagnoseAbstractType(Record); 4321 Invalid = true; 4322 } 4323 4324 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4325 }; 4326 4327 struct CheckAbstractUsage { 4328 AbstractUsageInfo &Info; 4329 const NamedDecl *Ctx; 4330 4331 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4332 : Info(Info), Ctx(Ctx) {} 4333 4334 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4335 switch (TL.getTypeLocClass()) { 4336 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4337 #define TYPELOC(CLASS, PARENT) \ 4338 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4339 #include "clang/AST/TypeLocNodes.def" 4340 } 4341 } 4342 4343 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4344 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4345 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4346 if (!TL.getParam(I)) 4347 continue; 4348 4349 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4350 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4351 } 4352 } 4353 4354 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4355 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4356 } 4357 4358 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4359 // Visit the type parameters from a permissive context. 4360 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4361 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4362 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4363 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4364 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4365 // TODO: other template argument types? 4366 } 4367 } 4368 4369 // Visit pointee types from a permissive context. 4370 #define CheckPolymorphic(Type) \ 4371 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4372 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4373 } 4374 CheckPolymorphic(PointerTypeLoc) 4375 CheckPolymorphic(ReferenceTypeLoc) 4376 CheckPolymorphic(MemberPointerTypeLoc) 4377 CheckPolymorphic(BlockPointerTypeLoc) 4378 CheckPolymorphic(AtomicTypeLoc) 4379 4380 /// Handle all the types we haven't given a more specific 4381 /// implementation for above. 4382 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4383 // Every other kind of type that we haven't called out already 4384 // that has an inner type is either (1) sugar or (2) contains that 4385 // inner type in some way as a subobject. 4386 if (TypeLoc Next = TL.getNextTypeLoc()) 4387 return Visit(Next, Sel); 4388 4389 // If there's no inner type and we're in a permissive context, 4390 // don't diagnose. 4391 if (Sel == Sema::AbstractNone) return; 4392 4393 // Check whether the type matches the abstract type. 4394 QualType T = TL.getType(); 4395 if (T->isArrayType()) { 4396 Sel = Sema::AbstractArrayType; 4397 T = Info.S.Context.getBaseElementType(T); 4398 } 4399 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4400 if (CT != Info.AbstractType) return; 4401 4402 // It matched; do some magic. 4403 if (Sel == Sema::AbstractArrayType) { 4404 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4405 << T << TL.getSourceRange(); 4406 } else { 4407 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4408 << Sel << T << TL.getSourceRange(); 4409 } 4410 Info.DiagnoseAbstractType(); 4411 } 4412 }; 4413 4414 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4415 Sema::AbstractDiagSelID Sel) { 4416 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4417 } 4418 4419 } 4420 4421 /// Check for invalid uses of an abstract type in a method declaration. 4422 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4423 CXXMethodDecl *MD) { 4424 // No need to do the check on definitions, which require that 4425 // the return/param types be complete. 4426 if (MD->doesThisDeclarationHaveABody()) 4427 return; 4428 4429 // For safety's sake, just ignore it if we don't have type source 4430 // information. This should never happen for non-implicit methods, 4431 // but... 4432 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4433 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4434 } 4435 4436 /// Check for invalid uses of an abstract type within a class definition. 4437 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4438 CXXRecordDecl *RD) { 4439 for (auto *D : RD->decls()) { 4440 if (D->isImplicit()) continue; 4441 4442 // Methods and method templates. 4443 if (isa<CXXMethodDecl>(D)) { 4444 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4445 } else if (isa<FunctionTemplateDecl>(D)) { 4446 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4447 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4448 4449 // Fields and static variables. 4450 } else if (isa<FieldDecl>(D)) { 4451 FieldDecl *FD = cast<FieldDecl>(D); 4452 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4453 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4454 } else if (isa<VarDecl>(D)) { 4455 VarDecl *VD = cast<VarDecl>(D); 4456 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4457 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4458 4459 // Nested classes and class templates. 4460 } else if (isa<CXXRecordDecl>(D)) { 4461 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4462 } else if (isa<ClassTemplateDecl>(D)) { 4463 CheckAbstractClassUsage(Info, 4464 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4465 } 4466 } 4467 } 4468 4469 /// \brief Check class-level dllimport/dllexport attribute. 4470 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) { 4471 Attr *ClassAttr = getDLLAttr(Class); 4472 4473 // MSVC inherits DLL attributes to partial class template specializations. 4474 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 4475 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 4476 if (Attr *TemplateAttr = 4477 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 4478 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext())); 4479 A->setInherited(true); 4480 ClassAttr = A; 4481 } 4482 } 4483 } 4484 4485 if (!ClassAttr) 4486 return; 4487 4488 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 4489 !ClassAttr->isInherited()) { 4490 // Diagnose dll attributes on members of class with dll attribute. 4491 for (Decl *Member : Class->decls()) { 4492 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 4493 continue; 4494 InheritableAttr *MemberAttr = getDLLAttr(Member); 4495 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 4496 continue; 4497 4498 S.Diag(MemberAttr->getLocation(), 4499 diag::err_attribute_dll_member_of_dll_class) 4500 << MemberAttr << ClassAttr; 4501 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 4502 Member->setInvalidDecl(); 4503 } 4504 } 4505 4506 if (Class->getDescribedClassTemplate()) 4507 // Don't inherit dll attribute until the template is instantiated. 4508 return; 4509 4510 bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 4511 4512 // Force declaration of implicit members so they can inherit the attribute. 4513 S.ForceDeclarationOfImplicitMembers(Class); 4514 4515 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 4516 // seem to be true in practice? 4517 4518 TemplateSpecializationKind TSK = 4519 Class->getTemplateSpecializationKind(); 4520 4521 for (Decl *Member : Class->decls()) { 4522 VarDecl *VD = dyn_cast<VarDecl>(Member); 4523 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 4524 4525 // Only methods and static fields inherit the attributes. 4526 if (!VD && !MD) 4527 continue; 4528 4529 // Don't process deleted methods. 4530 if (MD && MD->isDeleted()) 4531 continue; 4532 4533 if (MD && MD->isMoveAssignmentOperator() && !ClassExported && 4534 MD->isInlined()) { 4535 // Current MSVC versions don't export the move assignment operators, so 4536 // don't attempt to import them if we have a definition. 4537 continue; 4538 } 4539 4540 if (!getDLLAttr(Member)) { 4541 auto *NewAttr = 4542 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext())); 4543 NewAttr->setInherited(true); 4544 Member->addAttr(NewAttr); 4545 } 4546 4547 if (MD && ClassExported) { 4548 if (MD->isUserProvided()) { 4549 // Instantiate non-default methods.. 4550 4551 // .. except for certain kinds of template specializations. 4552 if (TSK == TSK_ExplicitInstantiationDeclaration) 4553 continue; 4554 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 4555 continue; 4556 4557 S.MarkFunctionReferenced(Class->getLocation(), MD); 4558 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 4559 MD->isCopyAssignmentOperator() || 4560 MD->isMoveAssignmentOperator()) { 4561 // Instantiate non-trivial or explicitly defaulted methods, and the 4562 // copy assignment / move assignment operators. 4563 S.MarkFunctionReferenced(Class->getLocation(), MD); 4564 // Resolve its exception specification; CodeGen needs it. 4565 auto *FPT = MD->getType()->getAs<FunctionProtoType>(); 4566 S.ResolveExceptionSpec(Class->getLocation(), FPT); 4567 S.ActOnFinishInlineMethodDef(MD); 4568 } 4569 } 4570 } 4571 } 4572 4573 /// \brief Perform semantic checks on a class definition that has been 4574 /// completing, introducing implicitly-declared members, checking for 4575 /// abstract types, etc. 4576 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4577 if (!Record) 4578 return; 4579 4580 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4581 AbstractUsageInfo Info(*this, Record); 4582 CheckAbstractClassUsage(Info, Record); 4583 } 4584 4585 // If this is not an aggregate type and has no user-declared constructor, 4586 // complain about any non-static data members of reference or const scalar 4587 // type, since they will never get initializers. 4588 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4589 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4590 !Record->isLambda()) { 4591 bool Complained = false; 4592 for (const auto *F : Record->fields()) { 4593 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4594 continue; 4595 4596 if (F->getType()->isReferenceType() || 4597 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4598 if (!Complained) { 4599 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4600 << Record->getTagKind() << Record; 4601 Complained = true; 4602 } 4603 4604 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4605 << F->getType()->isReferenceType() 4606 << F->getDeclName(); 4607 } 4608 } 4609 } 4610 4611 if (Record->isDynamicClass() && !Record->isDependentType()) 4612 DynamicClasses.push_back(Record); 4613 4614 if (Record->getIdentifier()) { 4615 // C++ [class.mem]p13: 4616 // If T is the name of a class, then each of the following shall have a 4617 // name different from T: 4618 // - every member of every anonymous union that is a member of class T. 4619 // 4620 // C++ [class.mem]p14: 4621 // In addition, if class T has a user-declared constructor (12.1), every 4622 // non-static data member of class T shall have a name different from T. 4623 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4624 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4625 ++I) { 4626 NamedDecl *D = *I; 4627 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4628 isa<IndirectFieldDecl>(D)) { 4629 Diag(D->getLocation(), diag::err_member_name_of_class) 4630 << D->getDeclName(); 4631 break; 4632 } 4633 } 4634 } 4635 4636 // Warn if the class has virtual methods but non-virtual public destructor. 4637 if (Record->isPolymorphic() && !Record->isDependentType()) { 4638 CXXDestructorDecl *dtor = Record->getDestructor(); 4639 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 4640 !Record->hasAttr<FinalAttr>()) 4641 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4642 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4643 } 4644 4645 if (Record->isAbstract()) { 4646 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4647 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4648 << FA->isSpelledAsSealed(); 4649 DiagnoseAbstractType(Record); 4650 } 4651 } 4652 4653 if (!Record->isDependentType()) { 4654 for (auto *M : Record->methods()) { 4655 // See if a method overloads virtual methods in a base 4656 // class without overriding any. 4657 if (!M->isStatic()) 4658 DiagnoseHiddenVirtualMethods(M); 4659 4660 // Check whether the explicitly-defaulted special members are valid. 4661 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4662 CheckExplicitlyDefaultedSpecialMember(M); 4663 4664 // For an explicitly defaulted or deleted special member, we defer 4665 // determining triviality until the class is complete. That time is now! 4666 if (!M->isImplicit() && !M->isUserProvided()) { 4667 CXXSpecialMember CSM = getSpecialMember(M); 4668 if (CSM != CXXInvalid) { 4669 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 4670 4671 // Inform the class that we've finished declaring this member. 4672 Record->finishedDefaultedOrDeletedMember(M); 4673 } 4674 } 4675 } 4676 } 4677 4678 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4679 // function that is not a constructor declares that member function to be 4680 // const. [...] The class of which that function is a member shall be 4681 // a literal type. 4682 // 4683 // If the class has virtual bases, any constexpr members will already have 4684 // been diagnosed by the checks performed on the member declaration, so 4685 // suppress this (less useful) diagnostic. 4686 // 4687 // We delay this until we know whether an explicitly-defaulted (or deleted) 4688 // destructor for the class is trivial. 4689 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4690 !Record->isLiteral() && !Record->getNumVBases()) { 4691 for (const auto *M : Record->methods()) { 4692 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) { 4693 switch (Record->getTemplateSpecializationKind()) { 4694 case TSK_ImplicitInstantiation: 4695 case TSK_ExplicitInstantiationDeclaration: 4696 case TSK_ExplicitInstantiationDefinition: 4697 // If a template instantiates to a non-literal type, but its members 4698 // instantiate to constexpr functions, the template is technically 4699 // ill-formed, but we allow it for sanity. 4700 continue; 4701 4702 case TSK_Undeclared: 4703 case TSK_ExplicitSpecialization: 4704 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4705 diag::err_constexpr_method_non_literal); 4706 break; 4707 } 4708 4709 // Only produce one error per class. 4710 break; 4711 } 4712 } 4713 } 4714 4715 // ms_struct is a request to use the same ABI rules as MSVC. Check 4716 // whether this class uses any C++ features that are implemented 4717 // completely differently in MSVC, and if so, emit a diagnostic. 4718 // That diagnostic defaults to an error, but we allow projects to 4719 // map it down to a warning (or ignore it). It's a fairly common 4720 // practice among users of the ms_struct pragma to mass-annotate 4721 // headers, sweeping up a bunch of types that the project doesn't 4722 // really rely on MSVC-compatible layout for. We must therefore 4723 // support "ms_struct except for C++ stuff" as a secondary ABI. 4724 if (Record->isMsStruct(Context) && 4725 (Record->isPolymorphic() || Record->getNumBases())) { 4726 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 4727 } 4728 4729 // Declare inheriting constructors. We do this eagerly here because: 4730 // - The standard requires an eager diagnostic for conflicting inheriting 4731 // constructors from different classes. 4732 // - The lazy declaration of the other implicit constructors is so as to not 4733 // waste space and performance on classes that are not meant to be 4734 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4735 // have inheriting constructors. 4736 DeclareInheritingConstructors(Record); 4737 4738 checkDLLAttribute(*this, Record); 4739 } 4740 4741 /// Look up the special member function that would be called by a special 4742 /// member function for a subobject of class type. 4743 /// 4744 /// \param Class The class type of the subobject. 4745 /// \param CSM The kind of special member function. 4746 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 4747 /// \param ConstRHS True if this is a copy operation with a const object 4748 /// on its RHS, that is, if the argument to the outer special member 4749 /// function is 'const' and this is not a field marked 'mutable'. 4750 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 4751 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 4752 unsigned FieldQuals, bool ConstRHS) { 4753 unsigned LHSQuals = 0; 4754 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 4755 LHSQuals = FieldQuals; 4756 4757 unsigned RHSQuals = FieldQuals; 4758 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4759 RHSQuals = 0; 4760 else if (ConstRHS) 4761 RHSQuals |= Qualifiers::Const; 4762 4763 return S.LookupSpecialMember(Class, CSM, 4764 RHSQuals & Qualifiers::Const, 4765 RHSQuals & Qualifiers::Volatile, 4766 false, 4767 LHSQuals & Qualifiers::Const, 4768 LHSQuals & Qualifiers::Volatile); 4769 } 4770 4771 /// Is the special member function which would be selected to perform the 4772 /// specified operation on the specified class type a constexpr constructor? 4773 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4774 Sema::CXXSpecialMember CSM, 4775 unsigned Quals, bool ConstRHS) { 4776 Sema::SpecialMemberOverloadResult *SMOR = 4777 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 4778 if (!SMOR || !SMOR->getMethod()) 4779 // A constructor we wouldn't select can't be "involved in initializing" 4780 // anything. 4781 return true; 4782 return SMOR->getMethod()->isConstexpr(); 4783 } 4784 4785 /// Determine whether the specified special member function would be constexpr 4786 /// if it were implicitly defined. 4787 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4788 Sema::CXXSpecialMember CSM, 4789 bool ConstArg) { 4790 if (!S.getLangOpts().CPlusPlus11) 4791 return false; 4792 4793 // C++11 [dcl.constexpr]p4: 4794 // In the definition of a constexpr constructor [...] 4795 bool Ctor = true; 4796 switch (CSM) { 4797 case Sema::CXXDefaultConstructor: 4798 // Since default constructor lookup is essentially trivial (and cannot 4799 // involve, for instance, template instantiation), we compute whether a 4800 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4801 // 4802 // This is important for performance; we need to know whether the default 4803 // constructor is constexpr to determine whether the type is a literal type. 4804 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4805 4806 case Sema::CXXCopyConstructor: 4807 case Sema::CXXMoveConstructor: 4808 // For copy or move constructors, we need to perform overload resolution. 4809 break; 4810 4811 case Sema::CXXCopyAssignment: 4812 case Sema::CXXMoveAssignment: 4813 if (!S.getLangOpts().CPlusPlus14) 4814 return false; 4815 // In C++1y, we need to perform overload resolution. 4816 Ctor = false; 4817 break; 4818 4819 case Sema::CXXDestructor: 4820 case Sema::CXXInvalid: 4821 return false; 4822 } 4823 4824 // -- if the class is a non-empty union, or for each non-empty anonymous 4825 // union member of a non-union class, exactly one non-static data member 4826 // shall be initialized; [DR1359] 4827 // 4828 // If we squint, this is guaranteed, since exactly one non-static data member 4829 // will be initialized (if the constructor isn't deleted), we just don't know 4830 // which one. 4831 if (Ctor && ClassDecl->isUnion()) 4832 return true; 4833 4834 // -- the class shall not have any virtual base classes; 4835 if (Ctor && ClassDecl->getNumVBases()) 4836 return false; 4837 4838 // C++1y [class.copy]p26: 4839 // -- [the class] is a literal type, and 4840 if (!Ctor && !ClassDecl->isLiteral()) 4841 return false; 4842 4843 // -- every constructor involved in initializing [...] base class 4844 // sub-objects shall be a constexpr constructor; 4845 // -- the assignment operator selected to copy/move each direct base 4846 // class is a constexpr function, and 4847 for (const auto &B : ClassDecl->bases()) { 4848 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 4849 if (!BaseType) continue; 4850 4851 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4852 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 4853 return false; 4854 } 4855 4856 // -- every constructor involved in initializing non-static data members 4857 // [...] shall be a constexpr constructor; 4858 // -- every non-static data member and base class sub-object shall be 4859 // initialized 4860 // -- for each non-static data member of X that is of class type (or array 4861 // thereof), the assignment operator selected to copy/move that member is 4862 // a constexpr function 4863 for (const auto *F : ClassDecl->fields()) { 4864 if (F->isInvalidDecl()) 4865 continue; 4866 QualType BaseType = S.Context.getBaseElementType(F->getType()); 4867 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 4868 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4869 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 4870 BaseType.getCVRQualifiers(), 4871 ConstArg && !F->isMutable())) 4872 return false; 4873 } 4874 } 4875 4876 // All OK, it's constexpr! 4877 return true; 4878 } 4879 4880 static Sema::ImplicitExceptionSpecification 4881 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4882 switch (S.getSpecialMember(MD)) { 4883 case Sema::CXXDefaultConstructor: 4884 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4885 case Sema::CXXCopyConstructor: 4886 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4887 case Sema::CXXCopyAssignment: 4888 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4889 case Sema::CXXMoveConstructor: 4890 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4891 case Sema::CXXMoveAssignment: 4892 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4893 case Sema::CXXDestructor: 4894 return S.ComputeDefaultedDtorExceptionSpec(MD); 4895 case Sema::CXXInvalid: 4896 break; 4897 } 4898 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4899 "only special members have implicit exception specs"); 4900 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4901 } 4902 4903 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 4904 CXXMethodDecl *MD) { 4905 FunctionProtoType::ExtProtoInfo EPI; 4906 4907 // Build an exception specification pointing back at this member. 4908 EPI.ExceptionSpec.Type = EST_Unevaluated; 4909 EPI.ExceptionSpec.SourceDecl = MD; 4910 4911 // Set the calling convention to the default for C++ instance methods. 4912 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 4913 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4914 /*IsCXXMethod=*/true)); 4915 return EPI; 4916 } 4917 4918 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4919 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4920 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4921 return; 4922 4923 // Evaluate the exception specification. 4924 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec(); 4925 4926 // Update the type of the special member to use it. 4927 UpdateExceptionSpec(MD, ESI); 4928 4929 // A user-provided destructor can be defined outside the class. When that 4930 // happens, be sure to update the exception specification on both 4931 // declarations. 4932 const FunctionProtoType *CanonicalFPT = 4933 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4934 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4935 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 4936 } 4937 4938 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4939 CXXRecordDecl *RD = MD->getParent(); 4940 CXXSpecialMember CSM = getSpecialMember(MD); 4941 4942 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4943 "not an explicitly-defaulted special member"); 4944 4945 // Whether this was the first-declared instance of the constructor. 4946 // This affects whether we implicitly add an exception spec and constexpr. 4947 bool First = MD == MD->getCanonicalDecl(); 4948 4949 bool HadError = false; 4950 4951 // C++11 [dcl.fct.def.default]p1: 4952 // A function that is explicitly defaulted shall 4953 // -- be a special member function (checked elsewhere), 4954 // -- have the same type (except for ref-qualifiers, and except that a 4955 // copy operation can take a non-const reference) as an implicit 4956 // declaration, and 4957 // -- not have default arguments. 4958 unsigned ExpectedParams = 1; 4959 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4960 ExpectedParams = 0; 4961 if (MD->getNumParams() != ExpectedParams) { 4962 // This also checks for default arguments: a copy or move constructor with a 4963 // default argument is classified as a default constructor, and assignment 4964 // operations and destructors can't have default arguments. 4965 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4966 << CSM << MD->getSourceRange(); 4967 HadError = true; 4968 } else if (MD->isVariadic()) { 4969 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4970 << CSM << MD->getSourceRange(); 4971 HadError = true; 4972 } 4973 4974 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4975 4976 bool CanHaveConstParam = false; 4977 if (CSM == CXXCopyConstructor) 4978 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4979 else if (CSM == CXXCopyAssignment) 4980 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4981 4982 QualType ReturnType = Context.VoidTy; 4983 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4984 // Check for return type matching. 4985 ReturnType = Type->getReturnType(); 4986 QualType ExpectedReturnType = 4987 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4988 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4989 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4990 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4991 HadError = true; 4992 } 4993 4994 // A defaulted special member cannot have cv-qualifiers. 4995 if (Type->getTypeQuals()) { 4996 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4997 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 4998 HadError = true; 4999 } 5000 } 5001 5002 // Check for parameter type matching. 5003 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 5004 bool HasConstParam = false; 5005 if (ExpectedParams && ArgType->isReferenceType()) { 5006 // Argument must be reference to possibly-const T. 5007 QualType ReferentType = ArgType->getPointeeType(); 5008 HasConstParam = ReferentType.isConstQualified(); 5009 5010 if (ReferentType.isVolatileQualified()) { 5011 Diag(MD->getLocation(), 5012 diag::err_defaulted_special_member_volatile_param) << CSM; 5013 HadError = true; 5014 } 5015 5016 if (HasConstParam && !CanHaveConstParam) { 5017 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 5018 Diag(MD->getLocation(), 5019 diag::err_defaulted_special_member_copy_const_param) 5020 << (CSM == CXXCopyAssignment); 5021 // FIXME: Explain why this special member can't be const. 5022 } else { 5023 Diag(MD->getLocation(), 5024 diag::err_defaulted_special_member_move_const_param) 5025 << (CSM == CXXMoveAssignment); 5026 } 5027 HadError = true; 5028 } 5029 } else if (ExpectedParams) { 5030 // A copy assignment operator can take its argument by value, but a 5031 // defaulted one cannot. 5032 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 5033 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 5034 HadError = true; 5035 } 5036 5037 // C++11 [dcl.fct.def.default]p2: 5038 // An explicitly-defaulted function may be declared constexpr only if it 5039 // would have been implicitly declared as constexpr, 5040 // Do not apply this rule to members of class templates, since core issue 1358 5041 // makes such functions always instantiate to constexpr functions. For 5042 // functions which cannot be constexpr (for non-constructors in C++11 and for 5043 // destructors in C++1y), this is checked elsewhere. 5044 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 5045 HasConstParam); 5046 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 5047 : isa<CXXConstructorDecl>(MD)) && 5048 MD->isConstexpr() && !Constexpr && 5049 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 5050 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 5051 // FIXME: Explain why the special member can't be constexpr. 5052 HadError = true; 5053 } 5054 5055 // and may have an explicit exception-specification only if it is compatible 5056 // with the exception-specification on the implicit declaration. 5057 if (Type->hasExceptionSpec()) { 5058 // Delay the check if this is the first declaration of the special member, 5059 // since we may not have parsed some necessary in-class initializers yet. 5060 if (First) { 5061 // If the exception specification needs to be instantiated, do so now, 5062 // before we clobber it with an EST_Unevaluated specification below. 5063 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 5064 InstantiateExceptionSpec(MD->getLocStart(), MD); 5065 Type = MD->getType()->getAs<FunctionProtoType>(); 5066 } 5067 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 5068 } else 5069 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 5070 } 5071 5072 // If a function is explicitly defaulted on its first declaration, 5073 if (First) { 5074 // -- it is implicitly considered to be constexpr if the implicit 5075 // definition would be, 5076 MD->setConstexpr(Constexpr); 5077 5078 // -- it is implicitly considered to have the same exception-specification 5079 // as if it had been implicitly declared, 5080 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 5081 EPI.ExceptionSpec.Type = EST_Unevaluated; 5082 EPI.ExceptionSpec.SourceDecl = MD; 5083 MD->setType(Context.getFunctionType(ReturnType, 5084 llvm::makeArrayRef(&ArgType, 5085 ExpectedParams), 5086 EPI)); 5087 } 5088 5089 if (ShouldDeleteSpecialMember(MD, CSM)) { 5090 if (First) { 5091 SetDeclDeleted(MD, MD->getLocation()); 5092 } else { 5093 // C++11 [dcl.fct.def.default]p4: 5094 // [For a] user-provided explicitly-defaulted function [...] if such a 5095 // function is implicitly defined as deleted, the program is ill-formed. 5096 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 5097 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 5098 HadError = true; 5099 } 5100 } 5101 5102 if (HadError) 5103 MD->setInvalidDecl(); 5104 } 5105 5106 /// Check whether the exception specification provided for an 5107 /// explicitly-defaulted special member matches the exception specification 5108 /// that would have been generated for an implicit special member, per 5109 /// C++11 [dcl.fct.def.default]p2. 5110 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 5111 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 5112 // Compute the implicit exception specification. 5113 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 5114 /*IsCXXMethod=*/true); 5115 FunctionProtoType::ExtProtoInfo EPI(CC); 5116 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD) 5117 .getExceptionSpec(); 5118 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 5119 Context.getFunctionType(Context.VoidTy, None, EPI)); 5120 5121 // Ensure that it matches. 5122 CheckEquivalentExceptionSpec( 5123 PDiag(diag::err_incorrect_defaulted_exception_spec) 5124 << getSpecialMember(MD), PDiag(), 5125 ImplicitType, SourceLocation(), 5126 SpecifiedType, MD->getLocation()); 5127 } 5128 5129 void Sema::CheckDelayedMemberExceptionSpecs() { 5130 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>, 5131 2> Checks; 5132 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs; 5133 5134 std::swap(Checks, DelayedDestructorExceptionSpecChecks); 5135 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 5136 5137 // Perform any deferred checking of exception specifications for virtual 5138 // destructors. 5139 for (unsigned i = 0, e = Checks.size(); i != e; ++i) { 5140 const CXXDestructorDecl *Dtor = Checks[i].first; 5141 assert(!Dtor->getParent()->isDependentType() && 5142 "Should not ever add destructors of templates into the list."); 5143 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second); 5144 } 5145 5146 // Check that any explicitly-defaulted methods have exception specifications 5147 // compatible with their implicit exception specifications. 5148 for (unsigned I = 0, N = Specs.size(); I != N; ++I) 5149 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first, 5150 Specs[I].second); 5151 } 5152 5153 namespace { 5154 struct SpecialMemberDeletionInfo { 5155 Sema &S; 5156 CXXMethodDecl *MD; 5157 Sema::CXXSpecialMember CSM; 5158 bool Diagnose; 5159 5160 // Properties of the special member, computed for convenience. 5161 bool IsConstructor, IsAssignment, IsMove, ConstArg; 5162 SourceLocation Loc; 5163 5164 bool AllFieldsAreConst; 5165 5166 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 5167 Sema::CXXSpecialMember CSM, bool Diagnose) 5168 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 5169 IsConstructor(false), IsAssignment(false), IsMove(false), 5170 ConstArg(false), Loc(MD->getLocation()), 5171 AllFieldsAreConst(true) { 5172 switch (CSM) { 5173 case Sema::CXXDefaultConstructor: 5174 case Sema::CXXCopyConstructor: 5175 IsConstructor = true; 5176 break; 5177 case Sema::CXXMoveConstructor: 5178 IsConstructor = true; 5179 IsMove = true; 5180 break; 5181 case Sema::CXXCopyAssignment: 5182 IsAssignment = true; 5183 break; 5184 case Sema::CXXMoveAssignment: 5185 IsAssignment = true; 5186 IsMove = true; 5187 break; 5188 case Sema::CXXDestructor: 5189 break; 5190 case Sema::CXXInvalid: 5191 llvm_unreachable("invalid special member kind"); 5192 } 5193 5194 if (MD->getNumParams()) { 5195 if (const ReferenceType *RT = 5196 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 5197 ConstArg = RT->getPointeeType().isConstQualified(); 5198 } 5199 } 5200 5201 bool inUnion() const { return MD->getParent()->isUnion(); } 5202 5203 /// Look up the corresponding special member in the given class. 5204 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 5205 unsigned Quals, bool IsMutable) { 5206 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 5207 ConstArg && !IsMutable); 5208 } 5209 5210 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 5211 5212 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 5213 bool shouldDeleteForField(FieldDecl *FD); 5214 bool shouldDeleteForAllConstMembers(); 5215 5216 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 5217 unsigned Quals); 5218 bool shouldDeleteForSubobjectCall(Subobject Subobj, 5219 Sema::SpecialMemberOverloadResult *SMOR, 5220 bool IsDtorCallInCtor); 5221 5222 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5223 }; 5224 } 5225 5226 /// Is the given special member inaccessible when used on the given 5227 /// sub-object. 5228 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5229 CXXMethodDecl *target) { 5230 /// If we're operating on a base class, the object type is the 5231 /// type of this special member. 5232 QualType objectTy; 5233 AccessSpecifier access = target->getAccess(); 5234 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5235 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5236 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5237 5238 // If we're operating on a field, the object type is the type of the field. 5239 } else { 5240 objectTy = S.Context.getTypeDeclType(target->getParent()); 5241 } 5242 5243 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5244 } 5245 5246 /// Check whether we should delete a special member due to the implicit 5247 /// definition containing a call to a special member of a subobject. 5248 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5249 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5250 bool IsDtorCallInCtor) { 5251 CXXMethodDecl *Decl = SMOR->getMethod(); 5252 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5253 5254 int DiagKind = -1; 5255 5256 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5257 DiagKind = !Decl ? 0 : 1; 5258 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5259 DiagKind = 2; 5260 else if (!isAccessible(Subobj, Decl)) 5261 DiagKind = 3; 5262 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5263 !Decl->isTrivial()) { 5264 // A member of a union must have a trivial corresponding special member. 5265 // As a weird special case, a destructor call from a union's constructor 5266 // must be accessible and non-deleted, but need not be trivial. Such a 5267 // destructor is never actually called, but is semantically checked as 5268 // if it were. 5269 DiagKind = 4; 5270 } 5271 5272 if (DiagKind == -1) 5273 return false; 5274 5275 if (Diagnose) { 5276 if (Field) { 5277 S.Diag(Field->getLocation(), 5278 diag::note_deleted_special_member_class_subobject) 5279 << CSM << MD->getParent() << /*IsField*/true 5280 << Field << DiagKind << IsDtorCallInCtor; 5281 } else { 5282 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5283 S.Diag(Base->getLocStart(), 5284 diag::note_deleted_special_member_class_subobject) 5285 << CSM << MD->getParent() << /*IsField*/false 5286 << Base->getType() << DiagKind << IsDtorCallInCtor; 5287 } 5288 5289 if (DiagKind == 1) 5290 S.NoteDeletedFunction(Decl); 5291 // FIXME: Explain inaccessibility if DiagKind == 3. 5292 } 5293 5294 return true; 5295 } 5296 5297 /// Check whether we should delete a special member function due to having a 5298 /// direct or virtual base class or non-static data member of class type M. 5299 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5300 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5301 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5302 bool IsMutable = Field && Field->isMutable(); 5303 5304 // C++11 [class.ctor]p5: 5305 // -- any direct or virtual base class, or non-static data member with no 5306 // brace-or-equal-initializer, has class type M (or array thereof) and 5307 // either M has no default constructor or overload resolution as applied 5308 // to M's default constructor results in an ambiguity or in a function 5309 // that is deleted or inaccessible 5310 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5311 // -- a direct or virtual base class B that cannot be copied/moved because 5312 // overload resolution, as applied to B's corresponding special member, 5313 // results in an ambiguity or a function that is deleted or inaccessible 5314 // from the defaulted special member 5315 // C++11 [class.dtor]p5: 5316 // -- any direct or virtual base class [...] has a type with a destructor 5317 // that is deleted or inaccessible 5318 if (!(CSM == Sema::CXXDefaultConstructor && 5319 Field && Field->hasInClassInitializer()) && 5320 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5321 false)) 5322 return true; 5323 5324 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5325 // -- any direct or virtual base class or non-static data member has a 5326 // type with a destructor that is deleted or inaccessible 5327 if (IsConstructor) { 5328 Sema::SpecialMemberOverloadResult *SMOR = 5329 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5330 false, false, false, false, false); 5331 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5332 return true; 5333 } 5334 5335 return false; 5336 } 5337 5338 /// Check whether we should delete a special member function due to the class 5339 /// having a particular direct or virtual base class. 5340 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5341 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5342 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5343 } 5344 5345 /// Check whether we should delete a special member function due to the class 5346 /// having a particular non-static data member. 5347 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5348 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5349 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5350 5351 if (CSM == Sema::CXXDefaultConstructor) { 5352 // For a default constructor, all references must be initialized in-class 5353 // and, if a union, it must have a non-const member. 5354 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5355 if (Diagnose) 5356 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5357 << MD->getParent() << FD << FieldType << /*Reference*/0; 5358 return true; 5359 } 5360 // C++11 [class.ctor]p5: any non-variant non-static data member of 5361 // const-qualified type (or array thereof) with no 5362 // brace-or-equal-initializer does not have a user-provided default 5363 // constructor. 5364 if (!inUnion() && FieldType.isConstQualified() && 5365 !FD->hasInClassInitializer() && 5366 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5367 if (Diagnose) 5368 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5369 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5370 return true; 5371 } 5372 5373 if (inUnion() && !FieldType.isConstQualified()) 5374 AllFieldsAreConst = false; 5375 } else if (CSM == Sema::CXXCopyConstructor) { 5376 // For a copy constructor, data members must not be of rvalue reference 5377 // type. 5378 if (FieldType->isRValueReferenceType()) { 5379 if (Diagnose) 5380 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5381 << MD->getParent() << FD << FieldType; 5382 return true; 5383 } 5384 } else if (IsAssignment) { 5385 // For an assignment operator, data members must not be of reference type. 5386 if (FieldType->isReferenceType()) { 5387 if (Diagnose) 5388 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5389 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5390 return true; 5391 } 5392 if (!FieldRecord && FieldType.isConstQualified()) { 5393 // C++11 [class.copy]p23: 5394 // -- a non-static data member of const non-class type (or array thereof) 5395 if (Diagnose) 5396 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5397 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5398 return true; 5399 } 5400 } 5401 5402 if (FieldRecord) { 5403 // Some additional restrictions exist on the variant members. 5404 if (!inUnion() && FieldRecord->isUnion() && 5405 FieldRecord->isAnonymousStructOrUnion()) { 5406 bool AllVariantFieldsAreConst = true; 5407 5408 // FIXME: Handle anonymous unions declared within anonymous unions. 5409 for (auto *UI : FieldRecord->fields()) { 5410 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5411 5412 if (!UnionFieldType.isConstQualified()) 5413 AllVariantFieldsAreConst = false; 5414 5415 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5416 if (UnionFieldRecord && 5417 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5418 UnionFieldType.getCVRQualifiers())) 5419 return true; 5420 } 5421 5422 // At least one member in each anonymous union must be non-const 5423 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5424 !FieldRecord->field_empty()) { 5425 if (Diagnose) 5426 S.Diag(FieldRecord->getLocation(), 5427 diag::note_deleted_default_ctor_all_const) 5428 << MD->getParent() << /*anonymous union*/1; 5429 return true; 5430 } 5431 5432 // Don't check the implicit member of the anonymous union type. 5433 // This is technically non-conformant, but sanity demands it. 5434 return false; 5435 } 5436 5437 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5438 FieldType.getCVRQualifiers())) 5439 return true; 5440 } 5441 5442 return false; 5443 } 5444 5445 /// C++11 [class.ctor] p5: 5446 /// A defaulted default constructor for a class X is defined as deleted if 5447 /// X is a union and all of its variant members are of const-qualified type. 5448 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5449 // This is a silly definition, because it gives an empty union a deleted 5450 // default constructor. Don't do that. 5451 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5452 !MD->getParent()->field_empty()) { 5453 if (Diagnose) 5454 S.Diag(MD->getParent()->getLocation(), 5455 diag::note_deleted_default_ctor_all_const) 5456 << MD->getParent() << /*not anonymous union*/0; 5457 return true; 5458 } 5459 return false; 5460 } 5461 5462 /// Determine whether a defaulted special member function should be defined as 5463 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5464 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5465 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5466 bool Diagnose) { 5467 if (MD->isInvalidDecl()) 5468 return false; 5469 CXXRecordDecl *RD = MD->getParent(); 5470 assert(!RD->isDependentType() && "do deletion after instantiation"); 5471 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5472 return false; 5473 5474 // C++11 [expr.lambda.prim]p19: 5475 // The closure type associated with a lambda-expression has a 5476 // deleted (8.4.3) default constructor and a deleted copy 5477 // assignment operator. 5478 if (RD->isLambda() && 5479 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5480 if (Diagnose) 5481 Diag(RD->getLocation(), diag::note_lambda_decl); 5482 return true; 5483 } 5484 5485 // For an anonymous struct or union, the copy and assignment special members 5486 // will never be used, so skip the check. For an anonymous union declared at 5487 // namespace scope, the constructor and destructor are used. 5488 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5489 RD->isAnonymousStructOrUnion()) 5490 return false; 5491 5492 // C++11 [class.copy]p7, p18: 5493 // If the class definition declares a move constructor or move assignment 5494 // operator, an implicitly declared copy constructor or copy assignment 5495 // operator is defined as deleted. 5496 if (MD->isImplicit() && 5497 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5498 CXXMethodDecl *UserDeclaredMove = nullptr; 5499 5500 // In Microsoft mode, a user-declared move only causes the deletion of the 5501 // corresponding copy operation, not both copy operations. 5502 if (RD->hasUserDeclaredMoveConstructor() && 5503 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5504 if (!Diagnose) return true; 5505 5506 // Find any user-declared move constructor. 5507 for (auto *I : RD->ctors()) { 5508 if (I->isMoveConstructor()) { 5509 UserDeclaredMove = I; 5510 break; 5511 } 5512 } 5513 assert(UserDeclaredMove); 5514 } else if (RD->hasUserDeclaredMoveAssignment() && 5515 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5516 if (!Diagnose) return true; 5517 5518 // Find any user-declared move assignment operator. 5519 for (auto *I : RD->methods()) { 5520 if (I->isMoveAssignmentOperator()) { 5521 UserDeclaredMove = I; 5522 break; 5523 } 5524 } 5525 assert(UserDeclaredMove); 5526 } 5527 5528 if (UserDeclaredMove) { 5529 Diag(UserDeclaredMove->getLocation(), 5530 diag::note_deleted_copy_user_declared_move) 5531 << (CSM == CXXCopyAssignment) << RD 5532 << UserDeclaredMove->isMoveAssignmentOperator(); 5533 return true; 5534 } 5535 } 5536 5537 // Do access control from the special member function 5538 ContextRAII MethodContext(*this, MD); 5539 5540 // C++11 [class.dtor]p5: 5541 // -- for a virtual destructor, lookup of the non-array deallocation function 5542 // results in an ambiguity or in a function that is deleted or inaccessible 5543 if (CSM == CXXDestructor && MD->isVirtual()) { 5544 FunctionDecl *OperatorDelete = nullptr; 5545 DeclarationName Name = 5546 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5547 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5548 OperatorDelete, false)) { 5549 if (Diagnose) 5550 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5551 return true; 5552 } 5553 } 5554 5555 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5556 5557 for (auto &BI : RD->bases()) 5558 if (!BI.isVirtual() && 5559 SMI.shouldDeleteForBase(&BI)) 5560 return true; 5561 5562 // Per DR1611, do not consider virtual bases of constructors of abstract 5563 // classes, since we are not going to construct them. 5564 if (!RD->isAbstract() || !SMI.IsConstructor) { 5565 for (auto &BI : RD->vbases()) 5566 if (SMI.shouldDeleteForBase(&BI)) 5567 return true; 5568 } 5569 5570 for (auto *FI : RD->fields()) 5571 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5572 SMI.shouldDeleteForField(FI)) 5573 return true; 5574 5575 if (SMI.shouldDeleteForAllConstMembers()) 5576 return true; 5577 5578 if (getLangOpts().CUDA) { 5579 // We should delete the special member in CUDA mode if target inference 5580 // failed. 5581 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg, 5582 Diagnose); 5583 } 5584 5585 return false; 5586 } 5587 5588 /// Perform lookup for a special member of the specified kind, and determine 5589 /// whether it is trivial. If the triviality can be determined without the 5590 /// lookup, skip it. This is intended for use when determining whether a 5591 /// special member of a containing object is trivial, and thus does not ever 5592 /// perform overload resolution for default constructors. 5593 /// 5594 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5595 /// member that was most likely to be intended to be trivial, if any. 5596 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5597 Sema::CXXSpecialMember CSM, unsigned Quals, 5598 bool ConstRHS, CXXMethodDecl **Selected) { 5599 if (Selected) 5600 *Selected = nullptr; 5601 5602 switch (CSM) { 5603 case Sema::CXXInvalid: 5604 llvm_unreachable("not a special member"); 5605 5606 case Sema::CXXDefaultConstructor: 5607 // C++11 [class.ctor]p5: 5608 // A default constructor is trivial if: 5609 // - all the [direct subobjects] have trivial default constructors 5610 // 5611 // Note, no overload resolution is performed in this case. 5612 if (RD->hasTrivialDefaultConstructor()) 5613 return true; 5614 5615 if (Selected) { 5616 // If there's a default constructor which could have been trivial, dig it 5617 // out. Otherwise, if there's any user-provided default constructor, point 5618 // to that as an example of why there's not a trivial one. 5619 CXXConstructorDecl *DefCtor = nullptr; 5620 if (RD->needsImplicitDefaultConstructor()) 5621 S.DeclareImplicitDefaultConstructor(RD); 5622 for (auto *CI : RD->ctors()) { 5623 if (!CI->isDefaultConstructor()) 5624 continue; 5625 DefCtor = CI; 5626 if (!DefCtor->isUserProvided()) 5627 break; 5628 } 5629 5630 *Selected = DefCtor; 5631 } 5632 5633 return false; 5634 5635 case Sema::CXXDestructor: 5636 // C++11 [class.dtor]p5: 5637 // A destructor is trivial if: 5638 // - all the direct [subobjects] have trivial destructors 5639 if (RD->hasTrivialDestructor()) 5640 return true; 5641 5642 if (Selected) { 5643 if (RD->needsImplicitDestructor()) 5644 S.DeclareImplicitDestructor(RD); 5645 *Selected = RD->getDestructor(); 5646 } 5647 5648 return false; 5649 5650 case Sema::CXXCopyConstructor: 5651 // C++11 [class.copy]p12: 5652 // A copy constructor is trivial if: 5653 // - the constructor selected to copy each direct [subobject] is trivial 5654 if (RD->hasTrivialCopyConstructor()) { 5655 if (Quals == Qualifiers::Const) 5656 // We must either select the trivial copy constructor or reach an 5657 // ambiguity; no need to actually perform overload resolution. 5658 return true; 5659 } else if (!Selected) { 5660 return false; 5661 } 5662 // In C++98, we are not supposed to perform overload resolution here, but we 5663 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5664 // cases like B as having a non-trivial copy constructor: 5665 // struct A { template<typename T> A(T&); }; 5666 // struct B { mutable A a; }; 5667 goto NeedOverloadResolution; 5668 5669 case Sema::CXXCopyAssignment: 5670 // C++11 [class.copy]p25: 5671 // A copy assignment operator is trivial if: 5672 // - the assignment operator selected to copy each direct [subobject] is 5673 // trivial 5674 if (RD->hasTrivialCopyAssignment()) { 5675 if (Quals == Qualifiers::Const) 5676 return true; 5677 } else if (!Selected) { 5678 return false; 5679 } 5680 // In C++98, we are not supposed to perform overload resolution here, but we 5681 // treat that as a language defect. 5682 goto NeedOverloadResolution; 5683 5684 case Sema::CXXMoveConstructor: 5685 case Sema::CXXMoveAssignment: 5686 NeedOverloadResolution: 5687 Sema::SpecialMemberOverloadResult *SMOR = 5688 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5689 5690 // The standard doesn't describe how to behave if the lookup is ambiguous. 5691 // We treat it as not making the member non-trivial, just like the standard 5692 // mandates for the default constructor. This should rarely matter, because 5693 // the member will also be deleted. 5694 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5695 return true; 5696 5697 if (!SMOR->getMethod()) { 5698 assert(SMOR->getKind() == 5699 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5700 return false; 5701 } 5702 5703 // We deliberately don't check if we found a deleted special member. We're 5704 // not supposed to! 5705 if (Selected) 5706 *Selected = SMOR->getMethod(); 5707 return SMOR->getMethod()->isTrivial(); 5708 } 5709 5710 llvm_unreachable("unknown special method kind"); 5711 } 5712 5713 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5714 for (auto *CI : RD->ctors()) 5715 if (!CI->isImplicit()) 5716 return CI; 5717 5718 // Look for constructor templates. 5719 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5720 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5721 if (CXXConstructorDecl *CD = 5722 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5723 return CD; 5724 } 5725 5726 return nullptr; 5727 } 5728 5729 /// The kind of subobject we are checking for triviality. The values of this 5730 /// enumeration are used in diagnostics. 5731 enum TrivialSubobjectKind { 5732 /// The subobject is a base class. 5733 TSK_BaseClass, 5734 /// The subobject is a non-static data member. 5735 TSK_Field, 5736 /// The object is actually the complete object. 5737 TSK_CompleteObject 5738 }; 5739 5740 /// Check whether the special member selected for a given type would be trivial. 5741 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5742 QualType SubType, bool ConstRHS, 5743 Sema::CXXSpecialMember CSM, 5744 TrivialSubobjectKind Kind, 5745 bool Diagnose) { 5746 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5747 if (!SubRD) 5748 return true; 5749 5750 CXXMethodDecl *Selected; 5751 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5752 ConstRHS, Diagnose ? &Selected : nullptr)) 5753 return true; 5754 5755 if (Diagnose) { 5756 if (ConstRHS) 5757 SubType.addConst(); 5758 5759 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5760 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5761 << Kind << SubType.getUnqualifiedType(); 5762 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5763 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5764 } else if (!Selected) 5765 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5766 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5767 else if (Selected->isUserProvided()) { 5768 if (Kind == TSK_CompleteObject) 5769 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5770 << Kind << SubType.getUnqualifiedType() << CSM; 5771 else { 5772 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5773 << Kind << SubType.getUnqualifiedType() << CSM; 5774 S.Diag(Selected->getLocation(), diag::note_declared_at); 5775 } 5776 } else { 5777 if (Kind != TSK_CompleteObject) 5778 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5779 << Kind << SubType.getUnqualifiedType() << CSM; 5780 5781 // Explain why the defaulted or deleted special member isn't trivial. 5782 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5783 } 5784 } 5785 5786 return false; 5787 } 5788 5789 /// Check whether the members of a class type allow a special member to be 5790 /// trivial. 5791 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5792 Sema::CXXSpecialMember CSM, 5793 bool ConstArg, bool Diagnose) { 5794 for (const auto *FI : RD->fields()) { 5795 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5796 continue; 5797 5798 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5799 5800 // Pretend anonymous struct or union members are members of this class. 5801 if (FI->isAnonymousStructOrUnion()) { 5802 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5803 CSM, ConstArg, Diagnose)) 5804 return false; 5805 continue; 5806 } 5807 5808 // C++11 [class.ctor]p5: 5809 // A default constructor is trivial if [...] 5810 // -- no non-static data member of its class has a 5811 // brace-or-equal-initializer 5812 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5813 if (Diagnose) 5814 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 5815 return false; 5816 } 5817 5818 // Objective C ARC 4.3.5: 5819 // [...] nontrivally ownership-qualified types are [...] not trivially 5820 // default constructible, copy constructible, move constructible, copy 5821 // assignable, move assignable, or destructible [...] 5822 if (S.getLangOpts().ObjCAutoRefCount && 5823 FieldType.hasNonTrivialObjCLifetime()) { 5824 if (Diagnose) 5825 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5826 << RD << FieldType.getObjCLifetime(); 5827 return false; 5828 } 5829 5830 bool ConstRHS = ConstArg && !FI->isMutable(); 5831 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 5832 CSM, TSK_Field, Diagnose)) 5833 return false; 5834 } 5835 5836 return true; 5837 } 5838 5839 /// Diagnose why the specified class does not have a trivial special member of 5840 /// the given kind. 5841 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5842 QualType Ty = Context.getRecordType(RD); 5843 5844 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 5845 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 5846 TSK_CompleteObject, /*Diagnose*/true); 5847 } 5848 5849 /// Determine whether a defaulted or deleted special member function is trivial, 5850 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5851 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5852 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5853 bool Diagnose) { 5854 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5855 5856 CXXRecordDecl *RD = MD->getParent(); 5857 5858 bool ConstArg = false; 5859 5860 // C++11 [class.copy]p12, p25: [DR1593] 5861 // A [special member] is trivial if [...] its parameter-type-list is 5862 // equivalent to the parameter-type-list of an implicit declaration [...] 5863 switch (CSM) { 5864 case CXXDefaultConstructor: 5865 case CXXDestructor: 5866 // Trivial default constructors and destructors cannot have parameters. 5867 break; 5868 5869 case CXXCopyConstructor: 5870 case CXXCopyAssignment: { 5871 // Trivial copy operations always have const, non-volatile parameter types. 5872 ConstArg = true; 5873 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5874 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5875 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5876 if (Diagnose) 5877 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5878 << Param0->getSourceRange() << Param0->getType() 5879 << Context.getLValueReferenceType( 5880 Context.getRecordType(RD).withConst()); 5881 return false; 5882 } 5883 break; 5884 } 5885 5886 case CXXMoveConstructor: 5887 case CXXMoveAssignment: { 5888 // Trivial move operations always have non-cv-qualified parameters. 5889 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5890 const RValueReferenceType *RT = 5891 Param0->getType()->getAs<RValueReferenceType>(); 5892 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5893 if (Diagnose) 5894 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5895 << Param0->getSourceRange() << Param0->getType() 5896 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5897 return false; 5898 } 5899 break; 5900 } 5901 5902 case CXXInvalid: 5903 llvm_unreachable("not a special member"); 5904 } 5905 5906 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5907 if (Diagnose) 5908 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5909 diag::note_nontrivial_default_arg) 5910 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5911 return false; 5912 } 5913 if (MD->isVariadic()) { 5914 if (Diagnose) 5915 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5916 return false; 5917 } 5918 5919 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5920 // A copy/move [constructor or assignment operator] is trivial if 5921 // -- the [member] selected to copy/move each direct base class subobject 5922 // is trivial 5923 // 5924 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5925 // A [default constructor or destructor] is trivial if 5926 // -- all the direct base classes have trivial [default constructors or 5927 // destructors] 5928 for (const auto &BI : RD->bases()) 5929 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 5930 ConstArg, CSM, TSK_BaseClass, Diagnose)) 5931 return false; 5932 5933 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5934 // A copy/move [constructor or assignment operator] for a class X is 5935 // trivial if 5936 // -- for each non-static data member of X that is of class type (or array 5937 // thereof), the constructor selected to copy/move that member is 5938 // trivial 5939 // 5940 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5941 // A [default constructor or destructor] is trivial if 5942 // -- for all of the non-static data members of its class that are of class 5943 // type (or array thereof), each such class has a trivial [default 5944 // constructor or destructor] 5945 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5946 return false; 5947 5948 // C++11 [class.dtor]p5: 5949 // A destructor is trivial if [...] 5950 // -- the destructor is not virtual 5951 if (CSM == CXXDestructor && MD->isVirtual()) { 5952 if (Diagnose) 5953 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5954 return false; 5955 } 5956 5957 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5958 // A [special member] for class X is trivial if [...] 5959 // -- class X has no virtual functions and no virtual base classes 5960 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5961 if (!Diagnose) 5962 return false; 5963 5964 if (RD->getNumVBases()) { 5965 // Check for virtual bases. We already know that the corresponding 5966 // member in all bases is trivial, so vbases must all be direct. 5967 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5968 assert(BS.isVirtual()); 5969 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5970 return false; 5971 } 5972 5973 // Must have a virtual method. 5974 for (const auto *MI : RD->methods()) { 5975 if (MI->isVirtual()) { 5976 SourceLocation MLoc = MI->getLocStart(); 5977 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5978 return false; 5979 } 5980 } 5981 5982 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5983 } 5984 5985 // Looks like it's trivial! 5986 return true; 5987 } 5988 5989 /// \brief Data used with FindHiddenVirtualMethod 5990 namespace { 5991 struct FindHiddenVirtualMethodData { 5992 Sema *S; 5993 CXXMethodDecl *Method; 5994 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5995 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5996 }; 5997 } 5998 5999 /// \brief Check whether any most overriden method from MD in Methods 6000 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 6001 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6002 if (MD->size_overridden_methods() == 0) 6003 return Methods.count(MD->getCanonicalDecl()); 6004 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6005 E = MD->end_overridden_methods(); 6006 I != E; ++I) 6007 if (CheckMostOverridenMethods(*I, Methods)) 6008 return true; 6009 return false; 6010 } 6011 6012 /// \brief Member lookup function that determines whether a given C++ 6013 /// method overloads virtual methods in a base class without overriding any, 6014 /// to be used with CXXRecordDecl::lookupInBases(). 6015 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 6016 CXXBasePath &Path, 6017 void *UserData) { 6018 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6019 6020 FindHiddenVirtualMethodData &Data 6021 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 6022 6023 DeclarationName Name = Data.Method->getDeclName(); 6024 assert(Name.getNameKind() == DeclarationName::Identifier); 6025 6026 bool foundSameNameMethod = false; 6027 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 6028 for (Path.Decls = BaseRecord->lookup(Name); 6029 !Path.Decls.empty(); 6030 Path.Decls = Path.Decls.slice(1)) { 6031 NamedDecl *D = Path.Decls.front(); 6032 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6033 MD = MD->getCanonicalDecl(); 6034 foundSameNameMethod = true; 6035 // Interested only in hidden virtual methods. 6036 if (!MD->isVirtual()) 6037 continue; 6038 // If the method we are checking overrides a method from its base 6039 // don't warn about the other overloaded methods. Clang deviates from GCC 6040 // by only diagnosing overloads of inherited virtual functions that do not 6041 // override any other virtual functions in the base. GCC's 6042 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 6043 // function from a base class. These cases may be better served by a 6044 // warning (not specific to virtual functions) on call sites when the call 6045 // would select a different function from the base class, were it visible. 6046 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 6047 if (!Data.S->IsOverload(Data.Method, MD, false)) 6048 return true; 6049 // Collect the overload only if its hidden. 6050 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 6051 overloadedMethods.push_back(MD); 6052 } 6053 } 6054 6055 if (foundSameNameMethod) 6056 Data.OverloadedMethods.append(overloadedMethods.begin(), 6057 overloadedMethods.end()); 6058 return foundSameNameMethod; 6059 } 6060 6061 /// \brief Add the most overriden methods from MD to Methods 6062 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 6063 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 6064 if (MD->size_overridden_methods() == 0) 6065 Methods.insert(MD->getCanonicalDecl()); 6066 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6067 E = MD->end_overridden_methods(); 6068 I != E; ++I) 6069 AddMostOverridenMethods(*I, Methods); 6070 } 6071 6072 /// \brief Check if a method overloads virtual methods in a base class without 6073 /// overriding any. 6074 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 6075 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6076 if (!MD->getDeclName().isIdentifier()) 6077 return; 6078 6079 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 6080 /*bool RecordPaths=*/false, 6081 /*bool DetectVirtual=*/false); 6082 FindHiddenVirtualMethodData Data; 6083 Data.Method = MD; 6084 Data.S = this; 6085 6086 // Keep the base methods that were overriden or introduced in the subclass 6087 // by 'using' in a set. A base method not in this set is hidden. 6088 CXXRecordDecl *DC = MD->getParent(); 6089 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 6090 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 6091 NamedDecl *ND = *I; 6092 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 6093 ND = shad->getTargetDecl(); 6094 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6095 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 6096 } 6097 6098 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 6099 OverloadedMethods = Data.OverloadedMethods; 6100 } 6101 6102 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 6103 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 6104 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 6105 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 6106 PartialDiagnostic PD = PDiag( 6107 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 6108 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 6109 Diag(overloadedMD->getLocation(), PD); 6110 } 6111 } 6112 6113 /// \brief Diagnose methods which overload virtual methods in a base class 6114 /// without overriding any. 6115 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 6116 if (MD->isInvalidDecl()) 6117 return; 6118 6119 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 6120 return; 6121 6122 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 6123 FindHiddenVirtualMethods(MD, OverloadedMethods); 6124 if (!OverloadedMethods.empty()) { 6125 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 6126 << MD << (OverloadedMethods.size() > 1); 6127 6128 NoteHiddenVirtualMethods(MD, OverloadedMethods); 6129 } 6130 } 6131 6132 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 6133 Decl *TagDecl, 6134 SourceLocation LBrac, 6135 SourceLocation RBrac, 6136 AttributeList *AttrList) { 6137 if (!TagDecl) 6138 return; 6139 6140 AdjustDeclIfTemplate(TagDecl); 6141 6142 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6143 if (l->getKind() != AttributeList::AT_Visibility) 6144 continue; 6145 l->setInvalid(); 6146 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 6147 l->getName(); 6148 } 6149 6150 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 6151 // strict aliasing violation! 6152 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 6153 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 6154 6155 CheckCompletedCXXClass( 6156 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 6157 } 6158 6159 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 6160 /// special functions, such as the default constructor, copy 6161 /// constructor, or destructor, to the given C++ class (C++ 6162 /// [special]p1). This routine can only be executed just before the 6163 /// definition of the class is complete. 6164 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 6165 if (!ClassDecl->hasUserDeclaredConstructor()) 6166 ++ASTContext::NumImplicitDefaultConstructors; 6167 6168 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 6169 ++ASTContext::NumImplicitCopyConstructors; 6170 6171 // If the properties or semantics of the copy constructor couldn't be 6172 // determined while the class was being declared, force a declaration 6173 // of it now. 6174 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 6175 DeclareImplicitCopyConstructor(ClassDecl); 6176 } 6177 6178 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 6179 ++ASTContext::NumImplicitMoveConstructors; 6180 6181 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 6182 DeclareImplicitMoveConstructor(ClassDecl); 6183 } 6184 6185 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 6186 ++ASTContext::NumImplicitCopyAssignmentOperators; 6187 6188 // If we have a dynamic class, then the copy assignment operator may be 6189 // virtual, so we have to declare it immediately. This ensures that, e.g., 6190 // it shows up in the right place in the vtable and that we diagnose 6191 // problems with the implicit exception specification. 6192 if (ClassDecl->isDynamicClass() || 6193 ClassDecl->needsOverloadResolutionForCopyAssignment()) 6194 DeclareImplicitCopyAssignment(ClassDecl); 6195 } 6196 6197 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 6198 ++ASTContext::NumImplicitMoveAssignmentOperators; 6199 6200 // Likewise for the move assignment operator. 6201 if (ClassDecl->isDynamicClass() || 6202 ClassDecl->needsOverloadResolutionForMoveAssignment()) 6203 DeclareImplicitMoveAssignment(ClassDecl); 6204 } 6205 6206 if (!ClassDecl->hasUserDeclaredDestructor()) { 6207 ++ASTContext::NumImplicitDestructors; 6208 6209 // If we have a dynamic class, then the destructor may be virtual, so we 6210 // have to declare the destructor immediately. This ensures that, e.g., it 6211 // shows up in the right place in the vtable and that we diagnose problems 6212 // with the implicit exception specification. 6213 if (ClassDecl->isDynamicClass() || 6214 ClassDecl->needsOverloadResolutionForDestructor()) 6215 DeclareImplicitDestructor(ClassDecl); 6216 } 6217 } 6218 6219 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6220 if (!D) 6221 return 0; 6222 6223 // The order of template parameters is not important here. All names 6224 // get added to the same scope. 6225 SmallVector<TemplateParameterList *, 4> ParameterLists; 6226 6227 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 6228 D = TD->getTemplatedDecl(); 6229 6230 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6231 ParameterLists.push_back(PSD->getTemplateParameters()); 6232 6233 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 6234 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 6235 ParameterLists.push_back(DD->getTemplateParameterList(i)); 6236 6237 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6238 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 6239 ParameterLists.push_back(FTD->getTemplateParameters()); 6240 } 6241 } 6242 6243 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 6244 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 6245 ParameterLists.push_back(TD->getTemplateParameterList(i)); 6246 6247 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 6248 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 6249 ParameterLists.push_back(CTD->getTemplateParameters()); 6250 } 6251 } 6252 6253 unsigned Count = 0; 6254 for (TemplateParameterList *Params : ParameterLists) { 6255 if (Params->size() > 0) 6256 // Ignore explicit specializations; they don't contribute to the template 6257 // depth. 6258 ++Count; 6259 for (NamedDecl *Param : *Params) { 6260 if (Param->getDeclName()) { 6261 S->AddDecl(Param); 6262 IdResolver.AddDecl(Param); 6263 } 6264 } 6265 } 6266 6267 return Count; 6268 } 6269 6270 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6271 if (!RecordD) return; 6272 AdjustDeclIfTemplate(RecordD); 6273 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6274 PushDeclContext(S, Record); 6275 } 6276 6277 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6278 if (!RecordD) return; 6279 PopDeclContext(); 6280 } 6281 6282 /// This is used to implement the constant expression evaluation part of the 6283 /// attribute enable_if extension. There is nothing in standard C++ which would 6284 /// require reentering parameters. 6285 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6286 if (!Param) 6287 return; 6288 6289 S->AddDecl(Param); 6290 if (Param->getDeclName()) 6291 IdResolver.AddDecl(Param); 6292 } 6293 6294 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6295 /// parsing a top-level (non-nested) C++ class, and we are now 6296 /// parsing those parts of the given Method declaration that could 6297 /// not be parsed earlier (C++ [class.mem]p2), such as default 6298 /// arguments. This action should enter the scope of the given 6299 /// Method declaration as if we had just parsed the qualified method 6300 /// name. However, it should not bring the parameters into scope; 6301 /// that will be performed by ActOnDelayedCXXMethodParameter. 6302 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6303 } 6304 6305 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6306 /// C++ method declaration. We're (re-)introducing the given 6307 /// function parameter into scope for use in parsing later parts of 6308 /// the method declaration. For example, we could see an 6309 /// ActOnParamDefaultArgument event for this parameter. 6310 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6311 if (!ParamD) 6312 return; 6313 6314 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6315 6316 // If this parameter has an unparsed default argument, clear it out 6317 // to make way for the parsed default argument. 6318 if (Param->hasUnparsedDefaultArg()) 6319 Param->setDefaultArg(nullptr); 6320 6321 S->AddDecl(Param); 6322 if (Param->getDeclName()) 6323 IdResolver.AddDecl(Param); 6324 } 6325 6326 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6327 /// processing the delayed method declaration for Method. The method 6328 /// declaration is now considered finished. There may be a separate 6329 /// ActOnStartOfFunctionDef action later (not necessarily 6330 /// immediately!) for this method, if it was also defined inside the 6331 /// class body. 6332 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6333 if (!MethodD) 6334 return; 6335 6336 AdjustDeclIfTemplate(MethodD); 6337 6338 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6339 6340 // Now that we have our default arguments, check the constructor 6341 // again. It could produce additional diagnostics or affect whether 6342 // the class has implicitly-declared destructors, among other 6343 // things. 6344 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6345 CheckConstructor(Constructor); 6346 6347 // Check the default arguments, which we may have added. 6348 if (!Method->isInvalidDecl()) 6349 CheckCXXDefaultArguments(Method); 6350 } 6351 6352 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6353 /// the well-formedness of the constructor declarator @p D with type @p 6354 /// R. If there are any errors in the declarator, this routine will 6355 /// emit diagnostics and set the invalid bit to true. In any case, the type 6356 /// will be updated to reflect a well-formed type for the constructor and 6357 /// returned. 6358 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6359 StorageClass &SC) { 6360 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6361 6362 // C++ [class.ctor]p3: 6363 // A constructor shall not be virtual (10.3) or static (9.4). A 6364 // constructor can be invoked for a const, volatile or const 6365 // volatile object. A constructor shall not be declared const, 6366 // volatile, or const volatile (9.3.2). 6367 if (isVirtual) { 6368 if (!D.isInvalidType()) 6369 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6370 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6371 << SourceRange(D.getIdentifierLoc()); 6372 D.setInvalidType(); 6373 } 6374 if (SC == SC_Static) { 6375 if (!D.isInvalidType()) 6376 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6377 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6378 << SourceRange(D.getIdentifierLoc()); 6379 D.setInvalidType(); 6380 SC = SC_None; 6381 } 6382 6383 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6384 diagnoseIgnoredQualifiers( 6385 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 6386 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 6387 D.getDeclSpec().getRestrictSpecLoc(), 6388 D.getDeclSpec().getAtomicSpecLoc()); 6389 D.setInvalidType(); 6390 } 6391 6392 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6393 if (FTI.TypeQuals != 0) { 6394 if (FTI.TypeQuals & Qualifiers::Const) 6395 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6396 << "const" << SourceRange(D.getIdentifierLoc()); 6397 if (FTI.TypeQuals & Qualifiers::Volatile) 6398 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6399 << "volatile" << SourceRange(D.getIdentifierLoc()); 6400 if (FTI.TypeQuals & Qualifiers::Restrict) 6401 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6402 << "restrict" << SourceRange(D.getIdentifierLoc()); 6403 D.setInvalidType(); 6404 } 6405 6406 // C++0x [class.ctor]p4: 6407 // A constructor shall not be declared with a ref-qualifier. 6408 if (FTI.hasRefQualifier()) { 6409 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6410 << FTI.RefQualifierIsLValueRef 6411 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6412 D.setInvalidType(); 6413 } 6414 6415 // Rebuild the function type "R" without any type qualifiers (in 6416 // case any of the errors above fired) and with "void" as the 6417 // return type, since constructors don't have return types. 6418 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6419 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6420 return R; 6421 6422 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6423 EPI.TypeQuals = 0; 6424 EPI.RefQualifier = RQ_None; 6425 6426 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6427 } 6428 6429 /// CheckConstructor - Checks a fully-formed constructor for 6430 /// well-formedness, issuing any diagnostics required. Returns true if 6431 /// the constructor declarator is invalid. 6432 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6433 CXXRecordDecl *ClassDecl 6434 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6435 if (!ClassDecl) 6436 return Constructor->setInvalidDecl(); 6437 6438 // C++ [class.copy]p3: 6439 // A declaration of a constructor for a class X is ill-formed if 6440 // its first parameter is of type (optionally cv-qualified) X and 6441 // either there are no other parameters or else all other 6442 // parameters have default arguments. 6443 if (!Constructor->isInvalidDecl() && 6444 ((Constructor->getNumParams() == 1) || 6445 (Constructor->getNumParams() > 1 && 6446 Constructor->getParamDecl(1)->hasDefaultArg())) && 6447 Constructor->getTemplateSpecializationKind() 6448 != TSK_ImplicitInstantiation) { 6449 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6450 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6451 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6452 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6453 const char *ConstRef 6454 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6455 : " const &"; 6456 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6457 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6458 6459 // FIXME: Rather that making the constructor invalid, we should endeavor 6460 // to fix the type. 6461 Constructor->setInvalidDecl(); 6462 } 6463 } 6464 } 6465 6466 /// CheckDestructor - Checks a fully-formed destructor definition for 6467 /// well-formedness, issuing any diagnostics required. Returns true 6468 /// on error. 6469 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6470 CXXRecordDecl *RD = Destructor->getParent(); 6471 6472 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6473 SourceLocation Loc; 6474 6475 if (!Destructor->isImplicit()) 6476 Loc = Destructor->getLocation(); 6477 else 6478 Loc = RD->getLocation(); 6479 6480 // If we have a virtual destructor, look up the deallocation function 6481 FunctionDecl *OperatorDelete = nullptr; 6482 DeclarationName Name = 6483 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6484 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6485 return true; 6486 // If there's no class-specific operator delete, look up the global 6487 // non-array delete. 6488 if (!OperatorDelete) 6489 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6490 6491 MarkFunctionReferenced(Loc, OperatorDelete); 6492 6493 Destructor->setOperatorDelete(OperatorDelete); 6494 } 6495 6496 return false; 6497 } 6498 6499 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6500 /// the well-formednes of the destructor declarator @p D with type @p 6501 /// R. If there are any errors in the declarator, this routine will 6502 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6503 /// will be updated to reflect a well-formed type for the destructor and 6504 /// returned. 6505 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6506 StorageClass& SC) { 6507 // C++ [class.dtor]p1: 6508 // [...] A typedef-name that names a class is a class-name 6509 // (7.1.3); however, a typedef-name that names a class shall not 6510 // be used as the identifier in the declarator for a destructor 6511 // declaration. 6512 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6513 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6514 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6515 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6516 else if (const TemplateSpecializationType *TST = 6517 DeclaratorType->getAs<TemplateSpecializationType>()) 6518 if (TST->isTypeAlias()) 6519 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6520 << DeclaratorType << 1; 6521 6522 // C++ [class.dtor]p2: 6523 // A destructor is used to destroy objects of its class type. A 6524 // destructor takes no parameters, and no return type can be 6525 // specified for it (not even void). The address of a destructor 6526 // shall not be taken. A destructor shall not be static. A 6527 // destructor can be invoked for a const, volatile or const 6528 // volatile object. A destructor shall not be declared const, 6529 // volatile or const volatile (9.3.2). 6530 if (SC == SC_Static) { 6531 if (!D.isInvalidType()) 6532 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6533 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6534 << SourceRange(D.getIdentifierLoc()) 6535 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6536 6537 SC = SC_None; 6538 } 6539 if (!D.isInvalidType()) { 6540 // Destructors don't have return types, but the parser will 6541 // happily parse something like: 6542 // 6543 // class X { 6544 // float ~X(); 6545 // }; 6546 // 6547 // The return type will be eliminated later. 6548 if (D.getDeclSpec().hasTypeSpecifier()) 6549 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6550 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6551 << SourceRange(D.getIdentifierLoc()); 6552 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 6553 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 6554 SourceLocation(), 6555 D.getDeclSpec().getConstSpecLoc(), 6556 D.getDeclSpec().getVolatileSpecLoc(), 6557 D.getDeclSpec().getRestrictSpecLoc(), 6558 D.getDeclSpec().getAtomicSpecLoc()); 6559 D.setInvalidType(); 6560 } 6561 } 6562 6563 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6564 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6565 if (FTI.TypeQuals & Qualifiers::Const) 6566 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6567 << "const" << SourceRange(D.getIdentifierLoc()); 6568 if (FTI.TypeQuals & Qualifiers::Volatile) 6569 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6570 << "volatile" << SourceRange(D.getIdentifierLoc()); 6571 if (FTI.TypeQuals & Qualifiers::Restrict) 6572 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6573 << "restrict" << SourceRange(D.getIdentifierLoc()); 6574 D.setInvalidType(); 6575 } 6576 6577 // C++0x [class.dtor]p2: 6578 // A destructor shall not be declared with a ref-qualifier. 6579 if (FTI.hasRefQualifier()) { 6580 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6581 << FTI.RefQualifierIsLValueRef 6582 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6583 D.setInvalidType(); 6584 } 6585 6586 // Make sure we don't have any parameters. 6587 if (FTIHasNonVoidParameters(FTI)) { 6588 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6589 6590 // Delete the parameters. 6591 FTI.freeParams(); 6592 D.setInvalidType(); 6593 } 6594 6595 // Make sure the destructor isn't variadic. 6596 if (FTI.isVariadic) { 6597 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6598 D.setInvalidType(); 6599 } 6600 6601 // Rebuild the function type "R" without any type qualifiers or 6602 // parameters (in case any of the errors above fired) and with 6603 // "void" as the return type, since destructors don't have return 6604 // types. 6605 if (!D.isInvalidType()) 6606 return R; 6607 6608 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6609 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6610 EPI.Variadic = false; 6611 EPI.TypeQuals = 0; 6612 EPI.RefQualifier = RQ_None; 6613 return Context.getFunctionType(Context.VoidTy, None, EPI); 6614 } 6615 6616 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6617 /// well-formednes of the conversion function declarator @p D with 6618 /// type @p R. If there are any errors in the declarator, this routine 6619 /// will emit diagnostics and return true. Otherwise, it will return 6620 /// false. Either way, the type @p R will be updated to reflect a 6621 /// well-formed type for the conversion operator. 6622 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6623 StorageClass& SC) { 6624 // C++ [class.conv.fct]p1: 6625 // Neither parameter types nor return type can be specified. The 6626 // type of a conversion function (8.3.5) is "function taking no 6627 // parameter returning conversion-type-id." 6628 if (SC == SC_Static) { 6629 if (!D.isInvalidType()) 6630 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6631 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6632 << D.getName().getSourceRange(); 6633 D.setInvalidType(); 6634 SC = SC_None; 6635 } 6636 6637 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6638 6639 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6640 // Conversion functions don't have return types, but the parser will 6641 // happily parse something like: 6642 // 6643 // class X { 6644 // float operator bool(); 6645 // }; 6646 // 6647 // The return type will be changed later anyway. 6648 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6649 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6650 << SourceRange(D.getIdentifierLoc()); 6651 D.setInvalidType(); 6652 } 6653 6654 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6655 6656 // Make sure we don't have any parameters. 6657 if (Proto->getNumParams() > 0) { 6658 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6659 6660 // Delete the parameters. 6661 D.getFunctionTypeInfo().freeParams(); 6662 D.setInvalidType(); 6663 } else if (Proto->isVariadic()) { 6664 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6665 D.setInvalidType(); 6666 } 6667 6668 // Diagnose "&operator bool()" and other such nonsense. This 6669 // is actually a gcc extension which we don't support. 6670 if (Proto->getReturnType() != ConvType) { 6671 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6672 << Proto->getReturnType(); 6673 D.setInvalidType(); 6674 ConvType = Proto->getReturnType(); 6675 } 6676 6677 // C++ [class.conv.fct]p4: 6678 // The conversion-type-id shall not represent a function type nor 6679 // an array type. 6680 if (ConvType->isArrayType()) { 6681 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6682 ConvType = Context.getPointerType(ConvType); 6683 D.setInvalidType(); 6684 } else if (ConvType->isFunctionType()) { 6685 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6686 ConvType = Context.getPointerType(ConvType); 6687 D.setInvalidType(); 6688 } 6689 6690 // Rebuild the function type "R" without any parameters (in case any 6691 // of the errors above fired) and with the conversion type as the 6692 // return type. 6693 if (D.isInvalidType()) 6694 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6695 6696 // C++0x explicit conversion operators. 6697 if (D.getDeclSpec().isExplicitSpecified()) 6698 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6699 getLangOpts().CPlusPlus11 ? 6700 diag::warn_cxx98_compat_explicit_conversion_functions : 6701 diag::ext_explicit_conversion_functions) 6702 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6703 } 6704 6705 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6706 /// the declaration of the given C++ conversion function. This routine 6707 /// is responsible for recording the conversion function in the C++ 6708 /// class, if possible. 6709 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6710 assert(Conversion && "Expected to receive a conversion function declaration"); 6711 6712 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6713 6714 // Make sure we aren't redeclaring the conversion function. 6715 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6716 6717 // C++ [class.conv.fct]p1: 6718 // [...] A conversion function is never used to convert a 6719 // (possibly cv-qualified) object to the (possibly cv-qualified) 6720 // same object type (or a reference to it), to a (possibly 6721 // cv-qualified) base class of that type (or a reference to it), 6722 // or to (possibly cv-qualified) void. 6723 // FIXME: Suppress this warning if the conversion function ends up being a 6724 // virtual function that overrides a virtual function in a base class. 6725 QualType ClassType 6726 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6727 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6728 ConvType = ConvTypeRef->getPointeeType(); 6729 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6730 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6731 /* Suppress diagnostics for instantiations. */; 6732 else if (ConvType->isRecordType()) { 6733 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6734 if (ConvType == ClassType) 6735 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6736 << ClassType; 6737 else if (IsDerivedFrom(ClassType, ConvType)) 6738 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6739 << ClassType << ConvType; 6740 } else if (ConvType->isVoidType()) { 6741 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6742 << ClassType << ConvType; 6743 } 6744 6745 if (FunctionTemplateDecl *ConversionTemplate 6746 = Conversion->getDescribedFunctionTemplate()) 6747 return ConversionTemplate; 6748 6749 return Conversion; 6750 } 6751 6752 //===----------------------------------------------------------------------===// 6753 // Namespace Handling 6754 //===----------------------------------------------------------------------===// 6755 6756 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6757 /// reopened. 6758 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6759 SourceLocation Loc, 6760 IdentifierInfo *II, bool *IsInline, 6761 NamespaceDecl *PrevNS) { 6762 assert(*IsInline != PrevNS->isInline()); 6763 6764 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6765 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6766 // inline namespaces, with the intention of bringing names into namespace std. 6767 // 6768 // We support this just well enough to get that case working; this is not 6769 // sufficient to support reopening namespaces as inline in general. 6770 if (*IsInline && II && II->getName().startswith("__atomic") && 6771 S.getSourceManager().isInSystemHeader(Loc)) { 6772 // Mark all prior declarations of the namespace as inline. 6773 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6774 NS = NS->getPreviousDecl()) 6775 NS->setInline(*IsInline); 6776 // Patch up the lookup table for the containing namespace. This isn't really 6777 // correct, but it's good enough for this particular case. 6778 for (auto *I : PrevNS->decls()) 6779 if (auto *ND = dyn_cast<NamedDecl>(I)) 6780 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6781 return; 6782 } 6783 6784 if (PrevNS->isInline()) 6785 // The user probably just forgot the 'inline', so suggest that it 6786 // be added back. 6787 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6788 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6789 else 6790 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 6791 6792 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6793 *IsInline = PrevNS->isInline(); 6794 } 6795 6796 /// ActOnStartNamespaceDef - This is called at the start of a namespace 6797 /// definition. 6798 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6799 SourceLocation InlineLoc, 6800 SourceLocation NamespaceLoc, 6801 SourceLocation IdentLoc, 6802 IdentifierInfo *II, 6803 SourceLocation LBrace, 6804 AttributeList *AttrList) { 6805 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6806 // For anonymous namespace, take the location of the left brace. 6807 SourceLocation Loc = II ? IdentLoc : LBrace; 6808 bool IsInline = InlineLoc.isValid(); 6809 bool IsInvalid = false; 6810 bool IsStd = false; 6811 bool AddToKnown = false; 6812 Scope *DeclRegionScope = NamespcScope->getParent(); 6813 6814 NamespaceDecl *PrevNS = nullptr; 6815 if (II) { 6816 // C++ [namespace.def]p2: 6817 // The identifier in an original-namespace-definition shall not 6818 // have been previously defined in the declarative region in 6819 // which the original-namespace-definition appears. The 6820 // identifier in an original-namespace-definition is the name of 6821 // the namespace. Subsequently in that declarative region, it is 6822 // treated as an original-namespace-name. 6823 // 6824 // Since namespace names are unique in their scope, and we don't 6825 // look through using directives, just look for any ordinary names. 6826 6827 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6828 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6829 Decl::IDNS_Namespace; 6830 NamedDecl *PrevDecl = nullptr; 6831 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6832 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6833 ++I) { 6834 if ((*I)->getIdentifierNamespace() & IDNS) { 6835 PrevDecl = *I; 6836 break; 6837 } 6838 } 6839 6840 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6841 6842 if (PrevNS) { 6843 // This is an extended namespace definition. 6844 if (IsInline != PrevNS->isInline()) 6845 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6846 &IsInline, PrevNS); 6847 } else if (PrevDecl) { 6848 // This is an invalid name redefinition. 6849 Diag(Loc, diag::err_redefinition_different_kind) 6850 << II; 6851 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6852 IsInvalid = true; 6853 // Continue on to push Namespc as current DeclContext and return it. 6854 } else if (II->isStr("std") && 6855 CurContext->getRedeclContext()->isTranslationUnit()) { 6856 // This is the first "real" definition of the namespace "std", so update 6857 // our cache of the "std" namespace to point at this definition. 6858 PrevNS = getStdNamespace(); 6859 IsStd = true; 6860 AddToKnown = !IsInline; 6861 } else { 6862 // We've seen this namespace for the first time. 6863 AddToKnown = !IsInline; 6864 } 6865 } else { 6866 // Anonymous namespaces. 6867 6868 // Determine whether the parent already has an anonymous namespace. 6869 DeclContext *Parent = CurContext->getRedeclContext(); 6870 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6871 PrevNS = TU->getAnonymousNamespace(); 6872 } else { 6873 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6874 PrevNS = ND->getAnonymousNamespace(); 6875 } 6876 6877 if (PrevNS && IsInline != PrevNS->isInline()) 6878 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6879 &IsInline, PrevNS); 6880 } 6881 6882 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6883 StartLoc, Loc, II, PrevNS); 6884 if (IsInvalid) 6885 Namespc->setInvalidDecl(); 6886 6887 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6888 6889 // FIXME: Should we be merging attributes? 6890 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6891 PushNamespaceVisibilityAttr(Attr, Loc); 6892 6893 if (IsStd) 6894 StdNamespace = Namespc; 6895 if (AddToKnown) 6896 KnownNamespaces[Namespc] = false; 6897 6898 if (II) { 6899 PushOnScopeChains(Namespc, DeclRegionScope); 6900 } else { 6901 // Link the anonymous namespace into its parent. 6902 DeclContext *Parent = CurContext->getRedeclContext(); 6903 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6904 TU->setAnonymousNamespace(Namespc); 6905 } else { 6906 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6907 } 6908 6909 CurContext->addDecl(Namespc); 6910 6911 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6912 // behaves as if it were replaced by 6913 // namespace unique { /* empty body */ } 6914 // using namespace unique; 6915 // namespace unique { namespace-body } 6916 // where all occurrences of 'unique' in a translation unit are 6917 // replaced by the same identifier and this identifier differs 6918 // from all other identifiers in the entire program. 6919 6920 // We just create the namespace with an empty name and then add an 6921 // implicit using declaration, just like the standard suggests. 6922 // 6923 // CodeGen enforces the "universally unique" aspect by giving all 6924 // declarations semantically contained within an anonymous 6925 // namespace internal linkage. 6926 6927 if (!PrevNS) { 6928 UsingDirectiveDecl* UD 6929 = UsingDirectiveDecl::Create(Context, Parent, 6930 /* 'using' */ LBrace, 6931 /* 'namespace' */ SourceLocation(), 6932 /* qualifier */ NestedNameSpecifierLoc(), 6933 /* identifier */ SourceLocation(), 6934 Namespc, 6935 /* Ancestor */ Parent); 6936 UD->setImplicit(); 6937 Parent->addDecl(UD); 6938 } 6939 } 6940 6941 ActOnDocumentableDecl(Namespc); 6942 6943 // Although we could have an invalid decl (i.e. the namespace name is a 6944 // redefinition), push it as current DeclContext and try to continue parsing. 6945 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6946 // for the namespace has the declarations that showed up in that particular 6947 // namespace definition. 6948 PushDeclContext(NamespcScope, Namespc); 6949 return Namespc; 6950 } 6951 6952 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6953 /// is a namespace alias, returns the namespace it points to. 6954 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6955 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6956 return AD->getNamespace(); 6957 return dyn_cast_or_null<NamespaceDecl>(D); 6958 } 6959 6960 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 6961 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6962 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6963 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6964 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6965 Namespc->setRBraceLoc(RBrace); 6966 PopDeclContext(); 6967 if (Namespc->hasAttr<VisibilityAttr>()) 6968 PopPragmaVisibility(true, RBrace); 6969 } 6970 6971 CXXRecordDecl *Sema::getStdBadAlloc() const { 6972 return cast_or_null<CXXRecordDecl>( 6973 StdBadAlloc.get(Context.getExternalSource())); 6974 } 6975 6976 NamespaceDecl *Sema::getStdNamespace() const { 6977 return cast_or_null<NamespaceDecl>( 6978 StdNamespace.get(Context.getExternalSource())); 6979 } 6980 6981 /// \brief Retrieve the special "std" namespace, which may require us to 6982 /// implicitly define the namespace. 6983 NamespaceDecl *Sema::getOrCreateStdNamespace() { 6984 if (!StdNamespace) { 6985 // The "std" namespace has not yet been defined, so build one implicitly. 6986 StdNamespace = NamespaceDecl::Create(Context, 6987 Context.getTranslationUnitDecl(), 6988 /*Inline=*/false, 6989 SourceLocation(), SourceLocation(), 6990 &PP.getIdentifierTable().get("std"), 6991 /*PrevDecl=*/nullptr); 6992 getStdNamespace()->setImplicit(true); 6993 } 6994 6995 return getStdNamespace(); 6996 } 6997 6998 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6999 assert(getLangOpts().CPlusPlus && 7000 "Looking for std::initializer_list outside of C++."); 7001 7002 // We're looking for implicit instantiations of 7003 // template <typename E> class std::initializer_list. 7004 7005 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 7006 return false; 7007 7008 ClassTemplateDecl *Template = nullptr; 7009 const TemplateArgument *Arguments = nullptr; 7010 7011 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7012 7013 ClassTemplateSpecializationDecl *Specialization = 7014 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 7015 if (!Specialization) 7016 return false; 7017 7018 Template = Specialization->getSpecializedTemplate(); 7019 Arguments = Specialization->getTemplateArgs().data(); 7020 } else if (const TemplateSpecializationType *TST = 7021 Ty->getAs<TemplateSpecializationType>()) { 7022 Template = dyn_cast_or_null<ClassTemplateDecl>( 7023 TST->getTemplateName().getAsTemplateDecl()); 7024 Arguments = TST->getArgs(); 7025 } 7026 if (!Template) 7027 return false; 7028 7029 if (!StdInitializerList) { 7030 // Haven't recognized std::initializer_list yet, maybe this is it. 7031 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 7032 if (TemplateClass->getIdentifier() != 7033 &PP.getIdentifierTable().get("initializer_list") || 7034 !getStdNamespace()->InEnclosingNamespaceSetOf( 7035 TemplateClass->getDeclContext())) 7036 return false; 7037 // This is a template called std::initializer_list, but is it the right 7038 // template? 7039 TemplateParameterList *Params = Template->getTemplateParameters(); 7040 if (Params->getMinRequiredArguments() != 1) 7041 return false; 7042 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 7043 return false; 7044 7045 // It's the right template. 7046 StdInitializerList = Template; 7047 } 7048 7049 if (Template != StdInitializerList) 7050 return false; 7051 7052 // This is an instance of std::initializer_list. Find the argument type. 7053 if (Element) 7054 *Element = Arguments[0].getAsType(); 7055 return true; 7056 } 7057 7058 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 7059 NamespaceDecl *Std = S.getStdNamespace(); 7060 if (!Std) { 7061 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7062 return nullptr; 7063 } 7064 7065 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 7066 Loc, Sema::LookupOrdinaryName); 7067 if (!S.LookupQualifiedName(Result, Std)) { 7068 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 7069 return nullptr; 7070 } 7071 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 7072 if (!Template) { 7073 Result.suppressDiagnostics(); 7074 // We found something weird. Complain about the first thing we found. 7075 NamedDecl *Found = *Result.begin(); 7076 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 7077 return nullptr; 7078 } 7079 7080 // We found some template called std::initializer_list. Now verify that it's 7081 // correct. 7082 TemplateParameterList *Params = Template->getTemplateParameters(); 7083 if (Params->getMinRequiredArguments() != 1 || 7084 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 7085 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 7086 return nullptr; 7087 } 7088 7089 return Template; 7090 } 7091 7092 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 7093 if (!StdInitializerList) { 7094 StdInitializerList = LookupStdInitializerList(*this, Loc); 7095 if (!StdInitializerList) 7096 return QualType(); 7097 } 7098 7099 TemplateArgumentListInfo Args(Loc, Loc); 7100 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 7101 Context.getTrivialTypeSourceInfo(Element, 7102 Loc))); 7103 return Context.getCanonicalType( 7104 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 7105 } 7106 7107 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 7108 // C++ [dcl.init.list]p2: 7109 // A constructor is an initializer-list constructor if its first parameter 7110 // is of type std::initializer_list<E> or reference to possibly cv-qualified 7111 // std::initializer_list<E> for some type E, and either there are no other 7112 // parameters or else all other parameters have default arguments. 7113 if (Ctor->getNumParams() < 1 || 7114 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 7115 return false; 7116 7117 QualType ArgType = Ctor->getParamDecl(0)->getType(); 7118 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 7119 ArgType = RT->getPointeeType().getUnqualifiedType(); 7120 7121 return isStdInitializerList(ArgType, nullptr); 7122 } 7123 7124 /// \brief Determine whether a using statement is in a context where it will be 7125 /// apply in all contexts. 7126 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 7127 switch (CurContext->getDeclKind()) { 7128 case Decl::TranslationUnit: 7129 return true; 7130 case Decl::LinkageSpec: 7131 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 7132 default: 7133 return false; 7134 } 7135 } 7136 7137 namespace { 7138 7139 // Callback to only accept typo corrections that are namespaces. 7140 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 7141 public: 7142 bool ValidateCandidate(const TypoCorrection &candidate) override { 7143 if (NamedDecl *ND = candidate.getCorrectionDecl()) 7144 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 7145 return false; 7146 } 7147 }; 7148 7149 } 7150 7151 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 7152 CXXScopeSpec &SS, 7153 SourceLocation IdentLoc, 7154 IdentifierInfo *Ident) { 7155 NamespaceValidatorCCC Validator; 7156 R.clear(); 7157 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 7158 R.getLookupKind(), Sc, &SS, 7159 Validator, 7160 Sema::CTK_ErrorRecovery)) { 7161 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 7162 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 7163 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 7164 Ident->getName().equals(CorrectedStr); 7165 S.diagnoseTypo(Corrected, 7166 S.PDiag(diag::err_using_directive_member_suggest) 7167 << Ident << DC << DroppedSpecifier << SS.getRange(), 7168 S.PDiag(diag::note_namespace_defined_here)); 7169 } else { 7170 S.diagnoseTypo(Corrected, 7171 S.PDiag(diag::err_using_directive_suggest) << Ident, 7172 S.PDiag(diag::note_namespace_defined_here)); 7173 } 7174 R.addDecl(Corrected.getCorrectionDecl()); 7175 return true; 7176 } 7177 return false; 7178 } 7179 7180 Decl *Sema::ActOnUsingDirective(Scope *S, 7181 SourceLocation UsingLoc, 7182 SourceLocation NamespcLoc, 7183 CXXScopeSpec &SS, 7184 SourceLocation IdentLoc, 7185 IdentifierInfo *NamespcName, 7186 AttributeList *AttrList) { 7187 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7188 assert(NamespcName && "Invalid NamespcName."); 7189 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 7190 7191 // This can only happen along a recovery path. 7192 while (S->getFlags() & Scope::TemplateParamScope) 7193 S = S->getParent(); 7194 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7195 7196 UsingDirectiveDecl *UDir = nullptr; 7197 NestedNameSpecifier *Qualifier = nullptr; 7198 if (SS.isSet()) 7199 Qualifier = SS.getScopeRep(); 7200 7201 // Lookup namespace name. 7202 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 7203 LookupParsedName(R, S, &SS); 7204 if (R.isAmbiguous()) 7205 return nullptr; 7206 7207 if (R.empty()) { 7208 R.clear(); 7209 // Allow "using namespace std;" or "using namespace ::std;" even if 7210 // "std" hasn't been defined yet, for GCC compatibility. 7211 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 7212 NamespcName->isStr("std")) { 7213 Diag(IdentLoc, diag::ext_using_undefined_std); 7214 R.addDecl(getOrCreateStdNamespace()); 7215 R.resolveKind(); 7216 } 7217 // Otherwise, attempt typo correction. 7218 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 7219 } 7220 7221 if (!R.empty()) { 7222 NamedDecl *Named = R.getFoundDecl(); 7223 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 7224 && "expected namespace decl"); 7225 // C++ [namespace.udir]p1: 7226 // A using-directive specifies that the names in the nominated 7227 // namespace can be used in the scope in which the 7228 // using-directive appears after the using-directive. During 7229 // unqualified name lookup (3.4.1), the names appear as if they 7230 // were declared in the nearest enclosing namespace which 7231 // contains both the using-directive and the nominated 7232 // namespace. [Note: in this context, "contains" means "contains 7233 // directly or indirectly". ] 7234 7235 // Find enclosing context containing both using-directive and 7236 // nominated namespace. 7237 NamespaceDecl *NS = getNamespaceDecl(Named); 7238 DeclContext *CommonAncestor = cast<DeclContext>(NS); 7239 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 7240 CommonAncestor = CommonAncestor->getParent(); 7241 7242 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 7243 SS.getWithLocInContext(Context), 7244 IdentLoc, Named, CommonAncestor); 7245 7246 if (IsUsingDirectiveInToplevelContext(CurContext) && 7247 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 7248 Diag(IdentLoc, diag::warn_using_directive_in_header); 7249 } 7250 7251 PushUsingDirective(S, UDir); 7252 } else { 7253 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7254 } 7255 7256 if (UDir) 7257 ProcessDeclAttributeList(S, UDir, AttrList); 7258 7259 return UDir; 7260 } 7261 7262 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7263 // If the scope has an associated entity and the using directive is at 7264 // namespace or translation unit scope, add the UsingDirectiveDecl into 7265 // its lookup structure so qualified name lookup can find it. 7266 DeclContext *Ctx = S->getEntity(); 7267 if (Ctx && !Ctx->isFunctionOrMethod()) 7268 Ctx->addDecl(UDir); 7269 else 7270 // Otherwise, it is at block scope. The using-directives will affect lookup 7271 // only to the end of the scope. 7272 S->PushUsingDirective(UDir); 7273 } 7274 7275 7276 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7277 AccessSpecifier AS, 7278 bool HasUsingKeyword, 7279 SourceLocation UsingLoc, 7280 CXXScopeSpec &SS, 7281 UnqualifiedId &Name, 7282 AttributeList *AttrList, 7283 bool HasTypenameKeyword, 7284 SourceLocation TypenameLoc) { 7285 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7286 7287 switch (Name.getKind()) { 7288 case UnqualifiedId::IK_ImplicitSelfParam: 7289 case UnqualifiedId::IK_Identifier: 7290 case UnqualifiedId::IK_OperatorFunctionId: 7291 case UnqualifiedId::IK_LiteralOperatorId: 7292 case UnqualifiedId::IK_ConversionFunctionId: 7293 break; 7294 7295 case UnqualifiedId::IK_ConstructorName: 7296 case UnqualifiedId::IK_ConstructorTemplateId: 7297 // C++11 inheriting constructors. 7298 Diag(Name.getLocStart(), 7299 getLangOpts().CPlusPlus11 ? 7300 diag::warn_cxx98_compat_using_decl_constructor : 7301 diag::err_using_decl_constructor) 7302 << SS.getRange(); 7303 7304 if (getLangOpts().CPlusPlus11) break; 7305 7306 return nullptr; 7307 7308 case UnqualifiedId::IK_DestructorName: 7309 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7310 << SS.getRange(); 7311 return nullptr; 7312 7313 case UnqualifiedId::IK_TemplateId: 7314 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7315 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7316 return nullptr; 7317 } 7318 7319 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7320 DeclarationName TargetName = TargetNameInfo.getName(); 7321 if (!TargetName) 7322 return nullptr; 7323 7324 // Warn about access declarations. 7325 if (!HasUsingKeyword) { 7326 Diag(Name.getLocStart(), 7327 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7328 : diag::warn_access_decl_deprecated) 7329 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7330 } 7331 7332 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7333 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7334 return nullptr; 7335 7336 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7337 TargetNameInfo, AttrList, 7338 /* IsInstantiation */ false, 7339 HasTypenameKeyword, TypenameLoc); 7340 if (UD) 7341 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7342 7343 return UD; 7344 } 7345 7346 /// \brief Determine whether a using declaration considers the given 7347 /// declarations as "equivalent", e.g., if they are redeclarations of 7348 /// the same entity or are both typedefs of the same type. 7349 static bool 7350 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7351 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7352 return true; 7353 7354 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7355 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7356 return Context.hasSameType(TD1->getUnderlyingType(), 7357 TD2->getUnderlyingType()); 7358 7359 return false; 7360 } 7361 7362 7363 /// Determines whether to create a using shadow decl for a particular 7364 /// decl, given the set of decls existing prior to this using lookup. 7365 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7366 const LookupResult &Previous, 7367 UsingShadowDecl *&PrevShadow) { 7368 // Diagnose finding a decl which is not from a base class of the 7369 // current class. We do this now because there are cases where this 7370 // function will silently decide not to build a shadow decl, which 7371 // will pre-empt further diagnostics. 7372 // 7373 // We don't need to do this in C++0x because we do the check once on 7374 // the qualifier. 7375 // 7376 // FIXME: diagnose the following if we care enough: 7377 // struct A { int foo; }; 7378 // struct B : A { using A::foo; }; 7379 // template <class T> struct C : A {}; 7380 // template <class T> struct D : C<T> { using B::foo; } // <--- 7381 // This is invalid (during instantiation) in C++03 because B::foo 7382 // resolves to the using decl in B, which is not a base class of D<T>. 7383 // We can't diagnose it immediately because C<T> is an unknown 7384 // specialization. The UsingShadowDecl in D<T> then points directly 7385 // to A::foo, which will look well-formed when we instantiate. 7386 // The right solution is to not collapse the shadow-decl chain. 7387 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7388 DeclContext *OrigDC = Orig->getDeclContext(); 7389 7390 // Handle enums and anonymous structs. 7391 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7392 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7393 while (OrigRec->isAnonymousStructOrUnion()) 7394 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7395 7396 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7397 if (OrigDC == CurContext) { 7398 Diag(Using->getLocation(), 7399 diag::err_using_decl_nested_name_specifier_is_current_class) 7400 << Using->getQualifierLoc().getSourceRange(); 7401 Diag(Orig->getLocation(), diag::note_using_decl_target); 7402 return true; 7403 } 7404 7405 Diag(Using->getQualifierLoc().getBeginLoc(), 7406 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7407 << Using->getQualifier() 7408 << cast<CXXRecordDecl>(CurContext) 7409 << Using->getQualifierLoc().getSourceRange(); 7410 Diag(Orig->getLocation(), diag::note_using_decl_target); 7411 return true; 7412 } 7413 } 7414 7415 if (Previous.empty()) return false; 7416 7417 NamedDecl *Target = Orig; 7418 if (isa<UsingShadowDecl>(Target)) 7419 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7420 7421 // If the target happens to be one of the previous declarations, we 7422 // don't have a conflict. 7423 // 7424 // FIXME: but we might be increasing its access, in which case we 7425 // should redeclare it. 7426 NamedDecl *NonTag = nullptr, *Tag = nullptr; 7427 bool FoundEquivalentDecl = false; 7428 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7429 I != E; ++I) { 7430 NamedDecl *D = (*I)->getUnderlyingDecl(); 7431 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7432 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7433 PrevShadow = Shadow; 7434 FoundEquivalentDecl = true; 7435 } 7436 7437 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7438 } 7439 7440 if (FoundEquivalentDecl) 7441 return false; 7442 7443 if (FunctionDecl *FD = Target->getAsFunction()) { 7444 NamedDecl *OldDecl = nullptr; 7445 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 7446 /*IsForUsingDecl*/ true)) { 7447 case Ovl_Overload: 7448 return false; 7449 7450 case Ovl_NonFunction: 7451 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7452 break; 7453 7454 // We found a decl with the exact signature. 7455 case Ovl_Match: 7456 // If we're in a record, we want to hide the target, so we 7457 // return true (without a diagnostic) to tell the caller not to 7458 // build a shadow decl. 7459 if (CurContext->isRecord()) 7460 return true; 7461 7462 // If we're not in a record, this is an error. 7463 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7464 break; 7465 } 7466 7467 Diag(Target->getLocation(), diag::note_using_decl_target); 7468 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7469 return true; 7470 } 7471 7472 // Target is not a function. 7473 7474 if (isa<TagDecl>(Target)) { 7475 // No conflict between a tag and a non-tag. 7476 if (!Tag) return false; 7477 7478 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7479 Diag(Target->getLocation(), diag::note_using_decl_target); 7480 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7481 return true; 7482 } 7483 7484 // No conflict between a tag and a non-tag. 7485 if (!NonTag) return false; 7486 7487 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7488 Diag(Target->getLocation(), diag::note_using_decl_target); 7489 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7490 return true; 7491 } 7492 7493 /// Builds a shadow declaration corresponding to a 'using' declaration. 7494 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7495 UsingDecl *UD, 7496 NamedDecl *Orig, 7497 UsingShadowDecl *PrevDecl) { 7498 7499 // If we resolved to another shadow declaration, just coalesce them. 7500 NamedDecl *Target = Orig; 7501 if (isa<UsingShadowDecl>(Target)) { 7502 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7503 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7504 } 7505 7506 UsingShadowDecl *Shadow 7507 = UsingShadowDecl::Create(Context, CurContext, 7508 UD->getLocation(), UD, Target); 7509 UD->addShadowDecl(Shadow); 7510 7511 Shadow->setAccess(UD->getAccess()); 7512 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7513 Shadow->setInvalidDecl(); 7514 7515 Shadow->setPreviousDecl(PrevDecl); 7516 7517 if (S) 7518 PushOnScopeChains(Shadow, S); 7519 else 7520 CurContext->addDecl(Shadow); 7521 7522 7523 return Shadow; 7524 } 7525 7526 /// Hides a using shadow declaration. This is required by the current 7527 /// using-decl implementation when a resolvable using declaration in a 7528 /// class is followed by a declaration which would hide or override 7529 /// one or more of the using decl's targets; for example: 7530 /// 7531 /// struct Base { void foo(int); }; 7532 /// struct Derived : Base { 7533 /// using Base::foo; 7534 /// void foo(int); 7535 /// }; 7536 /// 7537 /// The governing language is C++03 [namespace.udecl]p12: 7538 /// 7539 /// When a using-declaration brings names from a base class into a 7540 /// derived class scope, member functions in the derived class 7541 /// override and/or hide member functions with the same name and 7542 /// parameter types in a base class (rather than conflicting). 7543 /// 7544 /// There are two ways to implement this: 7545 /// (1) optimistically create shadow decls when they're not hidden 7546 /// by existing declarations, or 7547 /// (2) don't create any shadow decls (or at least don't make them 7548 /// visible) until we've fully parsed/instantiated the class. 7549 /// The problem with (1) is that we might have to retroactively remove 7550 /// a shadow decl, which requires several O(n) operations because the 7551 /// decl structures are (very reasonably) not designed for removal. 7552 /// (2) avoids this but is very fiddly and phase-dependent. 7553 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7554 if (Shadow->getDeclName().getNameKind() == 7555 DeclarationName::CXXConversionFunctionName) 7556 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7557 7558 // Remove it from the DeclContext... 7559 Shadow->getDeclContext()->removeDecl(Shadow); 7560 7561 // ...and the scope, if applicable... 7562 if (S) { 7563 S->RemoveDecl(Shadow); 7564 IdResolver.RemoveDecl(Shadow); 7565 } 7566 7567 // ...and the using decl. 7568 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7569 7570 // TODO: complain somehow if Shadow was used. It shouldn't 7571 // be possible for this to happen, because...? 7572 } 7573 7574 /// Find the base specifier for a base class with the given type. 7575 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 7576 QualType DesiredBase, 7577 bool &AnyDependentBases) { 7578 // Check whether the named type is a direct base class. 7579 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified(); 7580 for (auto &Base : Derived->bases()) { 7581 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 7582 if (CanonicalDesiredBase == BaseType) 7583 return &Base; 7584 if (BaseType->isDependentType()) 7585 AnyDependentBases = true; 7586 } 7587 return nullptr; 7588 } 7589 7590 namespace { 7591 class UsingValidatorCCC : public CorrectionCandidateCallback { 7592 public: 7593 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7594 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 7595 : HasTypenameKeyword(HasTypenameKeyword), 7596 IsInstantiation(IsInstantiation), OldNNS(NNS), 7597 RequireMemberOf(RequireMemberOf) {} 7598 7599 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7600 NamedDecl *ND = Candidate.getCorrectionDecl(); 7601 7602 // Keywords are not valid here. 7603 if (!ND || isa<NamespaceDecl>(ND)) 7604 return false; 7605 7606 // Completely unqualified names are invalid for a 'using' declaration. 7607 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7608 return false; 7609 7610 if (RequireMemberOf) { 7611 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 7612 if (FoundRecord && FoundRecord->isInjectedClassName()) { 7613 // No-one ever wants a using-declaration to name an injected-class-name 7614 // of a base class, unless they're declaring an inheriting constructor. 7615 ASTContext &Ctx = ND->getASTContext(); 7616 if (!Ctx.getLangOpts().CPlusPlus11) 7617 return false; 7618 QualType FoundType = Ctx.getRecordType(FoundRecord); 7619 7620 // Check that the injected-class-name is named as a member of its own 7621 // type; we don't want to suggest 'using Derived::Base;', since that 7622 // means something else. 7623 NestedNameSpecifier *Specifier = 7624 Candidate.WillReplaceSpecifier() 7625 ? Candidate.getCorrectionSpecifier() 7626 : OldNNS; 7627 if (!Specifier->getAsType() || 7628 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 7629 return false; 7630 7631 // Check that this inheriting constructor declaration actually names a 7632 // direct base class of the current class. 7633 bool AnyDependentBases = false; 7634 if (!findDirectBaseWithType(RequireMemberOf, 7635 Ctx.getRecordType(FoundRecord), 7636 AnyDependentBases) && 7637 !AnyDependentBases) 7638 return false; 7639 } else { 7640 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 7641 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 7642 return false; 7643 7644 // FIXME: Check that the base class member is accessible? 7645 } 7646 } 7647 7648 if (isa<TypeDecl>(ND)) 7649 return HasTypenameKeyword || !IsInstantiation; 7650 7651 return !HasTypenameKeyword; 7652 } 7653 7654 private: 7655 bool HasTypenameKeyword; 7656 bool IsInstantiation; 7657 NestedNameSpecifier *OldNNS; 7658 CXXRecordDecl *RequireMemberOf; 7659 }; 7660 } // end anonymous namespace 7661 7662 /// Builds a using declaration. 7663 /// 7664 /// \param IsInstantiation - Whether this call arises from an 7665 /// instantiation of an unresolved using declaration. We treat 7666 /// the lookup differently for these declarations. 7667 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7668 SourceLocation UsingLoc, 7669 CXXScopeSpec &SS, 7670 DeclarationNameInfo NameInfo, 7671 AttributeList *AttrList, 7672 bool IsInstantiation, 7673 bool HasTypenameKeyword, 7674 SourceLocation TypenameLoc) { 7675 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7676 SourceLocation IdentLoc = NameInfo.getLoc(); 7677 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7678 7679 // FIXME: We ignore attributes for now. 7680 7681 if (SS.isEmpty()) { 7682 Diag(IdentLoc, diag::err_using_requires_qualname); 7683 return nullptr; 7684 } 7685 7686 // Do the redeclaration lookup in the current scope. 7687 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7688 ForRedeclaration); 7689 Previous.setHideTags(false); 7690 if (S) { 7691 LookupName(Previous, S); 7692 7693 // It is really dumb that we have to do this. 7694 LookupResult::Filter F = Previous.makeFilter(); 7695 while (F.hasNext()) { 7696 NamedDecl *D = F.next(); 7697 if (!isDeclInScope(D, CurContext, S)) 7698 F.erase(); 7699 // If we found a local extern declaration that's not ordinarily visible, 7700 // and this declaration is being added to a non-block scope, ignore it. 7701 // We're only checking for scope conflicts here, not also for violations 7702 // of the linkage rules. 7703 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 7704 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 7705 F.erase(); 7706 } 7707 F.done(); 7708 } else { 7709 assert(IsInstantiation && "no scope in non-instantiation"); 7710 assert(CurContext->isRecord() && "scope not record in instantiation"); 7711 LookupQualifiedName(Previous, CurContext); 7712 } 7713 7714 // Check for invalid redeclarations. 7715 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7716 SS, IdentLoc, Previous)) 7717 return nullptr; 7718 7719 // Check for bad qualifiers. 7720 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 7721 return nullptr; 7722 7723 DeclContext *LookupContext = computeDeclContext(SS); 7724 NamedDecl *D; 7725 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7726 if (!LookupContext) { 7727 if (HasTypenameKeyword) { 7728 // FIXME: not all declaration name kinds are legal here 7729 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7730 UsingLoc, TypenameLoc, 7731 QualifierLoc, 7732 IdentLoc, NameInfo.getName()); 7733 } else { 7734 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7735 QualifierLoc, NameInfo); 7736 } 7737 D->setAccess(AS); 7738 CurContext->addDecl(D); 7739 return D; 7740 } 7741 7742 auto Build = [&](bool Invalid) { 7743 UsingDecl *UD = 7744 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, 7745 HasTypenameKeyword); 7746 UD->setAccess(AS); 7747 CurContext->addDecl(UD); 7748 UD->setInvalidDecl(Invalid); 7749 return UD; 7750 }; 7751 auto BuildInvalid = [&]{ return Build(true); }; 7752 auto BuildValid = [&]{ return Build(false); }; 7753 7754 if (RequireCompleteDeclContext(SS, LookupContext)) 7755 return BuildInvalid(); 7756 7757 // The normal rules do not apply to inheriting constructor declarations. 7758 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7759 UsingDecl *UD = BuildValid(); 7760 CheckInheritingConstructorUsingDecl(UD); 7761 return UD; 7762 } 7763 7764 // Otherwise, look up the target name. 7765 7766 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7767 7768 // Unlike most lookups, we don't always want to hide tag 7769 // declarations: tag names are visible through the using declaration 7770 // even if hidden by ordinary names, *except* in a dependent context 7771 // where it's important for the sanity of two-phase lookup. 7772 if (!IsInstantiation) 7773 R.setHideTags(false); 7774 7775 // For the purposes of this lookup, we have a base object type 7776 // equal to that of the current context. 7777 if (CurContext->isRecord()) { 7778 R.setBaseObjectType( 7779 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7780 } 7781 7782 LookupQualifiedName(R, LookupContext); 7783 7784 // Try to correct typos if possible. 7785 if (R.empty()) { 7786 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 7787 dyn_cast<CXXRecordDecl>(CurContext)); 7788 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(), 7789 R.getLookupKind(), S, &SS, CCC, 7790 CTK_ErrorRecovery)){ 7791 // We reject any correction for which ND would be NULL. 7792 NamedDecl *ND = Corrected.getCorrectionDecl(); 7793 7794 // We reject candidates where DroppedSpecifier == true, hence the 7795 // literal '0' below. 7796 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 7797 << NameInfo.getName() << LookupContext << 0 7798 << SS.getRange()); 7799 7800 // If we corrected to an inheriting constructor, handle it as one. 7801 auto *RD = dyn_cast<CXXRecordDecl>(ND); 7802 if (RD && RD->isInjectedClassName()) { 7803 // Fix up the information we'll use to build the using declaration. 7804 if (Corrected.WillReplaceSpecifier()) { 7805 NestedNameSpecifierLocBuilder Builder; 7806 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 7807 QualifierLoc.getSourceRange()); 7808 QualifierLoc = Builder.getWithLocInContext(Context); 7809 } 7810 7811 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 7812 Context.getCanonicalType(Context.getRecordType(RD)))); 7813 NameInfo.setNamedTypeInfo(nullptr); 7814 7815 // Build it and process it as an inheriting constructor. 7816 UsingDecl *UD = BuildValid(); 7817 CheckInheritingConstructorUsingDecl(UD); 7818 return UD; 7819 } 7820 7821 // FIXME: Pick up all the declarations if we found an overloaded function. 7822 R.setLookupName(Corrected.getCorrection()); 7823 R.addDecl(ND); 7824 } else { 7825 Diag(IdentLoc, diag::err_no_member) 7826 << NameInfo.getName() << LookupContext << SS.getRange(); 7827 return BuildInvalid(); 7828 } 7829 } 7830 7831 if (R.isAmbiguous()) 7832 return BuildInvalid(); 7833 7834 if (HasTypenameKeyword) { 7835 // If we asked for a typename and got a non-type decl, error out. 7836 if (!R.getAsSingle<TypeDecl>()) { 7837 Diag(IdentLoc, diag::err_using_typename_non_type); 7838 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7839 Diag((*I)->getUnderlyingDecl()->getLocation(), 7840 diag::note_using_decl_target); 7841 return BuildInvalid(); 7842 } 7843 } else { 7844 // If we asked for a non-typename and we got a type, error out, 7845 // but only if this is an instantiation of an unresolved using 7846 // decl. Otherwise just silently find the type name. 7847 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7848 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7849 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7850 return BuildInvalid(); 7851 } 7852 } 7853 7854 // C++0x N2914 [namespace.udecl]p6: 7855 // A using-declaration shall not name a namespace. 7856 if (R.getAsSingle<NamespaceDecl>()) { 7857 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7858 << SS.getRange(); 7859 return BuildInvalid(); 7860 } 7861 7862 UsingDecl *UD = BuildValid(); 7863 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7864 UsingShadowDecl *PrevDecl = nullptr; 7865 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 7866 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 7867 } 7868 7869 return UD; 7870 } 7871 7872 /// Additional checks for a using declaration referring to a constructor name. 7873 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7874 assert(!UD->hasTypename() && "expecting a constructor name"); 7875 7876 const Type *SourceType = UD->getQualifier()->getAsType(); 7877 assert(SourceType && 7878 "Using decl naming constructor doesn't have type in scope spec."); 7879 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7880 7881 // Check whether the named type is a direct base class. 7882 bool AnyDependentBases = false; 7883 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 7884 AnyDependentBases); 7885 if (!Base && !AnyDependentBases) { 7886 Diag(UD->getUsingLoc(), 7887 diag::err_using_decl_constructor_not_in_direct_base) 7888 << UD->getNameInfo().getSourceRange() 7889 << QualType(SourceType, 0) << TargetClass; 7890 UD->setInvalidDecl(); 7891 return true; 7892 } 7893 7894 if (Base) 7895 Base->setInheritConstructors(); 7896 7897 return false; 7898 } 7899 7900 /// Checks that the given using declaration is not an invalid 7901 /// redeclaration. Note that this is checking only for the using decl 7902 /// itself, not for any ill-formedness among the UsingShadowDecls. 7903 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7904 bool HasTypenameKeyword, 7905 const CXXScopeSpec &SS, 7906 SourceLocation NameLoc, 7907 const LookupResult &Prev) { 7908 // C++03 [namespace.udecl]p8: 7909 // C++0x [namespace.udecl]p10: 7910 // A using-declaration is a declaration and can therefore be used 7911 // repeatedly where (and only where) multiple declarations are 7912 // allowed. 7913 // 7914 // That's in non-member contexts. 7915 if (!CurContext->getRedeclContext()->isRecord()) 7916 return false; 7917 7918 NestedNameSpecifier *Qual = SS.getScopeRep(); 7919 7920 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7921 NamedDecl *D = *I; 7922 7923 bool DTypename; 7924 NestedNameSpecifier *DQual; 7925 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7926 DTypename = UD->hasTypename(); 7927 DQual = UD->getQualifier(); 7928 } else if (UnresolvedUsingValueDecl *UD 7929 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7930 DTypename = false; 7931 DQual = UD->getQualifier(); 7932 } else if (UnresolvedUsingTypenameDecl *UD 7933 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7934 DTypename = true; 7935 DQual = UD->getQualifier(); 7936 } else continue; 7937 7938 // using decls differ if one says 'typename' and the other doesn't. 7939 // FIXME: non-dependent using decls? 7940 if (HasTypenameKeyword != DTypename) continue; 7941 7942 // using decls differ if they name different scopes (but note that 7943 // template instantiation can cause this check to trigger when it 7944 // didn't before instantiation). 7945 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7946 Context.getCanonicalNestedNameSpecifier(DQual)) 7947 continue; 7948 7949 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7950 Diag(D->getLocation(), diag::note_using_decl) << 1; 7951 return true; 7952 } 7953 7954 return false; 7955 } 7956 7957 7958 /// Checks that the given nested-name qualifier used in a using decl 7959 /// in the current context is appropriately related to the current 7960 /// scope. If an error is found, diagnoses it and returns true. 7961 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7962 const CXXScopeSpec &SS, 7963 const DeclarationNameInfo &NameInfo, 7964 SourceLocation NameLoc) { 7965 DeclContext *NamedContext = computeDeclContext(SS); 7966 7967 if (!CurContext->isRecord()) { 7968 // C++03 [namespace.udecl]p3: 7969 // C++0x [namespace.udecl]p8: 7970 // A using-declaration for a class member shall be a member-declaration. 7971 7972 // If we weren't able to compute a valid scope, it must be a 7973 // dependent class scope. 7974 if (!NamedContext || NamedContext->isRecord()) { 7975 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext); 7976 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 7977 RD = nullptr; 7978 7979 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7980 << SS.getRange(); 7981 7982 // If we have a complete, non-dependent source type, try to suggest a 7983 // way to get the same effect. 7984 if (!RD) 7985 return true; 7986 7987 // Find what this using-declaration was referring to. 7988 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7989 R.setHideTags(false); 7990 R.suppressDiagnostics(); 7991 LookupQualifiedName(R, RD); 7992 7993 if (R.getAsSingle<TypeDecl>()) { 7994 if (getLangOpts().CPlusPlus11) { 7995 // Convert 'using X::Y;' to 'using Y = X::Y;'. 7996 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 7997 << 0 // alias declaration 7998 << FixItHint::CreateInsertion(SS.getBeginLoc(), 7999 NameInfo.getName().getAsString() + 8000 " = "); 8001 } else { 8002 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 8003 SourceLocation InsertLoc = 8004 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 8005 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 8006 << 1 // typedef declaration 8007 << FixItHint::CreateReplacement(UsingLoc, "typedef") 8008 << FixItHint::CreateInsertion( 8009 InsertLoc, " " + NameInfo.getName().getAsString()); 8010 } 8011 } else if (R.getAsSingle<VarDecl>()) { 8012 // Don't provide a fixit outside C++11 mode; we don't want to suggest 8013 // repeating the type of the static data member here. 8014 FixItHint FixIt; 8015 if (getLangOpts().CPlusPlus11) { 8016 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 8017 FixIt = FixItHint::CreateReplacement( 8018 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 8019 } 8020 8021 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 8022 << 2 // reference declaration 8023 << FixIt; 8024 } 8025 return true; 8026 } 8027 8028 // Otherwise, everything is known to be fine. 8029 return false; 8030 } 8031 8032 // The current scope is a record. 8033 8034 // If the named context is dependent, we can't decide much. 8035 if (!NamedContext) { 8036 // FIXME: in C++0x, we can diagnose if we can prove that the 8037 // nested-name-specifier does not refer to a base class, which is 8038 // still possible in some cases. 8039 8040 // Otherwise we have to conservatively report that things might be 8041 // okay. 8042 return false; 8043 } 8044 8045 if (!NamedContext->isRecord()) { 8046 // Ideally this would point at the last name in the specifier, 8047 // but we don't have that level of source info. 8048 Diag(SS.getRange().getBegin(), 8049 diag::err_using_decl_nested_name_specifier_is_not_class) 8050 << SS.getScopeRep() << SS.getRange(); 8051 return true; 8052 } 8053 8054 if (!NamedContext->isDependentContext() && 8055 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 8056 return true; 8057 8058 if (getLangOpts().CPlusPlus11) { 8059 // C++0x [namespace.udecl]p3: 8060 // In a using-declaration used as a member-declaration, the 8061 // nested-name-specifier shall name a base class of the class 8062 // being defined. 8063 8064 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 8065 cast<CXXRecordDecl>(NamedContext))) { 8066 if (CurContext == NamedContext) { 8067 Diag(NameLoc, 8068 diag::err_using_decl_nested_name_specifier_is_current_class) 8069 << SS.getRange(); 8070 return true; 8071 } 8072 8073 Diag(SS.getRange().getBegin(), 8074 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8075 << SS.getScopeRep() 8076 << cast<CXXRecordDecl>(CurContext) 8077 << SS.getRange(); 8078 return true; 8079 } 8080 8081 return false; 8082 } 8083 8084 // C++03 [namespace.udecl]p4: 8085 // A using-declaration used as a member-declaration shall refer 8086 // to a member of a base class of the class being defined [etc.]. 8087 8088 // Salient point: SS doesn't have to name a base class as long as 8089 // lookup only finds members from base classes. Therefore we can 8090 // diagnose here only if we can prove that that can't happen, 8091 // i.e. if the class hierarchies provably don't intersect. 8092 8093 // TODO: it would be nice if "definitely valid" results were cached 8094 // in the UsingDecl and UsingShadowDecl so that these checks didn't 8095 // need to be repeated. 8096 8097 struct UserData { 8098 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 8099 8100 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 8101 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8102 Data->Bases.insert(Base); 8103 return true; 8104 } 8105 8106 bool hasDependentBases(const CXXRecordDecl *Class) { 8107 return !Class->forallBases(collect, this); 8108 } 8109 8110 /// Returns true if the base is dependent or is one of the 8111 /// accumulated base classes. 8112 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 8113 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 8114 return !Data->Bases.count(Base); 8115 } 8116 8117 bool mightShareBases(const CXXRecordDecl *Class) { 8118 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 8119 } 8120 }; 8121 8122 UserData Data; 8123 8124 // Returns false if we find a dependent base. 8125 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 8126 return false; 8127 8128 // Returns false if the class has a dependent base or if it or one 8129 // of its bases is present in the base set of the current context. 8130 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 8131 return false; 8132 8133 Diag(SS.getRange().getBegin(), 8134 diag::err_using_decl_nested_name_specifier_is_not_base_class) 8135 << SS.getScopeRep() 8136 << cast<CXXRecordDecl>(CurContext) 8137 << SS.getRange(); 8138 8139 return true; 8140 } 8141 8142 Decl *Sema::ActOnAliasDeclaration(Scope *S, 8143 AccessSpecifier AS, 8144 MultiTemplateParamsArg TemplateParamLists, 8145 SourceLocation UsingLoc, 8146 UnqualifiedId &Name, 8147 AttributeList *AttrList, 8148 TypeResult Type) { 8149 // Skip up to the relevant declaration scope. 8150 while (S->getFlags() & Scope::TemplateParamScope) 8151 S = S->getParent(); 8152 assert((S->getFlags() & Scope::DeclScope) && 8153 "got alias-declaration outside of declaration scope"); 8154 8155 if (Type.isInvalid()) 8156 return nullptr; 8157 8158 bool Invalid = false; 8159 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 8160 TypeSourceInfo *TInfo = nullptr; 8161 GetTypeFromParser(Type.get(), &TInfo); 8162 8163 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 8164 return nullptr; 8165 8166 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 8167 UPPC_DeclarationType)) { 8168 Invalid = true; 8169 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 8170 TInfo->getTypeLoc().getBeginLoc()); 8171 } 8172 8173 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 8174 LookupName(Previous, S); 8175 8176 // Warn about shadowing the name of a template parameter. 8177 if (Previous.isSingleResult() && 8178 Previous.getFoundDecl()->isTemplateParameter()) { 8179 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 8180 Previous.clear(); 8181 } 8182 8183 assert(Name.Kind == UnqualifiedId::IK_Identifier && 8184 "name in alias declaration must be an identifier"); 8185 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 8186 Name.StartLocation, 8187 Name.Identifier, TInfo); 8188 8189 NewTD->setAccess(AS); 8190 8191 if (Invalid) 8192 NewTD->setInvalidDecl(); 8193 8194 ProcessDeclAttributeList(S, NewTD, AttrList); 8195 8196 CheckTypedefForVariablyModifiedType(S, NewTD); 8197 Invalid |= NewTD->isInvalidDecl(); 8198 8199 bool Redeclaration = false; 8200 8201 NamedDecl *NewND; 8202 if (TemplateParamLists.size()) { 8203 TypeAliasTemplateDecl *OldDecl = nullptr; 8204 TemplateParameterList *OldTemplateParams = nullptr; 8205 8206 if (TemplateParamLists.size() != 1) { 8207 Diag(UsingLoc, diag::err_alias_template_extra_headers) 8208 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 8209 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 8210 } 8211 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 8212 8213 // Only consider previous declarations in the same scope. 8214 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 8215 /*ExplicitInstantiationOrSpecialization*/false); 8216 if (!Previous.empty()) { 8217 Redeclaration = true; 8218 8219 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 8220 if (!OldDecl && !Invalid) { 8221 Diag(UsingLoc, diag::err_redefinition_different_kind) 8222 << Name.Identifier; 8223 8224 NamedDecl *OldD = Previous.getRepresentativeDecl(); 8225 if (OldD->getLocation().isValid()) 8226 Diag(OldD->getLocation(), diag::note_previous_definition); 8227 8228 Invalid = true; 8229 } 8230 8231 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 8232 if (TemplateParameterListsAreEqual(TemplateParams, 8233 OldDecl->getTemplateParameters(), 8234 /*Complain=*/true, 8235 TPL_TemplateMatch)) 8236 OldTemplateParams = OldDecl->getTemplateParameters(); 8237 else 8238 Invalid = true; 8239 8240 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 8241 if (!Invalid && 8242 !Context.hasSameType(OldTD->getUnderlyingType(), 8243 NewTD->getUnderlyingType())) { 8244 // FIXME: The C++0x standard does not clearly say this is ill-formed, 8245 // but we can't reasonably accept it. 8246 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 8247 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 8248 if (OldTD->getLocation().isValid()) 8249 Diag(OldTD->getLocation(), diag::note_previous_definition); 8250 Invalid = true; 8251 } 8252 } 8253 } 8254 8255 // Merge any previous default template arguments into our parameters, 8256 // and check the parameter list. 8257 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 8258 TPC_TypeAliasTemplate)) 8259 return nullptr; 8260 8261 TypeAliasTemplateDecl *NewDecl = 8262 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 8263 Name.Identifier, TemplateParams, 8264 NewTD); 8265 NewTD->setDescribedAliasTemplate(NewDecl); 8266 8267 NewDecl->setAccess(AS); 8268 8269 if (Invalid) 8270 NewDecl->setInvalidDecl(); 8271 else if (OldDecl) 8272 NewDecl->setPreviousDecl(OldDecl); 8273 8274 NewND = NewDecl; 8275 } else { 8276 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 8277 NewND = NewTD; 8278 } 8279 8280 if (!Redeclaration) 8281 PushOnScopeChains(NewND, S); 8282 8283 ActOnDocumentableDecl(NewND); 8284 return NewND; 8285 } 8286 8287 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 8288 SourceLocation AliasLoc, 8289 IdentifierInfo *Alias, CXXScopeSpec &SS, 8290 SourceLocation IdentLoc, 8291 IdentifierInfo *Ident) { 8292 8293 // Lookup the namespace name. 8294 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 8295 LookupParsedName(R, S, &SS); 8296 8297 if (R.isAmbiguous()) 8298 return nullptr; 8299 8300 if (R.empty()) { 8301 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8302 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8303 return nullptr; 8304 } 8305 } 8306 assert(!R.isAmbiguous() && !R.empty()); 8307 8308 // Check if we have a previous declaration with the same name. 8309 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 8310 ForRedeclaration); 8311 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 8312 PrevDecl = nullptr; 8313 8314 if (PrevDecl) { 8315 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 8316 // We already have an alias with the same name that points to the same 8317 // namespace; check that it matches. 8318 if (!AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) { 8319 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 8320 << Alias; 8321 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias) 8322 << AD->getNamespace(); 8323 return nullptr; 8324 } 8325 } else { 8326 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) 8327 ? diag::err_redefinition 8328 : diag::err_redefinition_different_kind; 8329 Diag(AliasLoc, DiagID) << Alias; 8330 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 8331 return nullptr; 8332 } 8333 } 8334 8335 NamespaceAliasDecl *AliasDecl = 8336 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8337 Alias, SS.getWithLocInContext(Context), 8338 IdentLoc, R.getFoundDecl()); 8339 if (PrevDecl) 8340 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl)); 8341 8342 PushOnScopeChains(AliasDecl, S); 8343 return AliasDecl; 8344 } 8345 8346 Sema::ImplicitExceptionSpecification 8347 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8348 CXXMethodDecl *MD) { 8349 CXXRecordDecl *ClassDecl = MD->getParent(); 8350 8351 // C++ [except.spec]p14: 8352 // An implicitly declared special member function (Clause 12) shall have an 8353 // exception-specification. [...] 8354 ImplicitExceptionSpecification ExceptSpec(*this); 8355 if (ClassDecl->isInvalidDecl()) 8356 return ExceptSpec; 8357 8358 // Direct base-class constructors. 8359 for (const auto &B : ClassDecl->bases()) { 8360 if (B.isVirtual()) // Handled below. 8361 continue; 8362 8363 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8364 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8365 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8366 // If this is a deleted function, add it anyway. This might be conformant 8367 // with the standard. This might not. I'm not sure. It might not matter. 8368 if (Constructor) 8369 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8370 } 8371 } 8372 8373 // Virtual base-class constructors. 8374 for (const auto &B : ClassDecl->vbases()) { 8375 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8376 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8377 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8378 // If this is a deleted function, add it anyway. This might be conformant 8379 // with the standard. This might not. I'm not sure. It might not matter. 8380 if (Constructor) 8381 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8382 } 8383 } 8384 8385 // Field constructors. 8386 for (const auto *F : ClassDecl->fields()) { 8387 if (F->hasInClassInitializer()) { 8388 if (Expr *E = F->getInClassInitializer()) 8389 ExceptSpec.CalledExpr(E); 8390 else if (!F->isInvalidDecl()) 8391 // DR1351: 8392 // If the brace-or-equal-initializer of a non-static data member 8393 // invokes a defaulted default constructor of its class or of an 8394 // enclosing class in a potentially evaluated subexpression, the 8395 // program is ill-formed. 8396 // 8397 // This resolution is unworkable: the exception specification of the 8398 // default constructor can be needed in an unevaluated context, in 8399 // particular, in the operand of a noexcept-expression, and we can be 8400 // unable to compute an exception specification for an enclosed class. 8401 // 8402 // We do not allow an in-class initializer to require the evaluation 8403 // of the exception specification for any in-class initializer whose 8404 // definition is not lexically complete. 8405 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 8406 } else if (const RecordType *RecordTy 8407 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8408 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8409 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8410 // If this is a deleted function, add it anyway. This might be conformant 8411 // with the standard. This might not. I'm not sure. It might not matter. 8412 // In particular, the problem is that this function never gets called. It 8413 // might just be ill-formed because this function attempts to refer to 8414 // a deleted function here. 8415 if (Constructor) 8416 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8417 } 8418 } 8419 8420 return ExceptSpec; 8421 } 8422 8423 Sema::ImplicitExceptionSpecification 8424 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8425 CXXRecordDecl *ClassDecl = CD->getParent(); 8426 8427 // C++ [except.spec]p14: 8428 // An inheriting constructor [...] shall have an exception-specification. [...] 8429 ImplicitExceptionSpecification ExceptSpec(*this); 8430 if (ClassDecl->isInvalidDecl()) 8431 return ExceptSpec; 8432 8433 // Inherited constructor. 8434 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8435 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8436 // FIXME: Copying or moving the parameters could add extra exceptions to the 8437 // set, as could the default arguments for the inherited constructor. This 8438 // will be addressed when we implement the resolution of core issue 1351. 8439 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8440 8441 // Direct base-class constructors. 8442 for (const auto &B : ClassDecl->bases()) { 8443 if (B.isVirtual()) // Handled below. 8444 continue; 8445 8446 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8447 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8448 if (BaseClassDecl == InheritedDecl) 8449 continue; 8450 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8451 if (Constructor) 8452 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8453 } 8454 } 8455 8456 // Virtual base-class constructors. 8457 for (const auto &B : ClassDecl->vbases()) { 8458 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8459 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8460 if (BaseClassDecl == InheritedDecl) 8461 continue; 8462 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8463 if (Constructor) 8464 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8465 } 8466 } 8467 8468 // Field constructors. 8469 for (const auto *F : ClassDecl->fields()) { 8470 if (F->hasInClassInitializer()) { 8471 if (Expr *E = F->getInClassInitializer()) 8472 ExceptSpec.CalledExpr(E); 8473 else if (!F->isInvalidDecl()) 8474 Diag(CD->getLocation(), 8475 diag::err_in_class_initializer_references_def_ctor) << CD; 8476 } else if (const RecordType *RecordTy 8477 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8478 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8479 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8480 if (Constructor) 8481 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8482 } 8483 } 8484 8485 return ExceptSpec; 8486 } 8487 8488 namespace { 8489 /// RAII object to register a special member as being currently declared. 8490 struct DeclaringSpecialMember { 8491 Sema &S; 8492 Sema::SpecialMemberDecl D; 8493 bool WasAlreadyBeingDeclared; 8494 8495 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8496 : S(S), D(RD, CSM) { 8497 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 8498 if (WasAlreadyBeingDeclared) 8499 // This almost never happens, but if it does, ensure that our cache 8500 // doesn't contain a stale result. 8501 S.SpecialMemberCache.clear(); 8502 8503 // FIXME: Register a note to be produced if we encounter an error while 8504 // declaring the special member. 8505 } 8506 ~DeclaringSpecialMember() { 8507 if (!WasAlreadyBeingDeclared) 8508 S.SpecialMembersBeingDeclared.erase(D); 8509 } 8510 8511 /// \brief Are we already trying to declare this special member? 8512 bool isAlreadyBeingDeclared() const { 8513 return WasAlreadyBeingDeclared; 8514 } 8515 }; 8516 } 8517 8518 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8519 CXXRecordDecl *ClassDecl) { 8520 // C++ [class.ctor]p5: 8521 // A default constructor for a class X is a constructor of class X 8522 // that can be called without an argument. If there is no 8523 // user-declared constructor for class X, a default constructor is 8524 // implicitly declared. An implicitly-declared default constructor 8525 // is an inline public member of its class. 8526 assert(ClassDecl->needsImplicitDefaultConstructor() && 8527 "Should not build implicit default constructor!"); 8528 8529 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8530 if (DSM.isAlreadyBeingDeclared()) 8531 return nullptr; 8532 8533 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8534 CXXDefaultConstructor, 8535 false); 8536 8537 // Create the actual constructor declaration. 8538 CanQualType ClassType 8539 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8540 SourceLocation ClassLoc = ClassDecl->getLocation(); 8541 DeclarationName Name 8542 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8543 DeclarationNameInfo NameInfo(Name, ClassLoc); 8544 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8545 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), 8546 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true, 8547 /*isImplicitlyDeclared=*/true, Constexpr); 8548 DefaultCon->setAccess(AS_public); 8549 DefaultCon->setDefaulted(); 8550 8551 if (getLangOpts().CUDA) { 8552 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 8553 DefaultCon, 8554 /* ConstRHS */ false, 8555 /* Diagnose */ false); 8556 } 8557 8558 // Build an exception specification pointing back at this constructor. 8559 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8560 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8561 8562 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8563 // constructors is easy to compute. 8564 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8565 8566 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8567 SetDeclDeleted(DefaultCon, ClassLoc); 8568 8569 // Note that we have declared this constructor. 8570 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8571 8572 if (Scope *S = getScopeForContext(ClassDecl)) 8573 PushOnScopeChains(DefaultCon, S, false); 8574 ClassDecl->addDecl(DefaultCon); 8575 8576 return DefaultCon; 8577 } 8578 8579 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8580 CXXConstructorDecl *Constructor) { 8581 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8582 !Constructor->doesThisDeclarationHaveABody() && 8583 !Constructor->isDeleted()) && 8584 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8585 8586 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8587 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8588 8589 SynthesizedFunctionScope Scope(*this, Constructor); 8590 DiagnosticErrorTrap Trap(Diags); 8591 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8592 Trap.hasErrorOccurred()) { 8593 Diag(CurrentLocation, diag::note_member_synthesized_at) 8594 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8595 Constructor->setInvalidDecl(); 8596 return; 8597 } 8598 8599 // The exception specification is needed because we are defining the 8600 // function. 8601 ResolveExceptionSpec(CurrentLocation, 8602 Constructor->getType()->castAs<FunctionProtoType>()); 8603 8604 SourceLocation Loc = Constructor->getLocEnd().isValid() 8605 ? Constructor->getLocEnd() 8606 : Constructor->getLocation(); 8607 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8608 8609 Constructor->markUsed(Context); 8610 MarkVTableUsed(CurrentLocation, ClassDecl); 8611 8612 if (ASTMutationListener *L = getASTMutationListener()) { 8613 L->CompletedImplicitDefinition(Constructor); 8614 } 8615 8616 DiagnoseUninitializedFields(*this, Constructor); 8617 } 8618 8619 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8620 // Perform any delayed checks on exception specifications. 8621 CheckDelayedMemberExceptionSpecs(); 8622 } 8623 8624 namespace { 8625 /// Information on inheriting constructors to declare. 8626 class InheritingConstructorInfo { 8627 public: 8628 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8629 : SemaRef(SemaRef), Derived(Derived) { 8630 // Mark the constructors that we already have in the derived class. 8631 // 8632 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8633 // unless there is a user-declared constructor with the same signature in 8634 // the class where the using-declaration appears. 8635 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8636 } 8637 8638 void inheritAll(CXXRecordDecl *RD) { 8639 visitAll(RD, &InheritingConstructorInfo::inherit); 8640 } 8641 8642 private: 8643 /// Information about an inheriting constructor. 8644 struct InheritingConstructor { 8645 InheritingConstructor() 8646 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {} 8647 8648 /// If \c true, a constructor with this signature is already declared 8649 /// in the derived class. 8650 bool DeclaredInDerived; 8651 8652 /// The constructor which is inherited. 8653 const CXXConstructorDecl *BaseCtor; 8654 8655 /// The derived constructor we declared. 8656 CXXConstructorDecl *DerivedCtor; 8657 }; 8658 8659 /// Inheriting constructors with a given canonical type. There can be at 8660 /// most one such non-template constructor, and any number of templated 8661 /// constructors. 8662 struct InheritingConstructorsForType { 8663 InheritingConstructor NonTemplate; 8664 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8665 Templates; 8666 8667 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8668 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8669 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8670 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8671 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8672 false, S.TPL_TemplateMatch)) 8673 return Templates[I].second; 8674 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8675 return Templates.back().second; 8676 } 8677 8678 return NonTemplate; 8679 } 8680 }; 8681 8682 /// Get or create the inheriting constructor record for a constructor. 8683 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8684 QualType CtorType) { 8685 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8686 .getEntry(SemaRef, Ctor); 8687 } 8688 8689 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8690 8691 /// Process all constructors for a class. 8692 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8693 for (const auto *Ctor : RD->ctors()) 8694 (this->*Callback)(Ctor); 8695 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8696 I(RD->decls_begin()), E(RD->decls_end()); 8697 I != E; ++I) { 8698 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8699 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8700 (this->*Callback)(CD); 8701 } 8702 } 8703 8704 /// Note that a constructor (or constructor template) was declared in Derived. 8705 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8706 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8707 } 8708 8709 /// Inherit a single constructor. 8710 void inherit(const CXXConstructorDecl *Ctor) { 8711 const FunctionProtoType *CtorType = 8712 Ctor->getType()->castAs<FunctionProtoType>(); 8713 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes(); 8714 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8715 8716 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8717 8718 // Core issue (no number yet): the ellipsis is always discarded. 8719 if (EPI.Variadic) { 8720 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8721 SemaRef.Diag(Ctor->getLocation(), 8722 diag::note_using_decl_constructor_ellipsis); 8723 EPI.Variadic = false; 8724 } 8725 8726 // Declare a constructor for each number of parameters. 8727 // 8728 // C++11 [class.inhctor]p1: 8729 // The candidate set of inherited constructors from the class X named in 8730 // the using-declaration consists of [... modulo defects ...] for each 8731 // constructor or constructor template of X, the set of constructors or 8732 // constructor templates that results from omitting any ellipsis parameter 8733 // specification and successively omitting parameters with a default 8734 // argument from the end of the parameter-type-list 8735 unsigned MinParams = minParamsToInherit(Ctor); 8736 unsigned Params = Ctor->getNumParams(); 8737 if (Params >= MinParams) { 8738 do 8739 declareCtor(UsingLoc, Ctor, 8740 SemaRef.Context.getFunctionType( 8741 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 8742 while (Params > MinParams && 8743 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8744 } 8745 } 8746 8747 /// Find the using-declaration which specified that we should inherit the 8748 /// constructors of \p Base. 8749 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8750 // No fancy lookup required; just look for the base constructor name 8751 // directly within the derived class. 8752 ASTContext &Context = SemaRef.Context; 8753 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8754 Context.getCanonicalType(Context.getRecordType(Base))); 8755 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8756 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8757 } 8758 8759 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8760 // C++11 [class.inhctor]p3: 8761 // [F]or each constructor template in the candidate set of inherited 8762 // constructors, a constructor template is implicitly declared 8763 if (Ctor->getDescribedFunctionTemplate()) 8764 return 0; 8765 8766 // For each non-template constructor in the candidate set of inherited 8767 // constructors other than a constructor having no parameters or a 8768 // copy/move constructor having a single parameter, a constructor is 8769 // implicitly declared [...] 8770 if (Ctor->getNumParams() == 0) 8771 return 1; 8772 if (Ctor->isCopyOrMoveConstructor()) 8773 return 2; 8774 8775 // Per discussion on core reflector, never inherit a constructor which 8776 // would become a default, copy, or move constructor of Derived either. 8777 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8778 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8779 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8780 } 8781 8782 /// Declare a single inheriting constructor, inheriting the specified 8783 /// constructor, with the given type. 8784 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8785 QualType DerivedType) { 8786 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8787 8788 // C++11 [class.inhctor]p3: 8789 // ... a constructor is implicitly declared with the same constructor 8790 // characteristics unless there is a user-declared constructor with 8791 // the same signature in the class where the using-declaration appears 8792 if (Entry.DeclaredInDerived) 8793 return; 8794 8795 // C++11 [class.inhctor]p7: 8796 // If two using-declarations declare inheriting constructors with the 8797 // same signature, the program is ill-formed 8798 if (Entry.DerivedCtor) { 8799 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8800 // Only diagnose this once per constructor. 8801 if (Entry.DerivedCtor->isInvalidDecl()) 8802 return; 8803 Entry.DerivedCtor->setInvalidDecl(); 8804 8805 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8806 SemaRef.Diag(BaseCtor->getLocation(), 8807 diag::note_using_decl_constructor_conflict_current_ctor); 8808 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8809 diag::note_using_decl_constructor_conflict_previous_ctor); 8810 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8811 diag::note_using_decl_constructor_conflict_previous_using); 8812 } else { 8813 // Core issue (no number): if the same inheriting constructor is 8814 // produced by multiple base class constructors from the same base 8815 // class, the inheriting constructor is defined as deleted. 8816 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8817 } 8818 8819 return; 8820 } 8821 8822 ASTContext &Context = SemaRef.Context; 8823 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8824 Context.getCanonicalType(Context.getRecordType(Derived))); 8825 DeclarationNameInfo NameInfo(Name, UsingLoc); 8826 8827 TemplateParameterList *TemplateParams = nullptr; 8828 if (const FunctionTemplateDecl *FTD = 8829 BaseCtor->getDescribedFunctionTemplate()) { 8830 TemplateParams = FTD->getTemplateParameters(); 8831 // We're reusing template parameters from a different DeclContext. This 8832 // is questionable at best, but works out because the template depth in 8833 // both places is guaranteed to be 0. 8834 // FIXME: Rebuild the template parameters in the new context, and 8835 // transform the function type to refer to them. 8836 } 8837 8838 // Build type source info pointing at the using-declaration. This is 8839 // required by template instantiation. 8840 TypeSourceInfo *TInfo = 8841 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8842 FunctionProtoTypeLoc ProtoLoc = 8843 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8844 8845 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8846 Context, Derived, UsingLoc, NameInfo, DerivedType, 8847 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8848 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8849 8850 // Build an unevaluated exception specification for this constructor. 8851 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8852 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8853 EPI.ExceptionSpec.Type = EST_Unevaluated; 8854 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 8855 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 8856 FPT->getParamTypes(), EPI)); 8857 8858 // Build the parameter declarations. 8859 SmallVector<ParmVarDecl *, 16> ParamDecls; 8860 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 8861 TypeSourceInfo *TInfo = 8862 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 8863 ParmVarDecl *PD = ParmVarDecl::Create( 8864 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 8865 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr); 8866 PD->setScopeInfo(0, I); 8867 PD->setImplicit(); 8868 ParamDecls.push_back(PD); 8869 ProtoLoc.setParam(I, PD); 8870 } 8871 8872 // Set up the new constructor. 8873 DerivedCtor->setAccess(BaseCtor->getAccess()); 8874 DerivedCtor->setParams(ParamDecls); 8875 DerivedCtor->setInheritedConstructor(BaseCtor); 8876 if (BaseCtor->isDeleted()) 8877 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8878 8879 // If this is a constructor template, build the template declaration. 8880 if (TemplateParams) { 8881 FunctionTemplateDecl *DerivedTemplate = 8882 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8883 TemplateParams, DerivedCtor); 8884 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8885 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8886 Derived->addDecl(DerivedTemplate); 8887 } else { 8888 Derived->addDecl(DerivedCtor); 8889 } 8890 8891 Entry.BaseCtor = BaseCtor; 8892 Entry.DerivedCtor = DerivedCtor; 8893 } 8894 8895 Sema &SemaRef; 8896 CXXRecordDecl *Derived; 8897 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8898 MapType Map; 8899 }; 8900 } 8901 8902 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8903 // Defer declaring the inheriting constructors until the class is 8904 // instantiated. 8905 if (ClassDecl->isDependentContext()) 8906 return; 8907 8908 // Find base classes from which we might inherit constructors. 8909 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8910 for (const auto &BaseIt : ClassDecl->bases()) 8911 if (BaseIt.getInheritConstructors()) 8912 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 8913 8914 // Go no further if we're not inheriting any constructors. 8915 if (InheritedBases.empty()) 8916 return; 8917 8918 // Declare the inherited constructors. 8919 InheritingConstructorInfo ICI(*this, ClassDecl); 8920 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8921 ICI.inheritAll(InheritedBases[I]); 8922 } 8923 8924 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8925 CXXConstructorDecl *Constructor) { 8926 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8927 assert(Constructor->getInheritedConstructor() && 8928 !Constructor->doesThisDeclarationHaveABody() && 8929 !Constructor->isDeleted()); 8930 8931 SynthesizedFunctionScope Scope(*this, Constructor); 8932 DiagnosticErrorTrap Trap(Diags); 8933 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8934 Trap.hasErrorOccurred()) { 8935 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8936 << Context.getTagDeclType(ClassDecl); 8937 Constructor->setInvalidDecl(); 8938 return; 8939 } 8940 8941 SourceLocation Loc = Constructor->getLocation(); 8942 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8943 8944 Constructor->markUsed(Context); 8945 MarkVTableUsed(CurrentLocation, ClassDecl); 8946 8947 if (ASTMutationListener *L = getASTMutationListener()) { 8948 L->CompletedImplicitDefinition(Constructor); 8949 } 8950 } 8951 8952 8953 Sema::ImplicitExceptionSpecification 8954 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8955 CXXRecordDecl *ClassDecl = MD->getParent(); 8956 8957 // C++ [except.spec]p14: 8958 // An implicitly declared special member function (Clause 12) shall have 8959 // an exception-specification. 8960 ImplicitExceptionSpecification ExceptSpec(*this); 8961 if (ClassDecl->isInvalidDecl()) 8962 return ExceptSpec; 8963 8964 // Direct base-class destructors. 8965 for (const auto &B : ClassDecl->bases()) { 8966 if (B.isVirtual()) // Handled below. 8967 continue; 8968 8969 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 8970 ExceptSpec.CalledDecl(B.getLocStart(), 8971 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8972 } 8973 8974 // Virtual base-class destructors. 8975 for (const auto &B : ClassDecl->vbases()) { 8976 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 8977 ExceptSpec.CalledDecl(B.getLocStart(), 8978 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8979 } 8980 8981 // Field destructors. 8982 for (const auto *F : ClassDecl->fields()) { 8983 if (const RecordType *RecordTy 8984 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8985 ExceptSpec.CalledDecl(F->getLocation(), 8986 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8987 } 8988 8989 return ExceptSpec; 8990 } 8991 8992 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8993 // C++ [class.dtor]p2: 8994 // If a class has no user-declared destructor, a destructor is 8995 // declared implicitly. An implicitly-declared destructor is an 8996 // inline public member of its class. 8997 assert(ClassDecl->needsImplicitDestructor()); 8998 8999 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 9000 if (DSM.isAlreadyBeingDeclared()) 9001 return nullptr; 9002 9003 // Create the actual destructor declaration. 9004 CanQualType ClassType 9005 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9006 SourceLocation ClassLoc = ClassDecl->getLocation(); 9007 DeclarationName Name 9008 = Context.DeclarationNames.getCXXDestructorName(ClassType); 9009 DeclarationNameInfo NameInfo(Name, ClassLoc); 9010 CXXDestructorDecl *Destructor 9011 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 9012 QualType(), nullptr, /*isInline=*/true, 9013 /*isImplicitlyDeclared=*/true); 9014 Destructor->setAccess(AS_public); 9015 Destructor->setDefaulted(); 9016 9017 if (getLangOpts().CUDA) { 9018 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 9019 Destructor, 9020 /* ConstRHS */ false, 9021 /* Diagnose */ false); 9022 } 9023 9024 // Build an exception specification pointing back at this destructor. 9025 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 9026 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9027 9028 AddOverriddenMethods(ClassDecl, Destructor); 9029 9030 // We don't need to use SpecialMemberIsTrivial here; triviality for 9031 // destructors is easy to compute. 9032 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 9033 9034 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 9035 SetDeclDeleted(Destructor, ClassLoc); 9036 9037 // Note that we have declared this destructor. 9038 ++ASTContext::NumImplicitDestructorsDeclared; 9039 9040 // Introduce this destructor into its scope. 9041 if (Scope *S = getScopeForContext(ClassDecl)) 9042 PushOnScopeChains(Destructor, S, false); 9043 ClassDecl->addDecl(Destructor); 9044 9045 return Destructor; 9046 } 9047 9048 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 9049 CXXDestructorDecl *Destructor) { 9050 assert((Destructor->isDefaulted() && 9051 !Destructor->doesThisDeclarationHaveABody() && 9052 !Destructor->isDeleted()) && 9053 "DefineImplicitDestructor - call it for implicit default dtor"); 9054 CXXRecordDecl *ClassDecl = Destructor->getParent(); 9055 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 9056 9057 if (Destructor->isInvalidDecl()) 9058 return; 9059 9060 SynthesizedFunctionScope Scope(*this, Destructor); 9061 9062 DiagnosticErrorTrap Trap(Diags); 9063 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 9064 Destructor->getParent()); 9065 9066 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 9067 Diag(CurrentLocation, diag::note_member_synthesized_at) 9068 << CXXDestructor << Context.getTagDeclType(ClassDecl); 9069 9070 Destructor->setInvalidDecl(); 9071 return; 9072 } 9073 9074 // The exception specification is needed because we are defining the 9075 // function. 9076 ResolveExceptionSpec(CurrentLocation, 9077 Destructor->getType()->castAs<FunctionProtoType>()); 9078 9079 SourceLocation Loc = Destructor->getLocEnd().isValid() 9080 ? Destructor->getLocEnd() 9081 : Destructor->getLocation(); 9082 Destructor->setBody(new (Context) CompoundStmt(Loc)); 9083 Destructor->markUsed(Context); 9084 MarkVTableUsed(CurrentLocation, ClassDecl); 9085 9086 if (ASTMutationListener *L = getASTMutationListener()) { 9087 L->CompletedImplicitDefinition(Destructor); 9088 } 9089 } 9090 9091 /// \brief Perform any semantic analysis which needs to be delayed until all 9092 /// pending class member declarations have been parsed. 9093 void Sema::ActOnFinishCXXMemberDecls() { 9094 // If the context is an invalid C++ class, just suppress these checks. 9095 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 9096 if (Record->isInvalidDecl()) { 9097 DelayedDefaultedMemberExceptionSpecs.clear(); 9098 DelayedDestructorExceptionSpecChecks.clear(); 9099 return; 9100 } 9101 } 9102 } 9103 9104 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 9105 CXXDestructorDecl *Destructor) { 9106 assert(getLangOpts().CPlusPlus11 && 9107 "adjusting dtor exception specs was introduced in c++11"); 9108 9109 // C++11 [class.dtor]p3: 9110 // A declaration of a destructor that does not have an exception- 9111 // specification is implicitly considered to have the same exception- 9112 // specification as an implicit declaration. 9113 const FunctionProtoType *DtorType = Destructor->getType()-> 9114 getAs<FunctionProtoType>(); 9115 if (DtorType->hasExceptionSpec()) 9116 return; 9117 9118 // Replace the destructor's type, building off the existing one. Fortunately, 9119 // the only thing of interest in the destructor type is its extended info. 9120 // The return and arguments are fixed. 9121 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 9122 EPI.ExceptionSpec.Type = EST_Unevaluated; 9123 EPI.ExceptionSpec.SourceDecl = Destructor; 9124 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 9125 9126 // FIXME: If the destructor has a body that could throw, and the newly created 9127 // spec doesn't allow exceptions, we should emit a warning, because this 9128 // change in behavior can break conforming C++03 programs at runtime. 9129 // However, we don't have a body or an exception specification yet, so it 9130 // needs to be done somewhere else. 9131 } 9132 9133 namespace { 9134 /// \brief An abstract base class for all helper classes used in building the 9135 // copy/move operators. These classes serve as factory functions and help us 9136 // avoid using the same Expr* in the AST twice. 9137 class ExprBuilder { 9138 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION; 9139 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION; 9140 9141 protected: 9142 static Expr *assertNotNull(Expr *E) { 9143 assert(E && "Expression construction must not fail."); 9144 return E; 9145 } 9146 9147 public: 9148 ExprBuilder() {} 9149 virtual ~ExprBuilder() {} 9150 9151 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 9152 }; 9153 9154 class RefBuilder: public ExprBuilder { 9155 VarDecl *Var; 9156 QualType VarType; 9157 9158 public: 9159 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9160 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get()); 9161 } 9162 9163 RefBuilder(VarDecl *Var, QualType VarType) 9164 : Var(Var), VarType(VarType) {} 9165 }; 9166 9167 class ThisBuilder: public ExprBuilder { 9168 public: 9169 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9170 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 9171 } 9172 }; 9173 9174 class CastBuilder: public ExprBuilder { 9175 const ExprBuilder &Builder; 9176 QualType Type; 9177 ExprValueKind Kind; 9178 const CXXCastPath &Path; 9179 9180 public: 9181 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9182 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 9183 CK_UncheckedDerivedToBase, Kind, 9184 &Path).get()); 9185 } 9186 9187 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 9188 const CXXCastPath &Path) 9189 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 9190 }; 9191 9192 class DerefBuilder: public ExprBuilder { 9193 const ExprBuilder &Builder; 9194 9195 public: 9196 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9197 return assertNotNull( 9198 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 9199 } 9200 9201 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9202 }; 9203 9204 class MemberBuilder: public ExprBuilder { 9205 const ExprBuilder &Builder; 9206 QualType Type; 9207 CXXScopeSpec SS; 9208 bool IsArrow; 9209 LookupResult &MemberLookup; 9210 9211 public: 9212 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9213 return assertNotNull(S.BuildMemberReferenceExpr( 9214 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 9215 nullptr, MemberLookup, nullptr).get()); 9216 } 9217 9218 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 9219 LookupResult &MemberLookup) 9220 : Builder(Builder), Type(Type), IsArrow(IsArrow), 9221 MemberLookup(MemberLookup) {} 9222 }; 9223 9224 class MoveCastBuilder: public ExprBuilder { 9225 const ExprBuilder &Builder; 9226 9227 public: 9228 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9229 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 9230 } 9231 9232 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9233 }; 9234 9235 class LvalueConvBuilder: public ExprBuilder { 9236 const ExprBuilder &Builder; 9237 9238 public: 9239 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9240 return assertNotNull( 9241 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 9242 } 9243 9244 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 9245 }; 9246 9247 class SubscriptBuilder: public ExprBuilder { 9248 const ExprBuilder &Base; 9249 const ExprBuilder &Index; 9250 9251 public: 9252 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 9253 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 9254 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 9255 } 9256 9257 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 9258 : Base(Base), Index(Index) {} 9259 }; 9260 9261 } // end anonymous namespace 9262 9263 /// When generating a defaulted copy or move assignment operator, if a field 9264 /// should be copied with __builtin_memcpy rather than via explicit assignments, 9265 /// do so. This optimization only applies for arrays of scalars, and for arrays 9266 /// of class type where the selected copy/move-assignment operator is trivial. 9267 static StmtResult 9268 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 9269 const ExprBuilder &ToB, const ExprBuilder &FromB) { 9270 // Compute the size of the memory buffer to be copied. 9271 QualType SizeType = S.Context.getSizeType(); 9272 llvm::APInt Size(S.Context.getTypeSize(SizeType), 9273 S.Context.getTypeSizeInChars(T).getQuantity()); 9274 9275 // Take the address of the field references for "from" and "to". We 9276 // directly construct UnaryOperators here because semantic analysis 9277 // does not permit us to take the address of an xvalue. 9278 Expr *From = FromB.build(S, Loc); 9279 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 9280 S.Context.getPointerType(From->getType()), 9281 VK_RValue, OK_Ordinary, Loc); 9282 Expr *To = ToB.build(S, Loc); 9283 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 9284 S.Context.getPointerType(To->getType()), 9285 VK_RValue, OK_Ordinary, Loc); 9286 9287 const Type *E = T->getBaseElementTypeUnsafe(); 9288 bool NeedsCollectableMemCpy = 9289 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 9290 9291 // Create a reference to the __builtin_objc_memmove_collectable function 9292 StringRef MemCpyName = NeedsCollectableMemCpy ? 9293 "__builtin_objc_memmove_collectable" : 9294 "__builtin_memcpy"; 9295 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 9296 Sema::LookupOrdinaryName); 9297 S.LookupName(R, S.TUScope, true); 9298 9299 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 9300 if (!MemCpy) 9301 // Something went horribly wrong earlier, and we will have complained 9302 // about it. 9303 return StmtError(); 9304 9305 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 9306 VK_RValue, Loc, nullptr); 9307 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 9308 9309 Expr *CallArgs[] = { 9310 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 9311 }; 9312 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 9313 Loc, CallArgs, Loc); 9314 9315 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 9316 return Call.getAs<Stmt>(); 9317 } 9318 9319 /// \brief Builds a statement that copies/moves the given entity from \p From to 9320 /// \c To. 9321 /// 9322 /// This routine is used to copy/move the members of a class with an 9323 /// implicitly-declared copy/move assignment operator. When the entities being 9324 /// copied are arrays, this routine builds for loops to copy them. 9325 /// 9326 /// \param S The Sema object used for type-checking. 9327 /// 9328 /// \param Loc The location where the implicit copy/move is being generated. 9329 /// 9330 /// \param T The type of the expressions being copied/moved. Both expressions 9331 /// must have this type. 9332 /// 9333 /// \param To The expression we are copying/moving to. 9334 /// 9335 /// \param From The expression we are copying/moving from. 9336 /// 9337 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 9338 /// Otherwise, it's a non-static member subobject. 9339 /// 9340 /// \param Copying Whether we're copying or moving. 9341 /// 9342 /// \param Depth Internal parameter recording the depth of the recursion. 9343 /// 9344 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 9345 /// if a memcpy should be used instead. 9346 static StmtResult 9347 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 9348 const ExprBuilder &To, const ExprBuilder &From, 9349 bool CopyingBaseSubobject, bool Copying, 9350 unsigned Depth = 0) { 9351 // C++11 [class.copy]p28: 9352 // Each subobject is assigned in the manner appropriate to its type: 9353 // 9354 // - if the subobject is of class type, as if by a call to operator= with 9355 // the subobject as the object expression and the corresponding 9356 // subobject of x as a single function argument (as if by explicit 9357 // qualification; that is, ignoring any possible virtual overriding 9358 // functions in more derived classes); 9359 // 9360 // C++03 [class.copy]p13: 9361 // - if the subobject is of class type, the copy assignment operator for 9362 // the class is used (as if by explicit qualification; that is, 9363 // ignoring any possible virtual overriding functions in more derived 9364 // classes); 9365 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9366 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9367 9368 // Look for operator=. 9369 DeclarationName Name 9370 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9371 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9372 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9373 9374 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9375 // operator. 9376 if (!S.getLangOpts().CPlusPlus11) { 9377 LookupResult::Filter F = OpLookup.makeFilter(); 9378 while (F.hasNext()) { 9379 NamedDecl *D = F.next(); 9380 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9381 if (Method->isCopyAssignmentOperator() || 9382 (!Copying && Method->isMoveAssignmentOperator())) 9383 continue; 9384 9385 F.erase(); 9386 } 9387 F.done(); 9388 } 9389 9390 // Suppress the protected check (C++ [class.protected]) for each of the 9391 // assignment operators we found. This strange dance is required when 9392 // we're assigning via a base classes's copy-assignment operator. To 9393 // ensure that we're getting the right base class subobject (without 9394 // ambiguities), we need to cast "this" to that subobject type; to 9395 // ensure that we don't go through the virtual call mechanism, we need 9396 // to qualify the operator= name with the base class (see below). However, 9397 // this means that if the base class has a protected copy assignment 9398 // operator, the protected member access check will fail. So, we 9399 // rewrite "protected" access to "public" access in this case, since we 9400 // know by construction that we're calling from a derived class. 9401 if (CopyingBaseSubobject) { 9402 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9403 L != LEnd; ++L) { 9404 if (L.getAccess() == AS_protected) 9405 L.setAccess(AS_public); 9406 } 9407 } 9408 9409 // Create the nested-name-specifier that will be used to qualify the 9410 // reference to operator=; this is required to suppress the virtual 9411 // call mechanism. 9412 CXXScopeSpec SS; 9413 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9414 SS.MakeTrivial(S.Context, 9415 NestedNameSpecifier::Create(S.Context, nullptr, false, 9416 CanonicalT), 9417 Loc); 9418 9419 // Create the reference to operator=. 9420 ExprResult OpEqualRef 9421 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9422 SS, /*TemplateKWLoc=*/SourceLocation(), 9423 /*FirstQualifierInScope=*/nullptr, 9424 OpLookup, 9425 /*TemplateArgs=*/nullptr, 9426 /*SuppressQualifierCheck=*/true); 9427 if (OpEqualRef.isInvalid()) 9428 return StmtError(); 9429 9430 // Build the call to the assignment operator. 9431 9432 Expr *FromInst = From.build(S, Loc); 9433 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 9434 OpEqualRef.getAs<Expr>(), 9435 Loc, FromInst, Loc); 9436 if (Call.isInvalid()) 9437 return StmtError(); 9438 9439 // If we built a call to a trivial 'operator=' while copying an array, 9440 // bail out. We'll replace the whole shebang with a memcpy. 9441 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9442 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9443 return StmtResult((Stmt*)nullptr); 9444 9445 // Convert to an expression-statement, and clean up any produced 9446 // temporaries. 9447 return S.ActOnExprStmt(Call); 9448 } 9449 9450 // - if the subobject is of scalar type, the built-in assignment 9451 // operator is used. 9452 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9453 if (!ArrayTy) { 9454 ExprResult Assignment = S.CreateBuiltinBinOp( 9455 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9456 if (Assignment.isInvalid()) 9457 return StmtError(); 9458 return S.ActOnExprStmt(Assignment); 9459 } 9460 9461 // - if the subobject is an array, each element is assigned, in the 9462 // manner appropriate to the element type; 9463 9464 // Construct a loop over the array bounds, e.g., 9465 // 9466 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9467 // 9468 // that will copy each of the array elements. 9469 QualType SizeType = S.Context.getSizeType(); 9470 9471 // Create the iteration variable. 9472 IdentifierInfo *IterationVarName = nullptr; 9473 { 9474 SmallString<8> Str; 9475 llvm::raw_svector_ostream OS(Str); 9476 OS << "__i" << Depth; 9477 IterationVarName = &S.Context.Idents.get(OS.str()); 9478 } 9479 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9480 IterationVarName, SizeType, 9481 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9482 SC_None); 9483 9484 // Initialize the iteration variable to zero. 9485 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9486 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9487 9488 // Creates a reference to the iteration variable. 9489 RefBuilder IterationVarRef(IterationVar, SizeType); 9490 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9491 9492 // Create the DeclStmt that holds the iteration variable. 9493 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9494 9495 // Subscript the "from" and "to" expressions with the iteration variable. 9496 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9497 MoveCastBuilder FromIndexMove(FromIndexCopy); 9498 const ExprBuilder *FromIndex; 9499 if (Copying) 9500 FromIndex = &FromIndexCopy; 9501 else 9502 FromIndex = &FromIndexMove; 9503 9504 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9505 9506 // Build the copy/move for an individual element of the array. 9507 StmtResult Copy = 9508 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9509 ToIndex, *FromIndex, CopyingBaseSubobject, 9510 Copying, Depth + 1); 9511 // Bail out if copying fails or if we determined that we should use memcpy. 9512 if (Copy.isInvalid() || !Copy.get()) 9513 return Copy; 9514 9515 // Create the comparison against the array bound. 9516 llvm::APInt Upper 9517 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9518 Expr *Comparison 9519 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9520 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9521 BO_NE, S.Context.BoolTy, 9522 VK_RValue, OK_Ordinary, Loc, false); 9523 9524 // Create the pre-increment of the iteration variable. 9525 Expr *Increment 9526 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9527 SizeType, VK_LValue, OK_Ordinary, Loc); 9528 9529 // Construct the loop that copies all elements of this array. 9530 return S.ActOnForStmt(Loc, Loc, InitStmt, 9531 S.MakeFullExpr(Comparison), 9532 nullptr, S.MakeFullDiscardedValueExpr(Increment), 9533 Loc, Copy.get()); 9534 } 9535 9536 static StmtResult 9537 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9538 const ExprBuilder &To, const ExprBuilder &From, 9539 bool CopyingBaseSubobject, bool Copying) { 9540 // Maybe we should use a memcpy? 9541 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9542 T.isTriviallyCopyableType(S.Context)) 9543 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9544 9545 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9546 CopyingBaseSubobject, 9547 Copying, 0)); 9548 9549 // If we ended up picking a trivial assignment operator for an array of a 9550 // non-trivially-copyable class type, just emit a memcpy. 9551 if (!Result.isInvalid() && !Result.get()) 9552 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9553 9554 return Result; 9555 } 9556 9557 Sema::ImplicitExceptionSpecification 9558 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9559 CXXRecordDecl *ClassDecl = MD->getParent(); 9560 9561 ImplicitExceptionSpecification ExceptSpec(*this); 9562 if (ClassDecl->isInvalidDecl()) 9563 return ExceptSpec; 9564 9565 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9566 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9567 unsigned ArgQuals = 9568 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9569 9570 // C++ [except.spec]p14: 9571 // An implicitly declared special member function (Clause 12) shall have an 9572 // exception-specification. [...] 9573 9574 // It is unspecified whether or not an implicit copy assignment operator 9575 // attempts to deduplicate calls to assignment operators of virtual bases are 9576 // made. As such, this exception specification is effectively unspecified. 9577 // Based on a similar decision made for constness in C++0x, we're erring on 9578 // the side of assuming such calls to be made regardless of whether they 9579 // actually happen. 9580 for (const auto &Base : ClassDecl->bases()) { 9581 if (Base.isVirtual()) 9582 continue; 9583 9584 CXXRecordDecl *BaseClassDecl 9585 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9586 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9587 ArgQuals, false, 0)) 9588 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9589 } 9590 9591 for (const auto &Base : ClassDecl->vbases()) { 9592 CXXRecordDecl *BaseClassDecl 9593 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9594 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9595 ArgQuals, false, 0)) 9596 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9597 } 9598 9599 for (const auto *Field : ClassDecl->fields()) { 9600 QualType FieldType = Context.getBaseElementType(Field->getType()); 9601 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9602 if (CXXMethodDecl *CopyAssign = 9603 LookupCopyingAssignment(FieldClassDecl, 9604 ArgQuals | FieldType.getCVRQualifiers(), 9605 false, 0)) 9606 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9607 } 9608 } 9609 9610 return ExceptSpec; 9611 } 9612 9613 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9614 // Note: The following rules are largely analoguous to the copy 9615 // constructor rules. Note that virtual bases are not taken into account 9616 // for determining the argument type of the operator. Note also that 9617 // operators taking an object instead of a reference are allowed. 9618 assert(ClassDecl->needsImplicitCopyAssignment()); 9619 9620 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9621 if (DSM.isAlreadyBeingDeclared()) 9622 return nullptr; 9623 9624 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9625 QualType RetType = Context.getLValueReferenceType(ArgType); 9626 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9627 if (Const) 9628 ArgType = ArgType.withConst(); 9629 ArgType = Context.getLValueReferenceType(ArgType); 9630 9631 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9632 CXXCopyAssignment, 9633 Const); 9634 9635 // An implicitly-declared copy assignment operator is an inline public 9636 // member of its class. 9637 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9638 SourceLocation ClassLoc = ClassDecl->getLocation(); 9639 DeclarationNameInfo NameInfo(Name, ClassLoc); 9640 CXXMethodDecl *CopyAssignment = 9641 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9642 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 9643 /*isInline=*/true, Constexpr, SourceLocation()); 9644 CopyAssignment->setAccess(AS_public); 9645 CopyAssignment->setDefaulted(); 9646 CopyAssignment->setImplicit(); 9647 9648 if (getLangOpts().CUDA) { 9649 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 9650 CopyAssignment, 9651 /* ConstRHS */ Const, 9652 /* Diagnose */ false); 9653 } 9654 9655 // Build an exception specification pointing back at this member. 9656 FunctionProtoType::ExtProtoInfo EPI = 9657 getImplicitMethodEPI(*this, CopyAssignment); 9658 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9659 9660 // Add the parameter to the operator. 9661 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9662 ClassLoc, ClassLoc, 9663 /*Id=*/nullptr, ArgType, 9664 /*TInfo=*/nullptr, SC_None, 9665 nullptr); 9666 CopyAssignment->setParams(FromParam); 9667 9668 AddOverriddenMethods(ClassDecl, CopyAssignment); 9669 9670 CopyAssignment->setTrivial( 9671 ClassDecl->needsOverloadResolutionForCopyAssignment() 9672 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9673 : ClassDecl->hasTrivialCopyAssignment()); 9674 9675 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9676 SetDeclDeleted(CopyAssignment, ClassLoc); 9677 9678 // Note that we have added this copy-assignment operator. 9679 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9680 9681 if (Scope *S = getScopeForContext(ClassDecl)) 9682 PushOnScopeChains(CopyAssignment, S, false); 9683 ClassDecl->addDecl(CopyAssignment); 9684 9685 return CopyAssignment; 9686 } 9687 9688 /// Diagnose an implicit copy operation for a class which is odr-used, but 9689 /// which is deprecated because the class has a user-declared copy constructor, 9690 /// copy assignment operator, or destructor. 9691 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 9692 SourceLocation UseLoc) { 9693 assert(CopyOp->isImplicit()); 9694 9695 CXXRecordDecl *RD = CopyOp->getParent(); 9696 CXXMethodDecl *UserDeclaredOperation = nullptr; 9697 9698 // In Microsoft mode, assignment operations don't affect constructors and 9699 // vice versa. 9700 if (RD->hasUserDeclaredDestructor()) { 9701 UserDeclaredOperation = RD->getDestructor(); 9702 } else if (!isa<CXXConstructorDecl>(CopyOp) && 9703 RD->hasUserDeclaredCopyConstructor() && 9704 !S.getLangOpts().MSVCCompat) { 9705 // Find any user-declared copy constructor. 9706 for (auto *I : RD->ctors()) { 9707 if (I->isCopyConstructor()) { 9708 UserDeclaredOperation = I; 9709 break; 9710 } 9711 } 9712 assert(UserDeclaredOperation); 9713 } else if (isa<CXXConstructorDecl>(CopyOp) && 9714 RD->hasUserDeclaredCopyAssignment() && 9715 !S.getLangOpts().MSVCCompat) { 9716 // Find any user-declared move assignment operator. 9717 for (auto *I : RD->methods()) { 9718 if (I->isCopyAssignmentOperator()) { 9719 UserDeclaredOperation = I; 9720 break; 9721 } 9722 } 9723 assert(UserDeclaredOperation); 9724 } 9725 9726 if (UserDeclaredOperation) { 9727 S.Diag(UserDeclaredOperation->getLocation(), 9728 diag::warn_deprecated_copy_operation) 9729 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 9730 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 9731 S.Diag(UseLoc, diag::note_member_synthesized_at) 9732 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 9733 : Sema::CXXCopyAssignment) 9734 << RD; 9735 } 9736 } 9737 9738 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 9739 CXXMethodDecl *CopyAssignOperator) { 9740 assert((CopyAssignOperator->isDefaulted() && 9741 CopyAssignOperator->isOverloadedOperator() && 9742 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 9743 !CopyAssignOperator->doesThisDeclarationHaveABody() && 9744 !CopyAssignOperator->isDeleted()) && 9745 "DefineImplicitCopyAssignment called for wrong function"); 9746 9747 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 9748 9749 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 9750 CopyAssignOperator->setInvalidDecl(); 9751 return; 9752 } 9753 9754 // C++11 [class.copy]p18: 9755 // The [definition of an implicitly declared copy assignment operator] is 9756 // deprecated if the class has a user-declared copy constructor or a 9757 // user-declared destructor. 9758 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 9759 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 9760 9761 CopyAssignOperator->markUsed(Context); 9762 9763 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 9764 DiagnosticErrorTrap Trap(Diags); 9765 9766 // C++0x [class.copy]p30: 9767 // The implicitly-defined or explicitly-defaulted copy assignment operator 9768 // for a non-union class X performs memberwise copy assignment of its 9769 // subobjects. The direct base classes of X are assigned first, in the 9770 // order of their declaration in the base-specifier-list, and then the 9771 // immediate non-static data members of X are assigned, in the order in 9772 // which they were declared in the class definition. 9773 9774 // The statements that form the synthesized function body. 9775 SmallVector<Stmt*, 8> Statements; 9776 9777 // The parameter for the "other" object, which we are copying from. 9778 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 9779 Qualifiers OtherQuals = Other->getType().getQualifiers(); 9780 QualType OtherRefType = Other->getType(); 9781 if (const LValueReferenceType *OtherRef 9782 = OtherRefType->getAs<LValueReferenceType>()) { 9783 OtherRefType = OtherRef->getPointeeType(); 9784 OtherQuals = OtherRefType.getQualifiers(); 9785 } 9786 9787 // Our location for everything implicitly-generated. 9788 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid() 9789 ? CopyAssignOperator->getLocEnd() 9790 : CopyAssignOperator->getLocation(); 9791 9792 // Builds a DeclRefExpr for the "other" object. 9793 RefBuilder OtherRef(Other, OtherRefType); 9794 9795 // Builds the "this" pointer. 9796 ThisBuilder This; 9797 9798 // Assign base classes. 9799 bool Invalid = false; 9800 for (auto &Base : ClassDecl->bases()) { 9801 // Form the assignment: 9802 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 9803 QualType BaseType = Base.getType().getUnqualifiedType(); 9804 if (!BaseType->isRecordType()) { 9805 Invalid = true; 9806 continue; 9807 } 9808 9809 CXXCastPath BasePath; 9810 BasePath.push_back(&Base); 9811 9812 // Construct the "from" expression, which is an implicit cast to the 9813 // appropriately-qualified base type. 9814 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 9815 VK_LValue, BasePath); 9816 9817 // Dereference "this". 9818 DerefBuilder DerefThis(This); 9819 CastBuilder To(DerefThis, 9820 Context.getCVRQualifiedType( 9821 BaseType, CopyAssignOperator->getTypeQualifiers()), 9822 VK_LValue, BasePath); 9823 9824 // Build the copy. 9825 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 9826 To, From, 9827 /*CopyingBaseSubobject=*/true, 9828 /*Copying=*/true); 9829 if (Copy.isInvalid()) { 9830 Diag(CurrentLocation, diag::note_member_synthesized_at) 9831 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9832 CopyAssignOperator->setInvalidDecl(); 9833 return; 9834 } 9835 9836 // Success! Record the copy. 9837 Statements.push_back(Copy.getAs<Expr>()); 9838 } 9839 9840 // Assign non-static members. 9841 for (auto *Field : ClassDecl->fields()) { 9842 if (Field->isUnnamedBitfield()) 9843 continue; 9844 9845 if (Field->isInvalidDecl()) { 9846 Invalid = true; 9847 continue; 9848 } 9849 9850 // Check for members of reference type; we can't copy those. 9851 if (Field->getType()->isReferenceType()) { 9852 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9853 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9854 Diag(Field->getLocation(), diag::note_declared_at); 9855 Diag(CurrentLocation, diag::note_member_synthesized_at) 9856 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9857 Invalid = true; 9858 continue; 9859 } 9860 9861 // Check for members of const-qualified, non-class type. 9862 QualType BaseType = Context.getBaseElementType(Field->getType()); 9863 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9864 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9865 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9866 Diag(Field->getLocation(), diag::note_declared_at); 9867 Diag(CurrentLocation, diag::note_member_synthesized_at) 9868 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9869 Invalid = true; 9870 continue; 9871 } 9872 9873 // Suppress assigning zero-width bitfields. 9874 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9875 continue; 9876 9877 QualType FieldType = Field->getType().getNonReferenceType(); 9878 if (FieldType->isIncompleteArrayType()) { 9879 assert(ClassDecl->hasFlexibleArrayMember() && 9880 "Incomplete array type is not valid"); 9881 continue; 9882 } 9883 9884 // Build references to the field in the object we're copying from and to. 9885 CXXScopeSpec SS; // Intentionally empty 9886 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9887 LookupMemberName); 9888 MemberLookup.addDecl(Field); 9889 MemberLookup.resolveKind(); 9890 9891 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 9892 9893 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 9894 9895 // Build the copy of this field. 9896 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 9897 To, From, 9898 /*CopyingBaseSubobject=*/false, 9899 /*Copying=*/true); 9900 if (Copy.isInvalid()) { 9901 Diag(CurrentLocation, diag::note_member_synthesized_at) 9902 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9903 CopyAssignOperator->setInvalidDecl(); 9904 return; 9905 } 9906 9907 // Success! Record the copy. 9908 Statements.push_back(Copy.getAs<Stmt>()); 9909 } 9910 9911 if (!Invalid) { 9912 // Add a "return *this;" 9913 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9914 9915 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 9916 if (Return.isInvalid()) 9917 Invalid = true; 9918 else { 9919 Statements.push_back(Return.getAs<Stmt>()); 9920 9921 if (Trap.hasErrorOccurred()) { 9922 Diag(CurrentLocation, diag::note_member_synthesized_at) 9923 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9924 Invalid = true; 9925 } 9926 } 9927 } 9928 9929 // The exception specification is needed because we are defining the 9930 // function. 9931 ResolveExceptionSpec(CurrentLocation, 9932 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 9933 9934 if (Invalid) { 9935 CopyAssignOperator->setInvalidDecl(); 9936 return; 9937 } 9938 9939 StmtResult Body; 9940 { 9941 CompoundScopeRAII CompoundScope(*this); 9942 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9943 /*isStmtExpr=*/false); 9944 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9945 } 9946 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 9947 9948 if (ASTMutationListener *L = getASTMutationListener()) { 9949 L->CompletedImplicitDefinition(CopyAssignOperator); 9950 } 9951 } 9952 9953 Sema::ImplicitExceptionSpecification 9954 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9955 CXXRecordDecl *ClassDecl = MD->getParent(); 9956 9957 ImplicitExceptionSpecification ExceptSpec(*this); 9958 if (ClassDecl->isInvalidDecl()) 9959 return ExceptSpec; 9960 9961 // C++0x [except.spec]p14: 9962 // An implicitly declared special member function (Clause 12) shall have an 9963 // exception-specification. [...] 9964 9965 // It is unspecified whether or not an implicit move assignment operator 9966 // attempts to deduplicate calls to assignment operators of virtual bases are 9967 // made. As such, this exception specification is effectively unspecified. 9968 // Based on a similar decision made for constness in C++0x, we're erring on 9969 // the side of assuming such calls to be made regardless of whether they 9970 // actually happen. 9971 // Note that a move constructor is not implicitly declared when there are 9972 // virtual bases, but it can still be user-declared and explicitly defaulted. 9973 for (const auto &Base : ClassDecl->bases()) { 9974 if (Base.isVirtual()) 9975 continue; 9976 9977 CXXRecordDecl *BaseClassDecl 9978 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9979 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9980 0, false, 0)) 9981 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 9982 } 9983 9984 for (const auto &Base : ClassDecl->vbases()) { 9985 CXXRecordDecl *BaseClassDecl 9986 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9987 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9988 0, false, 0)) 9989 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 9990 } 9991 9992 for (const auto *Field : ClassDecl->fields()) { 9993 QualType FieldType = Context.getBaseElementType(Field->getType()); 9994 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9995 if (CXXMethodDecl *MoveAssign = 9996 LookupMovingAssignment(FieldClassDecl, 9997 FieldType.getCVRQualifiers(), 9998 false, 0)) 9999 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 10000 } 10001 } 10002 10003 return ExceptSpec; 10004 } 10005 10006 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 10007 assert(ClassDecl->needsImplicitMoveAssignment()); 10008 10009 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 10010 if (DSM.isAlreadyBeingDeclared()) 10011 return nullptr; 10012 10013 // Note: The following rules are largely analoguous to the move 10014 // constructor rules. 10015 10016 QualType ArgType = Context.getTypeDeclType(ClassDecl); 10017 QualType RetType = Context.getLValueReferenceType(ArgType); 10018 ArgType = Context.getRValueReferenceType(ArgType); 10019 10020 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10021 CXXMoveAssignment, 10022 false); 10023 10024 // An implicitly-declared move assignment operator is an inline public 10025 // member of its class. 10026 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 10027 SourceLocation ClassLoc = ClassDecl->getLocation(); 10028 DeclarationNameInfo NameInfo(Name, ClassLoc); 10029 CXXMethodDecl *MoveAssignment = 10030 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 10031 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 10032 /*isInline=*/true, Constexpr, SourceLocation()); 10033 MoveAssignment->setAccess(AS_public); 10034 MoveAssignment->setDefaulted(); 10035 MoveAssignment->setImplicit(); 10036 10037 if (getLangOpts().CUDA) { 10038 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 10039 MoveAssignment, 10040 /* ConstRHS */ false, 10041 /* Diagnose */ false); 10042 } 10043 10044 // Build an exception specification pointing back at this member. 10045 FunctionProtoType::ExtProtoInfo EPI = 10046 getImplicitMethodEPI(*this, MoveAssignment); 10047 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 10048 10049 // Add the parameter to the operator. 10050 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 10051 ClassLoc, ClassLoc, 10052 /*Id=*/nullptr, ArgType, 10053 /*TInfo=*/nullptr, SC_None, 10054 nullptr); 10055 MoveAssignment->setParams(FromParam); 10056 10057 AddOverriddenMethods(ClassDecl, MoveAssignment); 10058 10059 MoveAssignment->setTrivial( 10060 ClassDecl->needsOverloadResolutionForMoveAssignment() 10061 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 10062 : ClassDecl->hasTrivialMoveAssignment()); 10063 10064 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 10065 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 10066 SetDeclDeleted(MoveAssignment, ClassLoc); 10067 } 10068 10069 // Note that we have added this copy-assignment operator. 10070 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 10071 10072 if (Scope *S = getScopeForContext(ClassDecl)) 10073 PushOnScopeChains(MoveAssignment, S, false); 10074 ClassDecl->addDecl(MoveAssignment); 10075 10076 return MoveAssignment; 10077 } 10078 10079 /// Check if we're implicitly defining a move assignment operator for a class 10080 /// with virtual bases. Such a move assignment might move-assign the virtual 10081 /// base multiple times. 10082 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 10083 SourceLocation CurrentLocation) { 10084 assert(!Class->isDependentContext() && "should not define dependent move"); 10085 10086 // Only a virtual base could get implicitly move-assigned multiple times. 10087 // Only a non-trivial move assignment can observe this. We only want to 10088 // diagnose if we implicitly define an assignment operator that assigns 10089 // two base classes, both of which move-assign the same virtual base. 10090 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 10091 Class->getNumBases() < 2) 10092 return; 10093 10094 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 10095 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 10096 VBaseMap VBases; 10097 10098 for (auto &BI : Class->bases()) { 10099 Worklist.push_back(&BI); 10100 while (!Worklist.empty()) { 10101 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 10102 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 10103 10104 // If the base has no non-trivial move assignment operators, 10105 // we don't care about moves from it. 10106 if (!Base->hasNonTrivialMoveAssignment()) 10107 continue; 10108 10109 // If there's nothing virtual here, skip it. 10110 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 10111 continue; 10112 10113 // If we're not actually going to call a move assignment for this base, 10114 // or the selected move assignment is trivial, skip it. 10115 Sema::SpecialMemberOverloadResult *SMOR = 10116 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 10117 /*ConstArg*/false, /*VolatileArg*/false, 10118 /*RValueThis*/true, /*ConstThis*/false, 10119 /*VolatileThis*/false); 10120 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 10121 !SMOR->getMethod()->isMoveAssignmentOperator()) 10122 continue; 10123 10124 if (BaseSpec->isVirtual()) { 10125 // We're going to move-assign this virtual base, and its move 10126 // assignment operator is not trivial. If this can happen for 10127 // multiple distinct direct bases of Class, diagnose it. (If it 10128 // only happens in one base, we'll diagnose it when synthesizing 10129 // that base class's move assignment operator.) 10130 CXXBaseSpecifier *&Existing = 10131 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 10132 .first->second; 10133 if (Existing && Existing != &BI) { 10134 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 10135 << Class << Base; 10136 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 10137 << (Base->getCanonicalDecl() == 10138 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10139 << Base << Existing->getType() << Existing->getSourceRange(); 10140 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 10141 << (Base->getCanonicalDecl() == 10142 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 10143 << Base << BI.getType() << BaseSpec->getSourceRange(); 10144 10145 // Only diagnose each vbase once. 10146 Existing = nullptr; 10147 } 10148 } else { 10149 // Only walk over bases that have defaulted move assignment operators. 10150 // We assume that any user-provided move assignment operator handles 10151 // the multiple-moves-of-vbase case itself somehow. 10152 if (!SMOR->getMethod()->isDefaulted()) 10153 continue; 10154 10155 // We're going to move the base classes of Base. Add them to the list. 10156 for (auto &BI : Base->bases()) 10157 Worklist.push_back(&BI); 10158 } 10159 } 10160 } 10161 } 10162 10163 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 10164 CXXMethodDecl *MoveAssignOperator) { 10165 assert((MoveAssignOperator->isDefaulted() && 10166 MoveAssignOperator->isOverloadedOperator() && 10167 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 10168 !MoveAssignOperator->doesThisDeclarationHaveABody() && 10169 !MoveAssignOperator->isDeleted()) && 10170 "DefineImplicitMoveAssignment called for wrong function"); 10171 10172 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 10173 10174 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 10175 MoveAssignOperator->setInvalidDecl(); 10176 return; 10177 } 10178 10179 MoveAssignOperator->markUsed(Context); 10180 10181 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 10182 DiagnosticErrorTrap Trap(Diags); 10183 10184 // C++0x [class.copy]p28: 10185 // The implicitly-defined or move assignment operator for a non-union class 10186 // X performs memberwise move assignment of its subobjects. The direct base 10187 // classes of X are assigned first, in the order of their declaration in the 10188 // base-specifier-list, and then the immediate non-static data members of X 10189 // are assigned, in the order in which they were declared in the class 10190 // definition. 10191 10192 // Issue a warning if our implicit move assignment operator will move 10193 // from a virtual base more than once. 10194 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 10195 10196 // The statements that form the synthesized function body. 10197 SmallVector<Stmt*, 8> Statements; 10198 10199 // The parameter for the "other" object, which we are move from. 10200 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 10201 QualType OtherRefType = Other->getType()-> 10202 getAs<RValueReferenceType>()->getPointeeType(); 10203 assert(!OtherRefType.getQualifiers() && 10204 "Bad argument type of defaulted move assignment"); 10205 10206 // Our location for everything implicitly-generated. 10207 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid() 10208 ? MoveAssignOperator->getLocEnd() 10209 : MoveAssignOperator->getLocation(); 10210 10211 // Builds a reference to the "other" object. 10212 RefBuilder OtherRef(Other, OtherRefType); 10213 // Cast to rvalue. 10214 MoveCastBuilder MoveOther(OtherRef); 10215 10216 // Builds the "this" pointer. 10217 ThisBuilder This; 10218 10219 // Assign base classes. 10220 bool Invalid = false; 10221 for (auto &Base : ClassDecl->bases()) { 10222 // C++11 [class.copy]p28: 10223 // It is unspecified whether subobjects representing virtual base classes 10224 // are assigned more than once by the implicitly-defined copy assignment 10225 // operator. 10226 // FIXME: Do not assign to a vbase that will be assigned by some other base 10227 // class. For a move-assignment, this can result in the vbase being moved 10228 // multiple times. 10229 10230 // Form the assignment: 10231 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 10232 QualType BaseType = Base.getType().getUnqualifiedType(); 10233 if (!BaseType->isRecordType()) { 10234 Invalid = true; 10235 continue; 10236 } 10237 10238 CXXCastPath BasePath; 10239 BasePath.push_back(&Base); 10240 10241 // Construct the "from" expression, which is an implicit cast to the 10242 // appropriately-qualified base type. 10243 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 10244 10245 // Dereference "this". 10246 DerefBuilder DerefThis(This); 10247 10248 // Implicitly cast "this" to the appropriately-qualified base type. 10249 CastBuilder To(DerefThis, 10250 Context.getCVRQualifiedType( 10251 BaseType, MoveAssignOperator->getTypeQualifiers()), 10252 VK_LValue, BasePath); 10253 10254 // Build the move. 10255 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 10256 To, From, 10257 /*CopyingBaseSubobject=*/true, 10258 /*Copying=*/false); 10259 if (Move.isInvalid()) { 10260 Diag(CurrentLocation, diag::note_member_synthesized_at) 10261 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10262 MoveAssignOperator->setInvalidDecl(); 10263 return; 10264 } 10265 10266 // Success! Record the move. 10267 Statements.push_back(Move.getAs<Expr>()); 10268 } 10269 10270 // Assign non-static members. 10271 for (auto *Field : ClassDecl->fields()) { 10272 if (Field->isUnnamedBitfield()) 10273 continue; 10274 10275 if (Field->isInvalidDecl()) { 10276 Invalid = true; 10277 continue; 10278 } 10279 10280 // Check for members of reference type; we can't move those. 10281 if (Field->getType()->isReferenceType()) { 10282 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10283 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 10284 Diag(Field->getLocation(), diag::note_declared_at); 10285 Diag(CurrentLocation, diag::note_member_synthesized_at) 10286 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10287 Invalid = true; 10288 continue; 10289 } 10290 10291 // Check for members of const-qualified, non-class type. 10292 QualType BaseType = Context.getBaseElementType(Field->getType()); 10293 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 10294 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 10295 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 10296 Diag(Field->getLocation(), diag::note_declared_at); 10297 Diag(CurrentLocation, diag::note_member_synthesized_at) 10298 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10299 Invalid = true; 10300 continue; 10301 } 10302 10303 // Suppress assigning zero-width bitfields. 10304 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 10305 continue; 10306 10307 QualType FieldType = Field->getType().getNonReferenceType(); 10308 if (FieldType->isIncompleteArrayType()) { 10309 assert(ClassDecl->hasFlexibleArrayMember() && 10310 "Incomplete array type is not valid"); 10311 continue; 10312 } 10313 10314 // Build references to the field in the object we're copying from and to. 10315 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 10316 LookupMemberName); 10317 MemberLookup.addDecl(Field); 10318 MemberLookup.resolveKind(); 10319 MemberBuilder From(MoveOther, OtherRefType, 10320 /*IsArrow=*/false, MemberLookup); 10321 MemberBuilder To(This, getCurrentThisType(), 10322 /*IsArrow=*/true, MemberLookup); 10323 10324 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 10325 "Member reference with rvalue base must be rvalue except for reference " 10326 "members, which aren't allowed for move assignment."); 10327 10328 // Build the move of this field. 10329 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10330 To, From, 10331 /*CopyingBaseSubobject=*/false, 10332 /*Copying=*/false); 10333 if (Move.isInvalid()) { 10334 Diag(CurrentLocation, diag::note_member_synthesized_at) 10335 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10336 MoveAssignOperator->setInvalidDecl(); 10337 return; 10338 } 10339 10340 // Success! Record the copy. 10341 Statements.push_back(Move.getAs<Stmt>()); 10342 } 10343 10344 if (!Invalid) { 10345 // Add a "return *this;" 10346 ExprResult ThisObj = 10347 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10348 10349 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 10350 if (Return.isInvalid()) 10351 Invalid = true; 10352 else { 10353 Statements.push_back(Return.getAs<Stmt>()); 10354 10355 if (Trap.hasErrorOccurred()) { 10356 Diag(CurrentLocation, diag::note_member_synthesized_at) 10357 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10358 Invalid = true; 10359 } 10360 } 10361 } 10362 10363 // The exception specification is needed because we are defining the 10364 // function. 10365 ResolveExceptionSpec(CurrentLocation, 10366 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 10367 10368 if (Invalid) { 10369 MoveAssignOperator->setInvalidDecl(); 10370 return; 10371 } 10372 10373 StmtResult Body; 10374 { 10375 CompoundScopeRAII CompoundScope(*this); 10376 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10377 /*isStmtExpr=*/false); 10378 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10379 } 10380 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 10381 10382 if (ASTMutationListener *L = getASTMutationListener()) { 10383 L->CompletedImplicitDefinition(MoveAssignOperator); 10384 } 10385 } 10386 10387 Sema::ImplicitExceptionSpecification 10388 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10389 CXXRecordDecl *ClassDecl = MD->getParent(); 10390 10391 ImplicitExceptionSpecification ExceptSpec(*this); 10392 if (ClassDecl->isInvalidDecl()) 10393 return ExceptSpec; 10394 10395 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10396 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10397 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10398 10399 // C++ [except.spec]p14: 10400 // An implicitly declared special member function (Clause 12) shall have an 10401 // exception-specification. [...] 10402 for (const auto &Base : ClassDecl->bases()) { 10403 // Virtual bases are handled below. 10404 if (Base.isVirtual()) 10405 continue; 10406 10407 CXXRecordDecl *BaseClassDecl 10408 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10409 if (CXXConstructorDecl *CopyConstructor = 10410 LookupCopyingConstructor(BaseClassDecl, Quals)) 10411 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10412 } 10413 for (const auto &Base : ClassDecl->vbases()) { 10414 CXXRecordDecl *BaseClassDecl 10415 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10416 if (CXXConstructorDecl *CopyConstructor = 10417 LookupCopyingConstructor(BaseClassDecl, Quals)) 10418 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10419 } 10420 for (const auto *Field : ClassDecl->fields()) { 10421 QualType FieldType = Context.getBaseElementType(Field->getType()); 10422 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10423 if (CXXConstructorDecl *CopyConstructor = 10424 LookupCopyingConstructor(FieldClassDecl, 10425 Quals | FieldType.getCVRQualifiers())) 10426 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10427 } 10428 } 10429 10430 return ExceptSpec; 10431 } 10432 10433 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10434 CXXRecordDecl *ClassDecl) { 10435 // C++ [class.copy]p4: 10436 // If the class definition does not explicitly declare a copy 10437 // constructor, one is declared implicitly. 10438 assert(ClassDecl->needsImplicitCopyConstructor()); 10439 10440 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10441 if (DSM.isAlreadyBeingDeclared()) 10442 return nullptr; 10443 10444 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10445 QualType ArgType = ClassType; 10446 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10447 if (Const) 10448 ArgType = ArgType.withConst(); 10449 ArgType = Context.getLValueReferenceType(ArgType); 10450 10451 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10452 CXXCopyConstructor, 10453 Const); 10454 10455 DeclarationName Name 10456 = Context.DeclarationNames.getCXXConstructorName( 10457 Context.getCanonicalType(ClassType)); 10458 SourceLocation ClassLoc = ClassDecl->getLocation(); 10459 DeclarationNameInfo NameInfo(Name, ClassLoc); 10460 10461 // An implicitly-declared copy constructor is an inline public 10462 // member of its class. 10463 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10464 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10465 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10466 Constexpr); 10467 CopyConstructor->setAccess(AS_public); 10468 CopyConstructor->setDefaulted(); 10469 10470 if (getLangOpts().CUDA) { 10471 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 10472 CopyConstructor, 10473 /* ConstRHS */ Const, 10474 /* Diagnose */ false); 10475 } 10476 10477 // Build an exception specification pointing back at this member. 10478 FunctionProtoType::ExtProtoInfo EPI = 10479 getImplicitMethodEPI(*this, CopyConstructor); 10480 CopyConstructor->setType( 10481 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10482 10483 // Add the parameter to the constructor. 10484 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10485 ClassLoc, ClassLoc, 10486 /*IdentifierInfo=*/nullptr, 10487 ArgType, /*TInfo=*/nullptr, 10488 SC_None, nullptr); 10489 CopyConstructor->setParams(FromParam); 10490 10491 CopyConstructor->setTrivial( 10492 ClassDecl->needsOverloadResolutionForCopyConstructor() 10493 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10494 : ClassDecl->hasTrivialCopyConstructor()); 10495 10496 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10497 SetDeclDeleted(CopyConstructor, ClassLoc); 10498 10499 // Note that we have declared this constructor. 10500 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10501 10502 if (Scope *S = getScopeForContext(ClassDecl)) 10503 PushOnScopeChains(CopyConstructor, S, false); 10504 ClassDecl->addDecl(CopyConstructor); 10505 10506 return CopyConstructor; 10507 } 10508 10509 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10510 CXXConstructorDecl *CopyConstructor) { 10511 assert((CopyConstructor->isDefaulted() && 10512 CopyConstructor->isCopyConstructor() && 10513 !CopyConstructor->doesThisDeclarationHaveABody() && 10514 !CopyConstructor->isDeleted()) && 10515 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10516 10517 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10518 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10519 10520 // C++11 [class.copy]p7: 10521 // The [definition of an implicitly declared copy constructor] is 10522 // deprecated if the class has a user-declared copy assignment operator 10523 // or a user-declared destructor. 10524 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10525 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10526 10527 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10528 DiagnosticErrorTrap Trap(Diags); 10529 10530 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10531 Trap.hasErrorOccurred()) { 10532 Diag(CurrentLocation, diag::note_member_synthesized_at) 10533 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10534 CopyConstructor->setInvalidDecl(); 10535 } else { 10536 SourceLocation Loc = CopyConstructor->getLocEnd().isValid() 10537 ? CopyConstructor->getLocEnd() 10538 : CopyConstructor->getLocation(); 10539 Sema::CompoundScopeRAII CompoundScope(*this); 10540 CopyConstructor->setBody( 10541 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 10542 } 10543 10544 // The exception specification is needed because we are defining the 10545 // function. 10546 ResolveExceptionSpec(CurrentLocation, 10547 CopyConstructor->getType()->castAs<FunctionProtoType>()); 10548 10549 CopyConstructor->markUsed(Context); 10550 MarkVTableUsed(CurrentLocation, ClassDecl); 10551 10552 if (ASTMutationListener *L = getASTMutationListener()) { 10553 L->CompletedImplicitDefinition(CopyConstructor); 10554 } 10555 } 10556 10557 Sema::ImplicitExceptionSpecification 10558 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10559 CXXRecordDecl *ClassDecl = MD->getParent(); 10560 10561 // C++ [except.spec]p14: 10562 // An implicitly declared special member function (Clause 12) shall have an 10563 // exception-specification. [...] 10564 ImplicitExceptionSpecification ExceptSpec(*this); 10565 if (ClassDecl->isInvalidDecl()) 10566 return ExceptSpec; 10567 10568 // Direct base-class constructors. 10569 for (const auto &B : ClassDecl->bases()) { 10570 if (B.isVirtual()) // Handled below. 10571 continue; 10572 10573 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10574 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10575 CXXConstructorDecl *Constructor = 10576 LookupMovingConstructor(BaseClassDecl, 0); 10577 // If this is a deleted function, add it anyway. This might be conformant 10578 // with the standard. This might not. I'm not sure. It might not matter. 10579 if (Constructor) 10580 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10581 } 10582 } 10583 10584 // Virtual base-class constructors. 10585 for (const auto &B : ClassDecl->vbases()) { 10586 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10587 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10588 CXXConstructorDecl *Constructor = 10589 LookupMovingConstructor(BaseClassDecl, 0); 10590 // If this is a deleted function, add it anyway. This might be conformant 10591 // with the standard. This might not. I'm not sure. It might not matter. 10592 if (Constructor) 10593 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10594 } 10595 } 10596 10597 // Field constructors. 10598 for (const auto *F : ClassDecl->fields()) { 10599 QualType FieldType = Context.getBaseElementType(F->getType()); 10600 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10601 CXXConstructorDecl *Constructor = 10602 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10603 // If this is a deleted function, add it anyway. This might be conformant 10604 // with the standard. This might not. I'm not sure. It might not matter. 10605 // In particular, the problem is that this function never gets called. It 10606 // might just be ill-formed because this function attempts to refer to 10607 // a deleted function here. 10608 if (Constructor) 10609 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10610 } 10611 } 10612 10613 return ExceptSpec; 10614 } 10615 10616 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10617 CXXRecordDecl *ClassDecl) { 10618 assert(ClassDecl->needsImplicitMoveConstructor()); 10619 10620 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10621 if (DSM.isAlreadyBeingDeclared()) 10622 return nullptr; 10623 10624 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10625 QualType ArgType = Context.getRValueReferenceType(ClassType); 10626 10627 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10628 CXXMoveConstructor, 10629 false); 10630 10631 DeclarationName Name 10632 = Context.DeclarationNames.getCXXConstructorName( 10633 Context.getCanonicalType(ClassType)); 10634 SourceLocation ClassLoc = ClassDecl->getLocation(); 10635 DeclarationNameInfo NameInfo(Name, ClassLoc); 10636 10637 // C++11 [class.copy]p11: 10638 // An implicitly-declared copy/move constructor is an inline public 10639 // member of its class. 10640 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10641 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 10642 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10643 Constexpr); 10644 MoveConstructor->setAccess(AS_public); 10645 MoveConstructor->setDefaulted(); 10646 10647 if (getLangOpts().CUDA) { 10648 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 10649 MoveConstructor, 10650 /* ConstRHS */ false, 10651 /* Diagnose */ false); 10652 } 10653 10654 // Build an exception specification pointing back at this member. 10655 FunctionProtoType::ExtProtoInfo EPI = 10656 getImplicitMethodEPI(*this, MoveConstructor); 10657 MoveConstructor->setType( 10658 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10659 10660 // Add the parameter to the constructor. 10661 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10662 ClassLoc, ClassLoc, 10663 /*IdentifierInfo=*/nullptr, 10664 ArgType, /*TInfo=*/nullptr, 10665 SC_None, nullptr); 10666 MoveConstructor->setParams(FromParam); 10667 10668 MoveConstructor->setTrivial( 10669 ClassDecl->needsOverloadResolutionForMoveConstructor() 10670 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10671 : ClassDecl->hasTrivialMoveConstructor()); 10672 10673 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10674 ClassDecl->setImplicitMoveConstructorIsDeleted(); 10675 SetDeclDeleted(MoveConstructor, ClassLoc); 10676 } 10677 10678 // Note that we have declared this constructor. 10679 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10680 10681 if (Scope *S = getScopeForContext(ClassDecl)) 10682 PushOnScopeChains(MoveConstructor, S, false); 10683 ClassDecl->addDecl(MoveConstructor); 10684 10685 return MoveConstructor; 10686 } 10687 10688 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 10689 CXXConstructorDecl *MoveConstructor) { 10690 assert((MoveConstructor->isDefaulted() && 10691 MoveConstructor->isMoveConstructor() && 10692 !MoveConstructor->doesThisDeclarationHaveABody() && 10693 !MoveConstructor->isDeleted()) && 10694 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 10695 10696 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 10697 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 10698 10699 SynthesizedFunctionScope Scope(*this, MoveConstructor); 10700 DiagnosticErrorTrap Trap(Diags); 10701 10702 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10703 Trap.hasErrorOccurred()) { 10704 Diag(CurrentLocation, diag::note_member_synthesized_at) 10705 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10706 MoveConstructor->setInvalidDecl(); 10707 } else { 10708 SourceLocation Loc = MoveConstructor->getLocEnd().isValid() 10709 ? MoveConstructor->getLocEnd() 10710 : MoveConstructor->getLocation(); 10711 Sema::CompoundScopeRAII CompoundScope(*this); 10712 MoveConstructor->setBody(ActOnCompoundStmt( 10713 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 10714 } 10715 10716 // The exception specification is needed because we are defining the 10717 // function. 10718 ResolveExceptionSpec(CurrentLocation, 10719 MoveConstructor->getType()->castAs<FunctionProtoType>()); 10720 10721 MoveConstructor->markUsed(Context); 10722 MarkVTableUsed(CurrentLocation, ClassDecl); 10723 10724 if (ASTMutationListener *L = getASTMutationListener()) { 10725 L->CompletedImplicitDefinition(MoveConstructor); 10726 } 10727 } 10728 10729 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10730 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10731 } 10732 10733 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10734 SourceLocation CurrentLocation, 10735 CXXConversionDecl *Conv) { 10736 CXXRecordDecl *Lambda = Conv->getParent(); 10737 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 10738 // If we are defining a specialization of a conversion to function-ptr 10739 // cache the deduced template arguments for this specialization 10740 // so that we can use them to retrieve the corresponding call-operator 10741 // and static-invoker. 10742 const TemplateArgumentList *DeducedTemplateArgs = nullptr; 10743 10744 // Retrieve the corresponding call-operator specialization. 10745 if (Lambda->isGenericLambda()) { 10746 assert(Conv->isFunctionTemplateSpecialization()); 10747 FunctionTemplateDecl *CallOpTemplate = 10748 CallOp->getDescribedFunctionTemplate(); 10749 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 10750 void *InsertPos = nullptr; 10751 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 10752 DeducedTemplateArgs->asArray(), 10753 InsertPos); 10754 assert(CallOpSpec && 10755 "Conversion operator must have a corresponding call operator"); 10756 CallOp = cast<CXXMethodDecl>(CallOpSpec); 10757 } 10758 // Mark the call operator referenced (and add to pending instantiations 10759 // if necessary). 10760 // For both the conversion and static-invoker template specializations 10761 // we construct their body's in this function, so no need to add them 10762 // to the PendingInstantiations. 10763 MarkFunctionReferenced(CurrentLocation, CallOp); 10764 10765 SynthesizedFunctionScope Scope(*this, Conv); 10766 DiagnosticErrorTrap Trap(Diags); 10767 10768 // Retrieve the static invoker... 10769 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 10770 // ... and get the corresponding specialization for a generic lambda. 10771 if (Lambda->isGenericLambda()) { 10772 assert(DeducedTemplateArgs && 10773 "Must have deduced template arguments from Conversion Operator"); 10774 FunctionTemplateDecl *InvokeTemplate = 10775 Invoker->getDescribedFunctionTemplate(); 10776 void *InsertPos = nullptr; 10777 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 10778 DeducedTemplateArgs->asArray(), 10779 InsertPos); 10780 assert(InvokeSpec && 10781 "Must have a corresponding static invoker specialization"); 10782 Invoker = cast<CXXMethodDecl>(InvokeSpec); 10783 } 10784 // Construct the body of the conversion function { return __invoke; }. 10785 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 10786 VK_LValue, Conv->getLocation()).get(); 10787 assert(FunctionRef && "Can't refer to __invoke function?"); 10788 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 10789 Conv->setBody(new (Context) CompoundStmt(Context, Return, 10790 Conv->getLocation(), 10791 Conv->getLocation())); 10792 10793 Conv->markUsed(Context); 10794 Conv->setReferenced(); 10795 10796 // Fill in the __invoke function with a dummy implementation. IR generation 10797 // will fill in the actual details. 10798 Invoker->markUsed(Context); 10799 Invoker->setReferenced(); 10800 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 10801 10802 if (ASTMutationListener *L = getASTMutationListener()) { 10803 L->CompletedImplicitDefinition(Conv); 10804 L->CompletedImplicitDefinition(Invoker); 10805 } 10806 } 10807 10808 10809 10810 void Sema::DefineImplicitLambdaToBlockPointerConversion( 10811 SourceLocation CurrentLocation, 10812 CXXConversionDecl *Conv) 10813 { 10814 assert(!Conv->getParent()->isGenericLambda()); 10815 10816 Conv->markUsed(Context); 10817 10818 SynthesizedFunctionScope Scope(*this, Conv); 10819 DiagnosticErrorTrap Trap(Diags); 10820 10821 // Copy-initialize the lambda object as needed to capture it. 10822 Expr *This = ActOnCXXThis(CurrentLocation).get(); 10823 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 10824 10825 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 10826 Conv->getLocation(), 10827 Conv, DerefThis); 10828 10829 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 10830 // behavior. Note that only the general conversion function does this 10831 // (since it's unusable otherwise); in the case where we inline the 10832 // block literal, it has block literal lifetime semantics. 10833 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 10834 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 10835 CK_CopyAndAutoreleaseBlockObject, 10836 BuildBlock.get(), nullptr, VK_RValue); 10837 10838 if (BuildBlock.isInvalid()) { 10839 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10840 Conv->setInvalidDecl(); 10841 return; 10842 } 10843 10844 // Create the return statement that returns the block from the conversion 10845 // function. 10846 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 10847 if (Return.isInvalid()) { 10848 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10849 Conv->setInvalidDecl(); 10850 return; 10851 } 10852 10853 // Set the body of the conversion function. 10854 Stmt *ReturnS = Return.get(); 10855 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 10856 Conv->getLocation(), 10857 Conv->getLocation())); 10858 10859 // We're done; notify the mutation listener, if any. 10860 if (ASTMutationListener *L = getASTMutationListener()) { 10861 L->CompletedImplicitDefinition(Conv); 10862 } 10863 } 10864 10865 /// \brief Determine whether the given list arguments contains exactly one 10866 /// "real" (non-default) argument. 10867 static bool hasOneRealArgument(MultiExprArg Args) { 10868 switch (Args.size()) { 10869 case 0: 10870 return false; 10871 10872 default: 10873 if (!Args[1]->isDefaultArgument()) 10874 return false; 10875 10876 // fall through 10877 case 1: 10878 return !Args[0]->isDefaultArgument(); 10879 } 10880 10881 return false; 10882 } 10883 10884 ExprResult 10885 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10886 CXXConstructorDecl *Constructor, 10887 MultiExprArg ExprArgs, 10888 bool HadMultipleCandidates, 10889 bool IsListInitialization, 10890 bool IsStdInitListInitialization, 10891 bool RequiresZeroInit, 10892 unsigned ConstructKind, 10893 SourceRange ParenRange) { 10894 bool Elidable = false; 10895 10896 // C++0x [class.copy]p34: 10897 // When certain criteria are met, an implementation is allowed to 10898 // omit the copy/move construction of a class object, even if the 10899 // copy/move constructor and/or destructor for the object have 10900 // side effects. [...] 10901 // - when a temporary class object that has not been bound to a 10902 // reference (12.2) would be copied/moved to a class object 10903 // with the same cv-unqualified type, the copy/move operation 10904 // can be omitted by constructing the temporary object 10905 // directly into the target of the omitted copy/move 10906 if (ConstructKind == CXXConstructExpr::CK_Complete && 10907 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10908 Expr *SubExpr = ExprArgs[0]; 10909 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10910 } 10911 10912 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10913 Elidable, ExprArgs, HadMultipleCandidates, 10914 IsListInitialization, 10915 IsStdInitListInitialization, RequiresZeroInit, 10916 ConstructKind, ParenRange); 10917 } 10918 10919 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 10920 /// including handling of its default argument expressions. 10921 ExprResult 10922 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10923 CXXConstructorDecl *Constructor, bool Elidable, 10924 MultiExprArg ExprArgs, 10925 bool HadMultipleCandidates, 10926 bool IsListInitialization, 10927 bool IsStdInitListInitialization, 10928 bool RequiresZeroInit, 10929 unsigned ConstructKind, 10930 SourceRange ParenRange) { 10931 MarkFunctionReferenced(ConstructLoc, Constructor); 10932 return CXXConstructExpr::Create( 10933 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 10934 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 10935 RequiresZeroInit, 10936 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10937 ParenRange); 10938 } 10939 10940 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10941 if (VD->isInvalidDecl()) return; 10942 10943 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10944 if (ClassDecl->isInvalidDecl()) return; 10945 if (ClassDecl->hasIrrelevantDestructor()) return; 10946 if (ClassDecl->isDependentContext()) return; 10947 10948 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10949 MarkFunctionReferenced(VD->getLocation(), Destructor); 10950 CheckDestructorAccess(VD->getLocation(), Destructor, 10951 PDiag(diag::err_access_dtor_var) 10952 << VD->getDeclName() 10953 << VD->getType()); 10954 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10955 10956 if (Destructor->isTrivial()) return; 10957 if (!VD->hasGlobalStorage()) return; 10958 10959 // Emit warning for non-trivial dtor in global scope (a real global, 10960 // class-static, function-static). 10961 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10962 10963 // TODO: this should be re-enabled for static locals by !CXAAtExit 10964 if (!VD->isStaticLocal()) 10965 Diag(VD->getLocation(), diag::warn_global_destructor); 10966 } 10967 10968 /// \brief Given a constructor and the set of arguments provided for the 10969 /// constructor, convert the arguments and add any required default arguments 10970 /// to form a proper call to this constructor. 10971 /// 10972 /// \returns true if an error occurred, false otherwise. 10973 bool 10974 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10975 MultiExprArg ArgsPtr, 10976 SourceLocation Loc, 10977 SmallVectorImpl<Expr*> &ConvertedArgs, 10978 bool AllowExplicit, 10979 bool IsListInitialization) { 10980 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10981 unsigned NumArgs = ArgsPtr.size(); 10982 Expr **Args = ArgsPtr.data(); 10983 10984 const FunctionProtoType *Proto 10985 = Constructor->getType()->getAs<FunctionProtoType>(); 10986 assert(Proto && "Constructor without a prototype?"); 10987 unsigned NumParams = Proto->getNumParams(); 10988 10989 // If too few arguments are available, we'll fill in the rest with defaults. 10990 if (NumArgs < NumParams) 10991 ConvertedArgs.reserve(NumParams); 10992 else 10993 ConvertedArgs.reserve(NumArgs); 10994 10995 VariadicCallType CallType = 10996 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10997 SmallVector<Expr *, 8> AllArgs; 10998 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10999 Proto, 0, 11000 llvm::makeArrayRef(Args, NumArgs), 11001 AllArgs, 11002 CallType, AllowExplicit, 11003 IsListInitialization); 11004 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 11005 11006 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 11007 11008 CheckConstructorCall(Constructor, 11009 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 11010 Proto, Loc); 11011 11012 return Invalid; 11013 } 11014 11015 static inline bool 11016 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 11017 const FunctionDecl *FnDecl) { 11018 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 11019 if (isa<NamespaceDecl>(DC)) { 11020 return SemaRef.Diag(FnDecl->getLocation(), 11021 diag::err_operator_new_delete_declared_in_namespace) 11022 << FnDecl->getDeclName(); 11023 } 11024 11025 if (isa<TranslationUnitDecl>(DC) && 11026 FnDecl->getStorageClass() == SC_Static) { 11027 return SemaRef.Diag(FnDecl->getLocation(), 11028 diag::err_operator_new_delete_declared_static) 11029 << FnDecl->getDeclName(); 11030 } 11031 11032 return false; 11033 } 11034 11035 static inline bool 11036 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 11037 CanQualType ExpectedResultType, 11038 CanQualType ExpectedFirstParamType, 11039 unsigned DependentParamTypeDiag, 11040 unsigned InvalidParamTypeDiag) { 11041 QualType ResultType = 11042 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 11043 11044 // Check that the result type is not dependent. 11045 if (ResultType->isDependentType()) 11046 return SemaRef.Diag(FnDecl->getLocation(), 11047 diag::err_operator_new_delete_dependent_result_type) 11048 << FnDecl->getDeclName() << ExpectedResultType; 11049 11050 // Check that the result type is what we expect. 11051 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 11052 return SemaRef.Diag(FnDecl->getLocation(), 11053 diag::err_operator_new_delete_invalid_result_type) 11054 << FnDecl->getDeclName() << ExpectedResultType; 11055 11056 // A function template must have at least 2 parameters. 11057 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 11058 return SemaRef.Diag(FnDecl->getLocation(), 11059 diag::err_operator_new_delete_template_too_few_parameters) 11060 << FnDecl->getDeclName(); 11061 11062 // The function decl must have at least 1 parameter. 11063 if (FnDecl->getNumParams() == 0) 11064 return SemaRef.Diag(FnDecl->getLocation(), 11065 diag::err_operator_new_delete_too_few_parameters) 11066 << FnDecl->getDeclName(); 11067 11068 // Check the first parameter type is not dependent. 11069 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 11070 if (FirstParamType->isDependentType()) 11071 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 11072 << FnDecl->getDeclName() << ExpectedFirstParamType; 11073 11074 // Check that the first parameter type is what we expect. 11075 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 11076 ExpectedFirstParamType) 11077 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 11078 << FnDecl->getDeclName() << ExpectedFirstParamType; 11079 11080 return false; 11081 } 11082 11083 static bool 11084 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 11085 // C++ [basic.stc.dynamic.allocation]p1: 11086 // A program is ill-formed if an allocation function is declared in a 11087 // namespace scope other than global scope or declared static in global 11088 // scope. 11089 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11090 return true; 11091 11092 CanQualType SizeTy = 11093 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 11094 11095 // C++ [basic.stc.dynamic.allocation]p1: 11096 // The return type shall be void*. The first parameter shall have type 11097 // std::size_t. 11098 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 11099 SizeTy, 11100 diag::err_operator_new_dependent_param_type, 11101 diag::err_operator_new_param_type)) 11102 return true; 11103 11104 // C++ [basic.stc.dynamic.allocation]p1: 11105 // The first parameter shall not have an associated default argument. 11106 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 11107 return SemaRef.Diag(FnDecl->getLocation(), 11108 diag::err_operator_new_default_arg) 11109 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 11110 11111 return false; 11112 } 11113 11114 static bool 11115 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 11116 // C++ [basic.stc.dynamic.deallocation]p1: 11117 // A program is ill-formed if deallocation functions are declared in a 11118 // namespace scope other than global scope or declared static in global 11119 // scope. 11120 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 11121 return true; 11122 11123 // C++ [basic.stc.dynamic.deallocation]p2: 11124 // Each deallocation function shall return void and its first parameter 11125 // shall be void*. 11126 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 11127 SemaRef.Context.VoidPtrTy, 11128 diag::err_operator_delete_dependent_param_type, 11129 diag::err_operator_delete_param_type)) 11130 return true; 11131 11132 return false; 11133 } 11134 11135 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 11136 /// of this overloaded operator is well-formed. If so, returns false; 11137 /// otherwise, emits appropriate diagnostics and returns true. 11138 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 11139 assert(FnDecl && FnDecl->isOverloadedOperator() && 11140 "Expected an overloaded operator declaration"); 11141 11142 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 11143 11144 // C++ [over.oper]p5: 11145 // The allocation and deallocation functions, operator new, 11146 // operator new[], operator delete and operator delete[], are 11147 // described completely in 3.7.3. The attributes and restrictions 11148 // found in the rest of this subclause do not apply to them unless 11149 // explicitly stated in 3.7.3. 11150 if (Op == OO_Delete || Op == OO_Array_Delete) 11151 return CheckOperatorDeleteDeclaration(*this, FnDecl); 11152 11153 if (Op == OO_New || Op == OO_Array_New) 11154 return CheckOperatorNewDeclaration(*this, FnDecl); 11155 11156 // C++ [over.oper]p6: 11157 // An operator function shall either be a non-static member 11158 // function or be a non-member function and have at least one 11159 // parameter whose type is a class, a reference to a class, an 11160 // enumeration, or a reference to an enumeration. 11161 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 11162 if (MethodDecl->isStatic()) 11163 return Diag(FnDecl->getLocation(), 11164 diag::err_operator_overload_static) << FnDecl->getDeclName(); 11165 } else { 11166 bool ClassOrEnumParam = false; 11167 for (auto Param : FnDecl->params()) { 11168 QualType ParamType = Param->getType().getNonReferenceType(); 11169 if (ParamType->isDependentType() || ParamType->isRecordType() || 11170 ParamType->isEnumeralType()) { 11171 ClassOrEnumParam = true; 11172 break; 11173 } 11174 } 11175 11176 if (!ClassOrEnumParam) 11177 return Diag(FnDecl->getLocation(), 11178 diag::err_operator_overload_needs_class_or_enum) 11179 << FnDecl->getDeclName(); 11180 } 11181 11182 // C++ [over.oper]p8: 11183 // An operator function cannot have default arguments (8.3.6), 11184 // except where explicitly stated below. 11185 // 11186 // Only the function-call operator allows default arguments 11187 // (C++ [over.call]p1). 11188 if (Op != OO_Call) { 11189 for (auto Param : FnDecl->params()) { 11190 if (Param->hasDefaultArg()) 11191 return Diag(Param->getLocation(), 11192 diag::err_operator_overload_default_arg) 11193 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 11194 } 11195 } 11196 11197 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 11198 { false, false, false } 11199 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 11200 , { Unary, Binary, MemberOnly } 11201 #include "clang/Basic/OperatorKinds.def" 11202 }; 11203 11204 bool CanBeUnaryOperator = OperatorUses[Op][0]; 11205 bool CanBeBinaryOperator = OperatorUses[Op][1]; 11206 bool MustBeMemberOperator = OperatorUses[Op][2]; 11207 11208 // C++ [over.oper]p8: 11209 // [...] Operator functions cannot have more or fewer parameters 11210 // than the number required for the corresponding operator, as 11211 // described in the rest of this subclause. 11212 unsigned NumParams = FnDecl->getNumParams() 11213 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 11214 if (Op != OO_Call && 11215 ((NumParams == 1 && !CanBeUnaryOperator) || 11216 (NumParams == 2 && !CanBeBinaryOperator) || 11217 (NumParams < 1) || (NumParams > 2))) { 11218 // We have the wrong number of parameters. 11219 unsigned ErrorKind; 11220 if (CanBeUnaryOperator && CanBeBinaryOperator) { 11221 ErrorKind = 2; // 2 -> unary or binary. 11222 } else if (CanBeUnaryOperator) { 11223 ErrorKind = 0; // 0 -> unary 11224 } else { 11225 assert(CanBeBinaryOperator && 11226 "All non-call overloaded operators are unary or binary!"); 11227 ErrorKind = 1; // 1 -> binary 11228 } 11229 11230 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 11231 << FnDecl->getDeclName() << NumParams << ErrorKind; 11232 } 11233 11234 // Overloaded operators other than operator() cannot be variadic. 11235 if (Op != OO_Call && 11236 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 11237 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 11238 << FnDecl->getDeclName(); 11239 } 11240 11241 // Some operators must be non-static member functions. 11242 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 11243 return Diag(FnDecl->getLocation(), 11244 diag::err_operator_overload_must_be_member) 11245 << FnDecl->getDeclName(); 11246 } 11247 11248 // C++ [over.inc]p1: 11249 // The user-defined function called operator++ implements the 11250 // prefix and postfix ++ operator. If this function is a member 11251 // function with no parameters, or a non-member function with one 11252 // parameter of class or enumeration type, it defines the prefix 11253 // increment operator ++ for objects of that type. If the function 11254 // is a member function with one parameter (which shall be of type 11255 // int) or a non-member function with two parameters (the second 11256 // of which shall be of type int), it defines the postfix 11257 // increment operator ++ for objects of that type. 11258 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 11259 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 11260 QualType ParamType = LastParam->getType(); 11261 11262 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 11263 !ParamType->isDependentType()) 11264 return Diag(LastParam->getLocation(), 11265 diag::err_operator_overload_post_incdec_must_be_int) 11266 << LastParam->getType() << (Op == OO_MinusMinus); 11267 } 11268 11269 return false; 11270 } 11271 11272 /// CheckLiteralOperatorDeclaration - Check whether the declaration 11273 /// of this literal operator function is well-formed. If so, returns 11274 /// false; otherwise, emits appropriate diagnostics and returns true. 11275 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 11276 if (isa<CXXMethodDecl>(FnDecl)) { 11277 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 11278 << FnDecl->getDeclName(); 11279 return true; 11280 } 11281 11282 if (FnDecl->isExternC()) { 11283 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 11284 return true; 11285 } 11286 11287 bool Valid = false; 11288 11289 // This might be the definition of a literal operator template. 11290 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 11291 // This might be a specialization of a literal operator template. 11292 if (!TpDecl) 11293 TpDecl = FnDecl->getPrimaryTemplate(); 11294 11295 // template <char...> type operator "" name() and 11296 // template <class T, T...> type operator "" name() are the only valid 11297 // template signatures, and the only valid signatures with no parameters. 11298 if (TpDecl) { 11299 if (FnDecl->param_size() == 0) { 11300 // Must have one or two template parameters 11301 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 11302 if (Params->size() == 1) { 11303 NonTypeTemplateParmDecl *PmDecl = 11304 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 11305 11306 // The template parameter must be a char parameter pack. 11307 if (PmDecl && PmDecl->isTemplateParameterPack() && 11308 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 11309 Valid = true; 11310 } else if (Params->size() == 2) { 11311 TemplateTypeParmDecl *PmType = 11312 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 11313 NonTypeTemplateParmDecl *PmArgs = 11314 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 11315 11316 // The second template parameter must be a parameter pack with the 11317 // first template parameter as its type. 11318 if (PmType && PmArgs && 11319 !PmType->isTemplateParameterPack() && 11320 PmArgs->isTemplateParameterPack()) { 11321 const TemplateTypeParmType *TArgs = 11322 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11323 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11324 TArgs->getIndex() == PmType->getIndex()) { 11325 Valid = true; 11326 if (ActiveTemplateInstantiations.empty()) 11327 Diag(FnDecl->getLocation(), 11328 diag::ext_string_literal_operator_template); 11329 } 11330 } 11331 } 11332 } 11333 } else if (FnDecl->param_size()) { 11334 // Check the first parameter 11335 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11336 11337 QualType T = (*Param)->getType().getUnqualifiedType(); 11338 11339 // unsigned long long int, long double, and any character type are allowed 11340 // as the only parameters. 11341 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11342 Context.hasSameType(T, Context.LongDoubleTy) || 11343 Context.hasSameType(T, Context.CharTy) || 11344 Context.hasSameType(T, Context.WideCharTy) || 11345 Context.hasSameType(T, Context.Char16Ty) || 11346 Context.hasSameType(T, Context.Char32Ty)) { 11347 if (++Param == FnDecl->param_end()) 11348 Valid = true; 11349 goto FinishedParams; 11350 } 11351 11352 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11353 const PointerType *PT = T->getAs<PointerType>(); 11354 if (!PT) 11355 goto FinishedParams; 11356 T = PT->getPointeeType(); 11357 if (!T.isConstQualified() || T.isVolatileQualified()) 11358 goto FinishedParams; 11359 T = T.getUnqualifiedType(); 11360 11361 // Move on to the second parameter; 11362 ++Param; 11363 11364 // If there is no second parameter, the first must be a const char * 11365 if (Param == FnDecl->param_end()) { 11366 if (Context.hasSameType(T, Context.CharTy)) 11367 Valid = true; 11368 goto FinishedParams; 11369 } 11370 11371 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11372 // are allowed as the first parameter to a two-parameter function 11373 if (!(Context.hasSameType(T, Context.CharTy) || 11374 Context.hasSameType(T, Context.WideCharTy) || 11375 Context.hasSameType(T, Context.Char16Ty) || 11376 Context.hasSameType(T, Context.Char32Ty))) 11377 goto FinishedParams; 11378 11379 // The second and final parameter must be an std::size_t 11380 T = (*Param)->getType().getUnqualifiedType(); 11381 if (Context.hasSameType(T, Context.getSizeType()) && 11382 ++Param == FnDecl->param_end()) 11383 Valid = true; 11384 } 11385 11386 // FIXME: This diagnostic is absolutely terrible. 11387 FinishedParams: 11388 if (!Valid) { 11389 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11390 << FnDecl->getDeclName(); 11391 return true; 11392 } 11393 11394 // A parameter-declaration-clause containing a default argument is not 11395 // equivalent to any of the permitted forms. 11396 for (auto Param : FnDecl->params()) { 11397 if (Param->hasDefaultArg()) { 11398 Diag(Param->getDefaultArgRange().getBegin(), 11399 diag::err_literal_operator_default_argument) 11400 << Param->getDefaultArgRange(); 11401 break; 11402 } 11403 } 11404 11405 StringRef LiteralName 11406 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11407 if (LiteralName[0] != '_') { 11408 // C++11 [usrlit.suffix]p1: 11409 // Literal suffix identifiers that do not start with an underscore 11410 // are reserved for future standardization. 11411 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11412 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11413 } 11414 11415 return false; 11416 } 11417 11418 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11419 /// linkage specification, including the language and (if present) 11420 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11421 /// language string literal. LBraceLoc, if valid, provides the location of 11422 /// the '{' brace. Otherwise, this linkage specification does not 11423 /// have any braces. 11424 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11425 Expr *LangStr, 11426 SourceLocation LBraceLoc) { 11427 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11428 if (!Lit->isAscii()) { 11429 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11430 << LangStr->getSourceRange(); 11431 return nullptr; 11432 } 11433 11434 StringRef Lang = Lit->getString(); 11435 LinkageSpecDecl::LanguageIDs Language; 11436 if (Lang == "C") 11437 Language = LinkageSpecDecl::lang_c; 11438 else if (Lang == "C++") 11439 Language = LinkageSpecDecl::lang_cxx; 11440 else { 11441 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11442 << LangStr->getSourceRange(); 11443 return nullptr; 11444 } 11445 11446 // FIXME: Add all the various semantics of linkage specifications 11447 11448 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11449 LangStr->getExprLoc(), Language, 11450 LBraceLoc.isValid()); 11451 CurContext->addDecl(D); 11452 PushDeclContext(S, D); 11453 return D; 11454 } 11455 11456 /// ActOnFinishLinkageSpecification - Complete the definition of 11457 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11458 /// valid, it's the position of the closing '}' brace in a linkage 11459 /// specification that uses braces. 11460 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11461 Decl *LinkageSpec, 11462 SourceLocation RBraceLoc) { 11463 if (RBraceLoc.isValid()) { 11464 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11465 LSDecl->setRBraceLoc(RBraceLoc); 11466 } 11467 PopDeclContext(); 11468 return LinkageSpec; 11469 } 11470 11471 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11472 AttributeList *AttrList, 11473 SourceLocation SemiLoc) { 11474 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11475 // Attribute declarations appertain to empty declaration so we handle 11476 // them here. 11477 if (AttrList) 11478 ProcessDeclAttributeList(S, ED, AttrList); 11479 11480 CurContext->addDecl(ED); 11481 return ED; 11482 } 11483 11484 /// \brief Perform semantic analysis for the variable declaration that 11485 /// occurs within a C++ catch clause, returning the newly-created 11486 /// variable. 11487 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11488 TypeSourceInfo *TInfo, 11489 SourceLocation StartLoc, 11490 SourceLocation Loc, 11491 IdentifierInfo *Name) { 11492 bool Invalid = false; 11493 QualType ExDeclType = TInfo->getType(); 11494 11495 // Arrays and functions decay. 11496 if (ExDeclType->isArrayType()) 11497 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11498 else if (ExDeclType->isFunctionType()) 11499 ExDeclType = Context.getPointerType(ExDeclType); 11500 11501 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11502 // The exception-declaration shall not denote a pointer or reference to an 11503 // incomplete type, other than [cv] void*. 11504 // N2844 forbids rvalue references. 11505 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11506 Diag(Loc, diag::err_catch_rvalue_ref); 11507 Invalid = true; 11508 } 11509 11510 QualType BaseType = ExDeclType; 11511 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11512 unsigned DK = diag::err_catch_incomplete; 11513 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11514 BaseType = Ptr->getPointeeType(); 11515 Mode = 1; 11516 DK = diag::err_catch_incomplete_ptr; 11517 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11518 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11519 BaseType = Ref->getPointeeType(); 11520 Mode = 2; 11521 DK = diag::err_catch_incomplete_ref; 11522 } 11523 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11524 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11525 Invalid = true; 11526 11527 if (!Invalid && !ExDeclType->isDependentType() && 11528 RequireNonAbstractType(Loc, ExDeclType, 11529 diag::err_abstract_type_in_decl, 11530 AbstractVariableType)) 11531 Invalid = true; 11532 11533 // Only the non-fragile NeXT runtime currently supports C++ catches 11534 // of ObjC types, and no runtime supports catching ObjC types by value. 11535 if (!Invalid && getLangOpts().ObjC1) { 11536 QualType T = ExDeclType; 11537 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11538 T = RT->getPointeeType(); 11539 11540 if (T->isObjCObjectType()) { 11541 Diag(Loc, diag::err_objc_object_catch); 11542 Invalid = true; 11543 } else if (T->isObjCObjectPointerType()) { 11544 // FIXME: should this be a test for macosx-fragile specifically? 11545 if (getLangOpts().ObjCRuntime.isFragile()) 11546 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11547 } 11548 } 11549 11550 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11551 ExDeclType, TInfo, SC_None); 11552 ExDecl->setExceptionVariable(true); 11553 11554 // In ARC, infer 'retaining' for variables of retainable type. 11555 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11556 Invalid = true; 11557 11558 if (!Invalid && !ExDeclType->isDependentType()) { 11559 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11560 // Insulate this from anything else we might currently be parsing. 11561 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11562 11563 // C++ [except.handle]p16: 11564 // The object declared in an exception-declaration or, if the 11565 // exception-declaration does not specify a name, a temporary (12.2) is 11566 // copy-initialized (8.5) from the exception object. [...] 11567 // The object is destroyed when the handler exits, after the destruction 11568 // of any automatic objects initialized within the handler. 11569 // 11570 // We just pretend to initialize the object with itself, then make sure 11571 // it can be destroyed later. 11572 QualType initType = ExDeclType; 11573 11574 InitializedEntity entity = 11575 InitializedEntity::InitializeVariable(ExDecl); 11576 InitializationKind initKind = 11577 InitializationKind::CreateCopy(Loc, SourceLocation()); 11578 11579 Expr *opaqueValue = 11580 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11581 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11582 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11583 if (result.isInvalid()) 11584 Invalid = true; 11585 else { 11586 // If the constructor used was non-trivial, set this as the 11587 // "initializer". 11588 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 11589 if (!construct->getConstructor()->isTrivial()) { 11590 Expr *init = MaybeCreateExprWithCleanups(construct); 11591 ExDecl->setInit(init); 11592 } 11593 11594 // And make sure it's destructable. 11595 FinalizeVarWithDestructor(ExDecl, recordType); 11596 } 11597 } 11598 } 11599 11600 if (Invalid) 11601 ExDecl->setInvalidDecl(); 11602 11603 return ExDecl; 11604 } 11605 11606 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11607 /// handler. 11608 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11609 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11610 bool Invalid = D.isInvalidType(); 11611 11612 // Check for unexpanded parameter packs. 11613 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11614 UPPC_ExceptionType)) { 11615 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11616 D.getIdentifierLoc()); 11617 Invalid = true; 11618 } 11619 11620 IdentifierInfo *II = D.getIdentifier(); 11621 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11622 LookupOrdinaryName, 11623 ForRedeclaration)) { 11624 // The scope should be freshly made just for us. There is just no way 11625 // it contains any previous declaration, except for function parameters in 11626 // a function-try-block's catch statement. 11627 assert(!S->isDeclScope(PrevDecl)); 11628 if (isDeclInScope(PrevDecl, CurContext, S)) { 11629 Diag(D.getIdentifierLoc(), diag::err_redefinition) 11630 << D.getIdentifier(); 11631 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11632 Invalid = true; 11633 } else if (PrevDecl->isTemplateParameter()) 11634 // Maybe we will complain about the shadowed template parameter. 11635 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11636 } 11637 11638 if (D.getCXXScopeSpec().isSet() && !Invalid) { 11639 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 11640 << D.getCXXScopeSpec().getRange(); 11641 Invalid = true; 11642 } 11643 11644 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 11645 D.getLocStart(), 11646 D.getIdentifierLoc(), 11647 D.getIdentifier()); 11648 if (Invalid) 11649 ExDecl->setInvalidDecl(); 11650 11651 // Add the exception declaration into this scope. 11652 if (II) 11653 PushOnScopeChains(ExDecl, S); 11654 else 11655 CurContext->addDecl(ExDecl); 11656 11657 ProcessDeclAttributes(S, ExDecl, D); 11658 return ExDecl; 11659 } 11660 11661 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11662 Expr *AssertExpr, 11663 Expr *AssertMessageExpr, 11664 SourceLocation RParenLoc) { 11665 StringLiteral *AssertMessage = 11666 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 11667 11668 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 11669 return nullptr; 11670 11671 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 11672 AssertMessage, RParenLoc, false); 11673 } 11674 11675 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11676 Expr *AssertExpr, 11677 StringLiteral *AssertMessage, 11678 SourceLocation RParenLoc, 11679 bool Failed) { 11680 assert(AssertExpr != nullptr && "Expected non-null condition"); 11681 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 11682 !Failed) { 11683 // In a static_assert-declaration, the constant-expression shall be a 11684 // constant expression that can be contextually converted to bool. 11685 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 11686 if (Converted.isInvalid()) 11687 Failed = true; 11688 11689 llvm::APSInt Cond; 11690 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 11691 diag::err_static_assert_expression_is_not_constant, 11692 /*AllowFold=*/false).isInvalid()) 11693 Failed = true; 11694 11695 if (!Failed && !Cond) { 11696 SmallString<256> MsgBuffer; 11697 llvm::raw_svector_ostream Msg(MsgBuffer); 11698 if (AssertMessage) 11699 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 11700 Diag(StaticAssertLoc, diag::err_static_assert_failed) 11701 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 11702 Failed = true; 11703 } 11704 } 11705 11706 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 11707 AssertExpr, AssertMessage, RParenLoc, 11708 Failed); 11709 11710 CurContext->addDecl(Decl); 11711 return Decl; 11712 } 11713 11714 /// \brief Perform semantic analysis of the given friend type declaration. 11715 /// 11716 /// \returns A friend declaration that. 11717 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 11718 SourceLocation FriendLoc, 11719 TypeSourceInfo *TSInfo) { 11720 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 11721 11722 QualType T = TSInfo->getType(); 11723 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 11724 11725 // C++03 [class.friend]p2: 11726 // An elaborated-type-specifier shall be used in a friend declaration 11727 // for a class.* 11728 // 11729 // * The class-key of the elaborated-type-specifier is required. 11730 if (!ActiveTemplateInstantiations.empty()) { 11731 // Do not complain about the form of friend template types during 11732 // template instantiation; we will already have complained when the 11733 // template was declared. 11734 } else { 11735 if (!T->isElaboratedTypeSpecifier()) { 11736 // If we evaluated the type to a record type, suggest putting 11737 // a tag in front. 11738 if (const RecordType *RT = T->getAs<RecordType>()) { 11739 RecordDecl *RD = RT->getDecl(); 11740 11741 SmallString<16> InsertionText(" "); 11742 InsertionText += RD->getKindName(); 11743 11744 Diag(TypeRange.getBegin(), 11745 getLangOpts().CPlusPlus11 ? 11746 diag::warn_cxx98_compat_unelaborated_friend_type : 11747 diag::ext_unelaborated_friend_type) 11748 << (unsigned) RD->getTagKind() 11749 << T 11750 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 11751 InsertionText); 11752 } else { 11753 Diag(FriendLoc, 11754 getLangOpts().CPlusPlus11 ? 11755 diag::warn_cxx98_compat_nonclass_type_friend : 11756 diag::ext_nonclass_type_friend) 11757 << T 11758 << TypeRange; 11759 } 11760 } else if (T->getAs<EnumType>()) { 11761 Diag(FriendLoc, 11762 getLangOpts().CPlusPlus11 ? 11763 diag::warn_cxx98_compat_enum_friend : 11764 diag::ext_enum_friend) 11765 << T 11766 << TypeRange; 11767 } 11768 11769 // C++11 [class.friend]p3: 11770 // A friend declaration that does not declare a function shall have one 11771 // of the following forms: 11772 // friend elaborated-type-specifier ; 11773 // friend simple-type-specifier ; 11774 // friend typename-specifier ; 11775 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 11776 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 11777 } 11778 11779 // If the type specifier in a friend declaration designates a (possibly 11780 // cv-qualified) class type, that class is declared as a friend; otherwise, 11781 // the friend declaration is ignored. 11782 return FriendDecl::Create(Context, CurContext, 11783 TSInfo->getTypeLoc().getLocStart(), TSInfo, 11784 FriendLoc); 11785 } 11786 11787 /// Handle a friend tag declaration where the scope specifier was 11788 /// templated. 11789 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 11790 unsigned TagSpec, SourceLocation TagLoc, 11791 CXXScopeSpec &SS, 11792 IdentifierInfo *Name, 11793 SourceLocation NameLoc, 11794 AttributeList *Attr, 11795 MultiTemplateParamsArg TempParamLists) { 11796 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11797 11798 bool isExplicitSpecialization = false; 11799 bool Invalid = false; 11800 11801 if (TemplateParameterList *TemplateParams = 11802 MatchTemplateParametersToScopeSpecifier( 11803 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 11804 isExplicitSpecialization, Invalid)) { 11805 if (TemplateParams->size() > 0) { 11806 // This is a declaration of a class template. 11807 if (Invalid) 11808 return nullptr; 11809 11810 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 11811 NameLoc, Attr, TemplateParams, AS_public, 11812 /*ModulePrivateLoc=*/SourceLocation(), 11813 FriendLoc, TempParamLists.size() - 1, 11814 TempParamLists.data()).get(); 11815 } else { 11816 // The "template<>" header is extraneous. 11817 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11818 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11819 isExplicitSpecialization = true; 11820 } 11821 } 11822 11823 if (Invalid) return nullptr; 11824 11825 bool isAllExplicitSpecializations = true; 11826 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 11827 if (TempParamLists[I]->size()) { 11828 isAllExplicitSpecializations = false; 11829 break; 11830 } 11831 } 11832 11833 // FIXME: don't ignore attributes. 11834 11835 // If it's explicit specializations all the way down, just forget 11836 // about the template header and build an appropriate non-templated 11837 // friend. TODO: for source fidelity, remember the headers. 11838 if (isAllExplicitSpecializations) { 11839 if (SS.isEmpty()) { 11840 bool Owned = false; 11841 bool IsDependent = false; 11842 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 11843 Attr, AS_public, 11844 /*ModulePrivateLoc=*/SourceLocation(), 11845 MultiTemplateParamsArg(), Owned, IsDependent, 11846 /*ScopedEnumKWLoc=*/SourceLocation(), 11847 /*ScopedEnumUsesClassTag=*/false, 11848 /*UnderlyingType=*/TypeResult(), 11849 /*IsTypeSpecifier=*/false); 11850 } 11851 11852 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11853 ElaboratedTypeKeyword Keyword 11854 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11855 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 11856 *Name, NameLoc); 11857 if (T.isNull()) 11858 return nullptr; 11859 11860 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11861 if (isa<DependentNameType>(T)) { 11862 DependentNameTypeLoc TL = 11863 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11864 TL.setElaboratedKeywordLoc(TagLoc); 11865 TL.setQualifierLoc(QualifierLoc); 11866 TL.setNameLoc(NameLoc); 11867 } else { 11868 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11869 TL.setElaboratedKeywordLoc(TagLoc); 11870 TL.setQualifierLoc(QualifierLoc); 11871 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 11872 } 11873 11874 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11875 TSI, FriendLoc, TempParamLists); 11876 Friend->setAccess(AS_public); 11877 CurContext->addDecl(Friend); 11878 return Friend; 11879 } 11880 11881 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 11882 11883 11884 11885 // Handle the case of a templated-scope friend class. e.g. 11886 // template <class T> class A<T>::B; 11887 // FIXME: we don't support these right now. 11888 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 11889 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 11890 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11891 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 11892 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11893 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11894 TL.setElaboratedKeywordLoc(TagLoc); 11895 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11896 TL.setNameLoc(NameLoc); 11897 11898 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11899 TSI, FriendLoc, TempParamLists); 11900 Friend->setAccess(AS_public); 11901 Friend->setUnsupportedFriend(true); 11902 CurContext->addDecl(Friend); 11903 return Friend; 11904 } 11905 11906 11907 /// Handle a friend type declaration. This works in tandem with 11908 /// ActOnTag. 11909 /// 11910 /// Notes on friend class templates: 11911 /// 11912 /// We generally treat friend class declarations as if they were 11913 /// declaring a class. So, for example, the elaborated type specifier 11914 /// in a friend declaration is required to obey the restrictions of a 11915 /// class-head (i.e. no typedefs in the scope chain), template 11916 /// parameters are required to match up with simple template-ids, &c. 11917 /// However, unlike when declaring a template specialization, it's 11918 /// okay to refer to a template specialization without an empty 11919 /// template parameter declaration, e.g. 11920 /// friend class A<T>::B<unsigned>; 11921 /// We permit this as a special case; if there are any template 11922 /// parameters present at all, require proper matching, i.e. 11923 /// template <> template \<class T> friend class A<int>::B; 11924 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 11925 MultiTemplateParamsArg TempParams) { 11926 SourceLocation Loc = DS.getLocStart(); 11927 11928 assert(DS.isFriendSpecified()); 11929 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11930 11931 // Try to convert the decl specifier to a type. This works for 11932 // friend templates because ActOnTag never produces a ClassTemplateDecl 11933 // for a TUK_Friend. 11934 Declarator TheDeclarator(DS, Declarator::MemberContext); 11935 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11936 QualType T = TSI->getType(); 11937 if (TheDeclarator.isInvalidType()) 11938 return nullptr; 11939 11940 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11941 return nullptr; 11942 11943 // This is definitely an error in C++98. It's probably meant to 11944 // be forbidden in C++0x, too, but the specification is just 11945 // poorly written. 11946 // 11947 // The problem is with declarations like the following: 11948 // template <T> friend A<T>::foo; 11949 // where deciding whether a class C is a friend or not now hinges 11950 // on whether there exists an instantiation of A that causes 11951 // 'foo' to equal C. There are restrictions on class-heads 11952 // (which we declare (by fiat) elaborated friend declarations to 11953 // be) that makes this tractable. 11954 // 11955 // FIXME: handle "template <> friend class A<T>;", which 11956 // is possibly well-formed? Who even knows? 11957 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11958 Diag(Loc, diag::err_tagless_friend_type_template) 11959 << DS.getSourceRange(); 11960 return nullptr; 11961 } 11962 11963 // C++98 [class.friend]p1: A friend of a class is a function 11964 // or class that is not a member of the class . . . 11965 // This is fixed in DR77, which just barely didn't make the C++03 11966 // deadline. It's also a very silly restriction that seriously 11967 // affects inner classes and which nobody else seems to implement; 11968 // thus we never diagnose it, not even in -pedantic. 11969 // 11970 // But note that we could warn about it: it's always useless to 11971 // friend one of your own members (it's not, however, worthless to 11972 // friend a member of an arbitrary specialization of your template). 11973 11974 Decl *D; 11975 if (unsigned NumTempParamLists = TempParams.size()) 11976 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11977 NumTempParamLists, 11978 TempParams.data(), 11979 TSI, 11980 DS.getFriendSpecLoc()); 11981 else 11982 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11983 11984 if (!D) 11985 return nullptr; 11986 11987 D->setAccess(AS_public); 11988 CurContext->addDecl(D); 11989 11990 return D; 11991 } 11992 11993 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11994 MultiTemplateParamsArg TemplateParams) { 11995 const DeclSpec &DS = D.getDeclSpec(); 11996 11997 assert(DS.isFriendSpecified()); 11998 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11999 12000 SourceLocation Loc = D.getIdentifierLoc(); 12001 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12002 12003 // C++ [class.friend]p1 12004 // A friend of a class is a function or class.... 12005 // Note that this sees through typedefs, which is intended. 12006 // It *doesn't* see through dependent types, which is correct 12007 // according to [temp.arg.type]p3: 12008 // If a declaration acquires a function type through a 12009 // type dependent on a template-parameter and this causes 12010 // a declaration that does not use the syntactic form of a 12011 // function declarator to have a function type, the program 12012 // is ill-formed. 12013 if (!TInfo->getType()->isFunctionType()) { 12014 Diag(Loc, diag::err_unexpected_friend); 12015 12016 // It might be worthwhile to try to recover by creating an 12017 // appropriate declaration. 12018 return nullptr; 12019 } 12020 12021 // C++ [namespace.memdef]p3 12022 // - If a friend declaration in a non-local class first declares a 12023 // class or function, the friend class or function is a member 12024 // of the innermost enclosing namespace. 12025 // - The name of the friend is not found by simple name lookup 12026 // until a matching declaration is provided in that namespace 12027 // scope (either before or after the class declaration granting 12028 // friendship). 12029 // - If a friend function is called, its name may be found by the 12030 // name lookup that considers functions from namespaces and 12031 // classes associated with the types of the function arguments. 12032 // - When looking for a prior declaration of a class or a function 12033 // declared as a friend, scopes outside the innermost enclosing 12034 // namespace scope are not considered. 12035 12036 CXXScopeSpec &SS = D.getCXXScopeSpec(); 12037 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 12038 DeclarationName Name = NameInfo.getName(); 12039 assert(Name); 12040 12041 // Check for unexpanded parameter packs. 12042 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 12043 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 12044 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 12045 return nullptr; 12046 12047 // The context we found the declaration in, or in which we should 12048 // create the declaration. 12049 DeclContext *DC; 12050 Scope *DCScope = S; 12051 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12052 ForRedeclaration); 12053 12054 // There are five cases here. 12055 // - There's no scope specifier and we're in a local class. Only look 12056 // for functions declared in the immediately-enclosing block scope. 12057 // We recover from invalid scope qualifiers as if they just weren't there. 12058 FunctionDecl *FunctionContainingLocalClass = nullptr; 12059 if ((SS.isInvalid() || !SS.isSet()) && 12060 (FunctionContainingLocalClass = 12061 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 12062 // C++11 [class.friend]p11: 12063 // If a friend declaration appears in a local class and the name 12064 // specified is an unqualified name, a prior declaration is 12065 // looked up without considering scopes that are outside the 12066 // innermost enclosing non-class scope. For a friend function 12067 // declaration, if there is no prior declaration, the program is 12068 // ill-formed. 12069 12070 // Find the innermost enclosing non-class scope. This is the block 12071 // scope containing the local class definition (or for a nested class, 12072 // the outer local class). 12073 DCScope = S->getFnParent(); 12074 12075 // Look up the function name in the scope. 12076 Previous.clear(LookupLocalFriendName); 12077 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 12078 12079 if (!Previous.empty()) { 12080 // All possible previous declarations must have the same context: 12081 // either they were declared at block scope or they are members of 12082 // one of the enclosing local classes. 12083 DC = Previous.getRepresentativeDecl()->getDeclContext(); 12084 } else { 12085 // This is ill-formed, but provide the context that we would have 12086 // declared the function in, if we were permitted to, for error recovery. 12087 DC = FunctionContainingLocalClass; 12088 } 12089 adjustContextForLocalExternDecl(DC); 12090 12091 // C++ [class.friend]p6: 12092 // A function can be defined in a friend declaration of a class if and 12093 // only if the class is a non-local class (9.8), the function name is 12094 // unqualified, and the function has namespace scope. 12095 if (D.isFunctionDefinition()) { 12096 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 12097 } 12098 12099 // - There's no scope specifier, in which case we just go to the 12100 // appropriate scope and look for a function or function template 12101 // there as appropriate. 12102 } else if (SS.isInvalid() || !SS.isSet()) { 12103 // C++11 [namespace.memdef]p3: 12104 // If the name in a friend declaration is neither qualified nor 12105 // a template-id and the declaration is a function or an 12106 // elaborated-type-specifier, the lookup to determine whether 12107 // the entity has been previously declared shall not consider 12108 // any scopes outside the innermost enclosing namespace. 12109 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 12110 12111 // Find the appropriate context according to the above. 12112 DC = CurContext; 12113 12114 // Skip class contexts. If someone can cite chapter and verse 12115 // for this behavior, that would be nice --- it's what GCC and 12116 // EDG do, and it seems like a reasonable intent, but the spec 12117 // really only says that checks for unqualified existing 12118 // declarations should stop at the nearest enclosing namespace, 12119 // not that they should only consider the nearest enclosing 12120 // namespace. 12121 while (DC->isRecord()) 12122 DC = DC->getParent(); 12123 12124 DeclContext *LookupDC = DC; 12125 while (LookupDC->isTransparentContext()) 12126 LookupDC = LookupDC->getParent(); 12127 12128 while (true) { 12129 LookupQualifiedName(Previous, LookupDC); 12130 12131 if (!Previous.empty()) { 12132 DC = LookupDC; 12133 break; 12134 } 12135 12136 if (isTemplateId) { 12137 if (isa<TranslationUnitDecl>(LookupDC)) break; 12138 } else { 12139 if (LookupDC->isFileContext()) break; 12140 } 12141 LookupDC = LookupDC->getParent(); 12142 } 12143 12144 DCScope = getScopeForDeclContext(S, DC); 12145 12146 // - There's a non-dependent scope specifier, in which case we 12147 // compute it and do a previous lookup there for a function 12148 // or function template. 12149 } else if (!SS.getScopeRep()->isDependent()) { 12150 DC = computeDeclContext(SS); 12151 if (!DC) return nullptr; 12152 12153 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 12154 12155 LookupQualifiedName(Previous, DC); 12156 12157 // Ignore things found implicitly in the wrong scope. 12158 // TODO: better diagnostics for this case. Suggesting the right 12159 // qualified scope would be nice... 12160 LookupResult::Filter F = Previous.makeFilter(); 12161 while (F.hasNext()) { 12162 NamedDecl *D = F.next(); 12163 if (!DC->InEnclosingNamespaceSetOf( 12164 D->getDeclContext()->getRedeclContext())) 12165 F.erase(); 12166 } 12167 F.done(); 12168 12169 if (Previous.empty()) { 12170 D.setInvalidType(); 12171 Diag(Loc, diag::err_qualified_friend_not_found) 12172 << Name << TInfo->getType(); 12173 return nullptr; 12174 } 12175 12176 // C++ [class.friend]p1: A friend of a class is a function or 12177 // class that is not a member of the class . . . 12178 if (DC->Equals(CurContext)) 12179 Diag(DS.getFriendSpecLoc(), 12180 getLangOpts().CPlusPlus11 ? 12181 diag::warn_cxx98_compat_friend_is_member : 12182 diag::err_friend_is_member); 12183 12184 if (D.isFunctionDefinition()) { 12185 // C++ [class.friend]p6: 12186 // A function can be defined in a friend declaration of a class if and 12187 // only if the class is a non-local class (9.8), the function name is 12188 // unqualified, and the function has namespace scope. 12189 SemaDiagnosticBuilder DB 12190 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 12191 12192 DB << SS.getScopeRep(); 12193 if (DC->isFileContext()) 12194 DB << FixItHint::CreateRemoval(SS.getRange()); 12195 SS.clear(); 12196 } 12197 12198 // - There's a scope specifier that does not match any template 12199 // parameter lists, in which case we use some arbitrary context, 12200 // create a method or method template, and wait for instantiation. 12201 // - There's a scope specifier that does match some template 12202 // parameter lists, which we don't handle right now. 12203 } else { 12204 if (D.isFunctionDefinition()) { 12205 // C++ [class.friend]p6: 12206 // A function can be defined in a friend declaration of a class if and 12207 // only if the class is a non-local class (9.8), the function name is 12208 // unqualified, and the function has namespace scope. 12209 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 12210 << SS.getScopeRep(); 12211 } 12212 12213 DC = CurContext; 12214 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 12215 } 12216 12217 if (!DC->isRecord()) { 12218 // This implies that it has to be an operator or function. 12219 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 12220 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 12221 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 12222 Diag(Loc, diag::err_introducing_special_friend) << 12223 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 12224 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 12225 return nullptr; 12226 } 12227 } 12228 12229 // FIXME: This is an egregious hack to cope with cases where the scope stack 12230 // does not contain the declaration context, i.e., in an out-of-line 12231 // definition of a class. 12232 Scope FakeDCScope(S, Scope::DeclScope, Diags); 12233 if (!DCScope) { 12234 FakeDCScope.setEntity(DC); 12235 DCScope = &FakeDCScope; 12236 } 12237 12238 bool AddToScope = true; 12239 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 12240 TemplateParams, AddToScope); 12241 if (!ND) return nullptr; 12242 12243 assert(ND->getLexicalDeclContext() == CurContext); 12244 12245 // If we performed typo correction, we might have added a scope specifier 12246 // and changed the decl context. 12247 DC = ND->getDeclContext(); 12248 12249 // Add the function declaration to the appropriate lookup tables, 12250 // adjusting the redeclarations list as necessary. We don't 12251 // want to do this yet if the friending class is dependent. 12252 // 12253 // Also update the scope-based lookup if the target context's 12254 // lookup context is in lexical scope. 12255 if (!CurContext->isDependentContext()) { 12256 DC = DC->getRedeclContext(); 12257 DC->makeDeclVisibleInContext(ND); 12258 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12259 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 12260 } 12261 12262 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 12263 D.getIdentifierLoc(), ND, 12264 DS.getFriendSpecLoc()); 12265 FrD->setAccess(AS_public); 12266 CurContext->addDecl(FrD); 12267 12268 if (ND->isInvalidDecl()) { 12269 FrD->setInvalidDecl(); 12270 } else { 12271 if (DC->isRecord()) CheckFriendAccess(ND); 12272 12273 FunctionDecl *FD; 12274 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 12275 FD = FTD->getTemplatedDecl(); 12276 else 12277 FD = cast<FunctionDecl>(ND); 12278 12279 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 12280 // default argument expression, that declaration shall be a definition 12281 // and shall be the only declaration of the function or function 12282 // template in the translation unit. 12283 if (functionDeclHasDefaultArgument(FD)) { 12284 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 12285 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 12286 Diag(OldFD->getLocation(), diag::note_previous_declaration); 12287 } else if (!D.isFunctionDefinition()) 12288 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 12289 } 12290 12291 // Mark templated-scope function declarations as unsupported. 12292 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 12293 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 12294 << SS.getScopeRep() << SS.getRange() 12295 << cast<CXXRecordDecl>(CurContext); 12296 FrD->setUnsupportedFriend(true); 12297 } 12298 } 12299 12300 return ND; 12301 } 12302 12303 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 12304 AdjustDeclIfTemplate(Dcl); 12305 12306 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 12307 if (!Fn) { 12308 Diag(DelLoc, diag::err_deleted_non_function); 12309 return; 12310 } 12311 12312 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 12313 // Don't consider the implicit declaration we generate for explicit 12314 // specializations. FIXME: Do not generate these implicit declarations. 12315 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 12316 Prev->getPreviousDecl()) && 12317 !Prev->isDefined()) { 12318 Diag(DelLoc, diag::err_deleted_decl_not_first); 12319 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 12320 Prev->isImplicit() ? diag::note_previous_implicit_declaration 12321 : diag::note_previous_declaration); 12322 } 12323 // If the declaration wasn't the first, we delete the function anyway for 12324 // recovery. 12325 Fn = Fn->getCanonicalDecl(); 12326 } 12327 12328 // dllimport/dllexport cannot be deleted. 12329 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 12330 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 12331 Fn->setInvalidDecl(); 12332 } 12333 12334 if (Fn->isDeleted()) 12335 return; 12336 12337 // See if we're deleting a function which is already known to override a 12338 // non-deleted virtual function. 12339 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 12340 bool IssuedDiagnostic = false; 12341 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 12342 E = MD->end_overridden_methods(); 12343 I != E; ++I) { 12344 if (!(*MD->begin_overridden_methods())->isDeleted()) { 12345 if (!IssuedDiagnostic) { 12346 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12347 IssuedDiagnostic = true; 12348 } 12349 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12350 } 12351 } 12352 } 12353 12354 // C++11 [basic.start.main]p3: 12355 // A program that defines main as deleted [...] is ill-formed. 12356 if (Fn->isMain()) 12357 Diag(DelLoc, diag::err_deleted_main); 12358 12359 Fn->setDeletedAsWritten(); 12360 } 12361 12362 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12363 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12364 12365 if (MD) { 12366 if (MD->getParent()->isDependentType()) { 12367 MD->setDefaulted(); 12368 MD->setExplicitlyDefaulted(); 12369 return; 12370 } 12371 12372 CXXSpecialMember Member = getSpecialMember(MD); 12373 if (Member == CXXInvalid) { 12374 if (!MD->isInvalidDecl()) 12375 Diag(DefaultLoc, diag::err_default_special_members); 12376 return; 12377 } 12378 12379 MD->setDefaulted(); 12380 MD->setExplicitlyDefaulted(); 12381 12382 // If this definition appears within the record, do the checking when 12383 // the record is complete. 12384 const FunctionDecl *Primary = MD; 12385 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12386 // Find the uninstantiated declaration that actually had the '= default' 12387 // on it. 12388 Pattern->isDefined(Primary); 12389 12390 // If the method was defaulted on its first declaration, we will have 12391 // already performed the checking in CheckCompletedCXXClass. Such a 12392 // declaration doesn't trigger an implicit definition. 12393 if (Primary == Primary->getCanonicalDecl()) 12394 return; 12395 12396 CheckExplicitlyDefaultedSpecialMember(MD); 12397 12398 if (MD->isInvalidDecl()) 12399 return; 12400 12401 switch (Member) { 12402 case CXXDefaultConstructor: 12403 DefineImplicitDefaultConstructor(DefaultLoc, 12404 cast<CXXConstructorDecl>(MD)); 12405 break; 12406 case CXXCopyConstructor: 12407 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12408 break; 12409 case CXXCopyAssignment: 12410 DefineImplicitCopyAssignment(DefaultLoc, MD); 12411 break; 12412 case CXXDestructor: 12413 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12414 break; 12415 case CXXMoveConstructor: 12416 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12417 break; 12418 case CXXMoveAssignment: 12419 DefineImplicitMoveAssignment(DefaultLoc, MD); 12420 break; 12421 case CXXInvalid: 12422 llvm_unreachable("Invalid special member."); 12423 } 12424 } else { 12425 Diag(DefaultLoc, diag::err_default_special_members); 12426 } 12427 } 12428 12429 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12430 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12431 Stmt *SubStmt = *CI; 12432 if (!SubStmt) 12433 continue; 12434 if (isa<ReturnStmt>(SubStmt)) 12435 Self.Diag(SubStmt->getLocStart(), 12436 diag::err_return_in_constructor_handler); 12437 if (!isa<Expr>(SubStmt)) 12438 SearchForReturnInStmt(Self, SubStmt); 12439 } 12440 } 12441 12442 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12443 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12444 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12445 SearchForReturnInStmt(*this, Handler); 12446 } 12447 } 12448 12449 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12450 const CXXMethodDecl *Old) { 12451 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12452 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12453 12454 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12455 12456 // If the calling conventions match, everything is fine 12457 if (NewCC == OldCC) 12458 return false; 12459 12460 // If the calling conventions mismatch because the new function is static, 12461 // suppress the calling convention mismatch error; the error about static 12462 // function override (err_static_overrides_virtual from 12463 // Sema::CheckFunctionDeclaration) is more clear. 12464 if (New->getStorageClass() == SC_Static) 12465 return false; 12466 12467 Diag(New->getLocation(), 12468 diag::err_conflicting_overriding_cc_attributes) 12469 << New->getDeclName() << New->getType() << Old->getType(); 12470 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12471 return true; 12472 } 12473 12474 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12475 const CXXMethodDecl *Old) { 12476 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12477 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12478 12479 if (Context.hasSameType(NewTy, OldTy) || 12480 NewTy->isDependentType() || OldTy->isDependentType()) 12481 return false; 12482 12483 // Check if the return types are covariant 12484 QualType NewClassTy, OldClassTy; 12485 12486 /// Both types must be pointers or references to classes. 12487 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12488 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12489 NewClassTy = NewPT->getPointeeType(); 12490 OldClassTy = OldPT->getPointeeType(); 12491 } 12492 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12493 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12494 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12495 NewClassTy = NewRT->getPointeeType(); 12496 OldClassTy = OldRT->getPointeeType(); 12497 } 12498 } 12499 } 12500 12501 // The return types aren't either both pointers or references to a class type. 12502 if (NewClassTy.isNull()) { 12503 Diag(New->getLocation(), 12504 diag::err_different_return_type_for_overriding_virtual_function) 12505 << New->getDeclName() << NewTy << OldTy 12506 << New->getReturnTypeSourceRange(); 12507 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12508 << Old->getReturnTypeSourceRange(); 12509 12510 return true; 12511 } 12512 12513 // C++ [class.virtual]p6: 12514 // If the return type of D::f differs from the return type of B::f, the 12515 // class type in the return type of D::f shall be complete at the point of 12516 // declaration of D::f or shall be the class type D. 12517 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12518 if (!RT->isBeingDefined() && 12519 RequireCompleteType(New->getLocation(), NewClassTy, 12520 diag::err_covariant_return_incomplete, 12521 New->getDeclName())) 12522 return true; 12523 } 12524 12525 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12526 // Check if the new class derives from the old class. 12527 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12528 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 12529 << New->getDeclName() << NewTy << OldTy 12530 << New->getReturnTypeSourceRange(); 12531 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12532 << Old->getReturnTypeSourceRange(); 12533 return true; 12534 } 12535 12536 // Check if we the conversion from derived to base is valid. 12537 if (CheckDerivedToBaseConversion( 12538 NewClassTy, OldClassTy, 12539 diag::err_covariant_return_inaccessible_base, 12540 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12541 New->getLocation(), New->getReturnTypeSourceRange(), 12542 New->getDeclName(), nullptr)) { 12543 // FIXME: this note won't trigger for delayed access control 12544 // diagnostics, and it's impossible to get an undelayed error 12545 // here from access control during the original parse because 12546 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12547 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12548 << Old->getReturnTypeSourceRange(); 12549 return true; 12550 } 12551 } 12552 12553 // The qualifiers of the return types must be the same. 12554 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12555 Diag(New->getLocation(), 12556 diag::err_covariant_return_type_different_qualifications) 12557 << New->getDeclName() << NewTy << OldTy 12558 << New->getReturnTypeSourceRange(); 12559 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12560 << Old->getReturnTypeSourceRange(); 12561 return true; 12562 }; 12563 12564 12565 // The new class type must have the same or less qualifiers as the old type. 12566 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12567 Diag(New->getLocation(), 12568 diag::err_covariant_return_type_class_type_more_qualified) 12569 << New->getDeclName() << NewTy << OldTy 12570 << New->getReturnTypeSourceRange(); 12571 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 12572 << Old->getReturnTypeSourceRange(); 12573 return true; 12574 }; 12575 12576 return false; 12577 } 12578 12579 /// \brief Mark the given method pure. 12580 /// 12581 /// \param Method the method to be marked pure. 12582 /// 12583 /// \param InitRange the source range that covers the "0" initializer. 12584 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12585 SourceLocation EndLoc = InitRange.getEnd(); 12586 if (EndLoc.isValid()) 12587 Method->setRangeEnd(EndLoc); 12588 12589 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12590 Method->setPure(); 12591 return false; 12592 } 12593 12594 if (!Method->isInvalidDecl()) 12595 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12596 << Method->getDeclName() << InitRange; 12597 return true; 12598 } 12599 12600 /// \brief Determine whether the given declaration is a static data member. 12601 static bool isStaticDataMember(const Decl *D) { 12602 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12603 return Var->isStaticDataMember(); 12604 12605 return false; 12606 } 12607 12608 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12609 /// an initializer for the out-of-line declaration 'Dcl'. The scope 12610 /// is a fresh scope pushed for just this purpose. 12611 /// 12612 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12613 /// static data member of class X, names should be looked up in the scope of 12614 /// class X. 12615 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12616 // If there is no declaration, there was an error parsing it. 12617 if (!D || D->isInvalidDecl()) 12618 return; 12619 12620 // We will always have a nested name specifier here, but this declaration 12621 // might not be out of line if the specifier names the current namespace: 12622 // extern int n; 12623 // int ::n = 0; 12624 if (D->isOutOfLine()) 12625 EnterDeclaratorContext(S, D->getDeclContext()); 12626 12627 // If we are parsing the initializer for a static data member, push a 12628 // new expression evaluation context that is associated with this static 12629 // data member. 12630 if (isStaticDataMember(D)) 12631 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12632 } 12633 12634 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12635 /// initializer for the out-of-line declaration 'D'. 12636 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12637 // If there is no declaration, there was an error parsing it. 12638 if (!D || D->isInvalidDecl()) 12639 return; 12640 12641 if (isStaticDataMember(D)) 12642 PopExpressionEvaluationContext(); 12643 12644 if (D->isOutOfLine()) 12645 ExitDeclaratorContext(S); 12646 } 12647 12648 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 12649 /// C++ if/switch/while/for statement. 12650 /// e.g: "if (int x = f()) {...}" 12651 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 12652 // C++ 6.4p2: 12653 // The declarator shall not specify a function or an array. 12654 // The type-specifier-seq shall not contain typedef and shall not declare a 12655 // new class or enumeration. 12656 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 12657 "Parser allowed 'typedef' as storage class of condition decl."); 12658 12659 Decl *Dcl = ActOnDeclarator(S, D); 12660 if (!Dcl) 12661 return true; 12662 12663 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 12664 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 12665 << D.getSourceRange(); 12666 return true; 12667 } 12668 12669 return Dcl; 12670 } 12671 12672 void Sema::LoadExternalVTableUses() { 12673 if (!ExternalSource) 12674 return; 12675 12676 SmallVector<ExternalVTableUse, 4> VTables; 12677 ExternalSource->ReadUsedVTables(VTables); 12678 SmallVector<VTableUse, 4> NewUses; 12679 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 12680 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 12681 = VTablesUsed.find(VTables[I].Record); 12682 // Even if a definition wasn't required before, it may be required now. 12683 if (Pos != VTablesUsed.end()) { 12684 if (!Pos->second && VTables[I].DefinitionRequired) 12685 Pos->second = true; 12686 continue; 12687 } 12688 12689 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 12690 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 12691 } 12692 12693 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 12694 } 12695 12696 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 12697 bool DefinitionRequired) { 12698 // Ignore any vtable uses in unevaluated operands or for classes that do 12699 // not have a vtable. 12700 if (!Class->isDynamicClass() || Class->isDependentContext() || 12701 CurContext->isDependentContext() || isUnevaluatedContext()) 12702 return; 12703 12704 // Try to insert this class into the map. 12705 LoadExternalVTableUses(); 12706 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12707 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 12708 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 12709 if (!Pos.second) { 12710 // If we already had an entry, check to see if we are promoting this vtable 12711 // to required a definition. If so, we need to reappend to the VTableUses 12712 // list, since we may have already processed the first entry. 12713 if (DefinitionRequired && !Pos.first->second) { 12714 Pos.first->second = true; 12715 } else { 12716 // Otherwise, we can early exit. 12717 return; 12718 } 12719 } else { 12720 // The Microsoft ABI requires that we perform the destructor body 12721 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 12722 // the deleting destructor is emitted with the vtable, not with the 12723 // destructor definition as in the Itanium ABI. 12724 // If it has a definition, we do the check at that point instead. 12725 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12726 Class->hasUserDeclaredDestructor() && 12727 !Class->getDestructor()->isDefined() && 12728 !Class->getDestructor()->isDeleted()) { 12729 CXXDestructorDecl *DD = Class->getDestructor(); 12730 ContextRAII SavedContext(*this, DD); 12731 CheckDestructor(DD); 12732 } 12733 } 12734 12735 // Local classes need to have their virtual members marked 12736 // immediately. For all other classes, we mark their virtual members 12737 // at the end of the translation unit. 12738 if (Class->isLocalClass()) 12739 MarkVirtualMembersReferenced(Loc, Class); 12740 else 12741 VTableUses.push_back(std::make_pair(Class, Loc)); 12742 } 12743 12744 bool Sema::DefineUsedVTables() { 12745 LoadExternalVTableUses(); 12746 if (VTableUses.empty()) 12747 return false; 12748 12749 // Note: The VTableUses vector could grow as a result of marking 12750 // the members of a class as "used", so we check the size each 12751 // time through the loop and prefer indices (which are stable) to 12752 // iterators (which are not). 12753 bool DefinedAnything = false; 12754 for (unsigned I = 0; I != VTableUses.size(); ++I) { 12755 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 12756 if (!Class) 12757 continue; 12758 12759 SourceLocation Loc = VTableUses[I].second; 12760 12761 bool DefineVTable = true; 12762 12763 // If this class has a key function, but that key function is 12764 // defined in another translation unit, we don't need to emit the 12765 // vtable even though we're using it. 12766 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 12767 if (KeyFunction && !KeyFunction->hasBody()) { 12768 // The key function is in another translation unit. 12769 DefineVTable = false; 12770 TemplateSpecializationKind TSK = 12771 KeyFunction->getTemplateSpecializationKind(); 12772 assert(TSK != TSK_ExplicitInstantiationDefinition && 12773 TSK != TSK_ImplicitInstantiation && 12774 "Instantiations don't have key functions"); 12775 (void)TSK; 12776 } else if (!KeyFunction) { 12777 // If we have a class with no key function that is the subject 12778 // of an explicit instantiation declaration, suppress the 12779 // vtable; it will live with the explicit instantiation 12780 // definition. 12781 bool IsExplicitInstantiationDeclaration 12782 = Class->getTemplateSpecializationKind() 12783 == TSK_ExplicitInstantiationDeclaration; 12784 for (auto R : Class->redecls()) { 12785 TemplateSpecializationKind TSK 12786 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 12787 if (TSK == TSK_ExplicitInstantiationDeclaration) 12788 IsExplicitInstantiationDeclaration = true; 12789 else if (TSK == TSK_ExplicitInstantiationDefinition) { 12790 IsExplicitInstantiationDeclaration = false; 12791 break; 12792 } 12793 } 12794 12795 if (IsExplicitInstantiationDeclaration) 12796 DefineVTable = false; 12797 } 12798 12799 // The exception specifications for all virtual members may be needed even 12800 // if we are not providing an authoritative form of the vtable in this TU. 12801 // We may choose to emit it available_externally anyway. 12802 if (!DefineVTable) { 12803 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 12804 continue; 12805 } 12806 12807 // Mark all of the virtual members of this class as referenced, so 12808 // that we can build a vtable. Then, tell the AST consumer that a 12809 // vtable for this class is required. 12810 DefinedAnything = true; 12811 MarkVirtualMembersReferenced(Loc, Class); 12812 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12813 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 12814 12815 // Optionally warn if we're emitting a weak vtable. 12816 if (Class->isExternallyVisible() && 12817 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 12818 const FunctionDecl *KeyFunctionDef = nullptr; 12819 if (!KeyFunction || 12820 (KeyFunction->hasBody(KeyFunctionDef) && 12821 KeyFunctionDef->isInlined())) 12822 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 12823 TSK_ExplicitInstantiationDefinition 12824 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 12825 << Class; 12826 } 12827 } 12828 VTableUses.clear(); 12829 12830 return DefinedAnything; 12831 } 12832 12833 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 12834 const CXXRecordDecl *RD) { 12835 for (const auto *I : RD->methods()) 12836 if (I->isVirtual() && !I->isPure()) 12837 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 12838 } 12839 12840 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 12841 const CXXRecordDecl *RD) { 12842 // Mark all functions which will appear in RD's vtable as used. 12843 CXXFinalOverriderMap FinalOverriders; 12844 RD->getFinalOverriders(FinalOverriders); 12845 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 12846 E = FinalOverriders.end(); 12847 I != E; ++I) { 12848 for (OverridingMethods::const_iterator OI = I->second.begin(), 12849 OE = I->second.end(); 12850 OI != OE; ++OI) { 12851 assert(OI->second.size() > 0 && "no final overrider"); 12852 CXXMethodDecl *Overrider = OI->second.front().Method; 12853 12854 // C++ [basic.def.odr]p2: 12855 // [...] A virtual member function is used if it is not pure. [...] 12856 if (!Overrider->isPure()) 12857 MarkFunctionReferenced(Loc, Overrider); 12858 } 12859 } 12860 12861 // Only classes that have virtual bases need a VTT. 12862 if (RD->getNumVBases() == 0) 12863 return; 12864 12865 for (const auto &I : RD->bases()) { 12866 const CXXRecordDecl *Base = 12867 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 12868 if (Base->getNumVBases() == 0) 12869 continue; 12870 MarkVirtualMembersReferenced(Loc, Base); 12871 } 12872 } 12873 12874 /// SetIvarInitializers - This routine builds initialization ASTs for the 12875 /// Objective-C implementation whose ivars need be initialized. 12876 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 12877 if (!getLangOpts().CPlusPlus) 12878 return; 12879 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 12880 SmallVector<ObjCIvarDecl*, 8> ivars; 12881 CollectIvarsToConstructOrDestruct(OID, ivars); 12882 if (ivars.empty()) 12883 return; 12884 SmallVector<CXXCtorInitializer*, 32> AllToInit; 12885 for (unsigned i = 0; i < ivars.size(); i++) { 12886 FieldDecl *Field = ivars[i]; 12887 if (Field->isInvalidDecl()) 12888 continue; 12889 12890 CXXCtorInitializer *Member; 12891 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 12892 InitializationKind InitKind = 12893 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 12894 12895 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 12896 ExprResult MemberInit = 12897 InitSeq.Perform(*this, InitEntity, InitKind, None); 12898 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 12899 // Note, MemberInit could actually come back empty if no initialization 12900 // is required (e.g., because it would call a trivial default constructor) 12901 if (!MemberInit.get() || MemberInit.isInvalid()) 12902 continue; 12903 12904 Member = 12905 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 12906 SourceLocation(), 12907 MemberInit.getAs<Expr>(), 12908 SourceLocation()); 12909 AllToInit.push_back(Member); 12910 12911 // Be sure that the destructor is accessible and is marked as referenced. 12912 if (const RecordType *RecordTy 12913 = Context.getBaseElementType(Field->getType()) 12914 ->getAs<RecordType>()) { 12915 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 12916 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 12917 MarkFunctionReferenced(Field->getLocation(), Destructor); 12918 CheckDestructorAccess(Field->getLocation(), Destructor, 12919 PDiag(diag::err_access_dtor_ivar) 12920 << Context.getBaseElementType(Field->getType())); 12921 } 12922 } 12923 } 12924 ObjCImplementation->setIvarInitializers(Context, 12925 AllToInit.data(), AllToInit.size()); 12926 } 12927 } 12928 12929 static 12930 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 12931 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 12932 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 12933 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 12934 Sema &S) { 12935 if (Ctor->isInvalidDecl()) 12936 return; 12937 12938 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 12939 12940 // Target may not be determinable yet, for instance if this is a dependent 12941 // call in an uninstantiated template. 12942 if (Target) { 12943 const FunctionDecl *FNTarget = nullptr; 12944 (void)Target->hasBody(FNTarget); 12945 Target = const_cast<CXXConstructorDecl*>( 12946 cast_or_null<CXXConstructorDecl>(FNTarget)); 12947 } 12948 12949 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 12950 // Avoid dereferencing a null pointer here. 12951 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 12952 12953 if (!Current.insert(Canonical)) 12954 return; 12955 12956 // We know that beyond here, we aren't chaining into a cycle. 12957 if (!Target || !Target->isDelegatingConstructor() || 12958 Target->isInvalidDecl() || Valid.count(TCanonical)) { 12959 Valid.insert(Current.begin(), Current.end()); 12960 Current.clear(); 12961 // We've hit a cycle. 12962 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 12963 Current.count(TCanonical)) { 12964 // If we haven't diagnosed this cycle yet, do so now. 12965 if (!Invalid.count(TCanonical)) { 12966 S.Diag((*Ctor->init_begin())->getSourceLocation(), 12967 diag::warn_delegating_ctor_cycle) 12968 << Ctor; 12969 12970 // Don't add a note for a function delegating directly to itself. 12971 if (TCanonical != Canonical) 12972 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 12973 12974 CXXConstructorDecl *C = Target; 12975 while (C->getCanonicalDecl() != Canonical) { 12976 const FunctionDecl *FNTarget = nullptr; 12977 (void)C->getTargetConstructor()->hasBody(FNTarget); 12978 assert(FNTarget && "Ctor cycle through bodiless function"); 12979 12980 C = const_cast<CXXConstructorDecl*>( 12981 cast<CXXConstructorDecl>(FNTarget)); 12982 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12983 } 12984 } 12985 12986 Invalid.insert(Current.begin(), Current.end()); 12987 Current.clear(); 12988 } else { 12989 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12990 } 12991 } 12992 12993 12994 void Sema::CheckDelegatingCtorCycles() { 12995 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12996 12997 for (DelegatingCtorDeclsType::iterator 12998 I = DelegatingCtorDecls.begin(ExternalSource), 12999 E = DelegatingCtorDecls.end(); 13000 I != E; ++I) 13001 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 13002 13003 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 13004 CE = Invalid.end(); 13005 CI != CE; ++CI) 13006 (*CI)->setInvalidDecl(); 13007 } 13008 13009 namespace { 13010 /// \brief AST visitor that finds references to the 'this' expression. 13011 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 13012 Sema &S; 13013 13014 public: 13015 explicit FindCXXThisExpr(Sema &S) : S(S) { } 13016 13017 bool VisitCXXThisExpr(CXXThisExpr *E) { 13018 S.Diag(E->getLocation(), diag::err_this_static_member_func) 13019 << E->isImplicit(); 13020 return false; 13021 } 13022 }; 13023 } 13024 13025 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 13026 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13027 if (!TSInfo) 13028 return false; 13029 13030 TypeLoc TL = TSInfo->getTypeLoc(); 13031 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13032 if (!ProtoTL) 13033 return false; 13034 13035 // C++11 [expr.prim.general]p3: 13036 // [The expression this] shall not appear before the optional 13037 // cv-qualifier-seq and it shall not appear within the declaration of a 13038 // static member function (although its type and value category are defined 13039 // within a static member function as they are within a non-static member 13040 // function). [ Note: this is because declaration matching does not occur 13041 // until the complete declarator is known. - end note ] 13042 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13043 FindCXXThisExpr Finder(*this); 13044 13045 // If the return type came after the cv-qualifier-seq, check it now. 13046 if (Proto->hasTrailingReturn() && 13047 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 13048 return true; 13049 13050 // Check the exception specification. 13051 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 13052 return true; 13053 13054 return checkThisInStaticMemberFunctionAttributes(Method); 13055 } 13056 13057 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 13058 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 13059 if (!TSInfo) 13060 return false; 13061 13062 TypeLoc TL = TSInfo->getTypeLoc(); 13063 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 13064 if (!ProtoTL) 13065 return false; 13066 13067 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 13068 FindCXXThisExpr Finder(*this); 13069 13070 switch (Proto->getExceptionSpecType()) { 13071 case EST_Uninstantiated: 13072 case EST_Unevaluated: 13073 case EST_BasicNoexcept: 13074 case EST_DynamicNone: 13075 case EST_MSAny: 13076 case EST_None: 13077 break; 13078 13079 case EST_ComputedNoexcept: 13080 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 13081 return true; 13082 13083 case EST_Dynamic: 13084 for (const auto &E : Proto->exceptions()) { 13085 if (!Finder.TraverseType(E)) 13086 return true; 13087 } 13088 break; 13089 } 13090 13091 return false; 13092 } 13093 13094 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 13095 FindCXXThisExpr Finder(*this); 13096 13097 // Check attributes. 13098 for (const auto *A : Method->attrs()) { 13099 // FIXME: This should be emitted by tblgen. 13100 Expr *Arg = nullptr; 13101 ArrayRef<Expr *> Args; 13102 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 13103 Arg = G->getArg(); 13104 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 13105 Arg = G->getArg(); 13106 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 13107 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 13108 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 13109 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 13110 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 13111 Arg = ETLF->getSuccessValue(); 13112 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 13113 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 13114 Arg = STLF->getSuccessValue(); 13115 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 13116 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 13117 Arg = LR->getArg(); 13118 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 13119 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 13120 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 13121 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13122 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 13123 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13124 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 13125 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 13126 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 13127 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 13128 13129 if (Arg && !Finder.TraverseStmt(Arg)) 13130 return true; 13131 13132 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 13133 if (!Finder.TraverseStmt(Args[I])) 13134 return true; 13135 } 13136 } 13137 13138 return false; 13139 } 13140 13141 void 13142 Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 13143 ArrayRef<ParsedType> DynamicExceptions, 13144 ArrayRef<SourceRange> DynamicExceptionRanges, 13145 Expr *NoexceptExpr, 13146 SmallVectorImpl<QualType> &Exceptions, 13147 FunctionProtoType::ExceptionSpecInfo &ESI) { 13148 Exceptions.clear(); 13149 ESI.Type = EST; 13150 if (EST == EST_Dynamic) { 13151 Exceptions.reserve(DynamicExceptions.size()); 13152 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 13153 // FIXME: Preserve type source info. 13154 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 13155 13156 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 13157 collectUnexpandedParameterPacks(ET, Unexpanded); 13158 if (!Unexpanded.empty()) { 13159 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 13160 UPPC_ExceptionType, 13161 Unexpanded); 13162 continue; 13163 } 13164 13165 // Check that the type is valid for an exception spec, and 13166 // drop it if not. 13167 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 13168 Exceptions.push_back(ET); 13169 } 13170 ESI.Exceptions = Exceptions; 13171 return; 13172 } 13173 13174 if (EST == EST_ComputedNoexcept) { 13175 // If an error occurred, there's no expression here. 13176 if (NoexceptExpr) { 13177 assert((NoexceptExpr->isTypeDependent() || 13178 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 13179 Context.BoolTy) && 13180 "Parser should have made sure that the expression is boolean"); 13181 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 13182 ESI.Type = EST_BasicNoexcept; 13183 return; 13184 } 13185 13186 if (!NoexceptExpr->isValueDependent()) 13187 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr, 13188 diag::err_noexcept_needs_constant_expression, 13189 /*AllowFold*/ false).get(); 13190 ESI.NoexceptExpr = NoexceptExpr; 13191 } 13192 return; 13193 } 13194 } 13195 13196 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 13197 /// 13198 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 13199 SourceLocation DeclStart, 13200 Declarator &D, Expr *BitWidth, 13201 InClassInitStyle InitStyle, 13202 AccessSpecifier AS, 13203 AttributeList *MSPropertyAttr) { 13204 IdentifierInfo *II = D.getIdentifier(); 13205 if (!II) { 13206 Diag(DeclStart, diag::err_anonymous_property); 13207 return nullptr; 13208 } 13209 SourceLocation Loc = D.getIdentifierLoc(); 13210 13211 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13212 QualType T = TInfo->getType(); 13213 if (getLangOpts().CPlusPlus) { 13214 CheckExtraCXXDefaultArguments(D); 13215 13216 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 13217 UPPC_DataMemberType)) { 13218 D.setInvalidType(); 13219 T = Context.IntTy; 13220 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 13221 } 13222 } 13223 13224 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 13225 13226 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 13227 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 13228 diag::err_invalid_thread) 13229 << DeclSpec::getSpecifierName(TSCS); 13230 13231 // Check to see if this name was declared as a member previously 13232 NamedDecl *PrevDecl = nullptr; 13233 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 13234 LookupName(Previous, S); 13235 switch (Previous.getResultKind()) { 13236 case LookupResult::Found: 13237 case LookupResult::FoundUnresolvedValue: 13238 PrevDecl = Previous.getAsSingle<NamedDecl>(); 13239 break; 13240 13241 case LookupResult::FoundOverloaded: 13242 PrevDecl = Previous.getRepresentativeDecl(); 13243 break; 13244 13245 case LookupResult::NotFound: 13246 case LookupResult::NotFoundInCurrentInstantiation: 13247 case LookupResult::Ambiguous: 13248 break; 13249 } 13250 13251 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13252 // Maybe we will complain about the shadowed template parameter. 13253 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13254 // Just pretend that we didn't see the previous declaration. 13255 PrevDecl = nullptr; 13256 } 13257 13258 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 13259 PrevDecl = nullptr; 13260 13261 SourceLocation TSSL = D.getLocStart(); 13262 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 13263 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 13264 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 13265 ProcessDeclAttributes(TUScope, NewPD, D); 13266 NewPD->setAccess(AS); 13267 13268 if (NewPD->isInvalidDecl()) 13269 Record->setInvalidDecl(); 13270 13271 if (D.getDeclSpec().isModulePrivateSpecified()) 13272 NewPD->setModulePrivate(); 13273 13274 if (NewPD->isInvalidDecl() && PrevDecl) { 13275 // Don't introduce NewFD into scope; there's already something 13276 // with the same name in the same scope. 13277 } else if (II) { 13278 PushOnScopeChains(NewPD, S); 13279 } else 13280 Record->addDecl(NewPD); 13281 13282 return NewPD; 13283 } 13284