SemaDeclCXX.cpp revision a4bb99cd0055ba0e1f3107890e5b6cbe31e6d1cc
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/ASTMutationListener.h" 18#include "clang/AST/CXXInheritance.h" 19#include "clang/AST/CharUnits.h" 20#include "clang/AST/DeclVisitor.h" 21#include "clang/AST/EvaluatedExprVisitor.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/RecordLayout.h" 24#include "clang/AST/RecursiveASTVisitor.h" 25#include "clang/AST/StmtVisitor.h" 26#include "clang/AST/TypeLoc.h" 27#include "clang/AST/TypeOrdering.h" 28#include "clang/Basic/PartialDiagnostic.h" 29#include "clang/Basic/TargetInfo.h" 30#include "clang/Lex/Preprocessor.h" 31#include "clang/Sema/CXXFieldCollector.h" 32#include "clang/Sema/DeclSpec.h" 33#include "clang/Sema/Initialization.h" 34#include "clang/Sema/Lookup.h" 35#include "clang/Sema/ParsedTemplate.h" 36#include "clang/Sema/Scope.h" 37#include "clang/Sema/ScopeInfo.h" 38#include "llvm/ADT/STLExtras.h" 39#include "llvm/ADT/SmallString.h" 40#include <map> 41#include <set> 42 43using namespace clang; 44 45//===----------------------------------------------------------------------===// 46// CheckDefaultArgumentVisitor 47//===----------------------------------------------------------------------===// 48 49namespace { 50 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 51 /// the default argument of a parameter to determine whether it 52 /// contains any ill-formed subexpressions. For example, this will 53 /// diagnose the use of local variables or parameters within the 54 /// default argument expression. 55 class CheckDefaultArgumentVisitor 56 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 57 Expr *DefaultArg; 58 Sema *S; 59 60 public: 61 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 62 : DefaultArg(defarg), S(s) {} 63 64 bool VisitExpr(Expr *Node); 65 bool VisitDeclRefExpr(DeclRefExpr *DRE); 66 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 67 bool VisitLambdaExpr(LambdaExpr *Lambda); 68 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 69 }; 70 71 /// VisitExpr - Visit all of the children of this expression. 72 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 73 bool IsInvalid = false; 74 for (Stmt::child_range I = Node->children(); I; ++I) 75 IsInvalid |= Visit(*I); 76 return IsInvalid; 77 } 78 79 /// VisitDeclRefExpr - Visit a reference to a declaration, to 80 /// determine whether this declaration can be used in the default 81 /// argument expression. 82 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 83 NamedDecl *Decl = DRE->getDecl(); 84 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 85 // C++ [dcl.fct.default]p9 86 // Default arguments are evaluated each time the function is 87 // called. The order of evaluation of function arguments is 88 // unspecified. Consequently, parameters of a function shall not 89 // be used in default argument expressions, even if they are not 90 // evaluated. Parameters of a function declared before a default 91 // argument expression are in scope and can hide namespace and 92 // class member names. 93 return S->Diag(DRE->getLocStart(), 94 diag::err_param_default_argument_references_param) 95 << Param->getDeclName() << DefaultArg->getSourceRange(); 96 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 97 // C++ [dcl.fct.default]p7 98 // Local variables shall not be used in default argument 99 // expressions. 100 if (VDecl->isLocalVarDecl()) 101 return S->Diag(DRE->getLocStart(), 102 diag::err_param_default_argument_references_local) 103 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 104 } 105 106 return false; 107 } 108 109 /// VisitCXXThisExpr - Visit a C++ "this" expression. 110 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 111 // C++ [dcl.fct.default]p8: 112 // The keyword this shall not be used in a default argument of a 113 // member function. 114 return S->Diag(ThisE->getLocStart(), 115 diag::err_param_default_argument_references_this) 116 << ThisE->getSourceRange(); 117 } 118 119 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 120 bool Invalid = false; 121 for (PseudoObjectExpr::semantics_iterator 122 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 123 Expr *E = *i; 124 125 // Look through bindings. 126 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 127 E = OVE->getSourceExpr(); 128 assert(E && "pseudo-object binding without source expression?"); 129 } 130 131 Invalid |= Visit(E); 132 } 133 return Invalid; 134 } 135 136 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 137 // C++11 [expr.lambda.prim]p13: 138 // A lambda-expression appearing in a default argument shall not 139 // implicitly or explicitly capture any entity. 140 if (Lambda->capture_begin() == Lambda->capture_end()) 141 return false; 142 143 return S->Diag(Lambda->getLocStart(), 144 diag::err_lambda_capture_default_arg); 145 } 146} 147 148void 149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 150 const CXXMethodDecl *Method) { 151 // If we have an MSAny spec already, don't bother. 152 if (!Method || ComputedEST == EST_MSAny) 153 return; 154 155 const FunctionProtoType *Proto 156 = Method->getType()->getAs<FunctionProtoType>(); 157 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 158 if (!Proto) 159 return; 160 161 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 162 163 // If this function can throw any exceptions, make a note of that. 164 if (EST == EST_MSAny || EST == EST_None) { 165 ClearExceptions(); 166 ComputedEST = EST; 167 return; 168 } 169 170 // FIXME: If the call to this decl is using any of its default arguments, we 171 // need to search them for potentially-throwing calls. 172 173 // If this function has a basic noexcept, it doesn't affect the outcome. 174 if (EST == EST_BasicNoexcept) 175 return; 176 177 // If we have a throw-all spec at this point, ignore the function. 178 if (ComputedEST == EST_None) 179 return; 180 181 // If we're still at noexcept(true) and there's a nothrow() callee, 182 // change to that specification. 183 if (EST == EST_DynamicNone) { 184 if (ComputedEST == EST_BasicNoexcept) 185 ComputedEST = EST_DynamicNone; 186 return; 187 } 188 189 // Check out noexcept specs. 190 if (EST == EST_ComputedNoexcept) { 191 FunctionProtoType::NoexceptResult NR = 192 Proto->getNoexceptSpec(Self->Context); 193 assert(NR != FunctionProtoType::NR_NoNoexcept && 194 "Must have noexcept result for EST_ComputedNoexcept."); 195 assert(NR != FunctionProtoType::NR_Dependent && 196 "Should not generate implicit declarations for dependent cases, " 197 "and don't know how to handle them anyway."); 198 199 // noexcept(false) -> no spec on the new function 200 if (NR == FunctionProtoType::NR_Throw) { 201 ClearExceptions(); 202 ComputedEST = EST_None; 203 } 204 // noexcept(true) won't change anything either. 205 return; 206 } 207 208 assert(EST == EST_Dynamic && "EST case not considered earlier."); 209 assert(ComputedEST != EST_None && 210 "Shouldn't collect exceptions when throw-all is guaranteed."); 211 ComputedEST = EST_Dynamic; 212 // Record the exceptions in this function's exception specification. 213 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 214 EEnd = Proto->exception_end(); 215 E != EEnd; ++E) 216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E))) 217 Exceptions.push_back(*E); 218} 219 220void 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 249bool 250Sema::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. 298void 299Sema::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. 335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 336 SourceLocation EqualLoc, 337 SourceLocation ArgLoc) { 338 if (!param) 339 return; 340 341 ParmVarDecl *Param = cast<ParmVarDecl>(param); 342 if (Param) 343 Param->setUnparsedDefaultArg(); 344 345 UnparsedDefaultArgLocs[Param] = ArgLoc; 346} 347 348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 349/// the default argument for the parameter param failed. 350void Sema::ActOnParamDefaultArgumentError(Decl *param) { 351 if (!param) 352 return; 353 354 ParmVarDecl *Param = cast<ParmVarDecl>(param); 355 356 Param->setInvalidDecl(); 357 358 UnparsedDefaultArgLocs.erase(Param); 359} 360 361/// CheckExtraCXXDefaultArguments - Check for any extra default 362/// arguments in the declarator, which is not a function declaration 363/// or definition and therefore is not permitted to have default 364/// arguments. This routine should be invoked for every declarator 365/// that is not a function declaration or definition. 366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 367 // C++ [dcl.fct.default]p3 368 // A default argument expression shall be specified only in the 369 // parameter-declaration-clause of a function declaration or in a 370 // template-parameter (14.1). It shall not be specified for a 371 // parameter pack. If it is specified in a 372 // parameter-declaration-clause, it shall not occur within a 373 // declarator or abstract-declarator of a parameter-declaration. 374 bool MightBeFunction = D.isFunctionDeclarationContext(); 375 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 376 DeclaratorChunk &chunk = D.getTypeObject(i); 377 if (chunk.Kind == DeclaratorChunk::Function) { 378 if (MightBeFunction) { 379 // This is a function declaration. It can have default arguments, but 380 // keep looking in case its return type is a function type with default 381 // arguments. 382 MightBeFunction = false; 383 continue; 384 } 385 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 386 ParmVarDecl *Param = 387 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 388 if (Param->hasUnparsedDefaultArg()) { 389 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 390 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 391 << SourceRange((*Toks)[1].getLocation(), 392 Toks->back().getLocation()); 393 delete Toks; 394 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 395 } else if (Param->getDefaultArg()) { 396 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 397 << Param->getDefaultArg()->getSourceRange(); 398 Param->setDefaultArg(0); 399 } 400 } 401 } else if (chunk.Kind != DeclaratorChunk::Paren) { 402 MightBeFunction = false; 403 } 404 } 405} 406 407/// MergeCXXFunctionDecl - Merge two declarations of the same C++ 408/// function, once we already know that they have the same 409/// type. Subroutine of MergeFunctionDecl. Returns true if there was an 410/// error, false otherwise. 411bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 412 Scope *S) { 413 bool Invalid = false; 414 415 // C++ [dcl.fct.default]p4: 416 // For non-template functions, default arguments can be added in 417 // later declarations of a function in the same 418 // scope. Declarations in different scopes have completely 419 // distinct sets of default arguments. That is, declarations in 420 // inner scopes do not acquire default arguments from 421 // declarations in outer scopes, and vice versa. In a given 422 // function declaration, all parameters subsequent to a 423 // parameter with a default argument shall have default 424 // arguments supplied in this or previous declarations. A 425 // default argument shall not be redefined by a later 426 // declaration (not even to the same value). 427 // 428 // C++ [dcl.fct.default]p6: 429 // Except for member functions of class templates, the default arguments 430 // in a member function definition that appears outside of the class 431 // definition are added to the set of default arguments provided by the 432 // member function declaration in the class definition. 433 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 434 ParmVarDecl *OldParam = Old->getParamDecl(p); 435 ParmVarDecl *NewParam = New->getParamDecl(p); 436 437 bool OldParamHasDfl = OldParam->hasDefaultArg(); 438 bool NewParamHasDfl = NewParam->hasDefaultArg(); 439 440 NamedDecl *ND = Old; 441 if (S && !isDeclInScope(ND, New->getDeclContext(), S)) 442 // Ignore default parameters of old decl if they are not in 443 // the same scope. 444 OldParamHasDfl = false; 445 446 if (OldParamHasDfl && NewParamHasDfl) { 447 448 unsigned DiagDefaultParamID = 449 diag::err_param_default_argument_redefinition; 450 451 // MSVC accepts that default parameters be redefined for member functions 452 // of template class. The new default parameter's value is ignored. 453 Invalid = true; 454 if (getLangOpts().MicrosoftExt) { 455 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 456 if (MD && MD->getParent()->getDescribedClassTemplate()) { 457 // Merge the old default argument into the new parameter. 458 NewParam->setHasInheritedDefaultArg(); 459 if (OldParam->hasUninstantiatedDefaultArg()) 460 NewParam->setUninstantiatedDefaultArg( 461 OldParam->getUninstantiatedDefaultArg()); 462 else 463 NewParam->setDefaultArg(OldParam->getInit()); 464 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 465 Invalid = false; 466 } 467 } 468 469 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 470 // hint here. Alternatively, we could walk the type-source information 471 // for NewParam to find the last source location in the type... but it 472 // isn't worth the effort right now. This is the kind of test case that 473 // is hard to get right: 474 // int f(int); 475 // void g(int (*fp)(int) = f); 476 // void g(int (*fp)(int) = &f); 477 Diag(NewParam->getLocation(), DiagDefaultParamID) 478 << NewParam->getDefaultArgRange(); 479 480 // Look for the function declaration where the default argument was 481 // actually written, which may be a declaration prior to Old. 482 for (FunctionDecl *Older = Old->getPreviousDecl(); 483 Older; Older = Older->getPreviousDecl()) { 484 if (!Older->getParamDecl(p)->hasDefaultArg()) 485 break; 486 487 OldParam = Older->getParamDecl(p); 488 } 489 490 Diag(OldParam->getLocation(), diag::note_previous_definition) 491 << OldParam->getDefaultArgRange(); 492 } else if (OldParamHasDfl) { 493 // Merge the old default argument into the new parameter. 494 // It's important to use getInit() here; getDefaultArg() 495 // strips off any top-level ExprWithCleanups. 496 NewParam->setHasInheritedDefaultArg(); 497 if (OldParam->hasUninstantiatedDefaultArg()) 498 NewParam->setUninstantiatedDefaultArg( 499 OldParam->getUninstantiatedDefaultArg()); 500 else 501 NewParam->setDefaultArg(OldParam->getInit()); 502 } else if (NewParamHasDfl) { 503 if (New->getDescribedFunctionTemplate()) { 504 // Paragraph 4, quoted above, only applies to non-template functions. 505 Diag(NewParam->getLocation(), 506 diag::err_param_default_argument_template_redecl) 507 << NewParam->getDefaultArgRange(); 508 Diag(Old->getLocation(), diag::note_template_prev_declaration) 509 << false; 510 } else if (New->getTemplateSpecializationKind() 511 != TSK_ImplicitInstantiation && 512 New->getTemplateSpecializationKind() != TSK_Undeclared) { 513 // C++ [temp.expr.spec]p21: 514 // Default function arguments shall not be specified in a declaration 515 // or a definition for one of the following explicit specializations: 516 // - the explicit specialization of a function template; 517 // - the explicit specialization of a member function template; 518 // - the explicit specialization of a member function of a class 519 // template where the class template specialization to which the 520 // member function specialization belongs is implicitly 521 // instantiated. 522 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 523 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 524 << New->getDeclName() 525 << NewParam->getDefaultArgRange(); 526 } else if (New->getDeclContext()->isDependentContext()) { 527 // C++ [dcl.fct.default]p6 (DR217): 528 // Default arguments for a member function of a class template shall 529 // be specified on the initial declaration of the member function 530 // within the class template. 531 // 532 // Reading the tea leaves a bit in DR217 and its reference to DR205 533 // leads me to the conclusion that one cannot add default function 534 // arguments for an out-of-line definition of a member function of a 535 // dependent type. 536 int WhichKind = 2; 537 if (CXXRecordDecl *Record 538 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 539 if (Record->getDescribedClassTemplate()) 540 WhichKind = 0; 541 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 542 WhichKind = 1; 543 else 544 WhichKind = 2; 545 } 546 547 Diag(NewParam->getLocation(), 548 diag::err_param_default_argument_member_template_redecl) 549 << WhichKind 550 << NewParam->getDefaultArgRange(); 551 } 552 } 553 } 554 555 // DR1344: If a default argument is added outside a class definition and that 556 // default argument makes the function a special member function, the program 557 // is ill-formed. This can only happen for constructors. 558 if (isa<CXXConstructorDecl>(New) && 559 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 560 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 561 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 562 if (NewSM != OldSM) { 563 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 564 assert(NewParam->hasDefaultArg()); 565 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 566 << NewParam->getDefaultArgRange() << NewSM; 567 Diag(Old->getLocation(), diag::note_previous_declaration); 568 } 569 } 570 571 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 572 // template has a constexpr specifier then all its declarations shall 573 // contain the constexpr specifier. 574 if (New->isConstexpr() != Old->isConstexpr()) { 575 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 576 << New << New->isConstexpr(); 577 Diag(Old->getLocation(), diag::note_previous_declaration); 578 Invalid = true; 579 } 580 581 if (CheckEquivalentExceptionSpec(Old, New)) 582 Invalid = true; 583 584 return Invalid; 585} 586 587/// \brief Merge the exception specifications of two variable declarations. 588/// 589/// This is called when there's a redeclaration of a VarDecl. The function 590/// checks if the redeclaration might have an exception specification and 591/// validates compatibility and merges the specs if necessary. 592void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 593 // Shortcut if exceptions are disabled. 594 if (!getLangOpts().CXXExceptions) 595 return; 596 597 assert(Context.hasSameType(New->getType(), Old->getType()) && 598 "Should only be called if types are otherwise the same."); 599 600 QualType NewType = New->getType(); 601 QualType OldType = Old->getType(); 602 603 // We're only interested in pointers and references to functions, as well 604 // as pointers to member functions. 605 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 606 NewType = R->getPointeeType(); 607 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 608 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 609 NewType = P->getPointeeType(); 610 OldType = OldType->getAs<PointerType>()->getPointeeType(); 611 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 612 NewType = M->getPointeeType(); 613 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 614 } 615 616 if (!NewType->isFunctionProtoType()) 617 return; 618 619 // There's lots of special cases for functions. For function pointers, system 620 // libraries are hopefully not as broken so that we don't need these 621 // workarounds. 622 if (CheckEquivalentExceptionSpec( 623 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 624 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 625 New->setInvalidDecl(); 626 } 627} 628 629/// CheckCXXDefaultArguments - Verify that the default arguments for a 630/// function declaration are well-formed according to C++ 631/// [dcl.fct.default]. 632void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 633 unsigned NumParams = FD->getNumParams(); 634 unsigned p; 635 636 // Find first parameter with a default argument 637 for (p = 0; p < NumParams; ++p) { 638 ParmVarDecl *Param = FD->getParamDecl(p); 639 if (Param->hasDefaultArg()) 640 break; 641 } 642 643 // C++ [dcl.fct.default]p4: 644 // In a given function declaration, all parameters 645 // subsequent to a parameter with a default argument shall 646 // have default arguments supplied in this or previous 647 // declarations. A default argument shall not be redefined 648 // by a later declaration (not even to the same value). 649 unsigned LastMissingDefaultArg = 0; 650 for (; p < NumParams; ++p) { 651 ParmVarDecl *Param = FD->getParamDecl(p); 652 if (!Param->hasDefaultArg()) { 653 if (Param->isInvalidDecl()) 654 /* We already complained about this parameter. */; 655 else if (Param->getIdentifier()) 656 Diag(Param->getLocation(), 657 diag::err_param_default_argument_missing_name) 658 << Param->getIdentifier(); 659 else 660 Diag(Param->getLocation(), 661 diag::err_param_default_argument_missing); 662 663 LastMissingDefaultArg = p; 664 } 665 } 666 667 if (LastMissingDefaultArg > 0) { 668 // Some default arguments were missing. Clear out all of the 669 // default arguments up to (and including) the last missing 670 // default argument, so that we leave the function parameters 671 // in a semantically valid state. 672 for (p = 0; p <= LastMissingDefaultArg; ++p) { 673 ParmVarDecl *Param = FD->getParamDecl(p); 674 if (Param->hasDefaultArg()) { 675 Param->setDefaultArg(0); 676 } 677 } 678 } 679} 680 681// CheckConstexprParameterTypes - Check whether a function's parameter types 682// are all literal types. If so, return true. If not, produce a suitable 683// diagnostic and return false. 684static bool CheckConstexprParameterTypes(Sema &SemaRef, 685 const FunctionDecl *FD) { 686 unsigned ArgIndex = 0; 687 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 688 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 689 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 690 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 691 SourceLocation ParamLoc = PD->getLocation(); 692 if (!(*i)->isDependentType() && 693 SemaRef.RequireLiteralType(ParamLoc, *i, 694 diag::err_constexpr_non_literal_param, 695 ArgIndex+1, PD->getSourceRange(), 696 isa<CXXConstructorDecl>(FD))) 697 return false; 698 } 699 return true; 700} 701 702/// \brief Get diagnostic %select index for tag kind for 703/// record diagnostic message. 704/// WARNING: Indexes apply to particular diagnostics only! 705/// 706/// \returns diagnostic %select index. 707static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 708 switch (Tag) { 709 case TTK_Struct: return 0; 710 case TTK_Interface: return 1; 711 case TTK_Class: return 2; 712 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 713 } 714} 715 716// CheckConstexprFunctionDecl - Check whether a function declaration satisfies 717// the requirements of a constexpr function definition or a constexpr 718// constructor definition. If so, return true. If not, produce appropriate 719// diagnostics and return false. 720// 721// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 722bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 723 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 724 if (MD && MD->isInstance()) { 725 // C++11 [dcl.constexpr]p4: 726 // The definition of a constexpr constructor shall satisfy the following 727 // constraints: 728 // - the class shall not have any virtual base classes; 729 const CXXRecordDecl *RD = MD->getParent(); 730 if (RD->getNumVBases()) { 731 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 732 << isa<CXXConstructorDecl>(NewFD) 733 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 734 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 735 E = RD->vbases_end(); I != E; ++I) 736 Diag(I->getLocStart(), 737 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 738 return false; 739 } 740 } 741 742 if (!isa<CXXConstructorDecl>(NewFD)) { 743 // C++11 [dcl.constexpr]p3: 744 // The definition of a constexpr function shall satisfy the following 745 // constraints: 746 // - it shall not be virtual; 747 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 748 if (Method && Method->isVirtual()) { 749 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 750 751 // If it's not obvious why this function is virtual, find an overridden 752 // function which uses the 'virtual' keyword. 753 const CXXMethodDecl *WrittenVirtual = Method; 754 while (!WrittenVirtual->isVirtualAsWritten()) 755 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 756 if (WrittenVirtual != Method) 757 Diag(WrittenVirtual->getLocation(), 758 diag::note_overridden_virtual_function); 759 return false; 760 } 761 762 // - its return type shall be a literal type; 763 QualType RT = NewFD->getResultType(); 764 if (!RT->isDependentType() && 765 RequireLiteralType(NewFD->getLocation(), RT, 766 diag::err_constexpr_non_literal_return)) 767 return false; 768 } 769 770 // - each of its parameter types shall be a literal type; 771 if (!CheckConstexprParameterTypes(*this, NewFD)) 772 return false; 773 774 return true; 775} 776 777/// Check the given declaration statement is legal within a constexpr function 778/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 779/// 780/// \return true if the body is OK (maybe only as an extension), false if we 781/// have diagnosed a problem. 782static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 783 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 784 // C++11 [dcl.constexpr]p3 and p4: 785 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 786 // contain only 787 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 788 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 789 switch ((*DclIt)->getKind()) { 790 case Decl::StaticAssert: 791 case Decl::Using: 792 case Decl::UsingShadow: 793 case Decl::UsingDirective: 794 case Decl::UnresolvedUsingTypename: 795 case Decl::UnresolvedUsingValue: 796 // - static_assert-declarations 797 // - using-declarations, 798 // - using-directives, 799 continue; 800 801 case Decl::Typedef: 802 case Decl::TypeAlias: { 803 // - typedef declarations and alias-declarations that do not define 804 // classes or enumerations, 805 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 806 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 807 // Don't allow variably-modified types in constexpr functions. 808 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 809 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 810 << TL.getSourceRange() << TL.getType() 811 << isa<CXXConstructorDecl>(Dcl); 812 return false; 813 } 814 continue; 815 } 816 817 case Decl::Enum: 818 case Decl::CXXRecord: 819 // C++1y allows types to be defined, not just declared. 820 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) 821 SemaRef.Diag(DS->getLocStart(), 822 SemaRef.getLangOpts().CPlusPlus1y 823 ? diag::warn_cxx11_compat_constexpr_type_definition 824 : diag::ext_constexpr_type_definition) 825 << isa<CXXConstructorDecl>(Dcl); 826 continue; 827 828 case Decl::EnumConstant: 829 case Decl::IndirectField: 830 case Decl::ParmVar: 831 // These can only appear with other declarations which are banned in 832 // C++11 and permitted in C++1y, so ignore them. 833 continue; 834 835 case Decl::Var: { 836 // C++1y [dcl.constexpr]p3 allows anything except: 837 // a definition of a variable of non-literal type or of static or 838 // thread storage duration or for which no initialization is performed. 839 VarDecl *VD = cast<VarDecl>(*DclIt); 840 if (VD->isThisDeclarationADefinition()) { 841 if (VD->isStaticLocal()) { 842 SemaRef.Diag(VD->getLocation(), 843 diag::err_constexpr_local_var_static) 844 << isa<CXXConstructorDecl>(Dcl) 845 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 846 return false; 847 } 848 if (!VD->getType()->isDependentType() && 849 SemaRef.RequireLiteralType( 850 VD->getLocation(), VD->getType(), 851 diag::err_constexpr_local_var_non_literal_type, 852 isa<CXXConstructorDecl>(Dcl))) 853 return false; 854 if (!VD->hasInit()) { 855 SemaRef.Diag(VD->getLocation(), 856 diag::err_constexpr_local_var_no_init) 857 << isa<CXXConstructorDecl>(Dcl); 858 return false; 859 } 860 } 861 SemaRef.Diag(VD->getLocation(), 862 SemaRef.getLangOpts().CPlusPlus1y 863 ? diag::warn_cxx11_compat_constexpr_local_var 864 : diag::ext_constexpr_local_var) 865 << isa<CXXConstructorDecl>(Dcl); 866 continue; 867 } 868 869 case Decl::NamespaceAlias: 870 case Decl::Function: 871 // These are disallowed in C++11 and permitted in C++1y. Allow them 872 // everywhere as an extension. 873 if (!Cxx1yLoc.isValid()) 874 Cxx1yLoc = DS->getLocStart(); 875 continue; 876 877 default: 878 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 879 << isa<CXXConstructorDecl>(Dcl); 880 return false; 881 } 882 } 883 884 return true; 885} 886 887/// Check that the given field is initialized within a constexpr constructor. 888/// 889/// \param Dcl The constexpr constructor being checked. 890/// \param Field The field being checked. This may be a member of an anonymous 891/// struct or union nested within the class being checked. 892/// \param Inits All declarations, including anonymous struct/union members and 893/// indirect members, for which any initialization was provided. 894/// \param Diagnosed Set to true if an error is produced. 895static void CheckConstexprCtorInitializer(Sema &SemaRef, 896 const FunctionDecl *Dcl, 897 FieldDecl *Field, 898 llvm::SmallSet<Decl*, 16> &Inits, 899 bool &Diagnosed) { 900 if (Field->isUnnamedBitfield()) 901 return; 902 903 if (Field->isAnonymousStructOrUnion() && 904 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 905 return; 906 907 if (!Inits.count(Field)) { 908 if (!Diagnosed) { 909 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 910 Diagnosed = true; 911 } 912 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 913 } else if (Field->isAnonymousStructOrUnion()) { 914 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 915 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 916 I != E; ++I) 917 // If an anonymous union contains an anonymous struct of which any member 918 // is initialized, all members must be initialized. 919 if (!RD->isUnion() || Inits.count(*I)) 920 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 921 } 922} 923 924/// Check the provided statement is allowed in a constexpr function 925/// definition. 926static bool 927CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 928 llvm::SmallVectorImpl<SourceLocation> &ReturnStmts, 929 SourceLocation &Cxx1yLoc) { 930 // - its function-body shall be [...] a compound-statement that contains only 931 switch (S->getStmtClass()) { 932 case Stmt::NullStmtClass: 933 // - null statements, 934 return true; 935 936 case Stmt::DeclStmtClass: 937 // - static_assert-declarations 938 // - using-declarations, 939 // - using-directives, 940 // - typedef declarations and alias-declarations that do not define 941 // classes or enumerations, 942 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 943 return false; 944 return true; 945 946 case Stmt::ReturnStmtClass: 947 // - and exactly one return statement; 948 if (isa<CXXConstructorDecl>(Dcl)) { 949 // C++1y allows return statements in constexpr constructors. 950 if (!Cxx1yLoc.isValid()) 951 Cxx1yLoc = S->getLocStart(); 952 return true; 953 } 954 955 ReturnStmts.push_back(S->getLocStart()); 956 return true; 957 958 case Stmt::CompoundStmtClass: { 959 // C++1y allows compound-statements. 960 if (!Cxx1yLoc.isValid()) 961 Cxx1yLoc = S->getLocStart(); 962 963 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 964 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(), 965 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) { 966 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts, 967 Cxx1yLoc)) 968 return false; 969 } 970 return true; 971 } 972 973 case Stmt::AttributedStmtClass: 974 if (!Cxx1yLoc.isValid()) 975 Cxx1yLoc = S->getLocStart(); 976 return true; 977 978 case Stmt::IfStmtClass: { 979 // C++1y allows if-statements. 980 if (!Cxx1yLoc.isValid()) 981 Cxx1yLoc = S->getLocStart(); 982 983 IfStmt *If = cast<IfStmt>(S); 984 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 985 Cxx1yLoc)) 986 return false; 987 if (If->getElse() && 988 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 989 Cxx1yLoc)) 990 return false; 991 return true; 992 } 993 994 case Stmt::WhileStmtClass: 995 case Stmt::DoStmtClass: 996 case Stmt::ForStmtClass: 997 case Stmt::CXXForRangeStmtClass: 998 case Stmt::ContinueStmtClass: 999 // C++1y allows all of these. We don't allow them as extensions in C++11, 1000 // because they don't make sense without variable mutation. 1001 if (!SemaRef.getLangOpts().CPlusPlus1y) 1002 break; 1003 if (!Cxx1yLoc.isValid()) 1004 Cxx1yLoc = S->getLocStart(); 1005 for (Stmt::child_range Children = S->children(); Children; ++Children) 1006 if (*Children && 1007 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1008 Cxx1yLoc)) 1009 return false; 1010 return true; 1011 1012 case Stmt::SwitchStmtClass: 1013 case Stmt::CaseStmtClass: 1014 case Stmt::DefaultStmtClass: 1015 case Stmt::BreakStmtClass: 1016 // C++1y allows switch-statements, and since they don't need variable 1017 // mutation, we can reasonably allow them in C++11 as an extension. 1018 if (!Cxx1yLoc.isValid()) 1019 Cxx1yLoc = S->getLocStart(); 1020 for (Stmt::child_range Children = S->children(); Children; ++Children) 1021 if (*Children && 1022 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1023 Cxx1yLoc)) 1024 return false; 1025 return true; 1026 1027 default: 1028 if (!isa<Expr>(S)) 1029 break; 1030 1031 // C++1y allows expression-statements. 1032 if (!Cxx1yLoc.isValid()) 1033 Cxx1yLoc = S->getLocStart(); 1034 return true; 1035 } 1036 1037 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1038 << isa<CXXConstructorDecl>(Dcl); 1039 return false; 1040} 1041 1042/// Check the body for the given constexpr function declaration only contains 1043/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1044/// 1045/// \return true if the body is OK, false if we have diagnosed a problem. 1046bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1047 if (isa<CXXTryStmt>(Body)) { 1048 // C++11 [dcl.constexpr]p3: 1049 // The definition of a constexpr function shall satisfy the following 1050 // constraints: [...] 1051 // - its function-body shall be = delete, = default, or a 1052 // compound-statement 1053 // 1054 // C++11 [dcl.constexpr]p4: 1055 // In the definition of a constexpr constructor, [...] 1056 // - its function-body shall not be a function-try-block; 1057 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1058 << isa<CXXConstructorDecl>(Dcl); 1059 return false; 1060 } 1061 1062 SmallVector<SourceLocation, 4> ReturnStmts; 1063 1064 // - its function-body shall be [...] a compound-statement that contains only 1065 // [... list of cases ...] 1066 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1067 SourceLocation Cxx1yLoc; 1068 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 1069 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 1070 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc)) 1071 return false; 1072 } 1073 1074 if (Cxx1yLoc.isValid()) 1075 Diag(Cxx1yLoc, 1076 getLangOpts().CPlusPlus1y 1077 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1078 : diag::ext_constexpr_body_invalid_stmt) 1079 << isa<CXXConstructorDecl>(Dcl); 1080 1081 if (const CXXConstructorDecl *Constructor 1082 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1083 const CXXRecordDecl *RD = Constructor->getParent(); 1084 // DR1359: 1085 // - every non-variant non-static data member and base class sub-object 1086 // shall be initialized; 1087 // - if the class is a non-empty union, or for each non-empty anonymous 1088 // union member of a non-union class, exactly one non-static data member 1089 // shall be initialized; 1090 if (RD->isUnion()) { 1091 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 1092 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1093 return false; 1094 } 1095 } else if (!Constructor->isDependentContext() && 1096 !Constructor->isDelegatingConstructor()) { 1097 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1098 1099 // Skip detailed checking if we have enough initializers, and we would 1100 // allow at most one initializer per member. 1101 bool AnyAnonStructUnionMembers = false; 1102 unsigned Fields = 0; 1103 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1104 E = RD->field_end(); I != E; ++I, ++Fields) { 1105 if (I->isAnonymousStructOrUnion()) { 1106 AnyAnonStructUnionMembers = true; 1107 break; 1108 } 1109 } 1110 if (AnyAnonStructUnionMembers || 1111 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1112 // Check initialization of non-static data members. Base classes are 1113 // always initialized so do not need to be checked. Dependent bases 1114 // might not have initializers in the member initializer list. 1115 llvm::SmallSet<Decl*, 16> Inits; 1116 for (CXXConstructorDecl::init_const_iterator 1117 I = Constructor->init_begin(), E = Constructor->init_end(); 1118 I != E; ++I) { 1119 if (FieldDecl *FD = (*I)->getMember()) 1120 Inits.insert(FD); 1121 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 1122 Inits.insert(ID->chain_begin(), ID->chain_end()); 1123 } 1124 1125 bool Diagnosed = false; 1126 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1127 E = RD->field_end(); I != E; ++I) 1128 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 1129 if (Diagnosed) 1130 return false; 1131 } 1132 } 1133 } else { 1134 if (ReturnStmts.empty()) { 1135 // C++1y doesn't require constexpr functions to contain a 'return' 1136 // statement. We still do, unless the return type is void, because 1137 // otherwise if there's no return statement, the function cannot 1138 // be used in a core constant expression. 1139 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType(); 1140 Diag(Dcl->getLocation(), 1141 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1142 : diag::err_constexpr_body_no_return); 1143 return OK; 1144 } 1145 if (ReturnStmts.size() > 1) { 1146 Diag(ReturnStmts.back(), 1147 getLangOpts().CPlusPlus1y 1148 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1149 : diag::ext_constexpr_body_multiple_return); 1150 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1151 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1152 } 1153 } 1154 1155 // C++11 [dcl.constexpr]p5: 1156 // if no function argument values exist such that the function invocation 1157 // substitution would produce a constant expression, the program is 1158 // ill-formed; no diagnostic required. 1159 // C++11 [dcl.constexpr]p3: 1160 // - every constructor call and implicit conversion used in initializing the 1161 // return value shall be one of those allowed in a constant expression. 1162 // C++11 [dcl.constexpr]p4: 1163 // - every constructor involved in initializing non-static data members and 1164 // base class sub-objects shall be a constexpr constructor. 1165 SmallVector<PartialDiagnosticAt, 8> Diags; 1166 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1167 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1168 << isa<CXXConstructorDecl>(Dcl); 1169 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1170 Diag(Diags[I].first, Diags[I].second); 1171 // Don't return false here: we allow this for compatibility in 1172 // system headers. 1173 } 1174 1175 return true; 1176} 1177 1178/// isCurrentClassName - Determine whether the identifier II is the 1179/// name of the class type currently being defined. In the case of 1180/// nested classes, this will only return true if II is the name of 1181/// the innermost class. 1182bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1183 const CXXScopeSpec *SS) { 1184 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1185 1186 CXXRecordDecl *CurDecl; 1187 if (SS && SS->isSet() && !SS->isInvalid()) { 1188 DeclContext *DC = computeDeclContext(*SS, true); 1189 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1190 } else 1191 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1192 1193 if (CurDecl && CurDecl->getIdentifier()) 1194 return &II == CurDecl->getIdentifier(); 1195 else 1196 return false; 1197} 1198 1199/// \brief Determine whether the given class is a base class of the given 1200/// class, including looking at dependent bases. 1201static bool findCircularInheritance(const CXXRecordDecl *Class, 1202 const CXXRecordDecl *Current) { 1203 SmallVector<const CXXRecordDecl*, 8> Queue; 1204 1205 Class = Class->getCanonicalDecl(); 1206 while (true) { 1207 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(), 1208 E = Current->bases_end(); 1209 I != E; ++I) { 1210 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 1211 if (!Base) 1212 continue; 1213 1214 Base = Base->getDefinition(); 1215 if (!Base) 1216 continue; 1217 1218 if (Base->getCanonicalDecl() == Class) 1219 return true; 1220 1221 Queue.push_back(Base); 1222 } 1223 1224 if (Queue.empty()) 1225 return false; 1226 1227 Current = Queue.back(); 1228 Queue.pop_back(); 1229 } 1230 1231 return false; 1232} 1233 1234/// \brief Check the validity of a C++ base class specifier. 1235/// 1236/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1237/// and returns NULL otherwise. 1238CXXBaseSpecifier * 1239Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1240 SourceRange SpecifierRange, 1241 bool Virtual, AccessSpecifier Access, 1242 TypeSourceInfo *TInfo, 1243 SourceLocation EllipsisLoc) { 1244 QualType BaseType = TInfo->getType(); 1245 1246 // C++ [class.union]p1: 1247 // A union shall not have base classes. 1248 if (Class->isUnion()) { 1249 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1250 << SpecifierRange; 1251 return 0; 1252 } 1253 1254 if (EllipsisLoc.isValid() && 1255 !TInfo->getType()->containsUnexpandedParameterPack()) { 1256 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1257 << TInfo->getTypeLoc().getSourceRange(); 1258 EllipsisLoc = SourceLocation(); 1259 } 1260 1261 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1262 1263 if (BaseType->isDependentType()) { 1264 // Make sure that we don't have circular inheritance among our dependent 1265 // bases. For non-dependent bases, the check for completeness below handles 1266 // this. 1267 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1268 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1269 ((BaseDecl = BaseDecl->getDefinition()) && 1270 findCircularInheritance(Class, BaseDecl))) { 1271 Diag(BaseLoc, diag::err_circular_inheritance) 1272 << BaseType << Context.getTypeDeclType(Class); 1273 1274 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1275 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1276 << BaseType; 1277 1278 return 0; 1279 } 1280 } 1281 1282 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1283 Class->getTagKind() == TTK_Class, 1284 Access, TInfo, EllipsisLoc); 1285 } 1286 1287 // Base specifiers must be record types. 1288 if (!BaseType->isRecordType()) { 1289 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1290 return 0; 1291 } 1292 1293 // C++ [class.union]p1: 1294 // A union shall not be used as a base class. 1295 if (BaseType->isUnionType()) { 1296 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1297 return 0; 1298 } 1299 1300 // C++ [class.derived]p2: 1301 // The class-name in a base-specifier shall not be an incompletely 1302 // defined class. 1303 if (RequireCompleteType(BaseLoc, BaseType, 1304 diag::err_incomplete_base_class, SpecifierRange)) { 1305 Class->setInvalidDecl(); 1306 return 0; 1307 } 1308 1309 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1310 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1311 assert(BaseDecl && "Record type has no declaration"); 1312 BaseDecl = BaseDecl->getDefinition(); 1313 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1314 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1315 assert(CXXBaseDecl && "Base type is not a C++ type"); 1316 1317 // C++ [class]p3: 1318 // If a class is marked final and it appears as a base-type-specifier in 1319 // base-clause, the program is ill-formed. 1320 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 1321 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1322 << CXXBaseDecl->getDeclName(); 1323 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1324 << CXXBaseDecl->getDeclName(); 1325 return 0; 1326 } 1327 1328 if (BaseDecl->isInvalidDecl()) 1329 Class->setInvalidDecl(); 1330 1331 // Create the base specifier. 1332 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1333 Class->getTagKind() == TTK_Class, 1334 Access, TInfo, EllipsisLoc); 1335} 1336 1337/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1338/// one entry in the base class list of a class specifier, for 1339/// example: 1340/// class foo : public bar, virtual private baz { 1341/// 'public bar' and 'virtual private baz' are each base-specifiers. 1342BaseResult 1343Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1344 ParsedAttributes &Attributes, 1345 bool Virtual, AccessSpecifier Access, 1346 ParsedType basetype, SourceLocation BaseLoc, 1347 SourceLocation EllipsisLoc) { 1348 if (!classdecl) 1349 return true; 1350 1351 AdjustDeclIfTemplate(classdecl); 1352 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1353 if (!Class) 1354 return true; 1355 1356 // We do not support any C++11 attributes on base-specifiers yet. 1357 // Diagnose any attributes we see. 1358 if (!Attributes.empty()) { 1359 for (AttributeList *Attr = Attributes.getList(); Attr; 1360 Attr = Attr->getNext()) { 1361 if (Attr->isInvalid() || 1362 Attr->getKind() == AttributeList::IgnoredAttribute) 1363 continue; 1364 Diag(Attr->getLoc(), 1365 Attr->getKind() == AttributeList::UnknownAttribute 1366 ? diag::warn_unknown_attribute_ignored 1367 : diag::err_base_specifier_attribute) 1368 << Attr->getName(); 1369 } 1370 } 1371 1372 TypeSourceInfo *TInfo = 0; 1373 GetTypeFromParser(basetype, &TInfo); 1374 1375 if (EllipsisLoc.isInvalid() && 1376 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1377 UPPC_BaseType)) 1378 return true; 1379 1380 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1381 Virtual, Access, TInfo, 1382 EllipsisLoc)) 1383 return BaseSpec; 1384 else 1385 Class->setInvalidDecl(); 1386 1387 return true; 1388} 1389 1390/// \brief Performs the actual work of attaching the given base class 1391/// specifiers to a C++ class. 1392bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1393 unsigned NumBases) { 1394 if (NumBases == 0) 1395 return false; 1396 1397 // Used to keep track of which base types we have already seen, so 1398 // that we can properly diagnose redundant direct base types. Note 1399 // that the key is always the unqualified canonical type of the base 1400 // class. 1401 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1402 1403 // Copy non-redundant base specifiers into permanent storage. 1404 unsigned NumGoodBases = 0; 1405 bool Invalid = false; 1406 for (unsigned idx = 0; idx < NumBases; ++idx) { 1407 QualType NewBaseType 1408 = Context.getCanonicalType(Bases[idx]->getType()); 1409 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1410 1411 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1412 if (KnownBase) { 1413 // C++ [class.mi]p3: 1414 // A class shall not be specified as a direct base class of a 1415 // derived class more than once. 1416 Diag(Bases[idx]->getLocStart(), 1417 diag::err_duplicate_base_class) 1418 << KnownBase->getType() 1419 << Bases[idx]->getSourceRange(); 1420 1421 // Delete the duplicate base class specifier; we're going to 1422 // overwrite its pointer later. 1423 Context.Deallocate(Bases[idx]); 1424 1425 Invalid = true; 1426 } else { 1427 // Okay, add this new base class. 1428 KnownBase = Bases[idx]; 1429 Bases[NumGoodBases++] = Bases[idx]; 1430 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1431 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1432 if (Class->isInterface() && 1433 (!RD->isInterface() || 1434 KnownBase->getAccessSpecifier() != AS_public)) { 1435 // The Microsoft extension __interface does not permit bases that 1436 // are not themselves public interfaces. 1437 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1438 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1439 << RD->getSourceRange(); 1440 Invalid = true; 1441 } 1442 if (RD->hasAttr<WeakAttr>()) 1443 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1444 } 1445 } 1446 } 1447 1448 // Attach the remaining base class specifiers to the derived class. 1449 Class->setBases(Bases, NumGoodBases); 1450 1451 // Delete the remaining (good) base class specifiers, since their 1452 // data has been copied into the CXXRecordDecl. 1453 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1454 Context.Deallocate(Bases[idx]); 1455 1456 return Invalid; 1457} 1458 1459/// ActOnBaseSpecifiers - Attach the given base specifiers to the 1460/// class, after checking whether there are any duplicate base 1461/// classes. 1462void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1463 unsigned NumBases) { 1464 if (!ClassDecl || !Bases || !NumBases) 1465 return; 1466 1467 AdjustDeclIfTemplate(ClassDecl); 1468 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 1469 (CXXBaseSpecifier**)(Bases), NumBases); 1470} 1471 1472/// \brief Determine whether the type \p Derived is a C++ class that is 1473/// derived from the type \p Base. 1474bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1475 if (!getLangOpts().CPlusPlus) 1476 return false; 1477 1478 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1479 if (!DerivedRD) 1480 return false; 1481 1482 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1483 if (!BaseRD) 1484 return false; 1485 1486 // If either the base or the derived type is invalid, don't try to 1487 // check whether one is derived from the other. 1488 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1489 return false; 1490 1491 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1492 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1493} 1494 1495/// \brief Determine whether the type \p Derived is a C++ class that is 1496/// derived from the type \p Base. 1497bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1498 if (!getLangOpts().CPlusPlus) 1499 return false; 1500 1501 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1502 if (!DerivedRD) 1503 return false; 1504 1505 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1506 if (!BaseRD) 1507 return false; 1508 1509 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1510} 1511 1512void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1513 CXXCastPath &BasePathArray) { 1514 assert(BasePathArray.empty() && "Base path array must be empty!"); 1515 assert(Paths.isRecordingPaths() && "Must record paths!"); 1516 1517 const CXXBasePath &Path = Paths.front(); 1518 1519 // We first go backward and check if we have a virtual base. 1520 // FIXME: It would be better if CXXBasePath had the base specifier for 1521 // the nearest virtual base. 1522 unsigned Start = 0; 1523 for (unsigned I = Path.size(); I != 0; --I) { 1524 if (Path[I - 1].Base->isVirtual()) { 1525 Start = I - 1; 1526 break; 1527 } 1528 } 1529 1530 // Now add all bases. 1531 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1532 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1533} 1534 1535/// \brief Determine whether the given base path includes a virtual 1536/// base class. 1537bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1538 for (CXXCastPath::const_iterator B = BasePath.begin(), 1539 BEnd = BasePath.end(); 1540 B != BEnd; ++B) 1541 if ((*B)->isVirtual()) 1542 return true; 1543 1544 return false; 1545} 1546 1547/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1548/// conversion (where Derived and Base are class types) is 1549/// well-formed, meaning that the conversion is unambiguous (and 1550/// that all of the base classes are accessible). Returns true 1551/// and emits a diagnostic if the code is ill-formed, returns false 1552/// otherwise. Loc is the location where this routine should point to 1553/// if there is an error, and Range is the source range to highlight 1554/// if there is an error. 1555bool 1556Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1557 unsigned InaccessibleBaseID, 1558 unsigned AmbigiousBaseConvID, 1559 SourceLocation Loc, SourceRange Range, 1560 DeclarationName Name, 1561 CXXCastPath *BasePath) { 1562 // First, determine whether the path from Derived to Base is 1563 // ambiguous. This is slightly more expensive than checking whether 1564 // the Derived to Base conversion exists, because here we need to 1565 // explore multiple paths to determine if there is an ambiguity. 1566 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1567 /*DetectVirtual=*/false); 1568 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1569 assert(DerivationOkay && 1570 "Can only be used with a derived-to-base conversion"); 1571 (void)DerivationOkay; 1572 1573 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1574 if (InaccessibleBaseID) { 1575 // Check that the base class can be accessed. 1576 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1577 InaccessibleBaseID)) { 1578 case AR_inaccessible: 1579 return true; 1580 case AR_accessible: 1581 case AR_dependent: 1582 case AR_delayed: 1583 break; 1584 } 1585 } 1586 1587 // Build a base path if necessary. 1588 if (BasePath) 1589 BuildBasePathArray(Paths, *BasePath); 1590 return false; 1591 } 1592 1593 // We know that the derived-to-base conversion is ambiguous, and 1594 // we're going to produce a diagnostic. Perform the derived-to-base 1595 // search just one more time to compute all of the possible paths so 1596 // that we can print them out. This is more expensive than any of 1597 // the previous derived-to-base checks we've done, but at this point 1598 // performance isn't as much of an issue. 1599 Paths.clear(); 1600 Paths.setRecordingPaths(true); 1601 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1602 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1603 (void)StillOkay; 1604 1605 // Build up a textual representation of the ambiguous paths, e.g., 1606 // D -> B -> A, that will be used to illustrate the ambiguous 1607 // conversions in the diagnostic. We only print one of the paths 1608 // to each base class subobject. 1609 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1610 1611 Diag(Loc, AmbigiousBaseConvID) 1612 << Derived << Base << PathDisplayStr << Range << Name; 1613 return true; 1614} 1615 1616bool 1617Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1618 SourceLocation Loc, SourceRange Range, 1619 CXXCastPath *BasePath, 1620 bool IgnoreAccess) { 1621 return CheckDerivedToBaseConversion(Derived, Base, 1622 IgnoreAccess ? 0 1623 : diag::err_upcast_to_inaccessible_base, 1624 diag::err_ambiguous_derived_to_base_conv, 1625 Loc, Range, DeclarationName(), 1626 BasePath); 1627} 1628 1629 1630/// @brief Builds a string representing ambiguous paths from a 1631/// specific derived class to different subobjects of the same base 1632/// class. 1633/// 1634/// This function builds a string that can be used in error messages 1635/// to show the different paths that one can take through the 1636/// inheritance hierarchy to go from the derived class to different 1637/// subobjects of a base class. The result looks something like this: 1638/// @code 1639/// struct D -> struct B -> struct A 1640/// struct D -> struct C -> struct A 1641/// @endcode 1642std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1643 std::string PathDisplayStr; 1644 std::set<unsigned> DisplayedPaths; 1645 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1646 Path != Paths.end(); ++Path) { 1647 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1648 // We haven't displayed a path to this particular base 1649 // class subobject yet. 1650 PathDisplayStr += "\n "; 1651 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1652 for (CXXBasePath::const_iterator Element = Path->begin(); 1653 Element != Path->end(); ++Element) 1654 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1655 } 1656 } 1657 1658 return PathDisplayStr; 1659} 1660 1661//===----------------------------------------------------------------------===// 1662// C++ class member Handling 1663//===----------------------------------------------------------------------===// 1664 1665/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1666bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1667 SourceLocation ASLoc, 1668 SourceLocation ColonLoc, 1669 AttributeList *Attrs) { 1670 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1671 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1672 ASLoc, ColonLoc); 1673 CurContext->addHiddenDecl(ASDecl); 1674 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1675} 1676 1677/// CheckOverrideControl - Check C++11 override control semantics. 1678void Sema::CheckOverrideControl(Decl *D) { 1679 if (D->isInvalidDecl()) 1680 return; 1681 1682 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1683 1684 // Do we know which functions this declaration might be overriding? 1685 bool OverridesAreKnown = !MD || 1686 (!MD->getParent()->hasAnyDependentBases() && 1687 !MD->getType()->isDependentType()); 1688 1689 if (!MD || !MD->isVirtual()) { 1690 if (OverridesAreKnown) { 1691 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1692 Diag(OA->getLocation(), 1693 diag::override_keyword_only_allowed_on_virtual_member_functions) 1694 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1695 D->dropAttr<OverrideAttr>(); 1696 } 1697 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1698 Diag(FA->getLocation(), 1699 diag::override_keyword_only_allowed_on_virtual_member_functions) 1700 << "final" << FixItHint::CreateRemoval(FA->getLocation()); 1701 D->dropAttr<FinalAttr>(); 1702 } 1703 } 1704 return; 1705 } 1706 1707 if (!OverridesAreKnown) 1708 return; 1709 1710 // C++11 [class.virtual]p5: 1711 // If a virtual function is marked with the virt-specifier override and 1712 // does not override a member function of a base class, the program is 1713 // ill-formed. 1714 bool HasOverriddenMethods = 1715 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1716 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1717 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1718 << MD->getDeclName(); 1719} 1720 1721/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1722/// function overrides a virtual member function marked 'final', according to 1723/// C++11 [class.virtual]p4. 1724bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1725 const CXXMethodDecl *Old) { 1726 if (!Old->hasAttr<FinalAttr>()) 1727 return false; 1728 1729 Diag(New->getLocation(), diag::err_final_function_overridden) 1730 << New->getDeclName(); 1731 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1732 return true; 1733} 1734 1735static bool InitializationHasSideEffects(const FieldDecl &FD) { 1736 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1737 // FIXME: Destruction of ObjC lifetime types has side-effects. 1738 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1739 return !RD->isCompleteDefinition() || 1740 !RD->hasTrivialDefaultConstructor() || 1741 !RD->hasTrivialDestructor(); 1742 return false; 1743} 1744 1745static AttributeList *getMSPropertyAttr(AttributeList *list) { 1746 for (AttributeList* it = list; it != 0; it = it->getNext()) 1747 if (it->isDeclspecPropertyAttribute()) 1748 return it; 1749 return 0; 1750} 1751 1752/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1753/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1754/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1755/// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1756/// present (but parsing it has been deferred). 1757NamedDecl * 1758Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1759 MultiTemplateParamsArg TemplateParameterLists, 1760 Expr *BW, const VirtSpecifiers &VS, 1761 InClassInitStyle InitStyle) { 1762 const DeclSpec &DS = D.getDeclSpec(); 1763 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1764 DeclarationName Name = NameInfo.getName(); 1765 SourceLocation Loc = NameInfo.getLoc(); 1766 1767 // For anonymous bitfields, the location should point to the type. 1768 if (Loc.isInvalid()) 1769 Loc = D.getLocStart(); 1770 1771 Expr *BitWidth = static_cast<Expr*>(BW); 1772 1773 assert(isa<CXXRecordDecl>(CurContext)); 1774 assert(!DS.isFriendSpecified()); 1775 1776 bool isFunc = D.isDeclarationOfFunction(); 1777 1778 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1779 // The Microsoft extension __interface only permits public member functions 1780 // and prohibits constructors, destructors, operators, non-public member 1781 // functions, static methods and data members. 1782 unsigned InvalidDecl; 1783 bool ShowDeclName = true; 1784 if (!isFunc) 1785 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1786 else if (AS != AS_public) 1787 InvalidDecl = 2; 1788 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1789 InvalidDecl = 3; 1790 else switch (Name.getNameKind()) { 1791 case DeclarationName::CXXConstructorName: 1792 InvalidDecl = 4; 1793 ShowDeclName = false; 1794 break; 1795 1796 case DeclarationName::CXXDestructorName: 1797 InvalidDecl = 5; 1798 ShowDeclName = false; 1799 break; 1800 1801 case DeclarationName::CXXOperatorName: 1802 case DeclarationName::CXXConversionFunctionName: 1803 InvalidDecl = 6; 1804 break; 1805 1806 default: 1807 InvalidDecl = 0; 1808 break; 1809 } 1810 1811 if (InvalidDecl) { 1812 if (ShowDeclName) 1813 Diag(Loc, diag::err_invalid_member_in_interface) 1814 << (InvalidDecl-1) << Name; 1815 else 1816 Diag(Loc, diag::err_invalid_member_in_interface) 1817 << (InvalidDecl-1) << ""; 1818 return 0; 1819 } 1820 } 1821 1822 // C++ 9.2p6: A member shall not be declared to have automatic storage 1823 // duration (auto, register) or with the extern storage-class-specifier. 1824 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1825 // data members and cannot be applied to names declared const or static, 1826 // and cannot be applied to reference members. 1827 switch (DS.getStorageClassSpec()) { 1828 case DeclSpec::SCS_unspecified: 1829 case DeclSpec::SCS_typedef: 1830 case DeclSpec::SCS_static: 1831 break; 1832 case DeclSpec::SCS_mutable: 1833 if (isFunc) { 1834 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1835 1836 // FIXME: It would be nicer if the keyword was ignored only for this 1837 // declarator. Otherwise we could get follow-up errors. 1838 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1839 } 1840 break; 1841 default: 1842 Diag(DS.getStorageClassSpecLoc(), 1843 diag::err_storageclass_invalid_for_member); 1844 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1845 break; 1846 } 1847 1848 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1849 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1850 !isFunc); 1851 1852 if (DS.isConstexprSpecified() && isInstField) { 1853 SemaDiagnosticBuilder B = 1854 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 1855 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 1856 if (InitStyle == ICIS_NoInit) { 1857 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const"); 1858 D.getMutableDeclSpec().ClearConstexprSpec(); 1859 const char *PrevSpec; 1860 unsigned DiagID; 1861 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc, 1862 PrevSpec, DiagID, getLangOpts()); 1863 (void)Failed; 1864 assert(!Failed && "Making a constexpr member const shouldn't fail"); 1865 } else { 1866 B << 1; 1867 const char *PrevSpec; 1868 unsigned DiagID; 1869 if (D.getMutableDeclSpec().SetStorageClassSpec( 1870 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) { 1871 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 1872 "This is the only DeclSpec that should fail to be applied"); 1873 B << 1; 1874 } else { 1875 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 1876 isInstField = false; 1877 } 1878 } 1879 } 1880 1881 NamedDecl *Member; 1882 if (isInstField) { 1883 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1884 1885 // Data members must have identifiers for names. 1886 if (!Name.isIdentifier()) { 1887 Diag(Loc, diag::err_bad_variable_name) 1888 << Name; 1889 return 0; 1890 } 1891 1892 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1893 1894 // Member field could not be with "template" keyword. 1895 // So TemplateParameterLists should be empty in this case. 1896 if (TemplateParameterLists.size()) { 1897 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 1898 if (TemplateParams->size()) { 1899 // There is no such thing as a member field template. 1900 Diag(D.getIdentifierLoc(), diag::err_template_member) 1901 << II 1902 << SourceRange(TemplateParams->getTemplateLoc(), 1903 TemplateParams->getRAngleLoc()); 1904 } else { 1905 // There is an extraneous 'template<>' for this member. 1906 Diag(TemplateParams->getTemplateLoc(), 1907 diag::err_template_member_noparams) 1908 << II 1909 << SourceRange(TemplateParams->getTemplateLoc(), 1910 TemplateParams->getRAngleLoc()); 1911 } 1912 return 0; 1913 } 1914 1915 if (SS.isSet() && !SS.isInvalid()) { 1916 // The user provided a superfluous scope specifier inside a class 1917 // definition: 1918 // 1919 // class X { 1920 // int X::member; 1921 // }; 1922 if (DeclContext *DC = computeDeclContext(SS, false)) 1923 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 1924 else 1925 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1926 << Name << SS.getRange(); 1927 1928 SS.clear(); 1929 } 1930 1931 AttributeList *MSPropertyAttr = 1932 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 1933 if (MSPropertyAttr) { 1934 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 1935 BitWidth, InitStyle, AS, MSPropertyAttr); 1936 isInstField = false; 1937 } else { 1938 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 1939 BitWidth, InitStyle, AS); 1940 } 1941 assert(Member && "HandleField never returns null"); 1942 } else { 1943 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 1944 1945 Member = HandleDeclarator(S, D, TemplateParameterLists); 1946 if (!Member) { 1947 return 0; 1948 } 1949 1950 // Non-instance-fields can't have a bitfield. 1951 if (BitWidth) { 1952 if (Member->isInvalidDecl()) { 1953 // don't emit another diagnostic. 1954 } else if (isa<VarDecl>(Member)) { 1955 // C++ 9.6p3: A bit-field shall not be a static member. 1956 // "static member 'A' cannot be a bit-field" 1957 Diag(Loc, diag::err_static_not_bitfield) 1958 << Name << BitWidth->getSourceRange(); 1959 } else if (isa<TypedefDecl>(Member)) { 1960 // "typedef member 'x' cannot be a bit-field" 1961 Diag(Loc, diag::err_typedef_not_bitfield) 1962 << Name << BitWidth->getSourceRange(); 1963 } else { 1964 // A function typedef ("typedef int f(); f a;"). 1965 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1966 Diag(Loc, diag::err_not_integral_type_bitfield) 1967 << Name << cast<ValueDecl>(Member)->getType() 1968 << BitWidth->getSourceRange(); 1969 } 1970 1971 BitWidth = 0; 1972 Member->setInvalidDecl(); 1973 } 1974 1975 Member->setAccess(AS); 1976 1977 // If we have declared a member function template, set the access of the 1978 // templated declaration as well. 1979 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 1980 FunTmpl->getTemplatedDecl()->setAccess(AS); 1981 } 1982 1983 if (VS.isOverrideSpecified()) 1984 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 1985 if (VS.isFinalSpecified()) 1986 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 1987 1988 if (VS.getLastLocation().isValid()) { 1989 // Update the end location of a method that has a virt-specifiers. 1990 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 1991 MD->setRangeEnd(VS.getLastLocation()); 1992 } 1993 1994 CheckOverrideControl(Member); 1995 1996 assert((Name || isInstField) && "No identifier for non-field ?"); 1997 1998 if (isInstField) { 1999 FieldDecl *FD = cast<FieldDecl>(Member); 2000 FieldCollector->Add(FD); 2001 2002 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 2003 FD->getLocation()) 2004 != DiagnosticsEngine::Ignored) { 2005 // Remember all explicit private FieldDecls that have a name, no side 2006 // effects and are not part of a dependent type declaration. 2007 if (!FD->isImplicit() && FD->getDeclName() && 2008 FD->getAccess() == AS_private && 2009 !FD->hasAttr<UnusedAttr>() && 2010 !FD->getParent()->isDependentContext() && 2011 !InitializationHasSideEffects(*FD)) 2012 UnusedPrivateFields.insert(FD); 2013 } 2014 } 2015 2016 return Member; 2017} 2018 2019namespace { 2020 class UninitializedFieldVisitor 2021 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2022 Sema &S; 2023 ValueDecl *VD; 2024 public: 2025 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2026 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context), 2027 S(S) { 2028 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD)) 2029 this->VD = IFD->getAnonField(); 2030 else 2031 this->VD = VD; 2032 } 2033 2034 void HandleExpr(Expr *E) { 2035 if (!E) return; 2036 2037 // Expressions like x(x) sometimes lack the surrounding expressions 2038 // but need to be checked anyways. 2039 HandleValue(E); 2040 Visit(E); 2041 } 2042 2043 void HandleValue(Expr *E) { 2044 E = E->IgnoreParens(); 2045 2046 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2047 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2048 return; 2049 2050 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2051 // or union. 2052 MemberExpr *FieldME = ME; 2053 2054 Expr *Base = E; 2055 while (isa<MemberExpr>(Base)) { 2056 ME = cast<MemberExpr>(Base); 2057 2058 if (isa<VarDecl>(ME->getMemberDecl())) 2059 return; 2060 2061 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2062 if (!FD->isAnonymousStructOrUnion()) 2063 FieldME = ME; 2064 2065 Base = ME->getBase(); 2066 } 2067 2068 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) { 2069 unsigned diag = VD->getType()->isReferenceType() 2070 ? diag::warn_reference_field_is_uninit 2071 : diag::warn_field_is_uninit; 2072 S.Diag(FieldME->getExprLoc(), diag) << VD; 2073 } 2074 return; 2075 } 2076 2077 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2078 HandleValue(CO->getTrueExpr()); 2079 HandleValue(CO->getFalseExpr()); 2080 return; 2081 } 2082 2083 if (BinaryConditionalOperator *BCO = 2084 dyn_cast<BinaryConditionalOperator>(E)) { 2085 HandleValue(BCO->getCommon()); 2086 HandleValue(BCO->getFalseExpr()); 2087 return; 2088 } 2089 2090 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2091 switch (BO->getOpcode()) { 2092 default: 2093 return; 2094 case(BO_PtrMemD): 2095 case(BO_PtrMemI): 2096 HandleValue(BO->getLHS()); 2097 return; 2098 case(BO_Comma): 2099 HandleValue(BO->getRHS()); 2100 return; 2101 } 2102 } 2103 } 2104 2105 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2106 if (E->getCastKind() == CK_LValueToRValue) 2107 HandleValue(E->getSubExpr()); 2108 2109 Inherited::VisitImplicitCastExpr(E); 2110 } 2111 2112 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2113 Expr *Callee = E->getCallee(); 2114 if (isa<MemberExpr>(Callee)) 2115 HandleValue(Callee); 2116 2117 Inherited::VisitCXXMemberCallExpr(E); 2118 } 2119 }; 2120 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E, 2121 ValueDecl *VD) { 2122 UninitializedFieldVisitor(S, VD).HandleExpr(E); 2123 } 2124} // namespace 2125 2126/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 2127/// in-class initializer for a non-static C++ class member, and after 2128/// instantiating an in-class initializer in a class template. Such actions 2129/// are deferred until the class is complete. 2130void 2131Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc, 2132 Expr *InitExpr) { 2133 FieldDecl *FD = cast<FieldDecl>(D); 2134 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2135 "must set init style when field is created"); 2136 2137 if (!InitExpr) { 2138 FD->setInvalidDecl(); 2139 FD->removeInClassInitializer(); 2140 return; 2141 } 2142 2143 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2144 FD->setInvalidDecl(); 2145 FD->removeInClassInitializer(); 2146 return; 2147 } 2148 2149 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc) 2150 != DiagnosticsEngine::Ignored) { 2151 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD); 2152 } 2153 2154 ExprResult Init = InitExpr; 2155 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2156 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) { 2157 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list) 2158 << /*at end of ctor*/1 << InitExpr->getSourceRange(); 2159 } 2160 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2161 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2162 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2163 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2164 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2165 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2166 if (Init.isInvalid()) { 2167 FD->setInvalidDecl(); 2168 return; 2169 } 2170 } 2171 2172 // C++11 [class.base.init]p7: 2173 // The initialization of each base and member constitutes a 2174 // full-expression. 2175 Init = ActOnFinishFullExpr(Init.take(), InitLoc); 2176 if (Init.isInvalid()) { 2177 FD->setInvalidDecl(); 2178 return; 2179 } 2180 2181 InitExpr = Init.release(); 2182 2183 FD->setInClassInitializer(InitExpr); 2184} 2185 2186/// \brief Find the direct and/or virtual base specifiers that 2187/// correspond to the given base type, for use in base initialization 2188/// within a constructor. 2189static bool FindBaseInitializer(Sema &SemaRef, 2190 CXXRecordDecl *ClassDecl, 2191 QualType BaseType, 2192 const CXXBaseSpecifier *&DirectBaseSpec, 2193 const CXXBaseSpecifier *&VirtualBaseSpec) { 2194 // First, check for a direct base class. 2195 DirectBaseSpec = 0; 2196 for (CXXRecordDecl::base_class_const_iterator Base 2197 = ClassDecl->bases_begin(); 2198 Base != ClassDecl->bases_end(); ++Base) { 2199 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 2200 // We found a direct base of this type. That's what we're 2201 // initializing. 2202 DirectBaseSpec = &*Base; 2203 break; 2204 } 2205 } 2206 2207 // Check for a virtual base class. 2208 // FIXME: We might be able to short-circuit this if we know in advance that 2209 // there are no virtual bases. 2210 VirtualBaseSpec = 0; 2211 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2212 // We haven't found a base yet; search the class hierarchy for a 2213 // virtual base class. 2214 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2215 /*DetectVirtual=*/false); 2216 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2217 BaseType, Paths)) { 2218 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2219 Path != Paths.end(); ++Path) { 2220 if (Path->back().Base->isVirtual()) { 2221 VirtualBaseSpec = Path->back().Base; 2222 break; 2223 } 2224 } 2225 } 2226 } 2227 2228 return DirectBaseSpec || VirtualBaseSpec; 2229} 2230 2231/// \brief Handle a C++ member initializer using braced-init-list syntax. 2232MemInitResult 2233Sema::ActOnMemInitializer(Decl *ConstructorD, 2234 Scope *S, 2235 CXXScopeSpec &SS, 2236 IdentifierInfo *MemberOrBase, 2237 ParsedType TemplateTypeTy, 2238 const DeclSpec &DS, 2239 SourceLocation IdLoc, 2240 Expr *InitList, 2241 SourceLocation EllipsisLoc) { 2242 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2243 DS, IdLoc, InitList, 2244 EllipsisLoc); 2245} 2246 2247/// \brief Handle a C++ member initializer using parentheses syntax. 2248MemInitResult 2249Sema::ActOnMemInitializer(Decl *ConstructorD, 2250 Scope *S, 2251 CXXScopeSpec &SS, 2252 IdentifierInfo *MemberOrBase, 2253 ParsedType TemplateTypeTy, 2254 const DeclSpec &DS, 2255 SourceLocation IdLoc, 2256 SourceLocation LParenLoc, 2257 ArrayRef<Expr *> Args, 2258 SourceLocation RParenLoc, 2259 SourceLocation EllipsisLoc) { 2260 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2261 Args, RParenLoc); 2262 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2263 DS, IdLoc, List, EllipsisLoc); 2264} 2265 2266namespace { 2267 2268// Callback to only accept typo corrections that can be a valid C++ member 2269// intializer: either a non-static field member or a base class. 2270class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2271 public: 2272 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2273 : ClassDecl(ClassDecl) {} 2274 2275 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 2276 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2277 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2278 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2279 else 2280 return isa<TypeDecl>(ND); 2281 } 2282 return false; 2283 } 2284 2285 private: 2286 CXXRecordDecl *ClassDecl; 2287}; 2288 2289} 2290 2291/// \brief Handle a C++ member initializer. 2292MemInitResult 2293Sema::BuildMemInitializer(Decl *ConstructorD, 2294 Scope *S, 2295 CXXScopeSpec &SS, 2296 IdentifierInfo *MemberOrBase, 2297 ParsedType TemplateTypeTy, 2298 const DeclSpec &DS, 2299 SourceLocation IdLoc, 2300 Expr *Init, 2301 SourceLocation EllipsisLoc) { 2302 if (!ConstructorD) 2303 return true; 2304 2305 AdjustDeclIfTemplate(ConstructorD); 2306 2307 CXXConstructorDecl *Constructor 2308 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2309 if (!Constructor) { 2310 // The user wrote a constructor initializer on a function that is 2311 // not a C++ constructor. Ignore the error for now, because we may 2312 // have more member initializers coming; we'll diagnose it just 2313 // once in ActOnMemInitializers. 2314 return true; 2315 } 2316 2317 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2318 2319 // C++ [class.base.init]p2: 2320 // Names in a mem-initializer-id are looked up in the scope of the 2321 // constructor's class and, if not found in that scope, are looked 2322 // up in the scope containing the constructor's definition. 2323 // [Note: if the constructor's class contains a member with the 2324 // same name as a direct or virtual base class of the class, a 2325 // mem-initializer-id naming the member or base class and composed 2326 // of a single identifier refers to the class member. A 2327 // mem-initializer-id for the hidden base class may be specified 2328 // using a qualified name. ] 2329 if (!SS.getScopeRep() && !TemplateTypeTy) { 2330 // Look for a member, first. 2331 DeclContext::lookup_result Result 2332 = ClassDecl->lookup(MemberOrBase); 2333 if (!Result.empty()) { 2334 ValueDecl *Member; 2335 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2336 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2337 if (EllipsisLoc.isValid()) 2338 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2339 << MemberOrBase 2340 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2341 2342 return BuildMemberInitializer(Member, Init, IdLoc); 2343 } 2344 } 2345 } 2346 // It didn't name a member, so see if it names a class. 2347 QualType BaseType; 2348 TypeSourceInfo *TInfo = 0; 2349 2350 if (TemplateTypeTy) { 2351 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2352 } else if (DS.getTypeSpecType() == TST_decltype) { 2353 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2354 } else { 2355 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2356 LookupParsedName(R, S, &SS); 2357 2358 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2359 if (!TyD) { 2360 if (R.isAmbiguous()) return true; 2361 2362 // We don't want access-control diagnostics here. 2363 R.suppressDiagnostics(); 2364 2365 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2366 bool NotUnknownSpecialization = false; 2367 DeclContext *DC = computeDeclContext(SS, false); 2368 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2369 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2370 2371 if (!NotUnknownSpecialization) { 2372 // When the scope specifier can refer to a member of an unknown 2373 // specialization, we take it as a type name. 2374 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2375 SS.getWithLocInContext(Context), 2376 *MemberOrBase, IdLoc); 2377 if (BaseType.isNull()) 2378 return true; 2379 2380 R.clear(); 2381 R.setLookupName(MemberOrBase); 2382 } 2383 } 2384 2385 // If no results were found, try to correct typos. 2386 TypoCorrection Corr; 2387 MemInitializerValidatorCCC Validator(ClassDecl); 2388 if (R.empty() && BaseType.isNull() && 2389 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2390 Validator, ClassDecl))) { 2391 std::string CorrectedStr(Corr.getAsString(getLangOpts())); 2392 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts())); 2393 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2394 // We have found a non-static data member with a similar 2395 // name to what was typed; complain and initialize that 2396 // member. 2397 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2398 << MemberOrBase << true << CorrectedQuotedStr 2399 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2400 Diag(Member->getLocation(), diag::note_previous_decl) 2401 << CorrectedQuotedStr; 2402 2403 return BuildMemberInitializer(Member, Init, IdLoc); 2404 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2405 const CXXBaseSpecifier *DirectBaseSpec; 2406 const CXXBaseSpecifier *VirtualBaseSpec; 2407 if (FindBaseInitializer(*this, ClassDecl, 2408 Context.getTypeDeclType(Type), 2409 DirectBaseSpec, VirtualBaseSpec)) { 2410 // We have found a direct or virtual base class with a 2411 // similar name to what was typed; complain and initialize 2412 // that base class. 2413 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 2414 << MemberOrBase << false << CorrectedQuotedStr 2415 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 2416 2417 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 2418 : VirtualBaseSpec; 2419 Diag(BaseSpec->getLocStart(), 2420 diag::note_base_class_specified_here) 2421 << BaseSpec->getType() 2422 << BaseSpec->getSourceRange(); 2423 2424 TyD = Type; 2425 } 2426 } 2427 } 2428 2429 if (!TyD && BaseType.isNull()) { 2430 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2431 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2432 return true; 2433 } 2434 } 2435 2436 if (BaseType.isNull()) { 2437 BaseType = Context.getTypeDeclType(TyD); 2438 if (SS.isSet()) { 2439 NestedNameSpecifier *Qualifier = 2440 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2441 2442 // FIXME: preserve source range information 2443 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 2444 } 2445 } 2446 } 2447 2448 if (!TInfo) 2449 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2450 2451 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2452} 2453 2454/// Checks a member initializer expression for cases where reference (or 2455/// pointer) members are bound to by-value parameters (or their addresses). 2456static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2457 Expr *Init, 2458 SourceLocation IdLoc) { 2459 QualType MemberTy = Member->getType(); 2460 2461 // We only handle pointers and references currently. 2462 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2463 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2464 return; 2465 2466 const bool IsPointer = MemberTy->isPointerType(); 2467 if (IsPointer) { 2468 if (const UnaryOperator *Op 2469 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2470 // The only case we're worried about with pointers requires taking the 2471 // address. 2472 if (Op->getOpcode() != UO_AddrOf) 2473 return; 2474 2475 Init = Op->getSubExpr(); 2476 } else { 2477 // We only handle address-of expression initializers for pointers. 2478 return; 2479 } 2480 } 2481 2482 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2483 // We only warn when referring to a non-reference parameter declaration. 2484 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2485 if (!Parameter || Parameter->getType()->isReferenceType()) 2486 return; 2487 2488 S.Diag(Init->getExprLoc(), 2489 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2490 : diag::warn_bind_ref_member_to_parameter) 2491 << Member << Parameter << Init->getSourceRange(); 2492 } else { 2493 // Other initializers are fine. 2494 return; 2495 } 2496 2497 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2498 << (unsigned)IsPointer; 2499} 2500 2501MemInitResult 2502Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2503 SourceLocation IdLoc) { 2504 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2505 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2506 assert((DirectMember || IndirectMember) && 2507 "Member must be a FieldDecl or IndirectFieldDecl"); 2508 2509 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2510 return true; 2511 2512 if (Member->isInvalidDecl()) 2513 return true; 2514 2515 // Diagnose value-uses of fields to initialize themselves, e.g. 2516 // foo(foo) 2517 // where foo is not also a parameter to the constructor. 2518 // TODO: implement -Wuninitialized and fold this into that framework. 2519 MultiExprArg Args; 2520 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2521 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2522 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2523 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2524 } else { 2525 // Template instantiation doesn't reconstruct ParenListExprs for us. 2526 Args = Init; 2527 } 2528 2529 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc) 2530 != DiagnosticsEngine::Ignored) 2531 for (unsigned i = 0, e = Args.size(); i != e; ++i) 2532 // FIXME: Warn about the case when other fields are used before being 2533 // initialized. For example, let this field be the i'th field. When 2534 // initializing the i'th field, throw a warning if any of the >= i'th 2535 // fields are used, as they are not yet initialized. 2536 // Right now we are only handling the case where the i'th field uses 2537 // itself in its initializer. 2538 // Also need to take into account that some fields may be initialized by 2539 // in-class initializers, see C++11 [class.base.init]p9. 2540 CheckInitExprContainsUninitializedFields(*this, Args[i], Member); 2541 2542 SourceRange InitRange = Init->getSourceRange(); 2543 2544 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2545 // Can't check initialization for a member of dependent type or when 2546 // any of the arguments are type-dependent expressions. 2547 DiscardCleanupsInEvaluationContext(); 2548 } else { 2549 bool InitList = false; 2550 if (isa<InitListExpr>(Init)) { 2551 InitList = true; 2552 Args = Init; 2553 2554 if (isStdInitializerList(Member->getType(), 0)) { 2555 Diag(IdLoc, diag::warn_dangling_std_initializer_list) 2556 << /*at end of ctor*/1 << InitRange; 2557 } 2558 } 2559 2560 // Initialize the member. 2561 InitializedEntity MemberEntity = 2562 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2563 : InitializedEntity::InitializeMember(IndirectMember, 0); 2564 InitializationKind Kind = 2565 InitList ? InitializationKind::CreateDirectList(IdLoc) 2566 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2567 InitRange.getEnd()); 2568 2569 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 2570 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0); 2571 if (MemberInit.isInvalid()) 2572 return true; 2573 2574 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 2575 2576 // C++11 [class.base.init]p7: 2577 // The initialization of each base and member constitutes a 2578 // full-expression. 2579 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2580 if (MemberInit.isInvalid()) 2581 return true; 2582 2583 Init = MemberInit.get(); 2584 } 2585 2586 if (DirectMember) { 2587 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2588 InitRange.getBegin(), Init, 2589 InitRange.getEnd()); 2590 } else { 2591 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2592 InitRange.getBegin(), Init, 2593 InitRange.getEnd()); 2594 } 2595} 2596 2597MemInitResult 2598Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2599 CXXRecordDecl *ClassDecl) { 2600 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2601 if (!LangOpts.CPlusPlus11) 2602 return Diag(NameLoc, diag::err_delegating_ctor) 2603 << TInfo->getTypeLoc().getLocalSourceRange(); 2604 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2605 2606 bool InitList = true; 2607 MultiExprArg Args = Init; 2608 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2609 InitList = false; 2610 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2611 } 2612 2613 SourceRange InitRange = Init->getSourceRange(); 2614 // Initialize the object. 2615 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2616 QualType(ClassDecl->getTypeForDecl(), 0)); 2617 InitializationKind Kind = 2618 InitList ? InitializationKind::CreateDirectList(NameLoc) 2619 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2620 InitRange.getEnd()); 2621 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 2622 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2623 Args, 0); 2624 if (DelegationInit.isInvalid()) 2625 return true; 2626 2627 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2628 "Delegating constructor with no target?"); 2629 2630 // C++11 [class.base.init]p7: 2631 // The initialization of each base and member constitutes a 2632 // full-expression. 2633 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2634 InitRange.getBegin()); 2635 if (DelegationInit.isInvalid()) 2636 return true; 2637 2638 // If we are in a dependent context, template instantiation will 2639 // perform this type-checking again. Just save the arguments that we 2640 // received in a ParenListExpr. 2641 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2642 // of the information that we have about the base 2643 // initializer. However, deconstructing the ASTs is a dicey process, 2644 // and this approach is far more likely to get the corner cases right. 2645 if (CurContext->isDependentContext()) 2646 DelegationInit = Owned(Init); 2647 2648 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2649 DelegationInit.takeAs<Expr>(), 2650 InitRange.getEnd()); 2651} 2652 2653MemInitResult 2654Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2655 Expr *Init, CXXRecordDecl *ClassDecl, 2656 SourceLocation EllipsisLoc) { 2657 SourceLocation BaseLoc 2658 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2659 2660 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2661 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2662 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2663 2664 // C++ [class.base.init]p2: 2665 // [...] Unless the mem-initializer-id names a nonstatic data 2666 // member of the constructor's class or a direct or virtual base 2667 // of that class, the mem-initializer is ill-formed. A 2668 // mem-initializer-list can initialize a base class using any 2669 // name that denotes that base class type. 2670 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2671 2672 SourceRange InitRange = Init->getSourceRange(); 2673 if (EllipsisLoc.isValid()) { 2674 // This is a pack expansion. 2675 if (!BaseType->containsUnexpandedParameterPack()) { 2676 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2677 << SourceRange(BaseLoc, InitRange.getEnd()); 2678 2679 EllipsisLoc = SourceLocation(); 2680 } 2681 } else { 2682 // Check for any unexpanded parameter packs. 2683 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2684 return true; 2685 2686 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2687 return true; 2688 } 2689 2690 // Check for direct and virtual base classes. 2691 const CXXBaseSpecifier *DirectBaseSpec = 0; 2692 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2693 if (!Dependent) { 2694 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2695 BaseType)) 2696 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2697 2698 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2699 VirtualBaseSpec); 2700 2701 // C++ [base.class.init]p2: 2702 // Unless the mem-initializer-id names a nonstatic data member of the 2703 // constructor's class or a direct or virtual base of that class, the 2704 // mem-initializer is ill-formed. 2705 if (!DirectBaseSpec && !VirtualBaseSpec) { 2706 // If the class has any dependent bases, then it's possible that 2707 // one of those types will resolve to the same type as 2708 // BaseType. Therefore, just treat this as a dependent base 2709 // class initialization. FIXME: Should we try to check the 2710 // initialization anyway? It seems odd. 2711 if (ClassDecl->hasAnyDependentBases()) 2712 Dependent = true; 2713 else 2714 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2715 << BaseType << Context.getTypeDeclType(ClassDecl) 2716 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2717 } 2718 } 2719 2720 if (Dependent) { 2721 DiscardCleanupsInEvaluationContext(); 2722 2723 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2724 /*IsVirtual=*/false, 2725 InitRange.getBegin(), Init, 2726 InitRange.getEnd(), EllipsisLoc); 2727 } 2728 2729 // C++ [base.class.init]p2: 2730 // If a mem-initializer-id is ambiguous because it designates both 2731 // a direct non-virtual base class and an inherited virtual base 2732 // class, the mem-initializer is ill-formed. 2733 if (DirectBaseSpec && VirtualBaseSpec) 2734 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2735 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2736 2737 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 2738 if (!BaseSpec) 2739 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 2740 2741 // Initialize the base. 2742 bool InitList = true; 2743 MultiExprArg Args = Init; 2744 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2745 InitList = false; 2746 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2747 } 2748 2749 InitializedEntity BaseEntity = 2750 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2751 InitializationKind Kind = 2752 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2753 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2754 InitRange.getEnd()); 2755 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 2756 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0); 2757 if (BaseInit.isInvalid()) 2758 return true; 2759 2760 // C++11 [class.base.init]p7: 2761 // The initialization of each base and member constitutes a 2762 // full-expression. 2763 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 2764 if (BaseInit.isInvalid()) 2765 return true; 2766 2767 // If we are in a dependent context, template instantiation will 2768 // perform this type-checking again. Just save the arguments that we 2769 // received in a ParenListExpr. 2770 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2771 // of the information that we have about the base 2772 // initializer. However, deconstructing the ASTs is a dicey process, 2773 // and this approach is far more likely to get the corner cases right. 2774 if (CurContext->isDependentContext()) 2775 BaseInit = Owned(Init); 2776 2777 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2778 BaseSpec->isVirtual(), 2779 InitRange.getBegin(), 2780 BaseInit.takeAs<Expr>(), 2781 InitRange.getEnd(), EllipsisLoc); 2782} 2783 2784// Create a static_cast\<T&&>(expr). 2785static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 2786 if (T.isNull()) T = E->getType(); 2787 QualType TargetType = SemaRef.BuildReferenceType( 2788 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 2789 SourceLocation ExprLoc = E->getLocStart(); 2790 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2791 TargetType, ExprLoc); 2792 2793 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2794 SourceRange(ExprLoc, ExprLoc), 2795 E->getSourceRange()).take(); 2796} 2797 2798/// ImplicitInitializerKind - How an implicit base or member initializer should 2799/// initialize its base or member. 2800enum ImplicitInitializerKind { 2801 IIK_Default, 2802 IIK_Copy, 2803 IIK_Move, 2804 IIK_Inherit 2805}; 2806 2807static bool 2808BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2809 ImplicitInitializerKind ImplicitInitKind, 2810 CXXBaseSpecifier *BaseSpec, 2811 bool IsInheritedVirtualBase, 2812 CXXCtorInitializer *&CXXBaseInit) { 2813 InitializedEntity InitEntity 2814 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2815 IsInheritedVirtualBase); 2816 2817 ExprResult BaseInit; 2818 2819 switch (ImplicitInitKind) { 2820 case IIK_Inherit: { 2821 const CXXRecordDecl *Inherited = 2822 Constructor->getInheritedConstructor()->getParent(); 2823 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 2824 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 2825 // C++11 [class.inhctor]p8: 2826 // Each expression in the expression-list is of the form 2827 // static_cast<T&&>(p), where p is the name of the corresponding 2828 // constructor parameter and T is the declared type of p. 2829 SmallVector<Expr*, 16> Args; 2830 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 2831 ParmVarDecl *PD = Constructor->getParamDecl(I); 2832 ExprResult ArgExpr = 2833 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 2834 VK_LValue, SourceLocation()); 2835 if (ArgExpr.isInvalid()) 2836 return true; 2837 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType())); 2838 } 2839 2840 InitializationKind InitKind = InitializationKind::CreateDirect( 2841 Constructor->getLocation(), SourceLocation(), SourceLocation()); 2842 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 2843 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 2844 break; 2845 } 2846 } 2847 // Fall through. 2848 case IIK_Default: { 2849 InitializationKind InitKind 2850 = InitializationKind::CreateDefault(Constructor->getLocation()); 2851 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 2852 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 2853 break; 2854 } 2855 2856 case IIK_Move: 2857 case IIK_Copy: { 2858 bool Moving = ImplicitInitKind == IIK_Move; 2859 ParmVarDecl *Param = Constructor->getParamDecl(0); 2860 QualType ParamType = Param->getType().getNonReferenceType(); 2861 2862 Expr *CopyCtorArg = 2863 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2864 SourceLocation(), Param, false, 2865 Constructor->getLocation(), ParamType, 2866 VK_LValue, 0); 2867 2868 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2869 2870 // Cast to the base class to avoid ambiguities. 2871 QualType ArgTy = 2872 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 2873 ParamType.getQualifiers()); 2874 2875 if (Moving) { 2876 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 2877 } 2878 2879 CXXCastPath BasePath; 2880 BasePath.push_back(BaseSpec); 2881 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 2882 CK_UncheckedDerivedToBase, 2883 Moving ? VK_XValue : VK_LValue, 2884 &BasePath).take(); 2885 2886 InitializationKind InitKind 2887 = InitializationKind::CreateDirect(Constructor->getLocation(), 2888 SourceLocation(), SourceLocation()); 2889 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 2890 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 2891 break; 2892 } 2893 } 2894 2895 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 2896 if (BaseInit.isInvalid()) 2897 return true; 2898 2899 CXXBaseInit = 2900 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2901 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 2902 SourceLocation()), 2903 BaseSpec->isVirtual(), 2904 SourceLocation(), 2905 BaseInit.takeAs<Expr>(), 2906 SourceLocation(), 2907 SourceLocation()); 2908 2909 return false; 2910} 2911 2912static bool RefersToRValueRef(Expr *MemRef) { 2913 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 2914 return Referenced->getType()->isRValueReferenceType(); 2915} 2916 2917static bool 2918BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2919 ImplicitInitializerKind ImplicitInitKind, 2920 FieldDecl *Field, IndirectFieldDecl *Indirect, 2921 CXXCtorInitializer *&CXXMemberInit) { 2922 if (Field->isInvalidDecl()) 2923 return true; 2924 2925 SourceLocation Loc = Constructor->getLocation(); 2926 2927 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 2928 bool Moving = ImplicitInitKind == IIK_Move; 2929 ParmVarDecl *Param = Constructor->getParamDecl(0); 2930 QualType ParamType = Param->getType().getNonReferenceType(); 2931 2932 // Suppress copying zero-width bitfields. 2933 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 2934 return false; 2935 2936 Expr *MemberExprBase = 2937 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2938 SourceLocation(), Param, false, 2939 Loc, ParamType, VK_LValue, 0); 2940 2941 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 2942 2943 if (Moving) { 2944 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 2945 } 2946 2947 // Build a reference to this field within the parameter. 2948 CXXScopeSpec SS; 2949 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 2950 Sema::LookupMemberName); 2951 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 2952 : cast<ValueDecl>(Field), AS_public); 2953 MemberLookup.resolveKind(); 2954 ExprResult CtorArg 2955 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 2956 ParamType, Loc, 2957 /*IsArrow=*/false, 2958 SS, 2959 /*TemplateKWLoc=*/SourceLocation(), 2960 /*FirstQualifierInScope=*/0, 2961 MemberLookup, 2962 /*TemplateArgs=*/0); 2963 if (CtorArg.isInvalid()) 2964 return true; 2965 2966 // C++11 [class.copy]p15: 2967 // - if a member m has rvalue reference type T&&, it is direct-initialized 2968 // with static_cast<T&&>(x.m); 2969 if (RefersToRValueRef(CtorArg.get())) { 2970 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2971 } 2972 2973 // When the field we are copying is an array, create index variables for 2974 // each dimension of the array. We use these index variables to subscript 2975 // the source array, and other clients (e.g., CodeGen) will perform the 2976 // necessary iteration with these index variables. 2977 SmallVector<VarDecl *, 4> IndexVariables; 2978 QualType BaseType = Field->getType(); 2979 QualType SizeType = SemaRef.Context.getSizeType(); 2980 bool InitializingArray = false; 2981 while (const ConstantArrayType *Array 2982 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 2983 InitializingArray = true; 2984 // Create the iteration variable for this array index. 2985 IdentifierInfo *IterationVarName = 0; 2986 { 2987 SmallString<8> Str; 2988 llvm::raw_svector_ostream OS(Str); 2989 OS << "__i" << IndexVariables.size(); 2990 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 2991 } 2992 VarDecl *IterationVar 2993 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 2994 IterationVarName, SizeType, 2995 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 2996 SC_None); 2997 IndexVariables.push_back(IterationVar); 2998 2999 // Create a reference to the iteration variable. 3000 ExprResult IterationVarRef 3001 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3002 assert(!IterationVarRef.isInvalid() && 3003 "Reference to invented variable cannot fail!"); 3004 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 3005 assert(!IterationVarRef.isInvalid() && 3006 "Conversion of invented variable cannot fail!"); 3007 3008 // Subscript the array with this iteration variable. 3009 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 3010 IterationVarRef.take(), 3011 Loc); 3012 if (CtorArg.isInvalid()) 3013 return true; 3014 3015 BaseType = Array->getElementType(); 3016 } 3017 3018 // The array subscript expression is an lvalue, which is wrong for moving. 3019 if (Moving && InitializingArray) 3020 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3021 3022 // Construct the entity that we will be initializing. For an array, this 3023 // will be first element in the array, which may require several levels 3024 // of array-subscript entities. 3025 SmallVector<InitializedEntity, 4> Entities; 3026 Entities.reserve(1 + IndexVariables.size()); 3027 if (Indirect) 3028 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3029 else 3030 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3031 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3032 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3033 0, 3034 Entities.back())); 3035 3036 // Direct-initialize to use the copy constructor. 3037 InitializationKind InitKind = 3038 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3039 3040 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 3041 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3042 3043 ExprResult MemberInit 3044 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3045 MultiExprArg(&CtorArgE, 1)); 3046 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3047 if (MemberInit.isInvalid()) 3048 return true; 3049 3050 if (Indirect) { 3051 assert(IndexVariables.size() == 0 && 3052 "Indirect field improperly initialized"); 3053 CXXMemberInit 3054 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3055 Loc, Loc, 3056 MemberInit.takeAs<Expr>(), 3057 Loc); 3058 } else 3059 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3060 Loc, MemberInit.takeAs<Expr>(), 3061 Loc, 3062 IndexVariables.data(), 3063 IndexVariables.size()); 3064 return false; 3065 } 3066 3067 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3068 "Unhandled implicit init kind!"); 3069 3070 QualType FieldBaseElementType = 3071 SemaRef.Context.getBaseElementType(Field->getType()); 3072 3073 if (FieldBaseElementType->isRecordType()) { 3074 InitializedEntity InitEntity 3075 = Indirect? InitializedEntity::InitializeMember(Indirect) 3076 : InitializedEntity::InitializeMember(Field); 3077 InitializationKind InitKind = 3078 InitializationKind::CreateDefault(Loc); 3079 3080 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3081 ExprResult MemberInit = 3082 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3083 3084 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3085 if (MemberInit.isInvalid()) 3086 return true; 3087 3088 if (Indirect) 3089 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3090 Indirect, Loc, 3091 Loc, 3092 MemberInit.get(), 3093 Loc); 3094 else 3095 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3096 Field, Loc, Loc, 3097 MemberInit.get(), 3098 Loc); 3099 return false; 3100 } 3101 3102 if (!Field->getParent()->isUnion()) { 3103 if (FieldBaseElementType->isReferenceType()) { 3104 SemaRef.Diag(Constructor->getLocation(), 3105 diag::err_uninitialized_member_in_ctor) 3106 << (int)Constructor->isImplicit() 3107 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3108 << 0 << Field->getDeclName(); 3109 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3110 return true; 3111 } 3112 3113 if (FieldBaseElementType.isConstQualified()) { 3114 SemaRef.Diag(Constructor->getLocation(), 3115 diag::err_uninitialized_member_in_ctor) 3116 << (int)Constructor->isImplicit() 3117 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3118 << 1 << Field->getDeclName(); 3119 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3120 return true; 3121 } 3122 } 3123 3124 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3125 FieldBaseElementType->isObjCRetainableType() && 3126 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3127 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3128 // ARC: 3129 // Default-initialize Objective-C pointers to NULL. 3130 CXXMemberInit 3131 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3132 Loc, Loc, 3133 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3134 Loc); 3135 return false; 3136 } 3137 3138 // Nothing to initialize. 3139 CXXMemberInit = 0; 3140 return false; 3141} 3142 3143namespace { 3144struct BaseAndFieldInfo { 3145 Sema &S; 3146 CXXConstructorDecl *Ctor; 3147 bool AnyErrorsInInits; 3148 ImplicitInitializerKind IIK; 3149 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3150 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3151 3152 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3153 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3154 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3155 if (Generated && Ctor->isCopyConstructor()) 3156 IIK = IIK_Copy; 3157 else if (Generated && Ctor->isMoveConstructor()) 3158 IIK = IIK_Move; 3159 else if (Ctor->getInheritedConstructor()) 3160 IIK = IIK_Inherit; 3161 else 3162 IIK = IIK_Default; 3163 } 3164 3165 bool isImplicitCopyOrMove() const { 3166 switch (IIK) { 3167 case IIK_Copy: 3168 case IIK_Move: 3169 return true; 3170 3171 case IIK_Default: 3172 case IIK_Inherit: 3173 return false; 3174 } 3175 3176 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3177 } 3178 3179 bool addFieldInitializer(CXXCtorInitializer *Init) { 3180 AllToInit.push_back(Init); 3181 3182 // Check whether this initializer makes the field "used". 3183 if (Init->getInit()->HasSideEffects(S.Context)) 3184 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3185 3186 return false; 3187 } 3188}; 3189} 3190 3191/// \brief Determine whether the given indirect field declaration is somewhere 3192/// within an anonymous union. 3193static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 3194 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 3195 CEnd = F->chain_end(); 3196 C != CEnd; ++C) 3197 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 3198 if (Record->isUnion()) 3199 return true; 3200 3201 return false; 3202} 3203 3204/// \brief Determine whether the given type is an incomplete or zero-lenfgth 3205/// array type. 3206static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3207 if (T->isIncompleteArrayType()) 3208 return true; 3209 3210 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3211 if (!ArrayT->getSize()) 3212 return true; 3213 3214 T = ArrayT->getElementType(); 3215 } 3216 3217 return false; 3218} 3219 3220static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3221 FieldDecl *Field, 3222 IndirectFieldDecl *Indirect = 0) { 3223 3224 // Overwhelmingly common case: we have a direct initializer for this field. 3225 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 3226 return Info.addFieldInitializer(Init); 3227 3228 // C++11 [class.base.init]p8: if the entity is a non-static data member that 3229 // has a brace-or-equal-initializer, the entity is initialized as specified 3230 // in [dcl.init]. 3231 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3232 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3233 Info.Ctor->getLocation(), Field); 3234 CXXCtorInitializer *Init; 3235 if (Indirect) 3236 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3237 SourceLocation(), 3238 SourceLocation(), DIE, 3239 SourceLocation()); 3240 else 3241 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3242 SourceLocation(), 3243 SourceLocation(), DIE, 3244 SourceLocation()); 3245 return Info.addFieldInitializer(Init); 3246 } 3247 3248 // Don't build an implicit initializer for union members if none was 3249 // explicitly specified. 3250 if (Field->getParent()->isUnion() || 3251 (Indirect && isWithinAnonymousUnion(Indirect))) 3252 return false; 3253 3254 // Don't initialize incomplete or zero-length arrays. 3255 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3256 return false; 3257 3258 // Don't try to build an implicit initializer if there were semantic 3259 // errors in any of the initializers (and therefore we might be 3260 // missing some that the user actually wrote). 3261 if (Info.AnyErrorsInInits || Field->isInvalidDecl()) 3262 return false; 3263 3264 CXXCtorInitializer *Init = 0; 3265 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3266 Indirect, Init)) 3267 return true; 3268 3269 if (!Init) 3270 return false; 3271 3272 return Info.addFieldInitializer(Init); 3273} 3274 3275bool 3276Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3277 CXXCtorInitializer *Initializer) { 3278 assert(Initializer->isDelegatingInitializer()); 3279 Constructor->setNumCtorInitializers(1); 3280 CXXCtorInitializer **initializer = 3281 new (Context) CXXCtorInitializer*[1]; 3282 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3283 Constructor->setCtorInitializers(initializer); 3284 3285 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3286 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3287 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3288 } 3289 3290 DelegatingCtorDecls.push_back(Constructor); 3291 3292 return false; 3293} 3294 3295bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3296 ArrayRef<CXXCtorInitializer *> Initializers) { 3297 if (Constructor->isDependentContext()) { 3298 // Just store the initializers as written, they will be checked during 3299 // instantiation. 3300 if (!Initializers.empty()) { 3301 Constructor->setNumCtorInitializers(Initializers.size()); 3302 CXXCtorInitializer **baseOrMemberInitializers = 3303 new (Context) CXXCtorInitializer*[Initializers.size()]; 3304 memcpy(baseOrMemberInitializers, Initializers.data(), 3305 Initializers.size() * sizeof(CXXCtorInitializer*)); 3306 Constructor->setCtorInitializers(baseOrMemberInitializers); 3307 } 3308 3309 // Let template instantiation know whether we had errors. 3310 if (AnyErrors) 3311 Constructor->setInvalidDecl(); 3312 3313 return false; 3314 } 3315 3316 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3317 3318 // We need to build the initializer AST according to order of construction 3319 // and not what user specified in the Initializers list. 3320 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3321 if (!ClassDecl) 3322 return true; 3323 3324 bool HadError = false; 3325 3326 for (unsigned i = 0; i < Initializers.size(); i++) { 3327 CXXCtorInitializer *Member = Initializers[i]; 3328 3329 if (Member->isBaseInitializer()) 3330 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3331 else 3332 Info.AllBaseFields[Member->getAnyMember()] = Member; 3333 } 3334 3335 // Keep track of the direct virtual bases. 3336 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3337 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 3338 E = ClassDecl->bases_end(); I != E; ++I) { 3339 if (I->isVirtual()) 3340 DirectVBases.insert(I); 3341 } 3342 3343 // Push virtual bases before others. 3344 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3345 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3346 3347 if (CXXCtorInitializer *Value 3348 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 3349 Info.AllToInit.push_back(Value); 3350 } else if (!AnyErrors) { 3351 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 3352 CXXCtorInitializer *CXXBaseInit; 3353 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3354 VBase, IsInheritedVirtualBase, 3355 CXXBaseInit)) { 3356 HadError = true; 3357 continue; 3358 } 3359 3360 Info.AllToInit.push_back(CXXBaseInit); 3361 } 3362 } 3363 3364 // Non-virtual bases. 3365 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3366 E = ClassDecl->bases_end(); Base != E; ++Base) { 3367 // Virtuals are in the virtual base list and already constructed. 3368 if (Base->isVirtual()) 3369 continue; 3370 3371 if (CXXCtorInitializer *Value 3372 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 3373 Info.AllToInit.push_back(Value); 3374 } else if (!AnyErrors) { 3375 CXXCtorInitializer *CXXBaseInit; 3376 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3377 Base, /*IsInheritedVirtualBase=*/false, 3378 CXXBaseInit)) { 3379 HadError = true; 3380 continue; 3381 } 3382 3383 Info.AllToInit.push_back(CXXBaseInit); 3384 } 3385 } 3386 3387 // Fields. 3388 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 3389 MemEnd = ClassDecl->decls_end(); 3390 Mem != MemEnd; ++Mem) { 3391 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 3392 // C++ [class.bit]p2: 3393 // A declaration for a bit-field that omits the identifier declares an 3394 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3395 // initialized. 3396 if (F->isUnnamedBitfield()) 3397 continue; 3398 3399 // If we're not generating the implicit copy/move constructor, then we'll 3400 // handle anonymous struct/union fields based on their individual 3401 // indirect fields. 3402 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3403 continue; 3404 3405 if (CollectFieldInitializer(*this, Info, F)) 3406 HadError = true; 3407 continue; 3408 } 3409 3410 // Beyond this point, we only consider default initialization. 3411 if (Info.isImplicitCopyOrMove()) 3412 continue; 3413 3414 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 3415 if (F->getType()->isIncompleteArrayType()) { 3416 assert(ClassDecl->hasFlexibleArrayMember() && 3417 "Incomplete array type is not valid"); 3418 continue; 3419 } 3420 3421 // Initialize each field of an anonymous struct individually. 3422 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3423 HadError = true; 3424 3425 continue; 3426 } 3427 } 3428 3429 unsigned NumInitializers = Info.AllToInit.size(); 3430 if (NumInitializers > 0) { 3431 Constructor->setNumCtorInitializers(NumInitializers); 3432 CXXCtorInitializer **baseOrMemberInitializers = 3433 new (Context) CXXCtorInitializer*[NumInitializers]; 3434 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3435 NumInitializers * sizeof(CXXCtorInitializer*)); 3436 Constructor->setCtorInitializers(baseOrMemberInitializers); 3437 3438 // Constructors implicitly reference the base and member 3439 // destructors. 3440 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3441 Constructor->getParent()); 3442 } 3443 3444 return HadError; 3445} 3446 3447static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3448 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3449 const RecordDecl *RD = RT->getDecl(); 3450 if (RD->isAnonymousStructOrUnion()) { 3451 for (RecordDecl::field_iterator Field = RD->field_begin(), 3452 E = RD->field_end(); Field != E; ++Field) 3453 PopulateKeysForFields(*Field, IdealInits); 3454 return; 3455 } 3456 } 3457 IdealInits.push_back(Field); 3458} 3459 3460static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3461 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 3462} 3463 3464static void *GetKeyForMember(ASTContext &Context, 3465 CXXCtorInitializer *Member) { 3466 if (!Member->isAnyMemberInitializer()) 3467 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3468 3469 return Member->getAnyMember(); 3470} 3471 3472static void DiagnoseBaseOrMemInitializerOrder( 3473 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3474 ArrayRef<CXXCtorInitializer *> Inits) { 3475 if (Constructor->getDeclContext()->isDependentContext()) 3476 return; 3477 3478 // Don't check initializers order unless the warning is enabled at the 3479 // location of at least one initializer. 3480 bool ShouldCheckOrder = false; 3481 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3482 CXXCtorInitializer *Init = Inits[InitIndex]; 3483 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3484 Init->getSourceLocation()) 3485 != DiagnosticsEngine::Ignored) { 3486 ShouldCheckOrder = true; 3487 break; 3488 } 3489 } 3490 if (!ShouldCheckOrder) 3491 return; 3492 3493 // Build the list of bases and members in the order that they'll 3494 // actually be initialized. The explicit initializers should be in 3495 // this same order but may be missing things. 3496 SmallVector<const void*, 32> IdealInitKeys; 3497 3498 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3499 3500 // 1. Virtual bases. 3501 for (CXXRecordDecl::base_class_const_iterator VBase = 3502 ClassDecl->vbases_begin(), 3503 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3504 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3505 3506 // 2. Non-virtual bases. 3507 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3508 E = ClassDecl->bases_end(); Base != E; ++Base) { 3509 if (Base->isVirtual()) 3510 continue; 3511 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3512 } 3513 3514 // 3. Direct fields. 3515 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3516 E = ClassDecl->field_end(); Field != E; ++Field) { 3517 if (Field->isUnnamedBitfield()) 3518 continue; 3519 3520 PopulateKeysForFields(*Field, IdealInitKeys); 3521 } 3522 3523 unsigned NumIdealInits = IdealInitKeys.size(); 3524 unsigned IdealIndex = 0; 3525 3526 CXXCtorInitializer *PrevInit = 0; 3527 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3528 CXXCtorInitializer *Init = Inits[InitIndex]; 3529 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3530 3531 // Scan forward to try to find this initializer in the idealized 3532 // initializers list. 3533 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3534 if (InitKey == IdealInitKeys[IdealIndex]) 3535 break; 3536 3537 // If we didn't find this initializer, it must be because we 3538 // scanned past it on a previous iteration. That can only 3539 // happen if we're out of order; emit a warning. 3540 if (IdealIndex == NumIdealInits && PrevInit) { 3541 Sema::SemaDiagnosticBuilder D = 3542 SemaRef.Diag(PrevInit->getSourceLocation(), 3543 diag::warn_initializer_out_of_order); 3544 3545 if (PrevInit->isAnyMemberInitializer()) 3546 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3547 else 3548 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3549 3550 if (Init->isAnyMemberInitializer()) 3551 D << 0 << Init->getAnyMember()->getDeclName(); 3552 else 3553 D << 1 << Init->getTypeSourceInfo()->getType(); 3554 3555 // Move back to the initializer's location in the ideal list. 3556 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3557 if (InitKey == IdealInitKeys[IdealIndex]) 3558 break; 3559 3560 assert(IdealIndex != NumIdealInits && 3561 "initializer not found in initializer list"); 3562 } 3563 3564 PrevInit = Init; 3565 } 3566} 3567 3568namespace { 3569bool CheckRedundantInit(Sema &S, 3570 CXXCtorInitializer *Init, 3571 CXXCtorInitializer *&PrevInit) { 3572 if (!PrevInit) { 3573 PrevInit = Init; 3574 return false; 3575 } 3576 3577 if (FieldDecl *Field = Init->getAnyMember()) 3578 S.Diag(Init->getSourceLocation(), 3579 diag::err_multiple_mem_initialization) 3580 << Field->getDeclName() 3581 << Init->getSourceRange(); 3582 else { 3583 const Type *BaseClass = Init->getBaseClass(); 3584 assert(BaseClass && "neither field nor base"); 3585 S.Diag(Init->getSourceLocation(), 3586 diag::err_multiple_base_initialization) 3587 << QualType(BaseClass, 0) 3588 << Init->getSourceRange(); 3589 } 3590 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3591 << 0 << PrevInit->getSourceRange(); 3592 3593 return true; 3594} 3595 3596typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3597typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3598 3599bool CheckRedundantUnionInit(Sema &S, 3600 CXXCtorInitializer *Init, 3601 RedundantUnionMap &Unions) { 3602 FieldDecl *Field = Init->getAnyMember(); 3603 RecordDecl *Parent = Field->getParent(); 3604 NamedDecl *Child = Field; 3605 3606 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3607 if (Parent->isUnion()) { 3608 UnionEntry &En = Unions[Parent]; 3609 if (En.first && En.first != Child) { 3610 S.Diag(Init->getSourceLocation(), 3611 diag::err_multiple_mem_union_initialization) 3612 << Field->getDeclName() 3613 << Init->getSourceRange(); 3614 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3615 << 0 << En.second->getSourceRange(); 3616 return true; 3617 } 3618 if (!En.first) { 3619 En.first = Child; 3620 En.second = Init; 3621 } 3622 if (!Parent->isAnonymousStructOrUnion()) 3623 return false; 3624 } 3625 3626 Child = Parent; 3627 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3628 } 3629 3630 return false; 3631} 3632} 3633 3634/// ActOnMemInitializers - Handle the member initializers for a constructor. 3635void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3636 SourceLocation ColonLoc, 3637 ArrayRef<CXXCtorInitializer*> MemInits, 3638 bool AnyErrors) { 3639 if (!ConstructorDecl) 3640 return; 3641 3642 AdjustDeclIfTemplate(ConstructorDecl); 3643 3644 CXXConstructorDecl *Constructor 3645 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3646 3647 if (!Constructor) { 3648 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3649 return; 3650 } 3651 3652 // Mapping for the duplicate initializers check. 3653 // For member initializers, this is keyed with a FieldDecl*. 3654 // For base initializers, this is keyed with a Type*. 3655 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 3656 3657 // Mapping for the inconsistent anonymous-union initializers check. 3658 RedundantUnionMap MemberUnions; 3659 3660 bool HadError = false; 3661 for (unsigned i = 0; i < MemInits.size(); i++) { 3662 CXXCtorInitializer *Init = MemInits[i]; 3663 3664 // Set the source order index. 3665 Init->setSourceOrder(i); 3666 3667 if (Init->isAnyMemberInitializer()) { 3668 FieldDecl *Field = Init->getAnyMember(); 3669 if (CheckRedundantInit(*this, Init, Members[Field]) || 3670 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3671 HadError = true; 3672 } else if (Init->isBaseInitializer()) { 3673 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3674 if (CheckRedundantInit(*this, Init, Members[Key])) 3675 HadError = true; 3676 } else { 3677 assert(Init->isDelegatingInitializer()); 3678 // This must be the only initializer 3679 if (MemInits.size() != 1) { 3680 Diag(Init->getSourceLocation(), 3681 diag::err_delegating_initializer_alone) 3682 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3683 // We will treat this as being the only initializer. 3684 } 3685 SetDelegatingInitializer(Constructor, MemInits[i]); 3686 // Return immediately as the initializer is set. 3687 return; 3688 } 3689 } 3690 3691 if (HadError) 3692 return; 3693 3694 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 3695 3696 SetCtorInitializers(Constructor, AnyErrors, MemInits); 3697} 3698 3699void 3700Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3701 CXXRecordDecl *ClassDecl) { 3702 // Ignore dependent contexts. Also ignore unions, since their members never 3703 // have destructors implicitly called. 3704 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3705 return; 3706 3707 // FIXME: all the access-control diagnostics are positioned on the 3708 // field/base declaration. That's probably good; that said, the 3709 // user might reasonably want to know why the destructor is being 3710 // emitted, and we currently don't say. 3711 3712 // Non-static data members. 3713 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3714 E = ClassDecl->field_end(); I != E; ++I) { 3715 FieldDecl *Field = *I; 3716 if (Field->isInvalidDecl()) 3717 continue; 3718 3719 // Don't destroy incomplete or zero-length arrays. 3720 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3721 continue; 3722 3723 QualType FieldType = Context.getBaseElementType(Field->getType()); 3724 3725 const RecordType* RT = FieldType->getAs<RecordType>(); 3726 if (!RT) 3727 continue; 3728 3729 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3730 if (FieldClassDecl->isInvalidDecl()) 3731 continue; 3732 if (FieldClassDecl->hasIrrelevantDestructor()) 3733 continue; 3734 // The destructor for an implicit anonymous union member is never invoked. 3735 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3736 continue; 3737 3738 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3739 assert(Dtor && "No dtor found for FieldClassDecl!"); 3740 CheckDestructorAccess(Field->getLocation(), Dtor, 3741 PDiag(diag::err_access_dtor_field) 3742 << Field->getDeclName() 3743 << FieldType); 3744 3745 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3746 DiagnoseUseOfDecl(Dtor, Location); 3747 } 3748 3749 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3750 3751 // Bases. 3752 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3753 E = ClassDecl->bases_end(); Base != E; ++Base) { 3754 // Bases are always records in a well-formed non-dependent class. 3755 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3756 3757 // Remember direct virtual bases. 3758 if (Base->isVirtual()) 3759 DirectVirtualBases.insert(RT); 3760 3761 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3762 // If our base class is invalid, we probably can't get its dtor anyway. 3763 if (BaseClassDecl->isInvalidDecl()) 3764 continue; 3765 if (BaseClassDecl->hasIrrelevantDestructor()) 3766 continue; 3767 3768 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3769 assert(Dtor && "No dtor found for BaseClassDecl!"); 3770 3771 // FIXME: caret should be on the start of the class name 3772 CheckDestructorAccess(Base->getLocStart(), Dtor, 3773 PDiag(diag::err_access_dtor_base) 3774 << Base->getType() 3775 << Base->getSourceRange(), 3776 Context.getTypeDeclType(ClassDecl)); 3777 3778 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3779 DiagnoseUseOfDecl(Dtor, Location); 3780 } 3781 3782 // Virtual bases. 3783 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3784 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3785 3786 // Bases are always records in a well-formed non-dependent class. 3787 const RecordType *RT = VBase->getType()->castAs<RecordType>(); 3788 3789 // Ignore direct virtual bases. 3790 if (DirectVirtualBases.count(RT)) 3791 continue; 3792 3793 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3794 // If our base class is invalid, we probably can't get its dtor anyway. 3795 if (BaseClassDecl->isInvalidDecl()) 3796 continue; 3797 if (BaseClassDecl->hasIrrelevantDestructor()) 3798 continue; 3799 3800 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3801 assert(Dtor && "No dtor found for BaseClassDecl!"); 3802 if (CheckDestructorAccess( 3803 ClassDecl->getLocation(), Dtor, 3804 PDiag(diag::err_access_dtor_vbase) 3805 << Context.getTypeDeclType(ClassDecl) << VBase->getType(), 3806 Context.getTypeDeclType(ClassDecl)) == 3807 AR_accessible) { 3808 CheckDerivedToBaseConversion( 3809 Context.getTypeDeclType(ClassDecl), VBase->getType(), 3810 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 3811 SourceRange(), DeclarationName(), 0); 3812 } 3813 3814 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3815 DiagnoseUseOfDecl(Dtor, Location); 3816 } 3817} 3818 3819void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 3820 if (!CDtorDecl) 3821 return; 3822 3823 if (CXXConstructorDecl *Constructor 3824 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 3825 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 3826} 3827 3828bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3829 unsigned DiagID, AbstractDiagSelID SelID) { 3830 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 3831 unsigned DiagID; 3832 AbstractDiagSelID SelID; 3833 3834 public: 3835 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 3836 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 3837 3838 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 3839 if (Suppressed) return; 3840 if (SelID == -1) 3841 S.Diag(Loc, DiagID) << T; 3842 else 3843 S.Diag(Loc, DiagID) << SelID << T; 3844 } 3845 } Diagnoser(DiagID, SelID); 3846 3847 return RequireNonAbstractType(Loc, T, Diagnoser); 3848} 3849 3850bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3851 TypeDiagnoser &Diagnoser) { 3852 if (!getLangOpts().CPlusPlus) 3853 return false; 3854 3855 if (const ArrayType *AT = Context.getAsArrayType(T)) 3856 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3857 3858 if (const PointerType *PT = T->getAs<PointerType>()) { 3859 // Find the innermost pointer type. 3860 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 3861 PT = T; 3862 3863 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 3864 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3865 } 3866 3867 const RecordType *RT = T->getAs<RecordType>(); 3868 if (!RT) 3869 return false; 3870 3871 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3872 3873 // We can't answer whether something is abstract until it has a 3874 // definition. If it's currently being defined, we'll walk back 3875 // over all the declarations when we have a full definition. 3876 const CXXRecordDecl *Def = RD->getDefinition(); 3877 if (!Def || Def->isBeingDefined()) 3878 return false; 3879 3880 if (!RD->isAbstract()) 3881 return false; 3882 3883 Diagnoser.diagnose(*this, Loc, T); 3884 DiagnoseAbstractType(RD); 3885 3886 return true; 3887} 3888 3889void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 3890 // Check if we've already emitted the list of pure virtual functions 3891 // for this class. 3892 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 3893 return; 3894 3895 CXXFinalOverriderMap FinalOverriders; 3896 RD->getFinalOverriders(FinalOverriders); 3897 3898 // Keep a set of seen pure methods so we won't diagnose the same method 3899 // more than once. 3900 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 3901 3902 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 3903 MEnd = FinalOverriders.end(); 3904 M != MEnd; 3905 ++M) { 3906 for (OverridingMethods::iterator SO = M->second.begin(), 3907 SOEnd = M->second.end(); 3908 SO != SOEnd; ++SO) { 3909 // C++ [class.abstract]p4: 3910 // A class is abstract if it contains or inherits at least one 3911 // pure virtual function for which the final overrider is pure 3912 // virtual. 3913 3914 // 3915 if (SO->second.size() != 1) 3916 continue; 3917 3918 if (!SO->second.front().Method->isPure()) 3919 continue; 3920 3921 if (!SeenPureMethods.insert(SO->second.front().Method)) 3922 continue; 3923 3924 Diag(SO->second.front().Method->getLocation(), 3925 diag::note_pure_virtual_function) 3926 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 3927 } 3928 } 3929 3930 if (!PureVirtualClassDiagSet) 3931 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 3932 PureVirtualClassDiagSet->insert(RD); 3933} 3934 3935namespace { 3936struct AbstractUsageInfo { 3937 Sema &S; 3938 CXXRecordDecl *Record; 3939 CanQualType AbstractType; 3940 bool Invalid; 3941 3942 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 3943 : S(S), Record(Record), 3944 AbstractType(S.Context.getCanonicalType( 3945 S.Context.getTypeDeclType(Record))), 3946 Invalid(false) {} 3947 3948 void DiagnoseAbstractType() { 3949 if (Invalid) return; 3950 S.DiagnoseAbstractType(Record); 3951 Invalid = true; 3952 } 3953 3954 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 3955}; 3956 3957struct CheckAbstractUsage { 3958 AbstractUsageInfo &Info; 3959 const NamedDecl *Ctx; 3960 3961 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 3962 : Info(Info), Ctx(Ctx) {} 3963 3964 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3965 switch (TL.getTypeLocClass()) { 3966#define ABSTRACT_TYPELOC(CLASS, PARENT) 3967#define TYPELOC(CLASS, PARENT) \ 3968 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 3969#include "clang/AST/TypeLocNodes.def" 3970 } 3971 } 3972 3973 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3974 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 3975 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3976 if (!TL.getArg(I)) 3977 continue; 3978 3979 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 3980 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 3981 } 3982 } 3983 3984 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3985 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 3986 } 3987 3988 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3989 // Visit the type parameters from a permissive context. 3990 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3991 TemplateArgumentLoc TAL = TL.getArgLoc(I); 3992 if (TAL.getArgument().getKind() == TemplateArgument::Type) 3993 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 3994 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 3995 // TODO: other template argument types? 3996 } 3997 } 3998 3999 // Visit pointee types from a permissive context. 4000#define CheckPolymorphic(Type) \ 4001 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4002 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4003 } 4004 CheckPolymorphic(PointerTypeLoc) 4005 CheckPolymorphic(ReferenceTypeLoc) 4006 CheckPolymorphic(MemberPointerTypeLoc) 4007 CheckPolymorphic(BlockPointerTypeLoc) 4008 CheckPolymorphic(AtomicTypeLoc) 4009 4010 /// Handle all the types we haven't given a more specific 4011 /// implementation for above. 4012 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4013 // Every other kind of type that we haven't called out already 4014 // that has an inner type is either (1) sugar or (2) contains that 4015 // inner type in some way as a subobject. 4016 if (TypeLoc Next = TL.getNextTypeLoc()) 4017 return Visit(Next, Sel); 4018 4019 // If there's no inner type and we're in a permissive context, 4020 // don't diagnose. 4021 if (Sel == Sema::AbstractNone) return; 4022 4023 // Check whether the type matches the abstract type. 4024 QualType T = TL.getType(); 4025 if (T->isArrayType()) { 4026 Sel = Sema::AbstractArrayType; 4027 T = Info.S.Context.getBaseElementType(T); 4028 } 4029 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4030 if (CT != Info.AbstractType) return; 4031 4032 // It matched; do some magic. 4033 if (Sel == Sema::AbstractArrayType) { 4034 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4035 << T << TL.getSourceRange(); 4036 } else { 4037 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4038 << Sel << T << TL.getSourceRange(); 4039 } 4040 Info.DiagnoseAbstractType(); 4041 } 4042}; 4043 4044void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4045 Sema::AbstractDiagSelID Sel) { 4046 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4047} 4048 4049} 4050 4051/// Check for invalid uses of an abstract type in a method declaration. 4052static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4053 CXXMethodDecl *MD) { 4054 // No need to do the check on definitions, which require that 4055 // the return/param types be complete. 4056 if (MD->doesThisDeclarationHaveABody()) 4057 return; 4058 4059 // For safety's sake, just ignore it if we don't have type source 4060 // information. This should never happen for non-implicit methods, 4061 // but... 4062 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4063 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4064} 4065 4066/// Check for invalid uses of an abstract type within a class definition. 4067static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4068 CXXRecordDecl *RD) { 4069 for (CXXRecordDecl::decl_iterator 4070 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 4071 Decl *D = *I; 4072 if (D->isImplicit()) continue; 4073 4074 // Methods and method templates. 4075 if (isa<CXXMethodDecl>(D)) { 4076 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4077 } else if (isa<FunctionTemplateDecl>(D)) { 4078 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4079 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4080 4081 // Fields and static variables. 4082 } else if (isa<FieldDecl>(D)) { 4083 FieldDecl *FD = cast<FieldDecl>(D); 4084 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4085 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4086 } else if (isa<VarDecl>(D)) { 4087 VarDecl *VD = cast<VarDecl>(D); 4088 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4089 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4090 4091 // Nested classes and class templates. 4092 } else if (isa<CXXRecordDecl>(D)) { 4093 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4094 } else if (isa<ClassTemplateDecl>(D)) { 4095 CheckAbstractClassUsage(Info, 4096 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4097 } 4098 } 4099} 4100 4101/// \brief Perform semantic checks on a class definition that has been 4102/// completing, introducing implicitly-declared members, checking for 4103/// abstract types, etc. 4104void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4105 if (!Record) 4106 return; 4107 4108 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4109 AbstractUsageInfo Info(*this, Record); 4110 CheckAbstractClassUsage(Info, Record); 4111 } 4112 4113 // If this is not an aggregate type and has no user-declared constructor, 4114 // complain about any non-static data members of reference or const scalar 4115 // type, since they will never get initializers. 4116 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4117 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4118 !Record->isLambda()) { 4119 bool Complained = false; 4120 for (RecordDecl::field_iterator F = Record->field_begin(), 4121 FEnd = Record->field_end(); 4122 F != FEnd; ++F) { 4123 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4124 continue; 4125 4126 if (F->getType()->isReferenceType() || 4127 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4128 if (!Complained) { 4129 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4130 << Record->getTagKind() << Record; 4131 Complained = true; 4132 } 4133 4134 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4135 << F->getType()->isReferenceType() 4136 << F->getDeclName(); 4137 } 4138 } 4139 } 4140 4141 if (Record->isDynamicClass() && !Record->isDependentType()) 4142 DynamicClasses.push_back(Record); 4143 4144 if (Record->getIdentifier()) { 4145 // C++ [class.mem]p13: 4146 // If T is the name of a class, then each of the following shall have a 4147 // name different from T: 4148 // - every member of every anonymous union that is a member of class T. 4149 // 4150 // C++ [class.mem]p14: 4151 // In addition, if class T has a user-declared constructor (12.1), every 4152 // non-static data member of class T shall have a name different from T. 4153 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4154 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4155 ++I) { 4156 NamedDecl *D = *I; 4157 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4158 isa<IndirectFieldDecl>(D)) { 4159 Diag(D->getLocation(), diag::err_member_name_of_class) 4160 << D->getDeclName(); 4161 break; 4162 } 4163 } 4164 } 4165 4166 // Warn if the class has virtual methods but non-virtual public destructor. 4167 if (Record->isPolymorphic() && !Record->isDependentType()) { 4168 CXXDestructorDecl *dtor = Record->getDestructor(); 4169 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 4170 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4171 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4172 } 4173 4174 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) { 4175 Diag(Record->getLocation(), diag::warn_abstract_final_class); 4176 DiagnoseAbstractType(Record); 4177 } 4178 4179 if (!Record->isDependentType()) { 4180 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4181 MEnd = Record->method_end(); 4182 M != MEnd; ++M) { 4183 // See if a method overloads virtual methods in a base 4184 // class without overriding any. 4185 if (!M->isStatic()) 4186 DiagnoseHiddenVirtualMethods(Record, *M); 4187 4188 // Check whether the explicitly-defaulted special members are valid. 4189 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4190 CheckExplicitlyDefaultedSpecialMember(*M); 4191 4192 // For an explicitly defaulted or deleted special member, we defer 4193 // determining triviality until the class is complete. That time is now! 4194 if (!M->isImplicit() && !M->isUserProvided()) { 4195 CXXSpecialMember CSM = getSpecialMember(*M); 4196 if (CSM != CXXInvalid) { 4197 M->setTrivial(SpecialMemberIsTrivial(*M, CSM)); 4198 4199 // Inform the class that we've finished declaring this member. 4200 Record->finishedDefaultedOrDeletedMember(*M); 4201 } 4202 } 4203 } 4204 } 4205 4206 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4207 // function that is not a constructor declares that member function to be 4208 // const. [...] The class of which that function is a member shall be 4209 // a literal type. 4210 // 4211 // If the class has virtual bases, any constexpr members will already have 4212 // been diagnosed by the checks performed on the member declaration, so 4213 // suppress this (less useful) diagnostic. 4214 // 4215 // We delay this until we know whether an explicitly-defaulted (or deleted) 4216 // destructor for the class is trivial. 4217 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4218 !Record->isLiteral() && !Record->getNumVBases()) { 4219 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4220 MEnd = Record->method_end(); 4221 M != MEnd; ++M) { 4222 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 4223 switch (Record->getTemplateSpecializationKind()) { 4224 case TSK_ImplicitInstantiation: 4225 case TSK_ExplicitInstantiationDeclaration: 4226 case TSK_ExplicitInstantiationDefinition: 4227 // If a template instantiates to a non-literal type, but its members 4228 // instantiate to constexpr functions, the template is technically 4229 // ill-formed, but we allow it for sanity. 4230 continue; 4231 4232 case TSK_Undeclared: 4233 case TSK_ExplicitSpecialization: 4234 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4235 diag::err_constexpr_method_non_literal); 4236 break; 4237 } 4238 4239 // Only produce one error per class. 4240 break; 4241 } 4242 } 4243 } 4244 4245 // Declare inheriting constructors. We do this eagerly here because: 4246 // - The standard requires an eager diagnostic for conflicting inheriting 4247 // constructors from different classes. 4248 // - The lazy declaration of the other implicit constructors is so as to not 4249 // waste space and performance on classes that are not meant to be 4250 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4251 // have inheriting constructors. 4252 DeclareInheritingConstructors(Record); 4253} 4254 4255/// Is the special member function which would be selected to perform the 4256/// specified operation on the specified class type a constexpr constructor? 4257static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4258 Sema::CXXSpecialMember CSM, 4259 bool ConstArg) { 4260 Sema::SpecialMemberOverloadResult *SMOR = 4261 S.LookupSpecialMember(ClassDecl, CSM, ConstArg, 4262 false, false, false, false); 4263 if (!SMOR || !SMOR->getMethod()) 4264 // A constructor we wouldn't select can't be "involved in initializing" 4265 // anything. 4266 return true; 4267 return SMOR->getMethod()->isConstexpr(); 4268} 4269 4270/// Determine whether the specified special member function would be constexpr 4271/// if it were implicitly defined. 4272static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4273 Sema::CXXSpecialMember CSM, 4274 bool ConstArg) { 4275 if (!S.getLangOpts().CPlusPlus11) 4276 return false; 4277 4278 // C++11 [dcl.constexpr]p4: 4279 // In the definition of a constexpr constructor [...] 4280 bool Ctor = true; 4281 switch (CSM) { 4282 case Sema::CXXDefaultConstructor: 4283 // Since default constructor lookup is essentially trivial (and cannot 4284 // involve, for instance, template instantiation), we compute whether a 4285 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4286 // 4287 // This is important for performance; we need to know whether the default 4288 // constructor is constexpr to determine whether the type is a literal type. 4289 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4290 4291 case Sema::CXXCopyConstructor: 4292 case Sema::CXXMoveConstructor: 4293 // For copy or move constructors, we need to perform overload resolution. 4294 break; 4295 4296 case Sema::CXXCopyAssignment: 4297 case Sema::CXXMoveAssignment: 4298 if (!S.getLangOpts().CPlusPlus1y) 4299 return false; 4300 // In C++1y, we need to perform overload resolution. 4301 Ctor = false; 4302 break; 4303 4304 case Sema::CXXDestructor: 4305 case Sema::CXXInvalid: 4306 return false; 4307 } 4308 4309 // -- if the class is a non-empty union, or for each non-empty anonymous 4310 // union member of a non-union class, exactly one non-static data member 4311 // shall be initialized; [DR1359] 4312 // 4313 // If we squint, this is guaranteed, since exactly one non-static data member 4314 // will be initialized (if the constructor isn't deleted), we just don't know 4315 // which one. 4316 if (Ctor && ClassDecl->isUnion()) 4317 return true; 4318 4319 // -- the class shall not have any virtual base classes; 4320 if (Ctor && ClassDecl->getNumVBases()) 4321 return false; 4322 4323 // C++1y [class.copy]p26: 4324 // -- [the class] is a literal type, and 4325 if (!Ctor && !ClassDecl->isLiteral()) 4326 return false; 4327 4328 // -- every constructor involved in initializing [...] base class 4329 // sub-objects shall be a constexpr constructor; 4330 // -- the assignment operator selected to copy/move each direct base 4331 // class is a constexpr function, and 4332 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4333 BEnd = ClassDecl->bases_end(); 4334 B != BEnd; ++B) { 4335 const RecordType *BaseType = B->getType()->getAs<RecordType>(); 4336 if (!BaseType) continue; 4337 4338 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4339 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg)) 4340 return false; 4341 } 4342 4343 // -- every constructor involved in initializing non-static data members 4344 // [...] shall be a constexpr constructor; 4345 // -- every non-static data member and base class sub-object shall be 4346 // initialized 4347 // -- for each non-stastic data member of X that is of class type (or array 4348 // thereof), the assignment operator selected to copy/move that member is 4349 // a constexpr function 4350 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4351 FEnd = ClassDecl->field_end(); 4352 F != FEnd; ++F) { 4353 if (F->isInvalidDecl()) 4354 continue; 4355 if (const RecordType *RecordTy = 4356 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4357 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4358 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg)) 4359 return false; 4360 } 4361 } 4362 4363 // All OK, it's constexpr! 4364 return true; 4365} 4366 4367static Sema::ImplicitExceptionSpecification 4368computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4369 switch (S.getSpecialMember(MD)) { 4370 case Sema::CXXDefaultConstructor: 4371 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4372 case Sema::CXXCopyConstructor: 4373 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4374 case Sema::CXXCopyAssignment: 4375 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4376 case Sema::CXXMoveConstructor: 4377 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4378 case Sema::CXXMoveAssignment: 4379 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4380 case Sema::CXXDestructor: 4381 return S.ComputeDefaultedDtorExceptionSpec(MD); 4382 case Sema::CXXInvalid: 4383 break; 4384 } 4385 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4386 "only special members have implicit exception specs"); 4387 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4388} 4389 4390static void 4391updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT, 4392 const Sema::ImplicitExceptionSpecification &ExceptSpec) { 4393 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4394 ExceptSpec.getEPI(EPI); 4395 FD->setType(S.Context.getFunctionType(FPT->getResultType(), 4396 FPT->getArgTypes(), EPI)); 4397} 4398 4399void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4400 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4401 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4402 return; 4403 4404 // Evaluate the exception specification. 4405 ImplicitExceptionSpecification ExceptSpec = 4406 computeImplicitExceptionSpec(*this, Loc, MD); 4407 4408 // Update the type of the special member to use it. 4409 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4410 4411 // A user-provided destructor can be defined outside the class. When that 4412 // happens, be sure to update the exception specification on both 4413 // declarations. 4414 const FunctionProtoType *CanonicalFPT = 4415 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4416 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4417 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4418 CanonicalFPT, ExceptSpec); 4419} 4420 4421void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4422 CXXRecordDecl *RD = MD->getParent(); 4423 CXXSpecialMember CSM = getSpecialMember(MD); 4424 4425 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4426 "not an explicitly-defaulted special member"); 4427 4428 // Whether this was the first-declared instance of the constructor. 4429 // This affects whether we implicitly add an exception spec and constexpr. 4430 bool First = MD == MD->getCanonicalDecl(); 4431 4432 bool HadError = false; 4433 4434 // C++11 [dcl.fct.def.default]p1: 4435 // A function that is explicitly defaulted shall 4436 // -- be a special member function (checked elsewhere), 4437 // -- have the same type (except for ref-qualifiers, and except that a 4438 // copy operation can take a non-const reference) as an implicit 4439 // declaration, and 4440 // -- not have default arguments. 4441 unsigned ExpectedParams = 1; 4442 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4443 ExpectedParams = 0; 4444 if (MD->getNumParams() != ExpectedParams) { 4445 // This also checks for default arguments: a copy or move constructor with a 4446 // default argument is classified as a default constructor, and assignment 4447 // operations and destructors can't have default arguments. 4448 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4449 << CSM << MD->getSourceRange(); 4450 HadError = true; 4451 } else if (MD->isVariadic()) { 4452 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4453 << CSM << MD->getSourceRange(); 4454 HadError = true; 4455 } 4456 4457 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4458 4459 bool CanHaveConstParam = false; 4460 if (CSM == CXXCopyConstructor) 4461 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4462 else if (CSM == CXXCopyAssignment) 4463 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4464 4465 QualType ReturnType = Context.VoidTy; 4466 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4467 // Check for return type matching. 4468 ReturnType = Type->getResultType(); 4469 QualType ExpectedReturnType = 4470 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4471 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4472 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4473 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4474 HadError = true; 4475 } 4476 4477 // A defaulted special member cannot have cv-qualifiers. 4478 if (Type->getTypeQuals()) { 4479 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4480 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y; 4481 HadError = true; 4482 } 4483 } 4484 4485 // Check for parameter type matching. 4486 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType(); 4487 bool HasConstParam = false; 4488 if (ExpectedParams && ArgType->isReferenceType()) { 4489 // Argument must be reference to possibly-const T. 4490 QualType ReferentType = ArgType->getPointeeType(); 4491 HasConstParam = ReferentType.isConstQualified(); 4492 4493 if (ReferentType.isVolatileQualified()) { 4494 Diag(MD->getLocation(), 4495 diag::err_defaulted_special_member_volatile_param) << CSM; 4496 HadError = true; 4497 } 4498 4499 if (HasConstParam && !CanHaveConstParam) { 4500 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4501 Diag(MD->getLocation(), 4502 diag::err_defaulted_special_member_copy_const_param) 4503 << (CSM == CXXCopyAssignment); 4504 // FIXME: Explain why this special member can't be const. 4505 } else { 4506 Diag(MD->getLocation(), 4507 diag::err_defaulted_special_member_move_const_param) 4508 << (CSM == CXXMoveAssignment); 4509 } 4510 HadError = true; 4511 } 4512 } else if (ExpectedParams) { 4513 // A copy assignment operator can take its argument by value, but a 4514 // defaulted one cannot. 4515 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4516 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4517 HadError = true; 4518 } 4519 4520 // C++11 [dcl.fct.def.default]p2: 4521 // An explicitly-defaulted function may be declared constexpr only if it 4522 // would have been implicitly declared as constexpr, 4523 // Do not apply this rule to members of class templates, since core issue 1358 4524 // makes such functions always instantiate to constexpr functions. For 4525 // functions which cannot be constexpr (for non-constructors in C++11 and for 4526 // destructors in C++1y), this is checked elsewhere. 4527 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4528 HasConstParam); 4529 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD) 4530 : isa<CXXConstructorDecl>(MD)) && 4531 MD->isConstexpr() && !Constexpr && 4532 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4533 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4534 // FIXME: Explain why the special member can't be constexpr. 4535 HadError = true; 4536 } 4537 4538 // and may have an explicit exception-specification only if it is compatible 4539 // with the exception-specification on the implicit declaration. 4540 if (Type->hasExceptionSpec()) { 4541 // Delay the check if this is the first declaration of the special member, 4542 // since we may not have parsed some necessary in-class initializers yet. 4543 if (First) { 4544 // If the exception specification needs to be instantiated, do so now, 4545 // before we clobber it with an EST_Unevaluated specification below. 4546 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4547 InstantiateExceptionSpec(MD->getLocStart(), MD); 4548 Type = MD->getType()->getAs<FunctionProtoType>(); 4549 } 4550 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4551 } else 4552 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4553 } 4554 4555 // If a function is explicitly defaulted on its first declaration, 4556 if (First) { 4557 // -- it is implicitly considered to be constexpr if the implicit 4558 // definition would be, 4559 MD->setConstexpr(Constexpr); 4560 4561 // -- it is implicitly considered to have the same exception-specification 4562 // as if it had been implicitly declared, 4563 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4564 EPI.ExceptionSpecType = EST_Unevaluated; 4565 EPI.ExceptionSpecDecl = MD; 4566 MD->setType(Context.getFunctionType(ReturnType, 4567 ArrayRef<QualType>(&ArgType, 4568 ExpectedParams), 4569 EPI)); 4570 } 4571 4572 if (ShouldDeleteSpecialMember(MD, CSM)) { 4573 if (First) { 4574 SetDeclDeleted(MD, MD->getLocation()); 4575 } else { 4576 // C++11 [dcl.fct.def.default]p4: 4577 // [For a] user-provided explicitly-defaulted function [...] if such a 4578 // function is implicitly defined as deleted, the program is ill-formed. 4579 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4580 HadError = true; 4581 } 4582 } 4583 4584 if (HadError) 4585 MD->setInvalidDecl(); 4586} 4587 4588/// Check whether the exception specification provided for an 4589/// explicitly-defaulted special member matches the exception specification 4590/// that would have been generated for an implicit special member, per 4591/// C++11 [dcl.fct.def.default]p2. 4592void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 4593 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 4594 // Compute the implicit exception specification. 4595 FunctionProtoType::ExtProtoInfo EPI; 4596 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4597 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 4598 Context.getFunctionType(Context.VoidTy, None, EPI)); 4599 4600 // Ensure that it matches. 4601 CheckEquivalentExceptionSpec( 4602 PDiag(diag::err_incorrect_defaulted_exception_spec) 4603 << getSpecialMember(MD), PDiag(), 4604 ImplicitType, SourceLocation(), 4605 SpecifiedType, MD->getLocation()); 4606} 4607 4608void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() { 4609 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size(); 4610 I != N; ++I) 4611 CheckExplicitlyDefaultedMemberExceptionSpec( 4612 DelayedDefaultedMemberExceptionSpecs[I].first, 4613 DelayedDefaultedMemberExceptionSpecs[I].second); 4614 4615 DelayedDefaultedMemberExceptionSpecs.clear(); 4616} 4617 4618namespace { 4619struct SpecialMemberDeletionInfo { 4620 Sema &S; 4621 CXXMethodDecl *MD; 4622 Sema::CXXSpecialMember CSM; 4623 bool Diagnose; 4624 4625 // Properties of the special member, computed for convenience. 4626 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg; 4627 SourceLocation Loc; 4628 4629 bool AllFieldsAreConst; 4630 4631 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4632 Sema::CXXSpecialMember CSM, bool Diagnose) 4633 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4634 IsConstructor(false), IsAssignment(false), IsMove(false), 4635 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()), 4636 AllFieldsAreConst(true) { 4637 switch (CSM) { 4638 case Sema::CXXDefaultConstructor: 4639 case Sema::CXXCopyConstructor: 4640 IsConstructor = true; 4641 break; 4642 case Sema::CXXMoveConstructor: 4643 IsConstructor = true; 4644 IsMove = true; 4645 break; 4646 case Sema::CXXCopyAssignment: 4647 IsAssignment = true; 4648 break; 4649 case Sema::CXXMoveAssignment: 4650 IsAssignment = true; 4651 IsMove = true; 4652 break; 4653 case Sema::CXXDestructor: 4654 break; 4655 case Sema::CXXInvalid: 4656 llvm_unreachable("invalid special member kind"); 4657 } 4658 4659 if (MD->getNumParams()) { 4660 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4661 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified(); 4662 } 4663 } 4664 4665 bool inUnion() const { return MD->getParent()->isUnion(); } 4666 4667 /// Look up the corresponding special member in the given class. 4668 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4669 unsigned Quals) { 4670 unsigned TQ = MD->getTypeQualifiers(); 4671 // cv-qualifiers on class members don't affect default ctor / dtor calls. 4672 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4673 Quals = 0; 4674 return S.LookupSpecialMember(Class, CSM, 4675 ConstArg || (Quals & Qualifiers::Const), 4676 VolatileArg || (Quals & Qualifiers::Volatile), 4677 MD->getRefQualifier() == RQ_RValue, 4678 TQ & Qualifiers::Const, 4679 TQ & Qualifiers::Volatile); 4680 } 4681 4682 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4683 4684 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4685 bool shouldDeleteForField(FieldDecl *FD); 4686 bool shouldDeleteForAllConstMembers(); 4687 4688 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4689 unsigned Quals); 4690 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4691 Sema::SpecialMemberOverloadResult *SMOR, 4692 bool IsDtorCallInCtor); 4693 4694 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4695}; 4696} 4697 4698/// Is the given special member inaccessible when used on the given 4699/// sub-object. 4700bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4701 CXXMethodDecl *target) { 4702 /// If we're operating on a base class, the object type is the 4703 /// type of this special member. 4704 QualType objectTy; 4705 AccessSpecifier access = target->getAccess(); 4706 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 4707 objectTy = S.Context.getTypeDeclType(MD->getParent()); 4708 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 4709 4710 // If we're operating on a field, the object type is the type of the field. 4711 } else { 4712 objectTy = S.Context.getTypeDeclType(target->getParent()); 4713 } 4714 4715 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 4716} 4717 4718/// Check whether we should delete a special member due to the implicit 4719/// definition containing a call to a special member of a subobject. 4720bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 4721 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 4722 bool IsDtorCallInCtor) { 4723 CXXMethodDecl *Decl = SMOR->getMethod(); 4724 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4725 4726 int DiagKind = -1; 4727 4728 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 4729 DiagKind = !Decl ? 0 : 1; 4730 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4731 DiagKind = 2; 4732 else if (!isAccessible(Subobj, Decl)) 4733 DiagKind = 3; 4734 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 4735 !Decl->isTrivial()) { 4736 // A member of a union must have a trivial corresponding special member. 4737 // As a weird special case, a destructor call from a union's constructor 4738 // must be accessible and non-deleted, but need not be trivial. Such a 4739 // destructor is never actually called, but is semantically checked as 4740 // if it were. 4741 DiagKind = 4; 4742 } 4743 4744 if (DiagKind == -1) 4745 return false; 4746 4747 if (Diagnose) { 4748 if (Field) { 4749 S.Diag(Field->getLocation(), 4750 diag::note_deleted_special_member_class_subobject) 4751 << CSM << MD->getParent() << /*IsField*/true 4752 << Field << DiagKind << IsDtorCallInCtor; 4753 } else { 4754 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 4755 S.Diag(Base->getLocStart(), 4756 diag::note_deleted_special_member_class_subobject) 4757 << CSM << MD->getParent() << /*IsField*/false 4758 << Base->getType() << DiagKind << IsDtorCallInCtor; 4759 } 4760 4761 if (DiagKind == 1) 4762 S.NoteDeletedFunction(Decl); 4763 // FIXME: Explain inaccessibility if DiagKind == 3. 4764 } 4765 4766 return true; 4767} 4768 4769/// Check whether we should delete a special member function due to having a 4770/// direct or virtual base class or non-static data member of class type M. 4771bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 4772 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 4773 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4774 4775 // C++11 [class.ctor]p5: 4776 // -- any direct or virtual base class, or non-static data member with no 4777 // brace-or-equal-initializer, has class type M (or array thereof) and 4778 // either M has no default constructor or overload resolution as applied 4779 // to M's default constructor results in an ambiguity or in a function 4780 // that is deleted or inaccessible 4781 // C++11 [class.copy]p11, C++11 [class.copy]p23: 4782 // -- a direct or virtual base class B that cannot be copied/moved because 4783 // overload resolution, as applied to B's corresponding special member, 4784 // results in an ambiguity or a function that is deleted or inaccessible 4785 // from the defaulted special member 4786 // C++11 [class.dtor]p5: 4787 // -- any direct or virtual base class [...] has a type with a destructor 4788 // that is deleted or inaccessible 4789 if (!(CSM == Sema::CXXDefaultConstructor && 4790 Field && Field->hasInClassInitializer()) && 4791 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false)) 4792 return true; 4793 4794 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 4795 // -- any direct or virtual base class or non-static data member has a 4796 // type with a destructor that is deleted or inaccessible 4797 if (IsConstructor) { 4798 Sema::SpecialMemberOverloadResult *SMOR = 4799 S.LookupSpecialMember(Class, Sema::CXXDestructor, 4800 false, false, false, false, false); 4801 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 4802 return true; 4803 } 4804 4805 return false; 4806} 4807 4808/// Check whether we should delete a special member function due to the class 4809/// having a particular direct or virtual base class. 4810bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 4811 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 4812 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 4813} 4814 4815/// Check whether we should delete a special member function due to the class 4816/// having a particular non-static data member. 4817bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 4818 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 4819 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4820 4821 if (CSM == Sema::CXXDefaultConstructor) { 4822 // For a default constructor, all references must be initialized in-class 4823 // and, if a union, it must have a non-const member. 4824 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 4825 if (Diagnose) 4826 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4827 << MD->getParent() << FD << FieldType << /*Reference*/0; 4828 return true; 4829 } 4830 // C++11 [class.ctor]p5: any non-variant non-static data member of 4831 // const-qualified type (or array thereof) with no 4832 // brace-or-equal-initializer does not have a user-provided default 4833 // constructor. 4834 if (!inUnion() && FieldType.isConstQualified() && 4835 !FD->hasInClassInitializer() && 4836 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 4837 if (Diagnose) 4838 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4839 << MD->getParent() << FD << FD->getType() << /*Const*/1; 4840 return true; 4841 } 4842 4843 if (inUnion() && !FieldType.isConstQualified()) 4844 AllFieldsAreConst = false; 4845 } else if (CSM == Sema::CXXCopyConstructor) { 4846 // For a copy constructor, data members must not be of rvalue reference 4847 // type. 4848 if (FieldType->isRValueReferenceType()) { 4849 if (Diagnose) 4850 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 4851 << MD->getParent() << FD << FieldType; 4852 return true; 4853 } 4854 } else if (IsAssignment) { 4855 // For an assignment operator, data members must not be of reference type. 4856 if (FieldType->isReferenceType()) { 4857 if (Diagnose) 4858 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4859 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 4860 return true; 4861 } 4862 if (!FieldRecord && FieldType.isConstQualified()) { 4863 // C++11 [class.copy]p23: 4864 // -- a non-static data member of const non-class type (or array thereof) 4865 if (Diagnose) 4866 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4867 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 4868 return true; 4869 } 4870 } 4871 4872 if (FieldRecord) { 4873 // Some additional restrictions exist on the variant members. 4874 if (!inUnion() && FieldRecord->isUnion() && 4875 FieldRecord->isAnonymousStructOrUnion()) { 4876 bool AllVariantFieldsAreConst = true; 4877 4878 // FIXME: Handle anonymous unions declared within anonymous unions. 4879 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4880 UE = FieldRecord->field_end(); 4881 UI != UE; ++UI) { 4882 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 4883 4884 if (!UnionFieldType.isConstQualified()) 4885 AllVariantFieldsAreConst = false; 4886 4887 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 4888 if (UnionFieldRecord && 4889 shouldDeleteForClassSubobject(UnionFieldRecord, *UI, 4890 UnionFieldType.getCVRQualifiers())) 4891 return true; 4892 } 4893 4894 // At least one member in each anonymous union must be non-const 4895 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 4896 FieldRecord->field_begin() != FieldRecord->field_end()) { 4897 if (Diagnose) 4898 S.Diag(FieldRecord->getLocation(), 4899 diag::note_deleted_default_ctor_all_const) 4900 << MD->getParent() << /*anonymous union*/1; 4901 return true; 4902 } 4903 4904 // Don't check the implicit member of the anonymous union type. 4905 // This is technically non-conformant, but sanity demands it. 4906 return false; 4907 } 4908 4909 if (shouldDeleteForClassSubobject(FieldRecord, FD, 4910 FieldType.getCVRQualifiers())) 4911 return true; 4912 } 4913 4914 return false; 4915} 4916 4917/// C++11 [class.ctor] p5: 4918/// A defaulted default constructor for a class X is defined as deleted if 4919/// X is a union and all of its variant members are of const-qualified type. 4920bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 4921 // This is a silly definition, because it gives an empty union a deleted 4922 // default constructor. Don't do that. 4923 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 4924 (MD->getParent()->field_begin() != MD->getParent()->field_end())) { 4925 if (Diagnose) 4926 S.Diag(MD->getParent()->getLocation(), 4927 diag::note_deleted_default_ctor_all_const) 4928 << MD->getParent() << /*not anonymous union*/0; 4929 return true; 4930 } 4931 return false; 4932} 4933 4934/// Determine whether a defaulted special member function should be defined as 4935/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 4936/// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 4937bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 4938 bool Diagnose) { 4939 if (MD->isInvalidDecl()) 4940 return false; 4941 CXXRecordDecl *RD = MD->getParent(); 4942 assert(!RD->isDependentType() && "do deletion after instantiation"); 4943 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 4944 return false; 4945 4946 // C++11 [expr.lambda.prim]p19: 4947 // The closure type associated with a lambda-expression has a 4948 // deleted (8.4.3) default constructor and a deleted copy 4949 // assignment operator. 4950 if (RD->isLambda() && 4951 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 4952 if (Diagnose) 4953 Diag(RD->getLocation(), diag::note_lambda_decl); 4954 return true; 4955 } 4956 4957 // For an anonymous struct or union, the copy and assignment special members 4958 // will never be used, so skip the check. For an anonymous union declared at 4959 // namespace scope, the constructor and destructor are used. 4960 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 4961 RD->isAnonymousStructOrUnion()) 4962 return false; 4963 4964 // C++11 [class.copy]p7, p18: 4965 // If the class definition declares a move constructor or move assignment 4966 // operator, an implicitly declared copy constructor or copy assignment 4967 // operator is defined as deleted. 4968 if (MD->isImplicit() && 4969 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 4970 CXXMethodDecl *UserDeclaredMove = 0; 4971 4972 // In Microsoft mode, a user-declared move only causes the deletion of the 4973 // corresponding copy operation, not both copy operations. 4974 if (RD->hasUserDeclaredMoveConstructor() && 4975 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) { 4976 if (!Diagnose) return true; 4977 4978 // Find any user-declared move constructor. 4979 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 4980 E = RD->ctor_end(); I != E; ++I) { 4981 if (I->isMoveConstructor()) { 4982 UserDeclaredMove = *I; 4983 break; 4984 } 4985 } 4986 assert(UserDeclaredMove); 4987 } else if (RD->hasUserDeclaredMoveAssignment() && 4988 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) { 4989 if (!Diagnose) return true; 4990 4991 // Find any user-declared move assignment operator. 4992 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 4993 E = RD->method_end(); I != E; ++I) { 4994 if (I->isMoveAssignmentOperator()) { 4995 UserDeclaredMove = *I; 4996 break; 4997 } 4998 } 4999 assert(UserDeclaredMove); 5000 } 5001 5002 if (UserDeclaredMove) { 5003 Diag(UserDeclaredMove->getLocation(), 5004 diag::note_deleted_copy_user_declared_move) 5005 << (CSM == CXXCopyAssignment) << RD 5006 << UserDeclaredMove->isMoveAssignmentOperator(); 5007 return true; 5008 } 5009 } 5010 5011 // Do access control from the special member function 5012 ContextRAII MethodContext(*this, MD); 5013 5014 // C++11 [class.dtor]p5: 5015 // -- for a virtual destructor, lookup of the non-array deallocation function 5016 // results in an ambiguity or in a function that is deleted or inaccessible 5017 if (CSM == CXXDestructor && MD->isVirtual()) { 5018 FunctionDecl *OperatorDelete = 0; 5019 DeclarationName Name = 5020 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5021 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5022 OperatorDelete, false)) { 5023 if (Diagnose) 5024 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5025 return true; 5026 } 5027 } 5028 5029 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5030 5031 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5032 BE = RD->bases_end(); BI != BE; ++BI) 5033 if (!BI->isVirtual() && 5034 SMI.shouldDeleteForBase(BI)) 5035 return true; 5036 5037 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 5038 BE = RD->vbases_end(); BI != BE; ++BI) 5039 if (SMI.shouldDeleteForBase(BI)) 5040 return true; 5041 5042 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5043 FE = RD->field_end(); FI != FE; ++FI) 5044 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5045 SMI.shouldDeleteForField(*FI)) 5046 return true; 5047 5048 if (SMI.shouldDeleteForAllConstMembers()) 5049 return true; 5050 5051 return false; 5052} 5053 5054/// Perform lookup for a special member of the specified kind, and determine 5055/// whether it is trivial. If the triviality can be determined without the 5056/// lookup, skip it. This is intended for use when determining whether a 5057/// special member of a containing object is trivial, and thus does not ever 5058/// perform overload resolution for default constructors. 5059/// 5060/// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5061/// member that was most likely to be intended to be trivial, if any. 5062static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5063 Sema::CXXSpecialMember CSM, unsigned Quals, 5064 CXXMethodDecl **Selected) { 5065 if (Selected) 5066 *Selected = 0; 5067 5068 switch (CSM) { 5069 case Sema::CXXInvalid: 5070 llvm_unreachable("not a special member"); 5071 5072 case Sema::CXXDefaultConstructor: 5073 // C++11 [class.ctor]p5: 5074 // A default constructor is trivial if: 5075 // - all the [direct subobjects] have trivial default constructors 5076 // 5077 // Note, no overload resolution is performed in this case. 5078 if (RD->hasTrivialDefaultConstructor()) 5079 return true; 5080 5081 if (Selected) { 5082 // If there's a default constructor which could have been trivial, dig it 5083 // out. Otherwise, if there's any user-provided default constructor, point 5084 // to that as an example of why there's not a trivial one. 5085 CXXConstructorDecl *DefCtor = 0; 5086 if (RD->needsImplicitDefaultConstructor()) 5087 S.DeclareImplicitDefaultConstructor(RD); 5088 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), 5089 CE = RD->ctor_end(); CI != CE; ++CI) { 5090 if (!CI->isDefaultConstructor()) 5091 continue; 5092 DefCtor = *CI; 5093 if (!DefCtor->isUserProvided()) 5094 break; 5095 } 5096 5097 *Selected = DefCtor; 5098 } 5099 5100 return false; 5101 5102 case Sema::CXXDestructor: 5103 // C++11 [class.dtor]p5: 5104 // A destructor is trivial if: 5105 // - all the direct [subobjects] have trivial destructors 5106 if (RD->hasTrivialDestructor()) 5107 return true; 5108 5109 if (Selected) { 5110 if (RD->needsImplicitDestructor()) 5111 S.DeclareImplicitDestructor(RD); 5112 *Selected = RD->getDestructor(); 5113 } 5114 5115 return false; 5116 5117 case Sema::CXXCopyConstructor: 5118 // C++11 [class.copy]p12: 5119 // A copy constructor is trivial if: 5120 // - the constructor selected to copy each direct [subobject] is trivial 5121 if (RD->hasTrivialCopyConstructor()) { 5122 if (Quals == Qualifiers::Const) 5123 // We must either select the trivial copy constructor or reach an 5124 // ambiguity; no need to actually perform overload resolution. 5125 return true; 5126 } else if (!Selected) { 5127 return false; 5128 } 5129 // In C++98, we are not supposed to perform overload resolution here, but we 5130 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5131 // cases like B as having a non-trivial copy constructor: 5132 // struct A { template<typename T> A(T&); }; 5133 // struct B { mutable A a; }; 5134 goto NeedOverloadResolution; 5135 5136 case Sema::CXXCopyAssignment: 5137 // C++11 [class.copy]p25: 5138 // A copy assignment operator is trivial if: 5139 // - the assignment operator selected to copy each direct [subobject] is 5140 // trivial 5141 if (RD->hasTrivialCopyAssignment()) { 5142 if (Quals == Qualifiers::Const) 5143 return true; 5144 } else if (!Selected) { 5145 return false; 5146 } 5147 // In C++98, we are not supposed to perform overload resolution here, but we 5148 // treat that as a language defect. 5149 goto NeedOverloadResolution; 5150 5151 case Sema::CXXMoveConstructor: 5152 case Sema::CXXMoveAssignment: 5153 NeedOverloadResolution: 5154 Sema::SpecialMemberOverloadResult *SMOR = 5155 S.LookupSpecialMember(RD, CSM, 5156 Quals & Qualifiers::Const, 5157 Quals & Qualifiers::Volatile, 5158 /*RValueThis*/false, /*ConstThis*/false, 5159 /*VolatileThis*/false); 5160 5161 // The standard doesn't describe how to behave if the lookup is ambiguous. 5162 // We treat it as not making the member non-trivial, just like the standard 5163 // mandates for the default constructor. This should rarely matter, because 5164 // the member will also be deleted. 5165 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5166 return true; 5167 5168 if (!SMOR->getMethod()) { 5169 assert(SMOR->getKind() == 5170 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5171 return false; 5172 } 5173 5174 // We deliberately don't check if we found a deleted special member. We're 5175 // not supposed to! 5176 if (Selected) 5177 *Selected = SMOR->getMethod(); 5178 return SMOR->getMethod()->isTrivial(); 5179 } 5180 5181 llvm_unreachable("unknown special method kind"); 5182} 5183 5184static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5185 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end(); 5186 CI != CE; ++CI) 5187 if (!CI->isImplicit()) 5188 return *CI; 5189 5190 // Look for constructor templates. 5191 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5192 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5193 if (CXXConstructorDecl *CD = 5194 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5195 return CD; 5196 } 5197 5198 return 0; 5199} 5200 5201/// The kind of subobject we are checking for triviality. The values of this 5202/// enumeration are used in diagnostics. 5203enum TrivialSubobjectKind { 5204 /// The subobject is a base class. 5205 TSK_BaseClass, 5206 /// The subobject is a non-static data member. 5207 TSK_Field, 5208 /// The object is actually the complete object. 5209 TSK_CompleteObject 5210}; 5211 5212/// Check whether the special member selected for a given type would be trivial. 5213static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5214 QualType SubType, 5215 Sema::CXXSpecialMember CSM, 5216 TrivialSubobjectKind Kind, 5217 bool Diagnose) { 5218 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5219 if (!SubRD) 5220 return true; 5221 5222 CXXMethodDecl *Selected; 5223 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5224 Diagnose ? &Selected : 0)) 5225 return true; 5226 5227 if (Diagnose) { 5228 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5229 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5230 << Kind << SubType.getUnqualifiedType(); 5231 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5232 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5233 } else if (!Selected) 5234 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5235 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5236 else if (Selected->isUserProvided()) { 5237 if (Kind == TSK_CompleteObject) 5238 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5239 << Kind << SubType.getUnqualifiedType() << CSM; 5240 else { 5241 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5242 << Kind << SubType.getUnqualifiedType() << CSM; 5243 S.Diag(Selected->getLocation(), diag::note_declared_at); 5244 } 5245 } else { 5246 if (Kind != TSK_CompleteObject) 5247 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5248 << Kind << SubType.getUnqualifiedType() << CSM; 5249 5250 // Explain why the defaulted or deleted special member isn't trivial. 5251 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5252 } 5253 } 5254 5255 return false; 5256} 5257 5258/// Check whether the members of a class type allow a special member to be 5259/// trivial. 5260static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5261 Sema::CXXSpecialMember CSM, 5262 bool ConstArg, bool Diagnose) { 5263 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5264 FE = RD->field_end(); FI != FE; ++FI) { 5265 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5266 continue; 5267 5268 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5269 5270 // Pretend anonymous struct or union members are members of this class. 5271 if (FI->isAnonymousStructOrUnion()) { 5272 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5273 CSM, ConstArg, Diagnose)) 5274 return false; 5275 continue; 5276 } 5277 5278 // C++11 [class.ctor]p5: 5279 // A default constructor is trivial if [...] 5280 // -- no non-static data member of its class has a 5281 // brace-or-equal-initializer 5282 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5283 if (Diagnose) 5284 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI; 5285 return false; 5286 } 5287 5288 // Objective C ARC 4.3.5: 5289 // [...] nontrivally ownership-qualified types are [...] not trivially 5290 // default constructible, copy constructible, move constructible, copy 5291 // assignable, move assignable, or destructible [...] 5292 if (S.getLangOpts().ObjCAutoRefCount && 5293 FieldType.hasNonTrivialObjCLifetime()) { 5294 if (Diagnose) 5295 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5296 << RD << FieldType.getObjCLifetime(); 5297 return false; 5298 } 5299 5300 if (ConstArg && !FI->isMutable()) 5301 FieldType.addConst(); 5302 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM, 5303 TSK_Field, Diagnose)) 5304 return false; 5305 } 5306 5307 return true; 5308} 5309 5310/// Diagnose why the specified class does not have a trivial special member of 5311/// the given kind. 5312void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5313 QualType Ty = Context.getRecordType(RD); 5314 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) 5315 Ty.addConst(); 5316 5317 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM, 5318 TSK_CompleteObject, /*Diagnose*/true); 5319} 5320 5321/// Determine whether a defaulted or deleted special member function is trivial, 5322/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5323/// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5324bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5325 bool Diagnose) { 5326 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5327 5328 CXXRecordDecl *RD = MD->getParent(); 5329 5330 bool ConstArg = false; 5331 5332 // C++11 [class.copy]p12, p25: 5333 // A [special member] is trivial if its declared parameter type is the same 5334 // as if it had been implicitly declared [...] 5335 switch (CSM) { 5336 case CXXDefaultConstructor: 5337 case CXXDestructor: 5338 // Trivial default constructors and destructors cannot have parameters. 5339 break; 5340 5341 case CXXCopyConstructor: 5342 case CXXCopyAssignment: { 5343 // Trivial copy operations always have const, non-volatile parameter types. 5344 ConstArg = true; 5345 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5346 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5347 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5348 if (Diagnose) 5349 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5350 << Param0->getSourceRange() << Param0->getType() 5351 << Context.getLValueReferenceType( 5352 Context.getRecordType(RD).withConst()); 5353 return false; 5354 } 5355 break; 5356 } 5357 5358 case CXXMoveConstructor: 5359 case CXXMoveAssignment: { 5360 // Trivial move operations always have non-cv-qualified parameters. 5361 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5362 const RValueReferenceType *RT = 5363 Param0->getType()->getAs<RValueReferenceType>(); 5364 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5365 if (Diagnose) 5366 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5367 << Param0->getSourceRange() << Param0->getType() 5368 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5369 return false; 5370 } 5371 break; 5372 } 5373 5374 case CXXInvalid: 5375 llvm_unreachable("not a special member"); 5376 } 5377 5378 // FIXME: We require that the parameter-declaration-clause is equivalent to 5379 // that of an implicit declaration, not just that the declared parameter type 5380 // matches, in order to prevent absuridities like a function simultaneously 5381 // being a trivial copy constructor and a non-trivial default constructor. 5382 // This issue has not yet been assigned a core issue number. 5383 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5384 if (Diagnose) 5385 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5386 diag::note_nontrivial_default_arg) 5387 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5388 return false; 5389 } 5390 if (MD->isVariadic()) { 5391 if (Diagnose) 5392 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5393 return false; 5394 } 5395 5396 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5397 // A copy/move [constructor or assignment operator] is trivial if 5398 // -- the [member] selected to copy/move each direct base class subobject 5399 // is trivial 5400 // 5401 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5402 // A [default constructor or destructor] is trivial if 5403 // -- all the direct base classes have trivial [default constructors or 5404 // destructors] 5405 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5406 BE = RD->bases_end(); BI != BE; ++BI) 5407 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), 5408 ConstArg ? BI->getType().withConst() 5409 : BI->getType(), 5410 CSM, TSK_BaseClass, Diagnose)) 5411 return false; 5412 5413 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5414 // A copy/move [constructor or assignment operator] for a class X is 5415 // trivial if 5416 // -- for each non-static data member of X that is of class type (or array 5417 // thereof), the constructor selected to copy/move that member is 5418 // trivial 5419 // 5420 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5421 // A [default constructor or destructor] is trivial if 5422 // -- for all of the non-static data members of its class that are of class 5423 // type (or array thereof), each such class has a trivial [default 5424 // constructor or destructor] 5425 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5426 return false; 5427 5428 // C++11 [class.dtor]p5: 5429 // A destructor is trivial if [...] 5430 // -- the destructor is not virtual 5431 if (CSM == CXXDestructor && MD->isVirtual()) { 5432 if (Diagnose) 5433 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5434 return false; 5435 } 5436 5437 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5438 // A [special member] for class X is trivial if [...] 5439 // -- class X has no virtual functions and no virtual base classes 5440 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5441 if (!Diagnose) 5442 return false; 5443 5444 if (RD->getNumVBases()) { 5445 // Check for virtual bases. We already know that the corresponding 5446 // member in all bases is trivial, so vbases must all be direct. 5447 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5448 assert(BS.isVirtual()); 5449 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5450 return false; 5451 } 5452 5453 // Must have a virtual method. 5454 for (CXXRecordDecl::method_iterator MI = RD->method_begin(), 5455 ME = RD->method_end(); MI != ME; ++MI) { 5456 if (MI->isVirtual()) { 5457 SourceLocation MLoc = MI->getLocStart(); 5458 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5459 return false; 5460 } 5461 } 5462 5463 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5464 } 5465 5466 // Looks like it's trivial! 5467 return true; 5468} 5469 5470/// \brief Data used with FindHiddenVirtualMethod 5471namespace { 5472 struct FindHiddenVirtualMethodData { 5473 Sema *S; 5474 CXXMethodDecl *Method; 5475 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5476 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5477 }; 5478} 5479 5480/// \brief Check whether any most overriden method from MD in Methods 5481static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5482 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5483 if (MD->size_overridden_methods() == 0) 5484 return Methods.count(MD->getCanonicalDecl()); 5485 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5486 E = MD->end_overridden_methods(); 5487 I != E; ++I) 5488 if (CheckMostOverridenMethods(*I, Methods)) 5489 return true; 5490 return false; 5491} 5492 5493/// \brief Member lookup function that determines whether a given C++ 5494/// method overloads virtual methods in a base class without overriding any, 5495/// to be used with CXXRecordDecl::lookupInBases(). 5496static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5497 CXXBasePath &Path, 5498 void *UserData) { 5499 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5500 5501 FindHiddenVirtualMethodData &Data 5502 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5503 5504 DeclarationName Name = Data.Method->getDeclName(); 5505 assert(Name.getNameKind() == DeclarationName::Identifier); 5506 5507 bool foundSameNameMethod = false; 5508 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5509 for (Path.Decls = BaseRecord->lookup(Name); 5510 !Path.Decls.empty(); 5511 Path.Decls = Path.Decls.slice(1)) { 5512 NamedDecl *D = Path.Decls.front(); 5513 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5514 MD = MD->getCanonicalDecl(); 5515 foundSameNameMethod = true; 5516 // Interested only in hidden virtual methods. 5517 if (!MD->isVirtual()) 5518 continue; 5519 // If the method we are checking overrides a method from its base 5520 // don't warn about the other overloaded methods. 5521 if (!Data.S->IsOverload(Data.Method, MD, false)) 5522 return true; 5523 // Collect the overload only if its hidden. 5524 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5525 overloadedMethods.push_back(MD); 5526 } 5527 } 5528 5529 if (foundSameNameMethod) 5530 Data.OverloadedMethods.append(overloadedMethods.begin(), 5531 overloadedMethods.end()); 5532 return foundSameNameMethod; 5533} 5534 5535/// \brief Add the most overriden methods from MD to Methods 5536static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5537 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5538 if (MD->size_overridden_methods() == 0) 5539 Methods.insert(MD->getCanonicalDecl()); 5540 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5541 E = MD->end_overridden_methods(); 5542 I != E; ++I) 5543 AddMostOverridenMethods(*I, Methods); 5544} 5545 5546/// \brief See if a method overloads virtual methods in a base class without 5547/// overriding any. 5548void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 5549 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5550 MD->getLocation()) == DiagnosticsEngine::Ignored) 5551 return; 5552 if (!MD->getDeclName().isIdentifier()) 5553 return; 5554 5555 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5556 /*bool RecordPaths=*/false, 5557 /*bool DetectVirtual=*/false); 5558 FindHiddenVirtualMethodData Data; 5559 Data.Method = MD; 5560 Data.S = this; 5561 5562 // Keep the base methods that were overriden or introduced in the subclass 5563 // by 'using' in a set. A base method not in this set is hidden. 5564 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5565 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5566 NamedDecl *ND = *I; 5567 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5568 ND = shad->getTargetDecl(); 5569 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5570 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5571 } 5572 5573 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 5574 !Data.OverloadedMethods.empty()) { 5575 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5576 << MD << (Data.OverloadedMethods.size() > 1); 5577 5578 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 5579 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 5580 PartialDiagnostic PD = PDiag( 5581 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5582 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 5583 Diag(overloadedMD->getLocation(), PD); 5584 } 5585 } 5586} 5587 5588void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5589 Decl *TagDecl, 5590 SourceLocation LBrac, 5591 SourceLocation RBrac, 5592 AttributeList *AttrList) { 5593 if (!TagDecl) 5594 return; 5595 5596 AdjustDeclIfTemplate(TagDecl); 5597 5598 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5599 if (l->getKind() != AttributeList::AT_Visibility) 5600 continue; 5601 l->setInvalid(); 5602 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5603 l->getName(); 5604 } 5605 5606 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5607 // strict aliasing violation! 5608 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5609 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5610 5611 CheckCompletedCXXClass( 5612 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5613} 5614 5615/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5616/// special functions, such as the default constructor, copy 5617/// constructor, or destructor, to the given C++ class (C++ 5618/// [special]p1). This routine can only be executed just before the 5619/// definition of the class is complete. 5620void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5621 if (!ClassDecl->hasUserDeclaredConstructor()) 5622 ++ASTContext::NumImplicitDefaultConstructors; 5623 5624 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 5625 ++ASTContext::NumImplicitCopyConstructors; 5626 5627 // If the properties or semantics of the copy constructor couldn't be 5628 // determined while the class was being declared, force a declaration 5629 // of it now. 5630 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 5631 DeclareImplicitCopyConstructor(ClassDecl); 5632 } 5633 5634 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 5635 ++ASTContext::NumImplicitMoveConstructors; 5636 5637 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 5638 DeclareImplicitMoveConstructor(ClassDecl); 5639 } 5640 5641 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5642 ++ASTContext::NumImplicitCopyAssignmentOperators; 5643 5644 // If we have a dynamic class, then the copy assignment operator may be 5645 // virtual, so we have to declare it immediately. This ensures that, e.g., 5646 // it shows up in the right place in the vtable and that we diagnose 5647 // problems with the implicit exception specification. 5648 if (ClassDecl->isDynamicClass() || 5649 ClassDecl->needsOverloadResolutionForCopyAssignment()) 5650 DeclareImplicitCopyAssignment(ClassDecl); 5651 } 5652 5653 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 5654 ++ASTContext::NumImplicitMoveAssignmentOperators; 5655 5656 // Likewise for the move assignment operator. 5657 if (ClassDecl->isDynamicClass() || 5658 ClassDecl->needsOverloadResolutionForMoveAssignment()) 5659 DeclareImplicitMoveAssignment(ClassDecl); 5660 } 5661 5662 if (!ClassDecl->hasUserDeclaredDestructor()) { 5663 ++ASTContext::NumImplicitDestructors; 5664 5665 // If we have a dynamic class, then the destructor may be virtual, so we 5666 // have to declare the destructor immediately. This ensures that, e.g., it 5667 // shows up in the right place in the vtable and that we diagnose problems 5668 // with the implicit exception specification. 5669 if (ClassDecl->isDynamicClass() || 5670 ClassDecl->needsOverloadResolutionForDestructor()) 5671 DeclareImplicitDestructor(ClassDecl); 5672 } 5673} 5674 5675void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5676 if (!D) 5677 return; 5678 5679 int NumParamList = D->getNumTemplateParameterLists(); 5680 for (int i = 0; i < NumParamList; i++) { 5681 TemplateParameterList* Params = D->getTemplateParameterList(i); 5682 for (TemplateParameterList::iterator Param = Params->begin(), 5683 ParamEnd = Params->end(); 5684 Param != ParamEnd; ++Param) { 5685 NamedDecl *Named = cast<NamedDecl>(*Param); 5686 if (Named->getDeclName()) { 5687 S->AddDecl(Named); 5688 IdResolver.AddDecl(Named); 5689 } 5690 } 5691 } 5692} 5693 5694void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 5695 if (!D) 5696 return; 5697 5698 TemplateParameterList *Params = 0; 5699 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 5700 Params = Template->getTemplateParameters(); 5701 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5702 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 5703 Params = PartialSpec->getTemplateParameters(); 5704 else 5705 return; 5706 5707 for (TemplateParameterList::iterator Param = Params->begin(), 5708 ParamEnd = Params->end(); 5709 Param != ParamEnd; ++Param) { 5710 NamedDecl *Named = cast<NamedDecl>(*Param); 5711 if (Named->getDeclName()) { 5712 S->AddDecl(Named); 5713 IdResolver.AddDecl(Named); 5714 } 5715 } 5716} 5717 5718void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5719 if (!RecordD) return; 5720 AdjustDeclIfTemplate(RecordD); 5721 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 5722 PushDeclContext(S, Record); 5723} 5724 5725void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5726 if (!RecordD) return; 5727 PopDeclContext(); 5728} 5729 5730/// ActOnStartDelayedCXXMethodDeclaration - We have completed 5731/// parsing a top-level (non-nested) C++ class, and we are now 5732/// parsing those parts of the given Method declaration that could 5733/// not be parsed earlier (C++ [class.mem]p2), such as default 5734/// arguments. This action should enter the scope of the given 5735/// Method declaration as if we had just parsed the qualified method 5736/// name. However, it should not bring the parameters into scope; 5737/// that will be performed by ActOnDelayedCXXMethodParameter. 5738void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5739} 5740 5741/// ActOnDelayedCXXMethodParameter - We've already started a delayed 5742/// C++ method declaration. We're (re-)introducing the given 5743/// function parameter into scope for use in parsing later parts of 5744/// the method declaration. For example, we could see an 5745/// ActOnParamDefaultArgument event for this parameter. 5746void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 5747 if (!ParamD) 5748 return; 5749 5750 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 5751 5752 // If this parameter has an unparsed default argument, clear it out 5753 // to make way for the parsed default argument. 5754 if (Param->hasUnparsedDefaultArg()) 5755 Param->setDefaultArg(0); 5756 5757 S->AddDecl(Param); 5758 if (Param->getDeclName()) 5759 IdResolver.AddDecl(Param); 5760} 5761 5762/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 5763/// processing the delayed method declaration for Method. The method 5764/// declaration is now considered finished. There may be a separate 5765/// ActOnStartOfFunctionDef action later (not necessarily 5766/// immediately!) for this method, if it was also defined inside the 5767/// class body. 5768void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5769 if (!MethodD) 5770 return; 5771 5772 AdjustDeclIfTemplate(MethodD); 5773 5774 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 5775 5776 // Now that we have our default arguments, check the constructor 5777 // again. It could produce additional diagnostics or affect whether 5778 // the class has implicitly-declared destructors, among other 5779 // things. 5780 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 5781 CheckConstructor(Constructor); 5782 5783 // Check the default arguments, which we may have added. 5784 if (!Method->isInvalidDecl()) 5785 CheckCXXDefaultArguments(Method); 5786} 5787 5788/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 5789/// the well-formedness of the constructor declarator @p D with type @p 5790/// R. If there are any errors in the declarator, this routine will 5791/// emit diagnostics and set the invalid bit to true. In any case, the type 5792/// will be updated to reflect a well-formed type for the constructor and 5793/// returned. 5794QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 5795 StorageClass &SC) { 5796 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 5797 5798 // C++ [class.ctor]p3: 5799 // A constructor shall not be virtual (10.3) or static (9.4). A 5800 // constructor can be invoked for a const, volatile or const 5801 // volatile object. A constructor shall not be declared const, 5802 // volatile, or const volatile (9.3.2). 5803 if (isVirtual) { 5804 if (!D.isInvalidType()) 5805 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5806 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 5807 << SourceRange(D.getIdentifierLoc()); 5808 D.setInvalidType(); 5809 } 5810 if (SC == SC_Static) { 5811 if (!D.isInvalidType()) 5812 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 5813 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5814 << SourceRange(D.getIdentifierLoc()); 5815 D.setInvalidType(); 5816 SC = SC_None; 5817 } 5818 5819 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5820 if (FTI.TypeQuals != 0) { 5821 if (FTI.TypeQuals & Qualifiers::Const) 5822 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5823 << "const" << SourceRange(D.getIdentifierLoc()); 5824 if (FTI.TypeQuals & Qualifiers::Volatile) 5825 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5826 << "volatile" << SourceRange(D.getIdentifierLoc()); 5827 if (FTI.TypeQuals & Qualifiers::Restrict) 5828 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 5829 << "restrict" << SourceRange(D.getIdentifierLoc()); 5830 D.setInvalidType(); 5831 } 5832 5833 // C++0x [class.ctor]p4: 5834 // A constructor shall not be declared with a ref-qualifier. 5835 if (FTI.hasRefQualifier()) { 5836 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 5837 << FTI.RefQualifierIsLValueRef 5838 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5839 D.setInvalidType(); 5840 } 5841 5842 // Rebuild the function type "R" without any type qualifiers (in 5843 // case any of the errors above fired) and with "void" as the 5844 // return type, since constructors don't have return types. 5845 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5846 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 5847 return R; 5848 5849 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5850 EPI.TypeQuals = 0; 5851 EPI.RefQualifier = RQ_None; 5852 5853 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI); 5854} 5855 5856/// CheckConstructor - Checks a fully-formed constructor for 5857/// well-formedness, issuing any diagnostics required. Returns true if 5858/// the constructor declarator is invalid. 5859void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 5860 CXXRecordDecl *ClassDecl 5861 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 5862 if (!ClassDecl) 5863 return Constructor->setInvalidDecl(); 5864 5865 // C++ [class.copy]p3: 5866 // A declaration of a constructor for a class X is ill-formed if 5867 // its first parameter is of type (optionally cv-qualified) X and 5868 // either there are no other parameters or else all other 5869 // parameters have default arguments. 5870 if (!Constructor->isInvalidDecl() && 5871 ((Constructor->getNumParams() == 1) || 5872 (Constructor->getNumParams() > 1 && 5873 Constructor->getParamDecl(1)->hasDefaultArg())) && 5874 Constructor->getTemplateSpecializationKind() 5875 != TSK_ImplicitInstantiation) { 5876 QualType ParamType = Constructor->getParamDecl(0)->getType(); 5877 QualType ClassTy = Context.getTagDeclType(ClassDecl); 5878 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 5879 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 5880 const char *ConstRef 5881 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 5882 : " const &"; 5883 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 5884 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 5885 5886 // FIXME: Rather that making the constructor invalid, we should endeavor 5887 // to fix the type. 5888 Constructor->setInvalidDecl(); 5889 } 5890 } 5891} 5892 5893/// CheckDestructor - Checks a fully-formed destructor definition for 5894/// well-formedness, issuing any diagnostics required. Returns true 5895/// on error. 5896bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 5897 CXXRecordDecl *RD = Destructor->getParent(); 5898 5899 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 5900 SourceLocation Loc; 5901 5902 if (!Destructor->isImplicit()) 5903 Loc = Destructor->getLocation(); 5904 else 5905 Loc = RD->getLocation(); 5906 5907 // If we have a virtual destructor, look up the deallocation function 5908 FunctionDecl *OperatorDelete = 0; 5909 DeclarationName Name = 5910 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5911 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 5912 return true; 5913 5914 MarkFunctionReferenced(Loc, OperatorDelete); 5915 5916 Destructor->setOperatorDelete(OperatorDelete); 5917 } 5918 5919 return false; 5920} 5921 5922static inline bool 5923FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 5924 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5925 FTI.ArgInfo[0].Param && 5926 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 5927} 5928 5929/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 5930/// the well-formednes of the destructor declarator @p D with type @p 5931/// R. If there are any errors in the declarator, this routine will 5932/// emit diagnostics and set the declarator to invalid. Even if this happens, 5933/// will be updated to reflect a well-formed type for the destructor and 5934/// returned. 5935QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 5936 StorageClass& SC) { 5937 // C++ [class.dtor]p1: 5938 // [...] A typedef-name that names a class is a class-name 5939 // (7.1.3); however, a typedef-name that names a class shall not 5940 // be used as the identifier in the declarator for a destructor 5941 // declaration. 5942 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 5943 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 5944 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5945 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 5946 else if (const TemplateSpecializationType *TST = 5947 DeclaratorType->getAs<TemplateSpecializationType>()) 5948 if (TST->isTypeAlias()) 5949 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5950 << DeclaratorType << 1; 5951 5952 // C++ [class.dtor]p2: 5953 // A destructor is used to destroy objects of its class type. A 5954 // destructor takes no parameters, and no return type can be 5955 // specified for it (not even void). The address of a destructor 5956 // shall not be taken. A destructor shall not be static. A 5957 // destructor can be invoked for a const, volatile or const 5958 // volatile object. A destructor shall not be declared const, 5959 // volatile or const volatile (9.3.2). 5960 if (SC == SC_Static) { 5961 if (!D.isInvalidType()) 5962 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 5963 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5964 << SourceRange(D.getIdentifierLoc()) 5965 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5966 5967 SC = SC_None; 5968 } 5969 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5970 // Destructors don't have return types, but the parser will 5971 // happily parse something like: 5972 // 5973 // class X { 5974 // float ~X(); 5975 // }; 5976 // 5977 // The return type will be eliminated later. 5978 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 5979 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5980 << SourceRange(D.getIdentifierLoc()); 5981 } 5982 5983 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5984 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 5985 if (FTI.TypeQuals & Qualifiers::Const) 5986 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5987 << "const" << SourceRange(D.getIdentifierLoc()); 5988 if (FTI.TypeQuals & Qualifiers::Volatile) 5989 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5990 << "volatile" << SourceRange(D.getIdentifierLoc()); 5991 if (FTI.TypeQuals & Qualifiers::Restrict) 5992 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5993 << "restrict" << SourceRange(D.getIdentifierLoc()); 5994 D.setInvalidType(); 5995 } 5996 5997 // C++0x [class.dtor]p2: 5998 // A destructor shall not be declared with a ref-qualifier. 5999 if (FTI.hasRefQualifier()) { 6000 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6001 << FTI.RefQualifierIsLValueRef 6002 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6003 D.setInvalidType(); 6004 } 6005 6006 // Make sure we don't have any parameters. 6007 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 6008 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6009 6010 // Delete the parameters. 6011 FTI.freeArgs(); 6012 D.setInvalidType(); 6013 } 6014 6015 // Make sure the destructor isn't variadic. 6016 if (FTI.isVariadic) { 6017 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6018 D.setInvalidType(); 6019 } 6020 6021 // Rebuild the function type "R" without any type qualifiers or 6022 // parameters (in case any of the errors above fired) and with 6023 // "void" as the return type, since destructors don't have return 6024 // types. 6025 if (!D.isInvalidType()) 6026 return R; 6027 6028 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6029 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6030 EPI.Variadic = false; 6031 EPI.TypeQuals = 0; 6032 EPI.RefQualifier = RQ_None; 6033 return Context.getFunctionType(Context.VoidTy, None, EPI); 6034} 6035 6036/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6037/// well-formednes of the conversion function declarator @p D with 6038/// type @p R. If there are any errors in the declarator, this routine 6039/// will emit diagnostics and return true. Otherwise, it will return 6040/// false. Either way, the type @p R will be updated to reflect a 6041/// well-formed type for the conversion operator. 6042void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6043 StorageClass& SC) { 6044 // C++ [class.conv.fct]p1: 6045 // Neither parameter types nor return type can be specified. The 6046 // type of a conversion function (8.3.5) is "function taking no 6047 // parameter returning conversion-type-id." 6048 if (SC == SC_Static) { 6049 if (!D.isInvalidType()) 6050 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6051 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6052 << SourceRange(D.getIdentifierLoc()); 6053 D.setInvalidType(); 6054 SC = SC_None; 6055 } 6056 6057 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6058 6059 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6060 // Conversion functions don't have return types, but the parser will 6061 // happily parse something like: 6062 // 6063 // class X { 6064 // float operator bool(); 6065 // }; 6066 // 6067 // The return type will be changed later anyway. 6068 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6069 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6070 << SourceRange(D.getIdentifierLoc()); 6071 D.setInvalidType(); 6072 } 6073 6074 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6075 6076 // Make sure we don't have any parameters. 6077 if (Proto->getNumArgs() > 0) { 6078 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6079 6080 // Delete the parameters. 6081 D.getFunctionTypeInfo().freeArgs(); 6082 D.setInvalidType(); 6083 } else if (Proto->isVariadic()) { 6084 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6085 D.setInvalidType(); 6086 } 6087 6088 // Diagnose "&operator bool()" and other such nonsense. This 6089 // is actually a gcc extension which we don't support. 6090 if (Proto->getResultType() != ConvType) { 6091 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6092 << Proto->getResultType(); 6093 D.setInvalidType(); 6094 ConvType = Proto->getResultType(); 6095 } 6096 6097 // C++ [class.conv.fct]p4: 6098 // The conversion-type-id shall not represent a function type nor 6099 // an array type. 6100 if (ConvType->isArrayType()) { 6101 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6102 ConvType = Context.getPointerType(ConvType); 6103 D.setInvalidType(); 6104 } else if (ConvType->isFunctionType()) { 6105 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6106 ConvType = Context.getPointerType(ConvType); 6107 D.setInvalidType(); 6108 } 6109 6110 // Rebuild the function type "R" without any parameters (in case any 6111 // of the errors above fired) and with the conversion type as the 6112 // return type. 6113 if (D.isInvalidType()) 6114 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6115 6116 // C++0x explicit conversion operators. 6117 if (D.getDeclSpec().isExplicitSpecified()) 6118 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6119 getLangOpts().CPlusPlus11 ? 6120 diag::warn_cxx98_compat_explicit_conversion_functions : 6121 diag::ext_explicit_conversion_functions) 6122 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6123} 6124 6125/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6126/// the declaration of the given C++ conversion function. This routine 6127/// is responsible for recording the conversion function in the C++ 6128/// class, if possible. 6129Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6130 assert(Conversion && "Expected to receive a conversion function declaration"); 6131 6132 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6133 6134 // Make sure we aren't redeclaring the conversion function. 6135 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6136 6137 // C++ [class.conv.fct]p1: 6138 // [...] A conversion function is never used to convert a 6139 // (possibly cv-qualified) object to the (possibly cv-qualified) 6140 // same object type (or a reference to it), to a (possibly 6141 // cv-qualified) base class of that type (or a reference to it), 6142 // or to (possibly cv-qualified) void. 6143 // FIXME: Suppress this warning if the conversion function ends up being a 6144 // virtual function that overrides a virtual function in a base class. 6145 QualType ClassType 6146 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6147 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6148 ConvType = ConvTypeRef->getPointeeType(); 6149 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6150 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6151 /* Suppress diagnostics for instantiations. */; 6152 else if (ConvType->isRecordType()) { 6153 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6154 if (ConvType == ClassType) 6155 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6156 << ClassType; 6157 else if (IsDerivedFrom(ClassType, ConvType)) 6158 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6159 << ClassType << ConvType; 6160 } else if (ConvType->isVoidType()) { 6161 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6162 << ClassType << ConvType; 6163 } 6164 6165 if (FunctionTemplateDecl *ConversionTemplate 6166 = Conversion->getDescribedFunctionTemplate()) 6167 return ConversionTemplate; 6168 6169 return Conversion; 6170} 6171 6172//===----------------------------------------------------------------------===// 6173// Namespace Handling 6174//===----------------------------------------------------------------------===// 6175 6176/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6177/// reopened. 6178static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6179 SourceLocation Loc, 6180 IdentifierInfo *II, bool *IsInline, 6181 NamespaceDecl *PrevNS) { 6182 assert(*IsInline != PrevNS->isInline()); 6183 6184 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6185 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6186 // inline namespaces, with the intention of bringing names into namespace std. 6187 // 6188 // We support this just well enough to get that case working; this is not 6189 // sufficient to support reopening namespaces as inline in general. 6190 if (*IsInline && II && II->getName().startswith("__atomic") && 6191 S.getSourceManager().isInSystemHeader(Loc)) { 6192 // Mark all prior declarations of the namespace as inline. 6193 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6194 NS = NS->getPreviousDecl()) 6195 NS->setInline(*IsInline); 6196 // Patch up the lookup table for the containing namespace. This isn't really 6197 // correct, but it's good enough for this particular case. 6198 for (DeclContext::decl_iterator I = PrevNS->decls_begin(), 6199 E = PrevNS->decls_end(); I != E; ++I) 6200 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) 6201 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6202 return; 6203 } 6204 6205 if (PrevNS->isInline()) 6206 // The user probably just forgot the 'inline', so suggest that it 6207 // be added back. 6208 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6209 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6210 else 6211 S.Diag(Loc, diag::err_inline_namespace_mismatch) 6212 << IsInline; 6213 6214 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6215 *IsInline = PrevNS->isInline(); 6216} 6217 6218/// ActOnStartNamespaceDef - This is called at the start of a namespace 6219/// definition. 6220Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6221 SourceLocation InlineLoc, 6222 SourceLocation NamespaceLoc, 6223 SourceLocation IdentLoc, 6224 IdentifierInfo *II, 6225 SourceLocation LBrace, 6226 AttributeList *AttrList) { 6227 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6228 // For anonymous namespace, take the location of the left brace. 6229 SourceLocation Loc = II ? IdentLoc : LBrace; 6230 bool IsInline = InlineLoc.isValid(); 6231 bool IsInvalid = false; 6232 bool IsStd = false; 6233 bool AddToKnown = false; 6234 Scope *DeclRegionScope = NamespcScope->getParent(); 6235 6236 NamespaceDecl *PrevNS = 0; 6237 if (II) { 6238 // C++ [namespace.def]p2: 6239 // The identifier in an original-namespace-definition shall not 6240 // have been previously defined in the declarative region in 6241 // which the original-namespace-definition appears. The 6242 // identifier in an original-namespace-definition is the name of 6243 // the namespace. Subsequently in that declarative region, it is 6244 // treated as an original-namespace-name. 6245 // 6246 // Since namespace names are unique in their scope, and we don't 6247 // look through using directives, just look for any ordinary names. 6248 6249 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6250 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6251 Decl::IDNS_Namespace; 6252 NamedDecl *PrevDecl = 0; 6253 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6254 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6255 ++I) { 6256 if ((*I)->getIdentifierNamespace() & IDNS) { 6257 PrevDecl = *I; 6258 break; 6259 } 6260 } 6261 6262 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6263 6264 if (PrevNS) { 6265 // This is an extended namespace definition. 6266 if (IsInline != PrevNS->isInline()) 6267 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6268 &IsInline, PrevNS); 6269 } else if (PrevDecl) { 6270 // This is an invalid name redefinition. 6271 Diag(Loc, diag::err_redefinition_different_kind) 6272 << II; 6273 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6274 IsInvalid = true; 6275 // Continue on to push Namespc as current DeclContext and return it. 6276 } else if (II->isStr("std") && 6277 CurContext->getRedeclContext()->isTranslationUnit()) { 6278 // This is the first "real" definition of the namespace "std", so update 6279 // our cache of the "std" namespace to point at this definition. 6280 PrevNS = getStdNamespace(); 6281 IsStd = true; 6282 AddToKnown = !IsInline; 6283 } else { 6284 // We've seen this namespace for the first time. 6285 AddToKnown = !IsInline; 6286 } 6287 } else { 6288 // Anonymous namespaces. 6289 6290 // Determine whether the parent already has an anonymous namespace. 6291 DeclContext *Parent = CurContext->getRedeclContext(); 6292 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6293 PrevNS = TU->getAnonymousNamespace(); 6294 } else { 6295 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6296 PrevNS = ND->getAnonymousNamespace(); 6297 } 6298 6299 if (PrevNS && IsInline != PrevNS->isInline()) 6300 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6301 &IsInline, PrevNS); 6302 } 6303 6304 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6305 StartLoc, Loc, II, PrevNS); 6306 if (IsInvalid) 6307 Namespc->setInvalidDecl(); 6308 6309 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6310 6311 // FIXME: Should we be merging attributes? 6312 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6313 PushNamespaceVisibilityAttr(Attr, Loc); 6314 6315 if (IsStd) 6316 StdNamespace = Namespc; 6317 if (AddToKnown) 6318 KnownNamespaces[Namespc] = false; 6319 6320 if (II) { 6321 PushOnScopeChains(Namespc, DeclRegionScope); 6322 } else { 6323 // Link the anonymous namespace into its parent. 6324 DeclContext *Parent = CurContext->getRedeclContext(); 6325 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6326 TU->setAnonymousNamespace(Namespc); 6327 } else { 6328 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6329 } 6330 6331 CurContext->addDecl(Namespc); 6332 6333 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6334 // behaves as if it were replaced by 6335 // namespace unique { /* empty body */ } 6336 // using namespace unique; 6337 // namespace unique { namespace-body } 6338 // where all occurrences of 'unique' in a translation unit are 6339 // replaced by the same identifier and this identifier differs 6340 // from all other identifiers in the entire program. 6341 6342 // We just create the namespace with an empty name and then add an 6343 // implicit using declaration, just like the standard suggests. 6344 // 6345 // CodeGen enforces the "universally unique" aspect by giving all 6346 // declarations semantically contained within an anonymous 6347 // namespace internal linkage. 6348 6349 if (!PrevNS) { 6350 UsingDirectiveDecl* UD 6351 = UsingDirectiveDecl::Create(Context, Parent, 6352 /* 'using' */ LBrace, 6353 /* 'namespace' */ SourceLocation(), 6354 /* qualifier */ NestedNameSpecifierLoc(), 6355 /* identifier */ SourceLocation(), 6356 Namespc, 6357 /* Ancestor */ Parent); 6358 UD->setImplicit(); 6359 Parent->addDecl(UD); 6360 } 6361 } 6362 6363 ActOnDocumentableDecl(Namespc); 6364 6365 // Although we could have an invalid decl (i.e. the namespace name is a 6366 // redefinition), push it as current DeclContext and try to continue parsing. 6367 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6368 // for the namespace has the declarations that showed up in that particular 6369 // namespace definition. 6370 PushDeclContext(NamespcScope, Namespc); 6371 return Namespc; 6372} 6373 6374/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6375/// is a namespace alias, returns the namespace it points to. 6376static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6377 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6378 return AD->getNamespace(); 6379 return dyn_cast_or_null<NamespaceDecl>(D); 6380} 6381 6382/// ActOnFinishNamespaceDef - This callback is called after a namespace is 6383/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6384void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6385 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6386 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6387 Namespc->setRBraceLoc(RBrace); 6388 PopDeclContext(); 6389 if (Namespc->hasAttr<VisibilityAttr>()) 6390 PopPragmaVisibility(true, RBrace); 6391} 6392 6393CXXRecordDecl *Sema::getStdBadAlloc() const { 6394 return cast_or_null<CXXRecordDecl>( 6395 StdBadAlloc.get(Context.getExternalSource())); 6396} 6397 6398NamespaceDecl *Sema::getStdNamespace() const { 6399 return cast_or_null<NamespaceDecl>( 6400 StdNamespace.get(Context.getExternalSource())); 6401} 6402 6403/// \brief Retrieve the special "std" namespace, which may require us to 6404/// implicitly define the namespace. 6405NamespaceDecl *Sema::getOrCreateStdNamespace() { 6406 if (!StdNamespace) { 6407 // The "std" namespace has not yet been defined, so build one implicitly. 6408 StdNamespace = NamespaceDecl::Create(Context, 6409 Context.getTranslationUnitDecl(), 6410 /*Inline=*/false, 6411 SourceLocation(), SourceLocation(), 6412 &PP.getIdentifierTable().get("std"), 6413 /*PrevDecl=*/0); 6414 getStdNamespace()->setImplicit(true); 6415 } 6416 6417 return getStdNamespace(); 6418} 6419 6420bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6421 assert(getLangOpts().CPlusPlus && 6422 "Looking for std::initializer_list outside of C++."); 6423 6424 // We're looking for implicit instantiations of 6425 // template <typename E> class std::initializer_list. 6426 6427 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6428 return false; 6429 6430 ClassTemplateDecl *Template = 0; 6431 const TemplateArgument *Arguments = 0; 6432 6433 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6434 6435 ClassTemplateSpecializationDecl *Specialization = 6436 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6437 if (!Specialization) 6438 return false; 6439 6440 Template = Specialization->getSpecializedTemplate(); 6441 Arguments = Specialization->getTemplateArgs().data(); 6442 } else if (const TemplateSpecializationType *TST = 6443 Ty->getAs<TemplateSpecializationType>()) { 6444 Template = dyn_cast_or_null<ClassTemplateDecl>( 6445 TST->getTemplateName().getAsTemplateDecl()); 6446 Arguments = TST->getArgs(); 6447 } 6448 if (!Template) 6449 return false; 6450 6451 if (!StdInitializerList) { 6452 // Haven't recognized std::initializer_list yet, maybe this is it. 6453 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6454 if (TemplateClass->getIdentifier() != 6455 &PP.getIdentifierTable().get("initializer_list") || 6456 !getStdNamespace()->InEnclosingNamespaceSetOf( 6457 TemplateClass->getDeclContext())) 6458 return false; 6459 // This is a template called std::initializer_list, but is it the right 6460 // template? 6461 TemplateParameterList *Params = Template->getTemplateParameters(); 6462 if (Params->getMinRequiredArguments() != 1) 6463 return false; 6464 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6465 return false; 6466 6467 // It's the right template. 6468 StdInitializerList = Template; 6469 } 6470 6471 if (Template != StdInitializerList) 6472 return false; 6473 6474 // This is an instance of std::initializer_list. Find the argument type. 6475 if (Element) 6476 *Element = Arguments[0].getAsType(); 6477 return true; 6478} 6479 6480static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6481 NamespaceDecl *Std = S.getStdNamespace(); 6482 if (!Std) { 6483 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6484 return 0; 6485 } 6486 6487 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6488 Loc, Sema::LookupOrdinaryName); 6489 if (!S.LookupQualifiedName(Result, Std)) { 6490 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6491 return 0; 6492 } 6493 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6494 if (!Template) { 6495 Result.suppressDiagnostics(); 6496 // We found something weird. Complain about the first thing we found. 6497 NamedDecl *Found = *Result.begin(); 6498 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6499 return 0; 6500 } 6501 6502 // We found some template called std::initializer_list. Now verify that it's 6503 // correct. 6504 TemplateParameterList *Params = Template->getTemplateParameters(); 6505 if (Params->getMinRequiredArguments() != 1 || 6506 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6507 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6508 return 0; 6509 } 6510 6511 return Template; 6512} 6513 6514QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6515 if (!StdInitializerList) { 6516 StdInitializerList = LookupStdInitializerList(*this, Loc); 6517 if (!StdInitializerList) 6518 return QualType(); 6519 } 6520 6521 TemplateArgumentListInfo Args(Loc, Loc); 6522 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6523 Context.getTrivialTypeSourceInfo(Element, 6524 Loc))); 6525 return Context.getCanonicalType( 6526 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6527} 6528 6529bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6530 // C++ [dcl.init.list]p2: 6531 // A constructor is an initializer-list constructor if its first parameter 6532 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6533 // std::initializer_list<E> for some type E, and either there are no other 6534 // parameters or else all other parameters have default arguments. 6535 if (Ctor->getNumParams() < 1 || 6536 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6537 return false; 6538 6539 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6540 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6541 ArgType = RT->getPointeeType().getUnqualifiedType(); 6542 6543 return isStdInitializerList(ArgType, 0); 6544} 6545 6546/// \brief Determine whether a using statement is in a context where it will be 6547/// apply in all contexts. 6548static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6549 switch (CurContext->getDeclKind()) { 6550 case Decl::TranslationUnit: 6551 return true; 6552 case Decl::LinkageSpec: 6553 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6554 default: 6555 return false; 6556 } 6557} 6558 6559namespace { 6560 6561// Callback to only accept typo corrections that are namespaces. 6562class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6563 public: 6564 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 6565 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 6566 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6567 } 6568 return false; 6569 } 6570}; 6571 6572} 6573 6574static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6575 CXXScopeSpec &SS, 6576 SourceLocation IdentLoc, 6577 IdentifierInfo *Ident) { 6578 NamespaceValidatorCCC Validator; 6579 R.clear(); 6580 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6581 R.getLookupKind(), Sc, &SS, 6582 Validator)) { 6583 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6584 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts())); 6585 if (DeclContext *DC = S.computeDeclContext(SS, false)) 6586 S.Diag(IdentLoc, diag::err_using_directive_member_suggest) 6587 << Ident << DC << CorrectedQuotedStr << SS.getRange() 6588 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 6589 CorrectedStr); 6590 else 6591 S.Diag(IdentLoc, diag::err_using_directive_suggest) 6592 << Ident << CorrectedQuotedStr 6593 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 6594 6595 S.Diag(Corrected.getCorrectionDecl()->getLocation(), 6596 diag::note_namespace_defined_here) << CorrectedQuotedStr; 6597 6598 R.addDecl(Corrected.getCorrectionDecl()); 6599 return true; 6600 } 6601 return false; 6602} 6603 6604Decl *Sema::ActOnUsingDirective(Scope *S, 6605 SourceLocation UsingLoc, 6606 SourceLocation NamespcLoc, 6607 CXXScopeSpec &SS, 6608 SourceLocation IdentLoc, 6609 IdentifierInfo *NamespcName, 6610 AttributeList *AttrList) { 6611 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6612 assert(NamespcName && "Invalid NamespcName."); 6613 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6614 6615 // This can only happen along a recovery path. 6616 while (S->getFlags() & Scope::TemplateParamScope) 6617 S = S->getParent(); 6618 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6619 6620 UsingDirectiveDecl *UDir = 0; 6621 NestedNameSpecifier *Qualifier = 0; 6622 if (SS.isSet()) 6623 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6624 6625 // Lookup namespace name. 6626 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6627 LookupParsedName(R, S, &SS); 6628 if (R.isAmbiguous()) 6629 return 0; 6630 6631 if (R.empty()) { 6632 R.clear(); 6633 // Allow "using namespace std;" or "using namespace ::std;" even if 6634 // "std" hasn't been defined yet, for GCC compatibility. 6635 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6636 NamespcName->isStr("std")) { 6637 Diag(IdentLoc, diag::ext_using_undefined_std); 6638 R.addDecl(getOrCreateStdNamespace()); 6639 R.resolveKind(); 6640 } 6641 // Otherwise, attempt typo correction. 6642 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6643 } 6644 6645 if (!R.empty()) { 6646 NamedDecl *Named = R.getFoundDecl(); 6647 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6648 && "expected namespace decl"); 6649 // C++ [namespace.udir]p1: 6650 // A using-directive specifies that the names in the nominated 6651 // namespace can be used in the scope in which the 6652 // using-directive appears after the using-directive. During 6653 // unqualified name lookup (3.4.1), the names appear as if they 6654 // were declared in the nearest enclosing namespace which 6655 // contains both the using-directive and the nominated 6656 // namespace. [Note: in this context, "contains" means "contains 6657 // directly or indirectly". ] 6658 6659 // Find enclosing context containing both using-directive and 6660 // nominated namespace. 6661 NamespaceDecl *NS = getNamespaceDecl(Named); 6662 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6663 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6664 CommonAncestor = CommonAncestor->getParent(); 6665 6666 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6667 SS.getWithLocInContext(Context), 6668 IdentLoc, Named, CommonAncestor); 6669 6670 if (IsUsingDirectiveInToplevelContext(CurContext) && 6671 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6672 Diag(IdentLoc, diag::warn_using_directive_in_header); 6673 } 6674 6675 PushUsingDirective(S, UDir); 6676 } else { 6677 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6678 } 6679 6680 if (UDir) 6681 ProcessDeclAttributeList(S, UDir, AttrList); 6682 6683 return UDir; 6684} 6685 6686void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 6687 // If the scope has an associated entity and the using directive is at 6688 // namespace or translation unit scope, add the UsingDirectiveDecl into 6689 // its lookup structure so qualified name lookup can find it. 6690 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 6691 if (Ctx && !Ctx->isFunctionOrMethod()) 6692 Ctx->addDecl(UDir); 6693 else 6694 // Otherwise, it is at block sope. The using-directives will affect lookup 6695 // only to the end of the scope. 6696 S->PushUsingDirective(UDir); 6697} 6698 6699 6700Decl *Sema::ActOnUsingDeclaration(Scope *S, 6701 AccessSpecifier AS, 6702 bool HasUsingKeyword, 6703 SourceLocation UsingLoc, 6704 CXXScopeSpec &SS, 6705 UnqualifiedId &Name, 6706 AttributeList *AttrList, 6707 bool IsTypeName, 6708 SourceLocation TypenameLoc) { 6709 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6710 6711 switch (Name.getKind()) { 6712 case UnqualifiedId::IK_ImplicitSelfParam: 6713 case UnqualifiedId::IK_Identifier: 6714 case UnqualifiedId::IK_OperatorFunctionId: 6715 case UnqualifiedId::IK_LiteralOperatorId: 6716 case UnqualifiedId::IK_ConversionFunctionId: 6717 break; 6718 6719 case UnqualifiedId::IK_ConstructorName: 6720 case UnqualifiedId::IK_ConstructorTemplateId: 6721 // C++11 inheriting constructors. 6722 Diag(Name.getLocStart(), 6723 getLangOpts().CPlusPlus11 ? 6724 diag::warn_cxx98_compat_using_decl_constructor : 6725 diag::err_using_decl_constructor) 6726 << SS.getRange(); 6727 6728 if (getLangOpts().CPlusPlus11) break; 6729 6730 return 0; 6731 6732 case UnqualifiedId::IK_DestructorName: 6733 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 6734 << SS.getRange(); 6735 return 0; 6736 6737 case UnqualifiedId::IK_TemplateId: 6738 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 6739 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 6740 return 0; 6741 } 6742 6743 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 6744 DeclarationName TargetName = TargetNameInfo.getName(); 6745 if (!TargetName) 6746 return 0; 6747 6748 // Warn about access declarations. 6749 // TODO: store that the declaration was written without 'using' and 6750 // talk about access decls instead of using decls in the 6751 // diagnostics. 6752 if (!HasUsingKeyword) { 6753 UsingLoc = Name.getLocStart(); 6754 6755 Diag(UsingLoc, diag::warn_access_decl_deprecated) 6756 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 6757 } 6758 6759 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 6760 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 6761 return 0; 6762 6763 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 6764 TargetNameInfo, AttrList, 6765 /* IsInstantiation */ false, 6766 IsTypeName, TypenameLoc); 6767 if (UD) 6768 PushOnScopeChains(UD, S, /*AddToContext*/ false); 6769 6770 return UD; 6771} 6772 6773/// \brief Determine whether a using declaration considers the given 6774/// declarations as "equivalent", e.g., if they are redeclarations of 6775/// the same entity or are both typedefs of the same type. 6776static bool 6777IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 6778 bool &SuppressRedeclaration) { 6779 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 6780 SuppressRedeclaration = false; 6781 return true; 6782 } 6783 6784 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 6785 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 6786 SuppressRedeclaration = true; 6787 return Context.hasSameType(TD1->getUnderlyingType(), 6788 TD2->getUnderlyingType()); 6789 } 6790 6791 return false; 6792} 6793 6794 6795/// Determines whether to create a using shadow decl for a particular 6796/// decl, given the set of decls existing prior to this using lookup. 6797bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 6798 const LookupResult &Previous) { 6799 // Diagnose finding a decl which is not from a base class of the 6800 // current class. We do this now because there are cases where this 6801 // function will silently decide not to build a shadow decl, which 6802 // will pre-empt further diagnostics. 6803 // 6804 // We don't need to do this in C++0x because we do the check once on 6805 // the qualifier. 6806 // 6807 // FIXME: diagnose the following if we care enough: 6808 // struct A { int foo; }; 6809 // struct B : A { using A::foo; }; 6810 // template <class T> struct C : A {}; 6811 // template <class T> struct D : C<T> { using B::foo; } // <--- 6812 // This is invalid (during instantiation) in C++03 because B::foo 6813 // resolves to the using decl in B, which is not a base class of D<T>. 6814 // We can't diagnose it immediately because C<T> is an unknown 6815 // specialization. The UsingShadowDecl in D<T> then points directly 6816 // to A::foo, which will look well-formed when we instantiate. 6817 // The right solution is to not collapse the shadow-decl chain. 6818 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 6819 DeclContext *OrigDC = Orig->getDeclContext(); 6820 6821 // Handle enums and anonymous structs. 6822 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 6823 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 6824 while (OrigRec->isAnonymousStructOrUnion()) 6825 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 6826 6827 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 6828 if (OrigDC == CurContext) { 6829 Diag(Using->getLocation(), 6830 diag::err_using_decl_nested_name_specifier_is_current_class) 6831 << Using->getQualifierLoc().getSourceRange(); 6832 Diag(Orig->getLocation(), diag::note_using_decl_target); 6833 return true; 6834 } 6835 6836 Diag(Using->getQualifierLoc().getBeginLoc(), 6837 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6838 << Using->getQualifier() 6839 << cast<CXXRecordDecl>(CurContext) 6840 << Using->getQualifierLoc().getSourceRange(); 6841 Diag(Orig->getLocation(), diag::note_using_decl_target); 6842 return true; 6843 } 6844 } 6845 6846 if (Previous.empty()) return false; 6847 6848 NamedDecl *Target = Orig; 6849 if (isa<UsingShadowDecl>(Target)) 6850 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6851 6852 // If the target happens to be one of the previous declarations, we 6853 // don't have a conflict. 6854 // 6855 // FIXME: but we might be increasing its access, in which case we 6856 // should redeclare it. 6857 NamedDecl *NonTag = 0, *Tag = 0; 6858 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6859 I != E; ++I) { 6860 NamedDecl *D = (*I)->getUnderlyingDecl(); 6861 bool Result; 6862 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 6863 return Result; 6864 6865 (isa<TagDecl>(D) ? Tag : NonTag) = D; 6866 } 6867 6868 if (Target->isFunctionOrFunctionTemplate()) { 6869 FunctionDecl *FD; 6870 if (isa<FunctionTemplateDecl>(Target)) 6871 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 6872 else 6873 FD = cast<FunctionDecl>(Target); 6874 6875 NamedDecl *OldDecl = 0; 6876 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 6877 case Ovl_Overload: 6878 return false; 6879 6880 case Ovl_NonFunction: 6881 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6882 break; 6883 6884 // We found a decl with the exact signature. 6885 case Ovl_Match: 6886 // If we're in a record, we want to hide the target, so we 6887 // return true (without a diagnostic) to tell the caller not to 6888 // build a shadow decl. 6889 if (CurContext->isRecord()) 6890 return true; 6891 6892 // If we're not in a record, this is an error. 6893 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6894 break; 6895 } 6896 6897 Diag(Target->getLocation(), diag::note_using_decl_target); 6898 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 6899 return true; 6900 } 6901 6902 // Target is not a function. 6903 6904 if (isa<TagDecl>(Target)) { 6905 // No conflict between a tag and a non-tag. 6906 if (!Tag) return false; 6907 6908 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6909 Diag(Target->getLocation(), diag::note_using_decl_target); 6910 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 6911 return true; 6912 } 6913 6914 // No conflict between a tag and a non-tag. 6915 if (!NonTag) return false; 6916 6917 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6918 Diag(Target->getLocation(), diag::note_using_decl_target); 6919 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 6920 return true; 6921} 6922 6923/// Builds a shadow declaration corresponding to a 'using' declaration. 6924UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 6925 UsingDecl *UD, 6926 NamedDecl *Orig) { 6927 6928 // If we resolved to another shadow declaration, just coalesce them. 6929 NamedDecl *Target = Orig; 6930 if (isa<UsingShadowDecl>(Target)) { 6931 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6932 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 6933 } 6934 6935 UsingShadowDecl *Shadow 6936 = UsingShadowDecl::Create(Context, CurContext, 6937 UD->getLocation(), UD, Target); 6938 UD->addShadowDecl(Shadow); 6939 6940 Shadow->setAccess(UD->getAccess()); 6941 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 6942 Shadow->setInvalidDecl(); 6943 6944 if (S) 6945 PushOnScopeChains(Shadow, S); 6946 else 6947 CurContext->addDecl(Shadow); 6948 6949 6950 return Shadow; 6951} 6952 6953/// Hides a using shadow declaration. This is required by the current 6954/// using-decl implementation when a resolvable using declaration in a 6955/// class is followed by a declaration which would hide or override 6956/// one or more of the using decl's targets; for example: 6957/// 6958/// struct Base { void foo(int); }; 6959/// struct Derived : Base { 6960/// using Base::foo; 6961/// void foo(int); 6962/// }; 6963/// 6964/// The governing language is C++03 [namespace.udecl]p12: 6965/// 6966/// When a using-declaration brings names from a base class into a 6967/// derived class scope, member functions in the derived class 6968/// override and/or hide member functions with the same name and 6969/// parameter types in a base class (rather than conflicting). 6970/// 6971/// There are two ways to implement this: 6972/// (1) optimistically create shadow decls when they're not hidden 6973/// by existing declarations, or 6974/// (2) don't create any shadow decls (or at least don't make them 6975/// visible) until we've fully parsed/instantiated the class. 6976/// The problem with (1) is that we might have to retroactively remove 6977/// a shadow decl, which requires several O(n) operations because the 6978/// decl structures are (very reasonably) not designed for removal. 6979/// (2) avoids this but is very fiddly and phase-dependent. 6980void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 6981 if (Shadow->getDeclName().getNameKind() == 6982 DeclarationName::CXXConversionFunctionName) 6983 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 6984 6985 // Remove it from the DeclContext... 6986 Shadow->getDeclContext()->removeDecl(Shadow); 6987 6988 // ...and the scope, if applicable... 6989 if (S) { 6990 S->RemoveDecl(Shadow); 6991 IdResolver.RemoveDecl(Shadow); 6992 } 6993 6994 // ...and the using decl. 6995 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 6996 6997 // TODO: complain somehow if Shadow was used. It shouldn't 6998 // be possible for this to happen, because...? 6999} 7000 7001/// Builds a using declaration. 7002/// 7003/// \param IsInstantiation - Whether this call arises from an 7004/// instantiation of an unresolved using declaration. We treat 7005/// the lookup differently for these declarations. 7006NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7007 SourceLocation UsingLoc, 7008 CXXScopeSpec &SS, 7009 const DeclarationNameInfo &NameInfo, 7010 AttributeList *AttrList, 7011 bool IsInstantiation, 7012 bool IsTypeName, 7013 SourceLocation TypenameLoc) { 7014 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7015 SourceLocation IdentLoc = NameInfo.getLoc(); 7016 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7017 7018 // FIXME: We ignore attributes for now. 7019 7020 if (SS.isEmpty()) { 7021 Diag(IdentLoc, diag::err_using_requires_qualname); 7022 return 0; 7023 } 7024 7025 // Do the redeclaration lookup in the current scope. 7026 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7027 ForRedeclaration); 7028 Previous.setHideTags(false); 7029 if (S) { 7030 LookupName(Previous, S); 7031 7032 // It is really dumb that we have to do this. 7033 LookupResult::Filter F = Previous.makeFilter(); 7034 while (F.hasNext()) { 7035 NamedDecl *D = F.next(); 7036 if (!isDeclInScope(D, CurContext, S)) 7037 F.erase(); 7038 } 7039 F.done(); 7040 } else { 7041 assert(IsInstantiation && "no scope in non-instantiation"); 7042 assert(CurContext->isRecord() && "scope not record in instantiation"); 7043 LookupQualifiedName(Previous, CurContext); 7044 } 7045 7046 // Check for invalid redeclarations. 7047 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 7048 return 0; 7049 7050 // Check for bad qualifiers. 7051 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 7052 return 0; 7053 7054 DeclContext *LookupContext = computeDeclContext(SS); 7055 NamedDecl *D; 7056 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7057 if (!LookupContext) { 7058 if (IsTypeName) { 7059 // FIXME: not all declaration name kinds are legal here 7060 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7061 UsingLoc, TypenameLoc, 7062 QualifierLoc, 7063 IdentLoc, NameInfo.getName()); 7064 } else { 7065 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7066 QualifierLoc, NameInfo); 7067 } 7068 } else { 7069 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 7070 NameInfo, IsTypeName); 7071 } 7072 D->setAccess(AS); 7073 CurContext->addDecl(D); 7074 7075 if (!LookupContext) return D; 7076 UsingDecl *UD = cast<UsingDecl>(D); 7077 7078 if (RequireCompleteDeclContext(SS, LookupContext)) { 7079 UD->setInvalidDecl(); 7080 return UD; 7081 } 7082 7083 // The normal rules do not apply to inheriting constructor declarations. 7084 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7085 if (CheckInheritingConstructorUsingDecl(UD)) 7086 UD->setInvalidDecl(); 7087 return UD; 7088 } 7089 7090 // Otherwise, look up the target name. 7091 7092 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7093 7094 // Unlike most lookups, we don't always want to hide tag 7095 // declarations: tag names are visible through the using declaration 7096 // even if hidden by ordinary names, *except* in a dependent context 7097 // where it's important for the sanity of two-phase lookup. 7098 if (!IsInstantiation) 7099 R.setHideTags(false); 7100 7101 // For the purposes of this lookup, we have a base object type 7102 // equal to that of the current context. 7103 if (CurContext->isRecord()) { 7104 R.setBaseObjectType( 7105 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7106 } 7107 7108 LookupQualifiedName(R, LookupContext); 7109 7110 if (R.empty()) { 7111 Diag(IdentLoc, diag::err_no_member) 7112 << NameInfo.getName() << LookupContext << SS.getRange(); 7113 UD->setInvalidDecl(); 7114 return UD; 7115 } 7116 7117 if (R.isAmbiguous()) { 7118 UD->setInvalidDecl(); 7119 return UD; 7120 } 7121 7122 if (IsTypeName) { 7123 // If we asked for a typename and got a non-type decl, error out. 7124 if (!R.getAsSingle<TypeDecl>()) { 7125 Diag(IdentLoc, diag::err_using_typename_non_type); 7126 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7127 Diag((*I)->getUnderlyingDecl()->getLocation(), 7128 diag::note_using_decl_target); 7129 UD->setInvalidDecl(); 7130 return UD; 7131 } 7132 } else { 7133 // If we asked for a non-typename and we got a type, error out, 7134 // but only if this is an instantiation of an unresolved using 7135 // decl. Otherwise just silently find the type name. 7136 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7137 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7138 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7139 UD->setInvalidDecl(); 7140 return UD; 7141 } 7142 } 7143 7144 // C++0x N2914 [namespace.udecl]p6: 7145 // A using-declaration shall not name a namespace. 7146 if (R.getAsSingle<NamespaceDecl>()) { 7147 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7148 << SS.getRange(); 7149 UD->setInvalidDecl(); 7150 return UD; 7151 } 7152 7153 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7154 if (!CheckUsingShadowDecl(UD, *I, Previous)) 7155 BuildUsingShadowDecl(S, UD, *I); 7156 } 7157 7158 return UD; 7159} 7160 7161/// Additional checks for a using declaration referring to a constructor name. 7162bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7163 assert(!UD->isTypeName() && "expecting a constructor name"); 7164 7165 const Type *SourceType = UD->getQualifier()->getAsType(); 7166 assert(SourceType && 7167 "Using decl naming constructor doesn't have type in scope spec."); 7168 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7169 7170 // Check whether the named type is a direct base class. 7171 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 7172 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 7173 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 7174 BaseIt != BaseE; ++BaseIt) { 7175 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 7176 if (CanonicalSourceType == BaseType) 7177 break; 7178 if (BaseIt->getType()->isDependentType()) 7179 break; 7180 } 7181 7182 if (BaseIt == BaseE) { 7183 // Did not find SourceType in the bases. 7184 Diag(UD->getUsingLocation(), 7185 diag::err_using_decl_constructor_not_in_direct_base) 7186 << UD->getNameInfo().getSourceRange() 7187 << QualType(SourceType, 0) << TargetClass; 7188 return true; 7189 } 7190 7191 if (!CurContext->isDependentContext()) 7192 BaseIt->setInheritConstructors(); 7193 7194 return false; 7195} 7196 7197/// Checks that the given using declaration is not an invalid 7198/// redeclaration. Note that this is checking only for the using decl 7199/// itself, not for any ill-formedness among the UsingShadowDecls. 7200bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7201 bool isTypeName, 7202 const CXXScopeSpec &SS, 7203 SourceLocation NameLoc, 7204 const LookupResult &Prev) { 7205 // C++03 [namespace.udecl]p8: 7206 // C++0x [namespace.udecl]p10: 7207 // A using-declaration is a declaration and can therefore be used 7208 // repeatedly where (and only where) multiple declarations are 7209 // allowed. 7210 // 7211 // That's in non-member contexts. 7212 if (!CurContext->getRedeclContext()->isRecord()) 7213 return false; 7214 7215 NestedNameSpecifier *Qual 7216 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 7217 7218 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7219 NamedDecl *D = *I; 7220 7221 bool DTypename; 7222 NestedNameSpecifier *DQual; 7223 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7224 DTypename = UD->isTypeName(); 7225 DQual = UD->getQualifier(); 7226 } else if (UnresolvedUsingValueDecl *UD 7227 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7228 DTypename = false; 7229 DQual = UD->getQualifier(); 7230 } else if (UnresolvedUsingTypenameDecl *UD 7231 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7232 DTypename = true; 7233 DQual = UD->getQualifier(); 7234 } else continue; 7235 7236 // using decls differ if one says 'typename' and the other doesn't. 7237 // FIXME: non-dependent using decls? 7238 if (isTypeName != DTypename) continue; 7239 7240 // using decls differ if they name different scopes (but note that 7241 // template instantiation can cause this check to trigger when it 7242 // didn't before instantiation). 7243 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7244 Context.getCanonicalNestedNameSpecifier(DQual)) 7245 continue; 7246 7247 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7248 Diag(D->getLocation(), diag::note_using_decl) << 1; 7249 return true; 7250 } 7251 7252 return false; 7253} 7254 7255 7256/// Checks that the given nested-name qualifier used in a using decl 7257/// in the current context is appropriately related to the current 7258/// scope. If an error is found, diagnoses it and returns true. 7259bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7260 const CXXScopeSpec &SS, 7261 SourceLocation NameLoc) { 7262 DeclContext *NamedContext = computeDeclContext(SS); 7263 7264 if (!CurContext->isRecord()) { 7265 // C++03 [namespace.udecl]p3: 7266 // C++0x [namespace.udecl]p8: 7267 // A using-declaration for a class member shall be a member-declaration. 7268 7269 // If we weren't able to compute a valid scope, it must be a 7270 // dependent class scope. 7271 if (!NamedContext || NamedContext->isRecord()) { 7272 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7273 << SS.getRange(); 7274 return true; 7275 } 7276 7277 // Otherwise, everything is known to be fine. 7278 return false; 7279 } 7280 7281 // The current scope is a record. 7282 7283 // If the named context is dependent, we can't decide much. 7284 if (!NamedContext) { 7285 // FIXME: in C++0x, we can diagnose if we can prove that the 7286 // nested-name-specifier does not refer to a base class, which is 7287 // still possible in some cases. 7288 7289 // Otherwise we have to conservatively report that things might be 7290 // okay. 7291 return false; 7292 } 7293 7294 if (!NamedContext->isRecord()) { 7295 // Ideally this would point at the last name in the specifier, 7296 // but we don't have that level of source info. 7297 Diag(SS.getRange().getBegin(), 7298 diag::err_using_decl_nested_name_specifier_is_not_class) 7299 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 7300 return true; 7301 } 7302 7303 if (!NamedContext->isDependentContext() && 7304 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7305 return true; 7306 7307 if (getLangOpts().CPlusPlus11) { 7308 // C++0x [namespace.udecl]p3: 7309 // In a using-declaration used as a member-declaration, the 7310 // nested-name-specifier shall name a base class of the class 7311 // being defined. 7312 7313 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7314 cast<CXXRecordDecl>(NamedContext))) { 7315 if (CurContext == NamedContext) { 7316 Diag(NameLoc, 7317 diag::err_using_decl_nested_name_specifier_is_current_class) 7318 << SS.getRange(); 7319 return true; 7320 } 7321 7322 Diag(SS.getRange().getBegin(), 7323 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7324 << (NestedNameSpecifier*) SS.getScopeRep() 7325 << cast<CXXRecordDecl>(CurContext) 7326 << SS.getRange(); 7327 return true; 7328 } 7329 7330 return false; 7331 } 7332 7333 // C++03 [namespace.udecl]p4: 7334 // A using-declaration used as a member-declaration shall refer 7335 // to a member of a base class of the class being defined [etc.]. 7336 7337 // Salient point: SS doesn't have to name a base class as long as 7338 // lookup only finds members from base classes. Therefore we can 7339 // diagnose here only if we can prove that that can't happen, 7340 // i.e. if the class hierarchies provably don't intersect. 7341 7342 // TODO: it would be nice if "definitely valid" results were cached 7343 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7344 // need to be repeated. 7345 7346 struct UserData { 7347 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7348 7349 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7350 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7351 Data->Bases.insert(Base); 7352 return true; 7353 } 7354 7355 bool hasDependentBases(const CXXRecordDecl *Class) { 7356 return !Class->forallBases(collect, this); 7357 } 7358 7359 /// Returns true if the base is dependent or is one of the 7360 /// accumulated base classes. 7361 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7362 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7363 return !Data->Bases.count(Base); 7364 } 7365 7366 bool mightShareBases(const CXXRecordDecl *Class) { 7367 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7368 } 7369 }; 7370 7371 UserData Data; 7372 7373 // Returns false if we find a dependent base. 7374 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7375 return false; 7376 7377 // Returns false if the class has a dependent base or if it or one 7378 // of its bases is present in the base set of the current context. 7379 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7380 return false; 7381 7382 Diag(SS.getRange().getBegin(), 7383 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7384 << (NestedNameSpecifier*) SS.getScopeRep() 7385 << cast<CXXRecordDecl>(CurContext) 7386 << SS.getRange(); 7387 7388 return true; 7389} 7390 7391Decl *Sema::ActOnAliasDeclaration(Scope *S, 7392 AccessSpecifier AS, 7393 MultiTemplateParamsArg TemplateParamLists, 7394 SourceLocation UsingLoc, 7395 UnqualifiedId &Name, 7396 AttributeList *AttrList, 7397 TypeResult Type) { 7398 // Skip up to the relevant declaration scope. 7399 while (S->getFlags() & Scope::TemplateParamScope) 7400 S = S->getParent(); 7401 assert((S->getFlags() & Scope::DeclScope) && 7402 "got alias-declaration outside of declaration scope"); 7403 7404 if (Type.isInvalid()) 7405 return 0; 7406 7407 bool Invalid = false; 7408 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7409 TypeSourceInfo *TInfo = 0; 7410 GetTypeFromParser(Type.get(), &TInfo); 7411 7412 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7413 return 0; 7414 7415 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7416 UPPC_DeclarationType)) { 7417 Invalid = true; 7418 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7419 TInfo->getTypeLoc().getBeginLoc()); 7420 } 7421 7422 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7423 LookupName(Previous, S); 7424 7425 // Warn about shadowing the name of a template parameter. 7426 if (Previous.isSingleResult() && 7427 Previous.getFoundDecl()->isTemplateParameter()) { 7428 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7429 Previous.clear(); 7430 } 7431 7432 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7433 "name in alias declaration must be an identifier"); 7434 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7435 Name.StartLocation, 7436 Name.Identifier, TInfo); 7437 7438 NewTD->setAccess(AS); 7439 7440 if (Invalid) 7441 NewTD->setInvalidDecl(); 7442 7443 ProcessDeclAttributeList(S, NewTD, AttrList); 7444 7445 CheckTypedefForVariablyModifiedType(S, NewTD); 7446 Invalid |= NewTD->isInvalidDecl(); 7447 7448 bool Redeclaration = false; 7449 7450 NamedDecl *NewND; 7451 if (TemplateParamLists.size()) { 7452 TypeAliasTemplateDecl *OldDecl = 0; 7453 TemplateParameterList *OldTemplateParams = 0; 7454 7455 if (TemplateParamLists.size() != 1) { 7456 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7457 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7458 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7459 } 7460 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7461 7462 // Only consider previous declarations in the same scope. 7463 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7464 /*ExplicitInstantiationOrSpecialization*/false); 7465 if (!Previous.empty()) { 7466 Redeclaration = true; 7467 7468 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7469 if (!OldDecl && !Invalid) { 7470 Diag(UsingLoc, diag::err_redefinition_different_kind) 7471 << Name.Identifier; 7472 7473 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7474 if (OldD->getLocation().isValid()) 7475 Diag(OldD->getLocation(), diag::note_previous_definition); 7476 7477 Invalid = true; 7478 } 7479 7480 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7481 if (TemplateParameterListsAreEqual(TemplateParams, 7482 OldDecl->getTemplateParameters(), 7483 /*Complain=*/true, 7484 TPL_TemplateMatch)) 7485 OldTemplateParams = OldDecl->getTemplateParameters(); 7486 else 7487 Invalid = true; 7488 7489 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7490 if (!Invalid && 7491 !Context.hasSameType(OldTD->getUnderlyingType(), 7492 NewTD->getUnderlyingType())) { 7493 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7494 // but we can't reasonably accept it. 7495 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7496 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7497 if (OldTD->getLocation().isValid()) 7498 Diag(OldTD->getLocation(), diag::note_previous_definition); 7499 Invalid = true; 7500 } 7501 } 7502 } 7503 7504 // Merge any previous default template arguments into our parameters, 7505 // and check the parameter list. 7506 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7507 TPC_TypeAliasTemplate)) 7508 return 0; 7509 7510 TypeAliasTemplateDecl *NewDecl = 7511 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7512 Name.Identifier, TemplateParams, 7513 NewTD); 7514 7515 NewDecl->setAccess(AS); 7516 7517 if (Invalid) 7518 NewDecl->setInvalidDecl(); 7519 else if (OldDecl) 7520 NewDecl->setPreviousDeclaration(OldDecl); 7521 7522 NewND = NewDecl; 7523 } else { 7524 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7525 NewND = NewTD; 7526 } 7527 7528 if (!Redeclaration) 7529 PushOnScopeChains(NewND, S); 7530 7531 ActOnDocumentableDecl(NewND); 7532 return NewND; 7533} 7534 7535Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7536 SourceLocation NamespaceLoc, 7537 SourceLocation AliasLoc, 7538 IdentifierInfo *Alias, 7539 CXXScopeSpec &SS, 7540 SourceLocation IdentLoc, 7541 IdentifierInfo *Ident) { 7542 7543 // Lookup the namespace name. 7544 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7545 LookupParsedName(R, S, &SS); 7546 7547 // Check if we have a previous declaration with the same name. 7548 NamedDecl *PrevDecl 7549 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7550 ForRedeclaration); 7551 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7552 PrevDecl = 0; 7553 7554 if (PrevDecl) { 7555 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7556 // We already have an alias with the same name that points to the same 7557 // namespace, so don't create a new one. 7558 // FIXME: At some point, we'll want to create the (redundant) 7559 // declaration to maintain better source information. 7560 if (!R.isAmbiguous() && !R.empty() && 7561 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7562 return 0; 7563 } 7564 7565 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7566 diag::err_redefinition_different_kind; 7567 Diag(AliasLoc, DiagID) << Alias; 7568 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7569 return 0; 7570 } 7571 7572 if (R.isAmbiguous()) 7573 return 0; 7574 7575 if (R.empty()) { 7576 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 7577 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7578 return 0; 7579 } 7580 } 7581 7582 NamespaceAliasDecl *AliasDecl = 7583 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 7584 Alias, SS.getWithLocInContext(Context), 7585 IdentLoc, R.getFoundDecl()); 7586 7587 PushOnScopeChains(AliasDecl, S); 7588 return AliasDecl; 7589} 7590 7591Sema::ImplicitExceptionSpecification 7592Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 7593 CXXMethodDecl *MD) { 7594 CXXRecordDecl *ClassDecl = MD->getParent(); 7595 7596 // C++ [except.spec]p14: 7597 // An implicitly declared special member function (Clause 12) shall have an 7598 // exception-specification. [...] 7599 ImplicitExceptionSpecification ExceptSpec(*this); 7600 if (ClassDecl->isInvalidDecl()) 7601 return ExceptSpec; 7602 7603 // Direct base-class constructors. 7604 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7605 BEnd = ClassDecl->bases_end(); 7606 B != BEnd; ++B) { 7607 if (B->isVirtual()) // Handled below. 7608 continue; 7609 7610 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7611 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7612 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7613 // If this is a deleted function, add it anyway. This might be conformant 7614 // with the standard. This might not. I'm not sure. It might not matter. 7615 if (Constructor) 7616 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7617 } 7618 } 7619 7620 // Virtual base-class constructors. 7621 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7622 BEnd = ClassDecl->vbases_end(); 7623 B != BEnd; ++B) { 7624 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7625 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7626 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7627 // If this is a deleted function, add it anyway. This might be conformant 7628 // with the standard. This might not. I'm not sure. It might not matter. 7629 if (Constructor) 7630 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7631 } 7632 } 7633 7634 // Field constructors. 7635 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7636 FEnd = ClassDecl->field_end(); 7637 F != FEnd; ++F) { 7638 if (F->hasInClassInitializer()) { 7639 if (Expr *E = F->getInClassInitializer()) 7640 ExceptSpec.CalledExpr(E); 7641 else if (!F->isInvalidDecl()) 7642 // DR1351: 7643 // If the brace-or-equal-initializer of a non-static data member 7644 // invokes a defaulted default constructor of its class or of an 7645 // enclosing class in a potentially evaluated subexpression, the 7646 // program is ill-formed. 7647 // 7648 // This resolution is unworkable: the exception specification of the 7649 // default constructor can be needed in an unevaluated context, in 7650 // particular, in the operand of a noexcept-expression, and we can be 7651 // unable to compute an exception specification for an enclosed class. 7652 // 7653 // We do not allow an in-class initializer to require the evaluation 7654 // of the exception specification for any in-class initializer whose 7655 // definition is not lexically complete. 7656 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 7657 } else if (const RecordType *RecordTy 7658 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7659 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7660 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7661 // If this is a deleted function, add it anyway. This might be conformant 7662 // with the standard. This might not. I'm not sure. It might not matter. 7663 // In particular, the problem is that this function never gets called. It 7664 // might just be ill-formed because this function attempts to refer to 7665 // a deleted function here. 7666 if (Constructor) 7667 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7668 } 7669 } 7670 7671 return ExceptSpec; 7672} 7673 7674Sema::ImplicitExceptionSpecification 7675Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 7676 CXXRecordDecl *ClassDecl = CD->getParent(); 7677 7678 // C++ [except.spec]p14: 7679 // An inheriting constructor [...] shall have an exception-specification. [...] 7680 ImplicitExceptionSpecification ExceptSpec(*this); 7681 if (ClassDecl->isInvalidDecl()) 7682 return ExceptSpec; 7683 7684 // Inherited constructor. 7685 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 7686 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 7687 // FIXME: Copying or moving the parameters could add extra exceptions to the 7688 // set, as could the default arguments for the inherited constructor. This 7689 // will be addressed when we implement the resolution of core issue 1351. 7690 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 7691 7692 // Direct base-class constructors. 7693 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7694 BEnd = ClassDecl->bases_end(); 7695 B != BEnd; ++B) { 7696 if (B->isVirtual()) // Handled below. 7697 continue; 7698 7699 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7700 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7701 if (BaseClassDecl == InheritedDecl) 7702 continue; 7703 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7704 if (Constructor) 7705 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7706 } 7707 } 7708 7709 // Virtual base-class constructors. 7710 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7711 BEnd = ClassDecl->vbases_end(); 7712 B != BEnd; ++B) { 7713 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7714 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7715 if (BaseClassDecl == InheritedDecl) 7716 continue; 7717 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7718 if (Constructor) 7719 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7720 } 7721 } 7722 7723 // Field constructors. 7724 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7725 FEnd = ClassDecl->field_end(); 7726 F != FEnd; ++F) { 7727 if (F->hasInClassInitializer()) { 7728 if (Expr *E = F->getInClassInitializer()) 7729 ExceptSpec.CalledExpr(E); 7730 else if (!F->isInvalidDecl()) 7731 Diag(CD->getLocation(), 7732 diag::err_in_class_initializer_references_def_ctor) << CD; 7733 } else if (const RecordType *RecordTy 7734 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7735 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7736 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7737 if (Constructor) 7738 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7739 } 7740 } 7741 7742 return ExceptSpec; 7743} 7744 7745namespace { 7746/// RAII object to register a special member as being currently declared. 7747struct DeclaringSpecialMember { 7748 Sema &S; 7749 Sema::SpecialMemberDecl D; 7750 bool WasAlreadyBeingDeclared; 7751 7752 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 7753 : S(S), D(RD, CSM) { 7754 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 7755 if (WasAlreadyBeingDeclared) 7756 // This almost never happens, but if it does, ensure that our cache 7757 // doesn't contain a stale result. 7758 S.SpecialMemberCache.clear(); 7759 7760 // FIXME: Register a note to be produced if we encounter an error while 7761 // declaring the special member. 7762 } 7763 ~DeclaringSpecialMember() { 7764 if (!WasAlreadyBeingDeclared) 7765 S.SpecialMembersBeingDeclared.erase(D); 7766 } 7767 7768 /// \brief Are we already trying to declare this special member? 7769 bool isAlreadyBeingDeclared() const { 7770 return WasAlreadyBeingDeclared; 7771 } 7772}; 7773} 7774 7775CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 7776 CXXRecordDecl *ClassDecl) { 7777 // C++ [class.ctor]p5: 7778 // A default constructor for a class X is a constructor of class X 7779 // that can be called without an argument. If there is no 7780 // user-declared constructor for class X, a default constructor is 7781 // implicitly declared. An implicitly-declared default constructor 7782 // is an inline public member of its class. 7783 assert(ClassDecl->needsImplicitDefaultConstructor() && 7784 "Should not build implicit default constructor!"); 7785 7786 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 7787 if (DSM.isAlreadyBeingDeclared()) 7788 return 0; 7789 7790 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 7791 CXXDefaultConstructor, 7792 false); 7793 7794 // Create the actual constructor declaration. 7795 CanQualType ClassType 7796 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7797 SourceLocation ClassLoc = ClassDecl->getLocation(); 7798 DeclarationName Name 7799 = Context.DeclarationNames.getCXXConstructorName(ClassType); 7800 DeclarationNameInfo NameInfo(Name, ClassLoc); 7801 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 7802 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 7803 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 7804 Constexpr); 7805 DefaultCon->setAccess(AS_public); 7806 DefaultCon->setDefaulted(); 7807 DefaultCon->setImplicit(); 7808 7809 // Build an exception specification pointing back at this constructor. 7810 FunctionProtoType::ExtProtoInfo EPI; 7811 EPI.ExceptionSpecType = EST_Unevaluated; 7812 EPI.ExceptionSpecDecl = DefaultCon; 7813 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 7814 7815 // We don't need to use SpecialMemberIsTrivial here; triviality for default 7816 // constructors is easy to compute. 7817 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 7818 7819 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 7820 SetDeclDeleted(DefaultCon, ClassLoc); 7821 7822 // Note that we have declared this constructor. 7823 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 7824 7825 if (Scope *S = getScopeForContext(ClassDecl)) 7826 PushOnScopeChains(DefaultCon, S, false); 7827 ClassDecl->addDecl(DefaultCon); 7828 7829 return DefaultCon; 7830} 7831 7832void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 7833 CXXConstructorDecl *Constructor) { 7834 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 7835 !Constructor->doesThisDeclarationHaveABody() && 7836 !Constructor->isDeleted()) && 7837 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 7838 7839 CXXRecordDecl *ClassDecl = Constructor->getParent(); 7840 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 7841 7842 SynthesizedFunctionScope Scope(*this, Constructor); 7843 DiagnosticErrorTrap Trap(Diags); 7844 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 7845 Trap.hasErrorOccurred()) { 7846 Diag(CurrentLocation, diag::note_member_synthesized_at) 7847 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 7848 Constructor->setInvalidDecl(); 7849 return; 7850 } 7851 7852 SourceLocation Loc = Constructor->getLocation(); 7853 Constructor->setBody(new (Context) CompoundStmt(Loc)); 7854 7855 Constructor->setUsed(); 7856 MarkVTableUsed(CurrentLocation, ClassDecl); 7857 7858 if (ASTMutationListener *L = getASTMutationListener()) { 7859 L->CompletedImplicitDefinition(Constructor); 7860 } 7861} 7862 7863void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 7864 // Check that any explicitly-defaulted methods have exception specifications 7865 // compatible with their implicit exception specifications. 7866 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs(); 7867} 7868 7869namespace { 7870/// Information on inheriting constructors to declare. 7871class InheritingConstructorInfo { 7872public: 7873 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 7874 : SemaRef(SemaRef), Derived(Derived) { 7875 // Mark the constructors that we already have in the derived class. 7876 // 7877 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 7878 // unless there is a user-declared constructor with the same signature in 7879 // the class where the using-declaration appears. 7880 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 7881 } 7882 7883 void inheritAll(CXXRecordDecl *RD) { 7884 visitAll(RD, &InheritingConstructorInfo::inherit); 7885 } 7886 7887private: 7888 /// Information about an inheriting constructor. 7889 struct InheritingConstructor { 7890 InheritingConstructor() 7891 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {} 7892 7893 /// If \c true, a constructor with this signature is already declared 7894 /// in the derived class. 7895 bool DeclaredInDerived; 7896 7897 /// The constructor which is inherited. 7898 const CXXConstructorDecl *BaseCtor; 7899 7900 /// The derived constructor we declared. 7901 CXXConstructorDecl *DerivedCtor; 7902 }; 7903 7904 /// Inheriting constructors with a given canonical type. There can be at 7905 /// most one such non-template constructor, and any number of templated 7906 /// constructors. 7907 struct InheritingConstructorsForType { 7908 InheritingConstructor NonTemplate; 7909 llvm::SmallVector< 7910 std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates; 7911 7912 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 7913 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 7914 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 7915 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 7916 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 7917 false, S.TPL_TemplateMatch)) 7918 return Templates[I].second; 7919 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 7920 return Templates.back().second; 7921 } 7922 7923 return NonTemplate; 7924 } 7925 }; 7926 7927 /// Get or create the inheriting constructor record for a constructor. 7928 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 7929 QualType CtorType) { 7930 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 7931 .getEntry(SemaRef, Ctor); 7932 } 7933 7934 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 7935 7936 /// Process all constructors for a class. 7937 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 7938 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(), 7939 CtorE = RD->ctor_end(); 7940 CtorIt != CtorE; ++CtorIt) 7941 (this->*Callback)(*CtorIt); 7942 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 7943 I(RD->decls_begin()), E(RD->decls_end()); 7944 I != E; ++I) { 7945 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 7946 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 7947 (this->*Callback)(CD); 7948 } 7949 } 7950 7951 /// Note that a constructor (or constructor template) was declared in Derived. 7952 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 7953 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 7954 } 7955 7956 /// Inherit a single constructor. 7957 void inherit(const CXXConstructorDecl *Ctor) { 7958 const FunctionProtoType *CtorType = 7959 Ctor->getType()->castAs<FunctionProtoType>(); 7960 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes()); 7961 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 7962 7963 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 7964 7965 // Core issue (no number yet): the ellipsis is always discarded. 7966 if (EPI.Variadic) { 7967 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 7968 SemaRef.Diag(Ctor->getLocation(), 7969 diag::note_using_decl_constructor_ellipsis); 7970 EPI.Variadic = false; 7971 } 7972 7973 // Declare a constructor for each number of parameters. 7974 // 7975 // C++11 [class.inhctor]p1: 7976 // The candidate set of inherited constructors from the class X named in 7977 // the using-declaration consists of [... modulo defects ...] for each 7978 // constructor or constructor template of X, the set of constructors or 7979 // constructor templates that results from omitting any ellipsis parameter 7980 // specification and successively omitting parameters with a default 7981 // argument from the end of the parameter-type-list 7982 unsigned MinParams = minParamsToInherit(Ctor); 7983 unsigned Params = Ctor->getNumParams(); 7984 if (Params >= MinParams) { 7985 do 7986 declareCtor(UsingLoc, Ctor, 7987 SemaRef.Context.getFunctionType( 7988 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI)); 7989 while (Params > MinParams && 7990 Ctor->getParamDecl(--Params)->hasDefaultArg()); 7991 } 7992 } 7993 7994 /// Find the using-declaration which specified that we should inherit the 7995 /// constructors of \p Base. 7996 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 7997 // No fancy lookup required; just look for the base constructor name 7998 // directly within the derived class. 7999 ASTContext &Context = SemaRef.Context; 8000 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8001 Context.getCanonicalType(Context.getRecordType(Base))); 8002 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8003 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8004 } 8005 8006 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8007 // C++11 [class.inhctor]p3: 8008 // [F]or each constructor template in the candidate set of inherited 8009 // constructors, a constructor template is implicitly declared 8010 if (Ctor->getDescribedFunctionTemplate()) 8011 return 0; 8012 8013 // For each non-template constructor in the candidate set of inherited 8014 // constructors other than a constructor having no parameters or a 8015 // copy/move constructor having a single parameter, a constructor is 8016 // implicitly declared [...] 8017 if (Ctor->getNumParams() == 0) 8018 return 1; 8019 if (Ctor->isCopyOrMoveConstructor()) 8020 return 2; 8021 8022 // Per discussion on core reflector, never inherit a constructor which 8023 // would become a default, copy, or move constructor of Derived either. 8024 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8025 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8026 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8027 } 8028 8029 /// Declare a single inheriting constructor, inheriting the specified 8030 /// constructor, with the given type. 8031 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8032 QualType DerivedType) { 8033 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8034 8035 // C++11 [class.inhctor]p3: 8036 // ... a constructor is implicitly declared with the same constructor 8037 // characteristics unless there is a user-declared constructor with 8038 // the same signature in the class where the using-declaration appears 8039 if (Entry.DeclaredInDerived) 8040 return; 8041 8042 // C++11 [class.inhctor]p7: 8043 // If two using-declarations declare inheriting constructors with the 8044 // same signature, the program is ill-formed 8045 if (Entry.DerivedCtor) { 8046 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8047 // Only diagnose this once per constructor. 8048 if (Entry.DerivedCtor->isInvalidDecl()) 8049 return; 8050 Entry.DerivedCtor->setInvalidDecl(); 8051 8052 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8053 SemaRef.Diag(BaseCtor->getLocation(), 8054 diag::note_using_decl_constructor_conflict_current_ctor); 8055 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8056 diag::note_using_decl_constructor_conflict_previous_ctor); 8057 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8058 diag::note_using_decl_constructor_conflict_previous_using); 8059 } else { 8060 // Core issue (no number): if the same inheriting constructor is 8061 // produced by multiple base class constructors from the same base 8062 // class, the inheriting constructor is defined as deleted. 8063 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8064 } 8065 8066 return; 8067 } 8068 8069 ASTContext &Context = SemaRef.Context; 8070 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8071 Context.getCanonicalType(Context.getRecordType(Derived))); 8072 DeclarationNameInfo NameInfo(Name, UsingLoc); 8073 8074 TemplateParameterList *TemplateParams = 0; 8075 if (const FunctionTemplateDecl *FTD = 8076 BaseCtor->getDescribedFunctionTemplate()) { 8077 TemplateParams = FTD->getTemplateParameters(); 8078 // We're reusing template parameters from a different DeclContext. This 8079 // is questionable at best, but works out because the template depth in 8080 // both places is guaranteed to be 0. 8081 // FIXME: Rebuild the template parameters in the new context, and 8082 // transform the function type to refer to them. 8083 } 8084 8085 // Build type source info pointing at the using-declaration. This is 8086 // required by template instantiation. 8087 TypeSourceInfo *TInfo = 8088 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8089 FunctionProtoTypeLoc ProtoLoc = 8090 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8091 8092 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8093 Context, Derived, UsingLoc, NameInfo, DerivedType, 8094 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8095 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8096 8097 // Build an unevaluated exception specification for this constructor. 8098 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8099 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8100 EPI.ExceptionSpecType = EST_Unevaluated; 8101 EPI.ExceptionSpecDecl = DerivedCtor; 8102 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(), 8103 FPT->getArgTypes(), EPI)); 8104 8105 // Build the parameter declarations. 8106 SmallVector<ParmVarDecl *, 16> ParamDecls; 8107 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) { 8108 TypeSourceInfo *TInfo = 8109 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc); 8110 ParmVarDecl *PD = ParmVarDecl::Create( 8111 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0, 8112 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0); 8113 PD->setScopeInfo(0, I); 8114 PD->setImplicit(); 8115 ParamDecls.push_back(PD); 8116 ProtoLoc.setArg(I, PD); 8117 } 8118 8119 // Set up the new constructor. 8120 DerivedCtor->setAccess(BaseCtor->getAccess()); 8121 DerivedCtor->setParams(ParamDecls); 8122 DerivedCtor->setInheritedConstructor(BaseCtor); 8123 if (BaseCtor->isDeleted()) 8124 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8125 8126 // If this is a constructor template, build the template declaration. 8127 if (TemplateParams) { 8128 FunctionTemplateDecl *DerivedTemplate = 8129 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8130 TemplateParams, DerivedCtor); 8131 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8132 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8133 Derived->addDecl(DerivedTemplate); 8134 } else { 8135 Derived->addDecl(DerivedCtor); 8136 } 8137 8138 Entry.BaseCtor = BaseCtor; 8139 Entry.DerivedCtor = DerivedCtor; 8140 } 8141 8142 Sema &SemaRef; 8143 CXXRecordDecl *Derived; 8144 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8145 MapType Map; 8146}; 8147} 8148 8149void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8150 // Defer declaring the inheriting constructors until the class is 8151 // instantiated. 8152 if (ClassDecl->isDependentContext()) 8153 return; 8154 8155 // Find base classes from which we might inherit constructors. 8156 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8157 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 8158 BaseE = ClassDecl->bases_end(); 8159 BaseIt != BaseE; ++BaseIt) 8160 if (BaseIt->getInheritConstructors()) 8161 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl()); 8162 8163 // Go no further if we're not inheriting any constructors. 8164 if (InheritedBases.empty()) 8165 return; 8166 8167 // Declare the inherited constructors. 8168 InheritingConstructorInfo ICI(*this, ClassDecl); 8169 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8170 ICI.inheritAll(InheritedBases[I]); 8171} 8172 8173void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8174 CXXConstructorDecl *Constructor) { 8175 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8176 assert(Constructor->getInheritedConstructor() && 8177 !Constructor->doesThisDeclarationHaveABody() && 8178 !Constructor->isDeleted()); 8179 8180 SynthesizedFunctionScope Scope(*this, Constructor); 8181 DiagnosticErrorTrap Trap(Diags); 8182 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8183 Trap.hasErrorOccurred()) { 8184 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8185 << Context.getTagDeclType(ClassDecl); 8186 Constructor->setInvalidDecl(); 8187 return; 8188 } 8189 8190 SourceLocation Loc = Constructor->getLocation(); 8191 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8192 8193 Constructor->setUsed(); 8194 MarkVTableUsed(CurrentLocation, ClassDecl); 8195 8196 if (ASTMutationListener *L = getASTMutationListener()) { 8197 L->CompletedImplicitDefinition(Constructor); 8198 } 8199} 8200 8201 8202Sema::ImplicitExceptionSpecification 8203Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8204 CXXRecordDecl *ClassDecl = MD->getParent(); 8205 8206 // C++ [except.spec]p14: 8207 // An implicitly declared special member function (Clause 12) shall have 8208 // an exception-specification. 8209 ImplicitExceptionSpecification ExceptSpec(*this); 8210 if (ClassDecl->isInvalidDecl()) 8211 return ExceptSpec; 8212 8213 // Direct base-class destructors. 8214 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8215 BEnd = ClassDecl->bases_end(); 8216 B != BEnd; ++B) { 8217 if (B->isVirtual()) // Handled below. 8218 continue; 8219 8220 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8221 ExceptSpec.CalledDecl(B->getLocStart(), 8222 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8223 } 8224 8225 // Virtual base-class destructors. 8226 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8227 BEnd = ClassDecl->vbases_end(); 8228 B != BEnd; ++B) { 8229 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8230 ExceptSpec.CalledDecl(B->getLocStart(), 8231 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8232 } 8233 8234 // Field destructors. 8235 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8236 FEnd = ClassDecl->field_end(); 8237 F != FEnd; ++F) { 8238 if (const RecordType *RecordTy 8239 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8240 ExceptSpec.CalledDecl(F->getLocation(), 8241 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8242 } 8243 8244 return ExceptSpec; 8245} 8246 8247CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8248 // C++ [class.dtor]p2: 8249 // If a class has no user-declared destructor, a destructor is 8250 // declared implicitly. An implicitly-declared destructor is an 8251 // inline public member of its class. 8252 assert(ClassDecl->needsImplicitDestructor()); 8253 8254 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8255 if (DSM.isAlreadyBeingDeclared()) 8256 return 0; 8257 8258 // Create the actual destructor declaration. 8259 CanQualType ClassType 8260 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8261 SourceLocation ClassLoc = ClassDecl->getLocation(); 8262 DeclarationName Name 8263 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8264 DeclarationNameInfo NameInfo(Name, ClassLoc); 8265 CXXDestructorDecl *Destructor 8266 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8267 QualType(), 0, /*isInline=*/true, 8268 /*isImplicitlyDeclared=*/true); 8269 Destructor->setAccess(AS_public); 8270 Destructor->setDefaulted(); 8271 Destructor->setImplicit(); 8272 8273 // Build an exception specification pointing back at this destructor. 8274 FunctionProtoType::ExtProtoInfo EPI; 8275 EPI.ExceptionSpecType = EST_Unevaluated; 8276 EPI.ExceptionSpecDecl = Destructor; 8277 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8278 8279 AddOverriddenMethods(ClassDecl, Destructor); 8280 8281 // We don't need to use SpecialMemberIsTrivial here; triviality for 8282 // destructors is easy to compute. 8283 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8284 8285 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8286 SetDeclDeleted(Destructor, ClassLoc); 8287 8288 // Note that we have declared this destructor. 8289 ++ASTContext::NumImplicitDestructorsDeclared; 8290 8291 // Introduce this destructor into its scope. 8292 if (Scope *S = getScopeForContext(ClassDecl)) 8293 PushOnScopeChains(Destructor, S, false); 8294 ClassDecl->addDecl(Destructor); 8295 8296 return Destructor; 8297} 8298 8299void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8300 CXXDestructorDecl *Destructor) { 8301 assert((Destructor->isDefaulted() && 8302 !Destructor->doesThisDeclarationHaveABody() && 8303 !Destructor->isDeleted()) && 8304 "DefineImplicitDestructor - call it for implicit default dtor"); 8305 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8306 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8307 8308 if (Destructor->isInvalidDecl()) 8309 return; 8310 8311 SynthesizedFunctionScope Scope(*this, Destructor); 8312 8313 DiagnosticErrorTrap Trap(Diags); 8314 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8315 Destructor->getParent()); 8316 8317 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8318 Diag(CurrentLocation, diag::note_member_synthesized_at) 8319 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8320 8321 Destructor->setInvalidDecl(); 8322 return; 8323 } 8324 8325 SourceLocation Loc = Destructor->getLocation(); 8326 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8327 Destructor->setImplicitlyDefined(true); 8328 Destructor->setUsed(); 8329 MarkVTableUsed(CurrentLocation, ClassDecl); 8330 8331 if (ASTMutationListener *L = getASTMutationListener()) { 8332 L->CompletedImplicitDefinition(Destructor); 8333 } 8334} 8335 8336/// \brief Perform any semantic analysis which needs to be delayed until all 8337/// pending class member declarations have been parsed. 8338void Sema::ActOnFinishCXXMemberDecls() { 8339 // If the context is an invalid C++ class, just suppress these checks. 8340 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8341 if (Record->isInvalidDecl()) { 8342 DelayedDestructorExceptionSpecChecks.clear(); 8343 return; 8344 } 8345 } 8346 8347 // Perform any deferred checking of exception specifications for virtual 8348 // destructors. 8349 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size(); 8350 i != e; ++i) { 8351 const CXXDestructorDecl *Dtor = 8352 DelayedDestructorExceptionSpecChecks[i].first; 8353 assert(!Dtor->getParent()->isDependentType() && 8354 "Should not ever add destructors of templates into the list."); 8355 CheckOverridingFunctionExceptionSpec(Dtor, 8356 DelayedDestructorExceptionSpecChecks[i].second); 8357 } 8358 DelayedDestructorExceptionSpecChecks.clear(); 8359} 8360 8361void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8362 CXXDestructorDecl *Destructor) { 8363 assert(getLangOpts().CPlusPlus11 && 8364 "adjusting dtor exception specs was introduced in c++11"); 8365 8366 // C++11 [class.dtor]p3: 8367 // A declaration of a destructor that does not have an exception- 8368 // specification is implicitly considered to have the same exception- 8369 // specification as an implicit declaration. 8370 const FunctionProtoType *DtorType = Destructor->getType()-> 8371 getAs<FunctionProtoType>(); 8372 if (DtorType->hasExceptionSpec()) 8373 return; 8374 8375 // Replace the destructor's type, building off the existing one. Fortunately, 8376 // the only thing of interest in the destructor type is its extended info. 8377 // The return and arguments are fixed. 8378 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8379 EPI.ExceptionSpecType = EST_Unevaluated; 8380 EPI.ExceptionSpecDecl = Destructor; 8381 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8382 8383 // FIXME: If the destructor has a body that could throw, and the newly created 8384 // spec doesn't allow exceptions, we should emit a warning, because this 8385 // change in behavior can break conforming C++03 programs at runtime. 8386 // However, we don't have a body or an exception specification yet, so it 8387 // needs to be done somewhere else. 8388} 8389 8390/// When generating a defaulted copy or move assignment operator, if a field 8391/// should be copied with __builtin_memcpy rather than via explicit assignments, 8392/// do so. This optimization only applies for arrays of scalars, and for arrays 8393/// of class type where the selected copy/move-assignment operator is trivial. 8394static StmtResult 8395buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 8396 Expr *To, Expr *From) { 8397 // Compute the size of the memory buffer to be copied. 8398 QualType SizeType = S.Context.getSizeType(); 8399 llvm::APInt Size(S.Context.getTypeSize(SizeType), 8400 S.Context.getTypeSizeInChars(T).getQuantity()); 8401 8402 // Take the address of the field references for "from" and "to". We 8403 // directly construct UnaryOperators here because semantic analysis 8404 // does not permit us to take the address of an xvalue. 8405 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 8406 S.Context.getPointerType(From->getType()), 8407 VK_RValue, OK_Ordinary, Loc); 8408 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 8409 S.Context.getPointerType(To->getType()), 8410 VK_RValue, OK_Ordinary, Loc); 8411 8412 const Type *E = T->getBaseElementTypeUnsafe(); 8413 bool NeedsCollectableMemCpy = 8414 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 8415 8416 // Create a reference to the __builtin_objc_memmove_collectable function 8417 StringRef MemCpyName = NeedsCollectableMemCpy ? 8418 "__builtin_objc_memmove_collectable" : 8419 "__builtin_memcpy"; 8420 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 8421 Sema::LookupOrdinaryName); 8422 S.LookupName(R, S.TUScope, true); 8423 8424 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 8425 if (!MemCpy) 8426 // Something went horribly wrong earlier, and we will have complained 8427 // about it. 8428 return StmtError(); 8429 8430 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 8431 VK_RValue, Loc, 0); 8432 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 8433 8434 Expr *CallArgs[] = { 8435 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 8436 }; 8437 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(), 8438 Loc, CallArgs, Loc); 8439 8440 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8441 return S.Owned(Call.takeAs<Stmt>()); 8442} 8443 8444/// \brief Builds a statement that copies/moves the given entity from \p From to 8445/// \c To. 8446/// 8447/// This routine is used to copy/move the members of a class with an 8448/// implicitly-declared copy/move assignment operator. When the entities being 8449/// copied are arrays, this routine builds for loops to copy them. 8450/// 8451/// \param S The Sema object used for type-checking. 8452/// 8453/// \param Loc The location where the implicit copy/move is being generated. 8454/// 8455/// \param T The type of the expressions being copied/moved. Both expressions 8456/// must have this type. 8457/// 8458/// \param To The expression we are copying/moving to. 8459/// 8460/// \param From The expression we are copying/moving from. 8461/// 8462/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 8463/// Otherwise, it's a non-static member subobject. 8464/// 8465/// \param Copying Whether we're copying or moving. 8466/// 8467/// \param Depth Internal parameter recording the depth of the recursion. 8468/// 8469/// \returns A statement or a loop that copies the expressions, or StmtResult(0) 8470/// if a memcpy should be used instead. 8471static StmtResult 8472buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 8473 Expr *To, Expr *From, 8474 bool CopyingBaseSubobject, bool Copying, 8475 unsigned Depth = 0) { 8476 // C++11 [class.copy]p28: 8477 // Each subobject is assigned in the manner appropriate to its type: 8478 // 8479 // - if the subobject is of class type, as if by a call to operator= with 8480 // the subobject as the object expression and the corresponding 8481 // subobject of x as a single function argument (as if by explicit 8482 // qualification; that is, ignoring any possible virtual overriding 8483 // functions in more derived classes); 8484 // 8485 // C++03 [class.copy]p13: 8486 // - if the subobject is of class type, the copy assignment operator for 8487 // the class is used (as if by explicit qualification; that is, 8488 // ignoring any possible virtual overriding functions in more derived 8489 // classes); 8490 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 8491 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8492 8493 // Look for operator=. 8494 DeclarationName Name 8495 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8496 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 8497 S.LookupQualifiedName(OpLookup, ClassDecl, false); 8498 8499 // Prior to C++11, filter out any result that isn't a copy/move-assignment 8500 // operator. 8501 if (!S.getLangOpts().CPlusPlus11) { 8502 LookupResult::Filter F = OpLookup.makeFilter(); 8503 while (F.hasNext()) { 8504 NamedDecl *D = F.next(); 8505 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 8506 if (Method->isCopyAssignmentOperator() || 8507 (!Copying && Method->isMoveAssignmentOperator())) 8508 continue; 8509 8510 F.erase(); 8511 } 8512 F.done(); 8513 } 8514 8515 // Suppress the protected check (C++ [class.protected]) for each of the 8516 // assignment operators we found. This strange dance is required when 8517 // we're assigning via a base classes's copy-assignment operator. To 8518 // ensure that we're getting the right base class subobject (without 8519 // ambiguities), we need to cast "this" to that subobject type; to 8520 // ensure that we don't go through the virtual call mechanism, we need 8521 // to qualify the operator= name with the base class (see below). However, 8522 // this means that if the base class has a protected copy assignment 8523 // operator, the protected member access check will fail. So, we 8524 // rewrite "protected" access to "public" access in this case, since we 8525 // know by construction that we're calling from a derived class. 8526 if (CopyingBaseSubobject) { 8527 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 8528 L != LEnd; ++L) { 8529 if (L.getAccess() == AS_protected) 8530 L.setAccess(AS_public); 8531 } 8532 } 8533 8534 // Create the nested-name-specifier that will be used to qualify the 8535 // reference to operator=; this is required to suppress the virtual 8536 // call mechanism. 8537 CXXScopeSpec SS; 8538 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 8539 SS.MakeTrivial(S.Context, 8540 NestedNameSpecifier::Create(S.Context, 0, false, 8541 CanonicalT), 8542 Loc); 8543 8544 // Create the reference to operator=. 8545 ExprResult OpEqualRef 8546 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 8547 /*TemplateKWLoc=*/SourceLocation(), 8548 /*FirstQualifierInScope=*/0, 8549 OpLookup, 8550 /*TemplateArgs=*/0, 8551 /*SuppressQualifierCheck=*/true); 8552 if (OpEqualRef.isInvalid()) 8553 return StmtError(); 8554 8555 // Build the call to the assignment operator. 8556 8557 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 8558 OpEqualRef.takeAs<Expr>(), 8559 Loc, From, Loc); 8560 if (Call.isInvalid()) 8561 return StmtError(); 8562 8563 // If we built a call to a trivial 'operator=' while copying an array, 8564 // bail out. We'll replace the whole shebang with a memcpy. 8565 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 8566 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 8567 return StmtResult((Stmt*)0); 8568 8569 // Convert to an expression-statement, and clean up any produced 8570 // temporaries. 8571 return S.ActOnExprStmt(Call); 8572 } 8573 8574 // - if the subobject is of scalar type, the built-in assignment 8575 // operator is used. 8576 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 8577 if (!ArrayTy) { 8578 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 8579 if (Assignment.isInvalid()) 8580 return StmtError(); 8581 return S.ActOnExprStmt(Assignment); 8582 } 8583 8584 // - if the subobject is an array, each element is assigned, in the 8585 // manner appropriate to the element type; 8586 8587 // Construct a loop over the array bounds, e.g., 8588 // 8589 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 8590 // 8591 // that will copy each of the array elements. 8592 QualType SizeType = S.Context.getSizeType(); 8593 8594 // Create the iteration variable. 8595 IdentifierInfo *IterationVarName = 0; 8596 { 8597 SmallString<8> Str; 8598 llvm::raw_svector_ostream OS(Str); 8599 OS << "__i" << Depth; 8600 IterationVarName = &S.Context.Idents.get(OS.str()); 8601 } 8602 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 8603 IterationVarName, SizeType, 8604 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 8605 SC_None); 8606 8607 // Initialize the iteration variable to zero. 8608 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8609 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8610 8611 // Create a reference to the iteration variable; we'll use this several 8612 // times throughout. 8613 Expr *IterationVarRef 8614 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take(); 8615 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 8616 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take(); 8617 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!"); 8618 8619 // Create the DeclStmt that holds the iteration variable. 8620 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 8621 8622 // Subscript the "from" and "to" expressions with the iteration variable. 8623 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 8624 IterationVarRefRVal, 8625 Loc)); 8626 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 8627 IterationVarRefRVal, 8628 Loc)); 8629 if (!Copying) // Cast to rvalue 8630 From = CastForMoving(S, From); 8631 8632 // Build the copy/move for an individual element of the array. 8633 StmtResult Copy = 8634 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 8635 To, From, CopyingBaseSubobject, 8636 Copying, Depth + 1); 8637 // Bail out if copying fails or if we determined that we should use memcpy. 8638 if (Copy.isInvalid() || !Copy.get()) 8639 return Copy; 8640 8641 // Create the comparison against the array bound. 8642 llvm::APInt Upper 8643 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 8644 Expr *Comparison 8645 = new (S.Context) BinaryOperator(IterationVarRefRVal, 8646 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 8647 BO_NE, S.Context.BoolTy, 8648 VK_RValue, OK_Ordinary, Loc, false); 8649 8650 // Create the pre-increment of the iteration variable. 8651 Expr *Increment 8652 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 8653 VK_LValue, OK_Ordinary, Loc); 8654 8655 // Construct the loop that copies all elements of this array. 8656 return S.ActOnForStmt(Loc, Loc, InitStmt, 8657 S.MakeFullExpr(Comparison), 8658 0, S.MakeFullDiscardedValueExpr(Increment), 8659 Loc, Copy.take()); 8660} 8661 8662static StmtResult 8663buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 8664 Expr *To, Expr *From, 8665 bool CopyingBaseSubobject, bool Copying) { 8666 // Maybe we should use a memcpy? 8667 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 8668 T.isTriviallyCopyableType(S.Context)) 8669 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8670 8671 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 8672 CopyingBaseSubobject, 8673 Copying, 0)); 8674 8675 // If we ended up picking a trivial assignment operator for an array of a 8676 // non-trivially-copyable class type, just emit a memcpy. 8677 if (!Result.isInvalid() && !Result.get()) 8678 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 8679 8680 return Result; 8681} 8682 8683Sema::ImplicitExceptionSpecification 8684Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 8685 CXXRecordDecl *ClassDecl = MD->getParent(); 8686 8687 ImplicitExceptionSpecification ExceptSpec(*this); 8688 if (ClassDecl->isInvalidDecl()) 8689 return ExceptSpec; 8690 8691 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 8692 assert(T->getNumArgs() == 1 && "not a copy assignment op"); 8693 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 8694 8695 // C++ [except.spec]p14: 8696 // An implicitly declared special member function (Clause 12) shall have an 8697 // exception-specification. [...] 8698 8699 // It is unspecified whether or not an implicit copy assignment operator 8700 // attempts to deduplicate calls to assignment operators of virtual bases are 8701 // made. As such, this exception specification is effectively unspecified. 8702 // Based on a similar decision made for constness in C++0x, we're erring on 8703 // the side of assuming such calls to be made regardless of whether they 8704 // actually happen. 8705 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8706 BaseEnd = ClassDecl->bases_end(); 8707 Base != BaseEnd; ++Base) { 8708 if (Base->isVirtual()) 8709 continue; 8710 8711 CXXRecordDecl *BaseClassDecl 8712 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8713 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8714 ArgQuals, false, 0)) 8715 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8716 } 8717 8718 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8719 BaseEnd = ClassDecl->vbases_end(); 8720 Base != BaseEnd; ++Base) { 8721 CXXRecordDecl *BaseClassDecl 8722 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8723 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 8724 ArgQuals, false, 0)) 8725 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 8726 } 8727 8728 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8729 FieldEnd = ClassDecl->field_end(); 8730 Field != FieldEnd; 8731 ++Field) { 8732 QualType FieldType = Context.getBaseElementType(Field->getType()); 8733 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8734 if (CXXMethodDecl *CopyAssign = 8735 LookupCopyingAssignment(FieldClassDecl, 8736 ArgQuals | FieldType.getCVRQualifiers(), 8737 false, 0)) 8738 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 8739 } 8740 } 8741 8742 return ExceptSpec; 8743} 8744 8745CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 8746 // Note: The following rules are largely analoguous to the copy 8747 // constructor rules. Note that virtual bases are not taken into account 8748 // for determining the argument type of the operator. Note also that 8749 // operators taking an object instead of a reference are allowed. 8750 assert(ClassDecl->needsImplicitCopyAssignment()); 8751 8752 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 8753 if (DSM.isAlreadyBeingDeclared()) 8754 return 0; 8755 8756 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8757 QualType RetType = Context.getLValueReferenceType(ArgType); 8758 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 8759 if (Const) 8760 ArgType = ArgType.withConst(); 8761 ArgType = Context.getLValueReferenceType(ArgType); 8762 8763 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8764 CXXCopyAssignment, 8765 Const); 8766 8767 // An implicitly-declared copy assignment operator is an inline public 8768 // member of its class. 8769 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8770 SourceLocation ClassLoc = ClassDecl->getLocation(); 8771 DeclarationNameInfo NameInfo(Name, ClassLoc); 8772 CXXMethodDecl *CopyAssignment = 8773 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 8774 /*TInfo=*/ 0, /*StorageClass=*/ SC_None, 8775 /*isInline=*/ true, Constexpr, SourceLocation()); 8776 CopyAssignment->setAccess(AS_public); 8777 CopyAssignment->setDefaulted(); 8778 CopyAssignment->setImplicit(); 8779 8780 // Build an exception specification pointing back at this member. 8781 FunctionProtoType::ExtProtoInfo EPI; 8782 EPI.ExceptionSpecType = EST_Unevaluated; 8783 EPI.ExceptionSpecDecl = CopyAssignment; 8784 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 8785 8786 // Add the parameter to the operator. 8787 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 8788 ClassLoc, ClassLoc, /*Id=*/0, 8789 ArgType, /*TInfo=*/0, 8790 SC_None, 0); 8791 CopyAssignment->setParams(FromParam); 8792 8793 AddOverriddenMethods(ClassDecl, CopyAssignment); 8794 8795 CopyAssignment->setTrivial( 8796 ClassDecl->needsOverloadResolutionForCopyAssignment() 8797 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 8798 : ClassDecl->hasTrivialCopyAssignment()); 8799 8800 // C++11 [class.copy]p19: 8801 // .... If the class definition does not explicitly declare a copy 8802 // assignment operator, there is no user-declared move constructor, and 8803 // there is no user-declared move assignment operator, a copy assignment 8804 // operator is implicitly declared as defaulted. 8805 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 8806 SetDeclDeleted(CopyAssignment, ClassLoc); 8807 8808 // Note that we have added this copy-assignment operator. 8809 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 8810 8811 if (Scope *S = getScopeForContext(ClassDecl)) 8812 PushOnScopeChains(CopyAssignment, S, false); 8813 ClassDecl->addDecl(CopyAssignment); 8814 8815 return CopyAssignment; 8816} 8817 8818void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 8819 CXXMethodDecl *CopyAssignOperator) { 8820 assert((CopyAssignOperator->isDefaulted() && 8821 CopyAssignOperator->isOverloadedOperator() && 8822 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 8823 !CopyAssignOperator->doesThisDeclarationHaveABody() && 8824 !CopyAssignOperator->isDeleted()) && 8825 "DefineImplicitCopyAssignment called for wrong function"); 8826 8827 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 8828 8829 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 8830 CopyAssignOperator->setInvalidDecl(); 8831 return; 8832 } 8833 8834 CopyAssignOperator->setUsed(); 8835 8836 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 8837 DiagnosticErrorTrap Trap(Diags); 8838 8839 // C++0x [class.copy]p30: 8840 // The implicitly-defined or explicitly-defaulted copy assignment operator 8841 // for a non-union class X performs memberwise copy assignment of its 8842 // subobjects. The direct base classes of X are assigned first, in the 8843 // order of their declaration in the base-specifier-list, and then the 8844 // immediate non-static data members of X are assigned, in the order in 8845 // which they were declared in the class definition. 8846 8847 // The statements that form the synthesized function body. 8848 SmallVector<Stmt*, 8> Statements; 8849 8850 // The parameter for the "other" object, which we are copying from. 8851 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 8852 Qualifiers OtherQuals = Other->getType().getQualifiers(); 8853 QualType OtherRefType = Other->getType(); 8854 if (const LValueReferenceType *OtherRef 8855 = OtherRefType->getAs<LValueReferenceType>()) { 8856 OtherRefType = OtherRef->getPointeeType(); 8857 OtherQuals = OtherRefType.getQualifiers(); 8858 } 8859 8860 // Our location for everything implicitly-generated. 8861 SourceLocation Loc = CopyAssignOperator->getLocation(); 8862 8863 // Construct a reference to the "other" object. We'll be using this 8864 // throughout the generated ASTs. 8865 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8866 assert(OtherRef && "Reference to parameter cannot fail!"); 8867 8868 // Construct the "this" pointer. We'll be using this throughout the generated 8869 // ASTs. 8870 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8871 assert(This && "Reference to this cannot fail!"); 8872 8873 // Assign base classes. 8874 bool Invalid = false; 8875 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8876 E = ClassDecl->bases_end(); Base != E; ++Base) { 8877 // Form the assignment: 8878 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 8879 QualType BaseType = Base->getType().getUnqualifiedType(); 8880 if (!BaseType->isRecordType()) { 8881 Invalid = true; 8882 continue; 8883 } 8884 8885 CXXCastPath BasePath; 8886 BasePath.push_back(Base); 8887 8888 // Construct the "from" expression, which is an implicit cast to the 8889 // appropriately-qualified base type. 8890 Expr *From = OtherRef; 8891 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 8892 CK_UncheckedDerivedToBase, 8893 VK_LValue, &BasePath).take(); 8894 8895 // Dereference "this". 8896 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8897 8898 // Implicitly cast "this" to the appropriately-qualified base type. 8899 To = ImpCastExprToType(To.take(), 8900 Context.getCVRQualifiedType(BaseType, 8901 CopyAssignOperator->getTypeQualifiers()), 8902 CK_UncheckedDerivedToBase, 8903 VK_LValue, &BasePath); 8904 8905 // Build the copy. 8906 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 8907 To.get(), From, 8908 /*CopyingBaseSubobject=*/true, 8909 /*Copying=*/true); 8910 if (Copy.isInvalid()) { 8911 Diag(CurrentLocation, diag::note_member_synthesized_at) 8912 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8913 CopyAssignOperator->setInvalidDecl(); 8914 return; 8915 } 8916 8917 // Success! Record the copy. 8918 Statements.push_back(Copy.takeAs<Expr>()); 8919 } 8920 8921 // Assign non-static members. 8922 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8923 FieldEnd = ClassDecl->field_end(); 8924 Field != FieldEnd; ++Field) { 8925 if (Field->isUnnamedBitfield()) 8926 continue; 8927 8928 if (Field->isInvalidDecl()) { 8929 Invalid = true; 8930 continue; 8931 } 8932 8933 // Check for members of reference type; we can't copy those. 8934 if (Field->getType()->isReferenceType()) { 8935 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8936 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8937 Diag(Field->getLocation(), diag::note_declared_at); 8938 Diag(CurrentLocation, diag::note_member_synthesized_at) 8939 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8940 Invalid = true; 8941 continue; 8942 } 8943 8944 // Check for members of const-qualified, non-class type. 8945 QualType BaseType = Context.getBaseElementType(Field->getType()); 8946 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8947 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8948 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8949 Diag(Field->getLocation(), diag::note_declared_at); 8950 Diag(CurrentLocation, diag::note_member_synthesized_at) 8951 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8952 Invalid = true; 8953 continue; 8954 } 8955 8956 // Suppress assigning zero-width bitfields. 8957 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 8958 continue; 8959 8960 QualType FieldType = Field->getType().getNonReferenceType(); 8961 if (FieldType->isIncompleteArrayType()) { 8962 assert(ClassDecl->hasFlexibleArrayMember() && 8963 "Incomplete array type is not valid"); 8964 continue; 8965 } 8966 8967 // Build references to the field in the object we're copying from and to. 8968 CXXScopeSpec SS; // Intentionally empty 8969 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8970 LookupMemberName); 8971 MemberLookup.addDecl(*Field); 8972 MemberLookup.resolveKind(); 8973 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8974 Loc, /*IsArrow=*/false, 8975 SS, SourceLocation(), 0, 8976 MemberLookup, 0); 8977 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8978 Loc, /*IsArrow=*/true, 8979 SS, SourceLocation(), 0, 8980 MemberLookup, 0); 8981 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8982 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8983 8984 // Build the copy of this field. 8985 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 8986 To.get(), From.get(), 8987 /*CopyingBaseSubobject=*/false, 8988 /*Copying=*/true); 8989 if (Copy.isInvalid()) { 8990 Diag(CurrentLocation, diag::note_member_synthesized_at) 8991 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 8992 CopyAssignOperator->setInvalidDecl(); 8993 return; 8994 } 8995 8996 // Success! Record the copy. 8997 Statements.push_back(Copy.takeAs<Stmt>()); 8998 } 8999 9000 if (!Invalid) { 9001 // Add a "return *this;" 9002 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9003 9004 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9005 if (Return.isInvalid()) 9006 Invalid = true; 9007 else { 9008 Statements.push_back(Return.takeAs<Stmt>()); 9009 9010 if (Trap.hasErrorOccurred()) { 9011 Diag(CurrentLocation, diag::note_member_synthesized_at) 9012 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9013 Invalid = true; 9014 } 9015 } 9016 } 9017 9018 if (Invalid) { 9019 CopyAssignOperator->setInvalidDecl(); 9020 return; 9021 } 9022 9023 StmtResult Body; 9024 { 9025 CompoundScopeRAII CompoundScope(*this); 9026 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9027 /*isStmtExpr=*/false); 9028 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9029 } 9030 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 9031 9032 if (ASTMutationListener *L = getASTMutationListener()) { 9033 L->CompletedImplicitDefinition(CopyAssignOperator); 9034 } 9035} 9036 9037Sema::ImplicitExceptionSpecification 9038Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9039 CXXRecordDecl *ClassDecl = MD->getParent(); 9040 9041 ImplicitExceptionSpecification ExceptSpec(*this); 9042 if (ClassDecl->isInvalidDecl()) 9043 return ExceptSpec; 9044 9045 // C++0x [except.spec]p14: 9046 // An implicitly declared special member function (Clause 12) shall have an 9047 // exception-specification. [...] 9048 9049 // It is unspecified whether or not an implicit move assignment operator 9050 // attempts to deduplicate calls to assignment operators of virtual bases are 9051 // made. As such, this exception specification is effectively unspecified. 9052 // Based on a similar decision made for constness in C++0x, we're erring on 9053 // the side of assuming such calls to be made regardless of whether they 9054 // actually happen. 9055 // Note that a move constructor is not implicitly declared when there are 9056 // virtual bases, but it can still be user-declared and explicitly defaulted. 9057 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9058 BaseEnd = ClassDecl->bases_end(); 9059 Base != BaseEnd; ++Base) { 9060 if (Base->isVirtual()) 9061 continue; 9062 9063 CXXRecordDecl *BaseClassDecl 9064 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9065 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9066 0, false, 0)) 9067 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9068 } 9069 9070 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9071 BaseEnd = ClassDecl->vbases_end(); 9072 Base != BaseEnd; ++Base) { 9073 CXXRecordDecl *BaseClassDecl 9074 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9075 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9076 0, false, 0)) 9077 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9078 } 9079 9080 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9081 FieldEnd = ClassDecl->field_end(); 9082 Field != FieldEnd; 9083 ++Field) { 9084 QualType FieldType = Context.getBaseElementType(Field->getType()); 9085 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9086 if (CXXMethodDecl *MoveAssign = 9087 LookupMovingAssignment(FieldClassDecl, 9088 FieldType.getCVRQualifiers(), 9089 false, 0)) 9090 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 9091 } 9092 } 9093 9094 return ExceptSpec; 9095} 9096 9097/// Determine whether the class type has any direct or indirect virtual base 9098/// classes which have a non-trivial move assignment operator. 9099static bool 9100hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) { 9101 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9102 BaseEnd = ClassDecl->vbases_end(); 9103 Base != BaseEnd; ++Base) { 9104 CXXRecordDecl *BaseClass = 9105 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9106 9107 // Try to declare the move assignment. If it would be deleted, then the 9108 // class does not have a non-trivial move assignment. 9109 if (BaseClass->needsImplicitMoveAssignment()) 9110 S.DeclareImplicitMoveAssignment(BaseClass); 9111 9112 if (BaseClass->hasNonTrivialMoveAssignment()) 9113 return true; 9114 } 9115 9116 return false; 9117} 9118 9119/// Determine whether the given type either has a move constructor or is 9120/// trivially copyable. 9121static bool 9122hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) { 9123 Type = S.Context.getBaseElementType(Type); 9124 9125 // FIXME: Technically, non-trivially-copyable non-class types, such as 9126 // reference types, are supposed to return false here, but that appears 9127 // to be a standard defect. 9128 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl(); 9129 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl()) 9130 return true; 9131 9132 if (Type.isTriviallyCopyableType(S.Context)) 9133 return true; 9134 9135 if (IsConstructor) { 9136 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to 9137 // give the right answer. 9138 if (ClassDecl->needsImplicitMoveConstructor()) 9139 S.DeclareImplicitMoveConstructor(ClassDecl); 9140 return ClassDecl->hasMoveConstructor(); 9141 } 9142 9143 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to 9144 // give the right answer. 9145 if (ClassDecl->needsImplicitMoveAssignment()) 9146 S.DeclareImplicitMoveAssignment(ClassDecl); 9147 return ClassDecl->hasMoveAssignment(); 9148} 9149 9150/// Determine whether all non-static data members and direct or virtual bases 9151/// of class \p ClassDecl have either a move operation, or are trivially 9152/// copyable. 9153static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl, 9154 bool IsConstructor) { 9155 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9156 BaseEnd = ClassDecl->bases_end(); 9157 Base != BaseEnd; ++Base) { 9158 if (Base->isVirtual()) 9159 continue; 9160 9161 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9162 return false; 9163 } 9164 9165 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9166 BaseEnd = ClassDecl->vbases_end(); 9167 Base != BaseEnd; ++Base) { 9168 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9169 return false; 9170 } 9171 9172 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9173 FieldEnd = ClassDecl->field_end(); 9174 Field != FieldEnd; ++Field) { 9175 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor)) 9176 return false; 9177 } 9178 9179 return true; 9180} 9181 9182CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9183 // C++11 [class.copy]p20: 9184 // If the definition of a class X does not explicitly declare a move 9185 // assignment operator, one will be implicitly declared as defaulted 9186 // if and only if: 9187 // 9188 // - [first 4 bullets] 9189 assert(ClassDecl->needsImplicitMoveAssignment()); 9190 9191 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9192 if (DSM.isAlreadyBeingDeclared()) 9193 return 0; 9194 9195 // [Checked after we build the declaration] 9196 // - the move assignment operator would not be implicitly defined as 9197 // deleted, 9198 9199 // [DR1402]: 9200 // - X has no direct or indirect virtual base class with a non-trivial 9201 // move assignment operator, and 9202 // - each of X's non-static data members and direct or virtual base classes 9203 // has a type that either has a move assignment operator or is trivially 9204 // copyable. 9205 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) || 9206 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) { 9207 ClassDecl->setFailedImplicitMoveAssignment(); 9208 return 0; 9209 } 9210 9211 // Note: The following rules are largely analoguous to the move 9212 // constructor rules. 9213 9214 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9215 QualType RetType = Context.getLValueReferenceType(ArgType); 9216 ArgType = Context.getRValueReferenceType(ArgType); 9217 9218 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9219 CXXMoveAssignment, 9220 false); 9221 9222 // An implicitly-declared move assignment operator is an inline public 9223 // member of its class. 9224 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9225 SourceLocation ClassLoc = ClassDecl->getLocation(); 9226 DeclarationNameInfo NameInfo(Name, ClassLoc); 9227 CXXMethodDecl *MoveAssignment = 9228 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9229 /*TInfo=*/0, /*StorageClass=*/SC_None, 9230 /*isInline=*/true, Constexpr, SourceLocation()); 9231 MoveAssignment->setAccess(AS_public); 9232 MoveAssignment->setDefaulted(); 9233 MoveAssignment->setImplicit(); 9234 9235 // Build an exception specification pointing back at this member. 9236 FunctionProtoType::ExtProtoInfo EPI; 9237 EPI.ExceptionSpecType = EST_Unevaluated; 9238 EPI.ExceptionSpecDecl = MoveAssignment; 9239 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9240 9241 // Add the parameter to the operator. 9242 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9243 ClassLoc, ClassLoc, /*Id=*/0, 9244 ArgType, /*TInfo=*/0, 9245 SC_None, 0); 9246 MoveAssignment->setParams(FromParam); 9247 9248 AddOverriddenMethods(ClassDecl, MoveAssignment); 9249 9250 MoveAssignment->setTrivial( 9251 ClassDecl->needsOverloadResolutionForMoveAssignment() 9252 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9253 : ClassDecl->hasTrivialMoveAssignment()); 9254 9255 // C++0x [class.copy]p9: 9256 // If the definition of a class X does not explicitly declare a move 9257 // assignment operator, one will be implicitly declared as defaulted if and 9258 // only if: 9259 // [...] 9260 // - the move assignment operator would not be implicitly defined as 9261 // deleted. 9262 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9263 // Cache this result so that we don't try to generate this over and over 9264 // on every lookup, leaking memory and wasting time. 9265 ClassDecl->setFailedImplicitMoveAssignment(); 9266 return 0; 9267 } 9268 9269 // Note that we have added this copy-assignment operator. 9270 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9271 9272 if (Scope *S = getScopeForContext(ClassDecl)) 9273 PushOnScopeChains(MoveAssignment, S, false); 9274 ClassDecl->addDecl(MoveAssignment); 9275 9276 return MoveAssignment; 9277} 9278 9279void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 9280 CXXMethodDecl *MoveAssignOperator) { 9281 assert((MoveAssignOperator->isDefaulted() && 9282 MoveAssignOperator->isOverloadedOperator() && 9283 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 9284 !MoveAssignOperator->doesThisDeclarationHaveABody() && 9285 !MoveAssignOperator->isDeleted()) && 9286 "DefineImplicitMoveAssignment called for wrong function"); 9287 9288 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 9289 9290 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 9291 MoveAssignOperator->setInvalidDecl(); 9292 return; 9293 } 9294 9295 MoveAssignOperator->setUsed(); 9296 9297 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 9298 DiagnosticErrorTrap Trap(Diags); 9299 9300 // C++0x [class.copy]p28: 9301 // The implicitly-defined or move assignment operator for a non-union class 9302 // X performs memberwise move assignment of its subobjects. The direct base 9303 // classes of X are assigned first, in the order of their declaration in the 9304 // base-specifier-list, and then the immediate non-static data members of X 9305 // are assigned, in the order in which they were declared in the class 9306 // definition. 9307 9308 // The statements that form the synthesized function body. 9309 SmallVector<Stmt*, 8> Statements; 9310 9311 // The parameter for the "other" object, which we are move from. 9312 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 9313 QualType OtherRefType = Other->getType()-> 9314 getAs<RValueReferenceType>()->getPointeeType(); 9315 assert(!OtherRefType.getQualifiers() && 9316 "Bad argument type of defaulted move assignment"); 9317 9318 // Our location for everything implicitly-generated. 9319 SourceLocation Loc = MoveAssignOperator->getLocation(); 9320 9321 // Construct a reference to the "other" object. We'll be using this 9322 // throughout the generated ASTs. 9323 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 9324 assert(OtherRef && "Reference to parameter cannot fail!"); 9325 // Cast to rvalue. 9326 OtherRef = CastForMoving(*this, OtherRef); 9327 9328 // Construct the "this" pointer. We'll be using this throughout the generated 9329 // ASTs. 9330 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 9331 assert(This && "Reference to this cannot fail!"); 9332 9333 // Assign base classes. 9334 bool Invalid = false; 9335 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9336 E = ClassDecl->bases_end(); Base != E; ++Base) { 9337 // Form the assignment: 9338 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 9339 QualType BaseType = Base->getType().getUnqualifiedType(); 9340 if (!BaseType->isRecordType()) { 9341 Invalid = true; 9342 continue; 9343 } 9344 9345 CXXCastPath BasePath; 9346 BasePath.push_back(Base); 9347 9348 // Construct the "from" expression, which is an implicit cast to the 9349 // appropriately-qualified base type. 9350 Expr *From = OtherRef; 9351 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase, 9352 VK_XValue, &BasePath).take(); 9353 9354 // Dereference "this". 9355 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9356 9357 // Implicitly cast "this" to the appropriately-qualified base type. 9358 To = ImpCastExprToType(To.take(), 9359 Context.getCVRQualifiedType(BaseType, 9360 MoveAssignOperator->getTypeQualifiers()), 9361 CK_UncheckedDerivedToBase, 9362 VK_LValue, &BasePath); 9363 9364 // Build the move. 9365 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 9366 To.get(), From, 9367 /*CopyingBaseSubobject=*/true, 9368 /*Copying=*/false); 9369 if (Move.isInvalid()) { 9370 Diag(CurrentLocation, diag::note_member_synthesized_at) 9371 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9372 MoveAssignOperator->setInvalidDecl(); 9373 return; 9374 } 9375 9376 // Success! Record the move. 9377 Statements.push_back(Move.takeAs<Expr>()); 9378 } 9379 9380 // Assign non-static members. 9381 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9382 FieldEnd = ClassDecl->field_end(); 9383 Field != FieldEnd; ++Field) { 9384 if (Field->isUnnamedBitfield()) 9385 continue; 9386 9387 if (Field->isInvalidDecl()) { 9388 Invalid = true; 9389 continue; 9390 } 9391 9392 // Check for members of reference type; we can't move those. 9393 if (Field->getType()->isReferenceType()) { 9394 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9395 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9396 Diag(Field->getLocation(), diag::note_declared_at); 9397 Diag(CurrentLocation, diag::note_member_synthesized_at) 9398 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9399 Invalid = true; 9400 continue; 9401 } 9402 9403 // Check for members of const-qualified, non-class type. 9404 QualType BaseType = Context.getBaseElementType(Field->getType()); 9405 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9406 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9407 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9408 Diag(Field->getLocation(), diag::note_declared_at); 9409 Diag(CurrentLocation, diag::note_member_synthesized_at) 9410 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9411 Invalid = true; 9412 continue; 9413 } 9414 9415 // Suppress assigning zero-width bitfields. 9416 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9417 continue; 9418 9419 QualType FieldType = Field->getType().getNonReferenceType(); 9420 if (FieldType->isIncompleteArrayType()) { 9421 assert(ClassDecl->hasFlexibleArrayMember() && 9422 "Incomplete array type is not valid"); 9423 continue; 9424 } 9425 9426 // Build references to the field in the object we're copying from and to. 9427 CXXScopeSpec SS; // Intentionally empty 9428 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9429 LookupMemberName); 9430 MemberLookup.addDecl(*Field); 9431 MemberLookup.resolveKind(); 9432 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 9433 Loc, /*IsArrow=*/false, 9434 SS, SourceLocation(), 0, 9435 MemberLookup, 0); 9436 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 9437 Loc, /*IsArrow=*/true, 9438 SS, SourceLocation(), 0, 9439 MemberLookup, 0); 9440 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 9441 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 9442 9443 assert(!From.get()->isLValue() && // could be xvalue or prvalue 9444 "Member reference with rvalue base must be rvalue except for reference " 9445 "members, which aren't allowed for move assignment."); 9446 9447 // Build the move of this field. 9448 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 9449 To.get(), From.get(), 9450 /*CopyingBaseSubobject=*/false, 9451 /*Copying=*/false); 9452 if (Move.isInvalid()) { 9453 Diag(CurrentLocation, diag::note_member_synthesized_at) 9454 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9455 MoveAssignOperator->setInvalidDecl(); 9456 return; 9457 } 9458 9459 // Success! Record the copy. 9460 Statements.push_back(Move.takeAs<Stmt>()); 9461 } 9462 9463 if (!Invalid) { 9464 // Add a "return *this;" 9465 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 9466 9467 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9468 if (Return.isInvalid()) 9469 Invalid = true; 9470 else { 9471 Statements.push_back(Return.takeAs<Stmt>()); 9472 9473 if (Trap.hasErrorOccurred()) { 9474 Diag(CurrentLocation, diag::note_member_synthesized_at) 9475 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9476 Invalid = true; 9477 } 9478 } 9479 } 9480 9481 if (Invalid) { 9482 MoveAssignOperator->setInvalidDecl(); 9483 return; 9484 } 9485 9486 StmtResult Body; 9487 { 9488 CompoundScopeRAII CompoundScope(*this); 9489 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9490 /*isStmtExpr=*/false); 9491 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9492 } 9493 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 9494 9495 if (ASTMutationListener *L = getASTMutationListener()) { 9496 L->CompletedImplicitDefinition(MoveAssignOperator); 9497 } 9498} 9499 9500Sema::ImplicitExceptionSpecification 9501Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 9502 CXXRecordDecl *ClassDecl = MD->getParent(); 9503 9504 ImplicitExceptionSpecification ExceptSpec(*this); 9505 if (ClassDecl->isInvalidDecl()) 9506 return ExceptSpec; 9507 9508 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9509 assert(T->getNumArgs() >= 1 && "not a copy ctor"); 9510 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 9511 9512 // C++ [except.spec]p14: 9513 // An implicitly declared special member function (Clause 12) shall have an 9514 // exception-specification. [...] 9515 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9516 BaseEnd = ClassDecl->bases_end(); 9517 Base != BaseEnd; 9518 ++Base) { 9519 // Virtual bases are handled below. 9520 if (Base->isVirtual()) 9521 continue; 9522 9523 CXXRecordDecl *BaseClassDecl 9524 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9525 if (CXXConstructorDecl *CopyConstructor = 9526 LookupCopyingConstructor(BaseClassDecl, Quals)) 9527 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9528 } 9529 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9530 BaseEnd = ClassDecl->vbases_end(); 9531 Base != BaseEnd; 9532 ++Base) { 9533 CXXRecordDecl *BaseClassDecl 9534 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9535 if (CXXConstructorDecl *CopyConstructor = 9536 LookupCopyingConstructor(BaseClassDecl, Quals)) 9537 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 9538 } 9539 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9540 FieldEnd = ClassDecl->field_end(); 9541 Field != FieldEnd; 9542 ++Field) { 9543 QualType FieldType = Context.getBaseElementType(Field->getType()); 9544 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9545 if (CXXConstructorDecl *CopyConstructor = 9546 LookupCopyingConstructor(FieldClassDecl, 9547 Quals | FieldType.getCVRQualifiers())) 9548 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 9549 } 9550 } 9551 9552 return ExceptSpec; 9553} 9554 9555CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 9556 CXXRecordDecl *ClassDecl) { 9557 // C++ [class.copy]p4: 9558 // If the class definition does not explicitly declare a copy 9559 // constructor, one is declared implicitly. 9560 assert(ClassDecl->needsImplicitCopyConstructor()); 9561 9562 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 9563 if (DSM.isAlreadyBeingDeclared()) 9564 return 0; 9565 9566 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9567 QualType ArgType = ClassType; 9568 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 9569 if (Const) 9570 ArgType = ArgType.withConst(); 9571 ArgType = Context.getLValueReferenceType(ArgType); 9572 9573 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9574 CXXCopyConstructor, 9575 Const); 9576 9577 DeclarationName Name 9578 = Context.DeclarationNames.getCXXConstructorName( 9579 Context.getCanonicalType(ClassType)); 9580 SourceLocation ClassLoc = ClassDecl->getLocation(); 9581 DeclarationNameInfo NameInfo(Name, ClassLoc); 9582 9583 // An implicitly-declared copy constructor is an inline public 9584 // member of its class. 9585 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 9586 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9587 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9588 Constexpr); 9589 CopyConstructor->setAccess(AS_public); 9590 CopyConstructor->setDefaulted(); 9591 9592 // Build an exception specification pointing back at this member. 9593 FunctionProtoType::ExtProtoInfo EPI; 9594 EPI.ExceptionSpecType = EST_Unevaluated; 9595 EPI.ExceptionSpecDecl = CopyConstructor; 9596 CopyConstructor->setType( 9597 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 9598 9599 // Add the parameter to the constructor. 9600 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 9601 ClassLoc, ClassLoc, 9602 /*IdentifierInfo=*/0, 9603 ArgType, /*TInfo=*/0, 9604 SC_None, 0); 9605 CopyConstructor->setParams(FromParam); 9606 9607 CopyConstructor->setTrivial( 9608 ClassDecl->needsOverloadResolutionForCopyConstructor() 9609 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 9610 : ClassDecl->hasTrivialCopyConstructor()); 9611 9612 // C++11 [class.copy]p8: 9613 // ... If the class definition does not explicitly declare a copy 9614 // constructor, there is no user-declared move constructor, and there is no 9615 // user-declared move assignment operator, a copy constructor is implicitly 9616 // declared as defaulted. 9617 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 9618 SetDeclDeleted(CopyConstructor, ClassLoc); 9619 9620 // Note that we have declared this constructor. 9621 ++ASTContext::NumImplicitCopyConstructorsDeclared; 9622 9623 if (Scope *S = getScopeForContext(ClassDecl)) 9624 PushOnScopeChains(CopyConstructor, S, false); 9625 ClassDecl->addDecl(CopyConstructor); 9626 9627 return CopyConstructor; 9628} 9629 9630void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 9631 CXXConstructorDecl *CopyConstructor) { 9632 assert((CopyConstructor->isDefaulted() && 9633 CopyConstructor->isCopyConstructor() && 9634 !CopyConstructor->doesThisDeclarationHaveABody() && 9635 !CopyConstructor->isDeleted()) && 9636 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 9637 9638 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 9639 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 9640 9641 SynthesizedFunctionScope Scope(*this, CopyConstructor); 9642 DiagnosticErrorTrap Trap(Diags); 9643 9644 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 9645 Trap.hasErrorOccurred()) { 9646 Diag(CurrentLocation, diag::note_member_synthesized_at) 9647 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 9648 CopyConstructor->setInvalidDecl(); 9649 } else { 9650 Sema::CompoundScopeRAII CompoundScope(*this); 9651 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 9652 CopyConstructor->getLocation(), 9653 MultiStmtArg(), 9654 /*isStmtExpr=*/false) 9655 .takeAs<Stmt>()); 9656 CopyConstructor->setImplicitlyDefined(true); 9657 } 9658 9659 CopyConstructor->setUsed(); 9660 if (ASTMutationListener *L = getASTMutationListener()) { 9661 L->CompletedImplicitDefinition(CopyConstructor); 9662 } 9663} 9664 9665Sema::ImplicitExceptionSpecification 9666Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 9667 CXXRecordDecl *ClassDecl = MD->getParent(); 9668 9669 // C++ [except.spec]p14: 9670 // An implicitly declared special member function (Clause 12) shall have an 9671 // exception-specification. [...] 9672 ImplicitExceptionSpecification ExceptSpec(*this); 9673 if (ClassDecl->isInvalidDecl()) 9674 return ExceptSpec; 9675 9676 // Direct base-class constructors. 9677 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 9678 BEnd = ClassDecl->bases_end(); 9679 B != BEnd; ++B) { 9680 if (B->isVirtual()) // Handled below. 9681 continue; 9682 9683 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9684 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9685 CXXConstructorDecl *Constructor = 9686 LookupMovingConstructor(BaseClassDecl, 0); 9687 // If this is a deleted function, add it anyway. This might be conformant 9688 // with the standard. This might not. I'm not sure. It might not matter. 9689 if (Constructor) 9690 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9691 } 9692 } 9693 9694 // Virtual base-class constructors. 9695 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 9696 BEnd = ClassDecl->vbases_end(); 9697 B != BEnd; ++B) { 9698 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 9699 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 9700 CXXConstructorDecl *Constructor = 9701 LookupMovingConstructor(BaseClassDecl, 0); 9702 // If this is a deleted function, add it anyway. This might be conformant 9703 // with the standard. This might not. I'm not sure. It might not matter. 9704 if (Constructor) 9705 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 9706 } 9707 } 9708 9709 // Field constructors. 9710 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 9711 FEnd = ClassDecl->field_end(); 9712 F != FEnd; ++F) { 9713 QualType FieldType = Context.getBaseElementType(F->getType()); 9714 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 9715 CXXConstructorDecl *Constructor = 9716 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 9717 // If this is a deleted function, add it anyway. This might be conformant 9718 // with the standard. This might not. I'm not sure. It might not matter. 9719 // In particular, the problem is that this function never gets called. It 9720 // might just be ill-formed because this function attempts to refer to 9721 // a deleted function here. 9722 if (Constructor) 9723 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 9724 } 9725 } 9726 9727 return ExceptSpec; 9728} 9729 9730CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 9731 CXXRecordDecl *ClassDecl) { 9732 // C++11 [class.copy]p9: 9733 // If the definition of a class X does not explicitly declare a move 9734 // constructor, one will be implicitly declared as defaulted if and only if: 9735 // 9736 // - [first 4 bullets] 9737 assert(ClassDecl->needsImplicitMoveConstructor()); 9738 9739 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 9740 if (DSM.isAlreadyBeingDeclared()) 9741 return 0; 9742 9743 // [Checked after we build the declaration] 9744 // - the move assignment operator would not be implicitly defined as 9745 // deleted, 9746 9747 // [DR1402]: 9748 // - each of X's non-static data members and direct or virtual base classes 9749 // has a type that either has a move constructor or is trivially copyable. 9750 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) { 9751 ClassDecl->setFailedImplicitMoveConstructor(); 9752 return 0; 9753 } 9754 9755 QualType ClassType = Context.getTypeDeclType(ClassDecl); 9756 QualType ArgType = Context.getRValueReferenceType(ClassType); 9757 9758 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9759 CXXMoveConstructor, 9760 false); 9761 9762 DeclarationName Name 9763 = Context.DeclarationNames.getCXXConstructorName( 9764 Context.getCanonicalType(ClassType)); 9765 SourceLocation ClassLoc = ClassDecl->getLocation(); 9766 DeclarationNameInfo NameInfo(Name, ClassLoc); 9767 9768 // C++11 [class.copy]p11: 9769 // An implicitly-declared copy/move constructor is an inline public 9770 // member of its class. 9771 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 9772 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 9773 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 9774 Constexpr); 9775 MoveConstructor->setAccess(AS_public); 9776 MoveConstructor->setDefaulted(); 9777 9778 // Build an exception specification pointing back at this member. 9779 FunctionProtoType::ExtProtoInfo EPI; 9780 EPI.ExceptionSpecType = EST_Unevaluated; 9781 EPI.ExceptionSpecDecl = MoveConstructor; 9782 MoveConstructor->setType( 9783 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 9784 9785 // Add the parameter to the constructor. 9786 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 9787 ClassLoc, ClassLoc, 9788 /*IdentifierInfo=*/0, 9789 ArgType, /*TInfo=*/0, 9790 SC_None, 0); 9791 MoveConstructor->setParams(FromParam); 9792 9793 MoveConstructor->setTrivial( 9794 ClassDecl->needsOverloadResolutionForMoveConstructor() 9795 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 9796 : ClassDecl->hasTrivialMoveConstructor()); 9797 9798 // C++0x [class.copy]p9: 9799 // If the definition of a class X does not explicitly declare a move 9800 // constructor, one will be implicitly declared as defaulted if and only if: 9801 // [...] 9802 // - the move constructor would not be implicitly defined as deleted. 9803 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 9804 // Cache this result so that we don't try to generate this over and over 9805 // on every lookup, leaking memory and wasting time. 9806 ClassDecl->setFailedImplicitMoveConstructor(); 9807 return 0; 9808 } 9809 9810 // Note that we have declared this constructor. 9811 ++ASTContext::NumImplicitMoveConstructorsDeclared; 9812 9813 if (Scope *S = getScopeForContext(ClassDecl)) 9814 PushOnScopeChains(MoveConstructor, S, false); 9815 ClassDecl->addDecl(MoveConstructor); 9816 9817 return MoveConstructor; 9818} 9819 9820void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 9821 CXXConstructorDecl *MoveConstructor) { 9822 assert((MoveConstructor->isDefaulted() && 9823 MoveConstructor->isMoveConstructor() && 9824 !MoveConstructor->doesThisDeclarationHaveABody() && 9825 !MoveConstructor->isDeleted()) && 9826 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 9827 9828 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 9829 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 9830 9831 SynthesizedFunctionScope Scope(*this, MoveConstructor); 9832 DiagnosticErrorTrap Trap(Diags); 9833 9834 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 9835 Trap.hasErrorOccurred()) { 9836 Diag(CurrentLocation, diag::note_member_synthesized_at) 9837 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 9838 MoveConstructor->setInvalidDecl(); 9839 } else { 9840 Sema::CompoundScopeRAII CompoundScope(*this); 9841 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(), 9842 MoveConstructor->getLocation(), 9843 MultiStmtArg(), 9844 /*isStmtExpr=*/false) 9845 .takeAs<Stmt>()); 9846 MoveConstructor->setImplicitlyDefined(true); 9847 } 9848 9849 MoveConstructor->setUsed(); 9850 9851 if (ASTMutationListener *L = getASTMutationListener()) { 9852 L->CompletedImplicitDefinition(MoveConstructor); 9853 } 9854} 9855 9856bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 9857 return FD->isDeleted() && 9858 (FD->isDefaulted() || FD->isImplicit()) && 9859 isa<CXXMethodDecl>(FD); 9860} 9861 9862/// \brief Mark the call operator of the given lambda closure type as "used". 9863static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) { 9864 CXXMethodDecl *CallOperator 9865 = cast<CXXMethodDecl>( 9866 Lambda->lookup( 9867 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); 9868 CallOperator->setReferenced(); 9869 CallOperator->setUsed(); 9870} 9871 9872void Sema::DefineImplicitLambdaToFunctionPointerConversion( 9873 SourceLocation CurrentLocation, 9874 CXXConversionDecl *Conv) 9875{ 9876 CXXRecordDecl *Lambda = Conv->getParent(); 9877 9878 // Make sure that the lambda call operator is marked used. 9879 markLambdaCallOperatorUsed(*this, Lambda); 9880 9881 Conv->setUsed(); 9882 9883 SynthesizedFunctionScope Scope(*this, Conv); 9884 DiagnosticErrorTrap Trap(Diags); 9885 9886 // Return the address of the __invoke function. 9887 DeclarationName InvokeName = &Context.Idents.get("__invoke"); 9888 CXXMethodDecl *Invoke 9889 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front()); 9890 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(), 9891 VK_LValue, Conv->getLocation()).take(); 9892 assert(FunctionRef && "Can't refer to __invoke function?"); 9893 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 9894 Conv->setBody(new (Context) CompoundStmt(Context, Return, 9895 Conv->getLocation(), 9896 Conv->getLocation())); 9897 9898 // Fill in the __invoke function with a dummy implementation. IR generation 9899 // will fill in the actual details. 9900 Invoke->setUsed(); 9901 Invoke->setReferenced(); 9902 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation())); 9903 9904 if (ASTMutationListener *L = getASTMutationListener()) { 9905 L->CompletedImplicitDefinition(Conv); 9906 L->CompletedImplicitDefinition(Invoke); 9907 } 9908} 9909 9910void Sema::DefineImplicitLambdaToBlockPointerConversion( 9911 SourceLocation CurrentLocation, 9912 CXXConversionDecl *Conv) 9913{ 9914 Conv->setUsed(); 9915 9916 SynthesizedFunctionScope Scope(*this, Conv); 9917 DiagnosticErrorTrap Trap(Diags); 9918 9919 // Copy-initialize the lambda object as needed to capture it. 9920 Expr *This = ActOnCXXThis(CurrentLocation).take(); 9921 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 9922 9923 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 9924 Conv->getLocation(), 9925 Conv, DerefThis); 9926 9927 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 9928 // behavior. Note that only the general conversion function does this 9929 // (since it's unusable otherwise); in the case where we inline the 9930 // block literal, it has block literal lifetime semantics. 9931 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 9932 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 9933 CK_CopyAndAutoreleaseBlockObject, 9934 BuildBlock.get(), 0, VK_RValue); 9935 9936 if (BuildBlock.isInvalid()) { 9937 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9938 Conv->setInvalidDecl(); 9939 return; 9940 } 9941 9942 // Create the return statement that returns the block from the conversion 9943 // function. 9944 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 9945 if (Return.isInvalid()) { 9946 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 9947 Conv->setInvalidDecl(); 9948 return; 9949 } 9950 9951 // Set the body of the conversion function. 9952 Stmt *ReturnS = Return.take(); 9953 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 9954 Conv->getLocation(), 9955 Conv->getLocation())); 9956 9957 // We're done; notify the mutation listener, if any. 9958 if (ASTMutationListener *L = getASTMutationListener()) { 9959 L->CompletedImplicitDefinition(Conv); 9960 } 9961} 9962 9963/// \brief Determine whether the given list arguments contains exactly one 9964/// "real" (non-default) argument. 9965static bool hasOneRealArgument(MultiExprArg Args) { 9966 switch (Args.size()) { 9967 case 0: 9968 return false; 9969 9970 default: 9971 if (!Args[1]->isDefaultArgument()) 9972 return false; 9973 9974 // fall through 9975 case 1: 9976 return !Args[0]->isDefaultArgument(); 9977 } 9978 9979 return false; 9980} 9981 9982ExprResult 9983Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9984 CXXConstructorDecl *Constructor, 9985 MultiExprArg ExprArgs, 9986 bool HadMultipleCandidates, 9987 bool IsListInitialization, 9988 bool RequiresZeroInit, 9989 unsigned ConstructKind, 9990 SourceRange ParenRange) { 9991 bool Elidable = false; 9992 9993 // C++0x [class.copy]p34: 9994 // When certain criteria are met, an implementation is allowed to 9995 // omit the copy/move construction of a class object, even if the 9996 // copy/move constructor and/or destructor for the object have 9997 // side effects. [...] 9998 // - when a temporary class object that has not been bound to a 9999 // reference (12.2) would be copied/moved to a class object 10000 // with the same cv-unqualified type, the copy/move operation 10001 // can be omitted by constructing the temporary object 10002 // directly into the target of the omitted copy/move 10003 if (ConstructKind == CXXConstructExpr::CK_Complete && 10004 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10005 Expr *SubExpr = ExprArgs[0]; 10006 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10007 } 10008 10009 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10010 Elidable, ExprArgs, HadMultipleCandidates, 10011 IsListInitialization, RequiresZeroInit, 10012 ConstructKind, ParenRange); 10013} 10014 10015/// BuildCXXConstructExpr - Creates a complete call to a constructor, 10016/// including handling of its default argument expressions. 10017ExprResult 10018Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10019 CXXConstructorDecl *Constructor, bool Elidable, 10020 MultiExprArg ExprArgs, 10021 bool HadMultipleCandidates, 10022 bool IsListInitialization, 10023 bool RequiresZeroInit, 10024 unsigned ConstructKind, 10025 SourceRange ParenRange) { 10026 MarkFunctionReferenced(ConstructLoc, Constructor); 10027 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 10028 Constructor, Elidable, ExprArgs, 10029 HadMultipleCandidates, 10030 IsListInitialization, RequiresZeroInit, 10031 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10032 ParenRange)); 10033} 10034 10035void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10036 if (VD->isInvalidDecl()) return; 10037 10038 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10039 if (ClassDecl->isInvalidDecl()) return; 10040 if (ClassDecl->hasIrrelevantDestructor()) return; 10041 if (ClassDecl->isDependentContext()) return; 10042 10043 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10044 MarkFunctionReferenced(VD->getLocation(), Destructor); 10045 CheckDestructorAccess(VD->getLocation(), Destructor, 10046 PDiag(diag::err_access_dtor_var) 10047 << VD->getDeclName() 10048 << VD->getType()); 10049 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10050 10051 if (!VD->hasGlobalStorage()) return; 10052 10053 // Emit warning for non-trivial dtor in global scope (a real global, 10054 // class-static, function-static). 10055 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10056 10057 // TODO: this should be re-enabled for static locals by !CXAAtExit 10058 if (!VD->isStaticLocal()) 10059 Diag(VD->getLocation(), diag::warn_global_destructor); 10060} 10061 10062/// \brief Given a constructor and the set of arguments provided for the 10063/// constructor, convert the arguments and add any required default arguments 10064/// to form a proper call to this constructor. 10065/// 10066/// \returns true if an error occurred, false otherwise. 10067bool 10068Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10069 MultiExprArg ArgsPtr, 10070 SourceLocation Loc, 10071 SmallVectorImpl<Expr*> &ConvertedArgs, 10072 bool AllowExplicit, 10073 bool IsListInitialization) { 10074 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10075 unsigned NumArgs = ArgsPtr.size(); 10076 Expr **Args = ArgsPtr.data(); 10077 10078 const FunctionProtoType *Proto 10079 = Constructor->getType()->getAs<FunctionProtoType>(); 10080 assert(Proto && "Constructor without a prototype?"); 10081 unsigned NumArgsInProto = Proto->getNumArgs(); 10082 10083 // If too few arguments are available, we'll fill in the rest with defaults. 10084 if (NumArgs < NumArgsInProto) 10085 ConvertedArgs.reserve(NumArgsInProto); 10086 else 10087 ConvertedArgs.reserve(NumArgs); 10088 10089 VariadicCallType CallType = 10090 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10091 SmallVector<Expr *, 8> AllArgs; 10092 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10093 Proto, 0, 10094 llvm::makeArrayRef(Args, NumArgs), 10095 AllArgs, 10096 CallType, AllowExplicit, 10097 IsListInitialization); 10098 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 10099 10100 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 10101 10102 CheckConstructorCall(Constructor, 10103 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 10104 AllArgs.size()), 10105 Proto, Loc); 10106 10107 return Invalid; 10108} 10109 10110static inline bool 10111CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 10112 const FunctionDecl *FnDecl) { 10113 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 10114 if (isa<NamespaceDecl>(DC)) { 10115 return SemaRef.Diag(FnDecl->getLocation(), 10116 diag::err_operator_new_delete_declared_in_namespace) 10117 << FnDecl->getDeclName(); 10118 } 10119 10120 if (isa<TranslationUnitDecl>(DC) && 10121 FnDecl->getStorageClass() == SC_Static) { 10122 return SemaRef.Diag(FnDecl->getLocation(), 10123 diag::err_operator_new_delete_declared_static) 10124 << FnDecl->getDeclName(); 10125 } 10126 10127 return false; 10128} 10129 10130static inline bool 10131CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 10132 CanQualType ExpectedResultType, 10133 CanQualType ExpectedFirstParamType, 10134 unsigned DependentParamTypeDiag, 10135 unsigned InvalidParamTypeDiag) { 10136 QualType ResultType = 10137 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 10138 10139 // Check that the result type is not dependent. 10140 if (ResultType->isDependentType()) 10141 return SemaRef.Diag(FnDecl->getLocation(), 10142 diag::err_operator_new_delete_dependent_result_type) 10143 << FnDecl->getDeclName() << ExpectedResultType; 10144 10145 // Check that the result type is what we expect. 10146 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 10147 return SemaRef.Diag(FnDecl->getLocation(), 10148 diag::err_operator_new_delete_invalid_result_type) 10149 << FnDecl->getDeclName() << ExpectedResultType; 10150 10151 // A function template must have at least 2 parameters. 10152 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 10153 return SemaRef.Diag(FnDecl->getLocation(), 10154 diag::err_operator_new_delete_template_too_few_parameters) 10155 << FnDecl->getDeclName(); 10156 10157 // The function decl must have at least 1 parameter. 10158 if (FnDecl->getNumParams() == 0) 10159 return SemaRef.Diag(FnDecl->getLocation(), 10160 diag::err_operator_new_delete_too_few_parameters) 10161 << FnDecl->getDeclName(); 10162 10163 // Check the first parameter type is not dependent. 10164 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10165 if (FirstParamType->isDependentType()) 10166 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10167 << FnDecl->getDeclName() << ExpectedFirstParamType; 10168 10169 // Check that the first parameter type is what we expect. 10170 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10171 ExpectedFirstParamType) 10172 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10173 << FnDecl->getDeclName() << ExpectedFirstParamType; 10174 10175 return false; 10176} 10177 10178static bool 10179CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10180 // C++ [basic.stc.dynamic.allocation]p1: 10181 // A program is ill-formed if an allocation function is declared in a 10182 // namespace scope other than global scope or declared static in global 10183 // scope. 10184 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10185 return true; 10186 10187 CanQualType SizeTy = 10188 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10189 10190 // C++ [basic.stc.dynamic.allocation]p1: 10191 // The return type shall be void*. The first parameter shall have type 10192 // std::size_t. 10193 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10194 SizeTy, 10195 diag::err_operator_new_dependent_param_type, 10196 diag::err_operator_new_param_type)) 10197 return true; 10198 10199 // C++ [basic.stc.dynamic.allocation]p1: 10200 // The first parameter shall not have an associated default argument. 10201 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10202 return SemaRef.Diag(FnDecl->getLocation(), 10203 diag::err_operator_new_default_arg) 10204 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10205 10206 return false; 10207} 10208 10209static bool 10210CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10211 // C++ [basic.stc.dynamic.deallocation]p1: 10212 // A program is ill-formed if deallocation functions are declared in a 10213 // namespace scope other than global scope or declared static in global 10214 // scope. 10215 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10216 return true; 10217 10218 // C++ [basic.stc.dynamic.deallocation]p2: 10219 // Each deallocation function shall return void and its first parameter 10220 // shall be void*. 10221 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10222 SemaRef.Context.VoidPtrTy, 10223 diag::err_operator_delete_dependent_param_type, 10224 diag::err_operator_delete_param_type)) 10225 return true; 10226 10227 return false; 10228} 10229 10230/// CheckOverloadedOperatorDeclaration - Check whether the declaration 10231/// of this overloaded operator is well-formed. If so, returns false; 10232/// otherwise, emits appropriate diagnostics and returns true. 10233bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10234 assert(FnDecl && FnDecl->isOverloadedOperator() && 10235 "Expected an overloaded operator declaration"); 10236 10237 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10238 10239 // C++ [over.oper]p5: 10240 // The allocation and deallocation functions, operator new, 10241 // operator new[], operator delete and operator delete[], are 10242 // described completely in 3.7.3. The attributes and restrictions 10243 // found in the rest of this subclause do not apply to them unless 10244 // explicitly stated in 3.7.3. 10245 if (Op == OO_Delete || Op == OO_Array_Delete) 10246 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10247 10248 if (Op == OO_New || Op == OO_Array_New) 10249 return CheckOperatorNewDeclaration(*this, FnDecl); 10250 10251 // C++ [over.oper]p6: 10252 // An operator function shall either be a non-static member 10253 // function or be a non-member function and have at least one 10254 // parameter whose type is a class, a reference to a class, an 10255 // enumeration, or a reference to an enumeration. 10256 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 10257 if (MethodDecl->isStatic()) 10258 return Diag(FnDecl->getLocation(), 10259 diag::err_operator_overload_static) << FnDecl->getDeclName(); 10260 } else { 10261 bool ClassOrEnumParam = false; 10262 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10263 ParamEnd = FnDecl->param_end(); 10264 Param != ParamEnd; ++Param) { 10265 QualType ParamType = (*Param)->getType().getNonReferenceType(); 10266 if (ParamType->isDependentType() || ParamType->isRecordType() || 10267 ParamType->isEnumeralType()) { 10268 ClassOrEnumParam = true; 10269 break; 10270 } 10271 } 10272 10273 if (!ClassOrEnumParam) 10274 return Diag(FnDecl->getLocation(), 10275 diag::err_operator_overload_needs_class_or_enum) 10276 << FnDecl->getDeclName(); 10277 } 10278 10279 // C++ [over.oper]p8: 10280 // An operator function cannot have default arguments (8.3.6), 10281 // except where explicitly stated below. 10282 // 10283 // Only the function-call operator allows default arguments 10284 // (C++ [over.call]p1). 10285 if (Op != OO_Call) { 10286 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10287 Param != FnDecl->param_end(); ++Param) { 10288 if ((*Param)->hasDefaultArg()) 10289 return Diag((*Param)->getLocation(), 10290 diag::err_operator_overload_default_arg) 10291 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 10292 } 10293 } 10294 10295 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 10296 { false, false, false } 10297#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 10298 , { Unary, Binary, MemberOnly } 10299#include "clang/Basic/OperatorKinds.def" 10300 }; 10301 10302 bool CanBeUnaryOperator = OperatorUses[Op][0]; 10303 bool CanBeBinaryOperator = OperatorUses[Op][1]; 10304 bool MustBeMemberOperator = OperatorUses[Op][2]; 10305 10306 // C++ [over.oper]p8: 10307 // [...] Operator functions cannot have more or fewer parameters 10308 // than the number required for the corresponding operator, as 10309 // described in the rest of this subclause. 10310 unsigned NumParams = FnDecl->getNumParams() 10311 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 10312 if (Op != OO_Call && 10313 ((NumParams == 1 && !CanBeUnaryOperator) || 10314 (NumParams == 2 && !CanBeBinaryOperator) || 10315 (NumParams < 1) || (NumParams > 2))) { 10316 // We have the wrong number of parameters. 10317 unsigned ErrorKind; 10318 if (CanBeUnaryOperator && CanBeBinaryOperator) { 10319 ErrorKind = 2; // 2 -> unary or binary. 10320 } else if (CanBeUnaryOperator) { 10321 ErrorKind = 0; // 0 -> unary 10322 } else { 10323 assert(CanBeBinaryOperator && 10324 "All non-call overloaded operators are unary or binary!"); 10325 ErrorKind = 1; // 1 -> binary 10326 } 10327 10328 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 10329 << FnDecl->getDeclName() << NumParams << ErrorKind; 10330 } 10331 10332 // Overloaded operators other than operator() cannot be variadic. 10333 if (Op != OO_Call && 10334 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 10335 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 10336 << FnDecl->getDeclName(); 10337 } 10338 10339 // Some operators must be non-static member functions. 10340 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 10341 return Diag(FnDecl->getLocation(), 10342 diag::err_operator_overload_must_be_member) 10343 << FnDecl->getDeclName(); 10344 } 10345 10346 // C++ [over.inc]p1: 10347 // The user-defined function called operator++ implements the 10348 // prefix and postfix ++ operator. If this function is a member 10349 // function with no parameters, or a non-member function with one 10350 // parameter of class or enumeration type, it defines the prefix 10351 // increment operator ++ for objects of that type. If the function 10352 // is a member function with one parameter (which shall be of type 10353 // int) or a non-member function with two parameters (the second 10354 // of which shall be of type int), it defines the postfix 10355 // increment operator ++ for objects of that type. 10356 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 10357 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 10358 bool ParamIsInt = false; 10359 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 10360 ParamIsInt = BT->getKind() == BuiltinType::Int; 10361 10362 if (!ParamIsInt) 10363 return Diag(LastParam->getLocation(), 10364 diag::err_operator_overload_post_incdec_must_be_int) 10365 << LastParam->getType() << (Op == OO_MinusMinus); 10366 } 10367 10368 return false; 10369} 10370 10371/// CheckLiteralOperatorDeclaration - Check whether the declaration 10372/// of this literal operator function is well-formed. If so, returns 10373/// false; otherwise, emits appropriate diagnostics and returns true. 10374bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 10375 if (isa<CXXMethodDecl>(FnDecl)) { 10376 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 10377 << FnDecl->getDeclName(); 10378 return true; 10379 } 10380 10381 if (FnDecl->isExternC()) { 10382 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 10383 return true; 10384 } 10385 10386 bool Valid = false; 10387 10388 // This might be the definition of a literal operator template. 10389 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 10390 // This might be a specialization of a literal operator template. 10391 if (!TpDecl) 10392 TpDecl = FnDecl->getPrimaryTemplate(); 10393 10394 // template <char...> type operator "" name() is the only valid template 10395 // signature, and the only valid signature with no parameters. 10396 if (TpDecl) { 10397 if (FnDecl->param_size() == 0) { 10398 // Must have only one template parameter 10399 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 10400 if (Params->size() == 1) { 10401 NonTypeTemplateParmDecl *PmDecl = 10402 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 10403 10404 // The template parameter must be a char parameter pack. 10405 if (PmDecl && PmDecl->isTemplateParameterPack() && 10406 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 10407 Valid = true; 10408 } 10409 } 10410 } else if (FnDecl->param_size()) { 10411 // Check the first parameter 10412 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10413 10414 QualType T = (*Param)->getType().getUnqualifiedType(); 10415 10416 // unsigned long long int, long double, and any character type are allowed 10417 // as the only parameters. 10418 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 10419 Context.hasSameType(T, Context.LongDoubleTy) || 10420 Context.hasSameType(T, Context.CharTy) || 10421 Context.hasSameType(T, Context.WideCharTy) || 10422 Context.hasSameType(T, Context.Char16Ty) || 10423 Context.hasSameType(T, Context.Char32Ty)) { 10424 if (++Param == FnDecl->param_end()) 10425 Valid = true; 10426 goto FinishedParams; 10427 } 10428 10429 // Otherwise it must be a pointer to const; let's strip those qualifiers. 10430 const PointerType *PT = T->getAs<PointerType>(); 10431 if (!PT) 10432 goto FinishedParams; 10433 T = PT->getPointeeType(); 10434 if (!T.isConstQualified() || T.isVolatileQualified()) 10435 goto FinishedParams; 10436 T = T.getUnqualifiedType(); 10437 10438 // Move on to the second parameter; 10439 ++Param; 10440 10441 // If there is no second parameter, the first must be a const char * 10442 if (Param == FnDecl->param_end()) { 10443 if (Context.hasSameType(T, Context.CharTy)) 10444 Valid = true; 10445 goto FinishedParams; 10446 } 10447 10448 // const char *, const wchar_t*, const char16_t*, and const char32_t* 10449 // are allowed as the first parameter to a two-parameter function 10450 if (!(Context.hasSameType(T, Context.CharTy) || 10451 Context.hasSameType(T, Context.WideCharTy) || 10452 Context.hasSameType(T, Context.Char16Ty) || 10453 Context.hasSameType(T, Context.Char32Ty))) 10454 goto FinishedParams; 10455 10456 // The second and final parameter must be an std::size_t 10457 T = (*Param)->getType().getUnqualifiedType(); 10458 if (Context.hasSameType(T, Context.getSizeType()) && 10459 ++Param == FnDecl->param_end()) 10460 Valid = true; 10461 } 10462 10463 // FIXME: This diagnostic is absolutely terrible. 10464FinishedParams: 10465 if (!Valid) { 10466 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 10467 << FnDecl->getDeclName(); 10468 return true; 10469 } 10470 10471 // A parameter-declaration-clause containing a default argument is not 10472 // equivalent to any of the permitted forms. 10473 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10474 ParamEnd = FnDecl->param_end(); 10475 Param != ParamEnd; ++Param) { 10476 if ((*Param)->hasDefaultArg()) { 10477 Diag((*Param)->getDefaultArgRange().getBegin(), 10478 diag::err_literal_operator_default_argument) 10479 << (*Param)->getDefaultArgRange(); 10480 break; 10481 } 10482 } 10483 10484 StringRef LiteralName 10485 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 10486 if (LiteralName[0] != '_') { 10487 // C++11 [usrlit.suffix]p1: 10488 // Literal suffix identifiers that do not start with an underscore 10489 // are reserved for future standardization. 10490 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved); 10491 } 10492 10493 return false; 10494} 10495 10496/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 10497/// linkage specification, including the language and (if present) 10498/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 10499/// the location of the language string literal, which is provided 10500/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 10501/// the '{' brace. Otherwise, this linkage specification does not 10502/// have any braces. 10503Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 10504 SourceLocation LangLoc, 10505 StringRef Lang, 10506 SourceLocation LBraceLoc) { 10507 LinkageSpecDecl::LanguageIDs Language; 10508 if (Lang == "\"C\"") 10509 Language = LinkageSpecDecl::lang_c; 10510 else if (Lang == "\"C++\"") 10511 Language = LinkageSpecDecl::lang_cxx; 10512 else { 10513 Diag(LangLoc, diag::err_bad_language); 10514 return 0; 10515 } 10516 10517 // FIXME: Add all the various semantics of linkage specifications 10518 10519 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 10520 ExternLoc, LangLoc, Language, 10521 LBraceLoc.isValid()); 10522 CurContext->addDecl(D); 10523 PushDeclContext(S, D); 10524 return D; 10525} 10526 10527/// ActOnFinishLinkageSpecification - Complete the definition of 10528/// the C++ linkage specification LinkageSpec. If RBraceLoc is 10529/// valid, it's the position of the closing '}' brace in a linkage 10530/// specification that uses braces. 10531Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 10532 Decl *LinkageSpec, 10533 SourceLocation RBraceLoc) { 10534 if (LinkageSpec) { 10535 if (RBraceLoc.isValid()) { 10536 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 10537 LSDecl->setRBraceLoc(RBraceLoc); 10538 } 10539 PopDeclContext(); 10540 } 10541 return LinkageSpec; 10542} 10543 10544Decl *Sema::ActOnEmptyDeclaration(Scope *S, 10545 AttributeList *AttrList, 10546 SourceLocation SemiLoc) { 10547 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 10548 // Attribute declarations appertain to empty declaration so we handle 10549 // them here. 10550 if (AttrList) 10551 ProcessDeclAttributeList(S, ED, AttrList); 10552 10553 CurContext->addDecl(ED); 10554 return ED; 10555} 10556 10557/// \brief Perform semantic analysis for the variable declaration that 10558/// occurs within a C++ catch clause, returning the newly-created 10559/// variable. 10560VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 10561 TypeSourceInfo *TInfo, 10562 SourceLocation StartLoc, 10563 SourceLocation Loc, 10564 IdentifierInfo *Name) { 10565 bool Invalid = false; 10566 QualType ExDeclType = TInfo->getType(); 10567 10568 // Arrays and functions decay. 10569 if (ExDeclType->isArrayType()) 10570 ExDeclType = Context.getArrayDecayedType(ExDeclType); 10571 else if (ExDeclType->isFunctionType()) 10572 ExDeclType = Context.getPointerType(ExDeclType); 10573 10574 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 10575 // The exception-declaration shall not denote a pointer or reference to an 10576 // incomplete type, other than [cv] void*. 10577 // N2844 forbids rvalue references. 10578 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 10579 Diag(Loc, diag::err_catch_rvalue_ref); 10580 Invalid = true; 10581 } 10582 10583 QualType BaseType = ExDeclType; 10584 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 10585 unsigned DK = diag::err_catch_incomplete; 10586 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 10587 BaseType = Ptr->getPointeeType(); 10588 Mode = 1; 10589 DK = diag::err_catch_incomplete_ptr; 10590 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 10591 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 10592 BaseType = Ref->getPointeeType(); 10593 Mode = 2; 10594 DK = diag::err_catch_incomplete_ref; 10595 } 10596 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 10597 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 10598 Invalid = true; 10599 10600 if (!Invalid && !ExDeclType->isDependentType() && 10601 RequireNonAbstractType(Loc, ExDeclType, 10602 diag::err_abstract_type_in_decl, 10603 AbstractVariableType)) 10604 Invalid = true; 10605 10606 // Only the non-fragile NeXT runtime currently supports C++ catches 10607 // of ObjC types, and no runtime supports catching ObjC types by value. 10608 if (!Invalid && getLangOpts().ObjC1) { 10609 QualType T = ExDeclType; 10610 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 10611 T = RT->getPointeeType(); 10612 10613 if (T->isObjCObjectType()) { 10614 Diag(Loc, diag::err_objc_object_catch); 10615 Invalid = true; 10616 } else if (T->isObjCObjectPointerType()) { 10617 // FIXME: should this be a test for macosx-fragile specifically? 10618 if (getLangOpts().ObjCRuntime.isFragile()) 10619 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 10620 } 10621 } 10622 10623 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 10624 ExDeclType, TInfo, SC_None); 10625 ExDecl->setExceptionVariable(true); 10626 10627 // In ARC, infer 'retaining' for variables of retainable type. 10628 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 10629 Invalid = true; 10630 10631 if (!Invalid && !ExDeclType->isDependentType()) { 10632 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 10633 // Insulate this from anything else we might currently be parsing. 10634 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 10635 10636 // C++ [except.handle]p16: 10637 // The object declared in an exception-declaration or, if the 10638 // exception-declaration does not specify a name, a temporary (12.2) is 10639 // copy-initialized (8.5) from the exception object. [...] 10640 // The object is destroyed when the handler exits, after the destruction 10641 // of any automatic objects initialized within the handler. 10642 // 10643 // We just pretend to initialize the object with itself, then make sure 10644 // it can be destroyed later. 10645 QualType initType = ExDeclType; 10646 10647 InitializedEntity entity = 10648 InitializedEntity::InitializeVariable(ExDecl); 10649 InitializationKind initKind = 10650 InitializationKind::CreateCopy(Loc, SourceLocation()); 10651 10652 Expr *opaqueValue = 10653 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 10654 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 10655 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 10656 if (result.isInvalid()) 10657 Invalid = true; 10658 else { 10659 // If the constructor used was non-trivial, set this as the 10660 // "initializer". 10661 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 10662 if (!construct->getConstructor()->isTrivial()) { 10663 Expr *init = MaybeCreateExprWithCleanups(construct); 10664 ExDecl->setInit(init); 10665 } 10666 10667 // And make sure it's destructable. 10668 FinalizeVarWithDestructor(ExDecl, recordType); 10669 } 10670 } 10671 } 10672 10673 if (Invalid) 10674 ExDecl->setInvalidDecl(); 10675 10676 return ExDecl; 10677} 10678 10679/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 10680/// handler. 10681Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 10682 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10683 bool Invalid = D.isInvalidType(); 10684 10685 // Check for unexpanded parameter packs. 10686 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 10687 UPPC_ExceptionType)) { 10688 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10689 D.getIdentifierLoc()); 10690 Invalid = true; 10691 } 10692 10693 IdentifierInfo *II = D.getIdentifier(); 10694 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 10695 LookupOrdinaryName, 10696 ForRedeclaration)) { 10697 // The scope should be freshly made just for us. There is just no way 10698 // it contains any previous declaration. 10699 assert(!S->isDeclScope(PrevDecl)); 10700 if (PrevDecl->isTemplateParameter()) { 10701 // Maybe we will complain about the shadowed template parameter. 10702 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10703 PrevDecl = 0; 10704 } 10705 } 10706 10707 if (D.getCXXScopeSpec().isSet() && !Invalid) { 10708 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 10709 << D.getCXXScopeSpec().getRange(); 10710 Invalid = true; 10711 } 10712 10713 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 10714 D.getLocStart(), 10715 D.getIdentifierLoc(), 10716 D.getIdentifier()); 10717 if (Invalid) 10718 ExDecl->setInvalidDecl(); 10719 10720 // Add the exception declaration into this scope. 10721 if (II) 10722 PushOnScopeChains(ExDecl, S); 10723 else 10724 CurContext->addDecl(ExDecl); 10725 10726 ProcessDeclAttributes(S, ExDecl, D); 10727 return ExDecl; 10728} 10729 10730Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10731 Expr *AssertExpr, 10732 Expr *AssertMessageExpr, 10733 SourceLocation RParenLoc) { 10734 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 10735 10736 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 10737 return 0; 10738 10739 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 10740 AssertMessage, RParenLoc, false); 10741} 10742 10743Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 10744 Expr *AssertExpr, 10745 StringLiteral *AssertMessage, 10746 SourceLocation RParenLoc, 10747 bool Failed) { 10748 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 10749 !Failed) { 10750 // In a static_assert-declaration, the constant-expression shall be a 10751 // constant expression that can be contextually converted to bool. 10752 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 10753 if (Converted.isInvalid()) 10754 Failed = true; 10755 10756 llvm::APSInt Cond; 10757 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 10758 diag::err_static_assert_expression_is_not_constant, 10759 /*AllowFold=*/false).isInvalid()) 10760 Failed = true; 10761 10762 if (!Failed && !Cond) { 10763 SmallString<256> MsgBuffer; 10764 llvm::raw_svector_ostream Msg(MsgBuffer); 10765 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 10766 Diag(StaticAssertLoc, diag::err_static_assert_failed) 10767 << Msg.str() << AssertExpr->getSourceRange(); 10768 Failed = true; 10769 } 10770 } 10771 10772 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 10773 AssertExpr, AssertMessage, RParenLoc, 10774 Failed); 10775 10776 CurContext->addDecl(Decl); 10777 return Decl; 10778} 10779 10780/// \brief Perform semantic analysis of the given friend type declaration. 10781/// 10782/// \returns A friend declaration that. 10783FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 10784 SourceLocation FriendLoc, 10785 TypeSourceInfo *TSInfo) { 10786 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 10787 10788 QualType T = TSInfo->getType(); 10789 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 10790 10791 // C++03 [class.friend]p2: 10792 // An elaborated-type-specifier shall be used in a friend declaration 10793 // for a class.* 10794 // 10795 // * The class-key of the elaborated-type-specifier is required. 10796 if (!ActiveTemplateInstantiations.empty()) { 10797 // Do not complain about the form of friend template types during 10798 // template instantiation; we will already have complained when the 10799 // template was declared. 10800 } else { 10801 if (!T->isElaboratedTypeSpecifier()) { 10802 // If we evaluated the type to a record type, suggest putting 10803 // a tag in front. 10804 if (const RecordType *RT = T->getAs<RecordType>()) { 10805 RecordDecl *RD = RT->getDecl(); 10806 10807 std::string InsertionText = std::string(" ") + RD->getKindName(); 10808 10809 Diag(TypeRange.getBegin(), 10810 getLangOpts().CPlusPlus11 ? 10811 diag::warn_cxx98_compat_unelaborated_friend_type : 10812 diag::ext_unelaborated_friend_type) 10813 << (unsigned) RD->getTagKind() 10814 << T 10815 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 10816 InsertionText); 10817 } else { 10818 Diag(FriendLoc, 10819 getLangOpts().CPlusPlus11 ? 10820 diag::warn_cxx98_compat_nonclass_type_friend : 10821 diag::ext_nonclass_type_friend) 10822 << T 10823 << TypeRange; 10824 } 10825 } else if (T->getAs<EnumType>()) { 10826 Diag(FriendLoc, 10827 getLangOpts().CPlusPlus11 ? 10828 diag::warn_cxx98_compat_enum_friend : 10829 diag::ext_enum_friend) 10830 << T 10831 << TypeRange; 10832 } 10833 10834 // C++11 [class.friend]p3: 10835 // A friend declaration that does not declare a function shall have one 10836 // of the following forms: 10837 // friend elaborated-type-specifier ; 10838 // friend simple-type-specifier ; 10839 // friend typename-specifier ; 10840 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 10841 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 10842 } 10843 10844 // If the type specifier in a friend declaration designates a (possibly 10845 // cv-qualified) class type, that class is declared as a friend; otherwise, 10846 // the friend declaration is ignored. 10847 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 10848} 10849 10850/// Handle a friend tag declaration where the scope specifier was 10851/// templated. 10852Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 10853 unsigned TagSpec, SourceLocation TagLoc, 10854 CXXScopeSpec &SS, 10855 IdentifierInfo *Name, 10856 SourceLocation NameLoc, 10857 AttributeList *Attr, 10858 MultiTemplateParamsArg TempParamLists) { 10859 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10860 10861 bool isExplicitSpecialization = false; 10862 bool Invalid = false; 10863 10864 if (TemplateParameterList *TemplateParams 10865 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, 10866 TempParamLists.data(), 10867 TempParamLists.size(), 10868 /*friend*/ true, 10869 isExplicitSpecialization, 10870 Invalid)) { 10871 if (TemplateParams->size() > 0) { 10872 // This is a declaration of a class template. 10873 if (Invalid) 10874 return 0; 10875 10876 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 10877 SS, Name, NameLoc, Attr, 10878 TemplateParams, AS_public, 10879 /*ModulePrivateLoc=*/SourceLocation(), 10880 TempParamLists.size() - 1, 10881 TempParamLists.data()).take(); 10882 } else { 10883 // The "template<>" header is extraneous. 10884 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 10885 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 10886 isExplicitSpecialization = true; 10887 } 10888 } 10889 10890 if (Invalid) return 0; 10891 10892 bool isAllExplicitSpecializations = true; 10893 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 10894 if (TempParamLists[I]->size()) { 10895 isAllExplicitSpecializations = false; 10896 break; 10897 } 10898 } 10899 10900 // FIXME: don't ignore attributes. 10901 10902 // If it's explicit specializations all the way down, just forget 10903 // about the template header and build an appropriate non-templated 10904 // friend. TODO: for source fidelity, remember the headers. 10905 if (isAllExplicitSpecializations) { 10906 if (SS.isEmpty()) { 10907 bool Owned = false; 10908 bool IsDependent = false; 10909 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 10910 Attr, AS_public, 10911 /*ModulePrivateLoc=*/SourceLocation(), 10912 MultiTemplateParamsArg(), Owned, IsDependent, 10913 /*ScopedEnumKWLoc=*/SourceLocation(), 10914 /*ScopedEnumUsesClassTag=*/false, 10915 /*UnderlyingType=*/TypeResult()); 10916 } 10917 10918 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 10919 ElaboratedTypeKeyword Keyword 10920 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10921 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 10922 *Name, NameLoc); 10923 if (T.isNull()) 10924 return 0; 10925 10926 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10927 if (isa<DependentNameType>(T)) { 10928 DependentNameTypeLoc TL = 10929 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 10930 TL.setElaboratedKeywordLoc(TagLoc); 10931 TL.setQualifierLoc(QualifierLoc); 10932 TL.setNameLoc(NameLoc); 10933 } else { 10934 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 10935 TL.setElaboratedKeywordLoc(TagLoc); 10936 TL.setQualifierLoc(QualifierLoc); 10937 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 10938 } 10939 10940 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10941 TSI, FriendLoc, TempParamLists); 10942 Friend->setAccess(AS_public); 10943 CurContext->addDecl(Friend); 10944 return Friend; 10945 } 10946 10947 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 10948 10949 10950 10951 // Handle the case of a templated-scope friend class. e.g. 10952 // template <class T> class A<T>::B; 10953 // FIXME: we don't support these right now. 10954 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10955 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 10956 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 10957 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 10958 TL.setElaboratedKeywordLoc(TagLoc); 10959 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 10960 TL.setNameLoc(NameLoc); 10961 10962 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 10963 TSI, FriendLoc, TempParamLists); 10964 Friend->setAccess(AS_public); 10965 Friend->setUnsupportedFriend(true); 10966 CurContext->addDecl(Friend); 10967 return Friend; 10968} 10969 10970 10971/// Handle a friend type declaration. This works in tandem with 10972/// ActOnTag. 10973/// 10974/// Notes on friend class templates: 10975/// 10976/// We generally treat friend class declarations as if they were 10977/// declaring a class. So, for example, the elaborated type specifier 10978/// in a friend declaration is required to obey the restrictions of a 10979/// class-head (i.e. no typedefs in the scope chain), template 10980/// parameters are required to match up with simple template-ids, &c. 10981/// However, unlike when declaring a template specialization, it's 10982/// okay to refer to a template specialization without an empty 10983/// template parameter declaration, e.g. 10984/// friend class A<T>::B<unsigned>; 10985/// We permit this as a special case; if there are any template 10986/// parameters present at all, require proper matching, i.e. 10987/// template <> template \<class T> friend class A<int>::B; 10988Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 10989 MultiTemplateParamsArg TempParams) { 10990 SourceLocation Loc = DS.getLocStart(); 10991 10992 assert(DS.isFriendSpecified()); 10993 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10994 10995 // Try to convert the decl specifier to a type. This works for 10996 // friend templates because ActOnTag never produces a ClassTemplateDecl 10997 // for a TUK_Friend. 10998 Declarator TheDeclarator(DS, Declarator::MemberContext); 10999 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11000 QualType T = TSI->getType(); 11001 if (TheDeclarator.isInvalidType()) 11002 return 0; 11003 11004 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11005 return 0; 11006 11007 // This is definitely an error in C++98. It's probably meant to 11008 // be forbidden in C++0x, too, but the specification is just 11009 // poorly written. 11010 // 11011 // The problem is with declarations like the following: 11012 // template <T> friend A<T>::foo; 11013 // where deciding whether a class C is a friend or not now hinges 11014 // on whether there exists an instantiation of A that causes 11015 // 'foo' to equal C. There are restrictions on class-heads 11016 // (which we declare (by fiat) elaborated friend declarations to 11017 // be) that makes this tractable. 11018 // 11019 // FIXME: handle "template <> friend class A<T>;", which 11020 // is possibly well-formed? Who even knows? 11021 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11022 Diag(Loc, diag::err_tagless_friend_type_template) 11023 << DS.getSourceRange(); 11024 return 0; 11025 } 11026 11027 // C++98 [class.friend]p1: A friend of a class is a function 11028 // or class that is not a member of the class . . . 11029 // This is fixed in DR77, which just barely didn't make the C++03 11030 // deadline. It's also a very silly restriction that seriously 11031 // affects inner classes and which nobody else seems to implement; 11032 // thus we never diagnose it, not even in -pedantic. 11033 // 11034 // But note that we could warn about it: it's always useless to 11035 // friend one of your own members (it's not, however, worthless to 11036 // friend a member of an arbitrary specialization of your template). 11037 11038 Decl *D; 11039 if (unsigned NumTempParamLists = TempParams.size()) 11040 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11041 NumTempParamLists, 11042 TempParams.data(), 11043 TSI, 11044 DS.getFriendSpecLoc()); 11045 else 11046 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11047 11048 if (!D) 11049 return 0; 11050 11051 D->setAccess(AS_public); 11052 CurContext->addDecl(D); 11053 11054 return D; 11055} 11056 11057NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11058 MultiTemplateParamsArg TemplateParams) { 11059 const DeclSpec &DS = D.getDeclSpec(); 11060 11061 assert(DS.isFriendSpecified()); 11062 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11063 11064 SourceLocation Loc = D.getIdentifierLoc(); 11065 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11066 11067 // C++ [class.friend]p1 11068 // A friend of a class is a function or class.... 11069 // Note that this sees through typedefs, which is intended. 11070 // It *doesn't* see through dependent types, which is correct 11071 // according to [temp.arg.type]p3: 11072 // If a declaration acquires a function type through a 11073 // type dependent on a template-parameter and this causes 11074 // a declaration that does not use the syntactic form of a 11075 // function declarator to have a function type, the program 11076 // is ill-formed. 11077 if (!TInfo->getType()->isFunctionType()) { 11078 Diag(Loc, diag::err_unexpected_friend); 11079 11080 // It might be worthwhile to try to recover by creating an 11081 // appropriate declaration. 11082 return 0; 11083 } 11084 11085 // C++ [namespace.memdef]p3 11086 // - If a friend declaration in a non-local class first declares a 11087 // class or function, the friend class or function is a member 11088 // of the innermost enclosing namespace. 11089 // - The name of the friend is not found by simple name lookup 11090 // until a matching declaration is provided in that namespace 11091 // scope (either before or after the class declaration granting 11092 // friendship). 11093 // - If a friend function is called, its name may be found by the 11094 // name lookup that considers functions from namespaces and 11095 // classes associated with the types of the function arguments. 11096 // - When looking for a prior declaration of a class or a function 11097 // declared as a friend, scopes outside the innermost enclosing 11098 // namespace scope are not considered. 11099 11100 CXXScopeSpec &SS = D.getCXXScopeSpec(); 11101 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 11102 DeclarationName Name = NameInfo.getName(); 11103 assert(Name); 11104 11105 // Check for unexpanded parameter packs. 11106 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 11107 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 11108 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 11109 return 0; 11110 11111 // The context we found the declaration in, or in which we should 11112 // create the declaration. 11113 DeclContext *DC; 11114 Scope *DCScope = S; 11115 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11116 ForRedeclaration); 11117 11118 // FIXME: there are different rules in local classes 11119 11120 // There are four cases here. 11121 // - There's no scope specifier, in which case we just go to the 11122 // appropriate scope and look for a function or function template 11123 // there as appropriate. 11124 // Recover from invalid scope qualifiers as if they just weren't there. 11125 if (SS.isInvalid() || !SS.isSet()) { 11126 // C++0x [namespace.memdef]p3: 11127 // If the name in a friend declaration is neither qualified nor 11128 // a template-id and the declaration is a function or an 11129 // elaborated-type-specifier, the lookup to determine whether 11130 // the entity has been previously declared shall not consider 11131 // any scopes outside the innermost enclosing namespace. 11132 // C++0x [class.friend]p11: 11133 // If a friend declaration appears in a local class and the name 11134 // specified is an unqualified name, a prior declaration is 11135 // looked up without considering scopes that are outside the 11136 // innermost enclosing non-class scope. For a friend function 11137 // declaration, if there is no prior declaration, the program is 11138 // ill-formed. 11139 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 11140 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 11141 11142 // Find the appropriate context according to the above. 11143 DC = CurContext; 11144 11145 // Skip class contexts. If someone can cite chapter and verse 11146 // for this behavior, that would be nice --- it's what GCC and 11147 // EDG do, and it seems like a reasonable intent, but the spec 11148 // really only says that checks for unqualified existing 11149 // declarations should stop at the nearest enclosing namespace, 11150 // not that they should only consider the nearest enclosing 11151 // namespace. 11152 while (DC->isRecord()) 11153 DC = DC->getParent(); 11154 11155 DeclContext *LookupDC = DC; 11156 while (LookupDC->isTransparentContext()) 11157 LookupDC = LookupDC->getParent(); 11158 11159 while (true) { 11160 LookupQualifiedName(Previous, LookupDC); 11161 11162 // TODO: decide what we think about using declarations. 11163 if (isLocal) 11164 break; 11165 11166 if (!Previous.empty()) { 11167 DC = LookupDC; 11168 break; 11169 } 11170 11171 if (isTemplateId) { 11172 if (isa<TranslationUnitDecl>(LookupDC)) break; 11173 } else { 11174 if (LookupDC->isFileContext()) break; 11175 } 11176 LookupDC = LookupDC->getParent(); 11177 } 11178 11179 DCScope = getScopeForDeclContext(S, DC); 11180 11181 // C++ [class.friend]p6: 11182 // A function can be defined in a friend declaration of a class if and 11183 // only if the class is a non-local class (9.8), the function name is 11184 // unqualified, and the function has namespace scope. 11185 if (isLocal && D.isFunctionDefinition()) { 11186 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11187 } 11188 11189 // - There's a non-dependent scope specifier, in which case we 11190 // compute it and do a previous lookup there for a function 11191 // or function template. 11192 } else if (!SS.getScopeRep()->isDependent()) { 11193 DC = computeDeclContext(SS); 11194 if (!DC) return 0; 11195 11196 if (RequireCompleteDeclContext(SS, DC)) return 0; 11197 11198 LookupQualifiedName(Previous, DC); 11199 11200 // Ignore things found implicitly in the wrong scope. 11201 // TODO: better diagnostics for this case. Suggesting the right 11202 // qualified scope would be nice... 11203 LookupResult::Filter F = Previous.makeFilter(); 11204 while (F.hasNext()) { 11205 NamedDecl *D = F.next(); 11206 if (!DC->InEnclosingNamespaceSetOf( 11207 D->getDeclContext()->getRedeclContext())) 11208 F.erase(); 11209 } 11210 F.done(); 11211 11212 if (Previous.empty()) { 11213 D.setInvalidType(); 11214 Diag(Loc, diag::err_qualified_friend_not_found) 11215 << Name << TInfo->getType(); 11216 return 0; 11217 } 11218 11219 // C++ [class.friend]p1: A friend of a class is a function or 11220 // class that is not a member of the class . . . 11221 if (DC->Equals(CurContext)) 11222 Diag(DS.getFriendSpecLoc(), 11223 getLangOpts().CPlusPlus11 ? 11224 diag::warn_cxx98_compat_friend_is_member : 11225 diag::err_friend_is_member); 11226 11227 if (D.isFunctionDefinition()) { 11228 // C++ [class.friend]p6: 11229 // A function can be defined in a friend declaration of a class if and 11230 // only if the class is a non-local class (9.8), the function name is 11231 // unqualified, and the function has namespace scope. 11232 SemaDiagnosticBuilder DB 11233 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 11234 11235 DB << SS.getScopeRep(); 11236 if (DC->isFileContext()) 11237 DB << FixItHint::CreateRemoval(SS.getRange()); 11238 SS.clear(); 11239 } 11240 11241 // - There's a scope specifier that does not match any template 11242 // parameter lists, in which case we use some arbitrary context, 11243 // create a method or method template, and wait for instantiation. 11244 // - There's a scope specifier that does match some template 11245 // parameter lists, which we don't handle right now. 11246 } else { 11247 if (D.isFunctionDefinition()) { 11248 // C++ [class.friend]p6: 11249 // A function can be defined in a friend declaration of a class if and 11250 // only if the class is a non-local class (9.8), the function name is 11251 // unqualified, and the function has namespace scope. 11252 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 11253 << SS.getScopeRep(); 11254 } 11255 11256 DC = CurContext; 11257 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 11258 } 11259 11260 if (!DC->isRecord()) { 11261 // This implies that it has to be an operator or function. 11262 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 11263 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 11264 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 11265 Diag(Loc, diag::err_introducing_special_friend) << 11266 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 11267 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 11268 return 0; 11269 } 11270 } 11271 11272 // FIXME: This is an egregious hack to cope with cases where the scope stack 11273 // does not contain the declaration context, i.e., in an out-of-line 11274 // definition of a class. 11275 Scope FakeDCScope(S, Scope::DeclScope, Diags); 11276 if (!DCScope) { 11277 FakeDCScope.setEntity(DC); 11278 DCScope = &FakeDCScope; 11279 } 11280 11281 bool AddToScope = true; 11282 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 11283 TemplateParams, AddToScope); 11284 if (!ND) return 0; 11285 11286 assert(ND->getDeclContext() == DC); 11287 assert(ND->getLexicalDeclContext() == CurContext); 11288 11289 // Add the function declaration to the appropriate lookup tables, 11290 // adjusting the redeclarations list as necessary. We don't 11291 // want to do this yet if the friending class is dependent. 11292 // 11293 // Also update the scope-based lookup if the target context's 11294 // lookup context is in lexical scope. 11295 if (!CurContext->isDependentContext()) { 11296 DC = DC->getRedeclContext(); 11297 DC->makeDeclVisibleInContext(ND); 11298 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11299 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 11300 } 11301 11302 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 11303 D.getIdentifierLoc(), ND, 11304 DS.getFriendSpecLoc()); 11305 FrD->setAccess(AS_public); 11306 CurContext->addDecl(FrD); 11307 11308 if (ND->isInvalidDecl()) { 11309 FrD->setInvalidDecl(); 11310 } else { 11311 if (DC->isRecord()) CheckFriendAccess(ND); 11312 11313 FunctionDecl *FD; 11314 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 11315 FD = FTD->getTemplatedDecl(); 11316 else 11317 FD = cast<FunctionDecl>(ND); 11318 11319 // Mark templated-scope function declarations as unsupported. 11320 if (FD->getNumTemplateParameterLists()) 11321 FrD->setUnsupportedFriend(true); 11322 } 11323 11324 return ND; 11325} 11326 11327void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 11328 AdjustDeclIfTemplate(Dcl); 11329 11330 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 11331 if (!Fn) { 11332 Diag(DelLoc, diag::err_deleted_non_function); 11333 return; 11334 } 11335 11336 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 11337 // Don't consider the implicit declaration we generate for explicit 11338 // specializations. FIXME: Do not generate these implicit declarations. 11339 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization 11340 || Prev->getPreviousDecl()) && !Prev->isDefined()) { 11341 Diag(DelLoc, diag::err_deleted_decl_not_first); 11342 Diag(Prev->getLocation(), diag::note_previous_declaration); 11343 } 11344 // If the declaration wasn't the first, we delete the function anyway for 11345 // recovery. 11346 Fn = Fn->getCanonicalDecl(); 11347 } 11348 11349 if (Fn->isDeleted()) 11350 return; 11351 11352 // See if we're deleting a function which is already known to override a 11353 // non-deleted virtual function. 11354 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 11355 bool IssuedDiagnostic = false; 11356 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 11357 E = MD->end_overridden_methods(); 11358 I != E; ++I) { 11359 if (!(*MD->begin_overridden_methods())->isDeleted()) { 11360 if (!IssuedDiagnostic) { 11361 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 11362 IssuedDiagnostic = true; 11363 } 11364 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 11365 } 11366 } 11367 } 11368 11369 Fn->setDeletedAsWritten(); 11370} 11371 11372void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 11373 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 11374 11375 if (MD) { 11376 if (MD->getParent()->isDependentType()) { 11377 MD->setDefaulted(); 11378 MD->setExplicitlyDefaulted(); 11379 return; 11380 } 11381 11382 CXXSpecialMember Member = getSpecialMember(MD); 11383 if (Member == CXXInvalid) { 11384 Diag(DefaultLoc, diag::err_default_special_members); 11385 return; 11386 } 11387 11388 MD->setDefaulted(); 11389 MD->setExplicitlyDefaulted(); 11390 11391 // If this definition appears within the record, do the checking when 11392 // the record is complete. 11393 const FunctionDecl *Primary = MD; 11394 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 11395 // Find the uninstantiated declaration that actually had the '= default' 11396 // on it. 11397 Pattern->isDefined(Primary); 11398 11399 // If the method was defaulted on its first declaration, we will have 11400 // already performed the checking in CheckCompletedCXXClass. Such a 11401 // declaration doesn't trigger an implicit definition. 11402 if (Primary == Primary->getCanonicalDecl()) 11403 return; 11404 11405 CheckExplicitlyDefaultedSpecialMember(MD); 11406 11407 // The exception specification is needed because we are defining the 11408 // function. 11409 ResolveExceptionSpec(DefaultLoc, 11410 MD->getType()->castAs<FunctionProtoType>()); 11411 11412 switch (Member) { 11413 case CXXDefaultConstructor: { 11414 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11415 if (!CD->isInvalidDecl()) 11416 DefineImplicitDefaultConstructor(DefaultLoc, CD); 11417 break; 11418 } 11419 11420 case CXXCopyConstructor: { 11421 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11422 if (!CD->isInvalidDecl()) 11423 DefineImplicitCopyConstructor(DefaultLoc, CD); 11424 break; 11425 } 11426 11427 case CXXCopyAssignment: { 11428 if (!MD->isInvalidDecl()) 11429 DefineImplicitCopyAssignment(DefaultLoc, MD); 11430 break; 11431 } 11432 11433 case CXXDestructor: { 11434 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 11435 if (!DD->isInvalidDecl()) 11436 DefineImplicitDestructor(DefaultLoc, DD); 11437 break; 11438 } 11439 11440 case CXXMoveConstructor: { 11441 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 11442 if (!CD->isInvalidDecl()) 11443 DefineImplicitMoveConstructor(DefaultLoc, CD); 11444 break; 11445 } 11446 11447 case CXXMoveAssignment: { 11448 if (!MD->isInvalidDecl()) 11449 DefineImplicitMoveAssignment(DefaultLoc, MD); 11450 break; 11451 } 11452 11453 case CXXInvalid: 11454 llvm_unreachable("Invalid special member."); 11455 } 11456 } else { 11457 Diag(DefaultLoc, diag::err_default_special_members); 11458 } 11459} 11460 11461static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 11462 for (Stmt::child_range CI = S->children(); CI; ++CI) { 11463 Stmt *SubStmt = *CI; 11464 if (!SubStmt) 11465 continue; 11466 if (isa<ReturnStmt>(SubStmt)) 11467 Self.Diag(SubStmt->getLocStart(), 11468 diag::err_return_in_constructor_handler); 11469 if (!isa<Expr>(SubStmt)) 11470 SearchForReturnInStmt(Self, SubStmt); 11471 } 11472} 11473 11474void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 11475 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 11476 CXXCatchStmt *Handler = TryBlock->getHandler(I); 11477 SearchForReturnInStmt(*this, Handler); 11478 } 11479} 11480 11481bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 11482 const CXXMethodDecl *Old) { 11483 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 11484 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 11485 11486 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 11487 11488 // If the calling conventions match, everything is fine 11489 if (NewCC == OldCC) 11490 return false; 11491 11492 // If either of the calling conventions are set to "default", we need to pick 11493 // something more sensible based on the target. This supports code where the 11494 // one method explicitly sets thiscall, and another has no explicit calling 11495 // convention. 11496 CallingConv Default = 11497 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member); 11498 if (NewCC == CC_Default) 11499 NewCC = Default; 11500 if (OldCC == CC_Default) 11501 OldCC = Default; 11502 11503 // If the calling conventions still don't match, then report the error 11504 if (NewCC != OldCC) { 11505 Diag(New->getLocation(), 11506 diag::err_conflicting_overriding_cc_attributes) 11507 << New->getDeclName() << New->getType() << Old->getType(); 11508 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11509 return true; 11510 } 11511 11512 return false; 11513} 11514 11515bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 11516 const CXXMethodDecl *Old) { 11517 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 11518 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 11519 11520 if (Context.hasSameType(NewTy, OldTy) || 11521 NewTy->isDependentType() || OldTy->isDependentType()) 11522 return false; 11523 11524 // Check if the return types are covariant 11525 QualType NewClassTy, OldClassTy; 11526 11527 /// Both types must be pointers or references to classes. 11528 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 11529 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 11530 NewClassTy = NewPT->getPointeeType(); 11531 OldClassTy = OldPT->getPointeeType(); 11532 } 11533 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 11534 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 11535 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 11536 NewClassTy = NewRT->getPointeeType(); 11537 OldClassTy = OldRT->getPointeeType(); 11538 } 11539 } 11540 } 11541 11542 // The return types aren't either both pointers or references to a class type. 11543 if (NewClassTy.isNull()) { 11544 Diag(New->getLocation(), 11545 diag::err_different_return_type_for_overriding_virtual_function) 11546 << New->getDeclName() << NewTy << OldTy; 11547 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11548 11549 return true; 11550 } 11551 11552 // C++ [class.virtual]p6: 11553 // If the return type of D::f differs from the return type of B::f, the 11554 // class type in the return type of D::f shall be complete at the point of 11555 // declaration of D::f or shall be the class type D. 11556 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 11557 if (!RT->isBeingDefined() && 11558 RequireCompleteType(New->getLocation(), NewClassTy, 11559 diag::err_covariant_return_incomplete, 11560 New->getDeclName())) 11561 return true; 11562 } 11563 11564 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 11565 // Check if the new class derives from the old class. 11566 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 11567 Diag(New->getLocation(), 11568 diag::err_covariant_return_not_derived) 11569 << New->getDeclName() << NewTy << OldTy; 11570 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11571 return true; 11572 } 11573 11574 // Check if we the conversion from derived to base is valid. 11575 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 11576 diag::err_covariant_return_inaccessible_base, 11577 diag::err_covariant_return_ambiguous_derived_to_base_conv, 11578 // FIXME: Should this point to the return type? 11579 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 11580 // FIXME: this note won't trigger for delayed access control 11581 // diagnostics, and it's impossible to get an undelayed error 11582 // here from access control during the original parse because 11583 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 11584 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11585 return true; 11586 } 11587 } 11588 11589 // The qualifiers of the return types must be the same. 11590 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 11591 Diag(New->getLocation(), 11592 diag::err_covariant_return_type_different_qualifications) 11593 << New->getDeclName() << NewTy << OldTy; 11594 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11595 return true; 11596 }; 11597 11598 11599 // The new class type must have the same or less qualifiers as the old type. 11600 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 11601 Diag(New->getLocation(), 11602 diag::err_covariant_return_type_class_type_more_qualified) 11603 << New->getDeclName() << NewTy << OldTy; 11604 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 11605 return true; 11606 }; 11607 11608 return false; 11609} 11610 11611/// \brief Mark the given method pure. 11612/// 11613/// \param Method the method to be marked pure. 11614/// 11615/// \param InitRange the source range that covers the "0" initializer. 11616bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 11617 SourceLocation EndLoc = InitRange.getEnd(); 11618 if (EndLoc.isValid()) 11619 Method->setRangeEnd(EndLoc); 11620 11621 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 11622 Method->setPure(); 11623 return false; 11624 } 11625 11626 if (!Method->isInvalidDecl()) 11627 Diag(Method->getLocation(), diag::err_non_virtual_pure) 11628 << Method->getDeclName() << InitRange; 11629 return true; 11630} 11631 11632/// \brief Determine whether the given declaration is a static data member. 11633static bool isStaticDataMember(Decl *D) { 11634 VarDecl *Var = dyn_cast_or_null<VarDecl>(D); 11635 if (!Var) 11636 return false; 11637 11638 return Var->isStaticDataMember(); 11639} 11640/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 11641/// an initializer for the out-of-line declaration 'Dcl'. The scope 11642/// is a fresh scope pushed for just this purpose. 11643/// 11644/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 11645/// static data member of class X, names should be looked up in the scope of 11646/// class X. 11647void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 11648 // If there is no declaration, there was an error parsing it. 11649 if (D == 0 || D->isInvalidDecl()) return; 11650 11651 // We should only get called for declarations with scope specifiers, like: 11652 // int foo::bar; 11653 assert(D->isOutOfLine()); 11654 EnterDeclaratorContext(S, D->getDeclContext()); 11655 11656 // If we are parsing the initializer for a static data member, push a 11657 // new expression evaluation context that is associated with this static 11658 // data member. 11659 if (isStaticDataMember(D)) 11660 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 11661} 11662 11663/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 11664/// initializer for the out-of-line declaration 'D'. 11665void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 11666 // If there is no declaration, there was an error parsing it. 11667 if (D == 0 || D->isInvalidDecl()) return; 11668 11669 if (isStaticDataMember(D)) 11670 PopExpressionEvaluationContext(); 11671 11672 assert(D->isOutOfLine()); 11673 ExitDeclaratorContext(S); 11674} 11675 11676/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 11677/// C++ if/switch/while/for statement. 11678/// e.g: "if (int x = f()) {...}" 11679DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 11680 // C++ 6.4p2: 11681 // The declarator shall not specify a function or an array. 11682 // The type-specifier-seq shall not contain typedef and shall not declare a 11683 // new class or enumeration. 11684 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 11685 "Parser allowed 'typedef' as storage class of condition decl."); 11686 11687 Decl *Dcl = ActOnDeclarator(S, D); 11688 if (!Dcl) 11689 return true; 11690 11691 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 11692 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 11693 << D.getSourceRange(); 11694 return true; 11695 } 11696 11697 return Dcl; 11698} 11699 11700void Sema::LoadExternalVTableUses() { 11701 if (!ExternalSource) 11702 return; 11703 11704 SmallVector<ExternalVTableUse, 4> VTables; 11705 ExternalSource->ReadUsedVTables(VTables); 11706 SmallVector<VTableUse, 4> NewUses; 11707 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 11708 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 11709 = VTablesUsed.find(VTables[I].Record); 11710 // Even if a definition wasn't required before, it may be required now. 11711 if (Pos != VTablesUsed.end()) { 11712 if (!Pos->second && VTables[I].DefinitionRequired) 11713 Pos->second = true; 11714 continue; 11715 } 11716 11717 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 11718 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 11719 } 11720 11721 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 11722} 11723 11724void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 11725 bool DefinitionRequired) { 11726 // Ignore any vtable uses in unevaluated operands or for classes that do 11727 // not have a vtable. 11728 if (!Class->isDynamicClass() || Class->isDependentContext() || 11729 CurContext->isDependentContext() || isUnevaluatedContext()) 11730 return; 11731 11732 // Try to insert this class into the map. 11733 LoadExternalVTableUses(); 11734 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11735 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 11736 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 11737 if (!Pos.second) { 11738 // If we already had an entry, check to see if we are promoting this vtable 11739 // to required a definition. If so, we need to reappend to the VTableUses 11740 // list, since we may have already processed the first entry. 11741 if (DefinitionRequired && !Pos.first->second) { 11742 Pos.first->second = true; 11743 } else { 11744 // Otherwise, we can early exit. 11745 return; 11746 } 11747 } 11748 11749 // Local classes need to have their virtual members marked 11750 // immediately. For all other classes, we mark their virtual members 11751 // at the end of the translation unit. 11752 if (Class->isLocalClass()) 11753 MarkVirtualMembersReferenced(Loc, Class); 11754 else 11755 VTableUses.push_back(std::make_pair(Class, Loc)); 11756} 11757 11758bool Sema::DefineUsedVTables() { 11759 LoadExternalVTableUses(); 11760 if (VTableUses.empty()) 11761 return false; 11762 11763 // Note: The VTableUses vector could grow as a result of marking 11764 // the members of a class as "used", so we check the size each 11765 // time through the loop and prefer indices (which are stable) to 11766 // iterators (which are not). 11767 bool DefinedAnything = false; 11768 for (unsigned I = 0; I != VTableUses.size(); ++I) { 11769 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 11770 if (!Class) 11771 continue; 11772 11773 SourceLocation Loc = VTableUses[I].second; 11774 11775 bool DefineVTable = true; 11776 11777 // If this class has a key function, but that key function is 11778 // defined in another translation unit, we don't need to emit the 11779 // vtable even though we're using it. 11780 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 11781 if (KeyFunction && !KeyFunction->hasBody()) { 11782 switch (KeyFunction->getTemplateSpecializationKind()) { 11783 case TSK_Undeclared: 11784 case TSK_ExplicitSpecialization: 11785 case TSK_ExplicitInstantiationDeclaration: 11786 // The key function is in another translation unit. 11787 DefineVTable = false; 11788 break; 11789 11790 case TSK_ExplicitInstantiationDefinition: 11791 case TSK_ImplicitInstantiation: 11792 // We will be instantiating the key function. 11793 break; 11794 } 11795 } else if (!KeyFunction) { 11796 // If we have a class with no key function that is the subject 11797 // of an explicit instantiation declaration, suppress the 11798 // vtable; it will live with the explicit instantiation 11799 // definition. 11800 bool IsExplicitInstantiationDeclaration 11801 = Class->getTemplateSpecializationKind() 11802 == TSK_ExplicitInstantiationDeclaration; 11803 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 11804 REnd = Class->redecls_end(); 11805 R != REnd; ++R) { 11806 TemplateSpecializationKind TSK 11807 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 11808 if (TSK == TSK_ExplicitInstantiationDeclaration) 11809 IsExplicitInstantiationDeclaration = true; 11810 else if (TSK == TSK_ExplicitInstantiationDefinition) { 11811 IsExplicitInstantiationDeclaration = false; 11812 break; 11813 } 11814 } 11815 11816 if (IsExplicitInstantiationDeclaration) 11817 DefineVTable = false; 11818 } 11819 11820 // The exception specifications for all virtual members may be needed even 11821 // if we are not providing an authoritative form of the vtable in this TU. 11822 // We may choose to emit it available_externally anyway. 11823 if (!DefineVTable) { 11824 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 11825 continue; 11826 } 11827 11828 // Mark all of the virtual members of this class as referenced, so 11829 // that we can build a vtable. Then, tell the AST consumer that a 11830 // vtable for this class is required. 11831 DefinedAnything = true; 11832 MarkVirtualMembersReferenced(Loc, Class); 11833 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 11834 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 11835 11836 // Optionally warn if we're emitting a weak vtable. 11837 if (Class->isExternallyVisible() && 11838 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 11839 const FunctionDecl *KeyFunctionDef = 0; 11840 if (!KeyFunction || 11841 (KeyFunction->hasBody(KeyFunctionDef) && 11842 KeyFunctionDef->isInlined())) 11843 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 11844 TSK_ExplicitInstantiationDefinition 11845 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 11846 << Class; 11847 } 11848 } 11849 VTableUses.clear(); 11850 11851 return DefinedAnything; 11852} 11853 11854void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 11855 const CXXRecordDecl *RD) { 11856 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 11857 E = RD->method_end(); I != E; ++I) 11858 if ((*I)->isVirtual() && !(*I)->isPure()) 11859 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 11860} 11861 11862void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 11863 const CXXRecordDecl *RD) { 11864 // Mark all functions which will appear in RD's vtable as used. 11865 CXXFinalOverriderMap FinalOverriders; 11866 RD->getFinalOverriders(FinalOverriders); 11867 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 11868 E = FinalOverriders.end(); 11869 I != E; ++I) { 11870 for (OverridingMethods::const_iterator OI = I->second.begin(), 11871 OE = I->second.end(); 11872 OI != OE; ++OI) { 11873 assert(OI->second.size() > 0 && "no final overrider"); 11874 CXXMethodDecl *Overrider = OI->second.front().Method; 11875 11876 // C++ [basic.def.odr]p2: 11877 // [...] A virtual member function is used if it is not pure. [...] 11878 if (!Overrider->isPure()) 11879 MarkFunctionReferenced(Loc, Overrider); 11880 } 11881 } 11882 11883 // Only classes that have virtual bases need a VTT. 11884 if (RD->getNumVBases() == 0) 11885 return; 11886 11887 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 11888 e = RD->bases_end(); i != e; ++i) { 11889 const CXXRecordDecl *Base = 11890 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 11891 if (Base->getNumVBases() == 0) 11892 continue; 11893 MarkVirtualMembersReferenced(Loc, Base); 11894 } 11895} 11896 11897/// SetIvarInitializers - This routine builds initialization ASTs for the 11898/// Objective-C implementation whose ivars need be initialized. 11899void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 11900 if (!getLangOpts().CPlusPlus) 11901 return; 11902 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 11903 SmallVector<ObjCIvarDecl*, 8> ivars; 11904 CollectIvarsToConstructOrDestruct(OID, ivars); 11905 if (ivars.empty()) 11906 return; 11907 SmallVector<CXXCtorInitializer*, 32> AllToInit; 11908 for (unsigned i = 0; i < ivars.size(); i++) { 11909 FieldDecl *Field = ivars[i]; 11910 if (Field->isInvalidDecl()) 11911 continue; 11912 11913 CXXCtorInitializer *Member; 11914 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 11915 InitializationKind InitKind = 11916 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 11917 11918 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 11919 ExprResult MemberInit = 11920 InitSeq.Perform(*this, InitEntity, InitKind, None); 11921 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 11922 // Note, MemberInit could actually come back empty if no initialization 11923 // is required (e.g., because it would call a trivial default constructor) 11924 if (!MemberInit.get() || MemberInit.isInvalid()) 11925 continue; 11926 11927 Member = 11928 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 11929 SourceLocation(), 11930 MemberInit.takeAs<Expr>(), 11931 SourceLocation()); 11932 AllToInit.push_back(Member); 11933 11934 // Be sure that the destructor is accessible and is marked as referenced. 11935 if (const RecordType *RecordTy 11936 = Context.getBaseElementType(Field->getType()) 11937 ->getAs<RecordType>()) { 11938 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 11939 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 11940 MarkFunctionReferenced(Field->getLocation(), Destructor); 11941 CheckDestructorAccess(Field->getLocation(), Destructor, 11942 PDiag(diag::err_access_dtor_ivar) 11943 << Context.getBaseElementType(Field->getType())); 11944 } 11945 } 11946 } 11947 ObjCImplementation->setIvarInitializers(Context, 11948 AllToInit.data(), AllToInit.size()); 11949 } 11950} 11951 11952static 11953void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 11954 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 11955 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 11956 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 11957 Sema &S) { 11958 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 11959 CE = Current.end(); 11960 if (Ctor->isInvalidDecl()) 11961 return; 11962 11963 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 11964 11965 // Target may not be determinable yet, for instance if this is a dependent 11966 // call in an uninstantiated template. 11967 if (Target) { 11968 const FunctionDecl *FNTarget = 0; 11969 (void)Target->hasBody(FNTarget); 11970 Target = const_cast<CXXConstructorDecl*>( 11971 cast_or_null<CXXConstructorDecl>(FNTarget)); 11972 } 11973 11974 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 11975 // Avoid dereferencing a null pointer here. 11976 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 11977 11978 if (!Current.insert(Canonical)) 11979 return; 11980 11981 // We know that beyond here, we aren't chaining into a cycle. 11982 if (!Target || !Target->isDelegatingConstructor() || 11983 Target->isInvalidDecl() || Valid.count(TCanonical)) { 11984 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 11985 Valid.insert(*CI); 11986 Current.clear(); 11987 // We've hit a cycle. 11988 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 11989 Current.count(TCanonical)) { 11990 // If we haven't diagnosed this cycle yet, do so now. 11991 if (!Invalid.count(TCanonical)) { 11992 S.Diag((*Ctor->init_begin())->getSourceLocation(), 11993 diag::warn_delegating_ctor_cycle) 11994 << Ctor; 11995 11996 // Don't add a note for a function delegating directly to itself. 11997 if (TCanonical != Canonical) 11998 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 11999 12000 CXXConstructorDecl *C = Target; 12001 while (C->getCanonicalDecl() != Canonical) { 12002 const FunctionDecl *FNTarget = 0; 12003 (void)C->getTargetConstructor()->hasBody(FNTarget); 12004 assert(FNTarget && "Ctor cycle through bodiless function"); 12005 12006 C = const_cast<CXXConstructorDecl*>( 12007 cast<CXXConstructorDecl>(FNTarget)); 12008 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12009 } 12010 } 12011 12012 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 12013 Invalid.insert(*CI); 12014 Current.clear(); 12015 } else { 12016 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12017 } 12018} 12019 12020 12021void Sema::CheckDelegatingCtorCycles() { 12022 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12023 12024 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 12025 CE = Current.end(); 12026 12027 for (DelegatingCtorDeclsType::iterator 12028 I = DelegatingCtorDecls.begin(ExternalSource), 12029 E = DelegatingCtorDecls.end(); 12030 I != E; ++I) 12031 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 12032 12033 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 12034 (*CI)->setInvalidDecl(); 12035} 12036 12037namespace { 12038 /// \brief AST visitor that finds references to the 'this' expression. 12039 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 12040 Sema &S; 12041 12042 public: 12043 explicit FindCXXThisExpr(Sema &S) : S(S) { } 12044 12045 bool VisitCXXThisExpr(CXXThisExpr *E) { 12046 S.Diag(E->getLocation(), diag::err_this_static_member_func) 12047 << E->isImplicit(); 12048 return false; 12049 } 12050 }; 12051} 12052 12053bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 12054 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12055 if (!TSInfo) 12056 return false; 12057 12058 TypeLoc TL = TSInfo->getTypeLoc(); 12059 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12060 if (!ProtoTL) 12061 return false; 12062 12063 // C++11 [expr.prim.general]p3: 12064 // [The expression this] shall not appear before the optional 12065 // cv-qualifier-seq and it shall not appear within the declaration of a 12066 // static member function (although its type and value category are defined 12067 // within a static member function as they are within a non-static member 12068 // function). [ Note: this is because declaration matching does not occur 12069 // until the complete declarator is known. - end note ] 12070 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12071 FindCXXThisExpr Finder(*this); 12072 12073 // If the return type came after the cv-qualifier-seq, check it now. 12074 if (Proto->hasTrailingReturn() && 12075 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc())) 12076 return true; 12077 12078 // Check the exception specification. 12079 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 12080 return true; 12081 12082 return checkThisInStaticMemberFunctionAttributes(Method); 12083} 12084 12085bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 12086 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12087 if (!TSInfo) 12088 return false; 12089 12090 TypeLoc TL = TSInfo->getTypeLoc(); 12091 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12092 if (!ProtoTL) 12093 return false; 12094 12095 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12096 FindCXXThisExpr Finder(*this); 12097 12098 switch (Proto->getExceptionSpecType()) { 12099 case EST_Uninstantiated: 12100 case EST_Unevaluated: 12101 case EST_BasicNoexcept: 12102 case EST_DynamicNone: 12103 case EST_MSAny: 12104 case EST_None: 12105 break; 12106 12107 case EST_ComputedNoexcept: 12108 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 12109 return true; 12110 12111 case EST_Dynamic: 12112 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 12113 EEnd = Proto->exception_end(); 12114 E != EEnd; ++E) { 12115 if (!Finder.TraverseType(*E)) 12116 return true; 12117 } 12118 break; 12119 } 12120 12121 return false; 12122} 12123 12124bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 12125 FindCXXThisExpr Finder(*this); 12126 12127 // Check attributes. 12128 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end(); 12129 A != AEnd; ++A) { 12130 // FIXME: This should be emitted by tblgen. 12131 Expr *Arg = 0; 12132 ArrayRef<Expr *> Args; 12133 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A)) 12134 Arg = G->getArg(); 12135 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A)) 12136 Arg = G->getArg(); 12137 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A)) 12138 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 12139 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A)) 12140 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 12141 else if (ExclusiveLockFunctionAttr *ELF 12142 = dyn_cast<ExclusiveLockFunctionAttr>(*A)) 12143 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 12144 else if (SharedLockFunctionAttr *SLF 12145 = dyn_cast<SharedLockFunctionAttr>(*A)) 12146 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 12147 else if (ExclusiveTrylockFunctionAttr *ETLF 12148 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) { 12149 Arg = ETLF->getSuccessValue(); 12150 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 12151 } else if (SharedTrylockFunctionAttr *STLF 12152 = dyn_cast<SharedTrylockFunctionAttr>(*A)) { 12153 Arg = STLF->getSuccessValue(); 12154 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 12155 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A)) 12156 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 12157 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A)) 12158 Arg = LR->getArg(); 12159 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A)) 12160 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 12161 else if (ExclusiveLocksRequiredAttr *ELR 12162 = dyn_cast<ExclusiveLocksRequiredAttr>(*A)) 12163 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size()); 12164 else if (SharedLocksRequiredAttr *SLR 12165 = dyn_cast<SharedLocksRequiredAttr>(*A)) 12166 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size()); 12167 12168 if (Arg && !Finder.TraverseStmt(Arg)) 12169 return true; 12170 12171 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12172 if (!Finder.TraverseStmt(Args[I])) 12173 return true; 12174 } 12175 } 12176 12177 return false; 12178} 12179 12180void 12181Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12182 ArrayRef<ParsedType> DynamicExceptions, 12183 ArrayRef<SourceRange> DynamicExceptionRanges, 12184 Expr *NoexceptExpr, 12185 SmallVectorImpl<QualType> &Exceptions, 12186 FunctionProtoType::ExtProtoInfo &EPI) { 12187 Exceptions.clear(); 12188 EPI.ExceptionSpecType = EST; 12189 if (EST == EST_Dynamic) { 12190 Exceptions.reserve(DynamicExceptions.size()); 12191 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12192 // FIXME: Preserve type source info. 12193 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12194 12195 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12196 collectUnexpandedParameterPacks(ET, Unexpanded); 12197 if (!Unexpanded.empty()) { 12198 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 12199 UPPC_ExceptionType, 12200 Unexpanded); 12201 continue; 12202 } 12203 12204 // Check that the type is valid for an exception spec, and 12205 // drop it if not. 12206 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 12207 Exceptions.push_back(ET); 12208 } 12209 EPI.NumExceptions = Exceptions.size(); 12210 EPI.Exceptions = Exceptions.data(); 12211 return; 12212 } 12213 12214 if (EST == EST_ComputedNoexcept) { 12215 // If an error occurred, there's no expression here. 12216 if (NoexceptExpr) { 12217 assert((NoexceptExpr->isTypeDependent() || 12218 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 12219 Context.BoolTy) && 12220 "Parser should have made sure that the expression is boolean"); 12221 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 12222 EPI.ExceptionSpecType = EST_BasicNoexcept; 12223 return; 12224 } 12225 12226 if (!NoexceptExpr->isValueDependent()) 12227 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 12228 diag::err_noexcept_needs_constant_expression, 12229 /*AllowFold*/ false).take(); 12230 EPI.NoexceptExpr = NoexceptExpr; 12231 } 12232 return; 12233 } 12234} 12235 12236/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 12237Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 12238 // Implicitly declared functions (e.g. copy constructors) are 12239 // __host__ __device__ 12240 if (D->isImplicit()) 12241 return CFT_HostDevice; 12242 12243 if (D->hasAttr<CUDAGlobalAttr>()) 12244 return CFT_Global; 12245 12246 if (D->hasAttr<CUDADeviceAttr>()) { 12247 if (D->hasAttr<CUDAHostAttr>()) 12248 return CFT_HostDevice; 12249 else 12250 return CFT_Device; 12251 } 12252 12253 return CFT_Host; 12254} 12255 12256bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 12257 CUDAFunctionTarget CalleeTarget) { 12258 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 12259 // Callable from the device only." 12260 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 12261 return true; 12262 12263 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 12264 // Callable from the host only." 12265 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 12266 // Callable from the host only." 12267 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 12268 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 12269 return true; 12270 12271 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 12272 return true; 12273 12274 return false; 12275} 12276 12277/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 12278/// 12279MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 12280 SourceLocation DeclStart, 12281 Declarator &D, Expr *BitWidth, 12282 InClassInitStyle InitStyle, 12283 AccessSpecifier AS, 12284 AttributeList *MSPropertyAttr) { 12285 IdentifierInfo *II = D.getIdentifier(); 12286 if (!II) { 12287 Diag(DeclStart, diag::err_anonymous_property); 12288 return NULL; 12289 } 12290 SourceLocation Loc = D.getIdentifierLoc(); 12291 12292 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12293 QualType T = TInfo->getType(); 12294 if (getLangOpts().CPlusPlus) { 12295 CheckExtraCXXDefaultArguments(D); 12296 12297 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12298 UPPC_DataMemberType)) { 12299 D.setInvalidType(); 12300 T = Context.IntTy; 12301 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12302 } 12303 } 12304 12305 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12306 12307 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12308 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12309 diag::err_invalid_thread) 12310 << DeclSpec::getSpecifierName(TSCS); 12311 12312 // Check to see if this name was declared as a member previously 12313 NamedDecl *PrevDecl = 0; 12314 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12315 LookupName(Previous, S); 12316 switch (Previous.getResultKind()) { 12317 case LookupResult::Found: 12318 case LookupResult::FoundUnresolvedValue: 12319 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12320 break; 12321 12322 case LookupResult::FoundOverloaded: 12323 PrevDecl = Previous.getRepresentativeDecl(); 12324 break; 12325 12326 case LookupResult::NotFound: 12327 case LookupResult::NotFoundInCurrentInstantiation: 12328 case LookupResult::Ambiguous: 12329 break; 12330 } 12331 12332 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12333 // Maybe we will complain about the shadowed template parameter. 12334 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12335 // Just pretend that we didn't see the previous declaration. 12336 PrevDecl = 0; 12337 } 12338 12339 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12340 PrevDecl = 0; 12341 12342 SourceLocation TSSL = D.getLocStart(); 12343 MSPropertyDecl *NewPD; 12344 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 12345 NewPD = new (Context) MSPropertyDecl(Record, Loc, 12346 II, T, TInfo, TSSL, 12347 Data.GetterId, Data.SetterId); 12348 ProcessDeclAttributes(TUScope, NewPD, D); 12349 NewPD->setAccess(AS); 12350 12351 if (NewPD->isInvalidDecl()) 12352 Record->setInvalidDecl(); 12353 12354 if (D.getDeclSpec().isModulePrivateSpecified()) 12355 NewPD->setModulePrivate(); 12356 12357 if (NewPD->isInvalidDecl() && PrevDecl) { 12358 // Don't introduce NewFD into scope; there's already something 12359 // with the same name in the same scope. 12360 } else if (II) { 12361 PushOnScopeChains(NewPD, S); 12362 } else 12363 Record->addDecl(NewPD); 12364 12365 return NewPD; 12366} 12367