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/DeclVisitor.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/RecordLayout.h" 25 #include "clang/AST/RecursiveASTVisitor.h" 26 #include "clang/AST/StmtVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/AST/TypeOrdering.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/LiteralSupport.h" 32 #include "clang/Lex/Preprocessor.h" 33 #include "clang/Sema/CXXFieldCollector.h" 34 #include "clang/Sema/DeclSpec.h" 35 #include "clang/Sema/Initialization.h" 36 #include "clang/Sema/Lookup.h" 37 #include "clang/Sema/ParsedTemplate.h" 38 #include "clang/Sema/Scope.h" 39 #include "clang/Sema/ScopeInfo.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/SmallString.h" 42 #include <map> 43 #include <set> 44 45 using namespace clang; 46 47 //===----------------------------------------------------------------------===// 48 // CheckDefaultArgumentVisitor 49 //===----------------------------------------------------------------------===// 50 51 namespace { 52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 53 /// the default argument of a parameter to determine whether it 54 /// contains any ill-formed subexpressions. For example, this will 55 /// diagnose the use of local variables or parameters within the 56 /// default argument expression. 57 class CheckDefaultArgumentVisitor 58 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 59 Expr *DefaultArg; 60 Sema *S; 61 62 public: 63 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 64 : DefaultArg(defarg), S(s) {} 65 66 bool VisitExpr(Expr *Node); 67 bool VisitDeclRefExpr(DeclRefExpr *DRE); 68 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 69 bool VisitLambdaExpr(LambdaExpr *Lambda); 70 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 71 }; 72 73 /// VisitExpr - Visit all of the children of this expression. 74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 75 bool IsInvalid = false; 76 for (Stmt::child_range I = Node->children(); I; ++I) 77 IsInvalid |= Visit(*I); 78 return IsInvalid; 79 } 80 81 /// VisitDeclRefExpr - Visit a reference to a declaration, to 82 /// determine whether this declaration can be used in the default 83 /// argument expression. 84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 85 NamedDecl *Decl = DRE->getDecl(); 86 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 87 // C++ [dcl.fct.default]p9 88 // Default arguments are evaluated each time the function is 89 // called. The order of evaluation of function arguments is 90 // unspecified. Consequently, parameters of a function shall not 91 // be used in default argument expressions, even if they are not 92 // evaluated. Parameters of a function declared before a default 93 // argument expression are in scope and can hide namespace and 94 // class member names. 95 return S->Diag(DRE->getLocStart(), 96 diag::err_param_default_argument_references_param) 97 << Param->getDeclName() << DefaultArg->getSourceRange(); 98 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 99 // C++ [dcl.fct.default]p7 100 // Local variables shall not be used in default argument 101 // expressions. 102 if (VDecl->isLocalVarDecl()) 103 return S->Diag(DRE->getLocStart(), 104 diag::err_param_default_argument_references_local) 105 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 106 } 107 108 return false; 109 } 110 111 /// VisitCXXThisExpr - Visit a C++ "this" expression. 112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 113 // C++ [dcl.fct.default]p8: 114 // The keyword this shall not be used in a default argument of a 115 // member function. 116 return S->Diag(ThisE->getLocStart(), 117 diag::err_param_default_argument_references_this) 118 << ThisE->getSourceRange(); 119 } 120 121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 122 bool Invalid = false; 123 for (PseudoObjectExpr::semantics_iterator 124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 125 Expr *E = *i; 126 127 // Look through bindings. 128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 129 E = OVE->getSourceExpr(); 130 assert(E && "pseudo-object binding without source expression?"); 131 } 132 133 Invalid |= Visit(E); 134 } 135 return Invalid; 136 } 137 138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 139 // C++11 [expr.lambda.prim]p13: 140 // A lambda-expression appearing in a default argument shall not 141 // implicitly or explicitly capture any entity. 142 if (Lambda->capture_begin() == Lambda->capture_end()) 143 return false; 144 145 return S->Diag(Lambda->getLocStart(), 146 diag::err_lambda_capture_default_arg); 147 } 148 } 149 150 void 151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 152 const CXXMethodDecl *Method) { 153 // If we have an MSAny spec already, don't bother. 154 if (!Method || ComputedEST == EST_MSAny) 155 return; 156 157 const FunctionProtoType *Proto 158 = Method->getType()->getAs<FunctionProtoType>(); 159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 160 if (!Proto) 161 return; 162 163 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 164 165 // If this function can throw any exceptions, make a note of that. 166 if (EST == EST_MSAny || EST == EST_None) { 167 ClearExceptions(); 168 ComputedEST = EST; 169 return; 170 } 171 172 // FIXME: If the call to this decl is using any of its default arguments, we 173 // need to search them for potentially-throwing calls. 174 175 // If this function has a basic noexcept, it doesn't affect the outcome. 176 if (EST == EST_BasicNoexcept) 177 return; 178 179 // If we have a throw-all spec at this point, ignore the function. 180 if (ComputedEST == EST_None) 181 return; 182 183 // If we're still at noexcept(true) and there's a nothrow() callee, 184 // change to that specification. 185 if (EST == EST_DynamicNone) { 186 if (ComputedEST == EST_BasicNoexcept) 187 ComputedEST = EST_DynamicNone; 188 return; 189 } 190 191 // Check out noexcept specs. 192 if (EST == EST_ComputedNoexcept) { 193 FunctionProtoType::NoexceptResult NR = 194 Proto->getNoexceptSpec(Self->Context); 195 assert(NR != FunctionProtoType::NR_NoNoexcept && 196 "Must have noexcept result for EST_ComputedNoexcept."); 197 assert(NR != FunctionProtoType::NR_Dependent && 198 "Should not generate implicit declarations for dependent cases, " 199 "and don't know how to handle them anyway."); 200 201 // noexcept(false) -> no spec on the new function 202 if (NR == FunctionProtoType::NR_Throw) { 203 ClearExceptions(); 204 ComputedEST = EST_None; 205 } 206 // noexcept(true) won't change anything either. 207 return; 208 } 209 210 assert(EST == EST_Dynamic && "EST case not considered earlier."); 211 assert(ComputedEST != EST_None && 212 "Shouldn't collect exceptions when throw-all is guaranteed."); 213 ComputedEST = EST_Dynamic; 214 // Record the exceptions in this function's exception specification. 215 for (const auto &E : Proto->exceptions()) 216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E))) 217 Exceptions.push_back(E); 218 } 219 220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 221 if (!E || ComputedEST == EST_MSAny) 222 return; 223 224 // FIXME: 225 // 226 // C++0x [except.spec]p14: 227 // [An] implicit exception-specification specifies the type-id T if and 228 // only if T is allowed by the exception-specification of a function directly 229 // invoked by f's implicit definition; f shall allow all exceptions if any 230 // function it directly invokes allows all exceptions, and f shall allow no 231 // exceptions if every function it directly invokes allows no exceptions. 232 // 233 // Note in particular that if an implicit exception-specification is generated 234 // for a function containing a throw-expression, that specification can still 235 // be noexcept(true). 236 // 237 // Note also that 'directly invoked' is not defined in the standard, and there 238 // is no indication that we should only consider potentially-evaluated calls. 239 // 240 // Ultimately we should implement the intent of the standard: the exception 241 // specification should be the set of exceptions which can be thrown by the 242 // implicit definition. For now, we assume that any non-nothrow expression can 243 // throw any exception. 244 245 if (Self->canThrow(E)) 246 ComputedEST = EST_None; 247 } 248 249 bool 250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 251 SourceLocation EqualLoc) { 252 if (RequireCompleteType(Param->getLocation(), Param->getType(), 253 diag::err_typecheck_decl_incomplete_type)) { 254 Param->setInvalidDecl(); 255 return true; 256 } 257 258 // C++ [dcl.fct.default]p5 259 // A default argument expression is implicitly converted (clause 260 // 4) to the parameter type. The default argument expression has 261 // the same semantic constraints as the initializer expression in 262 // a declaration of a variable of the parameter type, using the 263 // copy-initialization semantics (8.5). 264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 265 Param); 266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 267 EqualLoc); 268 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 270 if (Result.isInvalid()) 271 return true; 272 Arg = Result.takeAs<Expr>(); 273 274 CheckCompletedExpr(Arg, EqualLoc); 275 Arg = MaybeCreateExprWithCleanups(Arg); 276 277 // Okay: add the default argument to the parameter 278 Param->setDefaultArg(Arg); 279 280 // We have already instantiated this parameter; provide each of the 281 // instantiations with the uninstantiated default argument. 282 UnparsedDefaultArgInstantiationsMap::iterator InstPos 283 = UnparsedDefaultArgInstantiations.find(Param); 284 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 287 288 // We're done tracking this parameter's instantiations. 289 UnparsedDefaultArgInstantiations.erase(InstPos); 290 } 291 292 return false; 293 } 294 295 /// ActOnParamDefaultArgument - Check whether the default argument 296 /// provided for a function parameter is well-formed. If so, attach it 297 /// to the parameter declaration. 298 void 299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 300 Expr *DefaultArg) { 301 if (!param || !DefaultArg) 302 return; 303 304 ParmVarDecl *Param = cast<ParmVarDecl>(param); 305 UnparsedDefaultArgLocs.erase(Param); 306 307 // Default arguments are only permitted in C++ 308 if (!getLangOpts().CPlusPlus) { 309 Diag(EqualLoc, diag::err_param_default_argument) 310 << DefaultArg->getSourceRange(); 311 Param->setInvalidDecl(); 312 return; 313 } 314 315 // Check for unexpanded parameter packs. 316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 317 Param->setInvalidDecl(); 318 return; 319 } 320 321 // Check that the default argument is well-formed 322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 323 if (DefaultArgChecker.Visit(DefaultArg)) { 324 Param->setInvalidDecl(); 325 return; 326 } 327 328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 329 } 330 331 /// ActOnParamUnparsedDefaultArgument - We've seen a default 332 /// argument for a function parameter, but we can't parse it yet 333 /// because we're inside a class definition. Note that this default 334 /// argument will be parsed later. 335 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 336 SourceLocation EqualLoc, 337 SourceLocation ArgLoc) { 338 if (!param) 339 return; 340 341 ParmVarDecl *Param = cast<ParmVarDecl>(param); 342 Param->setUnparsedDefaultArg(); 343 UnparsedDefaultArgLocs[Param] = ArgLoc; 344 } 345 346 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 347 /// the default argument for the parameter param failed. 348 void Sema::ActOnParamDefaultArgumentError(Decl *param) { 349 if (!param) 350 return; 351 352 ParmVarDecl *Param = cast<ParmVarDecl>(param); 353 Param->setInvalidDecl(); 354 UnparsedDefaultArgLocs.erase(Param); 355 } 356 357 /// CheckExtraCXXDefaultArguments - Check for any extra default 358 /// arguments in the declarator, which is not a function declaration 359 /// or definition and therefore is not permitted to have default 360 /// arguments. This routine should be invoked for every declarator 361 /// that is not a function declaration or definition. 362 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 363 // C++ [dcl.fct.default]p3 364 // A default argument expression shall be specified only in the 365 // parameter-declaration-clause of a function declaration or in a 366 // template-parameter (14.1). It shall not be specified for a 367 // parameter pack. If it is specified in a 368 // parameter-declaration-clause, it shall not occur within a 369 // declarator or abstract-declarator of a parameter-declaration. 370 bool MightBeFunction = D.isFunctionDeclarationContext(); 371 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 372 DeclaratorChunk &chunk = D.getTypeObject(i); 373 if (chunk.Kind == DeclaratorChunk::Function) { 374 if (MightBeFunction) { 375 // This is a function declaration. It can have default arguments, but 376 // keep looking in case its return type is a function type with default 377 // arguments. 378 MightBeFunction = false; 379 continue; 380 } 381 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 382 ++argIdx) { 383 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 384 if (Param->hasUnparsedDefaultArg()) { 385 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens; 386 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 387 << SourceRange((*Toks)[1].getLocation(), 388 Toks->back().getLocation()); 389 delete Toks; 390 chunk.Fun.Params[argIdx].DefaultArgTokens = 0; 391 } else if (Param->getDefaultArg()) { 392 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 393 << Param->getDefaultArg()->getSourceRange(); 394 Param->setDefaultArg(0); 395 } 396 } 397 } else if (chunk.Kind != DeclaratorChunk::Paren) { 398 MightBeFunction = false; 399 } 400 } 401 } 402 403 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 404 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 405 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 406 if (!PVD->hasDefaultArg()) 407 return false; 408 if (!PVD->hasInheritedDefaultArg()) 409 return true; 410 } 411 return false; 412 } 413 414 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 415 /// function, once we already know that they have the same 416 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 417 /// error, false otherwise. 418 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 419 Scope *S) { 420 bool Invalid = false; 421 422 // C++ [dcl.fct.default]p4: 423 // For non-template functions, default arguments can be added in 424 // later declarations of a function in the same 425 // scope. Declarations in different scopes have completely 426 // distinct sets of default arguments. That is, declarations in 427 // inner scopes do not acquire default arguments from 428 // declarations in outer scopes, and vice versa. In a given 429 // function declaration, all parameters subsequent to a 430 // parameter with a default argument shall have default 431 // arguments supplied in this or previous declarations. A 432 // default argument shall not be redefined by a later 433 // declaration (not even to the same value). 434 // 435 // C++ [dcl.fct.default]p6: 436 // Except for member functions of class templates, the default arguments 437 // in a member function definition that appears outside of the class 438 // definition are added to the set of default arguments provided by the 439 // member function declaration in the class definition. 440 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 441 ParmVarDecl *OldParam = Old->getParamDecl(p); 442 ParmVarDecl *NewParam = New->getParamDecl(p); 443 444 bool OldParamHasDfl = OldParam->hasDefaultArg(); 445 bool NewParamHasDfl = NewParam->hasDefaultArg(); 446 447 NamedDecl *ND = Old; 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->getLexicalDeclContext(); 453 if (!ScopeDC->isFunctionOrMethod()) 454 ScopeDC = New->getDeclContext(); 455 if (S && !isDeclInScope(ND, 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 462 if (OldParamHasDfl && NewParamHasDfl) { 463 464 unsigned DiagDefaultParamID = 465 diag::err_param_default_argument_redefinition; 466 467 // MSVC accepts that default parameters be redefined for member functions 468 // of template class. The new default parameter's value is ignored. 469 Invalid = true; 470 if (getLangOpts().MicrosoftExt) { 471 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 472 if (MD && MD->getParent()->getDescribedClassTemplate()) { 473 // Merge the old default argument into the new parameter. 474 NewParam->setHasInheritedDefaultArg(); 475 if (OldParam->hasUninstantiatedDefaultArg()) 476 NewParam->setUninstantiatedDefaultArg( 477 OldParam->getUninstantiatedDefaultArg()); 478 else 479 NewParam->setDefaultArg(OldParam->getInit()); 480 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 481 Invalid = false; 482 } 483 } 484 485 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 486 // hint here. Alternatively, we could walk the type-source information 487 // for NewParam to find the last source location in the type... but it 488 // isn't worth the effort right now. This is the kind of test case that 489 // is hard to get right: 490 // int f(int); 491 // void g(int (*fp)(int) = f); 492 // void g(int (*fp)(int) = &f); 493 Diag(NewParam->getLocation(), DiagDefaultParamID) 494 << NewParam->getDefaultArgRange(); 495 496 // Look for the function declaration where the default argument was 497 // actually written, which may be a declaration prior to Old. 498 for (FunctionDecl *Older = Old->getPreviousDecl(); 499 Older; Older = Older->getPreviousDecl()) { 500 if (!Older->getParamDecl(p)->hasDefaultArg()) 501 break; 502 503 OldParam = Older->getParamDecl(p); 504 } 505 506 Diag(OldParam->getLocation(), diag::note_previous_definition) 507 << OldParam->getDefaultArgRange(); 508 } else if (OldParamHasDfl) { 509 // Merge the old default argument into the new parameter. 510 // It's important to use getInit() here; getDefaultArg() 511 // strips off any top-level ExprWithCleanups. 512 NewParam->setHasInheritedDefaultArg(); 513 if (OldParam->hasUninstantiatedDefaultArg()) 514 NewParam->setUninstantiatedDefaultArg( 515 OldParam->getUninstantiatedDefaultArg()); 516 else 517 NewParam->setDefaultArg(OldParam->getInit()); 518 } else if (NewParamHasDfl) { 519 if (New->getDescribedFunctionTemplate()) { 520 // Paragraph 4, quoted above, only applies to non-template functions. 521 Diag(NewParam->getLocation(), 522 diag::err_param_default_argument_template_redecl) 523 << NewParam->getDefaultArgRange(); 524 Diag(Old->getLocation(), diag::note_template_prev_declaration) 525 << false; 526 } else if (New->getTemplateSpecializationKind() 527 != TSK_ImplicitInstantiation && 528 New->getTemplateSpecializationKind() != TSK_Undeclared) { 529 // C++ [temp.expr.spec]p21: 530 // Default function arguments shall not be specified in a declaration 531 // or a definition for one of the following explicit specializations: 532 // - the explicit specialization of a function template; 533 // - the explicit specialization of a member function template; 534 // - the explicit specialization of a member function of a class 535 // template where the class template specialization to which the 536 // member function specialization belongs is implicitly 537 // instantiated. 538 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 539 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 540 << New->getDeclName() 541 << NewParam->getDefaultArgRange(); 542 } else if (New->getDeclContext()->isDependentContext()) { 543 // C++ [dcl.fct.default]p6 (DR217): 544 // Default arguments for a member function of a class template shall 545 // be specified on the initial declaration of the member function 546 // within the class template. 547 // 548 // Reading the tea leaves a bit in DR217 and its reference to DR205 549 // leads me to the conclusion that one cannot add default function 550 // arguments for an out-of-line definition of a member function of a 551 // dependent type. 552 int WhichKind = 2; 553 if (CXXRecordDecl *Record 554 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 555 if (Record->getDescribedClassTemplate()) 556 WhichKind = 0; 557 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 558 WhichKind = 1; 559 else 560 WhichKind = 2; 561 } 562 563 Diag(NewParam->getLocation(), 564 diag::err_param_default_argument_member_template_redecl) 565 << WhichKind 566 << NewParam->getDefaultArgRange(); 567 } 568 } 569 } 570 571 // DR1344: If a default argument is added outside a class definition and that 572 // default argument makes the function a special member function, the program 573 // is ill-formed. This can only happen for constructors. 574 if (isa<CXXConstructorDecl>(New) && 575 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 576 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 577 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 578 if (NewSM != OldSM) { 579 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 580 assert(NewParam->hasDefaultArg()); 581 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 582 << NewParam->getDefaultArgRange() << NewSM; 583 Diag(Old->getLocation(), diag::note_previous_declaration); 584 } 585 } 586 587 const FunctionDecl *Def; 588 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 589 // template has a constexpr specifier then all its declarations shall 590 // contain the constexpr specifier. 591 if (New->isConstexpr() != Old->isConstexpr()) { 592 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 593 << New << New->isConstexpr(); 594 Diag(Old->getLocation(), diag::note_previous_declaration); 595 Invalid = true; 596 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) { 597 // C++11 [dcl.fcn.spec]p4: 598 // If the definition of a function appears in a translation unit before its 599 // first declaration as inline, the program is ill-formed. 600 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 601 Diag(Def->getLocation(), diag::note_previous_definition); 602 Invalid = true; 603 } 604 605 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 606 // argument expression, that declaration shall be a definition and shall be 607 // the only declaration of the function or function template in the 608 // translation unit. 609 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 610 functionDeclHasDefaultArgument(Old)) { 611 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 612 Diag(Old->getLocation(), diag::note_previous_declaration); 613 Invalid = true; 614 } 615 616 if (CheckEquivalentExceptionSpec(Old, New)) 617 Invalid = true; 618 619 return Invalid; 620 } 621 622 /// \brief Merge the exception specifications of two variable declarations. 623 /// 624 /// This is called when there's a redeclaration of a VarDecl. The function 625 /// checks if the redeclaration might have an exception specification and 626 /// validates compatibility and merges the specs if necessary. 627 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 628 // Shortcut if exceptions are disabled. 629 if (!getLangOpts().CXXExceptions) 630 return; 631 632 assert(Context.hasSameType(New->getType(), Old->getType()) && 633 "Should only be called if types are otherwise the same."); 634 635 QualType NewType = New->getType(); 636 QualType OldType = Old->getType(); 637 638 // We're only interested in pointers and references to functions, as well 639 // as pointers to member functions. 640 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 641 NewType = R->getPointeeType(); 642 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 643 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 644 NewType = P->getPointeeType(); 645 OldType = OldType->getAs<PointerType>()->getPointeeType(); 646 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 647 NewType = M->getPointeeType(); 648 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 649 } 650 651 if (!NewType->isFunctionProtoType()) 652 return; 653 654 // There's lots of special cases for functions. For function pointers, system 655 // libraries are hopefully not as broken so that we don't need these 656 // workarounds. 657 if (CheckEquivalentExceptionSpec( 658 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 659 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 660 New->setInvalidDecl(); 661 } 662 } 663 664 /// CheckCXXDefaultArguments - Verify that the default arguments for a 665 /// function declaration are well-formed according to C++ 666 /// [dcl.fct.default]. 667 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 668 unsigned NumParams = FD->getNumParams(); 669 unsigned p; 670 671 // Find first parameter with a default argument 672 for (p = 0; p < NumParams; ++p) { 673 ParmVarDecl *Param = FD->getParamDecl(p); 674 if (Param->hasDefaultArg()) 675 break; 676 } 677 678 // C++ [dcl.fct.default]p4: 679 // In a given function declaration, all parameters 680 // subsequent to a parameter with a default argument shall 681 // have default arguments supplied in this or previous 682 // declarations. A default argument shall not be redefined 683 // by a later declaration (not even to the same value). 684 unsigned LastMissingDefaultArg = 0; 685 for (; p < NumParams; ++p) { 686 ParmVarDecl *Param = FD->getParamDecl(p); 687 if (!Param->hasDefaultArg()) { 688 if (Param->isInvalidDecl()) 689 /* We already complained about this parameter. */; 690 else if (Param->getIdentifier()) 691 Diag(Param->getLocation(), 692 diag::err_param_default_argument_missing_name) 693 << Param->getIdentifier(); 694 else 695 Diag(Param->getLocation(), 696 diag::err_param_default_argument_missing); 697 698 LastMissingDefaultArg = p; 699 } 700 } 701 702 if (LastMissingDefaultArg > 0) { 703 // Some default arguments were missing. Clear out all of the 704 // default arguments up to (and including) the last missing 705 // default argument, so that we leave the function parameters 706 // in a semantically valid state. 707 for (p = 0; p <= LastMissingDefaultArg; ++p) { 708 ParmVarDecl *Param = FD->getParamDecl(p); 709 if (Param->hasDefaultArg()) { 710 Param->setDefaultArg(0); 711 } 712 } 713 } 714 } 715 716 // CheckConstexprParameterTypes - Check whether a function's parameter types 717 // are all literal types. If so, return true. If not, produce a suitable 718 // diagnostic and return false. 719 static bool CheckConstexprParameterTypes(Sema &SemaRef, 720 const FunctionDecl *FD) { 721 unsigned ArgIndex = 0; 722 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 723 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 724 e = FT->param_type_end(); 725 i != e; ++i, ++ArgIndex) { 726 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 727 SourceLocation ParamLoc = PD->getLocation(); 728 if (!(*i)->isDependentType() && 729 SemaRef.RequireLiteralType(ParamLoc, *i, 730 diag::err_constexpr_non_literal_param, 731 ArgIndex+1, PD->getSourceRange(), 732 isa<CXXConstructorDecl>(FD))) 733 return false; 734 } 735 return true; 736 } 737 738 /// \brief Get diagnostic %select index for tag kind for 739 /// record diagnostic message. 740 /// WARNING: Indexes apply to particular diagnostics only! 741 /// 742 /// \returns diagnostic %select index. 743 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 744 switch (Tag) { 745 case TTK_Struct: return 0; 746 case TTK_Interface: return 1; 747 case TTK_Class: return 2; 748 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 749 } 750 } 751 752 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 753 // the requirements of a constexpr function definition or a constexpr 754 // constructor definition. If so, return true. If not, produce appropriate 755 // diagnostics and return false. 756 // 757 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 758 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 759 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 760 if (MD && MD->isInstance()) { 761 // C++11 [dcl.constexpr]p4: 762 // The definition of a constexpr constructor shall satisfy the following 763 // constraints: 764 // - the class shall not have any virtual base classes; 765 const CXXRecordDecl *RD = MD->getParent(); 766 if (RD->getNumVBases()) { 767 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 768 << isa<CXXConstructorDecl>(NewFD) 769 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 770 for (const auto &I : RD->vbases()) 771 Diag(I.getLocStart(), 772 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 773 return false; 774 } 775 } 776 777 if (!isa<CXXConstructorDecl>(NewFD)) { 778 // C++11 [dcl.constexpr]p3: 779 // The definition of a constexpr function shall satisfy the following 780 // constraints: 781 // - it shall not be virtual; 782 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 783 if (Method && Method->isVirtual()) { 784 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 785 786 // If it's not obvious why this function is virtual, find an overridden 787 // function which uses the 'virtual' keyword. 788 const CXXMethodDecl *WrittenVirtual = Method; 789 while (!WrittenVirtual->isVirtualAsWritten()) 790 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 791 if (WrittenVirtual != Method) 792 Diag(WrittenVirtual->getLocation(), 793 diag::note_overridden_virtual_function); 794 return false; 795 } 796 797 // - its return type shall be a literal type; 798 QualType RT = NewFD->getReturnType(); 799 if (!RT->isDependentType() && 800 RequireLiteralType(NewFD->getLocation(), RT, 801 diag::err_constexpr_non_literal_return)) 802 return false; 803 } 804 805 // - each of its parameter types shall be a literal type; 806 if (!CheckConstexprParameterTypes(*this, NewFD)) 807 return false; 808 809 return true; 810 } 811 812 /// Check the given declaration statement is legal within a constexpr function 813 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 814 /// 815 /// \return true if the body is OK (maybe only as an extension), false if we 816 /// have diagnosed a problem. 817 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 818 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 819 // C++11 [dcl.constexpr]p3 and p4: 820 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 821 // contain only 822 for (const auto *DclIt : DS->decls()) { 823 switch (DclIt->getKind()) { 824 case Decl::StaticAssert: 825 case Decl::Using: 826 case Decl::UsingShadow: 827 case Decl::UsingDirective: 828 case Decl::UnresolvedUsingTypename: 829 case Decl::UnresolvedUsingValue: 830 // - static_assert-declarations 831 // - using-declarations, 832 // - using-directives, 833 continue; 834 835 case Decl::Typedef: 836 case Decl::TypeAlias: { 837 // - typedef declarations and alias-declarations that do not define 838 // classes or enumerations, 839 const auto *TN = cast<TypedefNameDecl>(DclIt); 840 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 841 // Don't allow variably-modified types in constexpr functions. 842 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 843 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 844 << TL.getSourceRange() << TL.getType() 845 << isa<CXXConstructorDecl>(Dcl); 846 return false; 847 } 848 continue; 849 } 850 851 case Decl::Enum: 852 case Decl::CXXRecord: 853 // C++1y allows types to be defined, not just declared. 854 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 855 SemaRef.Diag(DS->getLocStart(), 856 SemaRef.getLangOpts().CPlusPlus1y 857 ? diag::warn_cxx11_compat_constexpr_type_definition 858 : diag::ext_constexpr_type_definition) 859 << isa<CXXConstructorDecl>(Dcl); 860 continue; 861 862 case Decl::EnumConstant: 863 case Decl::IndirectField: 864 case Decl::ParmVar: 865 // These can only appear with other declarations which are banned in 866 // C++11 and permitted in C++1y, so ignore them. 867 continue; 868 869 case Decl::Var: { 870 // C++1y [dcl.constexpr]p3 allows anything except: 871 // a definition of a variable of non-literal type or of static or 872 // thread storage duration or for which no initialization is performed. 873 const auto *VD = cast<VarDecl>(DclIt); 874 if (VD->isThisDeclarationADefinition()) { 875 if (VD->isStaticLocal()) { 876 SemaRef.Diag(VD->getLocation(), 877 diag::err_constexpr_local_var_static) 878 << isa<CXXConstructorDecl>(Dcl) 879 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 880 return false; 881 } 882 if (!VD->getType()->isDependentType() && 883 SemaRef.RequireLiteralType( 884 VD->getLocation(), VD->getType(), 885 diag::err_constexpr_local_var_non_literal_type, 886 isa<CXXConstructorDecl>(Dcl))) 887 return false; 888 if (!VD->getType()->isDependentType() && 889 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 890 SemaRef.Diag(VD->getLocation(), 891 diag::err_constexpr_local_var_no_init) 892 << isa<CXXConstructorDecl>(Dcl); 893 return false; 894 } 895 } 896 SemaRef.Diag(VD->getLocation(), 897 SemaRef.getLangOpts().CPlusPlus1y 898 ? diag::warn_cxx11_compat_constexpr_local_var 899 : diag::ext_constexpr_local_var) 900 << isa<CXXConstructorDecl>(Dcl); 901 continue; 902 } 903 904 case Decl::NamespaceAlias: 905 case Decl::Function: 906 // These are disallowed in C++11 and permitted in C++1y. Allow them 907 // everywhere as an extension. 908 if (!Cxx1yLoc.isValid()) 909 Cxx1yLoc = DS->getLocStart(); 910 continue; 911 912 default: 913 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 914 << isa<CXXConstructorDecl>(Dcl); 915 return false; 916 } 917 } 918 919 return true; 920 } 921 922 /// Check that the given field is initialized within a constexpr constructor. 923 /// 924 /// \param Dcl The constexpr constructor being checked. 925 /// \param Field The field being checked. This may be a member of an anonymous 926 /// struct or union nested within the class being checked. 927 /// \param Inits All declarations, including anonymous struct/union members and 928 /// indirect members, for which any initialization was provided. 929 /// \param Diagnosed Set to true if an error is produced. 930 static void CheckConstexprCtorInitializer(Sema &SemaRef, 931 const FunctionDecl *Dcl, 932 FieldDecl *Field, 933 llvm::SmallSet<Decl*, 16> &Inits, 934 bool &Diagnosed) { 935 if (Field->isInvalidDecl()) 936 return; 937 938 if (Field->isUnnamedBitfield()) 939 return; 940 941 // Anonymous unions with no variant members and empty anonymous structs do not 942 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 943 // indirect fields don't need initializing. 944 if (Field->isAnonymousStructOrUnion() && 945 (Field->getType()->isUnionType() 946 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 947 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 948 return; 949 950 if (!Inits.count(Field)) { 951 if (!Diagnosed) { 952 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 953 Diagnosed = true; 954 } 955 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 956 } else if (Field->isAnonymousStructOrUnion()) { 957 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 958 for (auto *I : RD->fields()) 959 // If an anonymous union contains an anonymous struct of which any member 960 // is initialized, all members must be initialized. 961 if (!RD->isUnion() || Inits.count(I)) 962 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 963 } 964 } 965 966 /// Check the provided statement is allowed in a constexpr function 967 /// definition. 968 static bool 969 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 970 SmallVectorImpl<SourceLocation> &ReturnStmts, 971 SourceLocation &Cxx1yLoc) { 972 // - its function-body shall be [...] a compound-statement that contains only 973 switch (S->getStmtClass()) { 974 case Stmt::NullStmtClass: 975 // - null statements, 976 return true; 977 978 case Stmt::DeclStmtClass: 979 // - static_assert-declarations 980 // - using-declarations, 981 // - using-directives, 982 // - typedef declarations and alias-declarations that do not define 983 // classes or enumerations, 984 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 985 return false; 986 return true; 987 988 case Stmt::ReturnStmtClass: 989 // - and exactly one return statement; 990 if (isa<CXXConstructorDecl>(Dcl)) { 991 // C++1y allows return statements in constexpr constructors. 992 if (!Cxx1yLoc.isValid()) 993 Cxx1yLoc = S->getLocStart(); 994 return true; 995 } 996 997 ReturnStmts.push_back(S->getLocStart()); 998 return true; 999 1000 case Stmt::CompoundStmtClass: { 1001 // C++1y allows compound-statements. 1002 if (!Cxx1yLoc.isValid()) 1003 Cxx1yLoc = S->getLocStart(); 1004 1005 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1006 for (auto *BodyIt : CompStmt->body()) { 1007 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1008 Cxx1yLoc)) 1009 return false; 1010 } 1011 return true; 1012 } 1013 1014 case Stmt::AttributedStmtClass: 1015 if (!Cxx1yLoc.isValid()) 1016 Cxx1yLoc = S->getLocStart(); 1017 return true; 1018 1019 case Stmt::IfStmtClass: { 1020 // C++1y allows if-statements. 1021 if (!Cxx1yLoc.isValid()) 1022 Cxx1yLoc = S->getLocStart(); 1023 1024 IfStmt *If = cast<IfStmt>(S); 1025 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1026 Cxx1yLoc)) 1027 return false; 1028 if (If->getElse() && 1029 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1030 Cxx1yLoc)) 1031 return false; 1032 return true; 1033 } 1034 1035 case Stmt::WhileStmtClass: 1036 case Stmt::DoStmtClass: 1037 case Stmt::ForStmtClass: 1038 case Stmt::CXXForRangeStmtClass: 1039 case Stmt::ContinueStmtClass: 1040 // C++1y allows all of these. We don't allow them as extensions in C++11, 1041 // because they don't make sense without variable mutation. 1042 if (!SemaRef.getLangOpts().CPlusPlus1y) 1043 break; 1044 if (!Cxx1yLoc.isValid()) 1045 Cxx1yLoc = S->getLocStart(); 1046 for (Stmt::child_range Children = S->children(); Children; ++Children) 1047 if (*Children && 1048 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1049 Cxx1yLoc)) 1050 return false; 1051 return true; 1052 1053 case Stmt::SwitchStmtClass: 1054 case Stmt::CaseStmtClass: 1055 case Stmt::DefaultStmtClass: 1056 case Stmt::BreakStmtClass: 1057 // C++1y allows switch-statements, and since they don't need variable 1058 // mutation, we can reasonably allow them in C++11 as an extension. 1059 if (!Cxx1yLoc.isValid()) 1060 Cxx1yLoc = S->getLocStart(); 1061 for (Stmt::child_range Children = S->children(); Children; ++Children) 1062 if (*Children && 1063 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1064 Cxx1yLoc)) 1065 return false; 1066 return true; 1067 1068 default: 1069 if (!isa<Expr>(S)) 1070 break; 1071 1072 // C++1y allows expression-statements. 1073 if (!Cxx1yLoc.isValid()) 1074 Cxx1yLoc = S->getLocStart(); 1075 return true; 1076 } 1077 1078 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1079 << isa<CXXConstructorDecl>(Dcl); 1080 return false; 1081 } 1082 1083 /// Check the body for the given constexpr function declaration only contains 1084 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1085 /// 1086 /// \return true if the body is OK, false if we have diagnosed a problem. 1087 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1088 if (isa<CXXTryStmt>(Body)) { 1089 // C++11 [dcl.constexpr]p3: 1090 // The definition of a constexpr function shall satisfy the following 1091 // constraints: [...] 1092 // - its function-body shall be = delete, = default, or a 1093 // compound-statement 1094 // 1095 // C++11 [dcl.constexpr]p4: 1096 // In the definition of a constexpr constructor, [...] 1097 // - its function-body shall not be a function-try-block; 1098 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1099 << isa<CXXConstructorDecl>(Dcl); 1100 return false; 1101 } 1102 1103 SmallVector<SourceLocation, 4> ReturnStmts; 1104 1105 // - its function-body shall be [...] a compound-statement that contains only 1106 // [... list of cases ...] 1107 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1108 SourceLocation Cxx1yLoc; 1109 for (auto *BodyIt : CompBody->body()) { 1110 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1111 return false; 1112 } 1113 1114 if (Cxx1yLoc.isValid()) 1115 Diag(Cxx1yLoc, 1116 getLangOpts().CPlusPlus1y 1117 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1118 : diag::ext_constexpr_body_invalid_stmt) 1119 << isa<CXXConstructorDecl>(Dcl); 1120 1121 if (const CXXConstructorDecl *Constructor 1122 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1123 const CXXRecordDecl *RD = Constructor->getParent(); 1124 // DR1359: 1125 // - every non-variant non-static data member and base class sub-object 1126 // shall be initialized; 1127 // DR1460: 1128 // - if the class is a union having variant members, exactly one of them 1129 // shall be initialized; 1130 if (RD->isUnion()) { 1131 if (Constructor->getNumCtorInitializers() == 0 && 1132 RD->hasVariantMembers()) { 1133 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1134 return false; 1135 } 1136 } else if (!Constructor->isDependentContext() && 1137 !Constructor->isDelegatingConstructor()) { 1138 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1139 1140 // Skip detailed checking if we have enough initializers, and we would 1141 // allow at most one initializer per member. 1142 bool AnyAnonStructUnionMembers = false; 1143 unsigned Fields = 0; 1144 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1145 E = RD->field_end(); I != E; ++I, ++Fields) { 1146 if (I->isAnonymousStructOrUnion()) { 1147 AnyAnonStructUnionMembers = true; 1148 break; 1149 } 1150 } 1151 // DR1460: 1152 // - if the class is a union-like class, but is not a union, for each of 1153 // its anonymous union members having variant members, exactly one of 1154 // them shall be initialized; 1155 if (AnyAnonStructUnionMembers || 1156 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1157 // Check initialization of non-static data members. Base classes are 1158 // always initialized so do not need to be checked. Dependent bases 1159 // might not have initializers in the member initializer list. 1160 llvm::SmallSet<Decl*, 16> Inits; 1161 for (const auto *I: Constructor->inits()) { 1162 if (FieldDecl *FD = I->getMember()) 1163 Inits.insert(FD); 1164 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1165 Inits.insert(ID->chain_begin(), ID->chain_end()); 1166 } 1167 1168 bool Diagnosed = false; 1169 for (auto *I : RD->fields()) 1170 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1171 if (Diagnosed) 1172 return false; 1173 } 1174 } 1175 } else { 1176 if (ReturnStmts.empty()) { 1177 // C++1y doesn't require constexpr functions to contain a 'return' 1178 // statement. We still do, unless the return type might be void, because 1179 // otherwise if there's no return statement, the function cannot 1180 // be used in a core constant expression. 1181 bool OK = getLangOpts().CPlusPlus1y && 1182 (Dcl->getReturnType()->isVoidType() || 1183 Dcl->getReturnType()->isDependentType()); 1184 Diag(Dcl->getLocation(), 1185 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1186 : diag::err_constexpr_body_no_return); 1187 return OK; 1188 } 1189 if (ReturnStmts.size() > 1) { 1190 Diag(ReturnStmts.back(), 1191 getLangOpts().CPlusPlus1y 1192 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1193 : diag::ext_constexpr_body_multiple_return); 1194 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1195 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1196 } 1197 } 1198 1199 // C++11 [dcl.constexpr]p5: 1200 // if no function argument values exist such that the function invocation 1201 // substitution would produce a constant expression, the program is 1202 // ill-formed; no diagnostic required. 1203 // C++11 [dcl.constexpr]p3: 1204 // - every constructor call and implicit conversion used in initializing the 1205 // return value shall be one of those allowed in a constant expression. 1206 // C++11 [dcl.constexpr]p4: 1207 // - every constructor involved in initializing non-static data members and 1208 // base class sub-objects shall be a constexpr constructor. 1209 SmallVector<PartialDiagnosticAt, 8> Diags; 1210 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1211 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1212 << isa<CXXConstructorDecl>(Dcl); 1213 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1214 Diag(Diags[I].first, Diags[I].second); 1215 // Don't return false here: we allow this for compatibility in 1216 // system headers. 1217 } 1218 1219 return true; 1220 } 1221 1222 /// isCurrentClassName - Determine whether the identifier II is the 1223 /// name of the class type currently being defined. In the case of 1224 /// nested classes, this will only return true if II is the name of 1225 /// the innermost class. 1226 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1227 const CXXScopeSpec *SS) { 1228 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1229 1230 CXXRecordDecl *CurDecl; 1231 if (SS && SS->isSet() && !SS->isInvalid()) { 1232 DeclContext *DC = computeDeclContext(*SS, true); 1233 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1234 } else 1235 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1236 1237 if (CurDecl && CurDecl->getIdentifier()) 1238 return &II == CurDecl->getIdentifier(); 1239 return false; 1240 } 1241 1242 /// \brief Determine whether the identifier II is a typo for the name of 1243 /// the class type currently being defined. If so, update it to the identifier 1244 /// that should have been used. 1245 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1246 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1247 1248 if (!getLangOpts().SpellChecking) 1249 return false; 1250 1251 CXXRecordDecl *CurDecl; 1252 if (SS && SS->isSet() && !SS->isInvalid()) { 1253 DeclContext *DC = computeDeclContext(*SS, true); 1254 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1255 } else 1256 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1257 1258 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1259 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1260 < II->getLength()) { 1261 II = CurDecl->getIdentifier(); 1262 return true; 1263 } 1264 1265 return false; 1266 } 1267 1268 /// \brief Determine whether the given class is a base class of the given 1269 /// class, including looking at dependent bases. 1270 static bool findCircularInheritance(const CXXRecordDecl *Class, 1271 const CXXRecordDecl *Current) { 1272 SmallVector<const CXXRecordDecl*, 8> Queue; 1273 1274 Class = Class->getCanonicalDecl(); 1275 while (true) { 1276 for (const auto &I : Current->bases()) { 1277 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1278 if (!Base) 1279 continue; 1280 1281 Base = Base->getDefinition(); 1282 if (!Base) 1283 continue; 1284 1285 if (Base->getCanonicalDecl() == Class) 1286 return true; 1287 1288 Queue.push_back(Base); 1289 } 1290 1291 if (Queue.empty()) 1292 return false; 1293 1294 Current = Queue.pop_back_val(); 1295 } 1296 1297 return false; 1298 } 1299 1300 /// \brief Check the validity of a C++ base class specifier. 1301 /// 1302 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1303 /// and returns NULL otherwise. 1304 CXXBaseSpecifier * 1305 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1306 SourceRange SpecifierRange, 1307 bool Virtual, AccessSpecifier Access, 1308 TypeSourceInfo *TInfo, 1309 SourceLocation EllipsisLoc) { 1310 QualType BaseType = TInfo->getType(); 1311 1312 // C++ [class.union]p1: 1313 // A union shall not have base classes. 1314 if (Class->isUnion()) { 1315 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1316 << SpecifierRange; 1317 return 0; 1318 } 1319 1320 if (EllipsisLoc.isValid() && 1321 !TInfo->getType()->containsUnexpandedParameterPack()) { 1322 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1323 << TInfo->getTypeLoc().getSourceRange(); 1324 EllipsisLoc = SourceLocation(); 1325 } 1326 1327 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1328 1329 if (BaseType->isDependentType()) { 1330 // Make sure that we don't have circular inheritance among our dependent 1331 // bases. For non-dependent bases, the check for completeness below handles 1332 // this. 1333 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1334 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1335 ((BaseDecl = BaseDecl->getDefinition()) && 1336 findCircularInheritance(Class, BaseDecl))) { 1337 Diag(BaseLoc, diag::err_circular_inheritance) 1338 << BaseType << Context.getTypeDeclType(Class); 1339 1340 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1341 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1342 << BaseType; 1343 1344 return 0; 1345 } 1346 } 1347 1348 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1349 Class->getTagKind() == TTK_Class, 1350 Access, TInfo, EllipsisLoc); 1351 } 1352 1353 // Base specifiers must be record types. 1354 if (!BaseType->isRecordType()) { 1355 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1356 return 0; 1357 } 1358 1359 // C++ [class.union]p1: 1360 // A union shall not be used as a base class. 1361 if (BaseType->isUnionType()) { 1362 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1363 return 0; 1364 } 1365 1366 // C++ [class.derived]p2: 1367 // The class-name in a base-specifier shall not be an incompletely 1368 // defined class. 1369 if (RequireCompleteType(BaseLoc, BaseType, 1370 diag::err_incomplete_base_class, SpecifierRange)) { 1371 Class->setInvalidDecl(); 1372 return 0; 1373 } 1374 1375 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1376 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1377 assert(BaseDecl && "Record type has no declaration"); 1378 BaseDecl = BaseDecl->getDefinition(); 1379 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1380 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1381 assert(CXXBaseDecl && "Base type is not a C++ type"); 1382 1383 // A class which contains a flexible array member is not suitable for use as a 1384 // base class: 1385 // - If the layout determines that a base comes before another base, 1386 // the flexible array member would index into the subsequent base. 1387 // - If the layout determines that base comes before the derived class, 1388 // the flexible array member would index into the derived class. 1389 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1390 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1391 << CXXBaseDecl->getDeclName(); 1392 return 0; 1393 } 1394 1395 // C++ [class]p3: 1396 // If a class is marked final and it appears as a base-type-specifier in 1397 // base-clause, the program is ill-formed. 1398 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1399 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1400 << CXXBaseDecl->getDeclName() 1401 << FA->isSpelledAsSealed(); 1402 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1403 << CXXBaseDecl->getDeclName(); 1404 return 0; 1405 } 1406 1407 if (BaseDecl->isInvalidDecl()) 1408 Class->setInvalidDecl(); 1409 1410 // Create the base specifier. 1411 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1412 Class->getTagKind() == TTK_Class, 1413 Access, TInfo, EllipsisLoc); 1414 } 1415 1416 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1417 /// one entry in the base class list of a class specifier, for 1418 /// example: 1419 /// class foo : public bar, virtual private baz { 1420 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1421 BaseResult 1422 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1423 ParsedAttributes &Attributes, 1424 bool Virtual, AccessSpecifier Access, 1425 ParsedType basetype, SourceLocation BaseLoc, 1426 SourceLocation EllipsisLoc) { 1427 if (!classdecl) 1428 return true; 1429 1430 AdjustDeclIfTemplate(classdecl); 1431 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1432 if (!Class) 1433 return true; 1434 1435 // We do not support any C++11 attributes on base-specifiers yet. 1436 // Diagnose any attributes we see. 1437 if (!Attributes.empty()) { 1438 for (AttributeList *Attr = Attributes.getList(); Attr; 1439 Attr = Attr->getNext()) { 1440 if (Attr->isInvalid() || 1441 Attr->getKind() == AttributeList::IgnoredAttribute) 1442 continue; 1443 Diag(Attr->getLoc(), 1444 Attr->getKind() == AttributeList::UnknownAttribute 1445 ? diag::warn_unknown_attribute_ignored 1446 : diag::err_base_specifier_attribute) 1447 << Attr->getName(); 1448 } 1449 } 1450 1451 TypeSourceInfo *TInfo = 0; 1452 GetTypeFromParser(basetype, &TInfo); 1453 1454 if (EllipsisLoc.isInvalid() && 1455 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1456 UPPC_BaseType)) 1457 return true; 1458 1459 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1460 Virtual, Access, TInfo, 1461 EllipsisLoc)) 1462 return BaseSpec; 1463 else 1464 Class->setInvalidDecl(); 1465 1466 return true; 1467 } 1468 1469 /// \brief Performs the actual work of attaching the given base class 1470 /// specifiers to a C++ class. 1471 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1472 unsigned NumBases) { 1473 if (NumBases == 0) 1474 return false; 1475 1476 // Used to keep track of which base types we have already seen, so 1477 // that we can properly diagnose redundant direct base types. Note 1478 // that the key is always the unqualified canonical type of the base 1479 // class. 1480 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1481 1482 // Copy non-redundant base specifiers into permanent storage. 1483 unsigned NumGoodBases = 0; 1484 bool Invalid = false; 1485 for (unsigned idx = 0; idx < NumBases; ++idx) { 1486 QualType NewBaseType 1487 = Context.getCanonicalType(Bases[idx]->getType()); 1488 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1489 1490 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1491 if (KnownBase) { 1492 // C++ [class.mi]p3: 1493 // A class shall not be specified as a direct base class of a 1494 // derived class more than once. 1495 Diag(Bases[idx]->getLocStart(), 1496 diag::err_duplicate_base_class) 1497 << KnownBase->getType() 1498 << Bases[idx]->getSourceRange(); 1499 1500 // Delete the duplicate base class specifier; we're going to 1501 // overwrite its pointer later. 1502 Context.Deallocate(Bases[idx]); 1503 1504 Invalid = true; 1505 } else { 1506 // Okay, add this new base class. 1507 KnownBase = Bases[idx]; 1508 Bases[NumGoodBases++] = Bases[idx]; 1509 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1510 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1511 if (Class->isInterface() && 1512 (!RD->isInterface() || 1513 KnownBase->getAccessSpecifier() != AS_public)) { 1514 // The Microsoft extension __interface does not permit bases that 1515 // are not themselves public interfaces. 1516 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1517 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1518 << RD->getSourceRange(); 1519 Invalid = true; 1520 } 1521 if (RD->hasAttr<WeakAttr>()) 1522 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1523 } 1524 } 1525 } 1526 1527 // Attach the remaining base class specifiers to the derived class. 1528 Class->setBases(Bases, NumGoodBases); 1529 1530 // Delete the remaining (good) base class specifiers, since their 1531 // data has been copied into the CXXRecordDecl. 1532 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1533 Context.Deallocate(Bases[idx]); 1534 1535 return Invalid; 1536 } 1537 1538 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1539 /// class, after checking whether there are any duplicate base 1540 /// classes. 1541 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1542 unsigned NumBases) { 1543 if (!ClassDecl || !Bases || !NumBases) 1544 return; 1545 1546 AdjustDeclIfTemplate(ClassDecl); 1547 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1548 } 1549 1550 /// \brief Determine whether the type \p Derived is a C++ class that is 1551 /// derived from the type \p Base. 1552 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1553 if (!getLangOpts().CPlusPlus) 1554 return false; 1555 1556 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1557 if (!DerivedRD) 1558 return false; 1559 1560 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1561 if (!BaseRD) 1562 return false; 1563 1564 // If either the base or the derived type is invalid, don't try to 1565 // check whether one is derived from the other. 1566 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1567 return false; 1568 1569 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1570 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1571 } 1572 1573 /// \brief Determine whether the type \p Derived is a C++ class that is 1574 /// derived from the type \p Base. 1575 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1576 if (!getLangOpts().CPlusPlus) 1577 return false; 1578 1579 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1580 if (!DerivedRD) 1581 return false; 1582 1583 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1584 if (!BaseRD) 1585 return false; 1586 1587 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1588 } 1589 1590 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1591 CXXCastPath &BasePathArray) { 1592 assert(BasePathArray.empty() && "Base path array must be empty!"); 1593 assert(Paths.isRecordingPaths() && "Must record paths!"); 1594 1595 const CXXBasePath &Path = Paths.front(); 1596 1597 // We first go backward and check if we have a virtual base. 1598 // FIXME: It would be better if CXXBasePath had the base specifier for 1599 // the nearest virtual base. 1600 unsigned Start = 0; 1601 for (unsigned I = Path.size(); I != 0; --I) { 1602 if (Path[I - 1].Base->isVirtual()) { 1603 Start = I - 1; 1604 break; 1605 } 1606 } 1607 1608 // Now add all bases. 1609 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1610 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1611 } 1612 1613 /// \brief Determine whether the given base path includes a virtual 1614 /// base class. 1615 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1616 for (CXXCastPath::const_iterator B = BasePath.begin(), 1617 BEnd = BasePath.end(); 1618 B != BEnd; ++B) 1619 if ((*B)->isVirtual()) 1620 return true; 1621 1622 return false; 1623 } 1624 1625 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1626 /// conversion (where Derived and Base are class types) is 1627 /// well-formed, meaning that the conversion is unambiguous (and 1628 /// that all of the base classes are accessible). Returns true 1629 /// and emits a diagnostic if the code is ill-formed, returns false 1630 /// otherwise. Loc is the location where this routine should point to 1631 /// if there is an error, and Range is the source range to highlight 1632 /// if there is an error. 1633 bool 1634 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1635 unsigned InaccessibleBaseID, 1636 unsigned AmbigiousBaseConvID, 1637 SourceLocation Loc, SourceRange Range, 1638 DeclarationName Name, 1639 CXXCastPath *BasePath) { 1640 // First, determine whether the path from Derived to Base is 1641 // ambiguous. This is slightly more expensive than checking whether 1642 // the Derived to Base conversion exists, because here we need to 1643 // explore multiple paths to determine if there is an ambiguity. 1644 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1645 /*DetectVirtual=*/false); 1646 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1647 assert(DerivationOkay && 1648 "Can only be used with a derived-to-base conversion"); 1649 (void)DerivationOkay; 1650 1651 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1652 if (InaccessibleBaseID) { 1653 // Check that the base class can be accessed. 1654 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1655 InaccessibleBaseID)) { 1656 case AR_inaccessible: 1657 return true; 1658 case AR_accessible: 1659 case AR_dependent: 1660 case AR_delayed: 1661 break; 1662 } 1663 } 1664 1665 // Build a base path if necessary. 1666 if (BasePath) 1667 BuildBasePathArray(Paths, *BasePath); 1668 return false; 1669 } 1670 1671 if (AmbigiousBaseConvID) { 1672 // We know that the derived-to-base conversion is ambiguous, and 1673 // we're going to produce a diagnostic. Perform the derived-to-base 1674 // search just one more time to compute all of the possible paths so 1675 // that we can print them out. This is more expensive than any of 1676 // the previous derived-to-base checks we've done, but at this point 1677 // performance isn't as much of an issue. 1678 Paths.clear(); 1679 Paths.setRecordingPaths(true); 1680 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1681 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1682 (void)StillOkay; 1683 1684 // Build up a textual representation of the ambiguous paths, e.g., 1685 // D -> B -> A, that will be used to illustrate the ambiguous 1686 // conversions in the diagnostic. We only print one of the paths 1687 // to each base class subobject. 1688 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1689 1690 Diag(Loc, AmbigiousBaseConvID) 1691 << Derived << Base << PathDisplayStr << Range << Name; 1692 } 1693 return true; 1694 } 1695 1696 bool 1697 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1698 SourceLocation Loc, SourceRange Range, 1699 CXXCastPath *BasePath, 1700 bool IgnoreAccess) { 1701 return CheckDerivedToBaseConversion(Derived, Base, 1702 IgnoreAccess ? 0 1703 : diag::err_upcast_to_inaccessible_base, 1704 diag::err_ambiguous_derived_to_base_conv, 1705 Loc, Range, DeclarationName(), 1706 BasePath); 1707 } 1708 1709 1710 /// @brief Builds a string representing ambiguous paths from a 1711 /// specific derived class to different subobjects of the same base 1712 /// class. 1713 /// 1714 /// This function builds a string that can be used in error messages 1715 /// to show the different paths that one can take through the 1716 /// inheritance hierarchy to go from the derived class to different 1717 /// subobjects of a base class. The result looks something like this: 1718 /// @code 1719 /// struct D -> struct B -> struct A 1720 /// struct D -> struct C -> struct A 1721 /// @endcode 1722 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1723 std::string PathDisplayStr; 1724 std::set<unsigned> DisplayedPaths; 1725 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1726 Path != Paths.end(); ++Path) { 1727 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1728 // We haven't displayed a path to this particular base 1729 // class subobject yet. 1730 PathDisplayStr += "\n "; 1731 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1732 for (CXXBasePath::const_iterator Element = Path->begin(); 1733 Element != Path->end(); ++Element) 1734 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1735 } 1736 } 1737 1738 return PathDisplayStr; 1739 } 1740 1741 //===----------------------------------------------------------------------===// 1742 // C++ class member Handling 1743 //===----------------------------------------------------------------------===// 1744 1745 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1746 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1747 SourceLocation ASLoc, 1748 SourceLocation ColonLoc, 1749 AttributeList *Attrs) { 1750 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1751 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1752 ASLoc, ColonLoc); 1753 CurContext->addHiddenDecl(ASDecl); 1754 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1755 } 1756 1757 /// CheckOverrideControl - Check C++11 override control semantics. 1758 void Sema::CheckOverrideControl(NamedDecl *D) { 1759 if (D->isInvalidDecl()) 1760 return; 1761 1762 // We only care about "override" and "final" declarations. 1763 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1764 return; 1765 1766 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1767 1768 // We can't check dependent instance methods. 1769 if (MD && MD->isInstance() && 1770 (MD->getParent()->hasAnyDependentBases() || 1771 MD->getType()->isDependentType())) 1772 return; 1773 1774 if (MD && !MD->isVirtual()) { 1775 // If we have a non-virtual method, check if if hides a virtual method. 1776 // (In that case, it's most likely the method has the wrong type.) 1777 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1778 FindHiddenVirtualMethods(MD, OverloadedMethods); 1779 1780 if (!OverloadedMethods.empty()) { 1781 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1782 Diag(OA->getLocation(), 1783 diag::override_keyword_hides_virtual_member_function) 1784 << "override" << (OverloadedMethods.size() > 1); 1785 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1786 Diag(FA->getLocation(), 1787 diag::override_keyword_hides_virtual_member_function) 1788 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1789 << (OverloadedMethods.size() > 1); 1790 } 1791 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1792 MD->setInvalidDecl(); 1793 return; 1794 } 1795 // Fall through into the general case diagnostic. 1796 // FIXME: We might want to attempt typo correction here. 1797 } 1798 1799 if (!MD || !MD->isVirtual()) { 1800 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1801 Diag(OA->getLocation(), 1802 diag::override_keyword_only_allowed_on_virtual_member_functions) 1803 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1804 D->dropAttr<OverrideAttr>(); 1805 } 1806 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1807 Diag(FA->getLocation(), 1808 diag::override_keyword_only_allowed_on_virtual_member_functions) 1809 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1810 << FixItHint::CreateRemoval(FA->getLocation()); 1811 D->dropAttr<FinalAttr>(); 1812 } 1813 return; 1814 } 1815 1816 // C++11 [class.virtual]p5: 1817 // If a virtual function is marked with the virt-specifier override and 1818 // does not override a member function of a base class, the program is 1819 // ill-formed. 1820 bool HasOverriddenMethods = 1821 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1822 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1823 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1824 << MD->getDeclName(); 1825 } 1826 1827 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1828 /// function overrides a virtual member function marked 'final', according to 1829 /// C++11 [class.virtual]p4. 1830 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1831 const CXXMethodDecl *Old) { 1832 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1833 if (!FA) 1834 return false; 1835 1836 Diag(New->getLocation(), diag::err_final_function_overridden) 1837 << New->getDeclName() 1838 << FA->isSpelledAsSealed(); 1839 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1840 return true; 1841 } 1842 1843 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1844 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1845 // FIXME: Destruction of ObjC lifetime types has side-effects. 1846 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1847 return !RD->isCompleteDefinition() || 1848 !RD->hasTrivialDefaultConstructor() || 1849 !RD->hasTrivialDestructor(); 1850 return false; 1851 } 1852 1853 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1854 for (AttributeList* it = list; it != 0; it = it->getNext()) 1855 if (it->isDeclspecPropertyAttribute()) 1856 return it; 1857 return 0; 1858 } 1859 1860 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1861 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1862 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1863 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1864 /// present (but parsing it has been deferred). 1865 NamedDecl * 1866 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1867 MultiTemplateParamsArg TemplateParameterLists, 1868 Expr *BW, const VirtSpecifiers &VS, 1869 InClassInitStyle InitStyle) { 1870 const DeclSpec &DS = D.getDeclSpec(); 1871 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1872 DeclarationName Name = NameInfo.getName(); 1873 SourceLocation Loc = NameInfo.getLoc(); 1874 1875 // For anonymous bitfields, the location should point to the type. 1876 if (Loc.isInvalid()) 1877 Loc = D.getLocStart(); 1878 1879 Expr *BitWidth = static_cast<Expr*>(BW); 1880 1881 assert(isa<CXXRecordDecl>(CurContext)); 1882 assert(!DS.isFriendSpecified()); 1883 1884 bool isFunc = D.isDeclarationOfFunction(); 1885 1886 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1887 // The Microsoft extension __interface only permits public member functions 1888 // and prohibits constructors, destructors, operators, non-public member 1889 // functions, static methods and data members. 1890 unsigned InvalidDecl; 1891 bool ShowDeclName = true; 1892 if (!isFunc) 1893 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1894 else if (AS != AS_public) 1895 InvalidDecl = 2; 1896 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1897 InvalidDecl = 3; 1898 else switch (Name.getNameKind()) { 1899 case DeclarationName::CXXConstructorName: 1900 InvalidDecl = 4; 1901 ShowDeclName = false; 1902 break; 1903 1904 case DeclarationName::CXXDestructorName: 1905 InvalidDecl = 5; 1906 ShowDeclName = false; 1907 break; 1908 1909 case DeclarationName::CXXOperatorName: 1910 case DeclarationName::CXXConversionFunctionName: 1911 InvalidDecl = 6; 1912 break; 1913 1914 default: 1915 InvalidDecl = 0; 1916 break; 1917 } 1918 1919 if (InvalidDecl) { 1920 if (ShowDeclName) 1921 Diag(Loc, diag::err_invalid_member_in_interface) 1922 << (InvalidDecl-1) << Name; 1923 else 1924 Diag(Loc, diag::err_invalid_member_in_interface) 1925 << (InvalidDecl-1) << ""; 1926 return 0; 1927 } 1928 } 1929 1930 // C++ 9.2p6: A member shall not be declared to have automatic storage 1931 // duration (auto, register) or with the extern storage-class-specifier. 1932 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1933 // data members and cannot be applied to names declared const or static, 1934 // and cannot be applied to reference members. 1935 switch (DS.getStorageClassSpec()) { 1936 case DeclSpec::SCS_unspecified: 1937 case DeclSpec::SCS_typedef: 1938 case DeclSpec::SCS_static: 1939 break; 1940 case DeclSpec::SCS_mutable: 1941 if (isFunc) { 1942 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1943 1944 // FIXME: It would be nicer if the keyword was ignored only for this 1945 // declarator. Otherwise we could get follow-up errors. 1946 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1947 } 1948 break; 1949 default: 1950 Diag(DS.getStorageClassSpecLoc(), 1951 diag::err_storageclass_invalid_for_member); 1952 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1953 break; 1954 } 1955 1956 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1957 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1958 !isFunc); 1959 1960 if (DS.isConstexprSpecified() && isInstField) { 1961 SemaDiagnosticBuilder B = 1962 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 1963 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 1964 if (InitStyle == ICIS_NoInit) { 1965 B << 0 << 0; 1966 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 1967 B << FixItHint::CreateRemoval(ConstexprLoc); 1968 else { 1969 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 1970 D.getMutableDeclSpec().ClearConstexprSpec(); 1971 const char *PrevSpec; 1972 unsigned DiagID; 1973 bool Failed = D.getMutableDeclSpec().SetTypeQual( 1974 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 1975 (void)Failed; 1976 assert(!Failed && "Making a constexpr member const shouldn't fail"); 1977 } 1978 } else { 1979 B << 1; 1980 const char *PrevSpec; 1981 unsigned DiagID; 1982 if (D.getMutableDeclSpec().SetStorageClassSpec( 1983 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 1984 Context.getPrintingPolicy())) { 1985 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 1986 "This is the only DeclSpec that should fail to be applied"); 1987 B << 1; 1988 } else { 1989 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 1990 isInstField = false; 1991 } 1992 } 1993 } 1994 1995 NamedDecl *Member; 1996 if (isInstField) { 1997 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1998 1999 // Data members must have identifiers for names. 2000 if (!Name.isIdentifier()) { 2001 Diag(Loc, diag::err_bad_variable_name) 2002 << Name; 2003 return 0; 2004 } 2005 2006 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2007 2008 // Member field could not be with "template" keyword. 2009 // So TemplateParameterLists should be empty in this case. 2010 if (TemplateParameterLists.size()) { 2011 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2012 if (TemplateParams->size()) { 2013 // There is no such thing as a member field template. 2014 Diag(D.getIdentifierLoc(), diag::err_template_member) 2015 << II 2016 << SourceRange(TemplateParams->getTemplateLoc(), 2017 TemplateParams->getRAngleLoc()); 2018 } else { 2019 // There is an extraneous 'template<>' for this member. 2020 Diag(TemplateParams->getTemplateLoc(), 2021 diag::err_template_member_noparams) 2022 << II 2023 << SourceRange(TemplateParams->getTemplateLoc(), 2024 TemplateParams->getRAngleLoc()); 2025 } 2026 return 0; 2027 } 2028 2029 if (SS.isSet() && !SS.isInvalid()) { 2030 // The user provided a superfluous scope specifier inside a class 2031 // definition: 2032 // 2033 // class X { 2034 // int X::member; 2035 // }; 2036 if (DeclContext *DC = computeDeclContext(SS, false)) 2037 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2038 else 2039 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2040 << Name << SS.getRange(); 2041 2042 SS.clear(); 2043 } 2044 2045 AttributeList *MSPropertyAttr = 2046 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2047 if (MSPropertyAttr) { 2048 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2049 BitWidth, InitStyle, AS, MSPropertyAttr); 2050 if (!Member) 2051 return 0; 2052 isInstField = false; 2053 } else { 2054 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2055 BitWidth, InitStyle, AS); 2056 assert(Member && "HandleField never returns null"); 2057 } 2058 } else { 2059 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2060 2061 Member = HandleDeclarator(S, D, TemplateParameterLists); 2062 if (!Member) 2063 return 0; 2064 2065 // Non-instance-fields can't have a bitfield. 2066 if (BitWidth) { 2067 if (Member->isInvalidDecl()) { 2068 // don't emit another diagnostic. 2069 } else if (isa<VarDecl>(Member)) { 2070 // C++ 9.6p3: A bit-field shall not be a static member. 2071 // "static member 'A' cannot be a bit-field" 2072 Diag(Loc, diag::err_static_not_bitfield) 2073 << Name << BitWidth->getSourceRange(); 2074 } else if (isa<TypedefDecl>(Member)) { 2075 // "typedef member 'x' cannot be a bit-field" 2076 Diag(Loc, diag::err_typedef_not_bitfield) 2077 << Name << BitWidth->getSourceRange(); 2078 } else { 2079 // A function typedef ("typedef int f(); f a;"). 2080 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2081 Diag(Loc, diag::err_not_integral_type_bitfield) 2082 << Name << cast<ValueDecl>(Member)->getType() 2083 << BitWidth->getSourceRange(); 2084 } 2085 2086 BitWidth = 0; 2087 Member->setInvalidDecl(); 2088 } 2089 2090 Member->setAccess(AS); 2091 2092 // If we have declared a member function template or static data member 2093 // template, set the access of the templated declaration as well. 2094 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2095 FunTmpl->getTemplatedDecl()->setAccess(AS); 2096 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2097 VarTmpl->getTemplatedDecl()->setAccess(AS); 2098 } 2099 2100 if (VS.isOverrideSpecified()) 2101 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2102 if (VS.isFinalSpecified()) 2103 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2104 VS.isFinalSpelledSealed())); 2105 2106 if (VS.getLastLocation().isValid()) { 2107 // Update the end location of a method that has a virt-specifiers. 2108 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2109 MD->setRangeEnd(VS.getLastLocation()); 2110 } 2111 2112 CheckOverrideControl(Member); 2113 2114 assert((Name || isInstField) && "No identifier for non-field ?"); 2115 2116 if (isInstField) { 2117 FieldDecl *FD = cast<FieldDecl>(Member); 2118 FieldCollector->Add(FD); 2119 2120 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 2121 FD->getLocation()) 2122 != DiagnosticsEngine::Ignored) { 2123 // Remember all explicit private FieldDecls that have a name, no side 2124 // effects and are not part of a dependent type declaration. 2125 if (!FD->isImplicit() && FD->getDeclName() && 2126 FD->getAccess() == AS_private && 2127 !FD->hasAttr<UnusedAttr>() && 2128 !FD->getParent()->isDependentContext() && 2129 !InitializationHasSideEffects(*FD)) 2130 UnusedPrivateFields.insert(FD); 2131 } 2132 } 2133 2134 return Member; 2135 } 2136 2137 namespace { 2138 class UninitializedFieldVisitor 2139 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2140 Sema &S; 2141 // List of Decls to generate a warning on. Also remove Decls that become 2142 // initialized. 2143 llvm::SmallPtrSet<ValueDecl*, 4> &Decls; 2144 // If non-null, add a note to the warning pointing back to the constructor. 2145 const CXXConstructorDecl *Constructor; 2146 public: 2147 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2148 UninitializedFieldVisitor(Sema &S, 2149 llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2150 const CXXConstructorDecl *Constructor) 2151 : Inherited(S.Context), S(S), Decls(Decls), 2152 Constructor(Constructor) { } 2153 2154 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) { 2155 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2156 return; 2157 2158 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2159 // or union. 2160 MemberExpr *FieldME = ME; 2161 2162 Expr *Base = ME; 2163 while (isa<MemberExpr>(Base)) { 2164 ME = cast<MemberExpr>(Base); 2165 2166 if (isa<VarDecl>(ME->getMemberDecl())) 2167 return; 2168 2169 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2170 if (!FD->isAnonymousStructOrUnion()) 2171 FieldME = ME; 2172 2173 Base = ME->getBase(); 2174 } 2175 2176 if (!isa<CXXThisExpr>(Base)) 2177 return; 2178 2179 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2180 2181 if (!Decls.count(FoundVD)) 2182 return; 2183 2184 const bool IsReference = FoundVD->getType()->isReferenceType(); 2185 2186 // Prevent double warnings on use of unbounded references. 2187 if (IsReference != CheckReferenceOnly) 2188 return; 2189 2190 unsigned diag = IsReference 2191 ? diag::warn_reference_field_is_uninit 2192 : diag::warn_field_is_uninit; 2193 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2194 if (Constructor) 2195 S.Diag(Constructor->getLocation(), 2196 diag::note_uninit_in_this_constructor) 2197 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2198 2199 } 2200 2201 void HandleValue(Expr *E) { 2202 E = E->IgnoreParens(); 2203 2204 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2205 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2206 return; 2207 } 2208 2209 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2210 HandleValue(CO->getTrueExpr()); 2211 HandleValue(CO->getFalseExpr()); 2212 return; 2213 } 2214 2215 if (BinaryConditionalOperator *BCO = 2216 dyn_cast<BinaryConditionalOperator>(E)) { 2217 HandleValue(BCO->getCommon()); 2218 HandleValue(BCO->getFalseExpr()); 2219 return; 2220 } 2221 2222 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2223 switch (BO->getOpcode()) { 2224 default: 2225 return; 2226 case(BO_PtrMemD): 2227 case(BO_PtrMemI): 2228 HandleValue(BO->getLHS()); 2229 return; 2230 case(BO_Comma): 2231 HandleValue(BO->getRHS()); 2232 return; 2233 } 2234 } 2235 } 2236 2237 void VisitMemberExpr(MemberExpr *ME) { 2238 // All uses of unbounded reference fields will warn. 2239 HandleMemberExpr(ME, true /*CheckReferenceOnly*/); 2240 2241 Inherited::VisitMemberExpr(ME); 2242 } 2243 2244 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2245 if (E->getCastKind() == CK_LValueToRValue) 2246 HandleValue(E->getSubExpr()); 2247 2248 Inherited::VisitImplicitCastExpr(E); 2249 } 2250 2251 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2252 if (E->getConstructor()->isCopyConstructor()) 2253 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0))) 2254 if (ICE->getCastKind() == CK_NoOp) 2255 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr())) 2256 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2257 2258 Inherited::VisitCXXConstructExpr(E); 2259 } 2260 2261 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2262 Expr *Callee = E->getCallee(); 2263 if (isa<MemberExpr>(Callee)) 2264 HandleValue(Callee); 2265 2266 Inherited::VisitCXXMemberCallExpr(E); 2267 } 2268 2269 void VisitBinaryOperator(BinaryOperator *E) { 2270 // If a field assignment is detected, remove the field from the 2271 // uninitiailized field set. 2272 if (E->getOpcode() == BO_Assign) 2273 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2274 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2275 if (!FD->getType()->isReferenceType()) 2276 Decls.erase(FD); 2277 2278 Inherited::VisitBinaryOperator(E); 2279 } 2280 }; 2281 static void CheckInitExprContainsUninitializedFields( 2282 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2283 const CXXConstructorDecl *Constructor) { 2284 if (Decls.size() == 0) 2285 return; 2286 2287 if (!E) 2288 return; 2289 2290 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) { 2291 E = Default->getExpr(); 2292 if (!E) 2293 return; 2294 // In class initializers will point to the constructor. 2295 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E); 2296 } else { 2297 UninitializedFieldVisitor(S, Decls, 0).Visit(E); 2298 } 2299 } 2300 2301 // Diagnose value-uses of fields to initialize themselves, e.g. 2302 // foo(foo) 2303 // where foo is not also a parameter to the constructor. 2304 // Also diagnose across field uninitialized use such as 2305 // x(y), y(x) 2306 // TODO: implement -Wuninitialized and fold this into that framework. 2307 static void DiagnoseUninitializedFields( 2308 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2309 2310 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, 2311 Constructor->getLocation()) 2312 == DiagnosticsEngine::Ignored) { 2313 return; 2314 } 2315 2316 if (Constructor->isInvalidDecl()) 2317 return; 2318 2319 const CXXRecordDecl *RD = Constructor->getParent(); 2320 2321 // Holds fields that are uninitialized. 2322 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2323 2324 // At the beginning, all fields are uninitialized. 2325 for (auto *I : RD->decls()) { 2326 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2327 UninitializedFields.insert(FD); 2328 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2329 UninitializedFields.insert(IFD->getAnonField()); 2330 } 2331 } 2332 2333 for (const auto *FieldInit : Constructor->inits()) { 2334 Expr *InitExpr = FieldInit->getInit(); 2335 2336 CheckInitExprContainsUninitializedFields( 2337 SemaRef, InitExpr, UninitializedFields, Constructor); 2338 2339 if (FieldDecl *Field = FieldInit->getAnyMember()) 2340 UninitializedFields.erase(Field); 2341 } 2342 } 2343 } // namespace 2344 2345 /// \brief Enter a new C++ default initializer scope. After calling this, the 2346 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2347 /// parsing or instantiating the initializer failed. 2348 void Sema::ActOnStartCXXInClassMemberInitializer() { 2349 // Create a synthetic function scope to represent the call to the constructor 2350 // that notionally surrounds a use of this initializer. 2351 PushFunctionScope(); 2352 } 2353 2354 /// \brief This is invoked after parsing an in-class initializer for a 2355 /// non-static C++ class member, and after instantiating an in-class initializer 2356 /// in a class template. Such actions are deferred until the class is complete. 2357 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2358 SourceLocation InitLoc, 2359 Expr *InitExpr) { 2360 // Pop the notional constructor scope we created earlier. 2361 PopFunctionScopeInfo(0, D); 2362 2363 FieldDecl *FD = cast<FieldDecl>(D); 2364 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2365 "must set init style when field is created"); 2366 2367 if (!InitExpr) { 2368 FD->setInvalidDecl(); 2369 FD->removeInClassInitializer(); 2370 return; 2371 } 2372 2373 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2374 FD->setInvalidDecl(); 2375 FD->removeInClassInitializer(); 2376 return; 2377 } 2378 2379 ExprResult Init = InitExpr; 2380 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2381 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2382 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2383 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2384 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2385 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2386 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2387 if (Init.isInvalid()) { 2388 FD->setInvalidDecl(); 2389 return; 2390 } 2391 } 2392 2393 // C++11 [class.base.init]p7: 2394 // The initialization of each base and member constitutes a 2395 // full-expression. 2396 Init = ActOnFinishFullExpr(Init.take(), InitLoc); 2397 if (Init.isInvalid()) { 2398 FD->setInvalidDecl(); 2399 return; 2400 } 2401 2402 InitExpr = Init.release(); 2403 2404 FD->setInClassInitializer(InitExpr); 2405 } 2406 2407 /// \brief Find the direct and/or virtual base specifiers that 2408 /// correspond to the given base type, for use in base initialization 2409 /// within a constructor. 2410 static bool FindBaseInitializer(Sema &SemaRef, 2411 CXXRecordDecl *ClassDecl, 2412 QualType BaseType, 2413 const CXXBaseSpecifier *&DirectBaseSpec, 2414 const CXXBaseSpecifier *&VirtualBaseSpec) { 2415 // First, check for a direct base class. 2416 DirectBaseSpec = 0; 2417 for (const auto &Base : ClassDecl->bases()) { 2418 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2419 // We found a direct base of this type. That's what we're 2420 // initializing. 2421 DirectBaseSpec = &Base; 2422 break; 2423 } 2424 } 2425 2426 // Check for a virtual base class. 2427 // FIXME: We might be able to short-circuit this if we know in advance that 2428 // there are no virtual bases. 2429 VirtualBaseSpec = 0; 2430 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2431 // We haven't found a base yet; search the class hierarchy for a 2432 // virtual base class. 2433 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2434 /*DetectVirtual=*/false); 2435 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2436 BaseType, Paths)) { 2437 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2438 Path != Paths.end(); ++Path) { 2439 if (Path->back().Base->isVirtual()) { 2440 VirtualBaseSpec = Path->back().Base; 2441 break; 2442 } 2443 } 2444 } 2445 } 2446 2447 return DirectBaseSpec || VirtualBaseSpec; 2448 } 2449 2450 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2451 MemInitResult 2452 Sema::ActOnMemInitializer(Decl *ConstructorD, 2453 Scope *S, 2454 CXXScopeSpec &SS, 2455 IdentifierInfo *MemberOrBase, 2456 ParsedType TemplateTypeTy, 2457 const DeclSpec &DS, 2458 SourceLocation IdLoc, 2459 Expr *InitList, 2460 SourceLocation EllipsisLoc) { 2461 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2462 DS, IdLoc, InitList, 2463 EllipsisLoc); 2464 } 2465 2466 /// \brief Handle a C++ member initializer using parentheses syntax. 2467 MemInitResult 2468 Sema::ActOnMemInitializer(Decl *ConstructorD, 2469 Scope *S, 2470 CXXScopeSpec &SS, 2471 IdentifierInfo *MemberOrBase, 2472 ParsedType TemplateTypeTy, 2473 const DeclSpec &DS, 2474 SourceLocation IdLoc, 2475 SourceLocation LParenLoc, 2476 ArrayRef<Expr *> Args, 2477 SourceLocation RParenLoc, 2478 SourceLocation EllipsisLoc) { 2479 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2480 Args, RParenLoc); 2481 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2482 DS, IdLoc, List, EllipsisLoc); 2483 } 2484 2485 namespace { 2486 2487 // Callback to only accept typo corrections that can be a valid C++ member 2488 // intializer: either a non-static field member or a base class. 2489 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2490 public: 2491 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2492 : ClassDecl(ClassDecl) {} 2493 2494 bool ValidateCandidate(const TypoCorrection &candidate) override { 2495 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2496 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2497 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2498 return isa<TypeDecl>(ND); 2499 } 2500 return false; 2501 } 2502 2503 private: 2504 CXXRecordDecl *ClassDecl; 2505 }; 2506 2507 } 2508 2509 /// \brief Handle a C++ member initializer. 2510 MemInitResult 2511 Sema::BuildMemInitializer(Decl *ConstructorD, 2512 Scope *S, 2513 CXXScopeSpec &SS, 2514 IdentifierInfo *MemberOrBase, 2515 ParsedType TemplateTypeTy, 2516 const DeclSpec &DS, 2517 SourceLocation IdLoc, 2518 Expr *Init, 2519 SourceLocation EllipsisLoc) { 2520 if (!ConstructorD) 2521 return true; 2522 2523 AdjustDeclIfTemplate(ConstructorD); 2524 2525 CXXConstructorDecl *Constructor 2526 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2527 if (!Constructor) { 2528 // The user wrote a constructor initializer on a function that is 2529 // not a C++ constructor. Ignore the error for now, because we may 2530 // have more member initializers coming; we'll diagnose it just 2531 // once in ActOnMemInitializers. 2532 return true; 2533 } 2534 2535 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2536 2537 // C++ [class.base.init]p2: 2538 // Names in a mem-initializer-id are looked up in the scope of the 2539 // constructor's class and, if not found in that scope, are looked 2540 // up in the scope containing the constructor's definition. 2541 // [Note: if the constructor's class contains a member with the 2542 // same name as a direct or virtual base class of the class, a 2543 // mem-initializer-id naming the member or base class and composed 2544 // of a single identifier refers to the class member. A 2545 // mem-initializer-id for the hidden base class may be specified 2546 // using a qualified name. ] 2547 if (!SS.getScopeRep() && !TemplateTypeTy) { 2548 // Look for a member, first. 2549 DeclContext::lookup_result Result 2550 = ClassDecl->lookup(MemberOrBase); 2551 if (!Result.empty()) { 2552 ValueDecl *Member; 2553 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2554 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2555 if (EllipsisLoc.isValid()) 2556 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2557 << MemberOrBase 2558 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2559 2560 return BuildMemberInitializer(Member, Init, IdLoc); 2561 } 2562 } 2563 } 2564 // It didn't name a member, so see if it names a class. 2565 QualType BaseType; 2566 TypeSourceInfo *TInfo = 0; 2567 2568 if (TemplateTypeTy) { 2569 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2570 } else if (DS.getTypeSpecType() == TST_decltype) { 2571 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2572 } else { 2573 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2574 LookupParsedName(R, S, &SS); 2575 2576 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2577 if (!TyD) { 2578 if (R.isAmbiguous()) return true; 2579 2580 // We don't want access-control diagnostics here. 2581 R.suppressDiagnostics(); 2582 2583 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2584 bool NotUnknownSpecialization = false; 2585 DeclContext *DC = computeDeclContext(SS, false); 2586 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2587 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2588 2589 if (!NotUnknownSpecialization) { 2590 // When the scope specifier can refer to a member of an unknown 2591 // specialization, we take it as a type name. 2592 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2593 SS.getWithLocInContext(Context), 2594 *MemberOrBase, IdLoc); 2595 if (BaseType.isNull()) 2596 return true; 2597 2598 R.clear(); 2599 R.setLookupName(MemberOrBase); 2600 } 2601 } 2602 2603 // If no results were found, try to correct typos. 2604 TypoCorrection Corr; 2605 MemInitializerValidatorCCC Validator(ClassDecl); 2606 if (R.empty() && BaseType.isNull() && 2607 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2608 Validator, CTK_ErrorRecovery, ClassDecl))) { 2609 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2610 // We have found a non-static data member with a similar 2611 // name to what was typed; complain and initialize that 2612 // member. 2613 diagnoseTypo(Corr, 2614 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2615 << MemberOrBase << true); 2616 return BuildMemberInitializer(Member, Init, IdLoc); 2617 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2618 const CXXBaseSpecifier *DirectBaseSpec; 2619 const CXXBaseSpecifier *VirtualBaseSpec; 2620 if (FindBaseInitializer(*this, ClassDecl, 2621 Context.getTypeDeclType(Type), 2622 DirectBaseSpec, VirtualBaseSpec)) { 2623 // We have found a direct or virtual base class with a 2624 // similar name to what was typed; complain and initialize 2625 // that base class. 2626 diagnoseTypo(Corr, 2627 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2628 << MemberOrBase << false, 2629 PDiag() /*Suppress note, we provide our own.*/); 2630 2631 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2632 : VirtualBaseSpec; 2633 Diag(BaseSpec->getLocStart(), 2634 diag::note_base_class_specified_here) 2635 << BaseSpec->getType() 2636 << BaseSpec->getSourceRange(); 2637 2638 TyD = Type; 2639 } 2640 } 2641 } 2642 2643 if (!TyD && BaseType.isNull()) { 2644 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2645 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2646 return true; 2647 } 2648 } 2649 2650 if (BaseType.isNull()) { 2651 BaseType = Context.getTypeDeclType(TyD); 2652 if (SS.isSet()) 2653 // FIXME: preserve source range information 2654 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 2655 BaseType); 2656 } 2657 } 2658 2659 if (!TInfo) 2660 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2661 2662 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2663 } 2664 2665 /// Checks a member initializer expression for cases where reference (or 2666 /// pointer) members are bound to by-value parameters (or their addresses). 2667 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2668 Expr *Init, 2669 SourceLocation IdLoc) { 2670 QualType MemberTy = Member->getType(); 2671 2672 // We only handle pointers and references currently. 2673 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2674 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2675 return; 2676 2677 const bool IsPointer = MemberTy->isPointerType(); 2678 if (IsPointer) { 2679 if (const UnaryOperator *Op 2680 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2681 // The only case we're worried about with pointers requires taking the 2682 // address. 2683 if (Op->getOpcode() != UO_AddrOf) 2684 return; 2685 2686 Init = Op->getSubExpr(); 2687 } else { 2688 // We only handle address-of expression initializers for pointers. 2689 return; 2690 } 2691 } 2692 2693 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2694 // We only warn when referring to a non-reference parameter declaration. 2695 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2696 if (!Parameter || Parameter->getType()->isReferenceType()) 2697 return; 2698 2699 S.Diag(Init->getExprLoc(), 2700 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2701 : diag::warn_bind_ref_member_to_parameter) 2702 << Member << Parameter << Init->getSourceRange(); 2703 } else { 2704 // Other initializers are fine. 2705 return; 2706 } 2707 2708 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2709 << (unsigned)IsPointer; 2710 } 2711 2712 MemInitResult 2713 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2714 SourceLocation IdLoc) { 2715 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2716 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2717 assert((DirectMember || IndirectMember) && 2718 "Member must be a FieldDecl or IndirectFieldDecl"); 2719 2720 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2721 return true; 2722 2723 if (Member->isInvalidDecl()) 2724 return true; 2725 2726 MultiExprArg Args; 2727 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2728 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2729 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2730 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2731 } else { 2732 // Template instantiation doesn't reconstruct ParenListExprs for us. 2733 Args = Init; 2734 } 2735 2736 SourceRange InitRange = Init->getSourceRange(); 2737 2738 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2739 // Can't check initialization for a member of dependent type or when 2740 // any of the arguments are type-dependent expressions. 2741 DiscardCleanupsInEvaluationContext(); 2742 } else { 2743 bool InitList = false; 2744 if (isa<InitListExpr>(Init)) { 2745 InitList = true; 2746 Args = Init; 2747 } 2748 2749 // Initialize the member. 2750 InitializedEntity MemberEntity = 2751 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2752 : InitializedEntity::InitializeMember(IndirectMember, 0); 2753 InitializationKind Kind = 2754 InitList ? InitializationKind::CreateDirectList(IdLoc) 2755 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2756 InitRange.getEnd()); 2757 2758 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 2759 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0); 2760 if (MemberInit.isInvalid()) 2761 return true; 2762 2763 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 2764 2765 // C++11 [class.base.init]p7: 2766 // The initialization of each base and member constitutes a 2767 // full-expression. 2768 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2769 if (MemberInit.isInvalid()) 2770 return true; 2771 2772 Init = MemberInit.get(); 2773 } 2774 2775 if (DirectMember) { 2776 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2777 InitRange.getBegin(), Init, 2778 InitRange.getEnd()); 2779 } else { 2780 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2781 InitRange.getBegin(), Init, 2782 InitRange.getEnd()); 2783 } 2784 } 2785 2786 MemInitResult 2787 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2788 CXXRecordDecl *ClassDecl) { 2789 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2790 if (!LangOpts.CPlusPlus11) 2791 return Diag(NameLoc, diag::err_delegating_ctor) 2792 << TInfo->getTypeLoc().getLocalSourceRange(); 2793 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2794 2795 bool InitList = true; 2796 MultiExprArg Args = Init; 2797 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2798 InitList = false; 2799 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2800 } 2801 2802 SourceRange InitRange = Init->getSourceRange(); 2803 // Initialize the object. 2804 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2805 QualType(ClassDecl->getTypeForDecl(), 0)); 2806 InitializationKind Kind = 2807 InitList ? InitializationKind::CreateDirectList(NameLoc) 2808 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2809 InitRange.getEnd()); 2810 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 2811 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2812 Args, 0); 2813 if (DelegationInit.isInvalid()) 2814 return true; 2815 2816 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2817 "Delegating constructor with no target?"); 2818 2819 // C++11 [class.base.init]p7: 2820 // The initialization of each base and member constitutes a 2821 // full-expression. 2822 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2823 InitRange.getBegin()); 2824 if (DelegationInit.isInvalid()) 2825 return true; 2826 2827 // If we are in a dependent context, template instantiation will 2828 // perform this type-checking again. Just save the arguments that we 2829 // received in a ParenListExpr. 2830 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2831 // of the information that we have about the base 2832 // initializer. However, deconstructing the ASTs is a dicey process, 2833 // and this approach is far more likely to get the corner cases right. 2834 if (CurContext->isDependentContext()) 2835 DelegationInit = Owned(Init); 2836 2837 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2838 DelegationInit.takeAs<Expr>(), 2839 InitRange.getEnd()); 2840 } 2841 2842 MemInitResult 2843 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2844 Expr *Init, CXXRecordDecl *ClassDecl, 2845 SourceLocation EllipsisLoc) { 2846 SourceLocation BaseLoc 2847 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2848 2849 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2850 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2851 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2852 2853 // C++ [class.base.init]p2: 2854 // [...] Unless the mem-initializer-id names a nonstatic data 2855 // member of the constructor's class or a direct or virtual base 2856 // of that class, the mem-initializer is ill-formed. A 2857 // mem-initializer-list can initialize a base class using any 2858 // name that denotes that base class type. 2859 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2860 2861 SourceRange InitRange = Init->getSourceRange(); 2862 if (EllipsisLoc.isValid()) { 2863 // This is a pack expansion. 2864 if (!BaseType->containsUnexpandedParameterPack()) { 2865 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2866 << SourceRange(BaseLoc, InitRange.getEnd()); 2867 2868 EllipsisLoc = SourceLocation(); 2869 } 2870 } else { 2871 // Check for any unexpanded parameter packs. 2872 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2873 return true; 2874 2875 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2876 return true; 2877 } 2878 2879 // Check for direct and virtual base classes. 2880 const CXXBaseSpecifier *DirectBaseSpec = 0; 2881 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2882 if (!Dependent) { 2883 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2884 BaseType)) 2885 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2886 2887 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2888 VirtualBaseSpec); 2889 2890 // C++ [base.class.init]p2: 2891 // Unless the mem-initializer-id names a nonstatic data member of the 2892 // constructor's class or a direct or virtual base of that class, the 2893 // mem-initializer is ill-formed. 2894 if (!DirectBaseSpec && !VirtualBaseSpec) { 2895 // If the class has any dependent bases, then it's possible that 2896 // one of those types will resolve to the same type as 2897 // BaseType. Therefore, just treat this as a dependent base 2898 // class initialization. FIXME: Should we try to check the 2899 // initialization anyway? It seems odd. 2900 if (ClassDecl->hasAnyDependentBases()) 2901 Dependent = true; 2902 else 2903 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2904 << BaseType << Context.getTypeDeclType(ClassDecl) 2905 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2906 } 2907 } 2908 2909 if (Dependent) { 2910 DiscardCleanupsInEvaluationContext(); 2911 2912 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2913 /*IsVirtual=*/false, 2914 InitRange.getBegin(), Init, 2915 InitRange.getEnd(), EllipsisLoc); 2916 } 2917 2918 // C++ [base.class.init]p2: 2919 // If a mem-initializer-id is ambiguous because it designates both 2920 // a direct non-virtual base class and an inherited virtual base 2921 // class, the mem-initializer is ill-formed. 2922 if (DirectBaseSpec && VirtualBaseSpec) 2923 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2924 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2925 2926 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 2927 if (!BaseSpec) 2928 BaseSpec = VirtualBaseSpec; 2929 2930 // Initialize the base. 2931 bool InitList = true; 2932 MultiExprArg Args = Init; 2933 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2934 InitList = false; 2935 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2936 } 2937 2938 InitializedEntity BaseEntity = 2939 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2940 InitializationKind Kind = 2941 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2942 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2943 InitRange.getEnd()); 2944 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 2945 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0); 2946 if (BaseInit.isInvalid()) 2947 return true; 2948 2949 // C++11 [class.base.init]p7: 2950 // The initialization of each base and member constitutes a 2951 // full-expression. 2952 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 2953 if (BaseInit.isInvalid()) 2954 return true; 2955 2956 // If we are in a dependent context, template instantiation will 2957 // perform this type-checking again. Just save the arguments that we 2958 // received in a ParenListExpr. 2959 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2960 // of the information that we have about the base 2961 // initializer. However, deconstructing the ASTs is a dicey process, 2962 // and this approach is far more likely to get the corner cases right. 2963 if (CurContext->isDependentContext()) 2964 BaseInit = Owned(Init); 2965 2966 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2967 BaseSpec->isVirtual(), 2968 InitRange.getBegin(), 2969 BaseInit.takeAs<Expr>(), 2970 InitRange.getEnd(), EllipsisLoc); 2971 } 2972 2973 // Create a static_cast\<T&&>(expr). 2974 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 2975 if (T.isNull()) T = E->getType(); 2976 QualType TargetType = SemaRef.BuildReferenceType( 2977 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 2978 SourceLocation ExprLoc = E->getLocStart(); 2979 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2980 TargetType, ExprLoc); 2981 2982 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2983 SourceRange(ExprLoc, ExprLoc), 2984 E->getSourceRange()).take(); 2985 } 2986 2987 /// ImplicitInitializerKind - How an implicit base or member initializer should 2988 /// initialize its base or member. 2989 enum ImplicitInitializerKind { 2990 IIK_Default, 2991 IIK_Copy, 2992 IIK_Move, 2993 IIK_Inherit 2994 }; 2995 2996 static bool 2997 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2998 ImplicitInitializerKind ImplicitInitKind, 2999 CXXBaseSpecifier *BaseSpec, 3000 bool IsInheritedVirtualBase, 3001 CXXCtorInitializer *&CXXBaseInit) { 3002 InitializedEntity InitEntity 3003 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 3004 IsInheritedVirtualBase); 3005 3006 ExprResult BaseInit; 3007 3008 switch (ImplicitInitKind) { 3009 case IIK_Inherit: { 3010 const CXXRecordDecl *Inherited = 3011 Constructor->getInheritedConstructor()->getParent(); 3012 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3013 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3014 // C++11 [class.inhctor]p8: 3015 // Each expression in the expression-list is of the form 3016 // static_cast<T&&>(p), where p is the name of the corresponding 3017 // constructor parameter and T is the declared type of p. 3018 SmallVector<Expr*, 16> Args; 3019 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3020 ParmVarDecl *PD = Constructor->getParamDecl(I); 3021 ExprResult ArgExpr = 3022 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3023 VK_LValue, SourceLocation()); 3024 if (ArgExpr.isInvalid()) 3025 return true; 3026 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType())); 3027 } 3028 3029 InitializationKind InitKind = InitializationKind::CreateDirect( 3030 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3031 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3032 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3033 break; 3034 } 3035 } 3036 // Fall through. 3037 case IIK_Default: { 3038 InitializationKind InitKind 3039 = InitializationKind::CreateDefault(Constructor->getLocation()); 3040 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3041 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3042 break; 3043 } 3044 3045 case IIK_Move: 3046 case IIK_Copy: { 3047 bool Moving = ImplicitInitKind == IIK_Move; 3048 ParmVarDecl *Param = Constructor->getParamDecl(0); 3049 QualType ParamType = Param->getType().getNonReferenceType(); 3050 3051 Expr *CopyCtorArg = 3052 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3053 SourceLocation(), Param, false, 3054 Constructor->getLocation(), ParamType, 3055 VK_LValue, 0); 3056 3057 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3058 3059 // Cast to the base class to avoid ambiguities. 3060 QualType ArgTy = 3061 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3062 ParamType.getQualifiers()); 3063 3064 if (Moving) { 3065 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3066 } 3067 3068 CXXCastPath BasePath; 3069 BasePath.push_back(BaseSpec); 3070 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3071 CK_UncheckedDerivedToBase, 3072 Moving ? VK_XValue : VK_LValue, 3073 &BasePath).take(); 3074 3075 InitializationKind InitKind 3076 = InitializationKind::CreateDirect(Constructor->getLocation(), 3077 SourceLocation(), SourceLocation()); 3078 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3079 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3080 break; 3081 } 3082 } 3083 3084 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3085 if (BaseInit.isInvalid()) 3086 return true; 3087 3088 CXXBaseInit = 3089 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3090 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3091 SourceLocation()), 3092 BaseSpec->isVirtual(), 3093 SourceLocation(), 3094 BaseInit.takeAs<Expr>(), 3095 SourceLocation(), 3096 SourceLocation()); 3097 3098 return false; 3099 } 3100 3101 static bool RefersToRValueRef(Expr *MemRef) { 3102 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3103 return Referenced->getType()->isRValueReferenceType(); 3104 } 3105 3106 static bool 3107 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3108 ImplicitInitializerKind ImplicitInitKind, 3109 FieldDecl *Field, IndirectFieldDecl *Indirect, 3110 CXXCtorInitializer *&CXXMemberInit) { 3111 if (Field->isInvalidDecl()) 3112 return true; 3113 3114 SourceLocation Loc = Constructor->getLocation(); 3115 3116 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3117 bool Moving = ImplicitInitKind == IIK_Move; 3118 ParmVarDecl *Param = Constructor->getParamDecl(0); 3119 QualType ParamType = Param->getType().getNonReferenceType(); 3120 3121 // Suppress copying zero-width bitfields. 3122 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3123 return false; 3124 3125 Expr *MemberExprBase = 3126 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3127 SourceLocation(), Param, false, 3128 Loc, ParamType, VK_LValue, 0); 3129 3130 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3131 3132 if (Moving) { 3133 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3134 } 3135 3136 // Build a reference to this field within the parameter. 3137 CXXScopeSpec SS; 3138 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3139 Sema::LookupMemberName); 3140 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3141 : cast<ValueDecl>(Field), AS_public); 3142 MemberLookup.resolveKind(); 3143 ExprResult CtorArg 3144 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3145 ParamType, Loc, 3146 /*IsArrow=*/false, 3147 SS, 3148 /*TemplateKWLoc=*/SourceLocation(), 3149 /*FirstQualifierInScope=*/0, 3150 MemberLookup, 3151 /*TemplateArgs=*/0); 3152 if (CtorArg.isInvalid()) 3153 return true; 3154 3155 // C++11 [class.copy]p15: 3156 // - if a member m has rvalue reference type T&&, it is direct-initialized 3157 // with static_cast<T&&>(x.m); 3158 if (RefersToRValueRef(CtorArg.get())) { 3159 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3160 } 3161 3162 // When the field we are copying is an array, create index variables for 3163 // each dimension of the array. We use these index variables to subscript 3164 // the source array, and other clients (e.g., CodeGen) will perform the 3165 // necessary iteration with these index variables. 3166 SmallVector<VarDecl *, 4> IndexVariables; 3167 QualType BaseType = Field->getType(); 3168 QualType SizeType = SemaRef.Context.getSizeType(); 3169 bool InitializingArray = false; 3170 while (const ConstantArrayType *Array 3171 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3172 InitializingArray = true; 3173 // Create the iteration variable for this array index. 3174 IdentifierInfo *IterationVarName = 0; 3175 { 3176 SmallString<8> Str; 3177 llvm::raw_svector_ostream OS(Str); 3178 OS << "__i" << IndexVariables.size(); 3179 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3180 } 3181 VarDecl *IterationVar 3182 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3183 IterationVarName, SizeType, 3184 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3185 SC_None); 3186 IndexVariables.push_back(IterationVar); 3187 3188 // Create a reference to the iteration variable. 3189 ExprResult IterationVarRef 3190 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3191 assert(!IterationVarRef.isInvalid() && 3192 "Reference to invented variable cannot fail!"); 3193 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 3194 assert(!IterationVarRef.isInvalid() && 3195 "Conversion of invented variable cannot fail!"); 3196 3197 // Subscript the array with this iteration variable. 3198 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 3199 IterationVarRef.take(), 3200 Loc); 3201 if (CtorArg.isInvalid()) 3202 return true; 3203 3204 BaseType = Array->getElementType(); 3205 } 3206 3207 // The array subscript expression is an lvalue, which is wrong for moving. 3208 if (Moving && InitializingArray) 3209 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3210 3211 // Construct the entity that we will be initializing. For an array, this 3212 // will be first element in the array, which may require several levels 3213 // of array-subscript entities. 3214 SmallVector<InitializedEntity, 4> Entities; 3215 Entities.reserve(1 + IndexVariables.size()); 3216 if (Indirect) 3217 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3218 else 3219 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3220 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3221 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3222 0, 3223 Entities.back())); 3224 3225 // Direct-initialize to use the copy constructor. 3226 InitializationKind InitKind = 3227 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3228 3229 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 3230 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3231 3232 ExprResult MemberInit 3233 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3234 MultiExprArg(&CtorArgE, 1)); 3235 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3236 if (MemberInit.isInvalid()) 3237 return true; 3238 3239 if (Indirect) { 3240 assert(IndexVariables.size() == 0 && 3241 "Indirect field improperly initialized"); 3242 CXXMemberInit 3243 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3244 Loc, Loc, 3245 MemberInit.takeAs<Expr>(), 3246 Loc); 3247 } else 3248 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3249 Loc, MemberInit.takeAs<Expr>(), 3250 Loc, 3251 IndexVariables.data(), 3252 IndexVariables.size()); 3253 return false; 3254 } 3255 3256 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3257 "Unhandled implicit init kind!"); 3258 3259 QualType FieldBaseElementType = 3260 SemaRef.Context.getBaseElementType(Field->getType()); 3261 3262 if (FieldBaseElementType->isRecordType()) { 3263 InitializedEntity InitEntity 3264 = Indirect? InitializedEntity::InitializeMember(Indirect) 3265 : InitializedEntity::InitializeMember(Field); 3266 InitializationKind InitKind = 3267 InitializationKind::CreateDefault(Loc); 3268 3269 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3270 ExprResult MemberInit = 3271 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3272 3273 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3274 if (MemberInit.isInvalid()) 3275 return true; 3276 3277 if (Indirect) 3278 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3279 Indirect, Loc, 3280 Loc, 3281 MemberInit.get(), 3282 Loc); 3283 else 3284 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3285 Field, Loc, Loc, 3286 MemberInit.get(), 3287 Loc); 3288 return false; 3289 } 3290 3291 if (!Field->getParent()->isUnion()) { 3292 if (FieldBaseElementType->isReferenceType()) { 3293 SemaRef.Diag(Constructor->getLocation(), 3294 diag::err_uninitialized_member_in_ctor) 3295 << (int)Constructor->isImplicit() 3296 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3297 << 0 << Field->getDeclName(); 3298 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3299 return true; 3300 } 3301 3302 if (FieldBaseElementType.isConstQualified()) { 3303 SemaRef.Diag(Constructor->getLocation(), 3304 diag::err_uninitialized_member_in_ctor) 3305 << (int)Constructor->isImplicit() 3306 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3307 << 1 << Field->getDeclName(); 3308 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3309 return true; 3310 } 3311 } 3312 3313 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3314 FieldBaseElementType->isObjCRetainableType() && 3315 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3316 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3317 // ARC: 3318 // Default-initialize Objective-C pointers to NULL. 3319 CXXMemberInit 3320 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3321 Loc, Loc, 3322 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3323 Loc); 3324 return false; 3325 } 3326 3327 // Nothing to initialize. 3328 CXXMemberInit = 0; 3329 return false; 3330 } 3331 3332 namespace { 3333 struct BaseAndFieldInfo { 3334 Sema &S; 3335 CXXConstructorDecl *Ctor; 3336 bool AnyErrorsInInits; 3337 ImplicitInitializerKind IIK; 3338 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3339 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3340 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3341 3342 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3343 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3344 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3345 if (Generated && Ctor->isCopyConstructor()) 3346 IIK = IIK_Copy; 3347 else if (Generated && Ctor->isMoveConstructor()) 3348 IIK = IIK_Move; 3349 else if (Ctor->getInheritedConstructor()) 3350 IIK = IIK_Inherit; 3351 else 3352 IIK = IIK_Default; 3353 } 3354 3355 bool isImplicitCopyOrMove() const { 3356 switch (IIK) { 3357 case IIK_Copy: 3358 case IIK_Move: 3359 return true; 3360 3361 case IIK_Default: 3362 case IIK_Inherit: 3363 return false; 3364 } 3365 3366 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3367 } 3368 3369 bool addFieldInitializer(CXXCtorInitializer *Init) { 3370 AllToInit.push_back(Init); 3371 3372 // Check whether this initializer makes the field "used". 3373 if (Init->getInit()->HasSideEffects(S.Context)) 3374 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3375 3376 return false; 3377 } 3378 3379 bool isInactiveUnionMember(FieldDecl *Field) { 3380 RecordDecl *Record = Field->getParent(); 3381 if (!Record->isUnion()) 3382 return false; 3383 3384 if (FieldDecl *Active = 3385 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3386 return Active != Field->getCanonicalDecl(); 3387 3388 // In an implicit copy or move constructor, ignore any in-class initializer. 3389 if (isImplicitCopyOrMove()) 3390 return true; 3391 3392 // If there's no explicit initialization, the field is active only if it 3393 // has an in-class initializer... 3394 if (Field->hasInClassInitializer()) 3395 return false; 3396 // ... or it's an anonymous struct or union whose class has an in-class 3397 // initializer. 3398 if (!Field->isAnonymousStructOrUnion()) 3399 return true; 3400 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3401 return !FieldRD->hasInClassInitializer(); 3402 } 3403 3404 /// \brief Determine whether the given field is, or is within, a union member 3405 /// that is inactive (because there was an initializer given for a different 3406 /// member of the union, or because the union was not initialized at all). 3407 bool isWithinInactiveUnionMember(FieldDecl *Field, 3408 IndirectFieldDecl *Indirect) { 3409 if (!Indirect) 3410 return isInactiveUnionMember(Field); 3411 3412 for (auto *C : Indirect->chain()) { 3413 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3414 if (Field && isInactiveUnionMember(Field)) 3415 return true; 3416 } 3417 return false; 3418 } 3419 }; 3420 } 3421 3422 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3423 /// array type. 3424 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3425 if (T->isIncompleteArrayType()) 3426 return true; 3427 3428 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3429 if (!ArrayT->getSize()) 3430 return true; 3431 3432 T = ArrayT->getElementType(); 3433 } 3434 3435 return false; 3436 } 3437 3438 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3439 FieldDecl *Field, 3440 IndirectFieldDecl *Indirect = 0) { 3441 if (Field->isInvalidDecl()) 3442 return false; 3443 3444 // Overwhelmingly common case: we have a direct initializer for this field. 3445 if (CXXCtorInitializer *Init = 3446 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 3447 return Info.addFieldInitializer(Init); 3448 3449 // C++11 [class.base.init]p8: 3450 // if the entity is a non-static data member that has a 3451 // brace-or-equal-initializer and either 3452 // -- the constructor's class is a union and no other variant member of that 3453 // union is designated by a mem-initializer-id or 3454 // -- the constructor's class is not a union, and, if the entity is a member 3455 // of an anonymous union, no other member of that union is designated by 3456 // a mem-initializer-id, 3457 // the entity is initialized as specified in [dcl.init]. 3458 // 3459 // We also apply the same rules to handle anonymous structs within anonymous 3460 // unions. 3461 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3462 return false; 3463 3464 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3465 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3466 Info.Ctor->getLocation(), Field); 3467 CXXCtorInitializer *Init; 3468 if (Indirect) 3469 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3470 SourceLocation(), 3471 SourceLocation(), DIE, 3472 SourceLocation()); 3473 else 3474 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3475 SourceLocation(), 3476 SourceLocation(), DIE, 3477 SourceLocation()); 3478 return Info.addFieldInitializer(Init); 3479 } 3480 3481 // Don't initialize incomplete or zero-length arrays. 3482 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3483 return false; 3484 3485 // Don't try to build an implicit initializer if there were semantic 3486 // errors in any of the initializers (and therefore we might be 3487 // missing some that the user actually wrote). 3488 if (Info.AnyErrorsInInits) 3489 return false; 3490 3491 CXXCtorInitializer *Init = 0; 3492 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3493 Indirect, Init)) 3494 return true; 3495 3496 if (!Init) 3497 return false; 3498 3499 return Info.addFieldInitializer(Init); 3500 } 3501 3502 bool 3503 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3504 CXXCtorInitializer *Initializer) { 3505 assert(Initializer->isDelegatingInitializer()); 3506 Constructor->setNumCtorInitializers(1); 3507 CXXCtorInitializer **initializer = 3508 new (Context) CXXCtorInitializer*[1]; 3509 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3510 Constructor->setCtorInitializers(initializer); 3511 3512 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3513 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3514 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3515 } 3516 3517 DelegatingCtorDecls.push_back(Constructor); 3518 3519 return false; 3520 } 3521 3522 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3523 ArrayRef<CXXCtorInitializer *> Initializers) { 3524 if (Constructor->isDependentContext()) { 3525 // Just store the initializers as written, they will be checked during 3526 // instantiation. 3527 if (!Initializers.empty()) { 3528 Constructor->setNumCtorInitializers(Initializers.size()); 3529 CXXCtorInitializer **baseOrMemberInitializers = 3530 new (Context) CXXCtorInitializer*[Initializers.size()]; 3531 memcpy(baseOrMemberInitializers, Initializers.data(), 3532 Initializers.size() * sizeof(CXXCtorInitializer*)); 3533 Constructor->setCtorInitializers(baseOrMemberInitializers); 3534 } 3535 3536 // Let template instantiation know whether we had errors. 3537 if (AnyErrors) 3538 Constructor->setInvalidDecl(); 3539 3540 return false; 3541 } 3542 3543 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3544 3545 // We need to build the initializer AST according to order of construction 3546 // and not what user specified in the Initializers list. 3547 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3548 if (!ClassDecl) 3549 return true; 3550 3551 bool HadError = false; 3552 3553 for (unsigned i = 0; i < Initializers.size(); i++) { 3554 CXXCtorInitializer *Member = Initializers[i]; 3555 3556 if (Member->isBaseInitializer()) 3557 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3558 else { 3559 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 3560 3561 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3562 for (auto *C : F->chain()) { 3563 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3564 if (FD && FD->getParent()->isUnion()) 3565 Info.ActiveUnionMember.insert(std::make_pair( 3566 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3567 } 3568 } else if (FieldDecl *FD = Member->getMember()) { 3569 if (FD->getParent()->isUnion()) 3570 Info.ActiveUnionMember.insert(std::make_pair( 3571 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3572 } 3573 } 3574 } 3575 3576 // Keep track of the direct virtual bases. 3577 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3578 for (auto &I : ClassDecl->bases()) { 3579 if (I.isVirtual()) 3580 DirectVBases.insert(&I); 3581 } 3582 3583 // Push virtual bases before others. 3584 for (auto &VBase : ClassDecl->vbases()) { 3585 if (CXXCtorInitializer *Value 3586 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3587 // [class.base.init]p7, per DR257: 3588 // A mem-initializer where the mem-initializer-id names a virtual base 3589 // class is ignored during execution of a constructor of any class that 3590 // is not the most derived class. 3591 if (ClassDecl->isAbstract()) { 3592 // FIXME: Provide a fixit to remove the base specifier. This requires 3593 // tracking the location of the associated comma for a base specifier. 3594 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3595 << VBase.getType() << ClassDecl; 3596 DiagnoseAbstractType(ClassDecl); 3597 } 3598 3599 Info.AllToInit.push_back(Value); 3600 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3601 // [class.base.init]p8, per DR257: 3602 // If a given [...] base class is not named by a mem-initializer-id 3603 // [...] and the entity is not a virtual base class of an abstract 3604 // class, then [...] the entity is default-initialized. 3605 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3606 CXXCtorInitializer *CXXBaseInit; 3607 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3608 &VBase, IsInheritedVirtualBase, 3609 CXXBaseInit)) { 3610 HadError = true; 3611 continue; 3612 } 3613 3614 Info.AllToInit.push_back(CXXBaseInit); 3615 } 3616 } 3617 3618 // Non-virtual bases. 3619 for (auto &Base : ClassDecl->bases()) { 3620 // Virtuals are in the virtual base list and already constructed. 3621 if (Base.isVirtual()) 3622 continue; 3623 3624 if (CXXCtorInitializer *Value 3625 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3626 Info.AllToInit.push_back(Value); 3627 } else if (!AnyErrors) { 3628 CXXCtorInitializer *CXXBaseInit; 3629 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3630 &Base, /*IsInheritedVirtualBase=*/false, 3631 CXXBaseInit)) { 3632 HadError = true; 3633 continue; 3634 } 3635 3636 Info.AllToInit.push_back(CXXBaseInit); 3637 } 3638 } 3639 3640 // Fields. 3641 for (auto *Mem : ClassDecl->decls()) { 3642 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 3643 // C++ [class.bit]p2: 3644 // A declaration for a bit-field that omits the identifier declares an 3645 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3646 // initialized. 3647 if (F->isUnnamedBitfield()) 3648 continue; 3649 3650 // If we're not generating the implicit copy/move constructor, then we'll 3651 // handle anonymous struct/union fields based on their individual 3652 // indirect fields. 3653 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3654 continue; 3655 3656 if (CollectFieldInitializer(*this, Info, F)) 3657 HadError = true; 3658 continue; 3659 } 3660 3661 // Beyond this point, we only consider default initialization. 3662 if (Info.isImplicitCopyOrMove()) 3663 continue; 3664 3665 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 3666 if (F->getType()->isIncompleteArrayType()) { 3667 assert(ClassDecl->hasFlexibleArrayMember() && 3668 "Incomplete array type is not valid"); 3669 continue; 3670 } 3671 3672 // Initialize each field of an anonymous struct individually. 3673 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3674 HadError = true; 3675 3676 continue; 3677 } 3678 } 3679 3680 unsigned NumInitializers = Info.AllToInit.size(); 3681 if (NumInitializers > 0) { 3682 Constructor->setNumCtorInitializers(NumInitializers); 3683 CXXCtorInitializer **baseOrMemberInitializers = 3684 new (Context) CXXCtorInitializer*[NumInitializers]; 3685 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3686 NumInitializers * sizeof(CXXCtorInitializer*)); 3687 Constructor->setCtorInitializers(baseOrMemberInitializers); 3688 3689 // Constructors implicitly reference the base and member 3690 // destructors. 3691 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3692 Constructor->getParent()); 3693 } 3694 3695 return HadError; 3696 } 3697 3698 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3699 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3700 const RecordDecl *RD = RT->getDecl(); 3701 if (RD->isAnonymousStructOrUnion()) { 3702 for (auto *Field : RD->fields()) 3703 PopulateKeysForFields(Field, IdealInits); 3704 return; 3705 } 3706 } 3707 IdealInits.push_back(Field->getCanonicalDecl()); 3708 } 3709 3710 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3711 return Context.getCanonicalType(BaseType).getTypePtr(); 3712 } 3713 3714 static const void *GetKeyForMember(ASTContext &Context, 3715 CXXCtorInitializer *Member) { 3716 if (!Member->isAnyMemberInitializer()) 3717 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3718 3719 return Member->getAnyMember()->getCanonicalDecl(); 3720 } 3721 3722 static void DiagnoseBaseOrMemInitializerOrder( 3723 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3724 ArrayRef<CXXCtorInitializer *> Inits) { 3725 if (Constructor->getDeclContext()->isDependentContext()) 3726 return; 3727 3728 // Don't check initializers order unless the warning is enabled at the 3729 // location of at least one initializer. 3730 bool ShouldCheckOrder = false; 3731 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3732 CXXCtorInitializer *Init = Inits[InitIndex]; 3733 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3734 Init->getSourceLocation()) 3735 != DiagnosticsEngine::Ignored) { 3736 ShouldCheckOrder = true; 3737 break; 3738 } 3739 } 3740 if (!ShouldCheckOrder) 3741 return; 3742 3743 // Build the list of bases and members in the order that they'll 3744 // actually be initialized. The explicit initializers should be in 3745 // this same order but may be missing things. 3746 SmallVector<const void*, 32> IdealInitKeys; 3747 3748 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3749 3750 // 1. Virtual bases. 3751 for (const auto &VBase : ClassDecl->vbases()) 3752 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 3753 3754 // 2. Non-virtual bases. 3755 for (const auto &Base : ClassDecl->bases()) { 3756 if (Base.isVirtual()) 3757 continue; 3758 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 3759 } 3760 3761 // 3. Direct fields. 3762 for (auto *Field : ClassDecl->fields()) { 3763 if (Field->isUnnamedBitfield()) 3764 continue; 3765 3766 PopulateKeysForFields(Field, IdealInitKeys); 3767 } 3768 3769 unsigned NumIdealInits = IdealInitKeys.size(); 3770 unsigned IdealIndex = 0; 3771 3772 CXXCtorInitializer *PrevInit = 0; 3773 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3774 CXXCtorInitializer *Init = Inits[InitIndex]; 3775 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3776 3777 // Scan forward to try to find this initializer in the idealized 3778 // initializers list. 3779 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3780 if (InitKey == IdealInitKeys[IdealIndex]) 3781 break; 3782 3783 // If we didn't find this initializer, it must be because we 3784 // scanned past it on a previous iteration. That can only 3785 // happen if we're out of order; emit a warning. 3786 if (IdealIndex == NumIdealInits && PrevInit) { 3787 Sema::SemaDiagnosticBuilder D = 3788 SemaRef.Diag(PrevInit->getSourceLocation(), 3789 diag::warn_initializer_out_of_order); 3790 3791 if (PrevInit->isAnyMemberInitializer()) 3792 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3793 else 3794 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3795 3796 if (Init->isAnyMemberInitializer()) 3797 D << 0 << Init->getAnyMember()->getDeclName(); 3798 else 3799 D << 1 << Init->getTypeSourceInfo()->getType(); 3800 3801 // Move back to the initializer's location in the ideal list. 3802 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3803 if (InitKey == IdealInitKeys[IdealIndex]) 3804 break; 3805 3806 assert(IdealIndex != NumIdealInits && 3807 "initializer not found in initializer list"); 3808 } 3809 3810 PrevInit = Init; 3811 } 3812 } 3813 3814 namespace { 3815 bool CheckRedundantInit(Sema &S, 3816 CXXCtorInitializer *Init, 3817 CXXCtorInitializer *&PrevInit) { 3818 if (!PrevInit) { 3819 PrevInit = Init; 3820 return false; 3821 } 3822 3823 if (FieldDecl *Field = Init->getAnyMember()) 3824 S.Diag(Init->getSourceLocation(), 3825 diag::err_multiple_mem_initialization) 3826 << Field->getDeclName() 3827 << Init->getSourceRange(); 3828 else { 3829 const Type *BaseClass = Init->getBaseClass(); 3830 assert(BaseClass && "neither field nor base"); 3831 S.Diag(Init->getSourceLocation(), 3832 diag::err_multiple_base_initialization) 3833 << QualType(BaseClass, 0) 3834 << Init->getSourceRange(); 3835 } 3836 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3837 << 0 << PrevInit->getSourceRange(); 3838 3839 return true; 3840 } 3841 3842 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3843 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3844 3845 bool CheckRedundantUnionInit(Sema &S, 3846 CXXCtorInitializer *Init, 3847 RedundantUnionMap &Unions) { 3848 FieldDecl *Field = Init->getAnyMember(); 3849 RecordDecl *Parent = Field->getParent(); 3850 NamedDecl *Child = Field; 3851 3852 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3853 if (Parent->isUnion()) { 3854 UnionEntry &En = Unions[Parent]; 3855 if (En.first && En.first != Child) { 3856 S.Diag(Init->getSourceLocation(), 3857 diag::err_multiple_mem_union_initialization) 3858 << Field->getDeclName() 3859 << Init->getSourceRange(); 3860 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3861 << 0 << En.second->getSourceRange(); 3862 return true; 3863 } 3864 if (!En.first) { 3865 En.first = Child; 3866 En.second = Init; 3867 } 3868 if (!Parent->isAnonymousStructOrUnion()) 3869 return false; 3870 } 3871 3872 Child = Parent; 3873 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3874 } 3875 3876 return false; 3877 } 3878 } 3879 3880 /// ActOnMemInitializers - Handle the member initializers for a constructor. 3881 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3882 SourceLocation ColonLoc, 3883 ArrayRef<CXXCtorInitializer*> MemInits, 3884 bool AnyErrors) { 3885 if (!ConstructorDecl) 3886 return; 3887 3888 AdjustDeclIfTemplate(ConstructorDecl); 3889 3890 CXXConstructorDecl *Constructor 3891 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3892 3893 if (!Constructor) { 3894 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3895 return; 3896 } 3897 3898 // Mapping for the duplicate initializers check. 3899 // For member initializers, this is keyed with a FieldDecl*. 3900 // For base initializers, this is keyed with a Type*. 3901 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 3902 3903 // Mapping for the inconsistent anonymous-union initializers check. 3904 RedundantUnionMap MemberUnions; 3905 3906 bool HadError = false; 3907 for (unsigned i = 0; i < MemInits.size(); i++) { 3908 CXXCtorInitializer *Init = MemInits[i]; 3909 3910 // Set the source order index. 3911 Init->setSourceOrder(i); 3912 3913 if (Init->isAnyMemberInitializer()) { 3914 const void *Key = GetKeyForMember(Context, Init); 3915 if (CheckRedundantInit(*this, Init, Members[Key]) || 3916 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3917 HadError = true; 3918 } else if (Init->isBaseInitializer()) { 3919 const void *Key = GetKeyForMember(Context, Init); 3920 if (CheckRedundantInit(*this, Init, Members[Key])) 3921 HadError = true; 3922 } else { 3923 assert(Init->isDelegatingInitializer()); 3924 // This must be the only initializer 3925 if (MemInits.size() != 1) { 3926 Diag(Init->getSourceLocation(), 3927 diag::err_delegating_initializer_alone) 3928 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3929 // We will treat this as being the only initializer. 3930 } 3931 SetDelegatingInitializer(Constructor, MemInits[i]); 3932 // Return immediately as the initializer is set. 3933 return; 3934 } 3935 } 3936 3937 if (HadError) 3938 return; 3939 3940 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 3941 3942 SetCtorInitializers(Constructor, AnyErrors, MemInits); 3943 3944 DiagnoseUninitializedFields(*this, Constructor); 3945 } 3946 3947 void 3948 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3949 CXXRecordDecl *ClassDecl) { 3950 // Ignore dependent contexts. Also ignore unions, since their members never 3951 // have destructors implicitly called. 3952 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3953 return; 3954 3955 // FIXME: all the access-control diagnostics are positioned on the 3956 // field/base declaration. That's probably good; that said, the 3957 // user might reasonably want to know why the destructor is being 3958 // emitted, and we currently don't say. 3959 3960 // Non-static data members. 3961 for (auto *Field : ClassDecl->fields()) { 3962 if (Field->isInvalidDecl()) 3963 continue; 3964 3965 // Don't destroy incomplete or zero-length arrays. 3966 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3967 continue; 3968 3969 QualType FieldType = Context.getBaseElementType(Field->getType()); 3970 3971 const RecordType* RT = FieldType->getAs<RecordType>(); 3972 if (!RT) 3973 continue; 3974 3975 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3976 if (FieldClassDecl->isInvalidDecl()) 3977 continue; 3978 if (FieldClassDecl->hasIrrelevantDestructor()) 3979 continue; 3980 // The destructor for an implicit anonymous union member is never invoked. 3981 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3982 continue; 3983 3984 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3985 assert(Dtor && "No dtor found for FieldClassDecl!"); 3986 CheckDestructorAccess(Field->getLocation(), Dtor, 3987 PDiag(diag::err_access_dtor_field) 3988 << Field->getDeclName() 3989 << FieldType); 3990 3991 MarkFunctionReferenced(Location, Dtor); 3992 DiagnoseUseOfDecl(Dtor, Location); 3993 } 3994 3995 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3996 3997 // Bases. 3998 for (const auto &Base : ClassDecl->bases()) { 3999 // Bases are always records in a well-formed non-dependent class. 4000 const RecordType *RT = Base.getType()->getAs<RecordType>(); 4001 4002 // Remember direct virtual bases. 4003 if (Base.isVirtual()) 4004 DirectVirtualBases.insert(RT); 4005 4006 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4007 // If our base class is invalid, we probably can't get its dtor anyway. 4008 if (BaseClassDecl->isInvalidDecl()) 4009 continue; 4010 if (BaseClassDecl->hasIrrelevantDestructor()) 4011 continue; 4012 4013 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4014 assert(Dtor && "No dtor found for BaseClassDecl!"); 4015 4016 // FIXME: caret should be on the start of the class name 4017 CheckDestructorAccess(Base.getLocStart(), Dtor, 4018 PDiag(diag::err_access_dtor_base) 4019 << Base.getType() 4020 << Base.getSourceRange(), 4021 Context.getTypeDeclType(ClassDecl)); 4022 4023 MarkFunctionReferenced(Location, Dtor); 4024 DiagnoseUseOfDecl(Dtor, Location); 4025 } 4026 4027 // Virtual bases. 4028 for (const auto &VBase : ClassDecl->vbases()) { 4029 // Bases are always records in a well-formed non-dependent class. 4030 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4031 4032 // Ignore direct virtual bases. 4033 if (DirectVirtualBases.count(RT)) 4034 continue; 4035 4036 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4037 // If our base class is invalid, we probably can't get its dtor anyway. 4038 if (BaseClassDecl->isInvalidDecl()) 4039 continue; 4040 if (BaseClassDecl->hasIrrelevantDestructor()) 4041 continue; 4042 4043 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4044 assert(Dtor && "No dtor found for BaseClassDecl!"); 4045 if (CheckDestructorAccess( 4046 ClassDecl->getLocation(), Dtor, 4047 PDiag(diag::err_access_dtor_vbase) 4048 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4049 Context.getTypeDeclType(ClassDecl)) == 4050 AR_accessible) { 4051 CheckDerivedToBaseConversion( 4052 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4053 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4054 SourceRange(), DeclarationName(), 0); 4055 } 4056 4057 MarkFunctionReferenced(Location, Dtor); 4058 DiagnoseUseOfDecl(Dtor, Location); 4059 } 4060 } 4061 4062 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4063 if (!CDtorDecl) 4064 return; 4065 4066 if (CXXConstructorDecl *Constructor 4067 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4068 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4069 DiagnoseUninitializedFields(*this, Constructor); 4070 } 4071 } 4072 4073 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4074 unsigned DiagID, AbstractDiagSelID SelID) { 4075 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4076 unsigned DiagID; 4077 AbstractDiagSelID SelID; 4078 4079 public: 4080 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4081 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4082 4083 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4084 if (Suppressed) return; 4085 if (SelID == -1) 4086 S.Diag(Loc, DiagID) << T; 4087 else 4088 S.Diag(Loc, DiagID) << SelID << T; 4089 } 4090 } Diagnoser(DiagID, SelID); 4091 4092 return RequireNonAbstractType(Loc, T, Diagnoser); 4093 } 4094 4095 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4096 TypeDiagnoser &Diagnoser) { 4097 if (!getLangOpts().CPlusPlus) 4098 return false; 4099 4100 if (const ArrayType *AT = Context.getAsArrayType(T)) 4101 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4102 4103 if (const PointerType *PT = T->getAs<PointerType>()) { 4104 // Find the innermost pointer type. 4105 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4106 PT = T; 4107 4108 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4109 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4110 } 4111 4112 const RecordType *RT = T->getAs<RecordType>(); 4113 if (!RT) 4114 return false; 4115 4116 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4117 4118 // We can't answer whether something is abstract until it has a 4119 // definition. If it's currently being defined, we'll walk back 4120 // over all the declarations when we have a full definition. 4121 const CXXRecordDecl *Def = RD->getDefinition(); 4122 if (!Def || Def->isBeingDefined()) 4123 return false; 4124 4125 if (!RD->isAbstract()) 4126 return false; 4127 4128 Diagnoser.diagnose(*this, Loc, T); 4129 DiagnoseAbstractType(RD); 4130 4131 return true; 4132 } 4133 4134 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4135 // Check if we've already emitted the list of pure virtual functions 4136 // for this class. 4137 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4138 return; 4139 4140 // If the diagnostic is suppressed, don't emit the notes. We're only 4141 // going to emit them once, so try to attach them to a diagnostic we're 4142 // actually going to show. 4143 if (Diags.isLastDiagnosticIgnored()) 4144 return; 4145 4146 CXXFinalOverriderMap FinalOverriders; 4147 RD->getFinalOverriders(FinalOverriders); 4148 4149 // Keep a set of seen pure methods so we won't diagnose the same method 4150 // more than once. 4151 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4152 4153 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4154 MEnd = FinalOverriders.end(); 4155 M != MEnd; 4156 ++M) { 4157 for (OverridingMethods::iterator SO = M->second.begin(), 4158 SOEnd = M->second.end(); 4159 SO != SOEnd; ++SO) { 4160 // C++ [class.abstract]p4: 4161 // A class is abstract if it contains or inherits at least one 4162 // pure virtual function for which the final overrider is pure 4163 // virtual. 4164 4165 // 4166 if (SO->second.size() != 1) 4167 continue; 4168 4169 if (!SO->second.front().Method->isPure()) 4170 continue; 4171 4172 if (!SeenPureMethods.insert(SO->second.front().Method)) 4173 continue; 4174 4175 Diag(SO->second.front().Method->getLocation(), 4176 diag::note_pure_virtual_function) 4177 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4178 } 4179 } 4180 4181 if (!PureVirtualClassDiagSet) 4182 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4183 PureVirtualClassDiagSet->insert(RD); 4184 } 4185 4186 namespace { 4187 struct AbstractUsageInfo { 4188 Sema &S; 4189 CXXRecordDecl *Record; 4190 CanQualType AbstractType; 4191 bool Invalid; 4192 4193 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4194 : S(S), Record(Record), 4195 AbstractType(S.Context.getCanonicalType( 4196 S.Context.getTypeDeclType(Record))), 4197 Invalid(false) {} 4198 4199 void DiagnoseAbstractType() { 4200 if (Invalid) return; 4201 S.DiagnoseAbstractType(Record); 4202 Invalid = true; 4203 } 4204 4205 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4206 }; 4207 4208 struct CheckAbstractUsage { 4209 AbstractUsageInfo &Info; 4210 const NamedDecl *Ctx; 4211 4212 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4213 : Info(Info), Ctx(Ctx) {} 4214 4215 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4216 switch (TL.getTypeLocClass()) { 4217 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4218 #define TYPELOC(CLASS, PARENT) \ 4219 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4220 #include "clang/AST/TypeLocNodes.def" 4221 } 4222 } 4223 4224 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4225 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4226 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4227 if (!TL.getParam(I)) 4228 continue; 4229 4230 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4231 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4232 } 4233 } 4234 4235 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4236 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4237 } 4238 4239 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4240 // Visit the type parameters from a permissive context. 4241 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4242 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4243 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4244 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4245 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4246 // TODO: other template argument types? 4247 } 4248 } 4249 4250 // Visit pointee types from a permissive context. 4251 #define CheckPolymorphic(Type) \ 4252 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4253 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4254 } 4255 CheckPolymorphic(PointerTypeLoc) 4256 CheckPolymorphic(ReferenceTypeLoc) 4257 CheckPolymorphic(MemberPointerTypeLoc) 4258 CheckPolymorphic(BlockPointerTypeLoc) 4259 CheckPolymorphic(AtomicTypeLoc) 4260 4261 /// Handle all the types we haven't given a more specific 4262 /// implementation for above. 4263 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4264 // Every other kind of type that we haven't called out already 4265 // that has an inner type is either (1) sugar or (2) contains that 4266 // inner type in some way as a subobject. 4267 if (TypeLoc Next = TL.getNextTypeLoc()) 4268 return Visit(Next, Sel); 4269 4270 // If there's no inner type and we're in a permissive context, 4271 // don't diagnose. 4272 if (Sel == Sema::AbstractNone) return; 4273 4274 // Check whether the type matches the abstract type. 4275 QualType T = TL.getType(); 4276 if (T->isArrayType()) { 4277 Sel = Sema::AbstractArrayType; 4278 T = Info.S.Context.getBaseElementType(T); 4279 } 4280 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4281 if (CT != Info.AbstractType) return; 4282 4283 // It matched; do some magic. 4284 if (Sel == Sema::AbstractArrayType) { 4285 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4286 << T << TL.getSourceRange(); 4287 } else { 4288 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4289 << Sel << T << TL.getSourceRange(); 4290 } 4291 Info.DiagnoseAbstractType(); 4292 } 4293 }; 4294 4295 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4296 Sema::AbstractDiagSelID Sel) { 4297 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4298 } 4299 4300 } 4301 4302 /// Check for invalid uses of an abstract type in a method declaration. 4303 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4304 CXXMethodDecl *MD) { 4305 // No need to do the check on definitions, which require that 4306 // the return/param types be complete. 4307 if (MD->doesThisDeclarationHaveABody()) 4308 return; 4309 4310 // For safety's sake, just ignore it if we don't have type source 4311 // information. This should never happen for non-implicit methods, 4312 // but... 4313 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4314 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4315 } 4316 4317 /// Check for invalid uses of an abstract type within a class definition. 4318 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4319 CXXRecordDecl *RD) { 4320 for (auto *D : RD->decls()) { 4321 if (D->isImplicit()) continue; 4322 4323 // Methods and method templates. 4324 if (isa<CXXMethodDecl>(D)) { 4325 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4326 } else if (isa<FunctionTemplateDecl>(D)) { 4327 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4328 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4329 4330 // Fields and static variables. 4331 } else if (isa<FieldDecl>(D)) { 4332 FieldDecl *FD = cast<FieldDecl>(D); 4333 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4334 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4335 } else if (isa<VarDecl>(D)) { 4336 VarDecl *VD = cast<VarDecl>(D); 4337 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4338 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4339 4340 // Nested classes and class templates. 4341 } else if (isa<CXXRecordDecl>(D)) { 4342 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4343 } else if (isa<ClassTemplateDecl>(D)) { 4344 CheckAbstractClassUsage(Info, 4345 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4346 } 4347 } 4348 } 4349 4350 /// \brief Perform semantic checks on a class definition that has been 4351 /// completing, introducing implicitly-declared members, checking for 4352 /// abstract types, etc. 4353 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4354 if (!Record) 4355 return; 4356 4357 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4358 AbstractUsageInfo Info(*this, Record); 4359 CheckAbstractClassUsage(Info, Record); 4360 } 4361 4362 // If this is not an aggregate type and has no user-declared constructor, 4363 // complain about any non-static data members of reference or const scalar 4364 // type, since they will never get initializers. 4365 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4366 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4367 !Record->isLambda()) { 4368 bool Complained = false; 4369 for (const auto *F : Record->fields()) { 4370 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4371 continue; 4372 4373 if (F->getType()->isReferenceType() || 4374 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4375 if (!Complained) { 4376 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4377 << Record->getTagKind() << Record; 4378 Complained = true; 4379 } 4380 4381 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4382 << F->getType()->isReferenceType() 4383 << F->getDeclName(); 4384 } 4385 } 4386 } 4387 4388 if (Record->isDynamicClass() && !Record->isDependentType()) 4389 DynamicClasses.push_back(Record); 4390 4391 if (Record->getIdentifier()) { 4392 // C++ [class.mem]p13: 4393 // If T is the name of a class, then each of the following shall have a 4394 // name different from T: 4395 // - every member of every anonymous union that is a member of class T. 4396 // 4397 // C++ [class.mem]p14: 4398 // In addition, if class T has a user-declared constructor (12.1), every 4399 // non-static data member of class T shall have a name different from T. 4400 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4401 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4402 ++I) { 4403 NamedDecl *D = *I; 4404 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4405 isa<IndirectFieldDecl>(D)) { 4406 Diag(D->getLocation(), diag::err_member_name_of_class) 4407 << D->getDeclName(); 4408 break; 4409 } 4410 } 4411 } 4412 4413 // Warn if the class has virtual methods but non-virtual public destructor. 4414 if (Record->isPolymorphic() && !Record->isDependentType()) { 4415 CXXDestructorDecl *dtor = Record->getDestructor(); 4416 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 4417 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4418 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4419 } 4420 4421 if (Record->isAbstract()) { 4422 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4423 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4424 << FA->isSpelledAsSealed(); 4425 DiagnoseAbstractType(Record); 4426 } 4427 } 4428 4429 if (!Record->isDependentType()) { 4430 for (auto *M : Record->methods()) { 4431 // See if a method overloads virtual methods in a base 4432 // class without overriding any. 4433 if (!M->isStatic()) 4434 DiagnoseHiddenVirtualMethods(M); 4435 4436 // Check whether the explicitly-defaulted special members are valid. 4437 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4438 CheckExplicitlyDefaultedSpecialMember(M); 4439 4440 // For an explicitly defaulted or deleted special member, we defer 4441 // determining triviality until the class is complete. That time is now! 4442 if (!M->isImplicit() && !M->isUserProvided()) { 4443 CXXSpecialMember CSM = getSpecialMember(M); 4444 if (CSM != CXXInvalid) { 4445 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 4446 4447 // Inform the class that we've finished declaring this member. 4448 Record->finishedDefaultedOrDeletedMember(M); 4449 } 4450 } 4451 } 4452 } 4453 4454 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4455 // function that is not a constructor declares that member function to be 4456 // const. [...] The class of which that function is a member shall be 4457 // a literal type. 4458 // 4459 // If the class has virtual bases, any constexpr members will already have 4460 // been diagnosed by the checks performed on the member declaration, so 4461 // suppress this (less useful) diagnostic. 4462 // 4463 // We delay this until we know whether an explicitly-defaulted (or deleted) 4464 // destructor for the class is trivial. 4465 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4466 !Record->isLiteral() && !Record->getNumVBases()) { 4467 for (const auto *M : Record->methods()) { 4468 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) { 4469 switch (Record->getTemplateSpecializationKind()) { 4470 case TSK_ImplicitInstantiation: 4471 case TSK_ExplicitInstantiationDeclaration: 4472 case TSK_ExplicitInstantiationDefinition: 4473 // If a template instantiates to a non-literal type, but its members 4474 // instantiate to constexpr functions, the template is technically 4475 // ill-formed, but we allow it for sanity. 4476 continue; 4477 4478 case TSK_Undeclared: 4479 case TSK_ExplicitSpecialization: 4480 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4481 diag::err_constexpr_method_non_literal); 4482 break; 4483 } 4484 4485 // Only produce one error per class. 4486 break; 4487 } 4488 } 4489 } 4490 4491 // ms_struct is a request to use the same ABI rules as MSVC. Check 4492 // whether this class uses any C++ features that are implemented 4493 // completely differently in MSVC, and if so, emit a diagnostic. 4494 // That diagnostic defaults to an error, but we allow projects to 4495 // map it down to a warning (or ignore it). It's a fairly common 4496 // practice among users of the ms_struct pragma to mass-annotate 4497 // headers, sweeping up a bunch of types that the project doesn't 4498 // really rely on MSVC-compatible layout for. We must therefore 4499 // support "ms_struct except for C++ stuff" as a secondary ABI. 4500 if (Record->isMsStruct(Context) && 4501 (Record->isPolymorphic() || Record->getNumBases())) { 4502 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 4503 } 4504 4505 // Declare inheriting constructors. We do this eagerly here because: 4506 // - The standard requires an eager diagnostic for conflicting inheriting 4507 // constructors from different classes. 4508 // - The lazy declaration of the other implicit constructors is so as to not 4509 // waste space and performance on classes that are not meant to be 4510 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4511 // have inheriting constructors. 4512 DeclareInheritingConstructors(Record); 4513 } 4514 4515 /// Look up the special member function that would be called by a special 4516 /// member function for a subobject of class type. 4517 /// 4518 /// \param Class The class type of the subobject. 4519 /// \param CSM The kind of special member function. 4520 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 4521 /// \param ConstRHS True if this is a copy operation with a const object 4522 /// on its RHS, that is, if the argument to the outer special member 4523 /// function is 'const' and this is not a field marked 'mutable'. 4524 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 4525 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 4526 unsigned FieldQuals, bool ConstRHS) { 4527 unsigned LHSQuals = 0; 4528 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 4529 LHSQuals = FieldQuals; 4530 4531 unsigned RHSQuals = FieldQuals; 4532 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4533 RHSQuals = 0; 4534 else if (ConstRHS) 4535 RHSQuals |= Qualifiers::Const; 4536 4537 return S.LookupSpecialMember(Class, CSM, 4538 RHSQuals & Qualifiers::Const, 4539 RHSQuals & Qualifiers::Volatile, 4540 false, 4541 LHSQuals & Qualifiers::Const, 4542 LHSQuals & Qualifiers::Volatile); 4543 } 4544 4545 /// Is the special member function which would be selected to perform the 4546 /// specified operation on the specified class type a constexpr constructor? 4547 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4548 Sema::CXXSpecialMember CSM, 4549 unsigned Quals, bool ConstRHS) { 4550 Sema::SpecialMemberOverloadResult *SMOR = 4551 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 4552 if (!SMOR || !SMOR->getMethod()) 4553 // A constructor we wouldn't select can't be "involved in initializing" 4554 // anything. 4555 return true; 4556 return SMOR->getMethod()->isConstexpr(); 4557 } 4558 4559 /// Determine whether the specified special member function would be constexpr 4560 /// if it were implicitly defined. 4561 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4562 Sema::CXXSpecialMember CSM, 4563 bool ConstArg) { 4564 if (!S.getLangOpts().CPlusPlus11) 4565 return false; 4566 4567 // C++11 [dcl.constexpr]p4: 4568 // In the definition of a constexpr constructor [...] 4569 bool Ctor = true; 4570 switch (CSM) { 4571 case Sema::CXXDefaultConstructor: 4572 // Since default constructor lookup is essentially trivial (and cannot 4573 // involve, for instance, template instantiation), we compute whether a 4574 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4575 // 4576 // This is important for performance; we need to know whether the default 4577 // constructor is constexpr to determine whether the type is a literal type. 4578 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4579 4580 case Sema::CXXCopyConstructor: 4581 case Sema::CXXMoveConstructor: 4582 // For copy or move constructors, we need to perform overload resolution. 4583 break; 4584 4585 case Sema::CXXCopyAssignment: 4586 case Sema::CXXMoveAssignment: 4587 if (!S.getLangOpts().CPlusPlus1y) 4588 return false; 4589 // In C++1y, we need to perform overload resolution. 4590 Ctor = false; 4591 break; 4592 4593 case Sema::CXXDestructor: 4594 case Sema::CXXInvalid: 4595 return false; 4596 } 4597 4598 // -- if the class is a non-empty union, or for each non-empty anonymous 4599 // union member of a non-union class, exactly one non-static data member 4600 // shall be initialized; [DR1359] 4601 // 4602 // If we squint, this is guaranteed, since exactly one non-static data member 4603 // will be initialized (if the constructor isn't deleted), we just don't know 4604 // which one. 4605 if (Ctor && ClassDecl->isUnion()) 4606 return true; 4607 4608 // -- the class shall not have any virtual base classes; 4609 if (Ctor && ClassDecl->getNumVBases()) 4610 return false; 4611 4612 // C++1y [class.copy]p26: 4613 // -- [the class] is a literal type, and 4614 if (!Ctor && !ClassDecl->isLiteral()) 4615 return false; 4616 4617 // -- every constructor involved in initializing [...] base class 4618 // sub-objects shall be a constexpr constructor; 4619 // -- the assignment operator selected to copy/move each direct base 4620 // class is a constexpr function, and 4621 for (const auto &B : ClassDecl->bases()) { 4622 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 4623 if (!BaseType) continue; 4624 4625 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4626 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 4627 return false; 4628 } 4629 4630 // -- every constructor involved in initializing non-static data members 4631 // [...] shall be a constexpr constructor; 4632 // -- every non-static data member and base class sub-object shall be 4633 // initialized 4634 // -- for each non-static data member of X that is of class type (or array 4635 // thereof), the assignment operator selected to copy/move that member is 4636 // a constexpr function 4637 for (const auto *F : ClassDecl->fields()) { 4638 if (F->isInvalidDecl()) 4639 continue; 4640 QualType BaseType = S.Context.getBaseElementType(F->getType()); 4641 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 4642 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4643 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 4644 BaseType.getCVRQualifiers(), 4645 ConstArg && !F->isMutable())) 4646 return false; 4647 } 4648 } 4649 4650 // All OK, it's constexpr! 4651 return true; 4652 } 4653 4654 static Sema::ImplicitExceptionSpecification 4655 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4656 switch (S.getSpecialMember(MD)) { 4657 case Sema::CXXDefaultConstructor: 4658 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4659 case Sema::CXXCopyConstructor: 4660 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4661 case Sema::CXXCopyAssignment: 4662 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4663 case Sema::CXXMoveConstructor: 4664 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4665 case Sema::CXXMoveAssignment: 4666 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4667 case Sema::CXXDestructor: 4668 return S.ComputeDefaultedDtorExceptionSpec(MD); 4669 case Sema::CXXInvalid: 4670 break; 4671 } 4672 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4673 "only special members have implicit exception specs"); 4674 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4675 } 4676 4677 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 4678 CXXMethodDecl *MD) { 4679 FunctionProtoType::ExtProtoInfo EPI; 4680 4681 // Build an exception specification pointing back at this member. 4682 EPI.ExceptionSpecType = EST_Unevaluated; 4683 EPI.ExceptionSpecDecl = MD; 4684 4685 // Set the calling convention to the default for C++ instance methods. 4686 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 4687 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4688 /*IsCXXMethod=*/true)); 4689 return EPI; 4690 } 4691 4692 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4693 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4694 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4695 return; 4696 4697 // Evaluate the exception specification. 4698 ImplicitExceptionSpecification ExceptSpec = 4699 computeImplicitExceptionSpec(*this, Loc, MD); 4700 4701 FunctionProtoType::ExtProtoInfo EPI; 4702 ExceptSpec.getEPI(EPI); 4703 4704 // Update the type of the special member to use it. 4705 UpdateExceptionSpec(MD, EPI); 4706 4707 // A user-provided destructor can be defined outside the class. When that 4708 // happens, be sure to update the exception specification on both 4709 // declarations. 4710 const FunctionProtoType *CanonicalFPT = 4711 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4712 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4713 UpdateExceptionSpec(MD->getCanonicalDecl(), EPI); 4714 } 4715 4716 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4717 CXXRecordDecl *RD = MD->getParent(); 4718 CXXSpecialMember CSM = getSpecialMember(MD); 4719 4720 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4721 "not an explicitly-defaulted special member"); 4722 4723 // Whether this was the first-declared instance of the constructor. 4724 // This affects whether we implicitly add an exception spec and constexpr. 4725 bool First = MD == MD->getCanonicalDecl(); 4726 4727 bool HadError = false; 4728 4729 // C++11 [dcl.fct.def.default]p1: 4730 // A function that is explicitly defaulted shall 4731 // -- be a special member function (checked elsewhere), 4732 // -- have the same type (except for ref-qualifiers, and except that a 4733 // copy operation can take a non-const reference) as an implicit 4734 // declaration, and 4735 // -- not have default arguments. 4736 unsigned ExpectedParams = 1; 4737 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4738 ExpectedParams = 0; 4739 if (MD->getNumParams() != ExpectedParams) { 4740 // This also checks for default arguments: a copy or move constructor with a 4741 // default argument is classified as a default constructor, and assignment 4742 // operations and destructors can't have default arguments. 4743 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4744 << CSM << MD->getSourceRange(); 4745 HadError = true; 4746 } else if (MD->isVariadic()) { 4747 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4748 << CSM << MD->getSourceRange(); 4749 HadError = true; 4750 } 4751 4752 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4753 4754 bool CanHaveConstParam = false; 4755 if (CSM == CXXCopyConstructor) 4756 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4757 else if (CSM == CXXCopyAssignment) 4758 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4759 4760 QualType ReturnType = Context.VoidTy; 4761 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4762 // Check for return type matching. 4763 ReturnType = Type->getReturnType(); 4764 QualType ExpectedReturnType = 4765 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4766 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4767 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4768 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4769 HadError = true; 4770 } 4771 4772 // A defaulted special member cannot have cv-qualifiers. 4773 if (Type->getTypeQuals()) { 4774 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4775 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y; 4776 HadError = true; 4777 } 4778 } 4779 4780 // Check for parameter type matching. 4781 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 4782 bool HasConstParam = false; 4783 if (ExpectedParams && ArgType->isReferenceType()) { 4784 // Argument must be reference to possibly-const T. 4785 QualType ReferentType = ArgType->getPointeeType(); 4786 HasConstParam = ReferentType.isConstQualified(); 4787 4788 if (ReferentType.isVolatileQualified()) { 4789 Diag(MD->getLocation(), 4790 diag::err_defaulted_special_member_volatile_param) << CSM; 4791 HadError = true; 4792 } 4793 4794 if (HasConstParam && !CanHaveConstParam) { 4795 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4796 Diag(MD->getLocation(), 4797 diag::err_defaulted_special_member_copy_const_param) 4798 << (CSM == CXXCopyAssignment); 4799 // FIXME: Explain why this special member can't be const. 4800 } else { 4801 Diag(MD->getLocation(), 4802 diag::err_defaulted_special_member_move_const_param) 4803 << (CSM == CXXMoveAssignment); 4804 } 4805 HadError = true; 4806 } 4807 } else if (ExpectedParams) { 4808 // A copy assignment operator can take its argument by value, but a 4809 // defaulted one cannot. 4810 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4811 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4812 HadError = true; 4813 } 4814 4815 // C++11 [dcl.fct.def.default]p2: 4816 // An explicitly-defaulted function may be declared constexpr only if it 4817 // would have been implicitly declared as constexpr, 4818 // Do not apply this rule to members of class templates, since core issue 1358 4819 // makes such functions always instantiate to constexpr functions. For 4820 // functions which cannot be constexpr (for non-constructors in C++11 and for 4821 // destructors in C++1y), this is checked elsewhere. 4822 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4823 HasConstParam); 4824 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD) 4825 : isa<CXXConstructorDecl>(MD)) && 4826 MD->isConstexpr() && !Constexpr && 4827 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4828 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4829 // FIXME: Explain why the special member can't be constexpr. 4830 HadError = true; 4831 } 4832 4833 // and may have an explicit exception-specification only if it is compatible 4834 // with the exception-specification on the implicit declaration. 4835 if (Type->hasExceptionSpec()) { 4836 // Delay the check if this is the first declaration of the special member, 4837 // since we may not have parsed some necessary in-class initializers yet. 4838 if (First) { 4839 // If the exception specification needs to be instantiated, do so now, 4840 // before we clobber it with an EST_Unevaluated specification below. 4841 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4842 InstantiateExceptionSpec(MD->getLocStart(), MD); 4843 Type = MD->getType()->getAs<FunctionProtoType>(); 4844 } 4845 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4846 } else 4847 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4848 } 4849 4850 // If a function is explicitly defaulted on its first declaration, 4851 if (First) { 4852 // -- it is implicitly considered to be constexpr if the implicit 4853 // definition would be, 4854 MD->setConstexpr(Constexpr); 4855 4856 // -- it is implicitly considered to have the same exception-specification 4857 // as if it had been implicitly declared, 4858 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4859 EPI.ExceptionSpecType = EST_Unevaluated; 4860 EPI.ExceptionSpecDecl = MD; 4861 MD->setType(Context.getFunctionType(ReturnType, 4862 ArrayRef<QualType>(&ArgType, 4863 ExpectedParams), 4864 EPI)); 4865 } 4866 4867 if (ShouldDeleteSpecialMember(MD, CSM)) { 4868 if (First) { 4869 SetDeclDeleted(MD, MD->getLocation()); 4870 } else { 4871 // C++11 [dcl.fct.def.default]p4: 4872 // [For a] user-provided explicitly-defaulted function [...] if such a 4873 // function is implicitly defined as deleted, the program is ill-formed. 4874 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4875 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 4876 HadError = true; 4877 } 4878 } 4879 4880 if (HadError) 4881 MD->setInvalidDecl(); 4882 } 4883 4884 /// Check whether the exception specification provided for an 4885 /// explicitly-defaulted special member matches the exception specification 4886 /// that would have been generated for an implicit special member, per 4887 /// C++11 [dcl.fct.def.default]p2. 4888 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 4889 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 4890 // Compute the implicit exception specification. 4891 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4892 /*IsCXXMethod=*/true); 4893 FunctionProtoType::ExtProtoInfo EPI(CC); 4894 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4895 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 4896 Context.getFunctionType(Context.VoidTy, None, EPI)); 4897 4898 // Ensure that it matches. 4899 CheckEquivalentExceptionSpec( 4900 PDiag(diag::err_incorrect_defaulted_exception_spec) 4901 << getSpecialMember(MD), PDiag(), 4902 ImplicitType, SourceLocation(), 4903 SpecifiedType, MD->getLocation()); 4904 } 4905 4906 void Sema::CheckDelayedMemberExceptionSpecs() { 4907 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>, 4908 2> Checks; 4909 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs; 4910 4911 std::swap(Checks, DelayedDestructorExceptionSpecChecks); 4912 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 4913 4914 // Perform any deferred checking of exception specifications for virtual 4915 // destructors. 4916 for (unsigned i = 0, e = Checks.size(); i != e; ++i) { 4917 const CXXDestructorDecl *Dtor = Checks[i].first; 4918 assert(!Dtor->getParent()->isDependentType() && 4919 "Should not ever add destructors of templates into the list."); 4920 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second); 4921 } 4922 4923 // Check that any explicitly-defaulted methods have exception specifications 4924 // compatible with their implicit exception specifications. 4925 for (unsigned I = 0, N = Specs.size(); I != N; ++I) 4926 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first, 4927 Specs[I].second); 4928 } 4929 4930 namespace { 4931 struct SpecialMemberDeletionInfo { 4932 Sema &S; 4933 CXXMethodDecl *MD; 4934 Sema::CXXSpecialMember CSM; 4935 bool Diagnose; 4936 4937 // Properties of the special member, computed for convenience. 4938 bool IsConstructor, IsAssignment, IsMove, ConstArg; 4939 SourceLocation Loc; 4940 4941 bool AllFieldsAreConst; 4942 4943 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4944 Sema::CXXSpecialMember CSM, bool Diagnose) 4945 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4946 IsConstructor(false), IsAssignment(false), IsMove(false), 4947 ConstArg(false), Loc(MD->getLocation()), 4948 AllFieldsAreConst(true) { 4949 switch (CSM) { 4950 case Sema::CXXDefaultConstructor: 4951 case Sema::CXXCopyConstructor: 4952 IsConstructor = true; 4953 break; 4954 case Sema::CXXMoveConstructor: 4955 IsConstructor = true; 4956 IsMove = true; 4957 break; 4958 case Sema::CXXCopyAssignment: 4959 IsAssignment = true; 4960 break; 4961 case Sema::CXXMoveAssignment: 4962 IsAssignment = true; 4963 IsMove = true; 4964 break; 4965 case Sema::CXXDestructor: 4966 break; 4967 case Sema::CXXInvalid: 4968 llvm_unreachable("invalid special member kind"); 4969 } 4970 4971 if (MD->getNumParams()) { 4972 if (const ReferenceType *RT = 4973 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 4974 ConstArg = RT->getPointeeType().isConstQualified(); 4975 } 4976 } 4977 4978 bool inUnion() const { return MD->getParent()->isUnion(); } 4979 4980 /// Look up the corresponding special member in the given class. 4981 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4982 unsigned Quals, bool IsMutable) { 4983 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 4984 ConstArg && !IsMutable); 4985 } 4986 4987 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4988 4989 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4990 bool shouldDeleteForField(FieldDecl *FD); 4991 bool shouldDeleteForAllConstMembers(); 4992 4993 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4994 unsigned Quals); 4995 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4996 Sema::SpecialMemberOverloadResult *SMOR, 4997 bool IsDtorCallInCtor); 4998 4999 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 5000 }; 5001 } 5002 5003 /// Is the given special member inaccessible when used on the given 5004 /// sub-object. 5005 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 5006 CXXMethodDecl *target) { 5007 /// If we're operating on a base class, the object type is the 5008 /// type of this special member. 5009 QualType objectTy; 5010 AccessSpecifier access = target->getAccess(); 5011 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5012 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5013 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5014 5015 // If we're operating on a field, the object type is the type of the field. 5016 } else { 5017 objectTy = S.Context.getTypeDeclType(target->getParent()); 5018 } 5019 5020 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5021 } 5022 5023 /// Check whether we should delete a special member due to the implicit 5024 /// definition containing a call to a special member of a subobject. 5025 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5026 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5027 bool IsDtorCallInCtor) { 5028 CXXMethodDecl *Decl = SMOR->getMethod(); 5029 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5030 5031 int DiagKind = -1; 5032 5033 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5034 DiagKind = !Decl ? 0 : 1; 5035 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5036 DiagKind = 2; 5037 else if (!isAccessible(Subobj, Decl)) 5038 DiagKind = 3; 5039 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5040 !Decl->isTrivial()) { 5041 // A member of a union must have a trivial corresponding special member. 5042 // As a weird special case, a destructor call from a union's constructor 5043 // must be accessible and non-deleted, but need not be trivial. Such a 5044 // destructor is never actually called, but is semantically checked as 5045 // if it were. 5046 DiagKind = 4; 5047 } 5048 5049 if (DiagKind == -1) 5050 return false; 5051 5052 if (Diagnose) { 5053 if (Field) { 5054 S.Diag(Field->getLocation(), 5055 diag::note_deleted_special_member_class_subobject) 5056 << CSM << MD->getParent() << /*IsField*/true 5057 << Field << DiagKind << IsDtorCallInCtor; 5058 } else { 5059 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5060 S.Diag(Base->getLocStart(), 5061 diag::note_deleted_special_member_class_subobject) 5062 << CSM << MD->getParent() << /*IsField*/false 5063 << Base->getType() << DiagKind << IsDtorCallInCtor; 5064 } 5065 5066 if (DiagKind == 1) 5067 S.NoteDeletedFunction(Decl); 5068 // FIXME: Explain inaccessibility if DiagKind == 3. 5069 } 5070 5071 return true; 5072 } 5073 5074 /// Check whether we should delete a special member function due to having a 5075 /// direct or virtual base class or non-static data member of class type M. 5076 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5077 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5078 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5079 bool IsMutable = Field && Field->isMutable(); 5080 5081 // C++11 [class.ctor]p5: 5082 // -- any direct or virtual base class, or non-static data member with no 5083 // brace-or-equal-initializer, has class type M (or array thereof) and 5084 // either M has no default constructor or overload resolution as applied 5085 // to M's default constructor results in an ambiguity or in a function 5086 // that is deleted or inaccessible 5087 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5088 // -- a direct or virtual base class B that cannot be copied/moved because 5089 // overload resolution, as applied to B's corresponding special member, 5090 // results in an ambiguity or a function that is deleted or inaccessible 5091 // from the defaulted special member 5092 // C++11 [class.dtor]p5: 5093 // -- any direct or virtual base class [...] has a type with a destructor 5094 // that is deleted or inaccessible 5095 if (!(CSM == Sema::CXXDefaultConstructor && 5096 Field && Field->hasInClassInitializer()) && 5097 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5098 false)) 5099 return true; 5100 5101 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5102 // -- any direct or virtual base class or non-static data member has a 5103 // type with a destructor that is deleted or inaccessible 5104 if (IsConstructor) { 5105 Sema::SpecialMemberOverloadResult *SMOR = 5106 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5107 false, false, false, false, false); 5108 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5109 return true; 5110 } 5111 5112 return false; 5113 } 5114 5115 /// Check whether we should delete a special member function due to the class 5116 /// having a particular direct or virtual base class. 5117 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5118 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5119 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5120 } 5121 5122 /// Check whether we should delete a special member function due to the class 5123 /// having a particular non-static data member. 5124 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5125 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5126 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5127 5128 if (CSM == Sema::CXXDefaultConstructor) { 5129 // For a default constructor, all references must be initialized in-class 5130 // and, if a union, it must have a non-const member. 5131 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5132 if (Diagnose) 5133 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5134 << MD->getParent() << FD << FieldType << /*Reference*/0; 5135 return true; 5136 } 5137 // C++11 [class.ctor]p5: any non-variant non-static data member of 5138 // const-qualified type (or array thereof) with no 5139 // brace-or-equal-initializer does not have a user-provided default 5140 // constructor. 5141 if (!inUnion() && FieldType.isConstQualified() && 5142 !FD->hasInClassInitializer() && 5143 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5144 if (Diagnose) 5145 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5146 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5147 return true; 5148 } 5149 5150 if (inUnion() && !FieldType.isConstQualified()) 5151 AllFieldsAreConst = false; 5152 } else if (CSM == Sema::CXXCopyConstructor) { 5153 // For a copy constructor, data members must not be of rvalue reference 5154 // type. 5155 if (FieldType->isRValueReferenceType()) { 5156 if (Diagnose) 5157 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5158 << MD->getParent() << FD << FieldType; 5159 return true; 5160 } 5161 } else if (IsAssignment) { 5162 // For an assignment operator, data members must not be of reference type. 5163 if (FieldType->isReferenceType()) { 5164 if (Diagnose) 5165 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5166 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5167 return true; 5168 } 5169 if (!FieldRecord && FieldType.isConstQualified()) { 5170 // C++11 [class.copy]p23: 5171 // -- a non-static data member of const non-class type (or array thereof) 5172 if (Diagnose) 5173 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5174 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5175 return true; 5176 } 5177 } 5178 5179 if (FieldRecord) { 5180 // Some additional restrictions exist on the variant members. 5181 if (!inUnion() && FieldRecord->isUnion() && 5182 FieldRecord->isAnonymousStructOrUnion()) { 5183 bool AllVariantFieldsAreConst = true; 5184 5185 // FIXME: Handle anonymous unions declared within anonymous unions. 5186 for (auto *UI : FieldRecord->fields()) { 5187 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5188 5189 if (!UnionFieldType.isConstQualified()) 5190 AllVariantFieldsAreConst = false; 5191 5192 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5193 if (UnionFieldRecord && 5194 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5195 UnionFieldType.getCVRQualifiers())) 5196 return true; 5197 } 5198 5199 // At least one member in each anonymous union must be non-const 5200 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5201 !FieldRecord->field_empty()) { 5202 if (Diagnose) 5203 S.Diag(FieldRecord->getLocation(), 5204 diag::note_deleted_default_ctor_all_const) 5205 << MD->getParent() << /*anonymous union*/1; 5206 return true; 5207 } 5208 5209 // Don't check the implicit member of the anonymous union type. 5210 // This is technically non-conformant, but sanity demands it. 5211 return false; 5212 } 5213 5214 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5215 FieldType.getCVRQualifiers())) 5216 return true; 5217 } 5218 5219 return false; 5220 } 5221 5222 /// C++11 [class.ctor] p5: 5223 /// A defaulted default constructor for a class X is defined as deleted if 5224 /// X is a union and all of its variant members are of const-qualified type. 5225 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5226 // This is a silly definition, because it gives an empty union a deleted 5227 // default constructor. Don't do that. 5228 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5229 !MD->getParent()->field_empty()) { 5230 if (Diagnose) 5231 S.Diag(MD->getParent()->getLocation(), 5232 diag::note_deleted_default_ctor_all_const) 5233 << MD->getParent() << /*not anonymous union*/0; 5234 return true; 5235 } 5236 return false; 5237 } 5238 5239 /// Determine whether a defaulted special member function should be defined as 5240 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5241 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5242 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5243 bool Diagnose) { 5244 if (MD->isInvalidDecl()) 5245 return false; 5246 CXXRecordDecl *RD = MD->getParent(); 5247 assert(!RD->isDependentType() && "do deletion after instantiation"); 5248 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5249 return false; 5250 5251 // C++11 [expr.lambda.prim]p19: 5252 // The closure type associated with a lambda-expression has a 5253 // deleted (8.4.3) default constructor and a deleted copy 5254 // assignment operator. 5255 if (RD->isLambda() && 5256 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5257 if (Diagnose) 5258 Diag(RD->getLocation(), diag::note_lambda_decl); 5259 return true; 5260 } 5261 5262 // For an anonymous struct or union, the copy and assignment special members 5263 // will never be used, so skip the check. For an anonymous union declared at 5264 // namespace scope, the constructor and destructor are used. 5265 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5266 RD->isAnonymousStructOrUnion()) 5267 return false; 5268 5269 // C++11 [class.copy]p7, p18: 5270 // If the class definition declares a move constructor or move assignment 5271 // operator, an implicitly declared copy constructor or copy assignment 5272 // operator is defined as deleted. 5273 if (MD->isImplicit() && 5274 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5275 CXXMethodDecl *UserDeclaredMove = 0; 5276 5277 // In Microsoft mode, a user-declared move only causes the deletion of the 5278 // corresponding copy operation, not both copy operations. 5279 if (RD->hasUserDeclaredMoveConstructor() && 5280 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5281 if (!Diagnose) return true; 5282 5283 // Find any user-declared move constructor. 5284 for (auto *I : RD->ctors()) { 5285 if (I->isMoveConstructor()) { 5286 UserDeclaredMove = I; 5287 break; 5288 } 5289 } 5290 assert(UserDeclaredMove); 5291 } else if (RD->hasUserDeclaredMoveAssignment() && 5292 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5293 if (!Diagnose) return true; 5294 5295 // Find any user-declared move assignment operator. 5296 for (auto *I : RD->methods()) { 5297 if (I->isMoveAssignmentOperator()) { 5298 UserDeclaredMove = I; 5299 break; 5300 } 5301 } 5302 assert(UserDeclaredMove); 5303 } 5304 5305 if (UserDeclaredMove) { 5306 Diag(UserDeclaredMove->getLocation(), 5307 diag::note_deleted_copy_user_declared_move) 5308 << (CSM == CXXCopyAssignment) << RD 5309 << UserDeclaredMove->isMoveAssignmentOperator(); 5310 return true; 5311 } 5312 } 5313 5314 // Do access control from the special member function 5315 ContextRAII MethodContext(*this, MD); 5316 5317 // C++11 [class.dtor]p5: 5318 // -- for a virtual destructor, lookup of the non-array deallocation function 5319 // results in an ambiguity or in a function that is deleted or inaccessible 5320 if (CSM == CXXDestructor && MD->isVirtual()) { 5321 FunctionDecl *OperatorDelete = 0; 5322 DeclarationName Name = 5323 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5324 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5325 OperatorDelete, false)) { 5326 if (Diagnose) 5327 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5328 return true; 5329 } 5330 } 5331 5332 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5333 5334 for (auto &BI : RD->bases()) 5335 if (!BI.isVirtual() && 5336 SMI.shouldDeleteForBase(&BI)) 5337 return true; 5338 5339 // Per DR1611, do not consider virtual bases of constructors of abstract 5340 // classes, since we are not going to construct them. 5341 if (!RD->isAbstract() || !SMI.IsConstructor) { 5342 for (auto &BI : RD->vbases()) 5343 if (SMI.shouldDeleteForBase(&BI)) 5344 return true; 5345 } 5346 5347 for (auto *FI : RD->fields()) 5348 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5349 SMI.shouldDeleteForField(FI)) 5350 return true; 5351 5352 if (SMI.shouldDeleteForAllConstMembers()) 5353 return true; 5354 5355 return false; 5356 } 5357 5358 /// Perform lookup for a special member of the specified kind, and determine 5359 /// whether it is trivial. If the triviality can be determined without the 5360 /// lookup, skip it. This is intended for use when determining whether a 5361 /// special member of a containing object is trivial, and thus does not ever 5362 /// perform overload resolution for default constructors. 5363 /// 5364 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5365 /// member that was most likely to be intended to be trivial, if any. 5366 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5367 Sema::CXXSpecialMember CSM, unsigned Quals, 5368 bool ConstRHS, CXXMethodDecl **Selected) { 5369 if (Selected) 5370 *Selected = 0; 5371 5372 switch (CSM) { 5373 case Sema::CXXInvalid: 5374 llvm_unreachable("not a special member"); 5375 5376 case Sema::CXXDefaultConstructor: 5377 // C++11 [class.ctor]p5: 5378 // A default constructor is trivial if: 5379 // - all the [direct subobjects] have trivial default constructors 5380 // 5381 // Note, no overload resolution is performed in this case. 5382 if (RD->hasTrivialDefaultConstructor()) 5383 return true; 5384 5385 if (Selected) { 5386 // If there's a default constructor which could have been trivial, dig it 5387 // out. Otherwise, if there's any user-provided default constructor, point 5388 // to that as an example of why there's not a trivial one. 5389 CXXConstructorDecl *DefCtor = 0; 5390 if (RD->needsImplicitDefaultConstructor()) 5391 S.DeclareImplicitDefaultConstructor(RD); 5392 for (auto *CI : RD->ctors()) { 5393 if (!CI->isDefaultConstructor()) 5394 continue; 5395 DefCtor = CI; 5396 if (!DefCtor->isUserProvided()) 5397 break; 5398 } 5399 5400 *Selected = DefCtor; 5401 } 5402 5403 return false; 5404 5405 case Sema::CXXDestructor: 5406 // C++11 [class.dtor]p5: 5407 // A destructor is trivial if: 5408 // - all the direct [subobjects] have trivial destructors 5409 if (RD->hasTrivialDestructor()) 5410 return true; 5411 5412 if (Selected) { 5413 if (RD->needsImplicitDestructor()) 5414 S.DeclareImplicitDestructor(RD); 5415 *Selected = RD->getDestructor(); 5416 } 5417 5418 return false; 5419 5420 case Sema::CXXCopyConstructor: 5421 // C++11 [class.copy]p12: 5422 // A copy constructor is trivial if: 5423 // - the constructor selected to copy each direct [subobject] is trivial 5424 if (RD->hasTrivialCopyConstructor()) { 5425 if (Quals == Qualifiers::Const) 5426 // We must either select the trivial copy constructor or reach an 5427 // ambiguity; no need to actually perform overload resolution. 5428 return true; 5429 } else if (!Selected) { 5430 return false; 5431 } 5432 // In C++98, we are not supposed to perform overload resolution here, but we 5433 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5434 // cases like B as having a non-trivial copy constructor: 5435 // struct A { template<typename T> A(T&); }; 5436 // struct B { mutable A a; }; 5437 goto NeedOverloadResolution; 5438 5439 case Sema::CXXCopyAssignment: 5440 // C++11 [class.copy]p25: 5441 // A copy assignment operator is trivial if: 5442 // - the assignment operator selected to copy each direct [subobject] is 5443 // trivial 5444 if (RD->hasTrivialCopyAssignment()) { 5445 if (Quals == Qualifiers::Const) 5446 return true; 5447 } else if (!Selected) { 5448 return false; 5449 } 5450 // In C++98, we are not supposed to perform overload resolution here, but we 5451 // treat that as a language defect. 5452 goto NeedOverloadResolution; 5453 5454 case Sema::CXXMoveConstructor: 5455 case Sema::CXXMoveAssignment: 5456 NeedOverloadResolution: 5457 Sema::SpecialMemberOverloadResult *SMOR = 5458 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5459 5460 // The standard doesn't describe how to behave if the lookup is ambiguous. 5461 // We treat it as not making the member non-trivial, just like the standard 5462 // mandates for the default constructor. This should rarely matter, because 5463 // the member will also be deleted. 5464 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5465 return true; 5466 5467 if (!SMOR->getMethod()) { 5468 assert(SMOR->getKind() == 5469 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5470 return false; 5471 } 5472 5473 // We deliberately don't check if we found a deleted special member. We're 5474 // not supposed to! 5475 if (Selected) 5476 *Selected = SMOR->getMethod(); 5477 return SMOR->getMethod()->isTrivial(); 5478 } 5479 5480 llvm_unreachable("unknown special method kind"); 5481 } 5482 5483 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5484 for (auto *CI : RD->ctors()) 5485 if (!CI->isImplicit()) 5486 return CI; 5487 5488 // Look for constructor templates. 5489 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5490 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5491 if (CXXConstructorDecl *CD = 5492 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5493 return CD; 5494 } 5495 5496 return 0; 5497 } 5498 5499 /// The kind of subobject we are checking for triviality. The values of this 5500 /// enumeration are used in diagnostics. 5501 enum TrivialSubobjectKind { 5502 /// The subobject is a base class. 5503 TSK_BaseClass, 5504 /// The subobject is a non-static data member. 5505 TSK_Field, 5506 /// The object is actually the complete object. 5507 TSK_CompleteObject 5508 }; 5509 5510 /// Check whether the special member selected for a given type would be trivial. 5511 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5512 QualType SubType, bool ConstRHS, 5513 Sema::CXXSpecialMember CSM, 5514 TrivialSubobjectKind Kind, 5515 bool Diagnose) { 5516 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5517 if (!SubRD) 5518 return true; 5519 5520 CXXMethodDecl *Selected; 5521 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5522 ConstRHS, Diagnose ? &Selected : 0)) 5523 return true; 5524 5525 if (Diagnose) { 5526 if (ConstRHS) 5527 SubType.addConst(); 5528 5529 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5530 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5531 << Kind << SubType.getUnqualifiedType(); 5532 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5533 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5534 } else if (!Selected) 5535 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5536 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5537 else if (Selected->isUserProvided()) { 5538 if (Kind == TSK_CompleteObject) 5539 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5540 << Kind << SubType.getUnqualifiedType() << CSM; 5541 else { 5542 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5543 << Kind << SubType.getUnqualifiedType() << CSM; 5544 S.Diag(Selected->getLocation(), diag::note_declared_at); 5545 } 5546 } else { 5547 if (Kind != TSK_CompleteObject) 5548 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5549 << Kind << SubType.getUnqualifiedType() << CSM; 5550 5551 // Explain why the defaulted or deleted special member isn't trivial. 5552 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5553 } 5554 } 5555 5556 return false; 5557 } 5558 5559 /// Check whether the members of a class type allow a special member to be 5560 /// trivial. 5561 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5562 Sema::CXXSpecialMember CSM, 5563 bool ConstArg, bool Diagnose) { 5564 for (const auto *FI : RD->fields()) { 5565 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5566 continue; 5567 5568 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5569 5570 // Pretend anonymous struct or union members are members of this class. 5571 if (FI->isAnonymousStructOrUnion()) { 5572 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5573 CSM, ConstArg, Diagnose)) 5574 return false; 5575 continue; 5576 } 5577 5578 // C++11 [class.ctor]p5: 5579 // A default constructor is trivial if [...] 5580 // -- no non-static data member of its class has a 5581 // brace-or-equal-initializer 5582 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5583 if (Diagnose) 5584 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 5585 return false; 5586 } 5587 5588 // Objective C ARC 4.3.5: 5589 // [...] nontrivally ownership-qualified types are [...] not trivially 5590 // default constructible, copy constructible, move constructible, copy 5591 // assignable, move assignable, or destructible [...] 5592 if (S.getLangOpts().ObjCAutoRefCount && 5593 FieldType.hasNonTrivialObjCLifetime()) { 5594 if (Diagnose) 5595 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5596 << RD << FieldType.getObjCLifetime(); 5597 return false; 5598 } 5599 5600 bool ConstRHS = ConstArg && !FI->isMutable(); 5601 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 5602 CSM, TSK_Field, Diagnose)) 5603 return false; 5604 } 5605 5606 return true; 5607 } 5608 5609 /// Diagnose why the specified class does not have a trivial special member of 5610 /// the given kind. 5611 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5612 QualType Ty = Context.getRecordType(RD); 5613 5614 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 5615 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 5616 TSK_CompleteObject, /*Diagnose*/true); 5617 } 5618 5619 /// Determine whether a defaulted or deleted special member function is trivial, 5620 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5621 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5622 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5623 bool Diagnose) { 5624 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5625 5626 CXXRecordDecl *RD = MD->getParent(); 5627 5628 bool ConstArg = false; 5629 5630 // C++11 [class.copy]p12, p25: [DR1593] 5631 // A [special member] is trivial if [...] its parameter-type-list is 5632 // equivalent to the parameter-type-list of an implicit declaration [...] 5633 switch (CSM) { 5634 case CXXDefaultConstructor: 5635 case CXXDestructor: 5636 // Trivial default constructors and destructors cannot have parameters. 5637 break; 5638 5639 case CXXCopyConstructor: 5640 case CXXCopyAssignment: { 5641 // Trivial copy operations always have const, non-volatile parameter types. 5642 ConstArg = true; 5643 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5644 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5645 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5646 if (Diagnose) 5647 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5648 << Param0->getSourceRange() << Param0->getType() 5649 << Context.getLValueReferenceType( 5650 Context.getRecordType(RD).withConst()); 5651 return false; 5652 } 5653 break; 5654 } 5655 5656 case CXXMoveConstructor: 5657 case CXXMoveAssignment: { 5658 // Trivial move operations always have non-cv-qualified parameters. 5659 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5660 const RValueReferenceType *RT = 5661 Param0->getType()->getAs<RValueReferenceType>(); 5662 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5663 if (Diagnose) 5664 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5665 << Param0->getSourceRange() << Param0->getType() 5666 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5667 return false; 5668 } 5669 break; 5670 } 5671 5672 case CXXInvalid: 5673 llvm_unreachable("not a special member"); 5674 } 5675 5676 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5677 if (Diagnose) 5678 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5679 diag::note_nontrivial_default_arg) 5680 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5681 return false; 5682 } 5683 if (MD->isVariadic()) { 5684 if (Diagnose) 5685 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5686 return false; 5687 } 5688 5689 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5690 // A copy/move [constructor or assignment operator] is trivial if 5691 // -- the [member] selected to copy/move each direct base class subobject 5692 // is trivial 5693 // 5694 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5695 // A [default constructor or destructor] is trivial if 5696 // -- all the direct base classes have trivial [default constructors or 5697 // destructors] 5698 for (const auto &BI : RD->bases()) 5699 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 5700 ConstArg, CSM, TSK_BaseClass, Diagnose)) 5701 return false; 5702 5703 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5704 // A copy/move [constructor or assignment operator] for a class X is 5705 // trivial if 5706 // -- for each non-static data member of X that is of class type (or array 5707 // thereof), the constructor selected to copy/move that member is 5708 // trivial 5709 // 5710 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5711 // A [default constructor or destructor] is trivial if 5712 // -- for all of the non-static data members of its class that are of class 5713 // type (or array thereof), each such class has a trivial [default 5714 // constructor or destructor] 5715 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5716 return false; 5717 5718 // C++11 [class.dtor]p5: 5719 // A destructor is trivial if [...] 5720 // -- the destructor is not virtual 5721 if (CSM == CXXDestructor && MD->isVirtual()) { 5722 if (Diagnose) 5723 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5724 return false; 5725 } 5726 5727 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5728 // A [special member] for class X is trivial if [...] 5729 // -- class X has no virtual functions and no virtual base classes 5730 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5731 if (!Diagnose) 5732 return false; 5733 5734 if (RD->getNumVBases()) { 5735 // Check for virtual bases. We already know that the corresponding 5736 // member in all bases is trivial, so vbases must all be direct. 5737 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5738 assert(BS.isVirtual()); 5739 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5740 return false; 5741 } 5742 5743 // Must have a virtual method. 5744 for (const auto *MI : RD->methods()) { 5745 if (MI->isVirtual()) { 5746 SourceLocation MLoc = MI->getLocStart(); 5747 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5748 return false; 5749 } 5750 } 5751 5752 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5753 } 5754 5755 // Looks like it's trivial! 5756 return true; 5757 } 5758 5759 /// \brief Data used with FindHiddenVirtualMethod 5760 namespace { 5761 struct FindHiddenVirtualMethodData { 5762 Sema *S; 5763 CXXMethodDecl *Method; 5764 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5765 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5766 }; 5767 } 5768 5769 /// \brief Check whether any most overriden method from MD in Methods 5770 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5771 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5772 if (MD->size_overridden_methods() == 0) 5773 return Methods.count(MD->getCanonicalDecl()); 5774 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5775 E = MD->end_overridden_methods(); 5776 I != E; ++I) 5777 if (CheckMostOverridenMethods(*I, Methods)) 5778 return true; 5779 return false; 5780 } 5781 5782 /// \brief Member lookup function that determines whether a given C++ 5783 /// method overloads virtual methods in a base class without overriding any, 5784 /// to be used with CXXRecordDecl::lookupInBases(). 5785 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5786 CXXBasePath &Path, 5787 void *UserData) { 5788 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5789 5790 FindHiddenVirtualMethodData &Data 5791 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5792 5793 DeclarationName Name = Data.Method->getDeclName(); 5794 assert(Name.getNameKind() == DeclarationName::Identifier); 5795 5796 bool foundSameNameMethod = false; 5797 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5798 for (Path.Decls = BaseRecord->lookup(Name); 5799 !Path.Decls.empty(); 5800 Path.Decls = Path.Decls.slice(1)) { 5801 NamedDecl *D = Path.Decls.front(); 5802 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5803 MD = MD->getCanonicalDecl(); 5804 foundSameNameMethod = true; 5805 // Interested only in hidden virtual methods. 5806 if (!MD->isVirtual()) 5807 continue; 5808 // If the method we are checking overrides a method from its base 5809 // don't warn about the other overloaded methods. 5810 if (!Data.S->IsOverload(Data.Method, MD, false)) 5811 return true; 5812 // Collect the overload only if its hidden. 5813 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5814 overloadedMethods.push_back(MD); 5815 } 5816 } 5817 5818 if (foundSameNameMethod) 5819 Data.OverloadedMethods.append(overloadedMethods.begin(), 5820 overloadedMethods.end()); 5821 return foundSameNameMethod; 5822 } 5823 5824 /// \brief Add the most overriden methods from MD to Methods 5825 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5826 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5827 if (MD->size_overridden_methods() == 0) 5828 Methods.insert(MD->getCanonicalDecl()); 5829 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5830 E = MD->end_overridden_methods(); 5831 I != E; ++I) 5832 AddMostOverridenMethods(*I, Methods); 5833 } 5834 5835 /// \brief Check if a method overloads virtual methods in a base class without 5836 /// overriding any. 5837 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 5838 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5839 if (!MD->getDeclName().isIdentifier()) 5840 return; 5841 5842 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5843 /*bool RecordPaths=*/false, 5844 /*bool DetectVirtual=*/false); 5845 FindHiddenVirtualMethodData Data; 5846 Data.Method = MD; 5847 Data.S = this; 5848 5849 // Keep the base methods that were overriden or introduced in the subclass 5850 // by 'using' in a set. A base method not in this set is hidden. 5851 CXXRecordDecl *DC = MD->getParent(); 5852 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5853 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5854 NamedDecl *ND = *I; 5855 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5856 ND = shad->getTargetDecl(); 5857 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5858 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5859 } 5860 5861 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 5862 OverloadedMethods = Data.OverloadedMethods; 5863 } 5864 5865 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 5866 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5867 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 5868 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 5869 PartialDiagnostic PD = PDiag( 5870 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5871 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 5872 Diag(overloadedMD->getLocation(), PD); 5873 } 5874 } 5875 5876 /// \brief Diagnose methods which overload virtual methods in a base class 5877 /// without overriding any. 5878 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 5879 if (MD->isInvalidDecl()) 5880 return; 5881 5882 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5883 MD->getLocation()) == DiagnosticsEngine::Ignored) 5884 return; 5885 5886 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5887 FindHiddenVirtualMethods(MD, OverloadedMethods); 5888 if (!OverloadedMethods.empty()) { 5889 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5890 << MD << (OverloadedMethods.size() > 1); 5891 5892 NoteHiddenVirtualMethods(MD, OverloadedMethods); 5893 } 5894 } 5895 5896 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5897 Decl *TagDecl, 5898 SourceLocation LBrac, 5899 SourceLocation RBrac, 5900 AttributeList *AttrList) { 5901 if (!TagDecl) 5902 return; 5903 5904 AdjustDeclIfTemplate(TagDecl); 5905 5906 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5907 if (l->getKind() != AttributeList::AT_Visibility) 5908 continue; 5909 l->setInvalid(); 5910 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5911 l->getName(); 5912 } 5913 5914 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5915 // strict aliasing violation! 5916 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5917 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5918 5919 CheckCompletedCXXClass( 5920 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5921 } 5922 5923 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5924 /// special functions, such as the default constructor, copy 5925 /// constructor, or destructor, to the given C++ class (C++ 5926 /// [special]p1). This routine can only be executed just before the 5927 /// definition of the class is complete. 5928 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5929 if (!ClassDecl->hasUserDeclaredConstructor()) 5930 ++ASTContext::NumImplicitDefaultConstructors; 5931 5932 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 5933 ++ASTContext::NumImplicitCopyConstructors; 5934 5935 // If the properties or semantics of the copy constructor couldn't be 5936 // determined while the class was being declared, force a declaration 5937 // of it now. 5938 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 5939 DeclareImplicitCopyConstructor(ClassDecl); 5940 } 5941 5942 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 5943 ++ASTContext::NumImplicitMoveConstructors; 5944 5945 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 5946 DeclareImplicitMoveConstructor(ClassDecl); 5947 } 5948 5949 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5950 ++ASTContext::NumImplicitCopyAssignmentOperators; 5951 5952 // If we have a dynamic class, then the copy assignment operator may be 5953 // virtual, so we have to declare it immediately. This ensures that, e.g., 5954 // it shows up in the right place in the vtable and that we diagnose 5955 // problems with the implicit exception specification. 5956 if (ClassDecl->isDynamicClass() || 5957 ClassDecl->needsOverloadResolutionForCopyAssignment()) 5958 DeclareImplicitCopyAssignment(ClassDecl); 5959 } 5960 5961 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 5962 ++ASTContext::NumImplicitMoveAssignmentOperators; 5963 5964 // Likewise for the move assignment operator. 5965 if (ClassDecl->isDynamicClass() || 5966 ClassDecl->needsOverloadResolutionForMoveAssignment()) 5967 DeclareImplicitMoveAssignment(ClassDecl); 5968 } 5969 5970 if (!ClassDecl->hasUserDeclaredDestructor()) { 5971 ++ASTContext::NumImplicitDestructors; 5972 5973 // If we have a dynamic class, then the destructor may be virtual, so we 5974 // have to declare the destructor immediately. This ensures that, e.g., it 5975 // shows up in the right place in the vtable and that we diagnose problems 5976 // with the implicit exception specification. 5977 if (ClassDecl->isDynamicClass() || 5978 ClassDecl->needsOverloadResolutionForDestructor()) 5979 DeclareImplicitDestructor(ClassDecl); 5980 } 5981 } 5982 5983 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5984 if (!D) 5985 return; 5986 5987 int NumParamList = D->getNumTemplateParameterLists(); 5988 for (int i = 0; i < NumParamList; i++) { 5989 TemplateParameterList* Params = D->getTemplateParameterList(i); 5990 for (TemplateParameterList::iterator Param = Params->begin(), 5991 ParamEnd = Params->end(); 5992 Param != ParamEnd; ++Param) { 5993 NamedDecl *Named = cast<NamedDecl>(*Param); 5994 if (Named->getDeclName()) { 5995 S->AddDecl(Named); 5996 IdResolver.AddDecl(Named); 5997 } 5998 } 5999 } 6000 } 6001 6002 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6003 if (!D) 6004 return; 6005 6006 TemplateParameterList *Params = 0; 6007 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 6008 Params = Template->getTemplateParameters(); 6009 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 6010 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6011 Params = PartialSpec->getTemplateParameters(); 6012 else 6013 return; 6014 6015 for (TemplateParameterList::iterator Param = Params->begin(), 6016 ParamEnd = Params->end(); 6017 Param != ParamEnd; ++Param) { 6018 NamedDecl *Named = cast<NamedDecl>(*Param); 6019 if (Named->getDeclName()) { 6020 S->AddDecl(Named); 6021 IdResolver.AddDecl(Named); 6022 } 6023 } 6024 } 6025 6026 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6027 if (!RecordD) return; 6028 AdjustDeclIfTemplate(RecordD); 6029 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6030 PushDeclContext(S, Record); 6031 } 6032 6033 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6034 if (!RecordD) return; 6035 PopDeclContext(); 6036 } 6037 6038 /// This is used to implement the constant expression evaluation part of the 6039 /// attribute enable_if extension. There is nothing in standard C++ which would 6040 /// require reentering parameters. 6041 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6042 if (!Param) 6043 return; 6044 6045 S->AddDecl(Param); 6046 if (Param->getDeclName()) 6047 IdResolver.AddDecl(Param); 6048 } 6049 6050 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6051 /// parsing a top-level (non-nested) C++ class, and we are now 6052 /// parsing those parts of the given Method declaration that could 6053 /// not be parsed earlier (C++ [class.mem]p2), such as default 6054 /// arguments. This action should enter the scope of the given 6055 /// Method declaration as if we had just parsed the qualified method 6056 /// name. However, it should not bring the parameters into scope; 6057 /// that will be performed by ActOnDelayedCXXMethodParameter. 6058 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6059 } 6060 6061 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6062 /// C++ method declaration. We're (re-)introducing the given 6063 /// function parameter into scope for use in parsing later parts of 6064 /// the method declaration. For example, we could see an 6065 /// ActOnParamDefaultArgument event for this parameter. 6066 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6067 if (!ParamD) 6068 return; 6069 6070 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6071 6072 // If this parameter has an unparsed default argument, clear it out 6073 // to make way for the parsed default argument. 6074 if (Param->hasUnparsedDefaultArg()) 6075 Param->setDefaultArg(0); 6076 6077 S->AddDecl(Param); 6078 if (Param->getDeclName()) 6079 IdResolver.AddDecl(Param); 6080 } 6081 6082 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6083 /// processing the delayed method declaration for Method. The method 6084 /// declaration is now considered finished. There may be a separate 6085 /// ActOnStartOfFunctionDef action later (not necessarily 6086 /// immediately!) for this method, if it was also defined inside the 6087 /// class body. 6088 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6089 if (!MethodD) 6090 return; 6091 6092 AdjustDeclIfTemplate(MethodD); 6093 6094 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6095 6096 // Now that we have our default arguments, check the constructor 6097 // again. It could produce additional diagnostics or affect whether 6098 // the class has implicitly-declared destructors, among other 6099 // things. 6100 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6101 CheckConstructor(Constructor); 6102 6103 // Check the default arguments, which we may have added. 6104 if (!Method->isInvalidDecl()) 6105 CheckCXXDefaultArguments(Method); 6106 } 6107 6108 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6109 /// the well-formedness of the constructor declarator @p D with type @p 6110 /// R. If there are any errors in the declarator, this routine will 6111 /// emit diagnostics and set the invalid bit to true. In any case, the type 6112 /// will be updated to reflect a well-formed type for the constructor and 6113 /// returned. 6114 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6115 StorageClass &SC) { 6116 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6117 6118 // C++ [class.ctor]p3: 6119 // A constructor shall not be virtual (10.3) or static (9.4). A 6120 // constructor can be invoked for a const, volatile or const 6121 // volatile object. A constructor shall not be declared const, 6122 // volatile, or const volatile (9.3.2). 6123 if (isVirtual) { 6124 if (!D.isInvalidType()) 6125 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6126 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6127 << SourceRange(D.getIdentifierLoc()); 6128 D.setInvalidType(); 6129 } 6130 if (SC == SC_Static) { 6131 if (!D.isInvalidType()) 6132 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6133 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6134 << SourceRange(D.getIdentifierLoc()); 6135 D.setInvalidType(); 6136 SC = SC_None; 6137 } 6138 6139 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6140 if (FTI.TypeQuals != 0) { 6141 if (FTI.TypeQuals & Qualifiers::Const) 6142 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6143 << "const" << SourceRange(D.getIdentifierLoc()); 6144 if (FTI.TypeQuals & Qualifiers::Volatile) 6145 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6146 << "volatile" << SourceRange(D.getIdentifierLoc()); 6147 if (FTI.TypeQuals & Qualifiers::Restrict) 6148 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6149 << "restrict" << SourceRange(D.getIdentifierLoc()); 6150 D.setInvalidType(); 6151 } 6152 6153 // C++0x [class.ctor]p4: 6154 // A constructor shall not be declared with a ref-qualifier. 6155 if (FTI.hasRefQualifier()) { 6156 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6157 << FTI.RefQualifierIsLValueRef 6158 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6159 D.setInvalidType(); 6160 } 6161 6162 // Rebuild the function type "R" without any type qualifiers (in 6163 // case any of the errors above fired) and with "void" as the 6164 // return type, since constructors don't have return types. 6165 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6166 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6167 return R; 6168 6169 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6170 EPI.TypeQuals = 0; 6171 EPI.RefQualifier = RQ_None; 6172 6173 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6174 } 6175 6176 /// CheckConstructor - Checks a fully-formed constructor for 6177 /// well-formedness, issuing any diagnostics required. Returns true if 6178 /// the constructor declarator is invalid. 6179 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6180 CXXRecordDecl *ClassDecl 6181 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6182 if (!ClassDecl) 6183 return Constructor->setInvalidDecl(); 6184 6185 // C++ [class.copy]p3: 6186 // A declaration of a constructor for a class X is ill-formed if 6187 // its first parameter is of type (optionally cv-qualified) X and 6188 // either there are no other parameters or else all other 6189 // parameters have default arguments. 6190 if (!Constructor->isInvalidDecl() && 6191 ((Constructor->getNumParams() == 1) || 6192 (Constructor->getNumParams() > 1 && 6193 Constructor->getParamDecl(1)->hasDefaultArg())) && 6194 Constructor->getTemplateSpecializationKind() 6195 != TSK_ImplicitInstantiation) { 6196 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6197 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6198 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6199 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6200 const char *ConstRef 6201 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6202 : " const &"; 6203 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6204 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6205 6206 // FIXME: Rather that making the constructor invalid, we should endeavor 6207 // to fix the type. 6208 Constructor->setInvalidDecl(); 6209 } 6210 } 6211 } 6212 6213 /// CheckDestructor - Checks a fully-formed destructor definition for 6214 /// well-formedness, issuing any diagnostics required. Returns true 6215 /// on error. 6216 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6217 CXXRecordDecl *RD = Destructor->getParent(); 6218 6219 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6220 SourceLocation Loc; 6221 6222 if (!Destructor->isImplicit()) 6223 Loc = Destructor->getLocation(); 6224 else 6225 Loc = RD->getLocation(); 6226 6227 // If we have a virtual destructor, look up the deallocation function 6228 FunctionDecl *OperatorDelete = 0; 6229 DeclarationName Name = 6230 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6231 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6232 return true; 6233 // If there's no class-specific operator delete, look up the global 6234 // non-array delete. 6235 if (!OperatorDelete) 6236 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6237 6238 MarkFunctionReferenced(Loc, OperatorDelete); 6239 6240 Destructor->setOperatorDelete(OperatorDelete); 6241 } 6242 6243 return false; 6244 } 6245 6246 static inline bool 6247 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 6248 return (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 && 6249 FTI.Params[0].Param && 6250 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()); 6251 } 6252 6253 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6254 /// the well-formednes of the destructor declarator @p D with type @p 6255 /// R. If there are any errors in the declarator, this routine will 6256 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6257 /// will be updated to reflect a well-formed type for the destructor and 6258 /// returned. 6259 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6260 StorageClass& SC) { 6261 // C++ [class.dtor]p1: 6262 // [...] A typedef-name that names a class is a class-name 6263 // (7.1.3); however, a typedef-name that names a class shall not 6264 // be used as the identifier in the declarator for a destructor 6265 // declaration. 6266 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6267 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6268 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6269 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6270 else if (const TemplateSpecializationType *TST = 6271 DeclaratorType->getAs<TemplateSpecializationType>()) 6272 if (TST->isTypeAlias()) 6273 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6274 << DeclaratorType << 1; 6275 6276 // C++ [class.dtor]p2: 6277 // A destructor is used to destroy objects of its class type. A 6278 // destructor takes no parameters, and no return type can be 6279 // specified for it (not even void). The address of a destructor 6280 // shall not be taken. A destructor shall not be static. A 6281 // destructor can be invoked for a const, volatile or const 6282 // volatile object. A destructor shall not be declared const, 6283 // volatile or const volatile (9.3.2). 6284 if (SC == SC_Static) { 6285 if (!D.isInvalidType()) 6286 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6287 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6288 << SourceRange(D.getIdentifierLoc()) 6289 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6290 6291 SC = SC_None; 6292 } 6293 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6294 // Destructors don't have return types, but the parser will 6295 // happily parse something like: 6296 // 6297 // class X { 6298 // float ~X(); 6299 // }; 6300 // 6301 // The return type will be eliminated later. 6302 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6303 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6304 << SourceRange(D.getIdentifierLoc()); 6305 } 6306 6307 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6308 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6309 if (FTI.TypeQuals & Qualifiers::Const) 6310 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6311 << "const" << SourceRange(D.getIdentifierLoc()); 6312 if (FTI.TypeQuals & Qualifiers::Volatile) 6313 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6314 << "volatile" << SourceRange(D.getIdentifierLoc()); 6315 if (FTI.TypeQuals & Qualifiers::Restrict) 6316 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6317 << "restrict" << SourceRange(D.getIdentifierLoc()); 6318 D.setInvalidType(); 6319 } 6320 6321 // C++0x [class.dtor]p2: 6322 // A destructor shall not be declared with a ref-qualifier. 6323 if (FTI.hasRefQualifier()) { 6324 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6325 << FTI.RefQualifierIsLValueRef 6326 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6327 D.setInvalidType(); 6328 } 6329 6330 // Make sure we don't have any parameters. 6331 if (FTI.NumParams > 0 && !FTIHasSingleVoidArgument(FTI)) { 6332 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6333 6334 // Delete the parameters. 6335 FTI.freeParams(); 6336 D.setInvalidType(); 6337 } 6338 6339 // Make sure the destructor isn't variadic. 6340 if (FTI.isVariadic) { 6341 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6342 D.setInvalidType(); 6343 } 6344 6345 // Rebuild the function type "R" without any type qualifiers or 6346 // parameters (in case any of the errors above fired) and with 6347 // "void" as the return type, since destructors don't have return 6348 // types. 6349 if (!D.isInvalidType()) 6350 return R; 6351 6352 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6353 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6354 EPI.Variadic = false; 6355 EPI.TypeQuals = 0; 6356 EPI.RefQualifier = RQ_None; 6357 return Context.getFunctionType(Context.VoidTy, None, EPI); 6358 } 6359 6360 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6361 /// well-formednes of the conversion function declarator @p D with 6362 /// type @p R. If there are any errors in the declarator, this routine 6363 /// will emit diagnostics and return true. Otherwise, it will return 6364 /// false. Either way, the type @p R will be updated to reflect a 6365 /// well-formed type for the conversion operator. 6366 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6367 StorageClass& SC) { 6368 // C++ [class.conv.fct]p1: 6369 // Neither parameter types nor return type can be specified. The 6370 // type of a conversion function (8.3.5) is "function taking no 6371 // parameter returning conversion-type-id." 6372 if (SC == SC_Static) { 6373 if (!D.isInvalidType()) 6374 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6375 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6376 << D.getName().getSourceRange(); 6377 D.setInvalidType(); 6378 SC = SC_None; 6379 } 6380 6381 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6382 6383 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6384 // Conversion functions don't have return types, but the parser will 6385 // happily parse something like: 6386 // 6387 // class X { 6388 // float operator bool(); 6389 // }; 6390 // 6391 // The return type will be changed later anyway. 6392 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6393 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6394 << SourceRange(D.getIdentifierLoc()); 6395 D.setInvalidType(); 6396 } 6397 6398 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6399 6400 // Make sure we don't have any parameters. 6401 if (Proto->getNumParams() > 0) { 6402 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6403 6404 // Delete the parameters. 6405 D.getFunctionTypeInfo().freeParams(); 6406 D.setInvalidType(); 6407 } else if (Proto->isVariadic()) { 6408 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6409 D.setInvalidType(); 6410 } 6411 6412 // Diagnose "&operator bool()" and other such nonsense. This 6413 // is actually a gcc extension which we don't support. 6414 if (Proto->getReturnType() != ConvType) { 6415 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6416 << Proto->getReturnType(); 6417 D.setInvalidType(); 6418 ConvType = Proto->getReturnType(); 6419 } 6420 6421 // C++ [class.conv.fct]p4: 6422 // The conversion-type-id shall not represent a function type nor 6423 // an array type. 6424 if (ConvType->isArrayType()) { 6425 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6426 ConvType = Context.getPointerType(ConvType); 6427 D.setInvalidType(); 6428 } else if (ConvType->isFunctionType()) { 6429 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6430 ConvType = Context.getPointerType(ConvType); 6431 D.setInvalidType(); 6432 } 6433 6434 // Rebuild the function type "R" without any parameters (in case any 6435 // of the errors above fired) and with the conversion type as the 6436 // return type. 6437 if (D.isInvalidType()) 6438 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6439 6440 // C++0x explicit conversion operators. 6441 if (D.getDeclSpec().isExplicitSpecified()) 6442 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6443 getLangOpts().CPlusPlus11 ? 6444 diag::warn_cxx98_compat_explicit_conversion_functions : 6445 diag::ext_explicit_conversion_functions) 6446 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6447 } 6448 6449 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6450 /// the declaration of the given C++ conversion function. This routine 6451 /// is responsible for recording the conversion function in the C++ 6452 /// class, if possible. 6453 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6454 assert(Conversion && "Expected to receive a conversion function declaration"); 6455 6456 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6457 6458 // Make sure we aren't redeclaring the conversion function. 6459 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6460 6461 // C++ [class.conv.fct]p1: 6462 // [...] A conversion function is never used to convert a 6463 // (possibly cv-qualified) object to the (possibly cv-qualified) 6464 // same object type (or a reference to it), to a (possibly 6465 // cv-qualified) base class of that type (or a reference to it), 6466 // or to (possibly cv-qualified) void. 6467 // FIXME: Suppress this warning if the conversion function ends up being a 6468 // virtual function that overrides a virtual function in a base class. 6469 QualType ClassType 6470 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6471 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6472 ConvType = ConvTypeRef->getPointeeType(); 6473 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6474 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6475 /* Suppress diagnostics for instantiations. */; 6476 else if (ConvType->isRecordType()) { 6477 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6478 if (ConvType == ClassType) 6479 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6480 << ClassType; 6481 else if (IsDerivedFrom(ClassType, ConvType)) 6482 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6483 << ClassType << ConvType; 6484 } else if (ConvType->isVoidType()) { 6485 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6486 << ClassType << ConvType; 6487 } 6488 6489 if (FunctionTemplateDecl *ConversionTemplate 6490 = Conversion->getDescribedFunctionTemplate()) 6491 return ConversionTemplate; 6492 6493 return Conversion; 6494 } 6495 6496 //===----------------------------------------------------------------------===// 6497 // Namespace Handling 6498 //===----------------------------------------------------------------------===// 6499 6500 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6501 /// reopened. 6502 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6503 SourceLocation Loc, 6504 IdentifierInfo *II, bool *IsInline, 6505 NamespaceDecl *PrevNS) { 6506 assert(*IsInline != PrevNS->isInline()); 6507 6508 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6509 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6510 // inline namespaces, with the intention of bringing names into namespace std. 6511 // 6512 // We support this just well enough to get that case working; this is not 6513 // sufficient to support reopening namespaces as inline in general. 6514 if (*IsInline && II && II->getName().startswith("__atomic") && 6515 S.getSourceManager().isInSystemHeader(Loc)) { 6516 // Mark all prior declarations of the namespace as inline. 6517 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6518 NS = NS->getPreviousDecl()) 6519 NS->setInline(*IsInline); 6520 // Patch up the lookup table for the containing namespace. This isn't really 6521 // correct, but it's good enough for this particular case. 6522 for (auto *I : PrevNS->decls()) 6523 if (auto *ND = dyn_cast<NamedDecl>(I)) 6524 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6525 return; 6526 } 6527 6528 if (PrevNS->isInline()) 6529 // The user probably just forgot the 'inline', so suggest that it 6530 // be added back. 6531 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6532 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6533 else 6534 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 6535 6536 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6537 *IsInline = PrevNS->isInline(); 6538 } 6539 6540 /// ActOnStartNamespaceDef - This is called at the start of a namespace 6541 /// definition. 6542 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6543 SourceLocation InlineLoc, 6544 SourceLocation NamespaceLoc, 6545 SourceLocation IdentLoc, 6546 IdentifierInfo *II, 6547 SourceLocation LBrace, 6548 AttributeList *AttrList) { 6549 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6550 // For anonymous namespace, take the location of the left brace. 6551 SourceLocation Loc = II ? IdentLoc : LBrace; 6552 bool IsInline = InlineLoc.isValid(); 6553 bool IsInvalid = false; 6554 bool IsStd = false; 6555 bool AddToKnown = false; 6556 Scope *DeclRegionScope = NamespcScope->getParent(); 6557 6558 NamespaceDecl *PrevNS = 0; 6559 if (II) { 6560 // C++ [namespace.def]p2: 6561 // The identifier in an original-namespace-definition shall not 6562 // have been previously defined in the declarative region in 6563 // which the original-namespace-definition appears. The 6564 // identifier in an original-namespace-definition is the name of 6565 // the namespace. Subsequently in that declarative region, it is 6566 // treated as an original-namespace-name. 6567 // 6568 // Since namespace names are unique in their scope, and we don't 6569 // look through using directives, just look for any ordinary names. 6570 6571 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6572 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6573 Decl::IDNS_Namespace; 6574 NamedDecl *PrevDecl = 0; 6575 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6576 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6577 ++I) { 6578 if ((*I)->getIdentifierNamespace() & IDNS) { 6579 PrevDecl = *I; 6580 break; 6581 } 6582 } 6583 6584 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6585 6586 if (PrevNS) { 6587 // This is an extended namespace definition. 6588 if (IsInline != PrevNS->isInline()) 6589 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6590 &IsInline, PrevNS); 6591 } else if (PrevDecl) { 6592 // This is an invalid name redefinition. 6593 Diag(Loc, diag::err_redefinition_different_kind) 6594 << II; 6595 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6596 IsInvalid = true; 6597 // Continue on to push Namespc as current DeclContext and return it. 6598 } else if (II->isStr("std") && 6599 CurContext->getRedeclContext()->isTranslationUnit()) { 6600 // This is the first "real" definition of the namespace "std", so update 6601 // our cache of the "std" namespace to point at this definition. 6602 PrevNS = getStdNamespace(); 6603 IsStd = true; 6604 AddToKnown = !IsInline; 6605 } else { 6606 // We've seen this namespace for the first time. 6607 AddToKnown = !IsInline; 6608 } 6609 } else { 6610 // Anonymous namespaces. 6611 6612 // Determine whether the parent already has an anonymous namespace. 6613 DeclContext *Parent = CurContext->getRedeclContext(); 6614 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6615 PrevNS = TU->getAnonymousNamespace(); 6616 } else { 6617 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6618 PrevNS = ND->getAnonymousNamespace(); 6619 } 6620 6621 if (PrevNS && IsInline != PrevNS->isInline()) 6622 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6623 &IsInline, PrevNS); 6624 } 6625 6626 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6627 StartLoc, Loc, II, PrevNS); 6628 if (IsInvalid) 6629 Namespc->setInvalidDecl(); 6630 6631 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6632 6633 // FIXME: Should we be merging attributes? 6634 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6635 PushNamespaceVisibilityAttr(Attr, Loc); 6636 6637 if (IsStd) 6638 StdNamespace = Namespc; 6639 if (AddToKnown) 6640 KnownNamespaces[Namespc] = false; 6641 6642 if (II) { 6643 PushOnScopeChains(Namespc, DeclRegionScope); 6644 } else { 6645 // Link the anonymous namespace into its parent. 6646 DeclContext *Parent = CurContext->getRedeclContext(); 6647 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6648 TU->setAnonymousNamespace(Namespc); 6649 } else { 6650 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6651 } 6652 6653 CurContext->addDecl(Namespc); 6654 6655 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6656 // behaves as if it were replaced by 6657 // namespace unique { /* empty body */ } 6658 // using namespace unique; 6659 // namespace unique { namespace-body } 6660 // where all occurrences of 'unique' in a translation unit are 6661 // replaced by the same identifier and this identifier differs 6662 // from all other identifiers in the entire program. 6663 6664 // We just create the namespace with an empty name and then add an 6665 // implicit using declaration, just like the standard suggests. 6666 // 6667 // CodeGen enforces the "universally unique" aspect by giving all 6668 // declarations semantically contained within an anonymous 6669 // namespace internal linkage. 6670 6671 if (!PrevNS) { 6672 UsingDirectiveDecl* UD 6673 = UsingDirectiveDecl::Create(Context, Parent, 6674 /* 'using' */ LBrace, 6675 /* 'namespace' */ SourceLocation(), 6676 /* qualifier */ NestedNameSpecifierLoc(), 6677 /* identifier */ SourceLocation(), 6678 Namespc, 6679 /* Ancestor */ Parent); 6680 UD->setImplicit(); 6681 Parent->addDecl(UD); 6682 } 6683 } 6684 6685 ActOnDocumentableDecl(Namespc); 6686 6687 // Although we could have an invalid decl (i.e. the namespace name is a 6688 // redefinition), push it as current DeclContext and try to continue parsing. 6689 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6690 // for the namespace has the declarations that showed up in that particular 6691 // namespace definition. 6692 PushDeclContext(NamespcScope, Namespc); 6693 return Namespc; 6694 } 6695 6696 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6697 /// is a namespace alias, returns the namespace it points to. 6698 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6699 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6700 return AD->getNamespace(); 6701 return dyn_cast_or_null<NamespaceDecl>(D); 6702 } 6703 6704 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 6705 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6706 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6707 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6708 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6709 Namespc->setRBraceLoc(RBrace); 6710 PopDeclContext(); 6711 if (Namespc->hasAttr<VisibilityAttr>()) 6712 PopPragmaVisibility(true, RBrace); 6713 } 6714 6715 CXXRecordDecl *Sema::getStdBadAlloc() const { 6716 return cast_or_null<CXXRecordDecl>( 6717 StdBadAlloc.get(Context.getExternalSource())); 6718 } 6719 6720 NamespaceDecl *Sema::getStdNamespace() const { 6721 return cast_or_null<NamespaceDecl>( 6722 StdNamespace.get(Context.getExternalSource())); 6723 } 6724 6725 /// \brief Retrieve the special "std" namespace, which may require us to 6726 /// implicitly define the namespace. 6727 NamespaceDecl *Sema::getOrCreateStdNamespace() { 6728 if (!StdNamespace) { 6729 // The "std" namespace has not yet been defined, so build one implicitly. 6730 StdNamespace = NamespaceDecl::Create(Context, 6731 Context.getTranslationUnitDecl(), 6732 /*Inline=*/false, 6733 SourceLocation(), SourceLocation(), 6734 &PP.getIdentifierTable().get("std"), 6735 /*PrevDecl=*/0); 6736 getStdNamespace()->setImplicit(true); 6737 } 6738 6739 return getStdNamespace(); 6740 } 6741 6742 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6743 assert(getLangOpts().CPlusPlus && 6744 "Looking for std::initializer_list outside of C++."); 6745 6746 // We're looking for implicit instantiations of 6747 // template <typename E> class std::initializer_list. 6748 6749 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6750 return false; 6751 6752 ClassTemplateDecl *Template = 0; 6753 const TemplateArgument *Arguments = 0; 6754 6755 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6756 6757 ClassTemplateSpecializationDecl *Specialization = 6758 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6759 if (!Specialization) 6760 return false; 6761 6762 Template = Specialization->getSpecializedTemplate(); 6763 Arguments = Specialization->getTemplateArgs().data(); 6764 } else if (const TemplateSpecializationType *TST = 6765 Ty->getAs<TemplateSpecializationType>()) { 6766 Template = dyn_cast_or_null<ClassTemplateDecl>( 6767 TST->getTemplateName().getAsTemplateDecl()); 6768 Arguments = TST->getArgs(); 6769 } 6770 if (!Template) 6771 return false; 6772 6773 if (!StdInitializerList) { 6774 // Haven't recognized std::initializer_list yet, maybe this is it. 6775 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6776 if (TemplateClass->getIdentifier() != 6777 &PP.getIdentifierTable().get("initializer_list") || 6778 !getStdNamespace()->InEnclosingNamespaceSetOf( 6779 TemplateClass->getDeclContext())) 6780 return false; 6781 // This is a template called std::initializer_list, but is it the right 6782 // template? 6783 TemplateParameterList *Params = Template->getTemplateParameters(); 6784 if (Params->getMinRequiredArguments() != 1) 6785 return false; 6786 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6787 return false; 6788 6789 // It's the right template. 6790 StdInitializerList = Template; 6791 } 6792 6793 if (Template != StdInitializerList) 6794 return false; 6795 6796 // This is an instance of std::initializer_list. Find the argument type. 6797 if (Element) 6798 *Element = Arguments[0].getAsType(); 6799 return true; 6800 } 6801 6802 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6803 NamespaceDecl *Std = S.getStdNamespace(); 6804 if (!Std) { 6805 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6806 return 0; 6807 } 6808 6809 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6810 Loc, Sema::LookupOrdinaryName); 6811 if (!S.LookupQualifiedName(Result, Std)) { 6812 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6813 return 0; 6814 } 6815 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6816 if (!Template) { 6817 Result.suppressDiagnostics(); 6818 // We found something weird. Complain about the first thing we found. 6819 NamedDecl *Found = *Result.begin(); 6820 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6821 return 0; 6822 } 6823 6824 // We found some template called std::initializer_list. Now verify that it's 6825 // correct. 6826 TemplateParameterList *Params = Template->getTemplateParameters(); 6827 if (Params->getMinRequiredArguments() != 1 || 6828 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6829 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6830 return 0; 6831 } 6832 6833 return Template; 6834 } 6835 6836 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6837 if (!StdInitializerList) { 6838 StdInitializerList = LookupStdInitializerList(*this, Loc); 6839 if (!StdInitializerList) 6840 return QualType(); 6841 } 6842 6843 TemplateArgumentListInfo Args(Loc, Loc); 6844 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6845 Context.getTrivialTypeSourceInfo(Element, 6846 Loc))); 6847 return Context.getCanonicalType( 6848 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6849 } 6850 6851 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6852 // C++ [dcl.init.list]p2: 6853 // A constructor is an initializer-list constructor if its first parameter 6854 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6855 // std::initializer_list<E> for some type E, and either there are no other 6856 // parameters or else all other parameters have default arguments. 6857 if (Ctor->getNumParams() < 1 || 6858 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6859 return false; 6860 6861 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6862 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6863 ArgType = RT->getPointeeType().getUnqualifiedType(); 6864 6865 return isStdInitializerList(ArgType, 0); 6866 } 6867 6868 /// \brief Determine whether a using statement is in a context where it will be 6869 /// apply in all contexts. 6870 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6871 switch (CurContext->getDeclKind()) { 6872 case Decl::TranslationUnit: 6873 return true; 6874 case Decl::LinkageSpec: 6875 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6876 default: 6877 return false; 6878 } 6879 } 6880 6881 namespace { 6882 6883 // Callback to only accept typo corrections that are namespaces. 6884 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6885 public: 6886 bool ValidateCandidate(const TypoCorrection &candidate) override { 6887 if (NamedDecl *ND = candidate.getCorrectionDecl()) 6888 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6889 return false; 6890 } 6891 }; 6892 6893 } 6894 6895 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6896 CXXScopeSpec &SS, 6897 SourceLocation IdentLoc, 6898 IdentifierInfo *Ident) { 6899 NamespaceValidatorCCC Validator; 6900 R.clear(); 6901 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6902 R.getLookupKind(), Sc, &SS, 6903 Validator, 6904 Sema::CTK_ErrorRecovery)) { 6905 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 6906 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6907 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 6908 Ident->getName().equals(CorrectedStr); 6909 S.diagnoseTypo(Corrected, 6910 S.PDiag(diag::err_using_directive_member_suggest) 6911 << Ident << DC << DroppedSpecifier << SS.getRange(), 6912 S.PDiag(diag::note_namespace_defined_here)); 6913 } else { 6914 S.diagnoseTypo(Corrected, 6915 S.PDiag(diag::err_using_directive_suggest) << Ident, 6916 S.PDiag(diag::note_namespace_defined_here)); 6917 } 6918 R.addDecl(Corrected.getCorrectionDecl()); 6919 return true; 6920 } 6921 return false; 6922 } 6923 6924 Decl *Sema::ActOnUsingDirective(Scope *S, 6925 SourceLocation UsingLoc, 6926 SourceLocation NamespcLoc, 6927 CXXScopeSpec &SS, 6928 SourceLocation IdentLoc, 6929 IdentifierInfo *NamespcName, 6930 AttributeList *AttrList) { 6931 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6932 assert(NamespcName && "Invalid NamespcName."); 6933 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6934 6935 // This can only happen along a recovery path. 6936 while (S->getFlags() & Scope::TemplateParamScope) 6937 S = S->getParent(); 6938 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6939 6940 UsingDirectiveDecl *UDir = 0; 6941 NestedNameSpecifier *Qualifier = 0; 6942 if (SS.isSet()) 6943 Qualifier = SS.getScopeRep(); 6944 6945 // Lookup namespace name. 6946 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6947 LookupParsedName(R, S, &SS); 6948 if (R.isAmbiguous()) 6949 return 0; 6950 6951 if (R.empty()) { 6952 R.clear(); 6953 // Allow "using namespace std;" or "using namespace ::std;" even if 6954 // "std" hasn't been defined yet, for GCC compatibility. 6955 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6956 NamespcName->isStr("std")) { 6957 Diag(IdentLoc, diag::ext_using_undefined_std); 6958 R.addDecl(getOrCreateStdNamespace()); 6959 R.resolveKind(); 6960 } 6961 // Otherwise, attempt typo correction. 6962 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6963 } 6964 6965 if (!R.empty()) { 6966 NamedDecl *Named = R.getFoundDecl(); 6967 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6968 && "expected namespace decl"); 6969 // C++ [namespace.udir]p1: 6970 // A using-directive specifies that the names in the nominated 6971 // namespace can be used in the scope in which the 6972 // using-directive appears after the using-directive. During 6973 // unqualified name lookup (3.4.1), the names appear as if they 6974 // were declared in the nearest enclosing namespace which 6975 // contains both the using-directive and the nominated 6976 // namespace. [Note: in this context, "contains" means "contains 6977 // directly or indirectly". ] 6978 6979 // Find enclosing context containing both using-directive and 6980 // nominated namespace. 6981 NamespaceDecl *NS = getNamespaceDecl(Named); 6982 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6983 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6984 CommonAncestor = CommonAncestor->getParent(); 6985 6986 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6987 SS.getWithLocInContext(Context), 6988 IdentLoc, Named, CommonAncestor); 6989 6990 if (IsUsingDirectiveInToplevelContext(CurContext) && 6991 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6992 Diag(IdentLoc, diag::warn_using_directive_in_header); 6993 } 6994 6995 PushUsingDirective(S, UDir); 6996 } else { 6997 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6998 } 6999 7000 if (UDir) 7001 ProcessDeclAttributeList(S, UDir, AttrList); 7002 7003 return UDir; 7004 } 7005 7006 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 7007 // If the scope has an associated entity and the using directive is at 7008 // namespace or translation unit scope, add the UsingDirectiveDecl into 7009 // its lookup structure so qualified name lookup can find it. 7010 DeclContext *Ctx = S->getEntity(); 7011 if (Ctx && !Ctx->isFunctionOrMethod()) 7012 Ctx->addDecl(UDir); 7013 else 7014 // Otherwise, it is at block sope. The using-directives will affect lookup 7015 // only to the end of the scope. 7016 S->PushUsingDirective(UDir); 7017 } 7018 7019 7020 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7021 AccessSpecifier AS, 7022 bool HasUsingKeyword, 7023 SourceLocation UsingLoc, 7024 CXXScopeSpec &SS, 7025 UnqualifiedId &Name, 7026 AttributeList *AttrList, 7027 bool HasTypenameKeyword, 7028 SourceLocation TypenameLoc) { 7029 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7030 7031 switch (Name.getKind()) { 7032 case UnqualifiedId::IK_ImplicitSelfParam: 7033 case UnqualifiedId::IK_Identifier: 7034 case UnqualifiedId::IK_OperatorFunctionId: 7035 case UnqualifiedId::IK_LiteralOperatorId: 7036 case UnqualifiedId::IK_ConversionFunctionId: 7037 break; 7038 7039 case UnqualifiedId::IK_ConstructorName: 7040 case UnqualifiedId::IK_ConstructorTemplateId: 7041 // C++11 inheriting constructors. 7042 Diag(Name.getLocStart(), 7043 getLangOpts().CPlusPlus11 ? 7044 diag::warn_cxx98_compat_using_decl_constructor : 7045 diag::err_using_decl_constructor) 7046 << SS.getRange(); 7047 7048 if (getLangOpts().CPlusPlus11) break; 7049 7050 return 0; 7051 7052 case UnqualifiedId::IK_DestructorName: 7053 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7054 << SS.getRange(); 7055 return 0; 7056 7057 case UnqualifiedId::IK_TemplateId: 7058 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7059 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7060 return 0; 7061 } 7062 7063 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7064 DeclarationName TargetName = TargetNameInfo.getName(); 7065 if (!TargetName) 7066 return 0; 7067 7068 // Warn about access declarations. 7069 if (!HasUsingKeyword) { 7070 Diag(Name.getLocStart(), 7071 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7072 : diag::warn_access_decl_deprecated) 7073 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7074 } 7075 7076 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7077 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7078 return 0; 7079 7080 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7081 TargetNameInfo, AttrList, 7082 /* IsInstantiation */ false, 7083 HasTypenameKeyword, TypenameLoc); 7084 if (UD) 7085 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7086 7087 return UD; 7088 } 7089 7090 /// \brief Determine whether a using declaration considers the given 7091 /// declarations as "equivalent", e.g., if they are redeclarations of 7092 /// the same entity or are both typedefs of the same type. 7093 static bool 7094 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7095 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7096 return true; 7097 7098 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7099 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7100 return Context.hasSameType(TD1->getUnderlyingType(), 7101 TD2->getUnderlyingType()); 7102 7103 return false; 7104 } 7105 7106 7107 /// Determines whether to create a using shadow decl for a particular 7108 /// decl, given the set of decls existing prior to this using lookup. 7109 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7110 const LookupResult &Previous, 7111 UsingShadowDecl *&PrevShadow) { 7112 // Diagnose finding a decl which is not from a base class of the 7113 // current class. We do this now because there are cases where this 7114 // function will silently decide not to build a shadow decl, which 7115 // will pre-empt further diagnostics. 7116 // 7117 // We don't need to do this in C++0x because we do the check once on 7118 // the qualifier. 7119 // 7120 // FIXME: diagnose the following if we care enough: 7121 // struct A { int foo; }; 7122 // struct B : A { using A::foo; }; 7123 // template <class T> struct C : A {}; 7124 // template <class T> struct D : C<T> { using B::foo; } // <--- 7125 // This is invalid (during instantiation) in C++03 because B::foo 7126 // resolves to the using decl in B, which is not a base class of D<T>. 7127 // We can't diagnose it immediately because C<T> is an unknown 7128 // specialization. The UsingShadowDecl in D<T> then points directly 7129 // to A::foo, which will look well-formed when we instantiate. 7130 // The right solution is to not collapse the shadow-decl chain. 7131 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7132 DeclContext *OrigDC = Orig->getDeclContext(); 7133 7134 // Handle enums and anonymous structs. 7135 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7136 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7137 while (OrigRec->isAnonymousStructOrUnion()) 7138 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7139 7140 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7141 if (OrigDC == CurContext) { 7142 Diag(Using->getLocation(), 7143 diag::err_using_decl_nested_name_specifier_is_current_class) 7144 << Using->getQualifierLoc().getSourceRange(); 7145 Diag(Orig->getLocation(), diag::note_using_decl_target); 7146 return true; 7147 } 7148 7149 Diag(Using->getQualifierLoc().getBeginLoc(), 7150 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7151 << Using->getQualifier() 7152 << cast<CXXRecordDecl>(CurContext) 7153 << Using->getQualifierLoc().getSourceRange(); 7154 Diag(Orig->getLocation(), diag::note_using_decl_target); 7155 return true; 7156 } 7157 } 7158 7159 if (Previous.empty()) return false; 7160 7161 NamedDecl *Target = Orig; 7162 if (isa<UsingShadowDecl>(Target)) 7163 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7164 7165 // If the target happens to be one of the previous declarations, we 7166 // don't have a conflict. 7167 // 7168 // FIXME: but we might be increasing its access, in which case we 7169 // should redeclare it. 7170 NamedDecl *NonTag = 0, *Tag = 0; 7171 bool FoundEquivalentDecl = false; 7172 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7173 I != E; ++I) { 7174 NamedDecl *D = (*I)->getUnderlyingDecl(); 7175 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7176 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7177 PrevShadow = Shadow; 7178 FoundEquivalentDecl = true; 7179 } 7180 7181 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7182 } 7183 7184 if (FoundEquivalentDecl) 7185 return false; 7186 7187 if (FunctionDecl *FD = Target->getAsFunction()) { 7188 NamedDecl *OldDecl = 0; 7189 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 7190 case Ovl_Overload: 7191 return false; 7192 7193 case Ovl_NonFunction: 7194 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7195 break; 7196 7197 // We found a decl with the exact signature. 7198 case Ovl_Match: 7199 // If we're in a record, we want to hide the target, so we 7200 // return true (without a diagnostic) to tell the caller not to 7201 // build a shadow decl. 7202 if (CurContext->isRecord()) 7203 return true; 7204 7205 // If we're not in a record, this is an error. 7206 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7207 break; 7208 } 7209 7210 Diag(Target->getLocation(), diag::note_using_decl_target); 7211 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7212 return true; 7213 } 7214 7215 // Target is not a function. 7216 7217 if (isa<TagDecl>(Target)) { 7218 // No conflict between a tag and a non-tag. 7219 if (!Tag) return false; 7220 7221 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7222 Diag(Target->getLocation(), diag::note_using_decl_target); 7223 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7224 return true; 7225 } 7226 7227 // No conflict between a tag and a non-tag. 7228 if (!NonTag) return false; 7229 7230 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7231 Diag(Target->getLocation(), diag::note_using_decl_target); 7232 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7233 return true; 7234 } 7235 7236 /// Builds a shadow declaration corresponding to a 'using' declaration. 7237 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7238 UsingDecl *UD, 7239 NamedDecl *Orig, 7240 UsingShadowDecl *PrevDecl) { 7241 7242 // If we resolved to another shadow declaration, just coalesce them. 7243 NamedDecl *Target = Orig; 7244 if (isa<UsingShadowDecl>(Target)) { 7245 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7246 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7247 } 7248 7249 UsingShadowDecl *Shadow 7250 = UsingShadowDecl::Create(Context, CurContext, 7251 UD->getLocation(), UD, Target); 7252 UD->addShadowDecl(Shadow); 7253 7254 Shadow->setAccess(UD->getAccess()); 7255 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7256 Shadow->setInvalidDecl(); 7257 7258 Shadow->setPreviousDecl(PrevDecl); 7259 7260 if (S) 7261 PushOnScopeChains(Shadow, S); 7262 else 7263 CurContext->addDecl(Shadow); 7264 7265 7266 return Shadow; 7267 } 7268 7269 /// Hides a using shadow declaration. This is required by the current 7270 /// using-decl implementation when a resolvable using declaration in a 7271 /// class is followed by a declaration which would hide or override 7272 /// one or more of the using decl's targets; for example: 7273 /// 7274 /// struct Base { void foo(int); }; 7275 /// struct Derived : Base { 7276 /// using Base::foo; 7277 /// void foo(int); 7278 /// }; 7279 /// 7280 /// The governing language is C++03 [namespace.udecl]p12: 7281 /// 7282 /// When a using-declaration brings names from a base class into a 7283 /// derived class scope, member functions in the derived class 7284 /// override and/or hide member functions with the same name and 7285 /// parameter types in a base class (rather than conflicting). 7286 /// 7287 /// There are two ways to implement this: 7288 /// (1) optimistically create shadow decls when they're not hidden 7289 /// by existing declarations, or 7290 /// (2) don't create any shadow decls (or at least don't make them 7291 /// visible) until we've fully parsed/instantiated the class. 7292 /// The problem with (1) is that we might have to retroactively remove 7293 /// a shadow decl, which requires several O(n) operations because the 7294 /// decl structures are (very reasonably) not designed for removal. 7295 /// (2) avoids this but is very fiddly and phase-dependent. 7296 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7297 if (Shadow->getDeclName().getNameKind() == 7298 DeclarationName::CXXConversionFunctionName) 7299 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7300 7301 // Remove it from the DeclContext... 7302 Shadow->getDeclContext()->removeDecl(Shadow); 7303 7304 // ...and the scope, if applicable... 7305 if (S) { 7306 S->RemoveDecl(Shadow); 7307 IdResolver.RemoveDecl(Shadow); 7308 } 7309 7310 // ...and the using decl. 7311 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7312 7313 // TODO: complain somehow if Shadow was used. It shouldn't 7314 // be possible for this to happen, because...? 7315 } 7316 7317 namespace { 7318 class UsingValidatorCCC : public CorrectionCandidateCallback { 7319 public: 7320 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7321 bool RequireMember) 7322 : HasTypenameKeyword(HasTypenameKeyword), 7323 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {} 7324 7325 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7326 NamedDecl *ND = Candidate.getCorrectionDecl(); 7327 7328 // Keywords are not valid here. 7329 if (!ND || isa<NamespaceDecl>(ND)) 7330 return false; 7331 7332 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) && 7333 !isa<TypeDecl>(ND)) 7334 return false; 7335 7336 // Completely unqualified names are invalid for a 'using' declaration. 7337 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7338 return false; 7339 7340 if (isa<TypeDecl>(ND)) 7341 return HasTypenameKeyword || !IsInstantiation; 7342 7343 return !HasTypenameKeyword; 7344 } 7345 7346 private: 7347 bool HasTypenameKeyword; 7348 bool IsInstantiation; 7349 bool RequireMember; 7350 }; 7351 } // end anonymous namespace 7352 7353 /// Builds a using declaration. 7354 /// 7355 /// \param IsInstantiation - Whether this call arises from an 7356 /// instantiation of an unresolved using declaration. We treat 7357 /// the lookup differently for these declarations. 7358 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7359 SourceLocation UsingLoc, 7360 CXXScopeSpec &SS, 7361 const DeclarationNameInfo &NameInfo, 7362 AttributeList *AttrList, 7363 bool IsInstantiation, 7364 bool HasTypenameKeyword, 7365 SourceLocation TypenameLoc) { 7366 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7367 SourceLocation IdentLoc = NameInfo.getLoc(); 7368 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7369 7370 // FIXME: We ignore attributes for now. 7371 7372 if (SS.isEmpty()) { 7373 Diag(IdentLoc, diag::err_using_requires_qualname); 7374 return 0; 7375 } 7376 7377 // Do the redeclaration lookup in the current scope. 7378 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7379 ForRedeclaration); 7380 Previous.setHideTags(false); 7381 if (S) { 7382 LookupName(Previous, S); 7383 7384 // It is really dumb that we have to do this. 7385 LookupResult::Filter F = Previous.makeFilter(); 7386 while (F.hasNext()) { 7387 NamedDecl *D = F.next(); 7388 if (!isDeclInScope(D, CurContext, S)) 7389 F.erase(); 7390 // If we found a local extern declaration that's not ordinarily visible, 7391 // and this declaration is being added to a non-block scope, ignore it. 7392 // We're only checking for scope conflicts here, not also for violations 7393 // of the linkage rules. 7394 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 7395 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 7396 F.erase(); 7397 } 7398 F.done(); 7399 } else { 7400 assert(IsInstantiation && "no scope in non-instantiation"); 7401 assert(CurContext->isRecord() && "scope not record in instantiation"); 7402 LookupQualifiedName(Previous, CurContext); 7403 } 7404 7405 // Check for invalid redeclarations. 7406 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7407 SS, IdentLoc, Previous)) 7408 return 0; 7409 7410 // Check for bad qualifiers. 7411 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 7412 return 0; 7413 7414 DeclContext *LookupContext = computeDeclContext(SS); 7415 NamedDecl *D; 7416 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7417 if (!LookupContext) { 7418 if (HasTypenameKeyword) { 7419 // FIXME: not all declaration name kinds are legal here 7420 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7421 UsingLoc, TypenameLoc, 7422 QualifierLoc, 7423 IdentLoc, NameInfo.getName()); 7424 } else { 7425 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7426 QualifierLoc, NameInfo); 7427 } 7428 } else { 7429 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 7430 NameInfo, HasTypenameKeyword); 7431 } 7432 D->setAccess(AS); 7433 CurContext->addDecl(D); 7434 7435 if (!LookupContext) return D; 7436 UsingDecl *UD = cast<UsingDecl>(D); 7437 7438 if (RequireCompleteDeclContext(SS, LookupContext)) { 7439 UD->setInvalidDecl(); 7440 return UD; 7441 } 7442 7443 // The normal rules do not apply to inheriting constructor declarations. 7444 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7445 if (CheckInheritingConstructorUsingDecl(UD)) 7446 UD->setInvalidDecl(); 7447 return UD; 7448 } 7449 7450 // Otherwise, look up the target name. 7451 7452 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7453 7454 // Unlike most lookups, we don't always want to hide tag 7455 // declarations: tag names are visible through the using declaration 7456 // even if hidden by ordinary names, *except* in a dependent context 7457 // where it's important for the sanity of two-phase lookup. 7458 if (!IsInstantiation) 7459 R.setHideTags(false); 7460 7461 // For the purposes of this lookup, we have a base object type 7462 // equal to that of the current context. 7463 if (CurContext->isRecord()) { 7464 R.setBaseObjectType( 7465 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7466 } 7467 7468 LookupQualifiedName(R, LookupContext); 7469 7470 // Try to correct typos if possible. 7471 if (R.empty()) { 7472 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, 7473 CurContext->isRecord()); 7474 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(), 7475 R.getLookupKind(), S, &SS, CCC, 7476 CTK_ErrorRecovery)){ 7477 // We reject any correction for which ND would be NULL. 7478 NamedDecl *ND = Corrected.getCorrectionDecl(); 7479 R.setLookupName(Corrected.getCorrection()); 7480 R.addDecl(ND); 7481 // We reject candidates where DroppedSpecifier == true, hence the 7482 // literal '0' below. 7483 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 7484 << NameInfo.getName() << LookupContext << 0 7485 << SS.getRange()); 7486 } else { 7487 Diag(IdentLoc, diag::err_no_member) 7488 << NameInfo.getName() << LookupContext << SS.getRange(); 7489 UD->setInvalidDecl(); 7490 return UD; 7491 } 7492 } 7493 7494 if (R.isAmbiguous()) { 7495 UD->setInvalidDecl(); 7496 return UD; 7497 } 7498 7499 if (HasTypenameKeyword) { 7500 // If we asked for a typename and got a non-type decl, error out. 7501 if (!R.getAsSingle<TypeDecl>()) { 7502 Diag(IdentLoc, diag::err_using_typename_non_type); 7503 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7504 Diag((*I)->getUnderlyingDecl()->getLocation(), 7505 diag::note_using_decl_target); 7506 UD->setInvalidDecl(); 7507 return UD; 7508 } 7509 } else { 7510 // If we asked for a non-typename and we got a type, error out, 7511 // but only if this is an instantiation of an unresolved using 7512 // decl. Otherwise just silently find the type name. 7513 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7514 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7515 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7516 UD->setInvalidDecl(); 7517 return UD; 7518 } 7519 } 7520 7521 // C++0x N2914 [namespace.udecl]p6: 7522 // A using-declaration shall not name a namespace. 7523 if (R.getAsSingle<NamespaceDecl>()) { 7524 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7525 << SS.getRange(); 7526 UD->setInvalidDecl(); 7527 return UD; 7528 } 7529 7530 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7531 UsingShadowDecl *PrevDecl = 0; 7532 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 7533 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 7534 } 7535 7536 return UD; 7537 } 7538 7539 /// Additional checks for a using declaration referring to a constructor name. 7540 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7541 assert(!UD->hasTypename() && "expecting a constructor name"); 7542 7543 const Type *SourceType = UD->getQualifier()->getAsType(); 7544 assert(SourceType && 7545 "Using decl naming constructor doesn't have type in scope spec."); 7546 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7547 7548 // Check whether the named type is a direct base class. 7549 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 7550 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 7551 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 7552 BaseIt != BaseE; ++BaseIt) { 7553 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 7554 if (CanonicalSourceType == BaseType) 7555 break; 7556 if (BaseIt->getType()->isDependentType()) 7557 break; 7558 } 7559 7560 if (BaseIt == BaseE) { 7561 // Did not find SourceType in the bases. 7562 Diag(UD->getUsingLoc(), 7563 diag::err_using_decl_constructor_not_in_direct_base) 7564 << UD->getNameInfo().getSourceRange() 7565 << QualType(SourceType, 0) << TargetClass; 7566 return true; 7567 } 7568 7569 if (!CurContext->isDependentContext()) 7570 BaseIt->setInheritConstructors(); 7571 7572 return false; 7573 } 7574 7575 /// Checks that the given using declaration is not an invalid 7576 /// redeclaration. Note that this is checking only for the using decl 7577 /// itself, not for any ill-formedness among the UsingShadowDecls. 7578 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7579 bool HasTypenameKeyword, 7580 const CXXScopeSpec &SS, 7581 SourceLocation NameLoc, 7582 const LookupResult &Prev) { 7583 // C++03 [namespace.udecl]p8: 7584 // C++0x [namespace.udecl]p10: 7585 // A using-declaration is a declaration and can therefore be used 7586 // repeatedly where (and only where) multiple declarations are 7587 // allowed. 7588 // 7589 // That's in non-member contexts. 7590 if (!CurContext->getRedeclContext()->isRecord()) 7591 return false; 7592 7593 NestedNameSpecifier *Qual = SS.getScopeRep(); 7594 7595 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7596 NamedDecl *D = *I; 7597 7598 bool DTypename; 7599 NestedNameSpecifier *DQual; 7600 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7601 DTypename = UD->hasTypename(); 7602 DQual = UD->getQualifier(); 7603 } else if (UnresolvedUsingValueDecl *UD 7604 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7605 DTypename = false; 7606 DQual = UD->getQualifier(); 7607 } else if (UnresolvedUsingTypenameDecl *UD 7608 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7609 DTypename = true; 7610 DQual = UD->getQualifier(); 7611 } else continue; 7612 7613 // using decls differ if one says 'typename' and the other doesn't. 7614 // FIXME: non-dependent using decls? 7615 if (HasTypenameKeyword != DTypename) continue; 7616 7617 // using decls differ if they name different scopes (but note that 7618 // template instantiation can cause this check to trigger when it 7619 // didn't before instantiation). 7620 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7621 Context.getCanonicalNestedNameSpecifier(DQual)) 7622 continue; 7623 7624 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7625 Diag(D->getLocation(), diag::note_using_decl) << 1; 7626 return true; 7627 } 7628 7629 return false; 7630 } 7631 7632 7633 /// Checks that the given nested-name qualifier used in a using decl 7634 /// in the current context is appropriately related to the current 7635 /// scope. If an error is found, diagnoses it and returns true. 7636 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7637 const CXXScopeSpec &SS, 7638 const DeclarationNameInfo &NameInfo, 7639 SourceLocation NameLoc) { 7640 DeclContext *NamedContext = computeDeclContext(SS); 7641 7642 if (!CurContext->isRecord()) { 7643 // C++03 [namespace.udecl]p3: 7644 // C++0x [namespace.udecl]p8: 7645 // A using-declaration for a class member shall be a member-declaration. 7646 7647 // If we weren't able to compute a valid scope, it must be a 7648 // dependent class scope. 7649 if (!NamedContext || NamedContext->isRecord()) { 7650 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext); 7651 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 7652 RD = 0; 7653 7654 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7655 << SS.getRange(); 7656 7657 // If we have a complete, non-dependent source type, try to suggest a 7658 // way to get the same effect. 7659 if (!RD) 7660 return true; 7661 7662 // Find what this using-declaration was referring to. 7663 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7664 R.setHideTags(false); 7665 R.suppressDiagnostics(); 7666 LookupQualifiedName(R, RD); 7667 7668 if (R.getAsSingle<TypeDecl>()) { 7669 if (getLangOpts().CPlusPlus11) { 7670 // Convert 'using X::Y;' to 'using Y = X::Y;'. 7671 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 7672 << 0 // alias declaration 7673 << FixItHint::CreateInsertion(SS.getBeginLoc(), 7674 NameInfo.getName().getAsString() + 7675 " = "); 7676 } else { 7677 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 7678 SourceLocation InsertLoc = 7679 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 7680 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 7681 << 1 // typedef declaration 7682 << FixItHint::CreateReplacement(UsingLoc, "typedef") 7683 << FixItHint::CreateInsertion( 7684 InsertLoc, " " + NameInfo.getName().getAsString()); 7685 } 7686 } else if (R.getAsSingle<VarDecl>()) { 7687 // Don't provide a fixit outside C++11 mode; we don't want to suggest 7688 // repeating the type of the static data member here. 7689 FixItHint FixIt; 7690 if (getLangOpts().CPlusPlus11) { 7691 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 7692 FixIt = FixItHint::CreateReplacement( 7693 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 7694 } 7695 7696 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 7697 << 2 // reference declaration 7698 << FixIt; 7699 } 7700 return true; 7701 } 7702 7703 // Otherwise, everything is known to be fine. 7704 return false; 7705 } 7706 7707 // The current scope is a record. 7708 7709 // If the named context is dependent, we can't decide much. 7710 if (!NamedContext) { 7711 // FIXME: in C++0x, we can diagnose if we can prove that the 7712 // nested-name-specifier does not refer to a base class, which is 7713 // still possible in some cases. 7714 7715 // Otherwise we have to conservatively report that things might be 7716 // okay. 7717 return false; 7718 } 7719 7720 if (!NamedContext->isRecord()) { 7721 // Ideally this would point at the last name in the specifier, 7722 // but we don't have that level of source info. 7723 Diag(SS.getRange().getBegin(), 7724 diag::err_using_decl_nested_name_specifier_is_not_class) 7725 << SS.getScopeRep() << SS.getRange(); 7726 return true; 7727 } 7728 7729 if (!NamedContext->isDependentContext() && 7730 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7731 return true; 7732 7733 if (getLangOpts().CPlusPlus11) { 7734 // C++0x [namespace.udecl]p3: 7735 // In a using-declaration used as a member-declaration, the 7736 // nested-name-specifier shall name a base class of the class 7737 // being defined. 7738 7739 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7740 cast<CXXRecordDecl>(NamedContext))) { 7741 if (CurContext == NamedContext) { 7742 Diag(NameLoc, 7743 diag::err_using_decl_nested_name_specifier_is_current_class) 7744 << SS.getRange(); 7745 return true; 7746 } 7747 7748 Diag(SS.getRange().getBegin(), 7749 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7750 << SS.getScopeRep() 7751 << cast<CXXRecordDecl>(CurContext) 7752 << SS.getRange(); 7753 return true; 7754 } 7755 7756 return false; 7757 } 7758 7759 // C++03 [namespace.udecl]p4: 7760 // A using-declaration used as a member-declaration shall refer 7761 // to a member of a base class of the class being defined [etc.]. 7762 7763 // Salient point: SS doesn't have to name a base class as long as 7764 // lookup only finds members from base classes. Therefore we can 7765 // diagnose here only if we can prove that that can't happen, 7766 // i.e. if the class hierarchies provably don't intersect. 7767 7768 // TODO: it would be nice if "definitely valid" results were cached 7769 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7770 // need to be repeated. 7771 7772 struct UserData { 7773 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7774 7775 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7776 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7777 Data->Bases.insert(Base); 7778 return true; 7779 } 7780 7781 bool hasDependentBases(const CXXRecordDecl *Class) { 7782 return !Class->forallBases(collect, this); 7783 } 7784 7785 /// Returns true if the base is dependent or is one of the 7786 /// accumulated base classes. 7787 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7788 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7789 return !Data->Bases.count(Base); 7790 } 7791 7792 bool mightShareBases(const CXXRecordDecl *Class) { 7793 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7794 } 7795 }; 7796 7797 UserData Data; 7798 7799 // Returns false if we find a dependent base. 7800 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7801 return false; 7802 7803 // Returns false if the class has a dependent base or if it or one 7804 // of its bases is present in the base set of the current context. 7805 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7806 return false; 7807 7808 Diag(SS.getRange().getBegin(), 7809 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7810 << SS.getScopeRep() 7811 << cast<CXXRecordDecl>(CurContext) 7812 << SS.getRange(); 7813 7814 return true; 7815 } 7816 7817 Decl *Sema::ActOnAliasDeclaration(Scope *S, 7818 AccessSpecifier AS, 7819 MultiTemplateParamsArg TemplateParamLists, 7820 SourceLocation UsingLoc, 7821 UnqualifiedId &Name, 7822 AttributeList *AttrList, 7823 TypeResult Type) { 7824 // Skip up to the relevant declaration scope. 7825 while (S->getFlags() & Scope::TemplateParamScope) 7826 S = S->getParent(); 7827 assert((S->getFlags() & Scope::DeclScope) && 7828 "got alias-declaration outside of declaration scope"); 7829 7830 if (Type.isInvalid()) 7831 return 0; 7832 7833 bool Invalid = false; 7834 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7835 TypeSourceInfo *TInfo = 0; 7836 GetTypeFromParser(Type.get(), &TInfo); 7837 7838 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7839 return 0; 7840 7841 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7842 UPPC_DeclarationType)) { 7843 Invalid = true; 7844 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7845 TInfo->getTypeLoc().getBeginLoc()); 7846 } 7847 7848 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7849 LookupName(Previous, S); 7850 7851 // Warn about shadowing the name of a template parameter. 7852 if (Previous.isSingleResult() && 7853 Previous.getFoundDecl()->isTemplateParameter()) { 7854 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7855 Previous.clear(); 7856 } 7857 7858 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7859 "name in alias declaration must be an identifier"); 7860 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7861 Name.StartLocation, 7862 Name.Identifier, TInfo); 7863 7864 NewTD->setAccess(AS); 7865 7866 if (Invalid) 7867 NewTD->setInvalidDecl(); 7868 7869 ProcessDeclAttributeList(S, NewTD, AttrList); 7870 7871 CheckTypedefForVariablyModifiedType(S, NewTD); 7872 Invalid |= NewTD->isInvalidDecl(); 7873 7874 bool Redeclaration = false; 7875 7876 NamedDecl *NewND; 7877 if (TemplateParamLists.size()) { 7878 TypeAliasTemplateDecl *OldDecl = 0; 7879 TemplateParameterList *OldTemplateParams = 0; 7880 7881 if (TemplateParamLists.size() != 1) { 7882 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7883 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7884 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7885 } 7886 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7887 7888 // Only consider previous declarations in the same scope. 7889 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7890 /*ExplicitInstantiationOrSpecialization*/false); 7891 if (!Previous.empty()) { 7892 Redeclaration = true; 7893 7894 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7895 if (!OldDecl && !Invalid) { 7896 Diag(UsingLoc, diag::err_redefinition_different_kind) 7897 << Name.Identifier; 7898 7899 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7900 if (OldD->getLocation().isValid()) 7901 Diag(OldD->getLocation(), diag::note_previous_definition); 7902 7903 Invalid = true; 7904 } 7905 7906 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7907 if (TemplateParameterListsAreEqual(TemplateParams, 7908 OldDecl->getTemplateParameters(), 7909 /*Complain=*/true, 7910 TPL_TemplateMatch)) 7911 OldTemplateParams = OldDecl->getTemplateParameters(); 7912 else 7913 Invalid = true; 7914 7915 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7916 if (!Invalid && 7917 !Context.hasSameType(OldTD->getUnderlyingType(), 7918 NewTD->getUnderlyingType())) { 7919 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7920 // but we can't reasonably accept it. 7921 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7922 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7923 if (OldTD->getLocation().isValid()) 7924 Diag(OldTD->getLocation(), diag::note_previous_definition); 7925 Invalid = true; 7926 } 7927 } 7928 } 7929 7930 // Merge any previous default template arguments into our parameters, 7931 // and check the parameter list. 7932 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7933 TPC_TypeAliasTemplate)) 7934 return 0; 7935 7936 TypeAliasTemplateDecl *NewDecl = 7937 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7938 Name.Identifier, TemplateParams, 7939 NewTD); 7940 7941 NewDecl->setAccess(AS); 7942 7943 if (Invalid) 7944 NewDecl->setInvalidDecl(); 7945 else if (OldDecl) 7946 NewDecl->setPreviousDecl(OldDecl); 7947 7948 NewND = NewDecl; 7949 } else { 7950 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7951 NewND = NewTD; 7952 } 7953 7954 if (!Redeclaration) 7955 PushOnScopeChains(NewND, S); 7956 7957 ActOnDocumentableDecl(NewND); 7958 return NewND; 7959 } 7960 7961 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7962 SourceLocation NamespaceLoc, 7963 SourceLocation AliasLoc, 7964 IdentifierInfo *Alias, 7965 CXXScopeSpec &SS, 7966 SourceLocation IdentLoc, 7967 IdentifierInfo *Ident) { 7968 7969 // Lookup the namespace name. 7970 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7971 LookupParsedName(R, S, &SS); 7972 7973 // Check if we have a previous declaration with the same name. 7974 NamedDecl *PrevDecl 7975 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7976 ForRedeclaration); 7977 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7978 PrevDecl = 0; 7979 7980 if (PrevDecl) { 7981 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7982 // We already have an alias with the same name that points to the same 7983 // namespace, so don't create a new one. 7984 // FIXME: At some point, we'll want to create the (redundant) 7985 // declaration to maintain better source information. 7986 if (!R.isAmbiguous() && !R.empty() && 7987 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7988 return 0; 7989 } 7990 7991 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7992 diag::err_redefinition_different_kind; 7993 Diag(AliasLoc, DiagID) << Alias; 7994 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7995 return 0; 7996 } 7997 7998 if (R.isAmbiguous()) 7999 return 0; 8000 8001 if (R.empty()) { 8002 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 8003 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 8004 return 0; 8005 } 8006 } 8007 8008 NamespaceAliasDecl *AliasDecl = 8009 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8010 Alias, SS.getWithLocInContext(Context), 8011 IdentLoc, R.getFoundDecl()); 8012 8013 PushOnScopeChains(AliasDecl, S); 8014 return AliasDecl; 8015 } 8016 8017 Sema::ImplicitExceptionSpecification 8018 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8019 CXXMethodDecl *MD) { 8020 CXXRecordDecl *ClassDecl = MD->getParent(); 8021 8022 // C++ [except.spec]p14: 8023 // An implicitly declared special member function (Clause 12) shall have an 8024 // exception-specification. [...] 8025 ImplicitExceptionSpecification ExceptSpec(*this); 8026 if (ClassDecl->isInvalidDecl()) 8027 return ExceptSpec; 8028 8029 // Direct base-class constructors. 8030 for (const auto &B : ClassDecl->bases()) { 8031 if (B.isVirtual()) // Handled below. 8032 continue; 8033 8034 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8035 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8036 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8037 // If this is a deleted function, add it anyway. This might be conformant 8038 // with the standard. This might not. I'm not sure. It might not matter. 8039 if (Constructor) 8040 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8041 } 8042 } 8043 8044 // Virtual base-class constructors. 8045 for (const auto &B : ClassDecl->vbases()) { 8046 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8047 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8048 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8049 // If this is a deleted function, add it anyway. This might be conformant 8050 // with the standard. This might not. I'm not sure. It might not matter. 8051 if (Constructor) 8052 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8053 } 8054 } 8055 8056 // Field constructors. 8057 for (const auto *F : ClassDecl->fields()) { 8058 if (F->hasInClassInitializer()) { 8059 if (Expr *E = F->getInClassInitializer()) 8060 ExceptSpec.CalledExpr(E); 8061 else if (!F->isInvalidDecl()) 8062 // DR1351: 8063 // If the brace-or-equal-initializer of a non-static data member 8064 // invokes a defaulted default constructor of its class or of an 8065 // enclosing class in a potentially evaluated subexpression, the 8066 // program is ill-formed. 8067 // 8068 // This resolution is unworkable: the exception specification of the 8069 // default constructor can be needed in an unevaluated context, in 8070 // particular, in the operand of a noexcept-expression, and we can be 8071 // unable to compute an exception specification for an enclosed class. 8072 // 8073 // We do not allow an in-class initializer to require the evaluation 8074 // of the exception specification for any in-class initializer whose 8075 // definition is not lexically complete. 8076 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 8077 } else if (const RecordType *RecordTy 8078 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8079 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8080 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8081 // If this is a deleted function, add it anyway. This might be conformant 8082 // with the standard. This might not. I'm not sure. It might not matter. 8083 // In particular, the problem is that this function never gets called. It 8084 // might just be ill-formed because this function attempts to refer to 8085 // a deleted function here. 8086 if (Constructor) 8087 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8088 } 8089 } 8090 8091 return ExceptSpec; 8092 } 8093 8094 Sema::ImplicitExceptionSpecification 8095 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8096 CXXRecordDecl *ClassDecl = CD->getParent(); 8097 8098 // C++ [except.spec]p14: 8099 // An inheriting constructor [...] shall have an exception-specification. [...] 8100 ImplicitExceptionSpecification ExceptSpec(*this); 8101 if (ClassDecl->isInvalidDecl()) 8102 return ExceptSpec; 8103 8104 // Inherited constructor. 8105 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8106 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8107 // FIXME: Copying or moving the parameters could add extra exceptions to the 8108 // set, as could the default arguments for the inherited constructor. This 8109 // will be addressed when we implement the resolution of core issue 1351. 8110 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8111 8112 // Direct base-class constructors. 8113 for (const auto &B : ClassDecl->bases()) { 8114 if (B.isVirtual()) // Handled below. 8115 continue; 8116 8117 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8118 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8119 if (BaseClassDecl == InheritedDecl) 8120 continue; 8121 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8122 if (Constructor) 8123 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8124 } 8125 } 8126 8127 // Virtual base-class constructors. 8128 for (const auto &B : ClassDecl->vbases()) { 8129 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8130 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8131 if (BaseClassDecl == InheritedDecl) 8132 continue; 8133 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8134 if (Constructor) 8135 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8136 } 8137 } 8138 8139 // Field constructors. 8140 for (const auto *F : ClassDecl->fields()) { 8141 if (F->hasInClassInitializer()) { 8142 if (Expr *E = F->getInClassInitializer()) 8143 ExceptSpec.CalledExpr(E); 8144 else if (!F->isInvalidDecl()) 8145 Diag(CD->getLocation(), 8146 diag::err_in_class_initializer_references_def_ctor) << CD; 8147 } else if (const RecordType *RecordTy 8148 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8149 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8150 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8151 if (Constructor) 8152 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8153 } 8154 } 8155 8156 return ExceptSpec; 8157 } 8158 8159 namespace { 8160 /// RAII object to register a special member as being currently declared. 8161 struct DeclaringSpecialMember { 8162 Sema &S; 8163 Sema::SpecialMemberDecl D; 8164 bool WasAlreadyBeingDeclared; 8165 8166 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8167 : S(S), D(RD, CSM) { 8168 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 8169 if (WasAlreadyBeingDeclared) 8170 // This almost never happens, but if it does, ensure that our cache 8171 // doesn't contain a stale result. 8172 S.SpecialMemberCache.clear(); 8173 8174 // FIXME: Register a note to be produced if we encounter an error while 8175 // declaring the special member. 8176 } 8177 ~DeclaringSpecialMember() { 8178 if (!WasAlreadyBeingDeclared) 8179 S.SpecialMembersBeingDeclared.erase(D); 8180 } 8181 8182 /// \brief Are we already trying to declare this special member? 8183 bool isAlreadyBeingDeclared() const { 8184 return WasAlreadyBeingDeclared; 8185 } 8186 }; 8187 } 8188 8189 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8190 CXXRecordDecl *ClassDecl) { 8191 // C++ [class.ctor]p5: 8192 // A default constructor for a class X is a constructor of class X 8193 // that can be called without an argument. If there is no 8194 // user-declared constructor for class X, a default constructor is 8195 // implicitly declared. An implicitly-declared default constructor 8196 // is an inline public member of its class. 8197 assert(ClassDecl->needsImplicitDefaultConstructor() && 8198 "Should not build implicit default constructor!"); 8199 8200 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8201 if (DSM.isAlreadyBeingDeclared()) 8202 return 0; 8203 8204 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8205 CXXDefaultConstructor, 8206 false); 8207 8208 // Create the actual constructor declaration. 8209 CanQualType ClassType 8210 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8211 SourceLocation ClassLoc = ClassDecl->getLocation(); 8212 DeclarationName Name 8213 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8214 DeclarationNameInfo NameInfo(Name, ClassLoc); 8215 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8216 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 8217 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8218 Constexpr); 8219 DefaultCon->setAccess(AS_public); 8220 DefaultCon->setDefaulted(); 8221 DefaultCon->setImplicit(); 8222 8223 // Build an exception specification pointing back at this constructor. 8224 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8225 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8226 8227 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8228 // constructors is easy to compute. 8229 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8230 8231 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8232 SetDeclDeleted(DefaultCon, ClassLoc); 8233 8234 // Note that we have declared this constructor. 8235 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8236 8237 if (Scope *S = getScopeForContext(ClassDecl)) 8238 PushOnScopeChains(DefaultCon, S, false); 8239 ClassDecl->addDecl(DefaultCon); 8240 8241 return DefaultCon; 8242 } 8243 8244 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8245 CXXConstructorDecl *Constructor) { 8246 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8247 !Constructor->doesThisDeclarationHaveABody() && 8248 !Constructor->isDeleted()) && 8249 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8250 8251 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8252 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8253 8254 SynthesizedFunctionScope Scope(*this, Constructor); 8255 DiagnosticErrorTrap Trap(Diags); 8256 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8257 Trap.hasErrorOccurred()) { 8258 Diag(CurrentLocation, diag::note_member_synthesized_at) 8259 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8260 Constructor->setInvalidDecl(); 8261 return; 8262 } 8263 8264 SourceLocation Loc = Constructor->getLocation(); 8265 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8266 8267 Constructor->markUsed(Context); 8268 MarkVTableUsed(CurrentLocation, ClassDecl); 8269 8270 if (ASTMutationListener *L = getASTMutationListener()) { 8271 L->CompletedImplicitDefinition(Constructor); 8272 } 8273 8274 DiagnoseUninitializedFields(*this, Constructor); 8275 } 8276 8277 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8278 // Perform any delayed checks on exception specifications. 8279 CheckDelayedMemberExceptionSpecs(); 8280 } 8281 8282 namespace { 8283 /// Information on inheriting constructors to declare. 8284 class InheritingConstructorInfo { 8285 public: 8286 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8287 : SemaRef(SemaRef), Derived(Derived) { 8288 // Mark the constructors that we already have in the derived class. 8289 // 8290 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8291 // unless there is a user-declared constructor with the same signature in 8292 // the class where the using-declaration appears. 8293 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8294 } 8295 8296 void inheritAll(CXXRecordDecl *RD) { 8297 visitAll(RD, &InheritingConstructorInfo::inherit); 8298 } 8299 8300 private: 8301 /// Information about an inheriting constructor. 8302 struct InheritingConstructor { 8303 InheritingConstructor() 8304 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {} 8305 8306 /// If \c true, a constructor with this signature is already declared 8307 /// in the derived class. 8308 bool DeclaredInDerived; 8309 8310 /// The constructor which is inherited. 8311 const CXXConstructorDecl *BaseCtor; 8312 8313 /// The derived constructor we declared. 8314 CXXConstructorDecl *DerivedCtor; 8315 }; 8316 8317 /// Inheriting constructors with a given canonical type. There can be at 8318 /// most one such non-template constructor, and any number of templated 8319 /// constructors. 8320 struct InheritingConstructorsForType { 8321 InheritingConstructor NonTemplate; 8322 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8323 Templates; 8324 8325 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8326 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8327 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8328 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8329 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8330 false, S.TPL_TemplateMatch)) 8331 return Templates[I].second; 8332 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8333 return Templates.back().second; 8334 } 8335 8336 return NonTemplate; 8337 } 8338 }; 8339 8340 /// Get or create the inheriting constructor record for a constructor. 8341 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8342 QualType CtorType) { 8343 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8344 .getEntry(SemaRef, Ctor); 8345 } 8346 8347 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8348 8349 /// Process all constructors for a class. 8350 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8351 for (const auto *Ctor : RD->ctors()) 8352 (this->*Callback)(Ctor); 8353 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8354 I(RD->decls_begin()), E(RD->decls_end()); 8355 I != E; ++I) { 8356 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8357 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8358 (this->*Callback)(CD); 8359 } 8360 } 8361 8362 /// Note that a constructor (or constructor template) was declared in Derived. 8363 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8364 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8365 } 8366 8367 /// Inherit a single constructor. 8368 void inherit(const CXXConstructorDecl *Ctor) { 8369 const FunctionProtoType *CtorType = 8370 Ctor->getType()->castAs<FunctionProtoType>(); 8371 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes()); 8372 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8373 8374 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8375 8376 // Core issue (no number yet): the ellipsis is always discarded. 8377 if (EPI.Variadic) { 8378 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8379 SemaRef.Diag(Ctor->getLocation(), 8380 diag::note_using_decl_constructor_ellipsis); 8381 EPI.Variadic = false; 8382 } 8383 8384 // Declare a constructor for each number of parameters. 8385 // 8386 // C++11 [class.inhctor]p1: 8387 // The candidate set of inherited constructors from the class X named in 8388 // the using-declaration consists of [... modulo defects ...] for each 8389 // constructor or constructor template of X, the set of constructors or 8390 // constructor templates that results from omitting any ellipsis parameter 8391 // specification and successively omitting parameters with a default 8392 // argument from the end of the parameter-type-list 8393 unsigned MinParams = minParamsToInherit(Ctor); 8394 unsigned Params = Ctor->getNumParams(); 8395 if (Params >= MinParams) { 8396 do 8397 declareCtor(UsingLoc, Ctor, 8398 SemaRef.Context.getFunctionType( 8399 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 8400 while (Params > MinParams && 8401 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8402 } 8403 } 8404 8405 /// Find the using-declaration which specified that we should inherit the 8406 /// constructors of \p Base. 8407 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8408 // No fancy lookup required; just look for the base constructor name 8409 // directly within the derived class. 8410 ASTContext &Context = SemaRef.Context; 8411 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8412 Context.getCanonicalType(Context.getRecordType(Base))); 8413 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8414 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8415 } 8416 8417 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8418 // C++11 [class.inhctor]p3: 8419 // [F]or each constructor template in the candidate set of inherited 8420 // constructors, a constructor template is implicitly declared 8421 if (Ctor->getDescribedFunctionTemplate()) 8422 return 0; 8423 8424 // For each non-template constructor in the candidate set of inherited 8425 // constructors other than a constructor having no parameters or a 8426 // copy/move constructor having a single parameter, a constructor is 8427 // implicitly declared [...] 8428 if (Ctor->getNumParams() == 0) 8429 return 1; 8430 if (Ctor->isCopyOrMoveConstructor()) 8431 return 2; 8432 8433 // Per discussion on core reflector, never inherit a constructor which 8434 // would become a default, copy, or move constructor of Derived either. 8435 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8436 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8437 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8438 } 8439 8440 /// Declare a single inheriting constructor, inheriting the specified 8441 /// constructor, with the given type. 8442 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8443 QualType DerivedType) { 8444 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8445 8446 // C++11 [class.inhctor]p3: 8447 // ... a constructor is implicitly declared with the same constructor 8448 // characteristics unless there is a user-declared constructor with 8449 // the same signature in the class where the using-declaration appears 8450 if (Entry.DeclaredInDerived) 8451 return; 8452 8453 // C++11 [class.inhctor]p7: 8454 // If two using-declarations declare inheriting constructors with the 8455 // same signature, the program is ill-formed 8456 if (Entry.DerivedCtor) { 8457 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8458 // Only diagnose this once per constructor. 8459 if (Entry.DerivedCtor->isInvalidDecl()) 8460 return; 8461 Entry.DerivedCtor->setInvalidDecl(); 8462 8463 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8464 SemaRef.Diag(BaseCtor->getLocation(), 8465 diag::note_using_decl_constructor_conflict_current_ctor); 8466 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8467 diag::note_using_decl_constructor_conflict_previous_ctor); 8468 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8469 diag::note_using_decl_constructor_conflict_previous_using); 8470 } else { 8471 // Core issue (no number): if the same inheriting constructor is 8472 // produced by multiple base class constructors from the same base 8473 // class, the inheriting constructor is defined as deleted. 8474 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8475 } 8476 8477 return; 8478 } 8479 8480 ASTContext &Context = SemaRef.Context; 8481 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8482 Context.getCanonicalType(Context.getRecordType(Derived))); 8483 DeclarationNameInfo NameInfo(Name, UsingLoc); 8484 8485 TemplateParameterList *TemplateParams = 0; 8486 if (const FunctionTemplateDecl *FTD = 8487 BaseCtor->getDescribedFunctionTemplate()) { 8488 TemplateParams = FTD->getTemplateParameters(); 8489 // We're reusing template parameters from a different DeclContext. This 8490 // is questionable at best, but works out because the template depth in 8491 // both places is guaranteed to be 0. 8492 // FIXME: Rebuild the template parameters in the new context, and 8493 // transform the function type to refer to them. 8494 } 8495 8496 // Build type source info pointing at the using-declaration. This is 8497 // required by template instantiation. 8498 TypeSourceInfo *TInfo = 8499 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8500 FunctionProtoTypeLoc ProtoLoc = 8501 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8502 8503 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8504 Context, Derived, UsingLoc, NameInfo, DerivedType, 8505 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8506 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8507 8508 // Build an unevaluated exception specification for this constructor. 8509 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8510 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8511 EPI.ExceptionSpecType = EST_Unevaluated; 8512 EPI.ExceptionSpecDecl = DerivedCtor; 8513 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 8514 FPT->getParamTypes(), EPI)); 8515 8516 // Build the parameter declarations. 8517 SmallVector<ParmVarDecl *, 16> ParamDecls; 8518 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 8519 TypeSourceInfo *TInfo = 8520 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 8521 ParmVarDecl *PD = ParmVarDecl::Create( 8522 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0, 8523 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/0); 8524 PD->setScopeInfo(0, I); 8525 PD->setImplicit(); 8526 ParamDecls.push_back(PD); 8527 ProtoLoc.setParam(I, PD); 8528 } 8529 8530 // Set up the new constructor. 8531 DerivedCtor->setAccess(BaseCtor->getAccess()); 8532 DerivedCtor->setParams(ParamDecls); 8533 DerivedCtor->setInheritedConstructor(BaseCtor); 8534 if (BaseCtor->isDeleted()) 8535 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8536 8537 // If this is a constructor template, build the template declaration. 8538 if (TemplateParams) { 8539 FunctionTemplateDecl *DerivedTemplate = 8540 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8541 TemplateParams, DerivedCtor); 8542 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8543 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8544 Derived->addDecl(DerivedTemplate); 8545 } else { 8546 Derived->addDecl(DerivedCtor); 8547 } 8548 8549 Entry.BaseCtor = BaseCtor; 8550 Entry.DerivedCtor = DerivedCtor; 8551 } 8552 8553 Sema &SemaRef; 8554 CXXRecordDecl *Derived; 8555 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8556 MapType Map; 8557 }; 8558 } 8559 8560 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8561 // Defer declaring the inheriting constructors until the class is 8562 // instantiated. 8563 if (ClassDecl->isDependentContext()) 8564 return; 8565 8566 // Find base classes from which we might inherit constructors. 8567 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8568 for (const auto &BaseIt : ClassDecl->bases()) 8569 if (BaseIt.getInheritConstructors()) 8570 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 8571 8572 // Go no further if we're not inheriting any constructors. 8573 if (InheritedBases.empty()) 8574 return; 8575 8576 // Declare the inherited constructors. 8577 InheritingConstructorInfo ICI(*this, ClassDecl); 8578 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8579 ICI.inheritAll(InheritedBases[I]); 8580 } 8581 8582 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8583 CXXConstructorDecl *Constructor) { 8584 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8585 assert(Constructor->getInheritedConstructor() && 8586 !Constructor->doesThisDeclarationHaveABody() && 8587 !Constructor->isDeleted()); 8588 8589 SynthesizedFunctionScope Scope(*this, Constructor); 8590 DiagnosticErrorTrap Trap(Diags); 8591 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8592 Trap.hasErrorOccurred()) { 8593 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8594 << Context.getTagDeclType(ClassDecl); 8595 Constructor->setInvalidDecl(); 8596 return; 8597 } 8598 8599 SourceLocation Loc = Constructor->getLocation(); 8600 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8601 8602 Constructor->markUsed(Context); 8603 MarkVTableUsed(CurrentLocation, ClassDecl); 8604 8605 if (ASTMutationListener *L = getASTMutationListener()) { 8606 L->CompletedImplicitDefinition(Constructor); 8607 } 8608 } 8609 8610 8611 Sema::ImplicitExceptionSpecification 8612 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8613 CXXRecordDecl *ClassDecl = MD->getParent(); 8614 8615 // C++ [except.spec]p14: 8616 // An implicitly declared special member function (Clause 12) shall have 8617 // an exception-specification. 8618 ImplicitExceptionSpecification ExceptSpec(*this); 8619 if (ClassDecl->isInvalidDecl()) 8620 return ExceptSpec; 8621 8622 // Direct base-class destructors. 8623 for (const auto &B : ClassDecl->bases()) { 8624 if (B.isVirtual()) // Handled below. 8625 continue; 8626 8627 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 8628 ExceptSpec.CalledDecl(B.getLocStart(), 8629 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8630 } 8631 8632 // Virtual base-class destructors. 8633 for (const auto &B : ClassDecl->vbases()) { 8634 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 8635 ExceptSpec.CalledDecl(B.getLocStart(), 8636 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8637 } 8638 8639 // Field destructors. 8640 for (const auto *F : ClassDecl->fields()) { 8641 if (const RecordType *RecordTy 8642 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8643 ExceptSpec.CalledDecl(F->getLocation(), 8644 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8645 } 8646 8647 return ExceptSpec; 8648 } 8649 8650 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8651 // C++ [class.dtor]p2: 8652 // If a class has no user-declared destructor, a destructor is 8653 // declared implicitly. An implicitly-declared destructor is an 8654 // inline public member of its class. 8655 assert(ClassDecl->needsImplicitDestructor()); 8656 8657 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8658 if (DSM.isAlreadyBeingDeclared()) 8659 return 0; 8660 8661 // Create the actual destructor declaration. 8662 CanQualType ClassType 8663 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8664 SourceLocation ClassLoc = ClassDecl->getLocation(); 8665 DeclarationName Name 8666 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8667 DeclarationNameInfo NameInfo(Name, ClassLoc); 8668 CXXDestructorDecl *Destructor 8669 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8670 QualType(), 0, /*isInline=*/true, 8671 /*isImplicitlyDeclared=*/true); 8672 Destructor->setAccess(AS_public); 8673 Destructor->setDefaulted(); 8674 Destructor->setImplicit(); 8675 8676 // Build an exception specification pointing back at this destructor. 8677 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 8678 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8679 8680 AddOverriddenMethods(ClassDecl, Destructor); 8681 8682 // We don't need to use SpecialMemberIsTrivial here; triviality for 8683 // destructors is easy to compute. 8684 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8685 8686 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8687 SetDeclDeleted(Destructor, ClassLoc); 8688 8689 // Note that we have declared this destructor. 8690 ++ASTContext::NumImplicitDestructorsDeclared; 8691 8692 // Introduce this destructor into its scope. 8693 if (Scope *S = getScopeForContext(ClassDecl)) 8694 PushOnScopeChains(Destructor, S, false); 8695 ClassDecl->addDecl(Destructor); 8696 8697 return Destructor; 8698 } 8699 8700 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8701 CXXDestructorDecl *Destructor) { 8702 assert((Destructor->isDefaulted() && 8703 !Destructor->doesThisDeclarationHaveABody() && 8704 !Destructor->isDeleted()) && 8705 "DefineImplicitDestructor - call it for implicit default dtor"); 8706 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8707 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8708 8709 if (Destructor->isInvalidDecl()) 8710 return; 8711 8712 SynthesizedFunctionScope Scope(*this, Destructor); 8713 8714 DiagnosticErrorTrap Trap(Diags); 8715 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8716 Destructor->getParent()); 8717 8718 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8719 Diag(CurrentLocation, diag::note_member_synthesized_at) 8720 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8721 8722 Destructor->setInvalidDecl(); 8723 return; 8724 } 8725 8726 SourceLocation Loc = Destructor->getLocation(); 8727 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8728 Destructor->markUsed(Context); 8729 MarkVTableUsed(CurrentLocation, ClassDecl); 8730 8731 if (ASTMutationListener *L = getASTMutationListener()) { 8732 L->CompletedImplicitDefinition(Destructor); 8733 } 8734 } 8735 8736 /// \brief Perform any semantic analysis which needs to be delayed until all 8737 /// pending class member declarations have been parsed. 8738 void Sema::ActOnFinishCXXMemberDecls() { 8739 // If the context is an invalid C++ class, just suppress these checks. 8740 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8741 if (Record->isInvalidDecl()) { 8742 DelayedDefaultedMemberExceptionSpecs.clear(); 8743 DelayedDestructorExceptionSpecChecks.clear(); 8744 return; 8745 } 8746 } 8747 } 8748 8749 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8750 CXXDestructorDecl *Destructor) { 8751 assert(getLangOpts().CPlusPlus11 && 8752 "adjusting dtor exception specs was introduced in c++11"); 8753 8754 // C++11 [class.dtor]p3: 8755 // A declaration of a destructor that does not have an exception- 8756 // specification is implicitly considered to have the same exception- 8757 // specification as an implicit declaration. 8758 const FunctionProtoType *DtorType = Destructor->getType()-> 8759 getAs<FunctionProtoType>(); 8760 if (DtorType->hasExceptionSpec()) 8761 return; 8762 8763 // Replace the destructor's type, building off the existing one. Fortunately, 8764 // the only thing of interest in the destructor type is its extended info. 8765 // The return and arguments are fixed. 8766 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8767 EPI.ExceptionSpecType = EST_Unevaluated; 8768 EPI.ExceptionSpecDecl = Destructor; 8769 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8770 8771 // FIXME: If the destructor has a body that could throw, and the newly created 8772 // spec doesn't allow exceptions, we should emit a warning, because this 8773 // change in behavior can break conforming C++03 programs at runtime. 8774 // However, we don't have a body or an exception specification yet, so it 8775 // needs to be done somewhere else. 8776 } 8777 8778 namespace { 8779 /// \brief An abstract base class for all helper classes used in building the 8780 // copy/move operators. These classes serve as factory functions and help us 8781 // avoid using the same Expr* in the AST twice. 8782 class ExprBuilder { 8783 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8784 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8785 8786 protected: 8787 static Expr *assertNotNull(Expr *E) { 8788 assert(E && "Expression construction must not fail."); 8789 return E; 8790 } 8791 8792 public: 8793 ExprBuilder() {} 8794 virtual ~ExprBuilder() {} 8795 8796 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 8797 }; 8798 8799 class RefBuilder: public ExprBuilder { 8800 VarDecl *Var; 8801 QualType VarType; 8802 8803 public: 8804 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8805 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take()); 8806 } 8807 8808 RefBuilder(VarDecl *Var, QualType VarType) 8809 : Var(Var), VarType(VarType) {} 8810 }; 8811 8812 class ThisBuilder: public ExprBuilder { 8813 public: 8814 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8815 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>()); 8816 } 8817 }; 8818 8819 class CastBuilder: public ExprBuilder { 8820 const ExprBuilder &Builder; 8821 QualType Type; 8822 ExprValueKind Kind; 8823 const CXXCastPath &Path; 8824 8825 public: 8826 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8827 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 8828 CK_UncheckedDerivedToBase, Kind, 8829 &Path).take()); 8830 } 8831 8832 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 8833 const CXXCastPath &Path) 8834 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 8835 }; 8836 8837 class DerefBuilder: public ExprBuilder { 8838 const ExprBuilder &Builder; 8839 8840 public: 8841 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8842 return assertNotNull( 8843 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take()); 8844 } 8845 8846 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8847 }; 8848 8849 class MemberBuilder: public ExprBuilder { 8850 const ExprBuilder &Builder; 8851 QualType Type; 8852 CXXScopeSpec SS; 8853 bool IsArrow; 8854 LookupResult &MemberLookup; 8855 8856 public: 8857 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8858 return assertNotNull(S.BuildMemberReferenceExpr( 8859 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0, 8860 MemberLookup, 0).take()); 8861 } 8862 8863 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 8864 LookupResult &MemberLookup) 8865 : Builder(Builder), Type(Type), IsArrow(IsArrow), 8866 MemberLookup(MemberLookup) {} 8867 }; 8868 8869 class MoveCastBuilder: public ExprBuilder { 8870 const ExprBuilder &Builder; 8871 8872 public: 8873 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8874 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 8875 } 8876 8877 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8878 }; 8879 8880 class LvalueConvBuilder: public ExprBuilder { 8881 const ExprBuilder &Builder; 8882 8883 public: 8884 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8885 return assertNotNull( 8886 S.DefaultLvalueConversion(Builder.build(S, Loc)).take()); 8887 } 8888 8889 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8890 }; 8891 8892 class SubscriptBuilder: public ExprBuilder { 8893 const ExprBuilder &Base; 8894 const ExprBuilder &Index; 8895 8896 public: 8897 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8898 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 8899 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take()); 8900 } 8901 8902 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 8903 : Base(Base), Index(Index) {} 8904 }; 8905 8906 } // end anonymous namespace 8907 8908 /// When generating a defaulted copy or move assignment operator, if a field 8909 /// should be copied with __builtin_memcpy rather than via explicit assignments, 8910 /// do so. This optimization only applies for arrays of scalars, and for arrays 8911 /// of class type where the selected copy/move-assignment operator is trivial. 8912 static StmtResult 8913 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 8914 const ExprBuilder &ToB, const ExprBuilder &FromB) { 8915 // Compute the size of the memory buffer to be copied. 8916 QualType SizeType = S.Context.getSizeType(); 8917 llvm::APInt Size(S.Context.getTypeSize(SizeType), 8918 S.Context.getTypeSizeInChars(T).getQuantity()); 8919 8920 // Take the address of the field references for "from" and "to". We 8921 // directly construct UnaryOperators here because semantic analysis 8922 // does not permit us to take the address of an xvalue. 8923 Expr *From = FromB.build(S, Loc); 8924 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 8925 S.Context.getPointerType(From->getType()), 8926 VK_RValue, OK_Ordinary, Loc); 8927 Expr *To = ToB.build(S, Loc); 8928 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 8929 S.Context.getPointerType(To->getType()), 8930 VK_RValue, OK_Ordinary, Loc); 8931 8932 const Type *E = T->getBaseElementTypeUnsafe(); 8933 bool NeedsCollectableMemCpy = 8934 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 8935 8936 // Create a reference to the __builtin_objc_memmove_collectable function 8937 StringRef MemCpyName = NeedsCollectableMemCpy ? 8938 "__builtin_objc_memmove_collectable" : 8939 "__builtin_memcpy"; 8940 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 8941 Sema::LookupOrdinaryName); 8942 S.LookupName(R, S.TUScope, true); 8943 8944 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 8945 if (!MemCpy) 8946 // Something went horribly wrong earlier, and we will have complained 8947 // about it. 8948 return StmtError(); 8949 8950 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 8951 VK_RValue, Loc, 0); 8952 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 8953 8954 Expr *CallArgs[] = { 8955 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 8956 }; 8957 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(), 8958 Loc, CallArgs, Loc); 8959 8960 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8961 return S.Owned(Call.takeAs<Stmt>()); 8962 } 8963 8964 /// \brief Builds a statement that copies/moves the given entity from \p From to 8965 /// \c To. 8966 /// 8967 /// This routine is used to copy/move the members of a class with an 8968 /// implicitly-declared copy/move assignment operator. When the entities being 8969 /// copied are arrays, this routine builds for loops to copy them. 8970 /// 8971 /// \param S The Sema object used for type-checking. 8972 /// 8973 /// \param Loc The location where the implicit copy/move is being generated. 8974 /// 8975 /// \param T The type of the expressions being copied/moved. Both expressions 8976 /// must have this type. 8977 /// 8978 /// \param To The expression we are copying/moving to. 8979 /// 8980 /// \param From The expression we are copying/moving from. 8981 /// 8982 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 8983 /// Otherwise, it's a non-static member subobject. 8984 /// 8985 /// \param Copying Whether we're copying or moving. 8986 /// 8987 /// \param Depth Internal parameter recording the depth of the recursion. 8988 /// 8989 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 8990 /// if a memcpy should be used instead. 8991 static StmtResult 8992 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 8993 const ExprBuilder &To, const ExprBuilder &From, 8994 bool CopyingBaseSubobject, bool Copying, 8995 unsigned Depth = 0) { 8996 // C++11 [class.copy]p28: 8997 // Each subobject is assigned in the manner appropriate to its type: 8998 // 8999 // - if the subobject is of class type, as if by a call to operator= with 9000 // the subobject as the object expression and the corresponding 9001 // subobject of x as a single function argument (as if by explicit 9002 // qualification; that is, ignoring any possible virtual overriding 9003 // functions in more derived classes); 9004 // 9005 // C++03 [class.copy]p13: 9006 // - if the subobject is of class type, the copy assignment operator for 9007 // the class is used (as if by explicit qualification; that is, 9008 // ignoring any possible virtual overriding functions in more derived 9009 // classes); 9010 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9011 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9012 9013 // Look for operator=. 9014 DeclarationName Name 9015 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9016 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9017 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9018 9019 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9020 // operator. 9021 if (!S.getLangOpts().CPlusPlus11) { 9022 LookupResult::Filter F = OpLookup.makeFilter(); 9023 while (F.hasNext()) { 9024 NamedDecl *D = F.next(); 9025 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9026 if (Method->isCopyAssignmentOperator() || 9027 (!Copying && Method->isMoveAssignmentOperator())) 9028 continue; 9029 9030 F.erase(); 9031 } 9032 F.done(); 9033 } 9034 9035 // Suppress the protected check (C++ [class.protected]) for each of the 9036 // assignment operators we found. This strange dance is required when 9037 // we're assigning via a base classes's copy-assignment operator. To 9038 // ensure that we're getting the right base class subobject (without 9039 // ambiguities), we need to cast "this" to that subobject type; to 9040 // ensure that we don't go through the virtual call mechanism, we need 9041 // to qualify the operator= name with the base class (see below). However, 9042 // this means that if the base class has a protected copy assignment 9043 // operator, the protected member access check will fail. So, we 9044 // rewrite "protected" access to "public" access in this case, since we 9045 // know by construction that we're calling from a derived class. 9046 if (CopyingBaseSubobject) { 9047 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9048 L != LEnd; ++L) { 9049 if (L.getAccess() == AS_protected) 9050 L.setAccess(AS_public); 9051 } 9052 } 9053 9054 // Create the nested-name-specifier that will be used to qualify the 9055 // reference to operator=; this is required to suppress the virtual 9056 // call mechanism. 9057 CXXScopeSpec SS; 9058 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9059 SS.MakeTrivial(S.Context, 9060 NestedNameSpecifier::Create(S.Context, 0, false, 9061 CanonicalT), 9062 Loc); 9063 9064 // Create the reference to operator=. 9065 ExprResult OpEqualRef 9066 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9067 SS, /*TemplateKWLoc=*/SourceLocation(), 9068 /*FirstQualifierInScope=*/0, 9069 OpLookup, 9070 /*TemplateArgs=*/0, 9071 /*SuppressQualifierCheck=*/true); 9072 if (OpEqualRef.isInvalid()) 9073 return StmtError(); 9074 9075 // Build the call to the assignment operator. 9076 9077 Expr *FromInst = From.build(S, Loc); 9078 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 9079 OpEqualRef.takeAs<Expr>(), 9080 Loc, FromInst, Loc); 9081 if (Call.isInvalid()) 9082 return StmtError(); 9083 9084 // If we built a call to a trivial 'operator=' while copying an array, 9085 // bail out. We'll replace the whole shebang with a memcpy. 9086 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9087 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9088 return StmtResult((Stmt*)0); 9089 9090 // Convert to an expression-statement, and clean up any produced 9091 // temporaries. 9092 return S.ActOnExprStmt(Call); 9093 } 9094 9095 // - if the subobject is of scalar type, the built-in assignment 9096 // operator is used. 9097 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9098 if (!ArrayTy) { 9099 ExprResult Assignment = S.CreateBuiltinBinOp( 9100 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9101 if (Assignment.isInvalid()) 9102 return StmtError(); 9103 return S.ActOnExprStmt(Assignment); 9104 } 9105 9106 // - if the subobject is an array, each element is assigned, in the 9107 // manner appropriate to the element type; 9108 9109 // Construct a loop over the array bounds, e.g., 9110 // 9111 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9112 // 9113 // that will copy each of the array elements. 9114 QualType SizeType = S.Context.getSizeType(); 9115 9116 // Create the iteration variable. 9117 IdentifierInfo *IterationVarName = 0; 9118 { 9119 SmallString<8> Str; 9120 llvm::raw_svector_ostream OS(Str); 9121 OS << "__i" << Depth; 9122 IterationVarName = &S.Context.Idents.get(OS.str()); 9123 } 9124 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9125 IterationVarName, SizeType, 9126 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9127 SC_None); 9128 9129 // Initialize the iteration variable to zero. 9130 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9131 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9132 9133 // Creates a reference to the iteration variable. 9134 RefBuilder IterationVarRef(IterationVar, SizeType); 9135 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9136 9137 // Create the DeclStmt that holds the iteration variable. 9138 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9139 9140 // Subscript the "from" and "to" expressions with the iteration variable. 9141 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9142 MoveCastBuilder FromIndexMove(FromIndexCopy); 9143 const ExprBuilder *FromIndex; 9144 if (Copying) 9145 FromIndex = &FromIndexCopy; 9146 else 9147 FromIndex = &FromIndexMove; 9148 9149 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9150 9151 // Build the copy/move for an individual element of the array. 9152 StmtResult Copy = 9153 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9154 ToIndex, *FromIndex, CopyingBaseSubobject, 9155 Copying, Depth + 1); 9156 // Bail out if copying fails or if we determined that we should use memcpy. 9157 if (Copy.isInvalid() || !Copy.get()) 9158 return Copy; 9159 9160 // Create the comparison against the array bound. 9161 llvm::APInt Upper 9162 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9163 Expr *Comparison 9164 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9165 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9166 BO_NE, S.Context.BoolTy, 9167 VK_RValue, OK_Ordinary, Loc, false); 9168 9169 // Create the pre-increment of the iteration variable. 9170 Expr *Increment 9171 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9172 SizeType, VK_LValue, OK_Ordinary, Loc); 9173 9174 // Construct the loop that copies all elements of this array. 9175 return S.ActOnForStmt(Loc, Loc, InitStmt, 9176 S.MakeFullExpr(Comparison), 9177 0, S.MakeFullDiscardedValueExpr(Increment), 9178 Loc, Copy.take()); 9179 } 9180 9181 static StmtResult 9182 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9183 const ExprBuilder &To, const ExprBuilder &From, 9184 bool CopyingBaseSubobject, bool Copying) { 9185 // Maybe we should use a memcpy? 9186 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9187 T.isTriviallyCopyableType(S.Context)) 9188 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9189 9190 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9191 CopyingBaseSubobject, 9192 Copying, 0)); 9193 9194 // If we ended up picking a trivial assignment operator for an array of a 9195 // non-trivially-copyable class type, just emit a memcpy. 9196 if (!Result.isInvalid() && !Result.get()) 9197 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9198 9199 return Result; 9200 } 9201 9202 Sema::ImplicitExceptionSpecification 9203 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9204 CXXRecordDecl *ClassDecl = MD->getParent(); 9205 9206 ImplicitExceptionSpecification ExceptSpec(*this); 9207 if (ClassDecl->isInvalidDecl()) 9208 return ExceptSpec; 9209 9210 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9211 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9212 unsigned ArgQuals = 9213 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9214 9215 // C++ [except.spec]p14: 9216 // An implicitly declared special member function (Clause 12) shall have an 9217 // exception-specification. [...] 9218 9219 // It is unspecified whether or not an implicit copy assignment operator 9220 // attempts to deduplicate calls to assignment operators of virtual bases are 9221 // made. As such, this exception specification is effectively unspecified. 9222 // Based on a similar decision made for constness in C++0x, we're erring on 9223 // the side of assuming such calls to be made regardless of whether they 9224 // actually happen. 9225 for (const auto &Base : ClassDecl->bases()) { 9226 if (Base.isVirtual()) 9227 continue; 9228 9229 CXXRecordDecl *BaseClassDecl 9230 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9231 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9232 ArgQuals, false, 0)) 9233 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9234 } 9235 9236 for (const auto &Base : ClassDecl->vbases()) { 9237 CXXRecordDecl *BaseClassDecl 9238 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9239 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9240 ArgQuals, false, 0)) 9241 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9242 } 9243 9244 for (const auto *Field : ClassDecl->fields()) { 9245 QualType FieldType = Context.getBaseElementType(Field->getType()); 9246 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9247 if (CXXMethodDecl *CopyAssign = 9248 LookupCopyingAssignment(FieldClassDecl, 9249 ArgQuals | FieldType.getCVRQualifiers(), 9250 false, 0)) 9251 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9252 } 9253 } 9254 9255 return ExceptSpec; 9256 } 9257 9258 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9259 // Note: The following rules are largely analoguous to the copy 9260 // constructor rules. Note that virtual bases are not taken into account 9261 // for determining the argument type of the operator. Note also that 9262 // operators taking an object instead of a reference are allowed. 9263 assert(ClassDecl->needsImplicitCopyAssignment()); 9264 9265 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9266 if (DSM.isAlreadyBeingDeclared()) 9267 return 0; 9268 9269 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9270 QualType RetType = Context.getLValueReferenceType(ArgType); 9271 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9272 if (Const) 9273 ArgType = ArgType.withConst(); 9274 ArgType = Context.getLValueReferenceType(ArgType); 9275 9276 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9277 CXXCopyAssignment, 9278 Const); 9279 9280 // An implicitly-declared copy assignment operator is an inline public 9281 // member of its class. 9282 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9283 SourceLocation ClassLoc = ClassDecl->getLocation(); 9284 DeclarationNameInfo NameInfo(Name, ClassLoc); 9285 CXXMethodDecl *CopyAssignment = 9286 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9287 /*TInfo=*/ 0, /*StorageClass=*/ SC_None, 9288 /*isInline=*/ true, Constexpr, SourceLocation()); 9289 CopyAssignment->setAccess(AS_public); 9290 CopyAssignment->setDefaulted(); 9291 CopyAssignment->setImplicit(); 9292 9293 // Build an exception specification pointing back at this member. 9294 FunctionProtoType::ExtProtoInfo EPI = 9295 getImplicitMethodEPI(*this, CopyAssignment); 9296 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9297 9298 // Add the parameter to the operator. 9299 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9300 ClassLoc, ClassLoc, /*Id=*/0, 9301 ArgType, /*TInfo=*/0, 9302 SC_None, 0); 9303 CopyAssignment->setParams(FromParam); 9304 9305 AddOverriddenMethods(ClassDecl, CopyAssignment); 9306 9307 CopyAssignment->setTrivial( 9308 ClassDecl->needsOverloadResolutionForCopyAssignment() 9309 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9310 : ClassDecl->hasTrivialCopyAssignment()); 9311 9312 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9313 SetDeclDeleted(CopyAssignment, ClassLoc); 9314 9315 // Note that we have added this copy-assignment operator. 9316 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9317 9318 if (Scope *S = getScopeForContext(ClassDecl)) 9319 PushOnScopeChains(CopyAssignment, S, false); 9320 ClassDecl->addDecl(CopyAssignment); 9321 9322 return CopyAssignment; 9323 } 9324 9325 /// Diagnose an implicit copy operation for a class which is odr-used, but 9326 /// which is deprecated because the class has a user-declared copy constructor, 9327 /// copy assignment operator, or destructor. 9328 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 9329 SourceLocation UseLoc) { 9330 assert(CopyOp->isImplicit()); 9331 9332 CXXRecordDecl *RD = CopyOp->getParent(); 9333 CXXMethodDecl *UserDeclaredOperation = 0; 9334 9335 // In Microsoft mode, assignment operations don't affect constructors and 9336 // vice versa. 9337 if (RD->hasUserDeclaredDestructor()) { 9338 UserDeclaredOperation = RD->getDestructor(); 9339 } else if (!isa<CXXConstructorDecl>(CopyOp) && 9340 RD->hasUserDeclaredCopyConstructor() && 9341 !S.getLangOpts().MSVCCompat) { 9342 // Find any user-declared copy constructor. 9343 for (auto *I : RD->ctors()) { 9344 if (I->isCopyConstructor()) { 9345 UserDeclaredOperation = I; 9346 break; 9347 } 9348 } 9349 assert(UserDeclaredOperation); 9350 } else if (isa<CXXConstructorDecl>(CopyOp) && 9351 RD->hasUserDeclaredCopyAssignment() && 9352 !S.getLangOpts().MSVCCompat) { 9353 // Find any user-declared move assignment operator. 9354 for (auto *I : RD->methods()) { 9355 if (I->isCopyAssignmentOperator()) { 9356 UserDeclaredOperation = I; 9357 break; 9358 } 9359 } 9360 assert(UserDeclaredOperation); 9361 } 9362 9363 if (UserDeclaredOperation) { 9364 S.Diag(UserDeclaredOperation->getLocation(), 9365 diag::warn_deprecated_copy_operation) 9366 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 9367 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 9368 S.Diag(UseLoc, diag::note_member_synthesized_at) 9369 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 9370 : Sema::CXXCopyAssignment) 9371 << RD; 9372 } 9373 } 9374 9375 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 9376 CXXMethodDecl *CopyAssignOperator) { 9377 assert((CopyAssignOperator->isDefaulted() && 9378 CopyAssignOperator->isOverloadedOperator() && 9379 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 9380 !CopyAssignOperator->doesThisDeclarationHaveABody() && 9381 !CopyAssignOperator->isDeleted()) && 9382 "DefineImplicitCopyAssignment called for wrong function"); 9383 9384 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 9385 9386 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 9387 CopyAssignOperator->setInvalidDecl(); 9388 return; 9389 } 9390 9391 // C++11 [class.copy]p18: 9392 // The [definition of an implicitly declared copy assignment operator] is 9393 // deprecated if the class has a user-declared copy constructor or a 9394 // user-declared destructor. 9395 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 9396 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 9397 9398 CopyAssignOperator->markUsed(Context); 9399 9400 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 9401 DiagnosticErrorTrap Trap(Diags); 9402 9403 // C++0x [class.copy]p30: 9404 // The implicitly-defined or explicitly-defaulted copy assignment operator 9405 // for a non-union class X performs memberwise copy assignment of its 9406 // subobjects. The direct base classes of X are assigned first, in the 9407 // order of their declaration in the base-specifier-list, and then the 9408 // immediate non-static data members of X are assigned, in the order in 9409 // which they were declared in the class definition. 9410 9411 // The statements that form the synthesized function body. 9412 SmallVector<Stmt*, 8> Statements; 9413 9414 // The parameter for the "other" object, which we are copying from. 9415 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 9416 Qualifiers OtherQuals = Other->getType().getQualifiers(); 9417 QualType OtherRefType = Other->getType(); 9418 if (const LValueReferenceType *OtherRef 9419 = OtherRefType->getAs<LValueReferenceType>()) { 9420 OtherRefType = OtherRef->getPointeeType(); 9421 OtherQuals = OtherRefType.getQualifiers(); 9422 } 9423 9424 // Our location for everything implicitly-generated. 9425 SourceLocation Loc = CopyAssignOperator->getLocation(); 9426 9427 // Builds a DeclRefExpr for the "other" object. 9428 RefBuilder OtherRef(Other, OtherRefType); 9429 9430 // Builds the "this" pointer. 9431 ThisBuilder This; 9432 9433 // Assign base classes. 9434 bool Invalid = false; 9435 for (auto &Base : ClassDecl->bases()) { 9436 // Form the assignment: 9437 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 9438 QualType BaseType = Base.getType().getUnqualifiedType(); 9439 if (!BaseType->isRecordType()) { 9440 Invalid = true; 9441 continue; 9442 } 9443 9444 CXXCastPath BasePath; 9445 BasePath.push_back(&Base); 9446 9447 // Construct the "from" expression, which is an implicit cast to the 9448 // appropriately-qualified base type. 9449 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 9450 VK_LValue, BasePath); 9451 9452 // Dereference "this". 9453 DerefBuilder DerefThis(This); 9454 CastBuilder To(DerefThis, 9455 Context.getCVRQualifiedType( 9456 BaseType, CopyAssignOperator->getTypeQualifiers()), 9457 VK_LValue, BasePath); 9458 9459 // Build the copy. 9460 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 9461 To, From, 9462 /*CopyingBaseSubobject=*/true, 9463 /*Copying=*/true); 9464 if (Copy.isInvalid()) { 9465 Diag(CurrentLocation, diag::note_member_synthesized_at) 9466 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9467 CopyAssignOperator->setInvalidDecl(); 9468 return; 9469 } 9470 9471 // Success! Record the copy. 9472 Statements.push_back(Copy.takeAs<Expr>()); 9473 } 9474 9475 // Assign non-static members. 9476 for (auto *Field : ClassDecl->fields()) { 9477 if (Field->isUnnamedBitfield()) 9478 continue; 9479 9480 if (Field->isInvalidDecl()) { 9481 Invalid = true; 9482 continue; 9483 } 9484 9485 // Check for members of reference type; we can't copy those. 9486 if (Field->getType()->isReferenceType()) { 9487 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9488 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9489 Diag(Field->getLocation(), diag::note_declared_at); 9490 Diag(CurrentLocation, diag::note_member_synthesized_at) 9491 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9492 Invalid = true; 9493 continue; 9494 } 9495 9496 // Check for members of const-qualified, non-class type. 9497 QualType BaseType = Context.getBaseElementType(Field->getType()); 9498 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9499 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9500 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9501 Diag(Field->getLocation(), diag::note_declared_at); 9502 Diag(CurrentLocation, diag::note_member_synthesized_at) 9503 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9504 Invalid = true; 9505 continue; 9506 } 9507 9508 // Suppress assigning zero-width bitfields. 9509 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9510 continue; 9511 9512 QualType FieldType = Field->getType().getNonReferenceType(); 9513 if (FieldType->isIncompleteArrayType()) { 9514 assert(ClassDecl->hasFlexibleArrayMember() && 9515 "Incomplete array type is not valid"); 9516 continue; 9517 } 9518 9519 // Build references to the field in the object we're copying from and to. 9520 CXXScopeSpec SS; // Intentionally empty 9521 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9522 LookupMemberName); 9523 MemberLookup.addDecl(Field); 9524 MemberLookup.resolveKind(); 9525 9526 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 9527 9528 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 9529 9530 // Build the copy of this field. 9531 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 9532 To, From, 9533 /*CopyingBaseSubobject=*/false, 9534 /*Copying=*/true); 9535 if (Copy.isInvalid()) { 9536 Diag(CurrentLocation, diag::note_member_synthesized_at) 9537 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9538 CopyAssignOperator->setInvalidDecl(); 9539 return; 9540 } 9541 9542 // Success! Record the copy. 9543 Statements.push_back(Copy.takeAs<Stmt>()); 9544 } 9545 9546 if (!Invalid) { 9547 // Add a "return *this;" 9548 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9549 9550 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9551 if (Return.isInvalid()) 9552 Invalid = true; 9553 else { 9554 Statements.push_back(Return.takeAs<Stmt>()); 9555 9556 if (Trap.hasErrorOccurred()) { 9557 Diag(CurrentLocation, diag::note_member_synthesized_at) 9558 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9559 Invalid = true; 9560 } 9561 } 9562 } 9563 9564 if (Invalid) { 9565 CopyAssignOperator->setInvalidDecl(); 9566 return; 9567 } 9568 9569 StmtResult Body; 9570 { 9571 CompoundScopeRAII CompoundScope(*this); 9572 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9573 /*isStmtExpr=*/false); 9574 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9575 } 9576 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 9577 9578 if (ASTMutationListener *L = getASTMutationListener()) { 9579 L->CompletedImplicitDefinition(CopyAssignOperator); 9580 } 9581 } 9582 9583 Sema::ImplicitExceptionSpecification 9584 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9585 CXXRecordDecl *ClassDecl = MD->getParent(); 9586 9587 ImplicitExceptionSpecification ExceptSpec(*this); 9588 if (ClassDecl->isInvalidDecl()) 9589 return ExceptSpec; 9590 9591 // C++0x [except.spec]p14: 9592 // An implicitly declared special member function (Clause 12) shall have an 9593 // exception-specification. [...] 9594 9595 // It is unspecified whether or not an implicit move assignment operator 9596 // attempts to deduplicate calls to assignment operators of virtual bases are 9597 // made. As such, this exception specification is effectively unspecified. 9598 // Based on a similar decision made for constness in C++0x, we're erring on 9599 // the side of assuming such calls to be made regardless of whether they 9600 // actually happen. 9601 // Note that a move constructor is not implicitly declared when there are 9602 // virtual bases, but it can still be user-declared and explicitly defaulted. 9603 for (const auto &Base : ClassDecl->bases()) { 9604 if (Base.isVirtual()) 9605 continue; 9606 9607 CXXRecordDecl *BaseClassDecl 9608 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9609 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9610 0, false, 0)) 9611 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 9612 } 9613 9614 for (const auto &Base : ClassDecl->vbases()) { 9615 CXXRecordDecl *BaseClassDecl 9616 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9617 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9618 0, false, 0)) 9619 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 9620 } 9621 9622 for (const auto *Field : ClassDecl->fields()) { 9623 QualType FieldType = Context.getBaseElementType(Field->getType()); 9624 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9625 if (CXXMethodDecl *MoveAssign = 9626 LookupMovingAssignment(FieldClassDecl, 9627 FieldType.getCVRQualifiers(), 9628 false, 0)) 9629 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 9630 } 9631 } 9632 9633 return ExceptSpec; 9634 } 9635 9636 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9637 assert(ClassDecl->needsImplicitMoveAssignment()); 9638 9639 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9640 if (DSM.isAlreadyBeingDeclared()) 9641 return 0; 9642 9643 // Note: The following rules are largely analoguous to the move 9644 // constructor rules. 9645 9646 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9647 QualType RetType = Context.getLValueReferenceType(ArgType); 9648 ArgType = Context.getRValueReferenceType(ArgType); 9649 9650 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9651 CXXMoveAssignment, 9652 false); 9653 9654 // An implicitly-declared move assignment operator is an inline public 9655 // member of its class. 9656 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9657 SourceLocation ClassLoc = ClassDecl->getLocation(); 9658 DeclarationNameInfo NameInfo(Name, ClassLoc); 9659 CXXMethodDecl *MoveAssignment = 9660 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9661 /*TInfo=*/0, /*StorageClass=*/SC_None, 9662 /*isInline=*/true, Constexpr, SourceLocation()); 9663 MoveAssignment->setAccess(AS_public); 9664 MoveAssignment->setDefaulted(); 9665 MoveAssignment->setImplicit(); 9666 9667 // Build an exception specification pointing back at this member. 9668 FunctionProtoType::ExtProtoInfo EPI = 9669 getImplicitMethodEPI(*this, MoveAssignment); 9670 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9671 9672 // Add the parameter to the operator. 9673 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9674 ClassLoc, ClassLoc, /*Id=*/0, 9675 ArgType, /*TInfo=*/0, 9676 SC_None, 0); 9677 MoveAssignment->setParams(FromParam); 9678 9679 AddOverriddenMethods(ClassDecl, MoveAssignment); 9680 9681 MoveAssignment->setTrivial( 9682 ClassDecl->needsOverloadResolutionForMoveAssignment() 9683 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9684 : ClassDecl->hasTrivialMoveAssignment()); 9685 9686 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9687 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 9688 SetDeclDeleted(MoveAssignment, ClassLoc); 9689 } 9690 9691 // Note that we have added this copy-assignment operator. 9692 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9693 9694 if (Scope *S = getScopeForContext(ClassDecl)) 9695 PushOnScopeChains(MoveAssignment, S, false); 9696 ClassDecl->addDecl(MoveAssignment); 9697 9698 return MoveAssignment; 9699 } 9700 9701 /// Check if we're implicitly defining a move assignment operator for a class 9702 /// with virtual bases. Such a move assignment might move-assign the virtual 9703 /// base multiple times. 9704 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 9705 SourceLocation CurrentLocation) { 9706 assert(!Class->isDependentContext() && "should not define dependent move"); 9707 9708 // Only a virtual base could get implicitly move-assigned multiple times. 9709 // Only a non-trivial move assignment can observe this. We only want to 9710 // diagnose if we implicitly define an assignment operator that assigns 9711 // two base classes, both of which move-assign the same virtual base. 9712 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 9713 Class->getNumBases() < 2) 9714 return; 9715 9716 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 9717 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 9718 VBaseMap VBases; 9719 9720 for (auto &BI : Class->bases()) { 9721 Worklist.push_back(&BI); 9722 while (!Worklist.empty()) { 9723 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 9724 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 9725 9726 // If the base has no non-trivial move assignment operators, 9727 // we don't care about moves from it. 9728 if (!Base->hasNonTrivialMoveAssignment()) 9729 continue; 9730 9731 // If there's nothing virtual here, skip it. 9732 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 9733 continue; 9734 9735 // If we're not actually going to call a move assignment for this base, 9736 // or the selected move assignment is trivial, skip it. 9737 Sema::SpecialMemberOverloadResult *SMOR = 9738 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 9739 /*ConstArg*/false, /*VolatileArg*/false, 9740 /*RValueThis*/true, /*ConstThis*/false, 9741 /*VolatileThis*/false); 9742 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 9743 !SMOR->getMethod()->isMoveAssignmentOperator()) 9744 continue; 9745 9746 if (BaseSpec->isVirtual()) { 9747 // We're going to move-assign this virtual base, and its move 9748 // assignment operator is not trivial. If this can happen for 9749 // multiple distinct direct bases of Class, diagnose it. (If it 9750 // only happens in one base, we'll diagnose it when synthesizing 9751 // that base class's move assignment operator.) 9752 CXXBaseSpecifier *&Existing = 9753 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 9754 .first->second; 9755 if (Existing && Existing != &BI) { 9756 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 9757 << Class << Base; 9758 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 9759 << (Base->getCanonicalDecl() == 9760 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 9761 << Base << Existing->getType() << Existing->getSourceRange(); 9762 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 9763 << (Base->getCanonicalDecl() == 9764 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 9765 << Base << BI.getType() << BaseSpec->getSourceRange(); 9766 9767 // Only diagnose each vbase once. 9768 Existing = 0; 9769 } 9770 } else { 9771 // Only walk over bases that have defaulted move assignment operators. 9772 // We assume that any user-provided move assignment operator handles 9773 // the multiple-moves-of-vbase case itself somehow. 9774 if (!SMOR->getMethod()->isDefaulted()) 9775 continue; 9776 9777 // We're going to move the base classes of Base. Add them to the list. 9778 for (auto &BI : Base->bases()) 9779 Worklist.push_back(&BI); 9780 } 9781 } 9782 } 9783 } 9784 9785 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 9786 CXXMethodDecl *MoveAssignOperator) { 9787 assert((MoveAssignOperator->isDefaulted() && 9788 MoveAssignOperator->isOverloadedOperator() && 9789 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 9790 !MoveAssignOperator->doesThisDeclarationHaveABody() && 9791 !MoveAssignOperator->isDeleted()) && 9792 "DefineImplicitMoveAssignment called for wrong function"); 9793 9794 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 9795 9796 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 9797 MoveAssignOperator->setInvalidDecl(); 9798 return; 9799 } 9800 9801 MoveAssignOperator->markUsed(Context); 9802 9803 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 9804 DiagnosticErrorTrap Trap(Diags); 9805 9806 // C++0x [class.copy]p28: 9807 // The implicitly-defined or move assignment operator for a non-union class 9808 // X performs memberwise move assignment of its subobjects. The direct base 9809 // classes of X are assigned first, in the order of their declaration in the 9810 // base-specifier-list, and then the immediate non-static data members of X 9811 // are assigned, in the order in which they were declared in the class 9812 // definition. 9813 9814 // Issue a warning if our implicit move assignment operator will move 9815 // from a virtual base more than once. 9816 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 9817 9818 // The statements that form the synthesized function body. 9819 SmallVector<Stmt*, 8> Statements; 9820 9821 // The parameter for the "other" object, which we are move from. 9822 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 9823 QualType OtherRefType = Other->getType()-> 9824 getAs<RValueReferenceType>()->getPointeeType(); 9825 assert(!OtherRefType.getQualifiers() && 9826 "Bad argument type of defaulted move assignment"); 9827 9828 // Our location for everything implicitly-generated. 9829 SourceLocation Loc = MoveAssignOperator->getLocation(); 9830 9831 // Builds a reference to the "other" object. 9832 RefBuilder OtherRef(Other, OtherRefType); 9833 // Cast to rvalue. 9834 MoveCastBuilder MoveOther(OtherRef); 9835 9836 // Builds the "this" pointer. 9837 ThisBuilder This; 9838 9839 // Assign base classes. 9840 bool Invalid = false; 9841 for (auto &Base : ClassDecl->bases()) { 9842 // C++11 [class.copy]p28: 9843 // It is unspecified whether subobjects representing virtual base classes 9844 // are assigned more than once by the implicitly-defined copy assignment 9845 // operator. 9846 // FIXME: Do not assign to a vbase that will be assigned by some other base 9847 // class. For a move-assignment, this can result in the vbase being moved 9848 // multiple times. 9849 9850 // Form the assignment: 9851 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 9852 QualType BaseType = Base.getType().getUnqualifiedType(); 9853 if (!BaseType->isRecordType()) { 9854 Invalid = true; 9855 continue; 9856 } 9857 9858 CXXCastPath BasePath; 9859 BasePath.push_back(&Base); 9860 9861 // Construct the "from" expression, which is an implicit cast to the 9862 // appropriately-qualified base type. 9863 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 9864 9865 // Dereference "this". 9866 DerefBuilder DerefThis(This); 9867 9868 // Implicitly cast "this" to the appropriately-qualified base type. 9869 CastBuilder To(DerefThis, 9870 Context.getCVRQualifiedType( 9871 BaseType, MoveAssignOperator->getTypeQualifiers()), 9872 VK_LValue, BasePath); 9873 9874 // Build the move. 9875 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 9876 To, From, 9877 /*CopyingBaseSubobject=*/true, 9878 /*Copying=*/false); 9879 if (Move.isInvalid()) { 9880 Diag(CurrentLocation, diag::note_member_synthesized_at) 9881 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9882 MoveAssignOperator->setInvalidDecl(); 9883 return; 9884 } 9885 9886 // Success! Record the move. 9887 Statements.push_back(Move.takeAs<Expr>()); 9888 } 9889 9890 // Assign non-static members. 9891 for (auto *Field : ClassDecl->fields()) { 9892 if (Field->isUnnamedBitfield()) 9893 continue; 9894 9895 if (Field->isInvalidDecl()) { 9896 Invalid = true; 9897 continue; 9898 } 9899 9900 // Check for members of reference type; we can't move those. 9901 if (Field->getType()->isReferenceType()) { 9902 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9903 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9904 Diag(Field->getLocation(), diag::note_declared_at); 9905 Diag(CurrentLocation, diag::note_member_synthesized_at) 9906 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9907 Invalid = true; 9908 continue; 9909 } 9910 9911 // Check for members of const-qualified, non-class type. 9912 QualType BaseType = Context.getBaseElementType(Field->getType()); 9913 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9914 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9915 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9916 Diag(Field->getLocation(), diag::note_declared_at); 9917 Diag(CurrentLocation, diag::note_member_synthesized_at) 9918 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9919 Invalid = true; 9920 continue; 9921 } 9922 9923 // Suppress assigning zero-width bitfields. 9924 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9925 continue; 9926 9927 QualType FieldType = Field->getType().getNonReferenceType(); 9928 if (FieldType->isIncompleteArrayType()) { 9929 assert(ClassDecl->hasFlexibleArrayMember() && 9930 "Incomplete array type is not valid"); 9931 continue; 9932 } 9933 9934 // Build references to the field in the object we're copying from and to. 9935 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9936 LookupMemberName); 9937 MemberLookup.addDecl(Field); 9938 MemberLookup.resolveKind(); 9939 MemberBuilder From(MoveOther, OtherRefType, 9940 /*IsArrow=*/false, MemberLookup); 9941 MemberBuilder To(This, getCurrentThisType(), 9942 /*IsArrow=*/true, MemberLookup); 9943 9944 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 9945 "Member reference with rvalue base must be rvalue except for reference " 9946 "members, which aren't allowed for move assignment."); 9947 9948 // Build the move of this field. 9949 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 9950 To, From, 9951 /*CopyingBaseSubobject=*/false, 9952 /*Copying=*/false); 9953 if (Move.isInvalid()) { 9954 Diag(CurrentLocation, diag::note_member_synthesized_at) 9955 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9956 MoveAssignOperator->setInvalidDecl(); 9957 return; 9958 } 9959 9960 // Success! Record the copy. 9961 Statements.push_back(Move.takeAs<Stmt>()); 9962 } 9963 9964 if (!Invalid) { 9965 // Add a "return *this;" 9966 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9967 9968 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9969 if (Return.isInvalid()) 9970 Invalid = true; 9971 else { 9972 Statements.push_back(Return.takeAs<Stmt>()); 9973 9974 if (Trap.hasErrorOccurred()) { 9975 Diag(CurrentLocation, diag::note_member_synthesized_at) 9976 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9977 Invalid = true; 9978 } 9979 } 9980 } 9981 9982 if (Invalid) { 9983 MoveAssignOperator->setInvalidDecl(); 9984 return; 9985 } 9986 9987 StmtResult Body; 9988 { 9989 CompoundScopeRAII CompoundScope(*this); 9990 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9991 /*isStmtExpr=*/false); 9992 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9993 } 9994 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 9995 9996 if (ASTMutationListener *L = getASTMutationListener()) { 9997 L->CompletedImplicitDefinition(MoveAssignOperator); 9998 } 9999 } 10000 10001 Sema::ImplicitExceptionSpecification 10002 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10003 CXXRecordDecl *ClassDecl = MD->getParent(); 10004 10005 ImplicitExceptionSpecification ExceptSpec(*this); 10006 if (ClassDecl->isInvalidDecl()) 10007 return ExceptSpec; 10008 10009 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10010 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10011 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10012 10013 // C++ [except.spec]p14: 10014 // An implicitly declared special member function (Clause 12) shall have an 10015 // exception-specification. [...] 10016 for (const auto &Base : ClassDecl->bases()) { 10017 // Virtual bases are handled below. 10018 if (Base.isVirtual()) 10019 continue; 10020 10021 CXXRecordDecl *BaseClassDecl 10022 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10023 if (CXXConstructorDecl *CopyConstructor = 10024 LookupCopyingConstructor(BaseClassDecl, Quals)) 10025 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10026 } 10027 for (const auto &Base : ClassDecl->vbases()) { 10028 CXXRecordDecl *BaseClassDecl 10029 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10030 if (CXXConstructorDecl *CopyConstructor = 10031 LookupCopyingConstructor(BaseClassDecl, Quals)) 10032 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10033 } 10034 for (const auto *Field : ClassDecl->fields()) { 10035 QualType FieldType = Context.getBaseElementType(Field->getType()); 10036 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10037 if (CXXConstructorDecl *CopyConstructor = 10038 LookupCopyingConstructor(FieldClassDecl, 10039 Quals | FieldType.getCVRQualifiers())) 10040 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10041 } 10042 } 10043 10044 return ExceptSpec; 10045 } 10046 10047 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10048 CXXRecordDecl *ClassDecl) { 10049 // C++ [class.copy]p4: 10050 // If the class definition does not explicitly declare a copy 10051 // constructor, one is declared implicitly. 10052 assert(ClassDecl->needsImplicitCopyConstructor()); 10053 10054 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10055 if (DSM.isAlreadyBeingDeclared()) 10056 return 0; 10057 10058 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10059 QualType ArgType = ClassType; 10060 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10061 if (Const) 10062 ArgType = ArgType.withConst(); 10063 ArgType = Context.getLValueReferenceType(ArgType); 10064 10065 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10066 CXXCopyConstructor, 10067 Const); 10068 10069 DeclarationName Name 10070 = Context.DeclarationNames.getCXXConstructorName( 10071 Context.getCanonicalType(ClassType)); 10072 SourceLocation ClassLoc = ClassDecl->getLocation(); 10073 DeclarationNameInfo NameInfo(Name, ClassLoc); 10074 10075 // An implicitly-declared copy constructor is an inline public 10076 // member of its class. 10077 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10078 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 10079 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10080 Constexpr); 10081 CopyConstructor->setAccess(AS_public); 10082 CopyConstructor->setDefaulted(); 10083 10084 // Build an exception specification pointing back at this member. 10085 FunctionProtoType::ExtProtoInfo EPI = 10086 getImplicitMethodEPI(*this, CopyConstructor); 10087 CopyConstructor->setType( 10088 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10089 10090 // Add the parameter to the constructor. 10091 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10092 ClassLoc, ClassLoc, 10093 /*IdentifierInfo=*/0, 10094 ArgType, /*TInfo=*/0, 10095 SC_None, 0); 10096 CopyConstructor->setParams(FromParam); 10097 10098 CopyConstructor->setTrivial( 10099 ClassDecl->needsOverloadResolutionForCopyConstructor() 10100 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10101 : ClassDecl->hasTrivialCopyConstructor()); 10102 10103 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10104 SetDeclDeleted(CopyConstructor, ClassLoc); 10105 10106 // Note that we have declared this constructor. 10107 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10108 10109 if (Scope *S = getScopeForContext(ClassDecl)) 10110 PushOnScopeChains(CopyConstructor, S, false); 10111 ClassDecl->addDecl(CopyConstructor); 10112 10113 return CopyConstructor; 10114 } 10115 10116 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10117 CXXConstructorDecl *CopyConstructor) { 10118 assert((CopyConstructor->isDefaulted() && 10119 CopyConstructor->isCopyConstructor() && 10120 !CopyConstructor->doesThisDeclarationHaveABody() && 10121 !CopyConstructor->isDeleted()) && 10122 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10123 10124 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10125 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10126 10127 // C++11 [class.copy]p7: 10128 // The [definition of an implicitly declared copy constructor] is 10129 // deprecated if the class has a user-declared copy assignment operator 10130 // or a user-declared destructor. 10131 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10132 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10133 10134 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10135 DiagnosticErrorTrap Trap(Diags); 10136 10137 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10138 Trap.hasErrorOccurred()) { 10139 Diag(CurrentLocation, diag::note_member_synthesized_at) 10140 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10141 CopyConstructor->setInvalidDecl(); 10142 } else { 10143 Sema::CompoundScopeRAII CompoundScope(*this); 10144 CopyConstructor->setBody(ActOnCompoundStmt( 10145 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None, 10146 /*isStmtExpr=*/ false).takeAs<Stmt>()); 10147 } 10148 10149 CopyConstructor->markUsed(Context); 10150 if (ASTMutationListener *L = getASTMutationListener()) { 10151 L->CompletedImplicitDefinition(CopyConstructor); 10152 } 10153 } 10154 10155 Sema::ImplicitExceptionSpecification 10156 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10157 CXXRecordDecl *ClassDecl = MD->getParent(); 10158 10159 // C++ [except.spec]p14: 10160 // An implicitly declared special member function (Clause 12) shall have an 10161 // exception-specification. [...] 10162 ImplicitExceptionSpecification ExceptSpec(*this); 10163 if (ClassDecl->isInvalidDecl()) 10164 return ExceptSpec; 10165 10166 // Direct base-class constructors. 10167 for (const auto &B : ClassDecl->bases()) { 10168 if (B.isVirtual()) // Handled below. 10169 continue; 10170 10171 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10172 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10173 CXXConstructorDecl *Constructor = 10174 LookupMovingConstructor(BaseClassDecl, 0); 10175 // If this is a deleted function, add it anyway. This might be conformant 10176 // with the standard. This might not. I'm not sure. It might not matter. 10177 if (Constructor) 10178 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10179 } 10180 } 10181 10182 // Virtual base-class constructors. 10183 for (const auto &B : ClassDecl->vbases()) { 10184 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10185 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10186 CXXConstructorDecl *Constructor = 10187 LookupMovingConstructor(BaseClassDecl, 0); 10188 // If this is a deleted function, add it anyway. This might be conformant 10189 // with the standard. This might not. I'm not sure. It might not matter. 10190 if (Constructor) 10191 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10192 } 10193 } 10194 10195 // Field constructors. 10196 for (const auto *F : ClassDecl->fields()) { 10197 QualType FieldType = Context.getBaseElementType(F->getType()); 10198 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10199 CXXConstructorDecl *Constructor = 10200 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10201 // If this is a deleted function, add it anyway. This might be conformant 10202 // with the standard. This might not. I'm not sure. It might not matter. 10203 // In particular, the problem is that this function never gets called. It 10204 // might just be ill-formed because this function attempts to refer to 10205 // a deleted function here. 10206 if (Constructor) 10207 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10208 } 10209 } 10210 10211 return ExceptSpec; 10212 } 10213 10214 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10215 CXXRecordDecl *ClassDecl) { 10216 assert(ClassDecl->needsImplicitMoveConstructor()); 10217 10218 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10219 if (DSM.isAlreadyBeingDeclared()) 10220 return 0; 10221 10222 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10223 QualType ArgType = Context.getRValueReferenceType(ClassType); 10224 10225 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10226 CXXMoveConstructor, 10227 false); 10228 10229 DeclarationName Name 10230 = Context.DeclarationNames.getCXXConstructorName( 10231 Context.getCanonicalType(ClassType)); 10232 SourceLocation ClassLoc = ClassDecl->getLocation(); 10233 DeclarationNameInfo NameInfo(Name, ClassLoc); 10234 10235 // C++11 [class.copy]p11: 10236 // An implicitly-declared copy/move constructor is an inline public 10237 // member of its class. 10238 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10239 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 10240 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10241 Constexpr); 10242 MoveConstructor->setAccess(AS_public); 10243 MoveConstructor->setDefaulted(); 10244 10245 // Build an exception specification pointing back at this member. 10246 FunctionProtoType::ExtProtoInfo EPI = 10247 getImplicitMethodEPI(*this, MoveConstructor); 10248 MoveConstructor->setType( 10249 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10250 10251 // Add the parameter to the constructor. 10252 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10253 ClassLoc, ClassLoc, 10254 /*IdentifierInfo=*/0, 10255 ArgType, /*TInfo=*/0, 10256 SC_None, 0); 10257 MoveConstructor->setParams(FromParam); 10258 10259 MoveConstructor->setTrivial( 10260 ClassDecl->needsOverloadResolutionForMoveConstructor() 10261 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10262 : ClassDecl->hasTrivialMoveConstructor()); 10263 10264 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10265 ClassDecl->setImplicitMoveConstructorIsDeleted(); 10266 SetDeclDeleted(MoveConstructor, ClassLoc); 10267 } 10268 10269 // Note that we have declared this constructor. 10270 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10271 10272 if (Scope *S = getScopeForContext(ClassDecl)) 10273 PushOnScopeChains(MoveConstructor, S, false); 10274 ClassDecl->addDecl(MoveConstructor); 10275 10276 return MoveConstructor; 10277 } 10278 10279 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 10280 CXXConstructorDecl *MoveConstructor) { 10281 assert((MoveConstructor->isDefaulted() && 10282 MoveConstructor->isMoveConstructor() && 10283 !MoveConstructor->doesThisDeclarationHaveABody() && 10284 !MoveConstructor->isDeleted()) && 10285 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 10286 10287 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 10288 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 10289 10290 SynthesizedFunctionScope Scope(*this, MoveConstructor); 10291 DiagnosticErrorTrap Trap(Diags); 10292 10293 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10294 Trap.hasErrorOccurred()) { 10295 Diag(CurrentLocation, diag::note_member_synthesized_at) 10296 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10297 MoveConstructor->setInvalidDecl(); 10298 } else { 10299 Sema::CompoundScopeRAII CompoundScope(*this); 10300 MoveConstructor->setBody(ActOnCompoundStmt( 10301 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None, 10302 /*isStmtExpr=*/ false).takeAs<Stmt>()); 10303 } 10304 10305 MoveConstructor->markUsed(Context); 10306 10307 if (ASTMutationListener *L = getASTMutationListener()) { 10308 L->CompletedImplicitDefinition(MoveConstructor); 10309 } 10310 } 10311 10312 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10313 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10314 } 10315 10316 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10317 SourceLocation CurrentLocation, 10318 CXXConversionDecl *Conv) { 10319 CXXRecordDecl *Lambda = Conv->getParent(); 10320 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 10321 // If we are defining a specialization of a conversion to function-ptr 10322 // cache the deduced template arguments for this specialization 10323 // so that we can use them to retrieve the corresponding call-operator 10324 // and static-invoker. 10325 const TemplateArgumentList *DeducedTemplateArgs = 0; 10326 10327 10328 // Retrieve the corresponding call-operator specialization. 10329 if (Lambda->isGenericLambda()) { 10330 assert(Conv->isFunctionTemplateSpecialization()); 10331 FunctionTemplateDecl *CallOpTemplate = 10332 CallOp->getDescribedFunctionTemplate(); 10333 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 10334 void *InsertPos = 0; 10335 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 10336 DeducedTemplateArgs->data(), 10337 DeducedTemplateArgs->size(), 10338 InsertPos); 10339 assert(CallOpSpec && 10340 "Conversion operator must have a corresponding call operator"); 10341 CallOp = cast<CXXMethodDecl>(CallOpSpec); 10342 } 10343 // Mark the call operator referenced (and add to pending instantiations 10344 // if necessary). 10345 // For both the conversion and static-invoker template specializations 10346 // we construct their body's in this function, so no need to add them 10347 // to the PendingInstantiations. 10348 MarkFunctionReferenced(CurrentLocation, CallOp); 10349 10350 SynthesizedFunctionScope Scope(*this, Conv); 10351 DiagnosticErrorTrap Trap(Diags); 10352 10353 // Retrieve the static invoker... 10354 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 10355 // ... and get the corresponding specialization for a generic lambda. 10356 if (Lambda->isGenericLambda()) { 10357 assert(DeducedTemplateArgs && 10358 "Must have deduced template arguments from Conversion Operator"); 10359 FunctionTemplateDecl *InvokeTemplate = 10360 Invoker->getDescribedFunctionTemplate(); 10361 void *InsertPos = 0; 10362 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 10363 DeducedTemplateArgs->data(), 10364 DeducedTemplateArgs->size(), 10365 InsertPos); 10366 assert(InvokeSpec && 10367 "Must have a corresponding static invoker specialization"); 10368 Invoker = cast<CXXMethodDecl>(InvokeSpec); 10369 } 10370 // Construct the body of the conversion function { return __invoke; }. 10371 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 10372 VK_LValue, Conv->getLocation()).take(); 10373 assert(FunctionRef && "Can't refer to __invoke function?"); 10374 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 10375 Conv->setBody(new (Context) CompoundStmt(Context, Return, 10376 Conv->getLocation(), 10377 Conv->getLocation())); 10378 10379 Conv->markUsed(Context); 10380 Conv->setReferenced(); 10381 10382 // Fill in the __invoke function with a dummy implementation. IR generation 10383 // will fill in the actual details. 10384 Invoker->markUsed(Context); 10385 Invoker->setReferenced(); 10386 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 10387 10388 if (ASTMutationListener *L = getASTMutationListener()) { 10389 L->CompletedImplicitDefinition(Conv); 10390 L->CompletedImplicitDefinition(Invoker); 10391 } 10392 } 10393 10394 10395 10396 void Sema::DefineImplicitLambdaToBlockPointerConversion( 10397 SourceLocation CurrentLocation, 10398 CXXConversionDecl *Conv) 10399 { 10400 assert(!Conv->getParent()->isGenericLambda()); 10401 10402 Conv->markUsed(Context); 10403 10404 SynthesizedFunctionScope Scope(*this, Conv); 10405 DiagnosticErrorTrap Trap(Diags); 10406 10407 // Copy-initialize the lambda object as needed to capture it. 10408 Expr *This = ActOnCXXThis(CurrentLocation).take(); 10409 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 10410 10411 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 10412 Conv->getLocation(), 10413 Conv, DerefThis); 10414 10415 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 10416 // behavior. Note that only the general conversion function does this 10417 // (since it's unusable otherwise); in the case where we inline the 10418 // block literal, it has block literal lifetime semantics. 10419 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 10420 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 10421 CK_CopyAndAutoreleaseBlockObject, 10422 BuildBlock.get(), 0, VK_RValue); 10423 10424 if (BuildBlock.isInvalid()) { 10425 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10426 Conv->setInvalidDecl(); 10427 return; 10428 } 10429 10430 // Create the return statement that returns the block from the conversion 10431 // function. 10432 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 10433 if (Return.isInvalid()) { 10434 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10435 Conv->setInvalidDecl(); 10436 return; 10437 } 10438 10439 // Set the body of the conversion function. 10440 Stmt *ReturnS = Return.take(); 10441 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 10442 Conv->getLocation(), 10443 Conv->getLocation())); 10444 10445 // We're done; notify the mutation listener, if any. 10446 if (ASTMutationListener *L = getASTMutationListener()) { 10447 L->CompletedImplicitDefinition(Conv); 10448 } 10449 } 10450 10451 /// \brief Determine whether the given list arguments contains exactly one 10452 /// "real" (non-default) argument. 10453 static bool hasOneRealArgument(MultiExprArg Args) { 10454 switch (Args.size()) { 10455 case 0: 10456 return false; 10457 10458 default: 10459 if (!Args[1]->isDefaultArgument()) 10460 return false; 10461 10462 // fall through 10463 case 1: 10464 return !Args[0]->isDefaultArgument(); 10465 } 10466 10467 return false; 10468 } 10469 10470 ExprResult 10471 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10472 CXXConstructorDecl *Constructor, 10473 MultiExprArg ExprArgs, 10474 bool HadMultipleCandidates, 10475 bool IsListInitialization, 10476 bool RequiresZeroInit, 10477 unsigned ConstructKind, 10478 SourceRange ParenRange) { 10479 bool Elidable = false; 10480 10481 // C++0x [class.copy]p34: 10482 // When certain criteria are met, an implementation is allowed to 10483 // omit the copy/move construction of a class object, even if the 10484 // copy/move constructor and/or destructor for the object have 10485 // side effects. [...] 10486 // - when a temporary class object that has not been bound to a 10487 // reference (12.2) would be copied/moved to a class object 10488 // with the same cv-unqualified type, the copy/move operation 10489 // can be omitted by constructing the temporary object 10490 // directly into the target of the omitted copy/move 10491 if (ConstructKind == CXXConstructExpr::CK_Complete && 10492 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10493 Expr *SubExpr = ExprArgs[0]; 10494 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10495 } 10496 10497 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10498 Elidable, ExprArgs, HadMultipleCandidates, 10499 IsListInitialization, RequiresZeroInit, 10500 ConstructKind, ParenRange); 10501 } 10502 10503 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 10504 /// including handling of its default argument expressions. 10505 ExprResult 10506 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10507 CXXConstructorDecl *Constructor, bool Elidable, 10508 MultiExprArg ExprArgs, 10509 bool HadMultipleCandidates, 10510 bool IsListInitialization, 10511 bool RequiresZeroInit, 10512 unsigned ConstructKind, 10513 SourceRange ParenRange) { 10514 MarkFunctionReferenced(ConstructLoc, Constructor); 10515 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 10516 Constructor, Elidable, ExprArgs, 10517 HadMultipleCandidates, 10518 IsListInitialization, RequiresZeroInit, 10519 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10520 ParenRange)); 10521 } 10522 10523 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10524 if (VD->isInvalidDecl()) return; 10525 10526 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10527 if (ClassDecl->isInvalidDecl()) return; 10528 if (ClassDecl->hasIrrelevantDestructor()) return; 10529 if (ClassDecl->isDependentContext()) return; 10530 10531 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10532 MarkFunctionReferenced(VD->getLocation(), Destructor); 10533 CheckDestructorAccess(VD->getLocation(), Destructor, 10534 PDiag(diag::err_access_dtor_var) 10535 << VD->getDeclName() 10536 << VD->getType()); 10537 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10538 10539 if (Destructor->isTrivial()) return; 10540 if (!VD->hasGlobalStorage()) return; 10541 10542 // Emit warning for non-trivial dtor in global scope (a real global, 10543 // class-static, function-static). 10544 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10545 10546 // TODO: this should be re-enabled for static locals by !CXAAtExit 10547 if (!VD->isStaticLocal()) 10548 Diag(VD->getLocation(), diag::warn_global_destructor); 10549 } 10550 10551 /// \brief Given a constructor and the set of arguments provided for the 10552 /// constructor, convert the arguments and add any required default arguments 10553 /// to form a proper call to this constructor. 10554 /// 10555 /// \returns true if an error occurred, false otherwise. 10556 bool 10557 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10558 MultiExprArg ArgsPtr, 10559 SourceLocation Loc, 10560 SmallVectorImpl<Expr*> &ConvertedArgs, 10561 bool AllowExplicit, 10562 bool IsListInitialization) { 10563 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10564 unsigned NumArgs = ArgsPtr.size(); 10565 Expr **Args = ArgsPtr.data(); 10566 10567 const FunctionProtoType *Proto 10568 = Constructor->getType()->getAs<FunctionProtoType>(); 10569 assert(Proto && "Constructor without a prototype?"); 10570 unsigned NumParams = Proto->getNumParams(); 10571 10572 // If too few arguments are available, we'll fill in the rest with defaults. 10573 if (NumArgs < NumParams) 10574 ConvertedArgs.reserve(NumParams); 10575 else 10576 ConvertedArgs.reserve(NumArgs); 10577 10578 VariadicCallType CallType = 10579 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10580 SmallVector<Expr *, 8> AllArgs; 10581 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10582 Proto, 0, 10583 llvm::makeArrayRef(Args, NumArgs), 10584 AllArgs, 10585 CallType, AllowExplicit, 10586 IsListInitialization); 10587 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 10588 10589 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 10590 10591 CheckConstructorCall(Constructor, 10592 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 10593 AllArgs.size()), 10594 Proto, Loc); 10595 10596 return Invalid; 10597 } 10598 10599 static inline bool 10600 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 10601 const FunctionDecl *FnDecl) { 10602 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 10603 if (isa<NamespaceDecl>(DC)) { 10604 return SemaRef.Diag(FnDecl->getLocation(), 10605 diag::err_operator_new_delete_declared_in_namespace) 10606 << FnDecl->getDeclName(); 10607 } 10608 10609 if (isa<TranslationUnitDecl>(DC) && 10610 FnDecl->getStorageClass() == SC_Static) { 10611 return SemaRef.Diag(FnDecl->getLocation(), 10612 diag::err_operator_new_delete_declared_static) 10613 << FnDecl->getDeclName(); 10614 } 10615 10616 return false; 10617 } 10618 10619 static inline bool 10620 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 10621 CanQualType ExpectedResultType, 10622 CanQualType ExpectedFirstParamType, 10623 unsigned DependentParamTypeDiag, 10624 unsigned InvalidParamTypeDiag) { 10625 QualType ResultType = 10626 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 10627 10628 // Check that the result type is not dependent. 10629 if (ResultType->isDependentType()) 10630 return SemaRef.Diag(FnDecl->getLocation(), 10631 diag::err_operator_new_delete_dependent_result_type) 10632 << FnDecl->getDeclName() << ExpectedResultType; 10633 10634 // Check that the result type is what we expect. 10635 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 10636 return SemaRef.Diag(FnDecl->getLocation(), 10637 diag::err_operator_new_delete_invalid_result_type) 10638 << FnDecl->getDeclName() << ExpectedResultType; 10639 10640 // A function template must have at least 2 parameters. 10641 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 10642 return SemaRef.Diag(FnDecl->getLocation(), 10643 diag::err_operator_new_delete_template_too_few_parameters) 10644 << FnDecl->getDeclName(); 10645 10646 // The function decl must have at least 1 parameter. 10647 if (FnDecl->getNumParams() == 0) 10648 return SemaRef.Diag(FnDecl->getLocation(), 10649 diag::err_operator_new_delete_too_few_parameters) 10650 << FnDecl->getDeclName(); 10651 10652 // Check the first parameter type is not dependent. 10653 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10654 if (FirstParamType->isDependentType()) 10655 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10656 << FnDecl->getDeclName() << ExpectedFirstParamType; 10657 10658 // Check that the first parameter type is what we expect. 10659 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10660 ExpectedFirstParamType) 10661 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10662 << FnDecl->getDeclName() << ExpectedFirstParamType; 10663 10664 return false; 10665 } 10666 10667 static bool 10668 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10669 // C++ [basic.stc.dynamic.allocation]p1: 10670 // A program is ill-formed if an allocation function is declared in a 10671 // namespace scope other than global scope or declared static in global 10672 // scope. 10673 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10674 return true; 10675 10676 CanQualType SizeTy = 10677 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10678 10679 // C++ [basic.stc.dynamic.allocation]p1: 10680 // The return type shall be void*. The first parameter shall have type 10681 // std::size_t. 10682 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10683 SizeTy, 10684 diag::err_operator_new_dependent_param_type, 10685 diag::err_operator_new_param_type)) 10686 return true; 10687 10688 // C++ [basic.stc.dynamic.allocation]p1: 10689 // The first parameter shall not have an associated default argument. 10690 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10691 return SemaRef.Diag(FnDecl->getLocation(), 10692 diag::err_operator_new_default_arg) 10693 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10694 10695 return false; 10696 } 10697 10698 static bool 10699 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10700 // C++ [basic.stc.dynamic.deallocation]p1: 10701 // A program is ill-formed if deallocation functions are declared in a 10702 // namespace scope other than global scope or declared static in global 10703 // scope. 10704 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10705 return true; 10706 10707 // C++ [basic.stc.dynamic.deallocation]p2: 10708 // Each deallocation function shall return void and its first parameter 10709 // shall be void*. 10710 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10711 SemaRef.Context.VoidPtrTy, 10712 diag::err_operator_delete_dependent_param_type, 10713 diag::err_operator_delete_param_type)) 10714 return true; 10715 10716 return false; 10717 } 10718 10719 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 10720 /// of this overloaded operator is well-formed. If so, returns false; 10721 /// otherwise, emits appropriate diagnostics and returns true. 10722 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10723 assert(FnDecl && FnDecl->isOverloadedOperator() && 10724 "Expected an overloaded operator declaration"); 10725 10726 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10727 10728 // C++ [over.oper]p5: 10729 // The allocation and deallocation functions, operator new, 10730 // operator new[], operator delete and operator delete[], are 10731 // described completely in 3.7.3. The attributes and restrictions 10732 // found in the rest of this subclause do not apply to them unless 10733 // explicitly stated in 3.7.3. 10734 if (Op == OO_Delete || Op == OO_Array_Delete) 10735 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10736 10737 if (Op == OO_New || Op == OO_Array_New) 10738 return CheckOperatorNewDeclaration(*this, FnDecl); 10739 10740 // C++ [over.oper]p6: 10741 // An operator function shall either be a non-static member 10742 // function or be a non-member function and have at least one 10743 // parameter whose type is a class, a reference to a class, an 10744 // enumeration, or a reference to an enumeration. 10745 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 10746 if (MethodDecl->isStatic()) 10747 return Diag(FnDecl->getLocation(), 10748 diag::err_operator_overload_static) << FnDecl->getDeclName(); 10749 } else { 10750 bool ClassOrEnumParam = false; 10751 for (auto Param : FnDecl->params()) { 10752 QualType ParamType = Param->getType().getNonReferenceType(); 10753 if (ParamType->isDependentType() || ParamType->isRecordType() || 10754 ParamType->isEnumeralType()) { 10755 ClassOrEnumParam = true; 10756 break; 10757 } 10758 } 10759 10760 if (!ClassOrEnumParam) 10761 return Diag(FnDecl->getLocation(), 10762 diag::err_operator_overload_needs_class_or_enum) 10763 << FnDecl->getDeclName(); 10764 } 10765 10766 // C++ [over.oper]p8: 10767 // An operator function cannot have default arguments (8.3.6), 10768 // except where explicitly stated below. 10769 // 10770 // Only the function-call operator allows default arguments 10771 // (C++ [over.call]p1). 10772 if (Op != OO_Call) { 10773 for (auto Param : FnDecl->params()) { 10774 if (Param->hasDefaultArg()) 10775 return Diag(Param->getLocation(), 10776 diag::err_operator_overload_default_arg) 10777 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 10778 } 10779 } 10780 10781 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 10782 { false, false, false } 10783 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 10784 , { Unary, Binary, MemberOnly } 10785 #include "clang/Basic/OperatorKinds.def" 10786 }; 10787 10788 bool CanBeUnaryOperator = OperatorUses[Op][0]; 10789 bool CanBeBinaryOperator = OperatorUses[Op][1]; 10790 bool MustBeMemberOperator = OperatorUses[Op][2]; 10791 10792 // C++ [over.oper]p8: 10793 // [...] Operator functions cannot have more or fewer parameters 10794 // than the number required for the corresponding operator, as 10795 // described in the rest of this subclause. 10796 unsigned NumParams = FnDecl->getNumParams() 10797 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 10798 if (Op != OO_Call && 10799 ((NumParams == 1 && !CanBeUnaryOperator) || 10800 (NumParams == 2 && !CanBeBinaryOperator) || 10801 (NumParams < 1) || (NumParams > 2))) { 10802 // We have the wrong number of parameters. 10803 unsigned ErrorKind; 10804 if (CanBeUnaryOperator && CanBeBinaryOperator) { 10805 ErrorKind = 2; // 2 -> unary or binary. 10806 } else if (CanBeUnaryOperator) { 10807 ErrorKind = 0; // 0 -> unary 10808 } else { 10809 assert(CanBeBinaryOperator && 10810 "All non-call overloaded operators are unary or binary!"); 10811 ErrorKind = 1; // 1 -> binary 10812 } 10813 10814 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 10815 << FnDecl->getDeclName() << NumParams << ErrorKind; 10816 } 10817 10818 // Overloaded operators other than operator() cannot be variadic. 10819 if (Op != OO_Call && 10820 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 10821 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 10822 << FnDecl->getDeclName(); 10823 } 10824 10825 // Some operators must be non-static member functions. 10826 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 10827 return Diag(FnDecl->getLocation(), 10828 diag::err_operator_overload_must_be_member) 10829 << FnDecl->getDeclName(); 10830 } 10831 10832 // C++ [over.inc]p1: 10833 // The user-defined function called operator++ implements the 10834 // prefix and postfix ++ operator. If this function is a member 10835 // function with no parameters, or a non-member function with one 10836 // parameter of class or enumeration type, it defines the prefix 10837 // increment operator ++ for objects of that type. If the function 10838 // is a member function with one parameter (which shall be of type 10839 // int) or a non-member function with two parameters (the second 10840 // of which shall be of type int), it defines the postfix 10841 // increment operator ++ for objects of that type. 10842 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 10843 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 10844 QualType ParamType = LastParam->getType(); 10845 10846 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 10847 !ParamType->isDependentType()) 10848 return Diag(LastParam->getLocation(), 10849 diag::err_operator_overload_post_incdec_must_be_int) 10850 << LastParam->getType() << (Op == OO_MinusMinus); 10851 } 10852 10853 return false; 10854 } 10855 10856 /// CheckLiteralOperatorDeclaration - Check whether the declaration 10857 /// of this literal operator function is well-formed. If so, returns 10858 /// false; otherwise, emits appropriate diagnostics and returns true. 10859 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 10860 if (isa<CXXMethodDecl>(FnDecl)) { 10861 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 10862 << FnDecl->getDeclName(); 10863 return true; 10864 } 10865 10866 if (FnDecl->isExternC()) { 10867 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 10868 return true; 10869 } 10870 10871 bool Valid = false; 10872 10873 // This might be the definition of a literal operator template. 10874 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 10875 // This might be a specialization of a literal operator template. 10876 if (!TpDecl) 10877 TpDecl = FnDecl->getPrimaryTemplate(); 10878 10879 // template <char...> type operator "" name() and 10880 // template <class T, T...> type operator "" name() are the only valid 10881 // template signatures, and the only valid signatures with no parameters. 10882 if (TpDecl) { 10883 if (FnDecl->param_size() == 0) { 10884 // Must have one or two template parameters 10885 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 10886 if (Params->size() == 1) { 10887 NonTypeTemplateParmDecl *PmDecl = 10888 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 10889 10890 // The template parameter must be a char parameter pack. 10891 if (PmDecl && PmDecl->isTemplateParameterPack() && 10892 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 10893 Valid = true; 10894 } else if (Params->size() == 2) { 10895 TemplateTypeParmDecl *PmType = 10896 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 10897 NonTypeTemplateParmDecl *PmArgs = 10898 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 10899 10900 // The second template parameter must be a parameter pack with the 10901 // first template parameter as its type. 10902 if (PmType && PmArgs && 10903 !PmType->isTemplateParameterPack() && 10904 PmArgs->isTemplateParameterPack()) { 10905 const TemplateTypeParmType *TArgs = 10906 PmArgs->getType()->getAs<TemplateTypeParmType>(); 10907 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 10908 TArgs->getIndex() == PmType->getIndex()) { 10909 Valid = true; 10910 if (ActiveTemplateInstantiations.empty()) 10911 Diag(FnDecl->getLocation(), 10912 diag::ext_string_literal_operator_template); 10913 } 10914 } 10915 } 10916 } 10917 } else if (FnDecl->param_size()) { 10918 // Check the first parameter 10919 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10920 10921 QualType T = (*Param)->getType().getUnqualifiedType(); 10922 10923 // unsigned long long int, long double, and any character type are allowed 10924 // as the only parameters. 10925 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 10926 Context.hasSameType(T, Context.LongDoubleTy) || 10927 Context.hasSameType(T, Context.CharTy) || 10928 Context.hasSameType(T, Context.WideCharTy) || 10929 Context.hasSameType(T, Context.Char16Ty) || 10930 Context.hasSameType(T, Context.Char32Ty)) { 10931 if (++Param == FnDecl->param_end()) 10932 Valid = true; 10933 goto FinishedParams; 10934 } 10935 10936 // Otherwise it must be a pointer to const; let's strip those qualifiers. 10937 const PointerType *PT = T->getAs<PointerType>(); 10938 if (!PT) 10939 goto FinishedParams; 10940 T = PT->getPointeeType(); 10941 if (!T.isConstQualified() || T.isVolatileQualified()) 10942 goto FinishedParams; 10943 T = T.getUnqualifiedType(); 10944 10945 // Move on to the second parameter; 10946 ++Param; 10947 10948 // If there is no second parameter, the first must be a const char * 10949 if (Param == FnDecl->param_end()) { 10950 if (Context.hasSameType(T, Context.CharTy)) 10951 Valid = true; 10952 goto FinishedParams; 10953 } 10954 10955 // const char *, const wchar_t*, const char16_t*, and const char32_t* 10956 // are allowed as the first parameter to a two-parameter function 10957 if (!(Context.hasSameType(T, Context.CharTy) || 10958 Context.hasSameType(T, Context.WideCharTy) || 10959 Context.hasSameType(T, Context.Char16Ty) || 10960 Context.hasSameType(T, Context.Char32Ty))) 10961 goto FinishedParams; 10962 10963 // The second and final parameter must be an std::size_t 10964 T = (*Param)->getType().getUnqualifiedType(); 10965 if (Context.hasSameType(T, Context.getSizeType()) && 10966 ++Param == FnDecl->param_end()) 10967 Valid = true; 10968 } 10969 10970 // FIXME: This diagnostic is absolutely terrible. 10971 FinishedParams: 10972 if (!Valid) { 10973 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 10974 << FnDecl->getDeclName(); 10975 return true; 10976 } 10977 10978 // A parameter-declaration-clause containing a default argument is not 10979 // equivalent to any of the permitted forms. 10980 for (auto Param : FnDecl->params()) { 10981 if (Param->hasDefaultArg()) { 10982 Diag(Param->getDefaultArgRange().getBegin(), 10983 diag::err_literal_operator_default_argument) 10984 << Param->getDefaultArgRange(); 10985 break; 10986 } 10987 } 10988 10989 StringRef LiteralName 10990 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 10991 if (LiteralName[0] != '_') { 10992 // C++11 [usrlit.suffix]p1: 10993 // Literal suffix identifiers that do not start with an underscore 10994 // are reserved for future standardization. 10995 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 10996 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 10997 } 10998 10999 return false; 11000 } 11001 11002 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11003 /// linkage specification, including the language and (if present) 11004 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 11005 /// language string literal. LBraceLoc, if valid, provides the location of 11006 /// the '{' brace. Otherwise, this linkage specification does not 11007 /// have any braces. 11008 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11009 Expr *LangStr, 11010 SourceLocation LBraceLoc) { 11011 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11012 if (!Lit->isAscii()) { 11013 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11014 << LangStr->getSourceRange(); 11015 return 0; 11016 } 11017 11018 StringRef Lang = Lit->getString(); 11019 LinkageSpecDecl::LanguageIDs Language; 11020 if (Lang == "C") 11021 Language = LinkageSpecDecl::lang_c; 11022 else if (Lang == "C++") 11023 Language = LinkageSpecDecl::lang_cxx; 11024 else { 11025 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11026 << LangStr->getSourceRange(); 11027 return 0; 11028 } 11029 11030 // FIXME: Add all the various semantics of linkage specifications 11031 11032 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11033 LangStr->getExprLoc(), Language, 11034 LBraceLoc.isValid()); 11035 CurContext->addDecl(D); 11036 PushDeclContext(S, D); 11037 return D; 11038 } 11039 11040 /// ActOnFinishLinkageSpecification - Complete the definition of 11041 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11042 /// valid, it's the position of the closing '}' brace in a linkage 11043 /// specification that uses braces. 11044 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11045 Decl *LinkageSpec, 11046 SourceLocation RBraceLoc) { 11047 if (RBraceLoc.isValid()) { 11048 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11049 LSDecl->setRBraceLoc(RBraceLoc); 11050 } 11051 PopDeclContext(); 11052 return LinkageSpec; 11053 } 11054 11055 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11056 AttributeList *AttrList, 11057 SourceLocation SemiLoc) { 11058 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11059 // Attribute declarations appertain to empty declaration so we handle 11060 // them here. 11061 if (AttrList) 11062 ProcessDeclAttributeList(S, ED, AttrList); 11063 11064 CurContext->addDecl(ED); 11065 return ED; 11066 } 11067 11068 /// \brief Perform semantic analysis for the variable declaration that 11069 /// occurs within a C++ catch clause, returning the newly-created 11070 /// variable. 11071 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11072 TypeSourceInfo *TInfo, 11073 SourceLocation StartLoc, 11074 SourceLocation Loc, 11075 IdentifierInfo *Name) { 11076 bool Invalid = false; 11077 QualType ExDeclType = TInfo->getType(); 11078 11079 // Arrays and functions decay. 11080 if (ExDeclType->isArrayType()) 11081 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11082 else if (ExDeclType->isFunctionType()) 11083 ExDeclType = Context.getPointerType(ExDeclType); 11084 11085 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11086 // The exception-declaration shall not denote a pointer or reference to an 11087 // incomplete type, other than [cv] void*. 11088 // N2844 forbids rvalue references. 11089 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11090 Diag(Loc, diag::err_catch_rvalue_ref); 11091 Invalid = true; 11092 } 11093 11094 QualType BaseType = ExDeclType; 11095 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11096 unsigned DK = diag::err_catch_incomplete; 11097 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11098 BaseType = Ptr->getPointeeType(); 11099 Mode = 1; 11100 DK = diag::err_catch_incomplete_ptr; 11101 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11102 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11103 BaseType = Ref->getPointeeType(); 11104 Mode = 2; 11105 DK = diag::err_catch_incomplete_ref; 11106 } 11107 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11108 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11109 Invalid = true; 11110 11111 if (!Invalid && !ExDeclType->isDependentType() && 11112 RequireNonAbstractType(Loc, ExDeclType, 11113 diag::err_abstract_type_in_decl, 11114 AbstractVariableType)) 11115 Invalid = true; 11116 11117 // Only the non-fragile NeXT runtime currently supports C++ catches 11118 // of ObjC types, and no runtime supports catching ObjC types by value. 11119 if (!Invalid && getLangOpts().ObjC1) { 11120 QualType T = ExDeclType; 11121 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11122 T = RT->getPointeeType(); 11123 11124 if (T->isObjCObjectType()) { 11125 Diag(Loc, diag::err_objc_object_catch); 11126 Invalid = true; 11127 } else if (T->isObjCObjectPointerType()) { 11128 // FIXME: should this be a test for macosx-fragile specifically? 11129 if (getLangOpts().ObjCRuntime.isFragile()) 11130 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11131 } 11132 } 11133 11134 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11135 ExDeclType, TInfo, SC_None); 11136 ExDecl->setExceptionVariable(true); 11137 11138 // In ARC, infer 'retaining' for variables of retainable type. 11139 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11140 Invalid = true; 11141 11142 if (!Invalid && !ExDeclType->isDependentType()) { 11143 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11144 // Insulate this from anything else we might currently be parsing. 11145 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11146 11147 // C++ [except.handle]p16: 11148 // The object declared in an exception-declaration or, if the 11149 // exception-declaration does not specify a name, a temporary (12.2) is 11150 // copy-initialized (8.5) from the exception object. [...] 11151 // The object is destroyed when the handler exits, after the destruction 11152 // of any automatic objects initialized within the handler. 11153 // 11154 // We just pretend to initialize the object with itself, then make sure 11155 // it can be destroyed later. 11156 QualType initType = ExDeclType; 11157 11158 InitializedEntity entity = 11159 InitializedEntity::InitializeVariable(ExDecl); 11160 InitializationKind initKind = 11161 InitializationKind::CreateCopy(Loc, SourceLocation()); 11162 11163 Expr *opaqueValue = 11164 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11165 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11166 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11167 if (result.isInvalid()) 11168 Invalid = true; 11169 else { 11170 // If the constructor used was non-trivial, set this as the 11171 // "initializer". 11172 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>(); 11173 if (!construct->getConstructor()->isTrivial()) { 11174 Expr *init = MaybeCreateExprWithCleanups(construct); 11175 ExDecl->setInit(init); 11176 } 11177 11178 // And make sure it's destructable. 11179 FinalizeVarWithDestructor(ExDecl, recordType); 11180 } 11181 } 11182 } 11183 11184 if (Invalid) 11185 ExDecl->setInvalidDecl(); 11186 11187 return ExDecl; 11188 } 11189 11190 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11191 /// handler. 11192 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11193 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11194 bool Invalid = D.isInvalidType(); 11195 11196 // Check for unexpanded parameter packs. 11197 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11198 UPPC_ExceptionType)) { 11199 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11200 D.getIdentifierLoc()); 11201 Invalid = true; 11202 } 11203 11204 IdentifierInfo *II = D.getIdentifier(); 11205 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11206 LookupOrdinaryName, 11207 ForRedeclaration)) { 11208 // The scope should be freshly made just for us. There is just no way 11209 // it contains any previous declaration. 11210 assert(!S->isDeclScope(PrevDecl)); 11211 if (PrevDecl->isTemplateParameter()) { 11212 // Maybe we will complain about the shadowed template parameter. 11213 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11214 PrevDecl = 0; 11215 } 11216 } 11217 11218 if (D.getCXXScopeSpec().isSet() && !Invalid) { 11219 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 11220 << D.getCXXScopeSpec().getRange(); 11221 Invalid = true; 11222 } 11223 11224 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 11225 D.getLocStart(), 11226 D.getIdentifierLoc(), 11227 D.getIdentifier()); 11228 if (Invalid) 11229 ExDecl->setInvalidDecl(); 11230 11231 // Add the exception declaration into this scope. 11232 if (II) 11233 PushOnScopeChains(ExDecl, S); 11234 else 11235 CurContext->addDecl(ExDecl); 11236 11237 ProcessDeclAttributes(S, ExDecl, D); 11238 return ExDecl; 11239 } 11240 11241 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11242 Expr *AssertExpr, 11243 Expr *AssertMessageExpr, 11244 SourceLocation RParenLoc) { 11245 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 11246 11247 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 11248 return 0; 11249 11250 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 11251 AssertMessage, RParenLoc, false); 11252 } 11253 11254 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11255 Expr *AssertExpr, 11256 StringLiteral *AssertMessage, 11257 SourceLocation RParenLoc, 11258 bool Failed) { 11259 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 11260 !Failed) { 11261 // In a static_assert-declaration, the constant-expression shall be a 11262 // constant expression that can be contextually converted to bool. 11263 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 11264 if (Converted.isInvalid()) 11265 Failed = true; 11266 11267 llvm::APSInt Cond; 11268 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 11269 diag::err_static_assert_expression_is_not_constant, 11270 /*AllowFold=*/false).isInvalid()) 11271 Failed = true; 11272 11273 if (!Failed && !Cond) { 11274 SmallString<256> MsgBuffer; 11275 llvm::raw_svector_ostream Msg(MsgBuffer); 11276 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 11277 Diag(StaticAssertLoc, diag::err_static_assert_failed) 11278 << Msg.str() << AssertExpr->getSourceRange(); 11279 Failed = true; 11280 } 11281 } 11282 11283 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 11284 AssertExpr, AssertMessage, RParenLoc, 11285 Failed); 11286 11287 CurContext->addDecl(Decl); 11288 return Decl; 11289 } 11290 11291 /// \brief Perform semantic analysis of the given friend type declaration. 11292 /// 11293 /// \returns A friend declaration that. 11294 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 11295 SourceLocation FriendLoc, 11296 TypeSourceInfo *TSInfo) { 11297 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 11298 11299 QualType T = TSInfo->getType(); 11300 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 11301 11302 // C++03 [class.friend]p2: 11303 // An elaborated-type-specifier shall be used in a friend declaration 11304 // for a class.* 11305 // 11306 // * The class-key of the elaborated-type-specifier is required. 11307 if (!ActiveTemplateInstantiations.empty()) { 11308 // Do not complain about the form of friend template types during 11309 // template instantiation; we will already have complained when the 11310 // template was declared. 11311 } else { 11312 if (!T->isElaboratedTypeSpecifier()) { 11313 // If we evaluated the type to a record type, suggest putting 11314 // a tag in front. 11315 if (const RecordType *RT = T->getAs<RecordType>()) { 11316 RecordDecl *RD = RT->getDecl(); 11317 11318 std::string InsertionText = std::string(" ") + RD->getKindName(); 11319 11320 Diag(TypeRange.getBegin(), 11321 getLangOpts().CPlusPlus11 ? 11322 diag::warn_cxx98_compat_unelaborated_friend_type : 11323 diag::ext_unelaborated_friend_type) 11324 << (unsigned) RD->getTagKind() 11325 << T 11326 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 11327 InsertionText); 11328 } else { 11329 Diag(FriendLoc, 11330 getLangOpts().CPlusPlus11 ? 11331 diag::warn_cxx98_compat_nonclass_type_friend : 11332 diag::ext_nonclass_type_friend) 11333 << T 11334 << TypeRange; 11335 } 11336 } else if (T->getAs<EnumType>()) { 11337 Diag(FriendLoc, 11338 getLangOpts().CPlusPlus11 ? 11339 diag::warn_cxx98_compat_enum_friend : 11340 diag::ext_enum_friend) 11341 << T 11342 << TypeRange; 11343 } 11344 11345 // C++11 [class.friend]p3: 11346 // A friend declaration that does not declare a function shall have one 11347 // of the following forms: 11348 // friend elaborated-type-specifier ; 11349 // friend simple-type-specifier ; 11350 // friend typename-specifier ; 11351 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 11352 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 11353 } 11354 11355 // If the type specifier in a friend declaration designates a (possibly 11356 // cv-qualified) class type, that class is declared as a friend; otherwise, 11357 // the friend declaration is ignored. 11358 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 11359 } 11360 11361 /// Handle a friend tag declaration where the scope specifier was 11362 /// templated. 11363 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 11364 unsigned TagSpec, SourceLocation TagLoc, 11365 CXXScopeSpec &SS, 11366 IdentifierInfo *Name, 11367 SourceLocation NameLoc, 11368 AttributeList *Attr, 11369 MultiTemplateParamsArg TempParamLists) { 11370 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11371 11372 bool isExplicitSpecialization = false; 11373 bool Invalid = false; 11374 11375 if (TemplateParameterList *TemplateParams = 11376 MatchTemplateParametersToScopeSpecifier( 11377 TagLoc, NameLoc, SS, 0, TempParamLists, /*friend*/ true, 11378 isExplicitSpecialization, Invalid)) { 11379 if (TemplateParams->size() > 0) { 11380 // This is a declaration of a class template. 11381 if (Invalid) 11382 return 0; 11383 11384 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 11385 SS, Name, NameLoc, Attr, 11386 TemplateParams, AS_public, 11387 /*ModulePrivateLoc=*/SourceLocation(), 11388 TempParamLists.size() - 1, 11389 TempParamLists.data()).take(); 11390 } else { 11391 // The "template<>" header is extraneous. 11392 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11393 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11394 isExplicitSpecialization = true; 11395 } 11396 } 11397 11398 if (Invalid) return 0; 11399 11400 bool isAllExplicitSpecializations = true; 11401 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 11402 if (TempParamLists[I]->size()) { 11403 isAllExplicitSpecializations = false; 11404 break; 11405 } 11406 } 11407 11408 // FIXME: don't ignore attributes. 11409 11410 // If it's explicit specializations all the way down, just forget 11411 // about the template header and build an appropriate non-templated 11412 // friend. TODO: for source fidelity, remember the headers. 11413 if (isAllExplicitSpecializations) { 11414 if (SS.isEmpty()) { 11415 bool Owned = false; 11416 bool IsDependent = false; 11417 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 11418 Attr, AS_public, 11419 /*ModulePrivateLoc=*/SourceLocation(), 11420 MultiTemplateParamsArg(), Owned, IsDependent, 11421 /*ScopedEnumKWLoc=*/SourceLocation(), 11422 /*ScopedEnumUsesClassTag=*/false, 11423 /*UnderlyingType=*/TypeResult(), 11424 /*IsTypeSpecifier=*/false); 11425 } 11426 11427 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11428 ElaboratedTypeKeyword Keyword 11429 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11430 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 11431 *Name, NameLoc); 11432 if (T.isNull()) 11433 return 0; 11434 11435 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11436 if (isa<DependentNameType>(T)) { 11437 DependentNameTypeLoc TL = 11438 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11439 TL.setElaboratedKeywordLoc(TagLoc); 11440 TL.setQualifierLoc(QualifierLoc); 11441 TL.setNameLoc(NameLoc); 11442 } else { 11443 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11444 TL.setElaboratedKeywordLoc(TagLoc); 11445 TL.setQualifierLoc(QualifierLoc); 11446 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 11447 } 11448 11449 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11450 TSI, FriendLoc, TempParamLists); 11451 Friend->setAccess(AS_public); 11452 CurContext->addDecl(Friend); 11453 return Friend; 11454 } 11455 11456 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 11457 11458 11459 11460 // Handle the case of a templated-scope friend class. e.g. 11461 // template <class T> class A<T>::B; 11462 // FIXME: we don't support these right now. 11463 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 11464 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 11465 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11466 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 11467 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11468 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11469 TL.setElaboratedKeywordLoc(TagLoc); 11470 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11471 TL.setNameLoc(NameLoc); 11472 11473 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11474 TSI, FriendLoc, TempParamLists); 11475 Friend->setAccess(AS_public); 11476 Friend->setUnsupportedFriend(true); 11477 CurContext->addDecl(Friend); 11478 return Friend; 11479 } 11480 11481 11482 /// Handle a friend type declaration. This works in tandem with 11483 /// ActOnTag. 11484 /// 11485 /// Notes on friend class templates: 11486 /// 11487 /// We generally treat friend class declarations as if they were 11488 /// declaring a class. So, for example, the elaborated type specifier 11489 /// in a friend declaration is required to obey the restrictions of a 11490 /// class-head (i.e. no typedefs in the scope chain), template 11491 /// parameters are required to match up with simple template-ids, &c. 11492 /// However, unlike when declaring a template specialization, it's 11493 /// okay to refer to a template specialization without an empty 11494 /// template parameter declaration, e.g. 11495 /// friend class A<T>::B<unsigned>; 11496 /// We permit this as a special case; if there are any template 11497 /// parameters present at all, require proper matching, i.e. 11498 /// template <> template \<class T> friend class A<int>::B; 11499 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 11500 MultiTemplateParamsArg TempParams) { 11501 SourceLocation Loc = DS.getLocStart(); 11502 11503 assert(DS.isFriendSpecified()); 11504 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11505 11506 // Try to convert the decl specifier to a type. This works for 11507 // friend templates because ActOnTag never produces a ClassTemplateDecl 11508 // for a TUK_Friend. 11509 Declarator TheDeclarator(DS, Declarator::MemberContext); 11510 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11511 QualType T = TSI->getType(); 11512 if (TheDeclarator.isInvalidType()) 11513 return 0; 11514 11515 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11516 return 0; 11517 11518 // This is definitely an error in C++98. It's probably meant to 11519 // be forbidden in C++0x, too, but the specification is just 11520 // poorly written. 11521 // 11522 // The problem is with declarations like the following: 11523 // template <T> friend A<T>::foo; 11524 // where deciding whether a class C is a friend or not now hinges 11525 // on whether there exists an instantiation of A that causes 11526 // 'foo' to equal C. There are restrictions on class-heads 11527 // (which we declare (by fiat) elaborated friend declarations to 11528 // be) that makes this tractable. 11529 // 11530 // FIXME: handle "template <> friend class A<T>;", which 11531 // is possibly well-formed? Who even knows? 11532 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11533 Diag(Loc, diag::err_tagless_friend_type_template) 11534 << DS.getSourceRange(); 11535 return 0; 11536 } 11537 11538 // C++98 [class.friend]p1: A friend of a class is a function 11539 // or class that is not a member of the class . . . 11540 // This is fixed in DR77, which just barely didn't make the C++03 11541 // deadline. It's also a very silly restriction that seriously 11542 // affects inner classes and which nobody else seems to implement; 11543 // thus we never diagnose it, not even in -pedantic. 11544 // 11545 // But note that we could warn about it: it's always useless to 11546 // friend one of your own members (it's not, however, worthless to 11547 // friend a member of an arbitrary specialization of your template). 11548 11549 Decl *D; 11550 if (unsigned NumTempParamLists = TempParams.size()) 11551 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11552 NumTempParamLists, 11553 TempParams.data(), 11554 TSI, 11555 DS.getFriendSpecLoc()); 11556 else 11557 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11558 11559 if (!D) 11560 return 0; 11561 11562 D->setAccess(AS_public); 11563 CurContext->addDecl(D); 11564 11565 return D; 11566 } 11567 11568 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11569 MultiTemplateParamsArg TemplateParams) { 11570 const DeclSpec &DS = D.getDeclSpec(); 11571 11572 assert(DS.isFriendSpecified()); 11573 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11574 11575 SourceLocation Loc = D.getIdentifierLoc(); 11576 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11577 11578 // C++ [class.friend]p1 11579 // A friend of a class is a function or class.... 11580 // Note that this sees through typedefs, which is intended. 11581 // It *doesn't* see through dependent types, which is correct 11582 // according to [temp.arg.type]p3: 11583 // If a declaration acquires a function type through a 11584 // type dependent on a template-parameter and this causes 11585 // a declaration that does not use the syntactic form of a 11586 // function declarator to have a function type, the program 11587 // is ill-formed. 11588 if (!TInfo->getType()->isFunctionType()) { 11589 Diag(Loc, diag::err_unexpected_friend); 11590 11591 // It might be worthwhile to try to recover by creating an 11592 // appropriate declaration. 11593 return 0; 11594 } 11595 11596 // C++ [namespace.memdef]p3 11597 // - If a friend declaration in a non-local class first declares a 11598 // class or function, the friend class or function is a member 11599 // of the innermost enclosing namespace. 11600 // - The name of the friend is not found by simple name lookup 11601 // until a matching declaration is provided in that namespace 11602 // scope (either before or after the class declaration granting 11603 // friendship). 11604 // - If a friend function is called, its name may be found by the 11605 // name lookup that considers functions from namespaces and 11606 // classes associated with the types of the function arguments. 11607 // - When looking for a prior declaration of a class or a function 11608 // declared as a friend, scopes outside the innermost enclosing 11609 // namespace scope are not considered. 11610 11611 CXXScopeSpec &SS = D.getCXXScopeSpec(); 11612 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 11613 DeclarationName Name = NameInfo.getName(); 11614 assert(Name); 11615 11616 // Check for unexpanded parameter packs. 11617 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 11618 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 11619 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 11620 return 0; 11621 11622 // The context we found the declaration in, or in which we should 11623 // create the declaration. 11624 DeclContext *DC; 11625 Scope *DCScope = S; 11626 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11627 ForRedeclaration); 11628 11629 // There are five cases here. 11630 // - There's no scope specifier and we're in a local class. Only look 11631 // for functions declared in the immediately-enclosing block scope. 11632 // We recover from invalid scope qualifiers as if they just weren't there. 11633 FunctionDecl *FunctionContainingLocalClass = 0; 11634 if ((SS.isInvalid() || !SS.isSet()) && 11635 (FunctionContainingLocalClass = 11636 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 11637 // C++11 [class.friend]p11: 11638 // If a friend declaration appears in a local class and the name 11639 // specified is an unqualified name, a prior declaration is 11640 // looked up without considering scopes that are outside the 11641 // innermost enclosing non-class scope. For a friend function 11642 // declaration, if there is no prior declaration, the program is 11643 // ill-formed. 11644 11645 // Find the innermost enclosing non-class scope. This is the block 11646 // scope containing the local class definition (or for a nested class, 11647 // the outer local class). 11648 DCScope = S->getFnParent(); 11649 11650 // Look up the function name in the scope. 11651 Previous.clear(LookupLocalFriendName); 11652 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 11653 11654 if (!Previous.empty()) { 11655 // All possible previous declarations must have the same context: 11656 // either they were declared at block scope or they are members of 11657 // one of the enclosing local classes. 11658 DC = Previous.getRepresentativeDecl()->getDeclContext(); 11659 } else { 11660 // This is ill-formed, but provide the context that we would have 11661 // declared the function in, if we were permitted to, for error recovery. 11662 DC = FunctionContainingLocalClass; 11663 } 11664 adjustContextForLocalExternDecl(DC); 11665 11666 // C++ [class.friend]p6: 11667 // A function can be defined in a friend declaration of a class if and 11668 // only if the class is a non-local class (9.8), the function name is 11669 // unqualified, and the function has namespace scope. 11670 if (D.isFunctionDefinition()) { 11671 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11672 } 11673 11674 // - There's no scope specifier, in which case we just go to the 11675 // appropriate scope and look for a function or function template 11676 // there as appropriate. 11677 } else if (SS.isInvalid() || !SS.isSet()) { 11678 // C++11 [namespace.memdef]p3: 11679 // If the name in a friend declaration is neither qualified nor 11680 // a template-id and the declaration is a function or an 11681 // elaborated-type-specifier, the lookup to determine whether 11682 // the entity has been previously declared shall not consider 11683 // any scopes outside the innermost enclosing namespace. 11684 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 11685 11686 // Find the appropriate context according to the above. 11687 DC = CurContext; 11688 11689 // Skip class contexts. If someone can cite chapter and verse 11690 // for this behavior, that would be nice --- it's what GCC and 11691 // EDG do, and it seems like a reasonable intent, but the spec 11692 // really only says that checks for unqualified existing 11693 // declarations should stop at the nearest enclosing namespace, 11694 // not that they should only consider the nearest enclosing 11695 // namespace. 11696 while (DC->isRecord()) 11697 DC = DC->getParent(); 11698 11699 DeclContext *LookupDC = DC; 11700 while (LookupDC->isTransparentContext()) 11701 LookupDC = LookupDC->getParent(); 11702 11703 while (true) { 11704 LookupQualifiedName(Previous, LookupDC); 11705 11706 if (!Previous.empty()) { 11707 DC = LookupDC; 11708 break; 11709 } 11710 11711 if (isTemplateId) { 11712 if (isa<TranslationUnitDecl>(LookupDC)) break; 11713 } else { 11714 if (LookupDC->isFileContext()) break; 11715 } 11716 LookupDC = LookupDC->getParent(); 11717 } 11718 11719 DCScope = getScopeForDeclContext(S, DC); 11720 11721 // - There's a non-dependent scope specifier, in which case we 11722 // compute it and do a previous lookup there for a function 11723 // or function template. 11724 } else if (!SS.getScopeRep()->isDependent()) { 11725 DC = computeDeclContext(SS); 11726 if (!DC) return 0; 11727 11728 if (RequireCompleteDeclContext(SS, DC)) return 0; 11729 11730 LookupQualifiedName(Previous, DC); 11731 11732 // Ignore things found implicitly in the wrong scope. 11733 // TODO: better diagnostics for this case. Suggesting the right 11734 // qualified scope would be nice... 11735 LookupResult::Filter F = Previous.makeFilter(); 11736 while (F.hasNext()) { 11737 NamedDecl *D = F.next(); 11738 if (!DC->InEnclosingNamespaceSetOf( 11739 D->getDeclContext()->getRedeclContext())) 11740 F.erase(); 11741 } 11742 F.done(); 11743 11744 if (Previous.empty()) { 11745 D.setInvalidType(); 11746 Diag(Loc, diag::err_qualified_friend_not_found) 11747 << Name << TInfo->getType(); 11748 return 0; 11749 } 11750 11751 // C++ [class.friend]p1: A friend of a class is a function or 11752 // class that is not a member of the class . . . 11753 if (DC->Equals(CurContext)) 11754 Diag(DS.getFriendSpecLoc(), 11755 getLangOpts().CPlusPlus11 ? 11756 diag::warn_cxx98_compat_friend_is_member : 11757 diag::err_friend_is_member); 11758 11759 if (D.isFunctionDefinition()) { 11760 // C++ [class.friend]p6: 11761 // A function can be defined in a friend declaration of a class if and 11762 // only if the class is a non-local class (9.8), the function name is 11763 // unqualified, and the function has namespace scope. 11764 SemaDiagnosticBuilder DB 11765 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 11766 11767 DB << SS.getScopeRep(); 11768 if (DC->isFileContext()) 11769 DB << FixItHint::CreateRemoval(SS.getRange()); 11770 SS.clear(); 11771 } 11772 11773 // - There's a scope specifier that does not match any template 11774 // parameter lists, in which case we use some arbitrary context, 11775 // create a method or method template, and wait for instantiation. 11776 // - There's a scope specifier that does match some template 11777 // parameter lists, which we don't handle right now. 11778 } else { 11779 if (D.isFunctionDefinition()) { 11780 // C++ [class.friend]p6: 11781 // A function can be defined in a friend declaration of a class if and 11782 // only if the class is a non-local class (9.8), the function name is 11783 // unqualified, and the function has namespace scope. 11784 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 11785 << SS.getScopeRep(); 11786 } 11787 11788 DC = CurContext; 11789 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 11790 } 11791 11792 if (!DC->isRecord()) { 11793 // This implies that it has to be an operator or function. 11794 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 11795 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 11796 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 11797 Diag(Loc, diag::err_introducing_special_friend) << 11798 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 11799 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 11800 return 0; 11801 } 11802 } 11803 11804 // FIXME: This is an egregious hack to cope with cases where the scope stack 11805 // does not contain the declaration context, i.e., in an out-of-line 11806 // definition of a class. 11807 Scope FakeDCScope(S, Scope::DeclScope, Diags); 11808 if (!DCScope) { 11809 FakeDCScope.setEntity(DC); 11810 DCScope = &FakeDCScope; 11811 } 11812 11813 bool AddToScope = true; 11814 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 11815 TemplateParams, AddToScope); 11816 if (!ND) return 0; 11817 11818 assert(ND->getLexicalDeclContext() == CurContext); 11819 11820 // If we performed typo correction, we might have added a scope specifier 11821 // and changed the decl context. 11822 DC = ND->getDeclContext(); 11823 11824 // Add the function declaration to the appropriate lookup tables, 11825 // adjusting the redeclarations list as necessary. We don't 11826 // want to do this yet if the friending class is dependent. 11827 // 11828 // Also update the scope-based lookup if the target context's 11829 // lookup context is in lexical scope. 11830 if (!CurContext->isDependentContext()) { 11831 DC = DC->getRedeclContext(); 11832 DC->makeDeclVisibleInContext(ND); 11833 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11834 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 11835 } 11836 11837 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 11838 D.getIdentifierLoc(), ND, 11839 DS.getFriendSpecLoc()); 11840 FrD->setAccess(AS_public); 11841 CurContext->addDecl(FrD); 11842 11843 if (ND->isInvalidDecl()) { 11844 FrD->setInvalidDecl(); 11845 } else { 11846 if (DC->isRecord()) CheckFriendAccess(ND); 11847 11848 FunctionDecl *FD; 11849 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 11850 FD = FTD->getTemplatedDecl(); 11851 else 11852 FD = cast<FunctionDecl>(ND); 11853 11854 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 11855 // default argument expression, that declaration shall be a definition 11856 // and shall be the only declaration of the function or function 11857 // template in the translation unit. 11858 if (functionDeclHasDefaultArgument(FD)) { 11859 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 11860 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 11861 Diag(OldFD->getLocation(), diag::note_previous_declaration); 11862 } else if (!D.isFunctionDefinition()) 11863 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 11864 } 11865 11866 // Mark templated-scope function declarations as unsupported. 11867 if (FD->getNumTemplateParameterLists()) 11868 FrD->setUnsupportedFriend(true); 11869 } 11870 11871 return ND; 11872 } 11873 11874 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 11875 AdjustDeclIfTemplate(Dcl); 11876 11877 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 11878 if (!Fn) { 11879 Diag(DelLoc, diag::err_deleted_non_function); 11880 return; 11881 } 11882 11883 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 11884 // Don't consider the implicit declaration we generate for explicit 11885 // specializations. FIXME: Do not generate these implicit declarations. 11886 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 11887 Prev->getPreviousDecl()) && 11888 !Prev->isDefined()) { 11889 Diag(DelLoc, diag::err_deleted_decl_not_first); 11890 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 11891 Prev->isImplicit() ? diag::note_previous_implicit_declaration 11892 : diag::note_previous_declaration); 11893 } 11894 // If the declaration wasn't the first, we delete the function anyway for 11895 // recovery. 11896 Fn = Fn->getCanonicalDecl(); 11897 } 11898 11899 if (Fn->isDeleted()) 11900 return; 11901 11902 // See if we're deleting a function which is already known to override a 11903 // non-deleted virtual function. 11904 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 11905 bool IssuedDiagnostic = false; 11906 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 11907 E = MD->end_overridden_methods(); 11908 I != E; ++I) { 11909 if (!(*MD->begin_overridden_methods())->isDeleted()) { 11910 if (!IssuedDiagnostic) { 11911 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 11912 IssuedDiagnostic = true; 11913 } 11914 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 11915 } 11916 } 11917 } 11918 11919 // C++11 [basic.start.main]p3: 11920 // A program that defines main as deleted [...] is ill-formed. 11921 if (Fn->isMain()) 11922 Diag(DelLoc, diag::err_deleted_main); 11923 11924 Fn->setDeletedAsWritten(); 11925 } 11926 11927 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 11928 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 11929 11930 if (MD) { 11931 if (MD->getParent()->isDependentType()) { 11932 MD->setDefaulted(); 11933 MD->setExplicitlyDefaulted(); 11934 return; 11935 } 11936 11937 CXXSpecialMember Member = getSpecialMember(MD); 11938 if (Member == CXXInvalid) { 11939 if (!MD->isInvalidDecl()) 11940 Diag(DefaultLoc, diag::err_default_special_members); 11941 return; 11942 } 11943 11944 MD->setDefaulted(); 11945 MD->setExplicitlyDefaulted(); 11946 11947 // If this definition appears within the record, do the checking when 11948 // the record is complete. 11949 const FunctionDecl *Primary = MD; 11950 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 11951 // Find the uninstantiated declaration that actually had the '= default' 11952 // on it. 11953 Pattern->isDefined(Primary); 11954 11955 // If the method was defaulted on its first declaration, we will have 11956 // already performed the checking in CheckCompletedCXXClass. Such a 11957 // declaration doesn't trigger an implicit definition. 11958 if (Primary == Primary->getCanonicalDecl()) 11959 return; 11960 11961 CheckExplicitlyDefaultedSpecialMember(MD); 11962 11963 // The exception specification is needed because we are defining the 11964 // function. 11965 ResolveExceptionSpec(DefaultLoc, 11966 MD->getType()->castAs<FunctionProtoType>()); 11967 11968 if (MD->isInvalidDecl()) 11969 return; 11970 11971 switch (Member) { 11972 case CXXDefaultConstructor: 11973 DefineImplicitDefaultConstructor(DefaultLoc, 11974 cast<CXXConstructorDecl>(MD)); 11975 break; 11976 case CXXCopyConstructor: 11977 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 11978 break; 11979 case CXXCopyAssignment: 11980 DefineImplicitCopyAssignment(DefaultLoc, MD); 11981 break; 11982 case CXXDestructor: 11983 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 11984 break; 11985 case CXXMoveConstructor: 11986 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 11987 break; 11988 case CXXMoveAssignment: 11989 DefineImplicitMoveAssignment(DefaultLoc, MD); 11990 break; 11991 case CXXInvalid: 11992 llvm_unreachable("Invalid special member."); 11993 } 11994 } else { 11995 Diag(DefaultLoc, diag::err_default_special_members); 11996 } 11997 } 11998 11999 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12000 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12001 Stmt *SubStmt = *CI; 12002 if (!SubStmt) 12003 continue; 12004 if (isa<ReturnStmt>(SubStmt)) 12005 Self.Diag(SubStmt->getLocStart(), 12006 diag::err_return_in_constructor_handler); 12007 if (!isa<Expr>(SubStmt)) 12008 SearchForReturnInStmt(Self, SubStmt); 12009 } 12010 } 12011 12012 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12013 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12014 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12015 SearchForReturnInStmt(*this, Handler); 12016 } 12017 } 12018 12019 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12020 const CXXMethodDecl *Old) { 12021 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12022 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12023 12024 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12025 12026 // If the calling conventions match, everything is fine 12027 if (NewCC == OldCC) 12028 return false; 12029 12030 // If the calling conventions mismatch because the new function is static, 12031 // suppress the calling convention mismatch error; the error about static 12032 // function override (err_static_overrides_virtual from 12033 // Sema::CheckFunctionDeclaration) is more clear. 12034 if (New->getStorageClass() == SC_Static) 12035 return false; 12036 12037 Diag(New->getLocation(), 12038 diag::err_conflicting_overriding_cc_attributes) 12039 << New->getDeclName() << New->getType() << Old->getType(); 12040 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12041 return true; 12042 } 12043 12044 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12045 const CXXMethodDecl *Old) { 12046 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12047 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12048 12049 if (Context.hasSameType(NewTy, OldTy) || 12050 NewTy->isDependentType() || OldTy->isDependentType()) 12051 return false; 12052 12053 // Check if the return types are covariant 12054 QualType NewClassTy, OldClassTy; 12055 12056 /// Both types must be pointers or references to classes. 12057 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12058 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12059 NewClassTy = NewPT->getPointeeType(); 12060 OldClassTy = OldPT->getPointeeType(); 12061 } 12062 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12063 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12064 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12065 NewClassTy = NewRT->getPointeeType(); 12066 OldClassTy = OldRT->getPointeeType(); 12067 } 12068 } 12069 } 12070 12071 // The return types aren't either both pointers or references to a class type. 12072 if (NewClassTy.isNull()) { 12073 Diag(New->getLocation(), 12074 diag::err_different_return_type_for_overriding_virtual_function) 12075 << New->getDeclName() << NewTy << OldTy; 12076 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12077 12078 return true; 12079 } 12080 12081 // C++ [class.virtual]p6: 12082 // If the return type of D::f differs from the return type of B::f, the 12083 // class type in the return type of D::f shall be complete at the point of 12084 // declaration of D::f or shall be the class type D. 12085 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12086 if (!RT->isBeingDefined() && 12087 RequireCompleteType(New->getLocation(), NewClassTy, 12088 diag::err_covariant_return_incomplete, 12089 New->getDeclName())) 12090 return true; 12091 } 12092 12093 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12094 // Check if the new class derives from the old class. 12095 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12096 Diag(New->getLocation(), 12097 diag::err_covariant_return_not_derived) 12098 << New->getDeclName() << NewTy << OldTy; 12099 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12100 return true; 12101 } 12102 12103 // Check if we the conversion from derived to base is valid. 12104 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 12105 diag::err_covariant_return_inaccessible_base, 12106 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12107 // FIXME: Should this point to the return type? 12108 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 12109 // FIXME: this note won't trigger for delayed access control 12110 // diagnostics, and it's impossible to get an undelayed error 12111 // here from access control during the original parse because 12112 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12113 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12114 return true; 12115 } 12116 } 12117 12118 // The qualifiers of the return types must be the same. 12119 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12120 Diag(New->getLocation(), 12121 diag::err_covariant_return_type_different_qualifications) 12122 << New->getDeclName() << NewTy << OldTy; 12123 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12124 return true; 12125 }; 12126 12127 12128 // The new class type must have the same or less qualifiers as the old type. 12129 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12130 Diag(New->getLocation(), 12131 diag::err_covariant_return_type_class_type_more_qualified) 12132 << New->getDeclName() << NewTy << OldTy; 12133 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12134 return true; 12135 }; 12136 12137 return false; 12138 } 12139 12140 /// \brief Mark the given method pure. 12141 /// 12142 /// \param Method the method to be marked pure. 12143 /// 12144 /// \param InitRange the source range that covers the "0" initializer. 12145 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12146 SourceLocation EndLoc = InitRange.getEnd(); 12147 if (EndLoc.isValid()) 12148 Method->setRangeEnd(EndLoc); 12149 12150 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12151 Method->setPure(); 12152 return false; 12153 } 12154 12155 if (!Method->isInvalidDecl()) 12156 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12157 << Method->getDeclName() << InitRange; 12158 return true; 12159 } 12160 12161 /// \brief Determine whether the given declaration is a static data member. 12162 static bool isStaticDataMember(const Decl *D) { 12163 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12164 return Var->isStaticDataMember(); 12165 12166 return false; 12167 } 12168 12169 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12170 /// an initializer for the out-of-line declaration 'Dcl'. The scope 12171 /// is a fresh scope pushed for just this purpose. 12172 /// 12173 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12174 /// static data member of class X, names should be looked up in the scope of 12175 /// class X. 12176 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12177 // If there is no declaration, there was an error parsing it. 12178 if (D == 0 || D->isInvalidDecl()) return; 12179 12180 // We will always have a nested name specifier here, but this declaration 12181 // might not be out of line if the specifier names the current namespace: 12182 // extern int n; 12183 // int ::n = 0; 12184 if (D->isOutOfLine()) 12185 EnterDeclaratorContext(S, D->getDeclContext()); 12186 12187 // If we are parsing the initializer for a static data member, push a 12188 // new expression evaluation context that is associated with this static 12189 // data member. 12190 if (isStaticDataMember(D)) 12191 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12192 } 12193 12194 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12195 /// initializer for the out-of-line declaration 'D'. 12196 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12197 // If there is no declaration, there was an error parsing it. 12198 if (D == 0 || D->isInvalidDecl()) return; 12199 12200 if (isStaticDataMember(D)) 12201 PopExpressionEvaluationContext(); 12202 12203 if (D->isOutOfLine()) 12204 ExitDeclaratorContext(S); 12205 } 12206 12207 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 12208 /// C++ if/switch/while/for statement. 12209 /// e.g: "if (int x = f()) {...}" 12210 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 12211 // C++ 6.4p2: 12212 // The declarator shall not specify a function or an array. 12213 // The type-specifier-seq shall not contain typedef and shall not declare a 12214 // new class or enumeration. 12215 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 12216 "Parser allowed 'typedef' as storage class of condition decl."); 12217 12218 Decl *Dcl = ActOnDeclarator(S, D); 12219 if (!Dcl) 12220 return true; 12221 12222 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 12223 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 12224 << D.getSourceRange(); 12225 return true; 12226 } 12227 12228 return Dcl; 12229 } 12230 12231 void Sema::LoadExternalVTableUses() { 12232 if (!ExternalSource) 12233 return; 12234 12235 SmallVector<ExternalVTableUse, 4> VTables; 12236 ExternalSource->ReadUsedVTables(VTables); 12237 SmallVector<VTableUse, 4> NewUses; 12238 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 12239 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 12240 = VTablesUsed.find(VTables[I].Record); 12241 // Even if a definition wasn't required before, it may be required now. 12242 if (Pos != VTablesUsed.end()) { 12243 if (!Pos->second && VTables[I].DefinitionRequired) 12244 Pos->second = true; 12245 continue; 12246 } 12247 12248 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 12249 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 12250 } 12251 12252 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 12253 } 12254 12255 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 12256 bool DefinitionRequired) { 12257 // Ignore any vtable uses in unevaluated operands or for classes that do 12258 // not have a vtable. 12259 if (!Class->isDynamicClass() || Class->isDependentContext() || 12260 CurContext->isDependentContext() || isUnevaluatedContext()) 12261 return; 12262 12263 // Try to insert this class into the map. 12264 LoadExternalVTableUses(); 12265 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12266 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 12267 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 12268 if (!Pos.second) { 12269 // If we already had an entry, check to see if we are promoting this vtable 12270 // to required a definition. If so, we need to reappend to the VTableUses 12271 // list, since we may have already processed the first entry. 12272 if (DefinitionRequired && !Pos.first->second) { 12273 Pos.first->second = true; 12274 } else { 12275 // Otherwise, we can early exit. 12276 return; 12277 } 12278 } else { 12279 // The Microsoft ABI requires that we perform the destructor body 12280 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 12281 // the deleting destructor is emitted with the vtable, not with the 12282 // destructor definition as in the Itanium ABI. 12283 // If it has a definition, we do the check at that point instead. 12284 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12285 Class->hasUserDeclaredDestructor() && 12286 !Class->getDestructor()->isDefined() && 12287 !Class->getDestructor()->isDeleted()) { 12288 CheckDestructor(Class->getDestructor()); 12289 } 12290 } 12291 12292 // Local classes need to have their virtual members marked 12293 // immediately. For all other classes, we mark their virtual members 12294 // at the end of the translation unit. 12295 if (Class->isLocalClass()) 12296 MarkVirtualMembersReferenced(Loc, Class); 12297 else 12298 VTableUses.push_back(std::make_pair(Class, Loc)); 12299 } 12300 12301 bool Sema::DefineUsedVTables() { 12302 LoadExternalVTableUses(); 12303 if (VTableUses.empty()) 12304 return false; 12305 12306 // Note: The VTableUses vector could grow as a result of marking 12307 // the members of a class as "used", so we check the size each 12308 // time through the loop and prefer indices (which are stable) to 12309 // iterators (which are not). 12310 bool DefinedAnything = false; 12311 for (unsigned I = 0; I != VTableUses.size(); ++I) { 12312 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 12313 if (!Class) 12314 continue; 12315 12316 SourceLocation Loc = VTableUses[I].second; 12317 12318 bool DefineVTable = true; 12319 12320 // If this class has a key function, but that key function is 12321 // defined in another translation unit, we don't need to emit the 12322 // vtable even though we're using it. 12323 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 12324 if (KeyFunction && !KeyFunction->hasBody()) { 12325 // The key function is in another translation unit. 12326 DefineVTable = false; 12327 TemplateSpecializationKind TSK = 12328 KeyFunction->getTemplateSpecializationKind(); 12329 assert(TSK != TSK_ExplicitInstantiationDefinition && 12330 TSK != TSK_ImplicitInstantiation && 12331 "Instantiations don't have key functions"); 12332 (void)TSK; 12333 } else if (!KeyFunction) { 12334 // If we have a class with no key function that is the subject 12335 // of an explicit instantiation declaration, suppress the 12336 // vtable; it will live with the explicit instantiation 12337 // definition. 12338 bool IsExplicitInstantiationDeclaration 12339 = Class->getTemplateSpecializationKind() 12340 == TSK_ExplicitInstantiationDeclaration; 12341 for (auto R : Class->redecls()) { 12342 TemplateSpecializationKind TSK 12343 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 12344 if (TSK == TSK_ExplicitInstantiationDeclaration) 12345 IsExplicitInstantiationDeclaration = true; 12346 else if (TSK == TSK_ExplicitInstantiationDefinition) { 12347 IsExplicitInstantiationDeclaration = false; 12348 break; 12349 } 12350 } 12351 12352 if (IsExplicitInstantiationDeclaration) 12353 DefineVTable = false; 12354 } 12355 12356 // The exception specifications for all virtual members may be needed even 12357 // if we are not providing an authoritative form of the vtable in this TU. 12358 // We may choose to emit it available_externally anyway. 12359 if (!DefineVTable) { 12360 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 12361 continue; 12362 } 12363 12364 // Mark all of the virtual members of this class as referenced, so 12365 // that we can build a vtable. Then, tell the AST consumer that a 12366 // vtable for this class is required. 12367 DefinedAnything = true; 12368 MarkVirtualMembersReferenced(Loc, Class); 12369 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12370 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 12371 12372 // Optionally warn if we're emitting a weak vtable. 12373 if (Class->isExternallyVisible() && 12374 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 12375 const FunctionDecl *KeyFunctionDef = 0; 12376 if (!KeyFunction || 12377 (KeyFunction->hasBody(KeyFunctionDef) && 12378 KeyFunctionDef->isInlined())) 12379 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 12380 TSK_ExplicitInstantiationDefinition 12381 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 12382 << Class; 12383 } 12384 } 12385 VTableUses.clear(); 12386 12387 return DefinedAnything; 12388 } 12389 12390 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 12391 const CXXRecordDecl *RD) { 12392 for (const auto *I : RD->methods()) 12393 if (I->isVirtual() && !I->isPure()) 12394 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 12395 } 12396 12397 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 12398 const CXXRecordDecl *RD) { 12399 // Mark all functions which will appear in RD's vtable as used. 12400 CXXFinalOverriderMap FinalOverriders; 12401 RD->getFinalOverriders(FinalOverriders); 12402 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 12403 E = FinalOverriders.end(); 12404 I != E; ++I) { 12405 for (OverridingMethods::const_iterator OI = I->second.begin(), 12406 OE = I->second.end(); 12407 OI != OE; ++OI) { 12408 assert(OI->second.size() > 0 && "no final overrider"); 12409 CXXMethodDecl *Overrider = OI->second.front().Method; 12410 12411 // C++ [basic.def.odr]p2: 12412 // [...] A virtual member function is used if it is not pure. [...] 12413 if (!Overrider->isPure()) 12414 MarkFunctionReferenced(Loc, Overrider); 12415 } 12416 } 12417 12418 // Only classes that have virtual bases need a VTT. 12419 if (RD->getNumVBases() == 0) 12420 return; 12421 12422 for (const auto &I : RD->bases()) { 12423 const CXXRecordDecl *Base = 12424 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 12425 if (Base->getNumVBases() == 0) 12426 continue; 12427 MarkVirtualMembersReferenced(Loc, Base); 12428 } 12429 } 12430 12431 /// SetIvarInitializers - This routine builds initialization ASTs for the 12432 /// Objective-C implementation whose ivars need be initialized. 12433 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 12434 if (!getLangOpts().CPlusPlus) 12435 return; 12436 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 12437 SmallVector<ObjCIvarDecl*, 8> ivars; 12438 CollectIvarsToConstructOrDestruct(OID, ivars); 12439 if (ivars.empty()) 12440 return; 12441 SmallVector<CXXCtorInitializer*, 32> AllToInit; 12442 for (unsigned i = 0; i < ivars.size(); i++) { 12443 FieldDecl *Field = ivars[i]; 12444 if (Field->isInvalidDecl()) 12445 continue; 12446 12447 CXXCtorInitializer *Member; 12448 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 12449 InitializationKind InitKind = 12450 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 12451 12452 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 12453 ExprResult MemberInit = 12454 InitSeq.Perform(*this, InitEntity, InitKind, None); 12455 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 12456 // Note, MemberInit could actually come back empty if no initialization 12457 // is required (e.g., because it would call a trivial default constructor) 12458 if (!MemberInit.get() || MemberInit.isInvalid()) 12459 continue; 12460 12461 Member = 12462 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 12463 SourceLocation(), 12464 MemberInit.takeAs<Expr>(), 12465 SourceLocation()); 12466 AllToInit.push_back(Member); 12467 12468 // Be sure that the destructor is accessible and is marked as referenced. 12469 if (const RecordType *RecordTy 12470 = Context.getBaseElementType(Field->getType()) 12471 ->getAs<RecordType>()) { 12472 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 12473 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 12474 MarkFunctionReferenced(Field->getLocation(), Destructor); 12475 CheckDestructorAccess(Field->getLocation(), Destructor, 12476 PDiag(diag::err_access_dtor_ivar) 12477 << Context.getBaseElementType(Field->getType())); 12478 } 12479 } 12480 } 12481 ObjCImplementation->setIvarInitializers(Context, 12482 AllToInit.data(), AllToInit.size()); 12483 } 12484 } 12485 12486 static 12487 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 12488 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 12489 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 12490 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 12491 Sema &S) { 12492 if (Ctor->isInvalidDecl()) 12493 return; 12494 12495 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 12496 12497 // Target may not be determinable yet, for instance if this is a dependent 12498 // call in an uninstantiated template. 12499 if (Target) { 12500 const FunctionDecl *FNTarget = 0; 12501 (void)Target->hasBody(FNTarget); 12502 Target = const_cast<CXXConstructorDecl*>( 12503 cast_or_null<CXXConstructorDecl>(FNTarget)); 12504 } 12505 12506 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 12507 // Avoid dereferencing a null pointer here. 12508 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 12509 12510 if (!Current.insert(Canonical)) 12511 return; 12512 12513 // We know that beyond here, we aren't chaining into a cycle. 12514 if (!Target || !Target->isDelegatingConstructor() || 12515 Target->isInvalidDecl() || Valid.count(TCanonical)) { 12516 Valid.insert(Current.begin(), Current.end()); 12517 Current.clear(); 12518 // We've hit a cycle. 12519 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 12520 Current.count(TCanonical)) { 12521 // If we haven't diagnosed this cycle yet, do so now. 12522 if (!Invalid.count(TCanonical)) { 12523 S.Diag((*Ctor->init_begin())->getSourceLocation(), 12524 diag::warn_delegating_ctor_cycle) 12525 << Ctor; 12526 12527 // Don't add a note for a function delegating directly to itself. 12528 if (TCanonical != Canonical) 12529 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 12530 12531 CXXConstructorDecl *C = Target; 12532 while (C->getCanonicalDecl() != Canonical) { 12533 const FunctionDecl *FNTarget = 0; 12534 (void)C->getTargetConstructor()->hasBody(FNTarget); 12535 assert(FNTarget && "Ctor cycle through bodiless function"); 12536 12537 C = const_cast<CXXConstructorDecl*>( 12538 cast<CXXConstructorDecl>(FNTarget)); 12539 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12540 } 12541 } 12542 12543 Invalid.insert(Current.begin(), Current.end()); 12544 Current.clear(); 12545 } else { 12546 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12547 } 12548 } 12549 12550 12551 void Sema::CheckDelegatingCtorCycles() { 12552 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12553 12554 for (DelegatingCtorDeclsType::iterator 12555 I = DelegatingCtorDecls.begin(ExternalSource), 12556 E = DelegatingCtorDecls.end(); 12557 I != E; ++I) 12558 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 12559 12560 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 12561 CE = Invalid.end(); 12562 CI != CE; ++CI) 12563 (*CI)->setInvalidDecl(); 12564 } 12565 12566 namespace { 12567 /// \brief AST visitor that finds references to the 'this' expression. 12568 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 12569 Sema &S; 12570 12571 public: 12572 explicit FindCXXThisExpr(Sema &S) : S(S) { } 12573 12574 bool VisitCXXThisExpr(CXXThisExpr *E) { 12575 S.Diag(E->getLocation(), diag::err_this_static_member_func) 12576 << E->isImplicit(); 12577 return false; 12578 } 12579 }; 12580 } 12581 12582 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 12583 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12584 if (!TSInfo) 12585 return false; 12586 12587 TypeLoc TL = TSInfo->getTypeLoc(); 12588 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12589 if (!ProtoTL) 12590 return false; 12591 12592 // C++11 [expr.prim.general]p3: 12593 // [The expression this] shall not appear before the optional 12594 // cv-qualifier-seq and it shall not appear within the declaration of a 12595 // static member function (although its type and value category are defined 12596 // within a static member function as they are within a non-static member 12597 // function). [ Note: this is because declaration matching does not occur 12598 // until the complete declarator is known. - end note ] 12599 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12600 FindCXXThisExpr Finder(*this); 12601 12602 // If the return type came after the cv-qualifier-seq, check it now. 12603 if (Proto->hasTrailingReturn() && 12604 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 12605 return true; 12606 12607 // Check the exception specification. 12608 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 12609 return true; 12610 12611 return checkThisInStaticMemberFunctionAttributes(Method); 12612 } 12613 12614 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 12615 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12616 if (!TSInfo) 12617 return false; 12618 12619 TypeLoc TL = TSInfo->getTypeLoc(); 12620 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12621 if (!ProtoTL) 12622 return false; 12623 12624 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12625 FindCXXThisExpr Finder(*this); 12626 12627 switch (Proto->getExceptionSpecType()) { 12628 case EST_Uninstantiated: 12629 case EST_Unevaluated: 12630 case EST_BasicNoexcept: 12631 case EST_DynamicNone: 12632 case EST_MSAny: 12633 case EST_None: 12634 break; 12635 12636 case EST_ComputedNoexcept: 12637 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 12638 return true; 12639 12640 case EST_Dynamic: 12641 for (const auto &E : Proto->exceptions()) { 12642 if (!Finder.TraverseType(E)) 12643 return true; 12644 } 12645 break; 12646 } 12647 12648 return false; 12649 } 12650 12651 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 12652 FindCXXThisExpr Finder(*this); 12653 12654 // Check attributes. 12655 for (const auto *A : Method->attrs()) { 12656 // FIXME: This should be emitted by tblgen. 12657 Expr *Arg = 0; 12658 ArrayRef<Expr *> Args; 12659 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 12660 Arg = G->getArg(); 12661 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 12662 Arg = G->getArg(); 12663 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 12664 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 12665 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 12666 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 12667 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 12668 Arg = ETLF->getSuccessValue(); 12669 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 12670 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 12671 Arg = STLF->getSuccessValue(); 12672 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 12673 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 12674 Arg = LR->getArg(); 12675 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 12676 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 12677 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 12678 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size()); 12679 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 12680 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size()); 12681 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 12682 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size()); 12683 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 12684 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size()); 12685 12686 if (Arg && !Finder.TraverseStmt(Arg)) 12687 return true; 12688 12689 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12690 if (!Finder.TraverseStmt(Args[I])) 12691 return true; 12692 } 12693 } 12694 12695 return false; 12696 } 12697 12698 void 12699 Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12700 ArrayRef<ParsedType> DynamicExceptions, 12701 ArrayRef<SourceRange> DynamicExceptionRanges, 12702 Expr *NoexceptExpr, 12703 SmallVectorImpl<QualType> &Exceptions, 12704 FunctionProtoType::ExtProtoInfo &EPI) { 12705 Exceptions.clear(); 12706 EPI.ExceptionSpecType = EST; 12707 if (EST == EST_Dynamic) { 12708 Exceptions.reserve(DynamicExceptions.size()); 12709 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12710 // FIXME: Preserve type source info. 12711 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12712 12713 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12714 collectUnexpandedParameterPacks(ET, Unexpanded); 12715 if (!Unexpanded.empty()) { 12716 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 12717 UPPC_ExceptionType, 12718 Unexpanded); 12719 continue; 12720 } 12721 12722 // Check that the type is valid for an exception spec, and 12723 // drop it if not. 12724 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 12725 Exceptions.push_back(ET); 12726 } 12727 EPI.NumExceptions = Exceptions.size(); 12728 EPI.Exceptions = Exceptions.data(); 12729 return; 12730 } 12731 12732 if (EST == EST_ComputedNoexcept) { 12733 // If an error occurred, there's no expression here. 12734 if (NoexceptExpr) { 12735 assert((NoexceptExpr->isTypeDependent() || 12736 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 12737 Context.BoolTy) && 12738 "Parser should have made sure that the expression is boolean"); 12739 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 12740 EPI.ExceptionSpecType = EST_BasicNoexcept; 12741 return; 12742 } 12743 12744 if (!NoexceptExpr->isValueDependent()) 12745 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 12746 diag::err_noexcept_needs_constant_expression, 12747 /*AllowFold*/ false).take(); 12748 EPI.NoexceptExpr = NoexceptExpr; 12749 } 12750 return; 12751 } 12752 } 12753 12754 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function 12755 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 12756 // Implicitly declared functions (e.g. copy constructors) are 12757 // __host__ __device__ 12758 if (D->isImplicit()) 12759 return CFT_HostDevice; 12760 12761 if (D->hasAttr<CUDAGlobalAttr>()) 12762 return CFT_Global; 12763 12764 if (D->hasAttr<CUDADeviceAttr>()) { 12765 if (D->hasAttr<CUDAHostAttr>()) 12766 return CFT_HostDevice; 12767 return CFT_Device; 12768 } 12769 12770 return CFT_Host; 12771 } 12772 12773 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 12774 CUDAFunctionTarget CalleeTarget) { 12775 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 12776 // Callable from the device only." 12777 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 12778 return true; 12779 12780 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 12781 // Callable from the host only." 12782 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 12783 // Callable from the host only." 12784 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 12785 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 12786 return true; 12787 12788 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 12789 return true; 12790 12791 return false; 12792 } 12793 12794 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 12795 /// 12796 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 12797 SourceLocation DeclStart, 12798 Declarator &D, Expr *BitWidth, 12799 InClassInitStyle InitStyle, 12800 AccessSpecifier AS, 12801 AttributeList *MSPropertyAttr) { 12802 IdentifierInfo *II = D.getIdentifier(); 12803 if (!II) { 12804 Diag(DeclStart, diag::err_anonymous_property); 12805 return NULL; 12806 } 12807 SourceLocation Loc = D.getIdentifierLoc(); 12808 12809 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12810 QualType T = TInfo->getType(); 12811 if (getLangOpts().CPlusPlus) { 12812 CheckExtraCXXDefaultArguments(D); 12813 12814 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12815 UPPC_DataMemberType)) { 12816 D.setInvalidType(); 12817 T = Context.IntTy; 12818 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12819 } 12820 } 12821 12822 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12823 12824 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12825 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12826 diag::err_invalid_thread) 12827 << DeclSpec::getSpecifierName(TSCS); 12828 12829 // Check to see if this name was declared as a member previously 12830 NamedDecl *PrevDecl = 0; 12831 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12832 LookupName(Previous, S); 12833 switch (Previous.getResultKind()) { 12834 case LookupResult::Found: 12835 case LookupResult::FoundUnresolvedValue: 12836 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12837 break; 12838 12839 case LookupResult::FoundOverloaded: 12840 PrevDecl = Previous.getRepresentativeDecl(); 12841 break; 12842 12843 case LookupResult::NotFound: 12844 case LookupResult::NotFoundInCurrentInstantiation: 12845 case LookupResult::Ambiguous: 12846 break; 12847 } 12848 12849 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12850 // Maybe we will complain about the shadowed template parameter. 12851 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12852 // Just pretend that we didn't see the previous declaration. 12853 PrevDecl = 0; 12854 } 12855 12856 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12857 PrevDecl = 0; 12858 12859 SourceLocation TSSL = D.getLocStart(); 12860 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 12861 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 12862 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 12863 ProcessDeclAttributes(TUScope, NewPD, D); 12864 NewPD->setAccess(AS); 12865 12866 if (NewPD->isInvalidDecl()) 12867 Record->setInvalidDecl(); 12868 12869 if (D.getDeclSpec().isModulePrivateSpecified()) 12870 NewPD->setModulePrivate(); 12871 12872 if (NewPD->isInvalidDecl() && PrevDecl) { 12873 // Don't introduce NewFD into scope; there's already something 12874 // with the same name in the same scope. 12875 } else if (II) { 12876 PushOnScopeChains(NewPD, S); 12877 } else 12878 Record->addDecl(NewPD); 12879 12880 return NewPD; 12881 } 12882