SemaDeclCXX.cpp revision 682a56b15ae01cc8154d4800d29498da93911981
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for C++ declarations. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/SemaInternal.h" 15#include "clang/AST/ASTConsumer.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/ASTLambda.h" 18#include "clang/AST/ASTMutationListener.h" 19#include "clang/AST/CXXInheritance.h" 20#include "clang/AST/CharUnits.h" 21#include "clang/AST/DeclVisitor.h" 22#include "clang/AST/EvaluatedExprVisitor.h" 23#include "clang/AST/ExprCXX.h" 24#include "clang/AST/RecordLayout.h" 25#include "clang/AST/RecursiveASTVisitor.h" 26#include "clang/AST/StmtVisitor.h" 27#include "clang/AST/TypeLoc.h" 28#include "clang/AST/TypeOrdering.h" 29#include "clang/Basic/PartialDiagnostic.h" 30#include "clang/Basic/TargetInfo.h" 31#include "clang/Lex/LiteralSupport.h" 32#include "clang/Lex/Preprocessor.h" 33#include "clang/Sema/CXXFieldCollector.h" 34#include "clang/Sema/DeclSpec.h" 35#include "clang/Sema/Initialization.h" 36#include "clang/Sema/Lookup.h" 37#include "clang/Sema/ParsedTemplate.h" 38#include "clang/Sema/Scope.h" 39#include "clang/Sema/ScopeInfo.h" 40#include "llvm/ADT/STLExtras.h" 41#include "llvm/ADT/SmallString.h" 42#include <map> 43#include <set> 44 45using namespace clang; 46 47//===----------------------------------------------------------------------===// 48// CheckDefaultArgumentVisitor 49//===----------------------------------------------------------------------===// 50 51namespace { 52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 53 /// the default argument of a parameter to determine whether it 54 /// contains any ill-formed subexpressions. For example, this will 55 /// diagnose the use of local variables or parameters within the 56 /// default argument expression. 57 class CheckDefaultArgumentVisitor 58 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 59 Expr *DefaultArg; 60 Sema *S; 61 62 public: 63 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 64 : DefaultArg(defarg), S(s) {} 65 66 bool VisitExpr(Expr *Node); 67 bool VisitDeclRefExpr(DeclRefExpr *DRE); 68 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 69 bool VisitLambdaExpr(LambdaExpr *Lambda); 70 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 71 }; 72 73 /// VisitExpr - Visit all of the children of this expression. 74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 75 bool IsInvalid = false; 76 for (Stmt::child_range I = Node->children(); I; ++I) 77 IsInvalid |= Visit(*I); 78 return IsInvalid; 79 } 80 81 /// VisitDeclRefExpr - Visit a reference to a declaration, to 82 /// determine whether this declaration can be used in the default 83 /// argument expression. 84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 85 NamedDecl *Decl = DRE->getDecl(); 86 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 87 // C++ [dcl.fct.default]p9 88 // Default arguments are evaluated each time the function is 89 // called. The order of evaluation of function arguments is 90 // unspecified. Consequently, parameters of a function shall not 91 // be used in default argument expressions, even if they are not 92 // evaluated. Parameters of a function declared before a default 93 // argument expression are in scope and can hide namespace and 94 // class member names. 95 return S->Diag(DRE->getLocStart(), 96 diag::err_param_default_argument_references_param) 97 << Param->getDeclName() << DefaultArg->getSourceRange(); 98 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 99 // C++ [dcl.fct.default]p7 100 // Local variables shall not be used in default argument 101 // expressions. 102 if (VDecl->isLocalVarDecl()) 103 return S->Diag(DRE->getLocStart(), 104 diag::err_param_default_argument_references_local) 105 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 106 } 107 108 return false; 109 } 110 111 /// VisitCXXThisExpr - Visit a C++ "this" expression. 112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 113 // C++ [dcl.fct.default]p8: 114 // The keyword this shall not be used in a default argument of a 115 // member function. 116 return S->Diag(ThisE->getLocStart(), 117 diag::err_param_default_argument_references_this) 118 << ThisE->getSourceRange(); 119 } 120 121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 122 bool Invalid = false; 123 for (PseudoObjectExpr::semantics_iterator 124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 125 Expr *E = *i; 126 127 // Look through bindings. 128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 129 E = OVE->getSourceExpr(); 130 assert(E && "pseudo-object binding without source expression?"); 131 } 132 133 Invalid |= Visit(E); 134 } 135 return Invalid; 136 } 137 138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 139 // C++11 [expr.lambda.prim]p13: 140 // A lambda-expression appearing in a default argument shall not 141 // implicitly or explicitly capture any entity. 142 if (Lambda->capture_begin() == Lambda->capture_end()) 143 return false; 144 145 return S->Diag(Lambda->getLocStart(), 146 diag::err_lambda_capture_default_arg); 147 } 148} 149 150void 151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 152 const CXXMethodDecl *Method) { 153 // If we have an MSAny spec already, don't bother. 154 if (!Method || ComputedEST == EST_MSAny) 155 return; 156 157 const FunctionProtoType *Proto 158 = Method->getType()->getAs<FunctionProtoType>(); 159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 160 if (!Proto) 161 return; 162 163 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 164 165 // If this function can throw any exceptions, make a note of that. 166 if (EST == EST_MSAny || EST == EST_None) { 167 ClearExceptions(); 168 ComputedEST = EST; 169 return; 170 } 171 172 // FIXME: If the call to this decl is using any of its default arguments, we 173 // need to search them for potentially-throwing calls. 174 175 // If this function has a basic noexcept, it doesn't affect the outcome. 176 if (EST == EST_BasicNoexcept) 177 return; 178 179 // If we have a throw-all spec at this point, ignore the function. 180 if (ComputedEST == EST_None) 181 return; 182 183 // If we're still at noexcept(true) and there's a nothrow() callee, 184 // change to that specification. 185 if (EST == EST_DynamicNone) { 186 if (ComputedEST == EST_BasicNoexcept) 187 ComputedEST = EST_DynamicNone; 188 return; 189 } 190 191 // Check out noexcept specs. 192 if (EST == EST_ComputedNoexcept) { 193 FunctionProtoType::NoexceptResult NR = 194 Proto->getNoexceptSpec(Self->Context); 195 assert(NR != FunctionProtoType::NR_NoNoexcept && 196 "Must have noexcept result for EST_ComputedNoexcept."); 197 assert(NR != FunctionProtoType::NR_Dependent && 198 "Should not generate implicit declarations for dependent cases, " 199 "and don't know how to handle them anyway."); 200 201 // noexcept(false) -> no spec on the new function 202 if (NR == FunctionProtoType::NR_Throw) { 203 ClearExceptions(); 204 ComputedEST = EST_None; 205 } 206 // noexcept(true) won't change anything either. 207 return; 208 } 209 210 assert(EST == EST_Dynamic && "EST case not considered earlier."); 211 assert(ComputedEST != EST_None && 212 "Shouldn't collect exceptions when throw-all is guaranteed."); 213 ComputedEST = EST_Dynamic; 214 // Record the exceptions in this function's exception specification. 215 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 216 EEnd = Proto->exception_end(); 217 E != EEnd; ++E) 218 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E))) 219 Exceptions.push_back(*E); 220} 221 222void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 223 if (!E || ComputedEST == EST_MSAny) 224 return; 225 226 // FIXME: 227 // 228 // C++0x [except.spec]p14: 229 // [An] implicit exception-specification specifies the type-id T if and 230 // only if T is allowed by the exception-specification of a function directly 231 // invoked by f's implicit definition; f shall allow all exceptions if any 232 // function it directly invokes allows all exceptions, and f shall allow no 233 // exceptions if every function it directly invokes allows no exceptions. 234 // 235 // Note in particular that if an implicit exception-specification is generated 236 // for a function containing a throw-expression, that specification can still 237 // be noexcept(true). 238 // 239 // Note also that 'directly invoked' is not defined in the standard, and there 240 // is no indication that we should only consider potentially-evaluated calls. 241 // 242 // Ultimately we should implement the intent of the standard: the exception 243 // specification should be the set of exceptions which can be thrown by the 244 // implicit definition. For now, we assume that any non-nothrow expression can 245 // throw any exception. 246 247 if (Self->canThrow(E)) 248 ComputedEST = EST_None; 249} 250 251bool 252Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 253 SourceLocation EqualLoc) { 254 if (RequireCompleteType(Param->getLocation(), Param->getType(), 255 diag::err_typecheck_decl_incomplete_type)) { 256 Param->setInvalidDecl(); 257 return true; 258 } 259 260 // C++ [dcl.fct.default]p5 261 // A default argument expression is implicitly converted (clause 262 // 4) to the parameter type. The default argument expression has 263 // the same semantic constraints as the initializer expression in 264 // a declaration of a variable of the parameter type, using the 265 // copy-initialization semantics (8.5). 266 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 267 Param); 268 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 269 EqualLoc); 270 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 271 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 272 if (Result.isInvalid()) 273 return true; 274 Arg = Result.takeAs<Expr>(); 275 276 CheckCompletedExpr(Arg, EqualLoc); 277 Arg = MaybeCreateExprWithCleanups(Arg); 278 279 // Okay: add the default argument to the parameter 280 Param->setDefaultArg(Arg); 281 282 // We have already instantiated this parameter; provide each of the 283 // instantiations with the uninstantiated default argument. 284 UnparsedDefaultArgInstantiationsMap::iterator InstPos 285 = UnparsedDefaultArgInstantiations.find(Param); 286 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 287 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 288 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 289 290 // We're done tracking this parameter's instantiations. 291 UnparsedDefaultArgInstantiations.erase(InstPos); 292 } 293 294 return false; 295} 296 297/// ActOnParamDefaultArgument - Check whether the default argument 298/// provided for a function parameter is well-formed. If so, attach it 299/// to the parameter declaration. 300void 301Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 302 Expr *DefaultArg) { 303 if (!param || !DefaultArg) 304 return; 305 306 ParmVarDecl *Param = cast<ParmVarDecl>(param); 307 UnparsedDefaultArgLocs.erase(Param); 308 309 // Default arguments are only permitted in C++ 310 if (!getLangOpts().CPlusPlus) { 311 Diag(EqualLoc, diag::err_param_default_argument) 312 << DefaultArg->getSourceRange(); 313 Param->setInvalidDecl(); 314 return; 315 } 316 317 // Check for unexpanded parameter packs. 318 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 319 Param->setInvalidDecl(); 320 return; 321 } 322 323 // Check that the default argument is well-formed 324 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 325 if (DefaultArgChecker.Visit(DefaultArg)) { 326 Param->setInvalidDecl(); 327 return; 328 } 329 330 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 331} 332 333/// ActOnParamUnparsedDefaultArgument - We've seen a default 334/// argument for a function parameter, but we can't parse it yet 335/// because we're inside a class definition. Note that this default 336/// argument will be parsed later. 337void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 338 SourceLocation EqualLoc, 339 SourceLocation ArgLoc) { 340 if (!param) 341 return; 342 343 ParmVarDecl *Param = cast<ParmVarDecl>(param); 344 Param->setUnparsedDefaultArg(); 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 Param->setInvalidDecl(); 356 UnparsedDefaultArgLocs.erase(Param); 357} 358 359/// CheckExtraCXXDefaultArguments - Check for any extra default 360/// arguments in the declarator, which is not a function declaration 361/// or definition and therefore is not permitted to have default 362/// arguments. This routine should be invoked for every declarator 363/// that is not a function declaration or definition. 364void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 365 // C++ [dcl.fct.default]p3 366 // A default argument expression shall be specified only in the 367 // parameter-declaration-clause of a function declaration or in a 368 // template-parameter (14.1). It shall not be specified for a 369 // parameter pack. If it is specified in a 370 // parameter-declaration-clause, it shall not occur within a 371 // declarator or abstract-declarator of a parameter-declaration. 372 bool MightBeFunction = D.isFunctionDeclarationContext(); 373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 374 DeclaratorChunk &chunk = D.getTypeObject(i); 375 if (chunk.Kind == DeclaratorChunk::Function) { 376 if (MightBeFunction) { 377 // This is a function declaration. It can have default arguments, but 378 // keep looking in case its return type is a function type with default 379 // arguments. 380 MightBeFunction = false; 381 continue; 382 } 383 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 384 ParmVarDecl *Param = 385 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 386 if (Param->hasUnparsedDefaultArg()) { 387 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 388 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 389 << SourceRange((*Toks)[1].getLocation(), 390 Toks->back().getLocation()); 391 delete Toks; 392 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 393 } else if (Param->getDefaultArg()) { 394 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 395 << Param->getDefaultArg()->getSourceRange(); 396 Param->setDefaultArg(0); 397 } 398 } 399 } else if (chunk.Kind != DeclaratorChunk::Paren) { 400 MightBeFunction = false; 401 } 402 } 403} 404 405static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 406 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 407 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 408 if (!PVD->hasDefaultArg()) 409 return false; 410 if (!PVD->hasInheritedDefaultArg()) 411 return true; 412 } 413 return false; 414} 415 416/// MergeCXXFunctionDecl - Merge two declarations of the same C++ 417/// function, once we already know that they have the same 418/// type. Subroutine of MergeFunctionDecl. Returns true if there was an 419/// error, false otherwise. 420bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 421 Scope *S) { 422 bool Invalid = false; 423 424 // C++ [dcl.fct.default]p4: 425 // For non-template functions, default arguments can be added in 426 // later declarations of a function in the same 427 // scope. Declarations in different scopes have completely 428 // distinct sets of default arguments. That is, declarations in 429 // inner scopes do not acquire default arguments from 430 // declarations in outer scopes, and vice versa. In a given 431 // function declaration, all parameters subsequent to a 432 // parameter with a default argument shall have default 433 // arguments supplied in this or previous declarations. A 434 // default argument shall not be redefined by a later 435 // declaration (not even to the same value). 436 // 437 // C++ [dcl.fct.default]p6: 438 // Except for member functions of class templates, the default arguments 439 // in a member function definition that appears outside of the class 440 // definition are added to the set of default arguments provided by the 441 // member function declaration in the class definition. 442 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 443 ParmVarDecl *OldParam = Old->getParamDecl(p); 444 ParmVarDecl *NewParam = New->getParamDecl(p); 445 446 bool OldParamHasDfl = OldParam->hasDefaultArg(); 447 bool NewParamHasDfl = NewParam->hasDefaultArg(); 448 449 NamedDecl *ND = Old; 450 451 // The declaration context corresponding to the scope is the semantic 452 // parent, unless this is a local function declaration, in which case 453 // it is that surrounding function. 454 DeclContext *ScopeDC = New->getLexicalDeclContext(); 455 if (!ScopeDC->isFunctionOrMethod()) 456 ScopeDC = New->getDeclContext(); 457 if (S && !isDeclInScope(ND, ScopeDC, S) && 458 !New->getDeclContext()->isRecord()) 459 // Ignore default parameters of old decl if they are not in 460 // the same scope and this is not an out-of-line definition of 461 // a member function. 462 OldParamHasDfl = false; 463 464 if (OldParamHasDfl && NewParamHasDfl) { 465 466 unsigned DiagDefaultParamID = 467 diag::err_param_default_argument_redefinition; 468 469 // MSVC accepts that default parameters be redefined for member functions 470 // of template class. The new default parameter's value is ignored. 471 Invalid = true; 472 if (getLangOpts().MicrosoftExt) { 473 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 474 if (MD && MD->getParent()->getDescribedClassTemplate()) { 475 // Merge the old default argument into the new parameter. 476 NewParam->setHasInheritedDefaultArg(); 477 if (OldParam->hasUninstantiatedDefaultArg()) 478 NewParam->setUninstantiatedDefaultArg( 479 OldParam->getUninstantiatedDefaultArg()); 480 else 481 NewParam->setDefaultArg(OldParam->getInit()); 482 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 483 Invalid = false; 484 } 485 } 486 487 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 488 // hint here. Alternatively, we could walk the type-source information 489 // for NewParam to find the last source location in the type... but it 490 // isn't worth the effort right now. This is the kind of test case that 491 // is hard to get right: 492 // int f(int); 493 // void g(int (*fp)(int) = f); 494 // void g(int (*fp)(int) = &f); 495 Diag(NewParam->getLocation(), DiagDefaultParamID) 496 << NewParam->getDefaultArgRange(); 497 498 // Look for the function declaration where the default argument was 499 // actually written, which may be a declaration prior to Old. 500 for (FunctionDecl *Older = Old->getPreviousDecl(); 501 Older; Older = Older->getPreviousDecl()) { 502 if (!Older->getParamDecl(p)->hasDefaultArg()) 503 break; 504 505 OldParam = Older->getParamDecl(p); 506 } 507 508 Diag(OldParam->getLocation(), diag::note_previous_definition) 509 << OldParam->getDefaultArgRange(); 510 } else if (OldParamHasDfl) { 511 // Merge the old default argument into the new parameter. 512 // It's important to use getInit() here; getDefaultArg() 513 // strips off any top-level ExprWithCleanups. 514 NewParam->setHasInheritedDefaultArg(); 515 if (OldParam->hasUninstantiatedDefaultArg()) 516 NewParam->setUninstantiatedDefaultArg( 517 OldParam->getUninstantiatedDefaultArg()); 518 else 519 NewParam->setDefaultArg(OldParam->getInit()); 520 } else if (NewParamHasDfl) { 521 if (New->getDescribedFunctionTemplate()) { 522 // Paragraph 4, quoted above, only applies to non-template functions. 523 Diag(NewParam->getLocation(), 524 diag::err_param_default_argument_template_redecl) 525 << NewParam->getDefaultArgRange(); 526 Diag(Old->getLocation(), diag::note_template_prev_declaration) 527 << false; 528 } else if (New->getTemplateSpecializationKind() 529 != TSK_ImplicitInstantiation && 530 New->getTemplateSpecializationKind() != TSK_Undeclared) { 531 // C++ [temp.expr.spec]p21: 532 // Default function arguments shall not be specified in a declaration 533 // or a definition for one of the following explicit specializations: 534 // - the explicit specialization of a function template; 535 // - the explicit specialization of a member function template; 536 // - the explicit specialization of a member function of a class 537 // template where the class template specialization to which the 538 // member function specialization belongs is implicitly 539 // instantiated. 540 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 541 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 542 << New->getDeclName() 543 << NewParam->getDefaultArgRange(); 544 } else if (New->getDeclContext()->isDependentContext()) { 545 // C++ [dcl.fct.default]p6 (DR217): 546 // Default arguments for a member function of a class template shall 547 // be specified on the initial declaration of the member function 548 // within the class template. 549 // 550 // Reading the tea leaves a bit in DR217 and its reference to DR205 551 // leads me to the conclusion that one cannot add default function 552 // arguments for an out-of-line definition of a member function of a 553 // dependent type. 554 int WhichKind = 2; 555 if (CXXRecordDecl *Record 556 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 557 if (Record->getDescribedClassTemplate()) 558 WhichKind = 0; 559 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 560 WhichKind = 1; 561 else 562 WhichKind = 2; 563 } 564 565 Diag(NewParam->getLocation(), 566 diag::err_param_default_argument_member_template_redecl) 567 << WhichKind 568 << NewParam->getDefaultArgRange(); 569 } 570 } 571 } 572 573 // DR1344: If a default argument is added outside a class definition and that 574 // default argument makes the function a special member function, the program 575 // is ill-formed. This can only happen for constructors. 576 if (isa<CXXConstructorDecl>(New) && 577 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 578 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 579 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 580 if (NewSM != OldSM) { 581 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 582 assert(NewParam->hasDefaultArg()); 583 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 584 << NewParam->getDefaultArgRange() << NewSM; 585 Diag(Old->getLocation(), diag::note_previous_declaration); 586 } 587 } 588 589 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 590 // template has a constexpr specifier then all its declarations shall 591 // contain the constexpr specifier. 592 if (New->isConstexpr() != Old->isConstexpr()) { 593 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 594 << New << New->isConstexpr(); 595 Diag(Old->getLocation(), diag::note_previous_declaration); 596 Invalid = true; 597 } 598 599 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 600 // argument expression, that declaration shall be a definition and shall be 601 // the only declaration of the function or function template in the 602 // translation unit. 603 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 604 functionDeclHasDefaultArgument(Old)) { 605 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 606 Diag(Old->getLocation(), diag::note_previous_declaration); 607 Invalid = true; 608 } 609 610 if (CheckEquivalentExceptionSpec(Old, New)) 611 Invalid = true; 612 613 return Invalid; 614} 615 616/// \brief Merge the exception specifications of two variable declarations. 617/// 618/// This is called when there's a redeclaration of a VarDecl. The function 619/// checks if the redeclaration might have an exception specification and 620/// validates compatibility and merges the specs if necessary. 621void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 622 // Shortcut if exceptions are disabled. 623 if (!getLangOpts().CXXExceptions) 624 return; 625 626 assert(Context.hasSameType(New->getType(), Old->getType()) && 627 "Should only be called if types are otherwise the same."); 628 629 QualType NewType = New->getType(); 630 QualType OldType = Old->getType(); 631 632 // We're only interested in pointers and references to functions, as well 633 // as pointers to member functions. 634 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 635 NewType = R->getPointeeType(); 636 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 637 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 638 NewType = P->getPointeeType(); 639 OldType = OldType->getAs<PointerType>()->getPointeeType(); 640 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 641 NewType = M->getPointeeType(); 642 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 643 } 644 645 if (!NewType->isFunctionProtoType()) 646 return; 647 648 // There's lots of special cases for functions. For function pointers, system 649 // libraries are hopefully not as broken so that we don't need these 650 // workarounds. 651 if (CheckEquivalentExceptionSpec( 652 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 653 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 654 New->setInvalidDecl(); 655 } 656} 657 658/// CheckCXXDefaultArguments - Verify that the default arguments for a 659/// function declaration are well-formed according to C++ 660/// [dcl.fct.default]. 661void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 662 unsigned NumParams = FD->getNumParams(); 663 unsigned p; 664 665 // Find first parameter with a default argument 666 for (p = 0; p < NumParams; ++p) { 667 ParmVarDecl *Param = FD->getParamDecl(p); 668 if (Param->hasDefaultArg()) 669 break; 670 } 671 672 // C++ [dcl.fct.default]p4: 673 // In a given function declaration, all parameters 674 // subsequent to a parameter with a default argument shall 675 // have default arguments supplied in this or previous 676 // declarations. A default argument shall not be redefined 677 // by a later declaration (not even to the same value). 678 unsigned LastMissingDefaultArg = 0; 679 for (; p < NumParams; ++p) { 680 ParmVarDecl *Param = FD->getParamDecl(p); 681 if (!Param->hasDefaultArg()) { 682 if (Param->isInvalidDecl()) 683 /* We already complained about this parameter. */; 684 else if (Param->getIdentifier()) 685 Diag(Param->getLocation(), 686 diag::err_param_default_argument_missing_name) 687 << Param->getIdentifier(); 688 else 689 Diag(Param->getLocation(), 690 diag::err_param_default_argument_missing); 691 692 LastMissingDefaultArg = p; 693 } 694 } 695 696 if (LastMissingDefaultArg > 0) { 697 // Some default arguments were missing. Clear out all of the 698 // default arguments up to (and including) the last missing 699 // default argument, so that we leave the function parameters 700 // in a semantically valid state. 701 for (p = 0; p <= LastMissingDefaultArg; ++p) { 702 ParmVarDecl *Param = FD->getParamDecl(p); 703 if (Param->hasDefaultArg()) { 704 Param->setDefaultArg(0); 705 } 706 } 707 } 708} 709 710// CheckConstexprParameterTypes - Check whether a function's parameter types 711// are all literal types. If so, return true. If not, produce a suitable 712// diagnostic and return false. 713static bool CheckConstexprParameterTypes(Sema &SemaRef, 714 const FunctionDecl *FD) { 715 unsigned ArgIndex = 0; 716 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 717 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 718 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 719 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 720 SourceLocation ParamLoc = PD->getLocation(); 721 if (!(*i)->isDependentType() && 722 SemaRef.RequireLiteralType(ParamLoc, *i, 723 diag::err_constexpr_non_literal_param, 724 ArgIndex+1, PD->getSourceRange(), 725 isa<CXXConstructorDecl>(FD))) 726 return false; 727 } 728 return true; 729} 730 731/// \brief Get diagnostic %select index for tag kind for 732/// record diagnostic message. 733/// WARNING: Indexes apply to particular diagnostics only! 734/// 735/// \returns diagnostic %select index. 736static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 737 switch (Tag) { 738 case TTK_Struct: return 0; 739 case TTK_Interface: return 1; 740 case TTK_Class: return 2; 741 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 742 } 743} 744 745// CheckConstexprFunctionDecl - Check whether a function declaration satisfies 746// the requirements of a constexpr function definition or a constexpr 747// constructor definition. If so, return true. If not, produce appropriate 748// diagnostics and return false. 749// 750// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 751bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 752 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 753 if (MD && MD->isInstance()) { 754 // C++11 [dcl.constexpr]p4: 755 // The definition of a constexpr constructor shall satisfy the following 756 // constraints: 757 // - the class shall not have any virtual base classes; 758 const CXXRecordDecl *RD = MD->getParent(); 759 if (RD->getNumVBases()) { 760 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 761 << isa<CXXConstructorDecl>(NewFD) 762 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 763 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 764 E = RD->vbases_end(); I != E; ++I) 765 Diag(I->getLocStart(), 766 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 767 return false; 768 } 769 } 770 771 if (!isa<CXXConstructorDecl>(NewFD)) { 772 // C++11 [dcl.constexpr]p3: 773 // The definition of a constexpr function shall satisfy the following 774 // constraints: 775 // - it shall not be virtual; 776 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 777 if (Method && Method->isVirtual()) { 778 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 779 780 // If it's not obvious why this function is virtual, find an overridden 781 // function which uses the 'virtual' keyword. 782 const CXXMethodDecl *WrittenVirtual = Method; 783 while (!WrittenVirtual->isVirtualAsWritten()) 784 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 785 if (WrittenVirtual != Method) 786 Diag(WrittenVirtual->getLocation(), 787 diag::note_overridden_virtual_function); 788 return false; 789 } 790 791 // - its return type shall be a literal type; 792 QualType RT = NewFD->getResultType(); 793 if (!RT->isDependentType() && 794 RequireLiteralType(NewFD->getLocation(), RT, 795 diag::err_constexpr_non_literal_return)) 796 return false; 797 } 798 799 // - each of its parameter types shall be a literal type; 800 if (!CheckConstexprParameterTypes(*this, NewFD)) 801 return false; 802 803 return true; 804} 805 806/// Check the given declaration statement is legal within a constexpr function 807/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 808/// 809/// \return true if the body is OK (maybe only as an extension), false if we 810/// have diagnosed a problem. 811static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 812 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 813 // C++11 [dcl.constexpr]p3 and p4: 814 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 815 // contain only 816 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 817 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 818 switch ((*DclIt)->getKind()) { 819 case Decl::StaticAssert: 820 case Decl::Using: 821 case Decl::UsingShadow: 822 case Decl::UsingDirective: 823 case Decl::UnresolvedUsingTypename: 824 case Decl::UnresolvedUsingValue: 825 // - static_assert-declarations 826 // - using-declarations, 827 // - using-directives, 828 continue; 829 830 case Decl::Typedef: 831 case Decl::TypeAlias: { 832 // - typedef declarations and alias-declarations that do not define 833 // classes or enumerations, 834 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 835 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 836 // Don't allow variably-modified types in constexpr functions. 837 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 838 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 839 << TL.getSourceRange() << TL.getType() 840 << isa<CXXConstructorDecl>(Dcl); 841 return false; 842 } 843 continue; 844 } 845 846 case Decl::Enum: 847 case Decl::CXXRecord: 848 // C++1y allows types to be defined, not just declared. 849 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) 850 SemaRef.Diag(DS->getLocStart(), 851 SemaRef.getLangOpts().CPlusPlus1y 852 ? diag::warn_cxx11_compat_constexpr_type_definition 853 : diag::ext_constexpr_type_definition) 854 << isa<CXXConstructorDecl>(Dcl); 855 continue; 856 857 case Decl::EnumConstant: 858 case Decl::IndirectField: 859 case Decl::ParmVar: 860 // These can only appear with other declarations which are banned in 861 // C++11 and permitted in C++1y, so ignore them. 862 continue; 863 864 case Decl::Var: { 865 // C++1y [dcl.constexpr]p3 allows anything except: 866 // a definition of a variable of non-literal type or of static or 867 // thread storage duration or for which no initialization is performed. 868 VarDecl *VD = cast<VarDecl>(*DclIt); 869 if (VD->isThisDeclarationADefinition()) { 870 if (VD->isStaticLocal()) { 871 SemaRef.Diag(VD->getLocation(), 872 diag::err_constexpr_local_var_static) 873 << isa<CXXConstructorDecl>(Dcl) 874 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 875 return false; 876 } 877 if (!VD->getType()->isDependentType() && 878 SemaRef.RequireLiteralType( 879 VD->getLocation(), VD->getType(), 880 diag::err_constexpr_local_var_non_literal_type, 881 isa<CXXConstructorDecl>(Dcl))) 882 return false; 883 if (!VD->hasInit()) { 884 SemaRef.Diag(VD->getLocation(), 885 diag::err_constexpr_local_var_no_init) 886 << isa<CXXConstructorDecl>(Dcl); 887 return false; 888 } 889 } 890 SemaRef.Diag(VD->getLocation(), 891 SemaRef.getLangOpts().CPlusPlus1y 892 ? diag::warn_cxx11_compat_constexpr_local_var 893 : diag::ext_constexpr_local_var) 894 << isa<CXXConstructorDecl>(Dcl); 895 continue; 896 } 897 898 case Decl::NamespaceAlias: 899 case Decl::Function: 900 // These are disallowed in C++11 and permitted in C++1y. Allow them 901 // everywhere as an extension. 902 if (!Cxx1yLoc.isValid()) 903 Cxx1yLoc = DS->getLocStart(); 904 continue; 905 906 default: 907 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 908 << isa<CXXConstructorDecl>(Dcl); 909 return false; 910 } 911 } 912 913 return true; 914} 915 916/// Check that the given field is initialized within a constexpr constructor. 917/// 918/// \param Dcl The constexpr constructor being checked. 919/// \param Field The field being checked. This may be a member of an anonymous 920/// struct or union nested within the class being checked. 921/// \param Inits All declarations, including anonymous struct/union members and 922/// indirect members, for which any initialization was provided. 923/// \param Diagnosed Set to true if an error is produced. 924static void CheckConstexprCtorInitializer(Sema &SemaRef, 925 const FunctionDecl *Dcl, 926 FieldDecl *Field, 927 llvm::SmallSet<Decl*, 16> &Inits, 928 bool &Diagnosed) { 929 if (Field->isInvalidDecl()) 930 return; 931 932 if (Field->isUnnamedBitfield()) 933 return; 934 935 if (Field->isAnonymousStructOrUnion() && 936 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 937 return; 938 939 if (!Inits.count(Field)) { 940 if (!Diagnosed) { 941 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 942 Diagnosed = true; 943 } 944 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 945 } else if (Field->isAnonymousStructOrUnion()) { 946 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 947 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 948 I != E; ++I) 949 // If an anonymous union contains an anonymous struct of which any member 950 // is initialized, all members must be initialized. 951 if (!RD->isUnion() || Inits.count(*I)) 952 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 953 } 954} 955 956/// Check the provided statement is allowed in a constexpr function 957/// definition. 958static bool 959CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 960 SmallVectorImpl<SourceLocation> &ReturnStmts, 961 SourceLocation &Cxx1yLoc) { 962 // - its function-body shall be [...] a compound-statement that contains only 963 switch (S->getStmtClass()) { 964 case Stmt::NullStmtClass: 965 // - null statements, 966 return true; 967 968 case Stmt::DeclStmtClass: 969 // - static_assert-declarations 970 // - using-declarations, 971 // - using-directives, 972 // - typedef declarations and alias-declarations that do not define 973 // classes or enumerations, 974 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 975 return false; 976 return true; 977 978 case Stmt::ReturnStmtClass: 979 // - and exactly one return statement; 980 if (isa<CXXConstructorDecl>(Dcl)) { 981 // C++1y allows return statements in constexpr constructors. 982 if (!Cxx1yLoc.isValid()) 983 Cxx1yLoc = S->getLocStart(); 984 return true; 985 } 986 987 ReturnStmts.push_back(S->getLocStart()); 988 return true; 989 990 case Stmt::CompoundStmtClass: { 991 // C++1y allows compound-statements. 992 if (!Cxx1yLoc.isValid()) 993 Cxx1yLoc = S->getLocStart(); 994 995 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 996 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(), 997 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) { 998 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts, 999 Cxx1yLoc)) 1000 return false; 1001 } 1002 return true; 1003 } 1004 1005 case Stmt::AttributedStmtClass: 1006 if (!Cxx1yLoc.isValid()) 1007 Cxx1yLoc = S->getLocStart(); 1008 return true; 1009 1010 case Stmt::IfStmtClass: { 1011 // C++1y allows if-statements. 1012 if (!Cxx1yLoc.isValid()) 1013 Cxx1yLoc = S->getLocStart(); 1014 1015 IfStmt *If = cast<IfStmt>(S); 1016 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1017 Cxx1yLoc)) 1018 return false; 1019 if (If->getElse() && 1020 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1021 Cxx1yLoc)) 1022 return false; 1023 return true; 1024 } 1025 1026 case Stmt::WhileStmtClass: 1027 case Stmt::DoStmtClass: 1028 case Stmt::ForStmtClass: 1029 case Stmt::CXXForRangeStmtClass: 1030 case Stmt::ContinueStmtClass: 1031 // C++1y allows all of these. We don't allow them as extensions in C++11, 1032 // because they don't make sense without variable mutation. 1033 if (!SemaRef.getLangOpts().CPlusPlus1y) 1034 break; 1035 if (!Cxx1yLoc.isValid()) 1036 Cxx1yLoc = S->getLocStart(); 1037 for (Stmt::child_range Children = S->children(); Children; ++Children) 1038 if (*Children && 1039 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1040 Cxx1yLoc)) 1041 return false; 1042 return true; 1043 1044 case Stmt::SwitchStmtClass: 1045 case Stmt::CaseStmtClass: 1046 case Stmt::DefaultStmtClass: 1047 case Stmt::BreakStmtClass: 1048 // C++1y allows switch-statements, and since they don't need variable 1049 // mutation, we can reasonably allow them in C++11 as an extension. 1050 if (!Cxx1yLoc.isValid()) 1051 Cxx1yLoc = S->getLocStart(); 1052 for (Stmt::child_range Children = S->children(); Children; ++Children) 1053 if (*Children && 1054 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1055 Cxx1yLoc)) 1056 return false; 1057 return true; 1058 1059 default: 1060 if (!isa<Expr>(S)) 1061 break; 1062 1063 // C++1y allows expression-statements. 1064 if (!Cxx1yLoc.isValid()) 1065 Cxx1yLoc = S->getLocStart(); 1066 return true; 1067 } 1068 1069 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1070 << isa<CXXConstructorDecl>(Dcl); 1071 return false; 1072} 1073 1074/// Check the body for the given constexpr function declaration only contains 1075/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1076/// 1077/// \return true if the body is OK, false if we have diagnosed a problem. 1078bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1079 if (isa<CXXTryStmt>(Body)) { 1080 // C++11 [dcl.constexpr]p3: 1081 // The definition of a constexpr function shall satisfy the following 1082 // constraints: [...] 1083 // - its function-body shall be = delete, = default, or a 1084 // compound-statement 1085 // 1086 // C++11 [dcl.constexpr]p4: 1087 // In the definition of a constexpr constructor, [...] 1088 // - its function-body shall not be a function-try-block; 1089 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1090 << isa<CXXConstructorDecl>(Dcl); 1091 return false; 1092 } 1093 1094 SmallVector<SourceLocation, 4> ReturnStmts; 1095 1096 // - its function-body shall be [...] a compound-statement that contains only 1097 // [... list of cases ...] 1098 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1099 SourceLocation Cxx1yLoc; 1100 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 1101 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 1102 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc)) 1103 return false; 1104 } 1105 1106 if (Cxx1yLoc.isValid()) 1107 Diag(Cxx1yLoc, 1108 getLangOpts().CPlusPlus1y 1109 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1110 : diag::ext_constexpr_body_invalid_stmt) 1111 << isa<CXXConstructorDecl>(Dcl); 1112 1113 if (const CXXConstructorDecl *Constructor 1114 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1115 const CXXRecordDecl *RD = Constructor->getParent(); 1116 // DR1359: 1117 // - every non-variant non-static data member and base class sub-object 1118 // shall be initialized; 1119 // - if the class is a non-empty union, or for each non-empty anonymous 1120 // union member of a non-union class, exactly one non-static data member 1121 // shall be initialized; 1122 if (RD->isUnion()) { 1123 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 1124 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1125 return false; 1126 } 1127 } else if (!Constructor->isDependentContext() && 1128 !Constructor->isDelegatingConstructor()) { 1129 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1130 1131 // Skip detailed checking if we have enough initializers, and we would 1132 // allow at most one initializer per member. 1133 bool AnyAnonStructUnionMembers = false; 1134 unsigned Fields = 0; 1135 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1136 E = RD->field_end(); I != E; ++I, ++Fields) { 1137 if (I->isAnonymousStructOrUnion()) { 1138 AnyAnonStructUnionMembers = true; 1139 break; 1140 } 1141 } 1142 if (AnyAnonStructUnionMembers || 1143 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1144 // Check initialization of non-static data members. Base classes are 1145 // always initialized so do not need to be checked. Dependent bases 1146 // might not have initializers in the member initializer list. 1147 llvm::SmallSet<Decl*, 16> Inits; 1148 for (CXXConstructorDecl::init_const_iterator 1149 I = Constructor->init_begin(), E = Constructor->init_end(); 1150 I != E; ++I) { 1151 if (FieldDecl *FD = (*I)->getMember()) 1152 Inits.insert(FD); 1153 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 1154 Inits.insert(ID->chain_begin(), ID->chain_end()); 1155 } 1156 1157 bool Diagnosed = false; 1158 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1159 E = RD->field_end(); I != E; ++I) 1160 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 1161 if (Diagnosed) 1162 return false; 1163 } 1164 } 1165 } else { 1166 if (ReturnStmts.empty()) { 1167 // C++1y doesn't require constexpr functions to contain a 'return' 1168 // statement. We still do, unless the return type is void, because 1169 // otherwise if there's no return statement, the function cannot 1170 // be used in a core constant expression. 1171 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType(); 1172 Diag(Dcl->getLocation(), 1173 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1174 : diag::err_constexpr_body_no_return); 1175 return OK; 1176 } 1177 if (ReturnStmts.size() > 1) { 1178 Diag(ReturnStmts.back(), 1179 getLangOpts().CPlusPlus1y 1180 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1181 : diag::ext_constexpr_body_multiple_return); 1182 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1183 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1184 } 1185 } 1186 1187 // C++11 [dcl.constexpr]p5: 1188 // if no function argument values exist such that the function invocation 1189 // substitution would produce a constant expression, the program is 1190 // ill-formed; no diagnostic required. 1191 // C++11 [dcl.constexpr]p3: 1192 // - every constructor call and implicit conversion used in initializing the 1193 // return value shall be one of those allowed in a constant expression. 1194 // C++11 [dcl.constexpr]p4: 1195 // - every constructor involved in initializing non-static data members and 1196 // base class sub-objects shall be a constexpr constructor. 1197 SmallVector<PartialDiagnosticAt, 8> Diags; 1198 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1199 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1200 << isa<CXXConstructorDecl>(Dcl); 1201 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1202 Diag(Diags[I].first, Diags[I].second); 1203 // Don't return false here: we allow this for compatibility in 1204 // system headers. 1205 } 1206 1207 return true; 1208} 1209 1210/// isCurrentClassName - Determine whether the identifier II is the 1211/// name of the class type currently being defined. In the case of 1212/// nested classes, this will only return true if II is the name of 1213/// the innermost class. 1214bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1215 const CXXScopeSpec *SS) { 1216 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1217 1218 CXXRecordDecl *CurDecl; 1219 if (SS && SS->isSet() && !SS->isInvalid()) { 1220 DeclContext *DC = computeDeclContext(*SS, true); 1221 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1222 } else 1223 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1224 1225 if (CurDecl && CurDecl->getIdentifier()) 1226 return &II == CurDecl->getIdentifier(); 1227 return false; 1228} 1229 1230/// \brief Determine whether the identifier II is a typo for the name of 1231/// the class type currently being defined. If so, update it to the identifier 1232/// that should have been used. 1233bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1234 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1235 1236 if (!getLangOpts().SpellChecking) 1237 return false; 1238 1239 CXXRecordDecl *CurDecl; 1240 if (SS && SS->isSet() && !SS->isInvalid()) { 1241 DeclContext *DC = computeDeclContext(*SS, true); 1242 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1243 } else 1244 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1245 1246 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1247 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1248 < II->getLength()) { 1249 II = CurDecl->getIdentifier(); 1250 return true; 1251 } 1252 1253 return false; 1254} 1255 1256/// \brief Determine whether the given class is a base class of the given 1257/// class, including looking at dependent bases. 1258static bool findCircularInheritance(const CXXRecordDecl *Class, 1259 const CXXRecordDecl *Current) { 1260 SmallVector<const CXXRecordDecl*, 8> Queue; 1261 1262 Class = Class->getCanonicalDecl(); 1263 while (true) { 1264 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(), 1265 E = Current->bases_end(); 1266 I != E; ++I) { 1267 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 1268 if (!Base) 1269 continue; 1270 1271 Base = Base->getDefinition(); 1272 if (!Base) 1273 continue; 1274 1275 if (Base->getCanonicalDecl() == Class) 1276 return true; 1277 1278 Queue.push_back(Base); 1279 } 1280 1281 if (Queue.empty()) 1282 return false; 1283 1284 Current = Queue.pop_back_val(); 1285 } 1286 1287 return false; 1288} 1289 1290/// \brief Check the validity of a C++ base class specifier. 1291/// 1292/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1293/// and returns NULL otherwise. 1294CXXBaseSpecifier * 1295Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1296 SourceRange SpecifierRange, 1297 bool Virtual, AccessSpecifier Access, 1298 TypeSourceInfo *TInfo, 1299 SourceLocation EllipsisLoc) { 1300 QualType BaseType = TInfo->getType(); 1301 1302 // C++ [class.union]p1: 1303 // A union shall not have base classes. 1304 if (Class->isUnion()) { 1305 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1306 << SpecifierRange; 1307 return 0; 1308 } 1309 1310 if (EllipsisLoc.isValid() && 1311 !TInfo->getType()->containsUnexpandedParameterPack()) { 1312 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1313 << TInfo->getTypeLoc().getSourceRange(); 1314 EllipsisLoc = SourceLocation(); 1315 } 1316 1317 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1318 1319 if (BaseType->isDependentType()) { 1320 // Make sure that we don't have circular inheritance among our dependent 1321 // bases. For non-dependent bases, the check for completeness below handles 1322 // this. 1323 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1324 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1325 ((BaseDecl = BaseDecl->getDefinition()) && 1326 findCircularInheritance(Class, BaseDecl))) { 1327 Diag(BaseLoc, diag::err_circular_inheritance) 1328 << BaseType << Context.getTypeDeclType(Class); 1329 1330 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1331 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1332 << BaseType; 1333 1334 return 0; 1335 } 1336 } 1337 1338 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1339 Class->getTagKind() == TTK_Class, 1340 Access, TInfo, EllipsisLoc); 1341 } 1342 1343 // Base specifiers must be record types. 1344 if (!BaseType->isRecordType()) { 1345 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1346 return 0; 1347 } 1348 1349 // C++ [class.union]p1: 1350 // A union shall not be used as a base class. 1351 if (BaseType->isUnionType()) { 1352 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1353 return 0; 1354 } 1355 1356 // C++ [class.derived]p2: 1357 // The class-name in a base-specifier shall not be an incompletely 1358 // defined class. 1359 if (RequireCompleteType(BaseLoc, BaseType, 1360 diag::err_incomplete_base_class, SpecifierRange)) { 1361 Class->setInvalidDecl(); 1362 return 0; 1363 } 1364 1365 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1366 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1367 assert(BaseDecl && "Record type has no declaration"); 1368 BaseDecl = BaseDecl->getDefinition(); 1369 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1370 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1371 assert(CXXBaseDecl && "Base type is not a C++ type"); 1372 1373 // C++ [class]p3: 1374 // If a class is marked final and it appears as a base-type-specifier in 1375 // base-clause, the program is ill-formed. 1376 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 1377 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1378 << CXXBaseDecl->getDeclName(); 1379 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1380 << CXXBaseDecl->getDeclName(); 1381 return 0; 1382 } 1383 1384 if (BaseDecl->isInvalidDecl()) 1385 Class->setInvalidDecl(); 1386 1387 // Create the base specifier. 1388 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1389 Class->getTagKind() == TTK_Class, 1390 Access, TInfo, EllipsisLoc); 1391} 1392 1393/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1394/// one entry in the base class list of a class specifier, for 1395/// example: 1396/// class foo : public bar, virtual private baz { 1397/// 'public bar' and 'virtual private baz' are each base-specifiers. 1398BaseResult 1399Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1400 ParsedAttributes &Attributes, 1401 bool Virtual, AccessSpecifier Access, 1402 ParsedType basetype, SourceLocation BaseLoc, 1403 SourceLocation EllipsisLoc) { 1404 if (!classdecl) 1405 return true; 1406 1407 AdjustDeclIfTemplate(classdecl); 1408 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1409 if (!Class) 1410 return true; 1411 1412 // We do not support any C++11 attributes on base-specifiers yet. 1413 // Diagnose any attributes we see. 1414 if (!Attributes.empty()) { 1415 for (AttributeList *Attr = Attributes.getList(); Attr; 1416 Attr = Attr->getNext()) { 1417 if (Attr->isInvalid() || 1418 Attr->getKind() == AttributeList::IgnoredAttribute) 1419 continue; 1420 Diag(Attr->getLoc(), 1421 Attr->getKind() == AttributeList::UnknownAttribute 1422 ? diag::warn_unknown_attribute_ignored 1423 : diag::err_base_specifier_attribute) 1424 << Attr->getName(); 1425 } 1426 } 1427 1428 TypeSourceInfo *TInfo = 0; 1429 GetTypeFromParser(basetype, &TInfo); 1430 1431 if (EllipsisLoc.isInvalid() && 1432 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1433 UPPC_BaseType)) 1434 return true; 1435 1436 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1437 Virtual, Access, TInfo, 1438 EllipsisLoc)) 1439 return BaseSpec; 1440 else 1441 Class->setInvalidDecl(); 1442 1443 return true; 1444} 1445 1446/// \brief Performs the actual work of attaching the given base class 1447/// specifiers to a C++ class. 1448bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1449 unsigned NumBases) { 1450 if (NumBases == 0) 1451 return false; 1452 1453 // Used to keep track of which base types we have already seen, so 1454 // that we can properly diagnose redundant direct base types. Note 1455 // that the key is always the unqualified canonical type of the base 1456 // class. 1457 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1458 1459 // Copy non-redundant base specifiers into permanent storage. 1460 unsigned NumGoodBases = 0; 1461 bool Invalid = false; 1462 for (unsigned idx = 0; idx < NumBases; ++idx) { 1463 QualType NewBaseType 1464 = Context.getCanonicalType(Bases[idx]->getType()); 1465 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1466 1467 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1468 if (KnownBase) { 1469 // C++ [class.mi]p3: 1470 // A class shall not be specified as a direct base class of a 1471 // derived class more than once. 1472 Diag(Bases[idx]->getLocStart(), 1473 diag::err_duplicate_base_class) 1474 << KnownBase->getType() 1475 << Bases[idx]->getSourceRange(); 1476 1477 // Delete the duplicate base class specifier; we're going to 1478 // overwrite its pointer later. 1479 Context.Deallocate(Bases[idx]); 1480 1481 Invalid = true; 1482 } else { 1483 // Okay, add this new base class. 1484 KnownBase = Bases[idx]; 1485 Bases[NumGoodBases++] = Bases[idx]; 1486 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1487 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1488 if (Class->isInterface() && 1489 (!RD->isInterface() || 1490 KnownBase->getAccessSpecifier() != AS_public)) { 1491 // The Microsoft extension __interface does not permit bases that 1492 // are not themselves public interfaces. 1493 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1494 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1495 << RD->getSourceRange(); 1496 Invalid = true; 1497 } 1498 if (RD->hasAttr<WeakAttr>()) 1499 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1500 } 1501 } 1502 } 1503 1504 // Attach the remaining base class specifiers to the derived class. 1505 Class->setBases(Bases, NumGoodBases); 1506 1507 // Delete the remaining (good) base class specifiers, since their 1508 // data has been copied into the CXXRecordDecl. 1509 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1510 Context.Deallocate(Bases[idx]); 1511 1512 return Invalid; 1513} 1514 1515/// ActOnBaseSpecifiers - Attach the given base specifiers to the 1516/// class, after checking whether there are any duplicate base 1517/// classes. 1518void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1519 unsigned NumBases) { 1520 if (!ClassDecl || !Bases || !NumBases) 1521 return; 1522 1523 AdjustDeclIfTemplate(ClassDecl); 1524 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1525} 1526 1527/// \brief Determine whether the type \p Derived is a C++ class that is 1528/// derived from the type \p Base. 1529bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1530 if (!getLangOpts().CPlusPlus) 1531 return false; 1532 1533 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1534 if (!DerivedRD) 1535 return false; 1536 1537 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1538 if (!BaseRD) 1539 return false; 1540 1541 // If either the base or the derived type is invalid, don't try to 1542 // check whether one is derived from the other. 1543 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1544 return false; 1545 1546 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1547 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1548} 1549 1550/// \brief Determine whether the type \p Derived is a C++ class that is 1551/// derived from the type \p Base. 1552bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1553 if (!getLangOpts().CPlusPlus) 1554 return false; 1555 1556 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1557 if (!DerivedRD) 1558 return false; 1559 1560 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1561 if (!BaseRD) 1562 return false; 1563 1564 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1565} 1566 1567void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1568 CXXCastPath &BasePathArray) { 1569 assert(BasePathArray.empty() && "Base path array must be empty!"); 1570 assert(Paths.isRecordingPaths() && "Must record paths!"); 1571 1572 const CXXBasePath &Path = Paths.front(); 1573 1574 // We first go backward and check if we have a virtual base. 1575 // FIXME: It would be better if CXXBasePath had the base specifier for 1576 // the nearest virtual base. 1577 unsigned Start = 0; 1578 for (unsigned I = Path.size(); I != 0; --I) { 1579 if (Path[I - 1].Base->isVirtual()) { 1580 Start = I - 1; 1581 break; 1582 } 1583 } 1584 1585 // Now add all bases. 1586 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1587 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1588} 1589 1590/// \brief Determine whether the given base path includes a virtual 1591/// base class. 1592bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1593 for (CXXCastPath::const_iterator B = BasePath.begin(), 1594 BEnd = BasePath.end(); 1595 B != BEnd; ++B) 1596 if ((*B)->isVirtual()) 1597 return true; 1598 1599 return false; 1600} 1601 1602/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1603/// conversion (where Derived and Base are class types) is 1604/// well-formed, meaning that the conversion is unambiguous (and 1605/// that all of the base classes are accessible). Returns true 1606/// and emits a diagnostic if the code is ill-formed, returns false 1607/// otherwise. Loc is the location where this routine should point to 1608/// if there is an error, and Range is the source range to highlight 1609/// if there is an error. 1610bool 1611Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1612 unsigned InaccessibleBaseID, 1613 unsigned AmbigiousBaseConvID, 1614 SourceLocation Loc, SourceRange Range, 1615 DeclarationName Name, 1616 CXXCastPath *BasePath) { 1617 // First, determine whether the path from Derived to Base is 1618 // ambiguous. This is slightly more expensive than checking whether 1619 // the Derived to Base conversion exists, because here we need to 1620 // explore multiple paths to determine if there is an ambiguity. 1621 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1622 /*DetectVirtual=*/false); 1623 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1624 assert(DerivationOkay && 1625 "Can only be used with a derived-to-base conversion"); 1626 (void)DerivationOkay; 1627 1628 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1629 if (InaccessibleBaseID) { 1630 // Check that the base class can be accessed. 1631 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1632 InaccessibleBaseID)) { 1633 case AR_inaccessible: 1634 return true; 1635 case AR_accessible: 1636 case AR_dependent: 1637 case AR_delayed: 1638 break; 1639 } 1640 } 1641 1642 // Build a base path if necessary. 1643 if (BasePath) 1644 BuildBasePathArray(Paths, *BasePath); 1645 return false; 1646 } 1647 1648 if (AmbigiousBaseConvID) { 1649 // We know that the derived-to-base conversion is ambiguous, and 1650 // we're going to produce a diagnostic. Perform the derived-to-base 1651 // search just one more time to compute all of the possible paths so 1652 // that we can print them out. This is more expensive than any of 1653 // the previous derived-to-base checks we've done, but at this point 1654 // performance isn't as much of an issue. 1655 Paths.clear(); 1656 Paths.setRecordingPaths(true); 1657 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1658 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1659 (void)StillOkay; 1660 1661 // Build up a textual representation of the ambiguous paths, e.g., 1662 // D -> B -> A, that will be used to illustrate the ambiguous 1663 // conversions in the diagnostic. We only print one of the paths 1664 // to each base class subobject. 1665 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1666 1667 Diag(Loc, AmbigiousBaseConvID) 1668 << Derived << Base << PathDisplayStr << Range << Name; 1669 } 1670 return true; 1671} 1672 1673bool 1674Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1675 SourceLocation Loc, SourceRange Range, 1676 CXXCastPath *BasePath, 1677 bool IgnoreAccess) { 1678 return CheckDerivedToBaseConversion(Derived, Base, 1679 IgnoreAccess ? 0 1680 : diag::err_upcast_to_inaccessible_base, 1681 diag::err_ambiguous_derived_to_base_conv, 1682 Loc, Range, DeclarationName(), 1683 BasePath); 1684} 1685 1686 1687/// @brief Builds a string representing ambiguous paths from a 1688/// specific derived class to different subobjects of the same base 1689/// class. 1690/// 1691/// This function builds a string that can be used in error messages 1692/// to show the different paths that one can take through the 1693/// inheritance hierarchy to go from the derived class to different 1694/// subobjects of a base class. The result looks something like this: 1695/// @code 1696/// struct D -> struct B -> struct A 1697/// struct D -> struct C -> struct A 1698/// @endcode 1699std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1700 std::string PathDisplayStr; 1701 std::set<unsigned> DisplayedPaths; 1702 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1703 Path != Paths.end(); ++Path) { 1704 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1705 // We haven't displayed a path to this particular base 1706 // class subobject yet. 1707 PathDisplayStr += "\n "; 1708 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1709 for (CXXBasePath::const_iterator Element = Path->begin(); 1710 Element != Path->end(); ++Element) 1711 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1712 } 1713 } 1714 1715 return PathDisplayStr; 1716} 1717 1718//===----------------------------------------------------------------------===// 1719// C++ class member Handling 1720//===----------------------------------------------------------------------===// 1721 1722/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1723bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1724 SourceLocation ASLoc, 1725 SourceLocation ColonLoc, 1726 AttributeList *Attrs) { 1727 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1728 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1729 ASLoc, ColonLoc); 1730 CurContext->addHiddenDecl(ASDecl); 1731 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1732} 1733 1734/// CheckOverrideControl - Check C++11 override control semantics. 1735void Sema::CheckOverrideControl(NamedDecl *D) { 1736 if (D->isInvalidDecl()) 1737 return; 1738 1739 // We only care about "override" and "final" declarations. 1740 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1741 return; 1742 1743 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1744 1745 // We can't check dependent instance methods. 1746 if (MD && MD->isInstance() && 1747 (MD->getParent()->hasAnyDependentBases() || 1748 MD->getType()->isDependentType())) 1749 return; 1750 1751 if (MD && !MD->isVirtual()) { 1752 // If we have a non-virtual method, check if if hides a virtual method. 1753 // (In that case, it's most likely the method has the wrong type.) 1754 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1755 FindHiddenVirtualMethods(MD, OverloadedMethods); 1756 1757 if (!OverloadedMethods.empty()) { 1758 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1759 Diag(OA->getLocation(), 1760 diag::override_keyword_hides_virtual_member_function) 1761 << "override" << (OverloadedMethods.size() > 1); 1762 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1763 Diag(FA->getLocation(), 1764 diag::override_keyword_hides_virtual_member_function) 1765 << "final" << (OverloadedMethods.size() > 1); 1766 } 1767 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1768 MD->setInvalidDecl(); 1769 return; 1770 } 1771 // Fall through into the general case diagnostic. 1772 // FIXME: We might want to attempt typo correction here. 1773 } 1774 1775 if (!MD || !MD->isVirtual()) { 1776 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1777 Diag(OA->getLocation(), 1778 diag::override_keyword_only_allowed_on_virtual_member_functions) 1779 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1780 D->dropAttr<OverrideAttr>(); 1781 } 1782 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1783 Diag(FA->getLocation(), 1784 diag::override_keyword_only_allowed_on_virtual_member_functions) 1785 << "final" << FixItHint::CreateRemoval(FA->getLocation()); 1786 D->dropAttr<FinalAttr>(); 1787 } 1788 return; 1789 } 1790 1791 // C++11 [class.virtual]p5: 1792 // If a virtual function is marked with the virt-specifier override and 1793 // does not override a member function of a base class, the program is 1794 // ill-formed. 1795 bool HasOverriddenMethods = 1796 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1797 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1798 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1799 << MD->getDeclName(); 1800} 1801 1802/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1803/// function overrides a virtual member function marked 'final', according to 1804/// C++11 [class.virtual]p4. 1805bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1806 const CXXMethodDecl *Old) { 1807 if (!Old->hasAttr<FinalAttr>()) 1808 return false; 1809 1810 Diag(New->getLocation(), diag::err_final_function_overridden) 1811 << New->getDeclName(); 1812 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1813 return true; 1814} 1815 1816static bool InitializationHasSideEffects(const FieldDecl &FD) { 1817 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1818 // FIXME: Destruction of ObjC lifetime types has side-effects. 1819 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1820 return !RD->isCompleteDefinition() || 1821 !RD->hasTrivialDefaultConstructor() || 1822 !RD->hasTrivialDestructor(); 1823 return false; 1824} 1825 1826static AttributeList *getMSPropertyAttr(AttributeList *list) { 1827 for (AttributeList* it = list; it != 0; it = it->getNext()) 1828 if (it->isDeclspecPropertyAttribute()) 1829 return it; 1830 return 0; 1831} 1832 1833/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1834/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1835/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1836/// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1837/// present (but parsing it has been deferred). 1838NamedDecl * 1839Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1840 MultiTemplateParamsArg TemplateParameterLists, 1841 Expr *BW, const VirtSpecifiers &VS, 1842 InClassInitStyle InitStyle) { 1843 const DeclSpec &DS = D.getDeclSpec(); 1844 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1845 DeclarationName Name = NameInfo.getName(); 1846 SourceLocation Loc = NameInfo.getLoc(); 1847 1848 // For anonymous bitfields, the location should point to the type. 1849 if (Loc.isInvalid()) 1850 Loc = D.getLocStart(); 1851 1852 Expr *BitWidth = static_cast<Expr*>(BW); 1853 1854 assert(isa<CXXRecordDecl>(CurContext)); 1855 assert(!DS.isFriendSpecified()); 1856 1857 bool isFunc = D.isDeclarationOfFunction(); 1858 1859 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1860 // The Microsoft extension __interface only permits public member functions 1861 // and prohibits constructors, destructors, operators, non-public member 1862 // functions, static methods and data members. 1863 unsigned InvalidDecl; 1864 bool ShowDeclName = true; 1865 if (!isFunc) 1866 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1867 else if (AS != AS_public) 1868 InvalidDecl = 2; 1869 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1870 InvalidDecl = 3; 1871 else switch (Name.getNameKind()) { 1872 case DeclarationName::CXXConstructorName: 1873 InvalidDecl = 4; 1874 ShowDeclName = false; 1875 break; 1876 1877 case DeclarationName::CXXDestructorName: 1878 InvalidDecl = 5; 1879 ShowDeclName = false; 1880 break; 1881 1882 case DeclarationName::CXXOperatorName: 1883 case DeclarationName::CXXConversionFunctionName: 1884 InvalidDecl = 6; 1885 break; 1886 1887 default: 1888 InvalidDecl = 0; 1889 break; 1890 } 1891 1892 if (InvalidDecl) { 1893 if (ShowDeclName) 1894 Diag(Loc, diag::err_invalid_member_in_interface) 1895 << (InvalidDecl-1) << Name; 1896 else 1897 Diag(Loc, diag::err_invalid_member_in_interface) 1898 << (InvalidDecl-1) << ""; 1899 return 0; 1900 } 1901 } 1902 1903 // C++ 9.2p6: A member shall not be declared to have automatic storage 1904 // duration (auto, register) or with the extern storage-class-specifier. 1905 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1906 // data members and cannot be applied to names declared const or static, 1907 // and cannot be applied to reference members. 1908 switch (DS.getStorageClassSpec()) { 1909 case DeclSpec::SCS_unspecified: 1910 case DeclSpec::SCS_typedef: 1911 case DeclSpec::SCS_static: 1912 break; 1913 case DeclSpec::SCS_mutable: 1914 if (isFunc) { 1915 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1916 1917 // FIXME: It would be nicer if the keyword was ignored only for this 1918 // declarator. Otherwise we could get follow-up errors. 1919 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1920 } 1921 break; 1922 default: 1923 Diag(DS.getStorageClassSpecLoc(), 1924 diag::err_storageclass_invalid_for_member); 1925 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1926 break; 1927 } 1928 1929 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1930 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1931 !isFunc); 1932 1933 if (DS.isConstexprSpecified() && isInstField) { 1934 SemaDiagnosticBuilder B = 1935 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 1936 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 1937 if (InitStyle == ICIS_NoInit) { 1938 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const"); 1939 D.getMutableDeclSpec().ClearConstexprSpec(); 1940 const char *PrevSpec; 1941 unsigned DiagID; 1942 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc, 1943 PrevSpec, DiagID, getLangOpts()); 1944 (void)Failed; 1945 assert(!Failed && "Making a constexpr member const shouldn't fail"); 1946 } else { 1947 B << 1; 1948 const char *PrevSpec; 1949 unsigned DiagID; 1950 if (D.getMutableDeclSpec().SetStorageClassSpec( 1951 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) { 1952 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 1953 "This is the only DeclSpec that should fail to be applied"); 1954 B << 1; 1955 } else { 1956 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 1957 isInstField = false; 1958 } 1959 } 1960 } 1961 1962 NamedDecl *Member; 1963 if (isInstField) { 1964 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1965 1966 // Data members must have identifiers for names. 1967 if (!Name.isIdentifier()) { 1968 Diag(Loc, diag::err_bad_variable_name) 1969 << Name; 1970 return 0; 1971 } 1972 1973 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1974 1975 // Member field could not be with "template" keyword. 1976 // So TemplateParameterLists should be empty in this case. 1977 if (TemplateParameterLists.size()) { 1978 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 1979 if (TemplateParams->size()) { 1980 // There is no such thing as a member field template. 1981 Diag(D.getIdentifierLoc(), diag::err_template_member) 1982 << II 1983 << SourceRange(TemplateParams->getTemplateLoc(), 1984 TemplateParams->getRAngleLoc()); 1985 } else { 1986 // There is an extraneous 'template<>' for this member. 1987 Diag(TemplateParams->getTemplateLoc(), 1988 diag::err_template_member_noparams) 1989 << II 1990 << SourceRange(TemplateParams->getTemplateLoc(), 1991 TemplateParams->getRAngleLoc()); 1992 } 1993 return 0; 1994 } 1995 1996 if (SS.isSet() && !SS.isInvalid()) { 1997 // The user provided a superfluous scope specifier inside a class 1998 // definition: 1999 // 2000 // class X { 2001 // int X::member; 2002 // }; 2003 if (DeclContext *DC = computeDeclContext(SS, false)) 2004 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2005 else 2006 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2007 << Name << SS.getRange(); 2008 2009 SS.clear(); 2010 } 2011 2012 AttributeList *MSPropertyAttr = 2013 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2014 if (MSPropertyAttr) { 2015 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2016 BitWidth, InitStyle, AS, MSPropertyAttr); 2017 if (!Member) 2018 return 0; 2019 isInstField = false; 2020 } else { 2021 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2022 BitWidth, InitStyle, AS); 2023 assert(Member && "HandleField never returns null"); 2024 } 2025 } else { 2026 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2027 2028 Member = HandleDeclarator(S, D, TemplateParameterLists); 2029 if (!Member) 2030 return 0; 2031 2032 // Non-instance-fields can't have a bitfield. 2033 if (BitWidth) { 2034 if (Member->isInvalidDecl()) { 2035 // don't emit another diagnostic. 2036 } else if (isa<VarDecl>(Member)) { 2037 // C++ 9.6p3: A bit-field shall not be a static member. 2038 // "static member 'A' cannot be a bit-field" 2039 Diag(Loc, diag::err_static_not_bitfield) 2040 << Name << BitWidth->getSourceRange(); 2041 } else if (isa<TypedefDecl>(Member)) { 2042 // "typedef member 'x' cannot be a bit-field" 2043 Diag(Loc, diag::err_typedef_not_bitfield) 2044 << Name << BitWidth->getSourceRange(); 2045 } else { 2046 // A function typedef ("typedef int f(); f a;"). 2047 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2048 Diag(Loc, diag::err_not_integral_type_bitfield) 2049 << Name << cast<ValueDecl>(Member)->getType() 2050 << BitWidth->getSourceRange(); 2051 } 2052 2053 BitWidth = 0; 2054 Member->setInvalidDecl(); 2055 } 2056 2057 Member->setAccess(AS); 2058 2059 // If we have declared a member function template or static data member 2060 // template, set the access of the templated declaration as well. 2061 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2062 FunTmpl->getTemplatedDecl()->setAccess(AS); 2063 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2064 VarTmpl->getTemplatedDecl()->setAccess(AS); 2065 } 2066 2067 if (VS.isOverrideSpecified()) 2068 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 2069 if (VS.isFinalSpecified()) 2070 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 2071 2072 if (VS.getLastLocation().isValid()) { 2073 // Update the end location of a method that has a virt-specifiers. 2074 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2075 MD->setRangeEnd(VS.getLastLocation()); 2076 } 2077 2078 CheckOverrideControl(Member); 2079 2080 assert((Name || isInstField) && "No identifier for non-field ?"); 2081 2082 if (isInstField) { 2083 FieldDecl *FD = cast<FieldDecl>(Member); 2084 FieldCollector->Add(FD); 2085 2086 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 2087 FD->getLocation()) 2088 != DiagnosticsEngine::Ignored) { 2089 // Remember all explicit private FieldDecls that have a name, no side 2090 // effects and are not part of a dependent type declaration. 2091 if (!FD->isImplicit() && FD->getDeclName() && 2092 FD->getAccess() == AS_private && 2093 !FD->hasAttr<UnusedAttr>() && 2094 !FD->getParent()->isDependentContext() && 2095 !InitializationHasSideEffects(*FD)) 2096 UnusedPrivateFields.insert(FD); 2097 } 2098 } 2099 2100 return Member; 2101} 2102 2103namespace { 2104 class UninitializedFieldVisitor 2105 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2106 Sema &S; 2107 // If VD is null, this visitor will only update the Decls set. 2108 ValueDecl *VD; 2109 bool isReferenceType; 2110 // List of Decls to generate a warning on. 2111 llvm::SmallPtrSet<ValueDecl*, 4> &Decls; 2112 bool WarnOnSelfReference; 2113 // If non-null, add a note to the warning pointing back to the constructor. 2114 const CXXConstructorDecl *Constructor; 2115 public: 2116 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2117 UninitializedFieldVisitor(Sema &S, ValueDecl *VD, 2118 llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2119 bool WarnOnSelfReference, 2120 const CXXConstructorDecl *Constructor) 2121 : Inherited(S.Context), S(S), VD(VD), isReferenceType(false), Decls(Decls), 2122 WarnOnSelfReference(WarnOnSelfReference), Constructor(Constructor) { 2123 // When VD is null, this visitor is used to detect initialization of other 2124 // fields. 2125 if (VD) { 2126 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD)) 2127 this->VD = IFD->getAnonField(); 2128 else 2129 this->VD = VD; 2130 isReferenceType = this->VD->getType()->isReferenceType(); 2131 } 2132 } 2133 2134 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) { 2135 if (!VD) 2136 return; 2137 2138 if (CheckReferenceOnly && !isReferenceType) 2139 return; 2140 2141 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2142 return; 2143 2144 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2145 // or union. 2146 MemberExpr *FieldME = ME; 2147 2148 Expr *Base = ME; 2149 while (isa<MemberExpr>(Base)) { 2150 ME = cast<MemberExpr>(Base); 2151 2152 if (isa<VarDecl>(ME->getMemberDecl())) 2153 return; 2154 2155 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2156 if (!FD->isAnonymousStructOrUnion()) 2157 FieldME = ME; 2158 2159 Base = ME->getBase(); 2160 } 2161 2162 if (!isa<CXXThisExpr>(Base)) 2163 return; 2164 2165 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2166 2167 if (VD == FoundVD) { 2168 if (!WarnOnSelfReference) 2169 return; 2170 2171 unsigned diag = isReferenceType 2172 ? diag::warn_reference_field_is_uninit 2173 : diag::warn_field_is_uninit; 2174 S.Diag(FieldME->getExprLoc(), diag) << VD; 2175 if (Constructor) 2176 S.Diag(Constructor->getLocation(), 2177 diag::note_uninit_in_this_constructor); 2178 return; 2179 } 2180 2181 if (CheckReferenceOnly) 2182 return; 2183 2184 if (Decls.count(FoundVD)) { 2185 S.Diag(FieldME->getExprLoc(), diag::warn_field_is_uninit) << FoundVD; 2186 if (Constructor) 2187 S.Diag(Constructor->getLocation(), 2188 diag::note_uninit_in_this_constructor); 2189 2190 } 2191 } 2192 2193 void HandleValue(Expr *E) { 2194 if (!VD) 2195 return; 2196 2197 E = E->IgnoreParens(); 2198 2199 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2200 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2201 return; 2202 } 2203 2204 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2205 HandleValue(CO->getTrueExpr()); 2206 HandleValue(CO->getFalseExpr()); 2207 return; 2208 } 2209 2210 if (BinaryConditionalOperator *BCO = 2211 dyn_cast<BinaryConditionalOperator>(E)) { 2212 HandleValue(BCO->getCommon()); 2213 HandleValue(BCO->getFalseExpr()); 2214 return; 2215 } 2216 2217 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2218 switch (BO->getOpcode()) { 2219 default: 2220 return; 2221 case(BO_PtrMemD): 2222 case(BO_PtrMemI): 2223 HandleValue(BO->getLHS()); 2224 return; 2225 case(BO_Comma): 2226 HandleValue(BO->getRHS()); 2227 return; 2228 } 2229 } 2230 } 2231 2232 void VisitMemberExpr(MemberExpr *ME) { 2233 HandleMemberExpr(ME, true /*CheckReferenceOnly*/); 2234 2235 Inherited::VisitMemberExpr(ME); 2236 } 2237 2238 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2239 if (E->getCastKind() == CK_LValueToRValue) 2240 HandleValue(E->getSubExpr()); 2241 2242 Inherited::VisitImplicitCastExpr(E); 2243 } 2244 2245 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2246 if (E->getConstructor()->isCopyConstructor()) 2247 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0))) 2248 if (ICE->getCastKind() == CK_NoOp) 2249 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr())) 2250 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2251 2252 Inherited::VisitCXXConstructExpr(E); 2253 } 2254 2255 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2256 Expr *Callee = E->getCallee(); 2257 if (isa<MemberExpr>(Callee)) 2258 HandleValue(Callee); 2259 2260 Inherited::VisitCXXMemberCallExpr(E); 2261 } 2262 2263 void VisitBinaryOperator(BinaryOperator *E) { 2264 // If a field assignment is detected, remove the field from the 2265 // uninitiailized field set. 2266 if (E->getOpcode() == BO_Assign) 2267 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2268 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2269 Decls.erase(FD); 2270 2271 Inherited::VisitBinaryOperator(E); 2272 } 2273 }; 2274 static void CheckInitExprContainsUninitializedFields( 2275 Sema &S, Expr *E, ValueDecl *VD, llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2276 bool WarnOnSelfReference, const CXXConstructorDecl *Constructor = 0) { 2277 if (Decls.size() == 0 && !WarnOnSelfReference) 2278 return; 2279 2280 if (E) 2281 UninitializedFieldVisitor(S, VD, Decls, WarnOnSelfReference, Constructor) 2282 .Visit(E); 2283 } 2284} // namespace 2285 2286/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 2287/// in-class initializer for a non-static C++ class member, and after 2288/// instantiating an in-class initializer in a class template. Such actions 2289/// are deferred until the class is complete. 2290void 2291Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc, 2292 Expr *InitExpr) { 2293 FieldDecl *FD = cast<FieldDecl>(D); 2294 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2295 "must set init style when field is created"); 2296 2297 if (!InitExpr) { 2298 FD->setInvalidDecl(); 2299 FD->removeInClassInitializer(); 2300 return; 2301 } 2302 2303 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2304 FD->setInvalidDecl(); 2305 FD->removeInClassInitializer(); 2306 return; 2307 } 2308 2309 ExprResult Init = InitExpr; 2310 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2311 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2312 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2313 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2314 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2315 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2316 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2317 if (Init.isInvalid()) { 2318 FD->setInvalidDecl(); 2319 return; 2320 } 2321 } 2322 2323 // C++11 [class.base.init]p7: 2324 // The initialization of each base and member constitutes a 2325 // full-expression. 2326 Init = ActOnFinishFullExpr(Init.take(), InitLoc); 2327 if (Init.isInvalid()) { 2328 FD->setInvalidDecl(); 2329 return; 2330 } 2331 2332 InitExpr = Init.release(); 2333 2334 FD->setInClassInitializer(InitExpr); 2335} 2336 2337/// \brief Find the direct and/or virtual base specifiers that 2338/// correspond to the given base type, for use in base initialization 2339/// within a constructor. 2340static bool FindBaseInitializer(Sema &SemaRef, 2341 CXXRecordDecl *ClassDecl, 2342 QualType BaseType, 2343 const CXXBaseSpecifier *&DirectBaseSpec, 2344 const CXXBaseSpecifier *&VirtualBaseSpec) { 2345 // First, check for a direct base class. 2346 DirectBaseSpec = 0; 2347 for (CXXRecordDecl::base_class_const_iterator Base 2348 = ClassDecl->bases_begin(); 2349 Base != ClassDecl->bases_end(); ++Base) { 2350 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 2351 // We found a direct base of this type. That's what we're 2352 // initializing. 2353 DirectBaseSpec = &*Base; 2354 break; 2355 } 2356 } 2357 2358 // Check for a virtual base class. 2359 // FIXME: We might be able to short-circuit this if we know in advance that 2360 // there are no virtual bases. 2361 VirtualBaseSpec = 0; 2362 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2363 // We haven't found a base yet; search the class hierarchy for a 2364 // virtual base class. 2365 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2366 /*DetectVirtual=*/false); 2367 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2368 BaseType, Paths)) { 2369 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2370 Path != Paths.end(); ++Path) { 2371 if (Path->back().Base->isVirtual()) { 2372 VirtualBaseSpec = Path->back().Base; 2373 break; 2374 } 2375 } 2376 } 2377 } 2378 2379 return DirectBaseSpec || VirtualBaseSpec; 2380} 2381 2382/// \brief Handle a C++ member initializer using braced-init-list syntax. 2383MemInitResult 2384Sema::ActOnMemInitializer(Decl *ConstructorD, 2385 Scope *S, 2386 CXXScopeSpec &SS, 2387 IdentifierInfo *MemberOrBase, 2388 ParsedType TemplateTypeTy, 2389 const DeclSpec &DS, 2390 SourceLocation IdLoc, 2391 Expr *InitList, 2392 SourceLocation EllipsisLoc) { 2393 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2394 DS, IdLoc, InitList, 2395 EllipsisLoc); 2396} 2397 2398/// \brief Handle a C++ member initializer using parentheses syntax. 2399MemInitResult 2400Sema::ActOnMemInitializer(Decl *ConstructorD, 2401 Scope *S, 2402 CXXScopeSpec &SS, 2403 IdentifierInfo *MemberOrBase, 2404 ParsedType TemplateTypeTy, 2405 const DeclSpec &DS, 2406 SourceLocation IdLoc, 2407 SourceLocation LParenLoc, 2408 ArrayRef<Expr *> Args, 2409 SourceLocation RParenLoc, 2410 SourceLocation EllipsisLoc) { 2411 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2412 Args, RParenLoc); 2413 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2414 DS, IdLoc, List, EllipsisLoc); 2415} 2416 2417namespace { 2418 2419// Callback to only accept typo corrections that can be a valid C++ member 2420// intializer: either a non-static field member or a base class. 2421class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2422public: 2423 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2424 : ClassDecl(ClassDecl) {} 2425 2426 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE { 2427 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2428 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2429 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2430 return isa<TypeDecl>(ND); 2431 } 2432 return false; 2433 } 2434 2435private: 2436 CXXRecordDecl *ClassDecl; 2437}; 2438 2439} 2440 2441/// \brief Handle a C++ member initializer. 2442MemInitResult 2443Sema::BuildMemInitializer(Decl *ConstructorD, 2444 Scope *S, 2445 CXXScopeSpec &SS, 2446 IdentifierInfo *MemberOrBase, 2447 ParsedType TemplateTypeTy, 2448 const DeclSpec &DS, 2449 SourceLocation IdLoc, 2450 Expr *Init, 2451 SourceLocation EllipsisLoc) { 2452 if (!ConstructorD) 2453 return true; 2454 2455 AdjustDeclIfTemplate(ConstructorD); 2456 2457 CXXConstructorDecl *Constructor 2458 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2459 if (!Constructor) { 2460 // The user wrote a constructor initializer on a function that is 2461 // not a C++ constructor. Ignore the error for now, because we may 2462 // have more member initializers coming; we'll diagnose it just 2463 // once in ActOnMemInitializers. 2464 return true; 2465 } 2466 2467 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2468 2469 // C++ [class.base.init]p2: 2470 // Names in a mem-initializer-id are looked up in the scope of the 2471 // constructor's class and, if not found in that scope, are looked 2472 // up in the scope containing the constructor's definition. 2473 // [Note: if the constructor's class contains a member with the 2474 // same name as a direct or virtual base class of the class, a 2475 // mem-initializer-id naming the member or base class and composed 2476 // of a single identifier refers to the class member. A 2477 // mem-initializer-id for the hidden base class may be specified 2478 // using a qualified name. ] 2479 if (!SS.getScopeRep() && !TemplateTypeTy) { 2480 // Look for a member, first. 2481 DeclContext::lookup_result Result 2482 = ClassDecl->lookup(MemberOrBase); 2483 if (!Result.empty()) { 2484 ValueDecl *Member; 2485 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2486 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2487 if (EllipsisLoc.isValid()) 2488 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2489 << MemberOrBase 2490 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2491 2492 return BuildMemberInitializer(Member, Init, IdLoc); 2493 } 2494 } 2495 } 2496 // It didn't name a member, so see if it names a class. 2497 QualType BaseType; 2498 TypeSourceInfo *TInfo = 0; 2499 2500 if (TemplateTypeTy) { 2501 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2502 } else if (DS.getTypeSpecType() == TST_decltype) { 2503 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2504 } else { 2505 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2506 LookupParsedName(R, S, &SS); 2507 2508 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2509 if (!TyD) { 2510 if (R.isAmbiguous()) return true; 2511 2512 // We don't want access-control diagnostics here. 2513 R.suppressDiagnostics(); 2514 2515 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2516 bool NotUnknownSpecialization = false; 2517 DeclContext *DC = computeDeclContext(SS, false); 2518 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2519 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2520 2521 if (!NotUnknownSpecialization) { 2522 // When the scope specifier can refer to a member of an unknown 2523 // specialization, we take it as a type name. 2524 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2525 SS.getWithLocInContext(Context), 2526 *MemberOrBase, IdLoc); 2527 if (BaseType.isNull()) 2528 return true; 2529 2530 R.clear(); 2531 R.setLookupName(MemberOrBase); 2532 } 2533 } 2534 2535 // If no results were found, try to correct typos. 2536 TypoCorrection Corr; 2537 MemInitializerValidatorCCC Validator(ClassDecl); 2538 if (R.empty() && BaseType.isNull() && 2539 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2540 Validator, ClassDecl))) { 2541 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2542 // We have found a non-static data member with a similar 2543 // name to what was typed; complain and initialize that 2544 // member. 2545 diagnoseTypo(Corr, 2546 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2547 << MemberOrBase << true); 2548 return BuildMemberInitializer(Member, Init, IdLoc); 2549 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2550 const CXXBaseSpecifier *DirectBaseSpec; 2551 const CXXBaseSpecifier *VirtualBaseSpec; 2552 if (FindBaseInitializer(*this, ClassDecl, 2553 Context.getTypeDeclType(Type), 2554 DirectBaseSpec, VirtualBaseSpec)) { 2555 // We have found a direct or virtual base class with a 2556 // similar name to what was typed; complain and initialize 2557 // that base class. 2558 diagnoseTypo(Corr, 2559 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2560 << MemberOrBase << false, 2561 PDiag() /*Suppress note, we provide our own.*/); 2562 2563 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2564 : VirtualBaseSpec; 2565 Diag(BaseSpec->getLocStart(), 2566 diag::note_base_class_specified_here) 2567 << BaseSpec->getType() 2568 << BaseSpec->getSourceRange(); 2569 2570 TyD = Type; 2571 } 2572 } 2573 } 2574 2575 if (!TyD && BaseType.isNull()) { 2576 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2577 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2578 return true; 2579 } 2580 } 2581 2582 if (BaseType.isNull()) { 2583 BaseType = Context.getTypeDeclType(TyD); 2584 if (SS.isSet()) { 2585 NestedNameSpecifier *Qualifier = 2586 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2587 2588 // FIXME: preserve source range information 2589 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 2590 } 2591 } 2592 } 2593 2594 if (!TInfo) 2595 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2596 2597 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2598} 2599 2600/// Checks a member initializer expression for cases where reference (or 2601/// pointer) members are bound to by-value parameters (or their addresses). 2602static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2603 Expr *Init, 2604 SourceLocation IdLoc) { 2605 QualType MemberTy = Member->getType(); 2606 2607 // We only handle pointers and references currently. 2608 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2609 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2610 return; 2611 2612 const bool IsPointer = MemberTy->isPointerType(); 2613 if (IsPointer) { 2614 if (const UnaryOperator *Op 2615 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2616 // The only case we're worried about with pointers requires taking the 2617 // address. 2618 if (Op->getOpcode() != UO_AddrOf) 2619 return; 2620 2621 Init = Op->getSubExpr(); 2622 } else { 2623 // We only handle address-of expression initializers for pointers. 2624 return; 2625 } 2626 } 2627 2628 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2629 // We only warn when referring to a non-reference parameter declaration. 2630 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2631 if (!Parameter || Parameter->getType()->isReferenceType()) 2632 return; 2633 2634 S.Diag(Init->getExprLoc(), 2635 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2636 : diag::warn_bind_ref_member_to_parameter) 2637 << Member << Parameter << Init->getSourceRange(); 2638 } else { 2639 // Other initializers are fine. 2640 return; 2641 } 2642 2643 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2644 << (unsigned)IsPointer; 2645} 2646 2647MemInitResult 2648Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2649 SourceLocation IdLoc) { 2650 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2651 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2652 assert((DirectMember || IndirectMember) && 2653 "Member must be a FieldDecl or IndirectFieldDecl"); 2654 2655 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2656 return true; 2657 2658 if (Member->isInvalidDecl()) 2659 return true; 2660 2661 MultiExprArg Args; 2662 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2663 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2664 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2665 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2666 } else { 2667 // Template instantiation doesn't reconstruct ParenListExprs for us. 2668 Args = Init; 2669 } 2670 2671 SourceRange InitRange = Init->getSourceRange(); 2672 2673 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2674 // Can't check initialization for a member of dependent type or when 2675 // any of the arguments are type-dependent expressions. 2676 DiscardCleanupsInEvaluationContext(); 2677 } else { 2678 bool InitList = false; 2679 if (isa<InitListExpr>(Init)) { 2680 InitList = true; 2681 Args = Init; 2682 } 2683 2684 // Initialize the member. 2685 InitializedEntity MemberEntity = 2686 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2687 : InitializedEntity::InitializeMember(IndirectMember, 0); 2688 InitializationKind Kind = 2689 InitList ? InitializationKind::CreateDirectList(IdLoc) 2690 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2691 InitRange.getEnd()); 2692 2693 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 2694 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0); 2695 if (MemberInit.isInvalid()) 2696 return true; 2697 2698 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 2699 2700 // C++11 [class.base.init]p7: 2701 // The initialization of each base and member constitutes a 2702 // full-expression. 2703 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2704 if (MemberInit.isInvalid()) 2705 return true; 2706 2707 Init = MemberInit.get(); 2708 } 2709 2710 if (DirectMember) { 2711 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2712 InitRange.getBegin(), Init, 2713 InitRange.getEnd()); 2714 } else { 2715 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2716 InitRange.getBegin(), Init, 2717 InitRange.getEnd()); 2718 } 2719} 2720 2721MemInitResult 2722Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2723 CXXRecordDecl *ClassDecl) { 2724 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2725 if (!LangOpts.CPlusPlus11) 2726 return Diag(NameLoc, diag::err_delegating_ctor) 2727 << TInfo->getTypeLoc().getLocalSourceRange(); 2728 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2729 2730 bool InitList = true; 2731 MultiExprArg Args = Init; 2732 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2733 InitList = false; 2734 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2735 } 2736 2737 SourceRange InitRange = Init->getSourceRange(); 2738 // Initialize the object. 2739 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2740 QualType(ClassDecl->getTypeForDecl(), 0)); 2741 InitializationKind Kind = 2742 InitList ? InitializationKind::CreateDirectList(NameLoc) 2743 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2744 InitRange.getEnd()); 2745 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 2746 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2747 Args, 0); 2748 if (DelegationInit.isInvalid()) 2749 return true; 2750 2751 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2752 "Delegating constructor with no target?"); 2753 2754 // C++11 [class.base.init]p7: 2755 // The initialization of each base and member constitutes a 2756 // full-expression. 2757 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2758 InitRange.getBegin()); 2759 if (DelegationInit.isInvalid()) 2760 return true; 2761 2762 // If we are in a dependent context, template instantiation will 2763 // perform this type-checking again. Just save the arguments that we 2764 // received in a ParenListExpr. 2765 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2766 // of the information that we have about the base 2767 // initializer. However, deconstructing the ASTs is a dicey process, 2768 // and this approach is far more likely to get the corner cases right. 2769 if (CurContext->isDependentContext()) 2770 DelegationInit = Owned(Init); 2771 2772 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2773 DelegationInit.takeAs<Expr>(), 2774 InitRange.getEnd()); 2775} 2776 2777MemInitResult 2778Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2779 Expr *Init, CXXRecordDecl *ClassDecl, 2780 SourceLocation EllipsisLoc) { 2781 SourceLocation BaseLoc 2782 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2783 2784 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2785 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2786 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2787 2788 // C++ [class.base.init]p2: 2789 // [...] Unless the mem-initializer-id names a nonstatic data 2790 // member of the constructor's class or a direct or virtual base 2791 // of that class, the mem-initializer is ill-formed. A 2792 // mem-initializer-list can initialize a base class using any 2793 // name that denotes that base class type. 2794 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2795 2796 SourceRange InitRange = Init->getSourceRange(); 2797 if (EllipsisLoc.isValid()) { 2798 // This is a pack expansion. 2799 if (!BaseType->containsUnexpandedParameterPack()) { 2800 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2801 << SourceRange(BaseLoc, InitRange.getEnd()); 2802 2803 EllipsisLoc = SourceLocation(); 2804 } 2805 } else { 2806 // Check for any unexpanded parameter packs. 2807 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2808 return true; 2809 2810 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2811 return true; 2812 } 2813 2814 // Check for direct and virtual base classes. 2815 const CXXBaseSpecifier *DirectBaseSpec = 0; 2816 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2817 if (!Dependent) { 2818 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2819 BaseType)) 2820 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2821 2822 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2823 VirtualBaseSpec); 2824 2825 // C++ [base.class.init]p2: 2826 // Unless the mem-initializer-id names a nonstatic data member of the 2827 // constructor's class or a direct or virtual base of that class, the 2828 // mem-initializer is ill-formed. 2829 if (!DirectBaseSpec && !VirtualBaseSpec) { 2830 // If the class has any dependent bases, then it's possible that 2831 // one of those types will resolve to the same type as 2832 // BaseType. Therefore, just treat this as a dependent base 2833 // class initialization. FIXME: Should we try to check the 2834 // initialization anyway? It seems odd. 2835 if (ClassDecl->hasAnyDependentBases()) 2836 Dependent = true; 2837 else 2838 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2839 << BaseType << Context.getTypeDeclType(ClassDecl) 2840 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2841 } 2842 } 2843 2844 if (Dependent) { 2845 DiscardCleanupsInEvaluationContext(); 2846 2847 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2848 /*IsVirtual=*/false, 2849 InitRange.getBegin(), Init, 2850 InitRange.getEnd(), EllipsisLoc); 2851 } 2852 2853 // C++ [base.class.init]p2: 2854 // If a mem-initializer-id is ambiguous because it designates both 2855 // a direct non-virtual base class and an inherited virtual base 2856 // class, the mem-initializer is ill-formed. 2857 if (DirectBaseSpec && VirtualBaseSpec) 2858 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2859 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2860 2861 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 2862 if (!BaseSpec) 2863 BaseSpec = VirtualBaseSpec; 2864 2865 // Initialize the base. 2866 bool InitList = true; 2867 MultiExprArg Args = Init; 2868 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2869 InitList = false; 2870 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2871 } 2872 2873 InitializedEntity BaseEntity = 2874 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2875 InitializationKind Kind = 2876 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2877 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2878 InitRange.getEnd()); 2879 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 2880 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0); 2881 if (BaseInit.isInvalid()) 2882 return true; 2883 2884 // C++11 [class.base.init]p7: 2885 // The initialization of each base and member constitutes a 2886 // full-expression. 2887 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 2888 if (BaseInit.isInvalid()) 2889 return true; 2890 2891 // If we are in a dependent context, template instantiation will 2892 // perform this type-checking again. Just save the arguments that we 2893 // received in a ParenListExpr. 2894 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2895 // of the information that we have about the base 2896 // initializer. However, deconstructing the ASTs is a dicey process, 2897 // and this approach is far more likely to get the corner cases right. 2898 if (CurContext->isDependentContext()) 2899 BaseInit = Owned(Init); 2900 2901 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2902 BaseSpec->isVirtual(), 2903 InitRange.getBegin(), 2904 BaseInit.takeAs<Expr>(), 2905 InitRange.getEnd(), EllipsisLoc); 2906} 2907 2908// Create a static_cast\<T&&>(expr). 2909static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 2910 if (T.isNull()) T = E->getType(); 2911 QualType TargetType = SemaRef.BuildReferenceType( 2912 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 2913 SourceLocation ExprLoc = E->getLocStart(); 2914 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2915 TargetType, ExprLoc); 2916 2917 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2918 SourceRange(ExprLoc, ExprLoc), 2919 E->getSourceRange()).take(); 2920} 2921 2922/// ImplicitInitializerKind - How an implicit base or member initializer should 2923/// initialize its base or member. 2924enum ImplicitInitializerKind { 2925 IIK_Default, 2926 IIK_Copy, 2927 IIK_Move, 2928 IIK_Inherit 2929}; 2930 2931static bool 2932BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2933 ImplicitInitializerKind ImplicitInitKind, 2934 CXXBaseSpecifier *BaseSpec, 2935 bool IsInheritedVirtualBase, 2936 CXXCtorInitializer *&CXXBaseInit) { 2937 InitializedEntity InitEntity 2938 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2939 IsInheritedVirtualBase); 2940 2941 ExprResult BaseInit; 2942 2943 switch (ImplicitInitKind) { 2944 case IIK_Inherit: { 2945 const CXXRecordDecl *Inherited = 2946 Constructor->getInheritedConstructor()->getParent(); 2947 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 2948 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 2949 // C++11 [class.inhctor]p8: 2950 // Each expression in the expression-list is of the form 2951 // static_cast<T&&>(p), where p is the name of the corresponding 2952 // constructor parameter and T is the declared type of p. 2953 SmallVector<Expr*, 16> Args; 2954 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 2955 ParmVarDecl *PD = Constructor->getParamDecl(I); 2956 ExprResult ArgExpr = 2957 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 2958 VK_LValue, SourceLocation()); 2959 if (ArgExpr.isInvalid()) 2960 return true; 2961 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType())); 2962 } 2963 2964 InitializationKind InitKind = InitializationKind::CreateDirect( 2965 Constructor->getLocation(), SourceLocation(), SourceLocation()); 2966 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 2967 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 2968 break; 2969 } 2970 } 2971 // Fall through. 2972 case IIK_Default: { 2973 InitializationKind InitKind 2974 = InitializationKind::CreateDefault(Constructor->getLocation()); 2975 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 2976 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 2977 break; 2978 } 2979 2980 case IIK_Move: 2981 case IIK_Copy: { 2982 bool Moving = ImplicitInitKind == IIK_Move; 2983 ParmVarDecl *Param = Constructor->getParamDecl(0); 2984 QualType ParamType = Param->getType().getNonReferenceType(); 2985 2986 Expr *CopyCtorArg = 2987 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2988 SourceLocation(), Param, false, 2989 Constructor->getLocation(), ParamType, 2990 VK_LValue, 0); 2991 2992 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2993 2994 // Cast to the base class to avoid ambiguities. 2995 QualType ArgTy = 2996 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 2997 ParamType.getQualifiers()); 2998 2999 if (Moving) { 3000 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3001 } 3002 3003 CXXCastPath BasePath; 3004 BasePath.push_back(BaseSpec); 3005 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3006 CK_UncheckedDerivedToBase, 3007 Moving ? VK_XValue : VK_LValue, 3008 &BasePath).take(); 3009 3010 InitializationKind InitKind 3011 = InitializationKind::CreateDirect(Constructor->getLocation(), 3012 SourceLocation(), SourceLocation()); 3013 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3014 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3015 break; 3016 } 3017 } 3018 3019 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3020 if (BaseInit.isInvalid()) 3021 return true; 3022 3023 CXXBaseInit = 3024 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3025 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3026 SourceLocation()), 3027 BaseSpec->isVirtual(), 3028 SourceLocation(), 3029 BaseInit.takeAs<Expr>(), 3030 SourceLocation(), 3031 SourceLocation()); 3032 3033 return false; 3034} 3035 3036static bool RefersToRValueRef(Expr *MemRef) { 3037 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3038 return Referenced->getType()->isRValueReferenceType(); 3039} 3040 3041static bool 3042BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3043 ImplicitInitializerKind ImplicitInitKind, 3044 FieldDecl *Field, IndirectFieldDecl *Indirect, 3045 CXXCtorInitializer *&CXXMemberInit) { 3046 if (Field->isInvalidDecl()) 3047 return true; 3048 3049 SourceLocation Loc = Constructor->getLocation(); 3050 3051 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3052 bool Moving = ImplicitInitKind == IIK_Move; 3053 ParmVarDecl *Param = Constructor->getParamDecl(0); 3054 QualType ParamType = Param->getType().getNonReferenceType(); 3055 3056 // Suppress copying zero-width bitfields. 3057 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3058 return false; 3059 3060 Expr *MemberExprBase = 3061 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3062 SourceLocation(), Param, false, 3063 Loc, ParamType, VK_LValue, 0); 3064 3065 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3066 3067 if (Moving) { 3068 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3069 } 3070 3071 // Build a reference to this field within the parameter. 3072 CXXScopeSpec SS; 3073 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3074 Sema::LookupMemberName); 3075 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3076 : cast<ValueDecl>(Field), AS_public); 3077 MemberLookup.resolveKind(); 3078 ExprResult CtorArg 3079 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3080 ParamType, Loc, 3081 /*IsArrow=*/false, 3082 SS, 3083 /*TemplateKWLoc=*/SourceLocation(), 3084 /*FirstQualifierInScope=*/0, 3085 MemberLookup, 3086 /*TemplateArgs=*/0); 3087 if (CtorArg.isInvalid()) 3088 return true; 3089 3090 // C++11 [class.copy]p15: 3091 // - if a member m has rvalue reference type T&&, it is direct-initialized 3092 // with static_cast<T&&>(x.m); 3093 if (RefersToRValueRef(CtorArg.get())) { 3094 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3095 } 3096 3097 // When the field we are copying is an array, create index variables for 3098 // each dimension of the array. We use these index variables to subscript 3099 // the source array, and other clients (e.g., CodeGen) will perform the 3100 // necessary iteration with these index variables. 3101 SmallVector<VarDecl *, 4> IndexVariables; 3102 QualType BaseType = Field->getType(); 3103 QualType SizeType = SemaRef.Context.getSizeType(); 3104 bool InitializingArray = false; 3105 while (const ConstantArrayType *Array 3106 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3107 InitializingArray = true; 3108 // Create the iteration variable for this array index. 3109 IdentifierInfo *IterationVarName = 0; 3110 { 3111 SmallString<8> Str; 3112 llvm::raw_svector_ostream OS(Str); 3113 OS << "__i" << IndexVariables.size(); 3114 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3115 } 3116 VarDecl *IterationVar 3117 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3118 IterationVarName, SizeType, 3119 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3120 SC_None); 3121 IndexVariables.push_back(IterationVar); 3122 3123 // Create a reference to the iteration variable. 3124 ExprResult IterationVarRef 3125 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3126 assert(!IterationVarRef.isInvalid() && 3127 "Reference to invented variable cannot fail!"); 3128 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 3129 assert(!IterationVarRef.isInvalid() && 3130 "Conversion of invented variable cannot fail!"); 3131 3132 // Subscript the array with this iteration variable. 3133 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 3134 IterationVarRef.take(), 3135 Loc); 3136 if (CtorArg.isInvalid()) 3137 return true; 3138 3139 BaseType = Array->getElementType(); 3140 } 3141 3142 // The array subscript expression is an lvalue, which is wrong for moving. 3143 if (Moving && InitializingArray) 3144 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3145 3146 // Construct the entity that we will be initializing. For an array, this 3147 // will be first element in the array, which may require several levels 3148 // of array-subscript entities. 3149 SmallVector<InitializedEntity, 4> Entities; 3150 Entities.reserve(1 + IndexVariables.size()); 3151 if (Indirect) 3152 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3153 else 3154 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3155 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3156 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3157 0, 3158 Entities.back())); 3159 3160 // Direct-initialize to use the copy constructor. 3161 InitializationKind InitKind = 3162 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3163 3164 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 3165 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3166 3167 ExprResult MemberInit 3168 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3169 MultiExprArg(&CtorArgE, 1)); 3170 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3171 if (MemberInit.isInvalid()) 3172 return true; 3173 3174 if (Indirect) { 3175 assert(IndexVariables.size() == 0 && 3176 "Indirect field improperly initialized"); 3177 CXXMemberInit 3178 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3179 Loc, Loc, 3180 MemberInit.takeAs<Expr>(), 3181 Loc); 3182 } else 3183 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3184 Loc, MemberInit.takeAs<Expr>(), 3185 Loc, 3186 IndexVariables.data(), 3187 IndexVariables.size()); 3188 return false; 3189 } 3190 3191 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3192 "Unhandled implicit init kind!"); 3193 3194 QualType FieldBaseElementType = 3195 SemaRef.Context.getBaseElementType(Field->getType()); 3196 3197 if (FieldBaseElementType->isRecordType()) { 3198 InitializedEntity InitEntity 3199 = Indirect? InitializedEntity::InitializeMember(Indirect) 3200 : InitializedEntity::InitializeMember(Field); 3201 InitializationKind InitKind = 3202 InitializationKind::CreateDefault(Loc); 3203 3204 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3205 ExprResult MemberInit = 3206 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3207 3208 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3209 if (MemberInit.isInvalid()) 3210 return true; 3211 3212 if (Indirect) 3213 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3214 Indirect, Loc, 3215 Loc, 3216 MemberInit.get(), 3217 Loc); 3218 else 3219 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3220 Field, Loc, Loc, 3221 MemberInit.get(), 3222 Loc); 3223 return false; 3224 } 3225 3226 if (!Field->getParent()->isUnion()) { 3227 if (FieldBaseElementType->isReferenceType()) { 3228 SemaRef.Diag(Constructor->getLocation(), 3229 diag::err_uninitialized_member_in_ctor) 3230 << (int)Constructor->isImplicit() 3231 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3232 << 0 << Field->getDeclName(); 3233 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3234 return true; 3235 } 3236 3237 if (FieldBaseElementType.isConstQualified()) { 3238 SemaRef.Diag(Constructor->getLocation(), 3239 diag::err_uninitialized_member_in_ctor) 3240 << (int)Constructor->isImplicit() 3241 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3242 << 1 << Field->getDeclName(); 3243 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3244 return true; 3245 } 3246 } 3247 3248 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3249 FieldBaseElementType->isObjCRetainableType() && 3250 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3251 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3252 // ARC: 3253 // Default-initialize Objective-C pointers to NULL. 3254 CXXMemberInit 3255 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3256 Loc, Loc, 3257 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3258 Loc); 3259 return false; 3260 } 3261 3262 // Nothing to initialize. 3263 CXXMemberInit = 0; 3264 return false; 3265} 3266 3267namespace { 3268struct BaseAndFieldInfo { 3269 Sema &S; 3270 CXXConstructorDecl *Ctor; 3271 bool AnyErrorsInInits; 3272 ImplicitInitializerKind IIK; 3273 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3274 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3275 3276 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3277 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3278 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3279 if (Generated && Ctor->isCopyConstructor()) 3280 IIK = IIK_Copy; 3281 else if (Generated && Ctor->isMoveConstructor()) 3282 IIK = IIK_Move; 3283 else if (Ctor->getInheritedConstructor()) 3284 IIK = IIK_Inherit; 3285 else 3286 IIK = IIK_Default; 3287 } 3288 3289 bool isImplicitCopyOrMove() const { 3290 switch (IIK) { 3291 case IIK_Copy: 3292 case IIK_Move: 3293 return true; 3294 3295 case IIK_Default: 3296 case IIK_Inherit: 3297 return false; 3298 } 3299 3300 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3301 } 3302 3303 bool addFieldInitializer(CXXCtorInitializer *Init) { 3304 AllToInit.push_back(Init); 3305 3306 // Check whether this initializer makes the field "used". 3307 if (Init->getInit()->HasSideEffects(S.Context)) 3308 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3309 3310 return false; 3311 } 3312}; 3313} 3314 3315/// \brief Determine whether the given indirect field declaration is somewhere 3316/// within an anonymous union. 3317static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 3318 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 3319 CEnd = F->chain_end(); 3320 C != CEnd; ++C) 3321 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 3322 if (Record->isUnion()) 3323 return true; 3324 3325 return false; 3326} 3327 3328/// \brief Determine whether the given type is an incomplete or zero-lenfgth 3329/// array type. 3330static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3331 if (T->isIncompleteArrayType()) 3332 return true; 3333 3334 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3335 if (!ArrayT->getSize()) 3336 return true; 3337 3338 T = ArrayT->getElementType(); 3339 } 3340 3341 return false; 3342} 3343 3344static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3345 FieldDecl *Field, 3346 IndirectFieldDecl *Indirect = 0) { 3347 if (Field->isInvalidDecl()) 3348 return false; 3349 3350 // Overwhelmingly common case: we have a direct initializer for this field. 3351 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 3352 return Info.addFieldInitializer(Init); 3353 3354 // C++11 [class.base.init]p8: if the entity is a non-static data member that 3355 // has a brace-or-equal-initializer, the entity is initialized as specified 3356 // in [dcl.init]. 3357 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3358 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3359 Info.Ctor->getLocation(), Field); 3360 CXXCtorInitializer *Init; 3361 if (Indirect) 3362 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3363 SourceLocation(), 3364 SourceLocation(), DIE, 3365 SourceLocation()); 3366 else 3367 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3368 SourceLocation(), 3369 SourceLocation(), DIE, 3370 SourceLocation()); 3371 return Info.addFieldInitializer(Init); 3372 } 3373 3374 // Don't build an implicit initializer for union members if none was 3375 // explicitly specified. 3376 if (Field->getParent()->isUnion() || 3377 (Indirect && isWithinAnonymousUnion(Indirect))) 3378 return false; 3379 3380 // Don't initialize incomplete or zero-length arrays. 3381 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3382 return false; 3383 3384 // Don't try to build an implicit initializer if there were semantic 3385 // errors in any of the initializers (and therefore we might be 3386 // missing some that the user actually wrote). 3387 if (Info.AnyErrorsInInits) 3388 return false; 3389 3390 CXXCtorInitializer *Init = 0; 3391 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3392 Indirect, Init)) 3393 return true; 3394 3395 if (!Init) 3396 return false; 3397 3398 return Info.addFieldInitializer(Init); 3399} 3400 3401bool 3402Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3403 CXXCtorInitializer *Initializer) { 3404 assert(Initializer->isDelegatingInitializer()); 3405 Constructor->setNumCtorInitializers(1); 3406 CXXCtorInitializer **initializer = 3407 new (Context) CXXCtorInitializer*[1]; 3408 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3409 Constructor->setCtorInitializers(initializer); 3410 3411 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3412 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3413 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3414 } 3415 3416 DelegatingCtorDecls.push_back(Constructor); 3417 3418 return false; 3419} 3420 3421bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3422 ArrayRef<CXXCtorInitializer *> Initializers) { 3423 if (Constructor->isDependentContext()) { 3424 // Just store the initializers as written, they will be checked during 3425 // instantiation. 3426 if (!Initializers.empty()) { 3427 Constructor->setNumCtorInitializers(Initializers.size()); 3428 CXXCtorInitializer **baseOrMemberInitializers = 3429 new (Context) CXXCtorInitializer*[Initializers.size()]; 3430 memcpy(baseOrMemberInitializers, Initializers.data(), 3431 Initializers.size() * sizeof(CXXCtorInitializer*)); 3432 Constructor->setCtorInitializers(baseOrMemberInitializers); 3433 } 3434 3435 // Let template instantiation know whether we had errors. 3436 if (AnyErrors) 3437 Constructor->setInvalidDecl(); 3438 3439 return false; 3440 } 3441 3442 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3443 3444 // We need to build the initializer AST according to order of construction 3445 // and not what user specified in the Initializers list. 3446 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3447 if (!ClassDecl) 3448 return true; 3449 3450 bool HadError = false; 3451 3452 for (unsigned i = 0; i < Initializers.size(); i++) { 3453 CXXCtorInitializer *Member = Initializers[i]; 3454 3455 if (Member->isBaseInitializer()) 3456 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3457 else 3458 Info.AllBaseFields[Member->getAnyMember()] = Member; 3459 } 3460 3461 // Keep track of the direct virtual bases. 3462 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3463 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 3464 E = ClassDecl->bases_end(); I != E; ++I) { 3465 if (I->isVirtual()) 3466 DirectVBases.insert(I); 3467 } 3468 3469 // Push virtual bases before others. 3470 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3471 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3472 3473 if (CXXCtorInitializer *Value 3474 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 3475 // [class.base.init]p7, per DR257: 3476 // A mem-initializer where the mem-initializer-id names a virtual base 3477 // class is ignored during execution of a constructor of any class that 3478 // is not the most derived class. 3479 if (ClassDecl->isAbstract()) { 3480 // FIXME: Provide a fixit to remove the base specifier. This requires 3481 // tracking the location of the associated comma for a base specifier. 3482 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3483 << VBase->getType() << ClassDecl; 3484 DiagnoseAbstractType(ClassDecl); 3485 } 3486 3487 Info.AllToInit.push_back(Value); 3488 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3489 // [class.base.init]p8, per DR257: 3490 // If a given [...] base class is not named by a mem-initializer-id 3491 // [...] and the entity is not a virtual base class of an abstract 3492 // class, then [...] the entity is default-initialized. 3493 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 3494 CXXCtorInitializer *CXXBaseInit; 3495 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3496 VBase, IsInheritedVirtualBase, 3497 CXXBaseInit)) { 3498 HadError = true; 3499 continue; 3500 } 3501 3502 Info.AllToInit.push_back(CXXBaseInit); 3503 } 3504 } 3505 3506 // Non-virtual bases. 3507 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3508 E = ClassDecl->bases_end(); Base != E; ++Base) { 3509 // Virtuals are in the virtual base list and already constructed. 3510 if (Base->isVirtual()) 3511 continue; 3512 3513 if (CXXCtorInitializer *Value 3514 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 3515 Info.AllToInit.push_back(Value); 3516 } else if (!AnyErrors) { 3517 CXXCtorInitializer *CXXBaseInit; 3518 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3519 Base, /*IsInheritedVirtualBase=*/false, 3520 CXXBaseInit)) { 3521 HadError = true; 3522 continue; 3523 } 3524 3525 Info.AllToInit.push_back(CXXBaseInit); 3526 } 3527 } 3528 3529 // Fields. 3530 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 3531 MemEnd = ClassDecl->decls_end(); 3532 Mem != MemEnd; ++Mem) { 3533 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 3534 // C++ [class.bit]p2: 3535 // A declaration for a bit-field that omits the identifier declares an 3536 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3537 // initialized. 3538 if (F->isUnnamedBitfield()) 3539 continue; 3540 3541 // If we're not generating the implicit copy/move constructor, then we'll 3542 // handle anonymous struct/union fields based on their individual 3543 // indirect fields. 3544 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3545 continue; 3546 3547 if (CollectFieldInitializer(*this, Info, F)) 3548 HadError = true; 3549 continue; 3550 } 3551 3552 // Beyond this point, we only consider default initialization. 3553 if (Info.isImplicitCopyOrMove()) 3554 continue; 3555 3556 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 3557 if (F->getType()->isIncompleteArrayType()) { 3558 assert(ClassDecl->hasFlexibleArrayMember() && 3559 "Incomplete array type is not valid"); 3560 continue; 3561 } 3562 3563 // Initialize each field of an anonymous struct individually. 3564 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3565 HadError = true; 3566 3567 continue; 3568 } 3569 } 3570 3571 unsigned NumInitializers = Info.AllToInit.size(); 3572 if (NumInitializers > 0) { 3573 Constructor->setNumCtorInitializers(NumInitializers); 3574 CXXCtorInitializer **baseOrMemberInitializers = 3575 new (Context) CXXCtorInitializer*[NumInitializers]; 3576 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3577 NumInitializers * sizeof(CXXCtorInitializer*)); 3578 Constructor->setCtorInitializers(baseOrMemberInitializers); 3579 3580 // Constructors implicitly reference the base and member 3581 // destructors. 3582 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3583 Constructor->getParent()); 3584 } 3585 3586 return HadError; 3587} 3588 3589static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3590 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3591 const RecordDecl *RD = RT->getDecl(); 3592 if (RD->isAnonymousStructOrUnion()) { 3593 for (RecordDecl::field_iterator Field = RD->field_begin(), 3594 E = RD->field_end(); Field != E; ++Field) 3595 PopulateKeysForFields(*Field, IdealInits); 3596 return; 3597 } 3598 } 3599 IdealInits.push_back(Field); 3600} 3601 3602static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3603 return Context.getCanonicalType(BaseType).getTypePtr(); 3604} 3605 3606static const void *GetKeyForMember(ASTContext &Context, 3607 CXXCtorInitializer *Member) { 3608 if (!Member->isAnyMemberInitializer()) 3609 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3610 3611 return Member->getAnyMember(); 3612} 3613 3614static void DiagnoseBaseOrMemInitializerOrder( 3615 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3616 ArrayRef<CXXCtorInitializer *> Inits) { 3617 if (Constructor->getDeclContext()->isDependentContext()) 3618 return; 3619 3620 // Don't check initializers order unless the warning is enabled at the 3621 // location of at least one initializer. 3622 bool ShouldCheckOrder = false; 3623 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3624 CXXCtorInitializer *Init = Inits[InitIndex]; 3625 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3626 Init->getSourceLocation()) 3627 != DiagnosticsEngine::Ignored) { 3628 ShouldCheckOrder = true; 3629 break; 3630 } 3631 } 3632 if (!ShouldCheckOrder) 3633 return; 3634 3635 // Build the list of bases and members in the order that they'll 3636 // actually be initialized. The explicit initializers should be in 3637 // this same order but may be missing things. 3638 SmallVector<const void*, 32> IdealInitKeys; 3639 3640 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3641 3642 // 1. Virtual bases. 3643 for (CXXRecordDecl::base_class_const_iterator VBase = 3644 ClassDecl->vbases_begin(), 3645 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3646 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3647 3648 // 2. Non-virtual bases. 3649 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3650 E = ClassDecl->bases_end(); Base != E; ++Base) { 3651 if (Base->isVirtual()) 3652 continue; 3653 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3654 } 3655 3656 // 3. Direct fields. 3657 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3658 E = ClassDecl->field_end(); Field != E; ++Field) { 3659 if (Field->isUnnamedBitfield()) 3660 continue; 3661 3662 PopulateKeysForFields(*Field, IdealInitKeys); 3663 } 3664 3665 unsigned NumIdealInits = IdealInitKeys.size(); 3666 unsigned IdealIndex = 0; 3667 3668 CXXCtorInitializer *PrevInit = 0; 3669 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3670 CXXCtorInitializer *Init = Inits[InitIndex]; 3671 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3672 3673 // Scan forward to try to find this initializer in the idealized 3674 // initializers list. 3675 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3676 if (InitKey == IdealInitKeys[IdealIndex]) 3677 break; 3678 3679 // If we didn't find this initializer, it must be because we 3680 // scanned past it on a previous iteration. That can only 3681 // happen if we're out of order; emit a warning. 3682 if (IdealIndex == NumIdealInits && PrevInit) { 3683 Sema::SemaDiagnosticBuilder D = 3684 SemaRef.Diag(PrevInit->getSourceLocation(), 3685 diag::warn_initializer_out_of_order); 3686 3687 if (PrevInit->isAnyMemberInitializer()) 3688 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3689 else 3690 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3691 3692 if (Init->isAnyMemberInitializer()) 3693 D << 0 << Init->getAnyMember()->getDeclName(); 3694 else 3695 D << 1 << Init->getTypeSourceInfo()->getType(); 3696 3697 // Move back to the initializer's location in the ideal list. 3698 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3699 if (InitKey == IdealInitKeys[IdealIndex]) 3700 break; 3701 3702 assert(IdealIndex != NumIdealInits && 3703 "initializer not found in initializer list"); 3704 } 3705 3706 PrevInit = Init; 3707 } 3708} 3709 3710namespace { 3711bool CheckRedundantInit(Sema &S, 3712 CXXCtorInitializer *Init, 3713 CXXCtorInitializer *&PrevInit) { 3714 if (!PrevInit) { 3715 PrevInit = Init; 3716 return false; 3717 } 3718 3719 if (FieldDecl *Field = Init->getAnyMember()) 3720 S.Diag(Init->getSourceLocation(), 3721 diag::err_multiple_mem_initialization) 3722 << Field->getDeclName() 3723 << Init->getSourceRange(); 3724 else { 3725 const Type *BaseClass = Init->getBaseClass(); 3726 assert(BaseClass && "neither field nor base"); 3727 S.Diag(Init->getSourceLocation(), 3728 diag::err_multiple_base_initialization) 3729 << QualType(BaseClass, 0) 3730 << Init->getSourceRange(); 3731 } 3732 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3733 << 0 << PrevInit->getSourceRange(); 3734 3735 return true; 3736} 3737 3738typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3739typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3740 3741bool CheckRedundantUnionInit(Sema &S, 3742 CXXCtorInitializer *Init, 3743 RedundantUnionMap &Unions) { 3744 FieldDecl *Field = Init->getAnyMember(); 3745 RecordDecl *Parent = Field->getParent(); 3746 NamedDecl *Child = Field; 3747 3748 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3749 if (Parent->isUnion()) { 3750 UnionEntry &En = Unions[Parent]; 3751 if (En.first && En.first != Child) { 3752 S.Diag(Init->getSourceLocation(), 3753 diag::err_multiple_mem_union_initialization) 3754 << Field->getDeclName() 3755 << Init->getSourceRange(); 3756 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3757 << 0 << En.second->getSourceRange(); 3758 return true; 3759 } 3760 if (!En.first) { 3761 En.first = Child; 3762 En.second = Init; 3763 } 3764 if (!Parent->isAnonymousStructOrUnion()) 3765 return false; 3766 } 3767 3768 Child = Parent; 3769 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3770 } 3771 3772 return false; 3773} 3774} 3775 3776// Diagnose value-uses of fields to initialize themselves, e.g. 3777// foo(foo) 3778// where foo is not also a parameter to the constructor. 3779// Also diagnose across field uninitialized use such as 3780// x(y), y(x) 3781// TODO: implement -Wuninitialized and fold this into that framework. 3782static void DiagnoseUnitializedFields( 3783 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3784 3785 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, 3786 Constructor->getLocation()) 3787 == DiagnosticsEngine::Ignored) { 3788 return; 3789 } 3790 3791 const CXXRecordDecl *RD = Constructor->getParent(); 3792 3793 // Holds fields that are uninitialized. 3794 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3795 3796 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end(); 3797 I != E; ++I) { 3798 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) { 3799 UninitializedFields.insert(FD); 3800 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) { 3801 UninitializedFields.insert(IFD->getAnonField()); 3802 } 3803 } 3804 3805 // Fields already checked when processing the in class initializers. 3806 llvm::SmallPtrSet<ValueDecl*, 4> 3807 InClassUninitializedFields = UninitializedFields; 3808 3809 for (CXXConstructorDecl::init_const_iterator FieldInit = 3810 Constructor->init_begin(), 3811 FieldInitEnd = Constructor->init_end(); 3812 FieldInit != FieldInitEnd; ++FieldInit) { 3813 3814 FieldDecl *Field = (*FieldInit)->getAnyMember(); 3815 Expr *InitExpr = (*FieldInit)->getInit(); 3816 3817 if (!Field) { 3818 CheckInitExprContainsUninitializedFields( 3819 SemaRef, InitExpr, 0, UninitializedFields, 3820 false/*WarnOnSelfReference*/); 3821 continue; 3822 } 3823 3824 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3825 // This field is initialized with an in-class initailzer. Remove the 3826 // fields already checked to prevent duplicate warnings. 3827 llvm::SmallPtrSet<ValueDecl*, 4> DiffSet = UninitializedFields; 3828 for (llvm::SmallPtrSet<ValueDecl*, 4>::iterator 3829 I = InClassUninitializedFields.begin(), 3830 E = InClassUninitializedFields.end(); 3831 I != E; ++I) { 3832 DiffSet.erase(*I); 3833 } 3834 CheckInitExprContainsUninitializedFields( 3835 SemaRef, Default->getExpr(), Field, DiffSet, 3836 DiffSet.count(Field), Constructor); 3837 3838 // Update the unitialized field sets. 3839 CheckInitExprContainsUninitializedFields( 3840 SemaRef, Default->getExpr(), 0, UninitializedFields, 3841 false); 3842 CheckInitExprContainsUninitializedFields( 3843 SemaRef, Default->getExpr(), 0, InClassUninitializedFields, 3844 false); 3845 } else { 3846 CheckInitExprContainsUninitializedFields( 3847 SemaRef, InitExpr, Field, UninitializedFields, 3848 UninitializedFields.count(Field)); 3849 if (Expr* InClassInit = Field->getInClassInitializer()) { 3850 CheckInitExprContainsUninitializedFields( 3851 SemaRef, InClassInit, 0, InClassUninitializedFields, 3852 false); 3853 } 3854 } 3855 UninitializedFields.erase(Field); 3856 InClassUninitializedFields.erase(Field); 3857 } 3858} 3859 3860/// ActOnMemInitializers - Handle the member initializers for a constructor. 3861void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3862 SourceLocation ColonLoc, 3863 ArrayRef<CXXCtorInitializer*> MemInits, 3864 bool AnyErrors) { 3865 if (!ConstructorDecl) 3866 return; 3867 3868 AdjustDeclIfTemplate(ConstructorDecl); 3869 3870 CXXConstructorDecl *Constructor 3871 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3872 3873 if (!Constructor) { 3874 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3875 return; 3876 } 3877 3878 // Mapping for the duplicate initializers check. 3879 // For member initializers, this is keyed with a FieldDecl*. 3880 // For base initializers, this is keyed with a Type*. 3881 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 3882 3883 // Mapping for the inconsistent anonymous-union initializers check. 3884 RedundantUnionMap MemberUnions; 3885 3886 bool HadError = false; 3887 for (unsigned i = 0; i < MemInits.size(); i++) { 3888 CXXCtorInitializer *Init = MemInits[i]; 3889 3890 // Set the source order index. 3891 Init->setSourceOrder(i); 3892 3893 if (Init->isAnyMemberInitializer()) { 3894 FieldDecl *Field = Init->getAnyMember(); 3895 if (CheckRedundantInit(*this, Init, Members[Field]) || 3896 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3897 HadError = true; 3898 } else if (Init->isBaseInitializer()) { 3899 const void *Key = 3900 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3901 if (CheckRedundantInit(*this, Init, Members[Key])) 3902 HadError = true; 3903 } else { 3904 assert(Init->isDelegatingInitializer()); 3905 // This must be the only initializer 3906 if (MemInits.size() != 1) { 3907 Diag(Init->getSourceLocation(), 3908 diag::err_delegating_initializer_alone) 3909 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3910 // We will treat this as being the only initializer. 3911 } 3912 SetDelegatingInitializer(Constructor, MemInits[i]); 3913 // Return immediately as the initializer is set. 3914 return; 3915 } 3916 } 3917 3918 if (HadError) 3919 return; 3920 3921 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 3922 3923 SetCtorInitializers(Constructor, AnyErrors, MemInits); 3924 3925 DiagnoseUnitializedFields(*this, Constructor); 3926} 3927 3928void 3929Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3930 CXXRecordDecl *ClassDecl) { 3931 // Ignore dependent contexts. Also ignore unions, since their members never 3932 // have destructors implicitly called. 3933 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3934 return; 3935 3936 // FIXME: all the access-control diagnostics are positioned on the 3937 // field/base declaration. That's probably good; that said, the 3938 // user might reasonably want to know why the destructor is being 3939 // emitted, and we currently don't say. 3940 3941 // Non-static data members. 3942 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3943 E = ClassDecl->field_end(); I != E; ++I) { 3944 FieldDecl *Field = *I; 3945 if (Field->isInvalidDecl()) 3946 continue; 3947 3948 // Don't destroy incomplete or zero-length arrays. 3949 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3950 continue; 3951 3952 QualType FieldType = Context.getBaseElementType(Field->getType()); 3953 3954 const RecordType* RT = FieldType->getAs<RecordType>(); 3955 if (!RT) 3956 continue; 3957 3958 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3959 if (FieldClassDecl->isInvalidDecl()) 3960 continue; 3961 if (FieldClassDecl->hasIrrelevantDestructor()) 3962 continue; 3963 // The destructor for an implicit anonymous union member is never invoked. 3964 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3965 continue; 3966 3967 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3968 assert(Dtor && "No dtor found for FieldClassDecl!"); 3969 CheckDestructorAccess(Field->getLocation(), Dtor, 3970 PDiag(diag::err_access_dtor_field) 3971 << Field->getDeclName() 3972 << FieldType); 3973 3974 MarkFunctionReferenced(Location, Dtor); 3975 DiagnoseUseOfDecl(Dtor, Location); 3976 } 3977 3978 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3979 3980 // Bases. 3981 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3982 E = ClassDecl->bases_end(); Base != E; ++Base) { 3983 // Bases are always records in a well-formed non-dependent class. 3984 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3985 3986 // Remember direct virtual bases. 3987 if (Base->isVirtual()) 3988 DirectVirtualBases.insert(RT); 3989 3990 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3991 // If our base class is invalid, we probably can't get its dtor anyway. 3992 if (BaseClassDecl->isInvalidDecl()) 3993 continue; 3994 if (BaseClassDecl->hasIrrelevantDestructor()) 3995 continue; 3996 3997 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3998 assert(Dtor && "No dtor found for BaseClassDecl!"); 3999 4000 // FIXME: caret should be on the start of the class name 4001 CheckDestructorAccess(Base->getLocStart(), Dtor, 4002 PDiag(diag::err_access_dtor_base) 4003 << Base->getType() 4004 << Base->getSourceRange(), 4005 Context.getTypeDeclType(ClassDecl)); 4006 4007 MarkFunctionReferenced(Location, Dtor); 4008 DiagnoseUseOfDecl(Dtor, Location); 4009 } 4010 4011 // Virtual bases. 4012 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 4013 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 4014 4015 // Bases are always records in a well-formed non-dependent class. 4016 const RecordType *RT = VBase->getType()->castAs<RecordType>(); 4017 4018 // Ignore direct virtual bases. 4019 if (DirectVirtualBases.count(RT)) 4020 continue; 4021 4022 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4023 // If our base class is invalid, we probably can't get its dtor anyway. 4024 if (BaseClassDecl->isInvalidDecl()) 4025 continue; 4026 if (BaseClassDecl->hasIrrelevantDestructor()) 4027 continue; 4028 4029 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4030 assert(Dtor && "No dtor found for BaseClassDecl!"); 4031 if (CheckDestructorAccess( 4032 ClassDecl->getLocation(), Dtor, 4033 PDiag(diag::err_access_dtor_vbase) 4034 << Context.getTypeDeclType(ClassDecl) << VBase->getType(), 4035 Context.getTypeDeclType(ClassDecl)) == 4036 AR_accessible) { 4037 CheckDerivedToBaseConversion( 4038 Context.getTypeDeclType(ClassDecl), VBase->getType(), 4039 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4040 SourceRange(), DeclarationName(), 0); 4041 } 4042 4043 MarkFunctionReferenced(Location, Dtor); 4044 DiagnoseUseOfDecl(Dtor, Location); 4045 } 4046} 4047 4048void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4049 if (!CDtorDecl) 4050 return; 4051 4052 if (CXXConstructorDecl *Constructor 4053 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 4054 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4055} 4056 4057bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4058 unsigned DiagID, AbstractDiagSelID SelID) { 4059 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4060 unsigned DiagID; 4061 AbstractDiagSelID SelID; 4062 4063 public: 4064 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4065 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4066 4067 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE { 4068 if (Suppressed) return; 4069 if (SelID == -1) 4070 S.Diag(Loc, DiagID) << T; 4071 else 4072 S.Diag(Loc, DiagID) << SelID << T; 4073 } 4074 } Diagnoser(DiagID, SelID); 4075 4076 return RequireNonAbstractType(Loc, T, Diagnoser); 4077} 4078 4079bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4080 TypeDiagnoser &Diagnoser) { 4081 if (!getLangOpts().CPlusPlus) 4082 return false; 4083 4084 if (const ArrayType *AT = Context.getAsArrayType(T)) 4085 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4086 4087 if (const PointerType *PT = T->getAs<PointerType>()) { 4088 // Find the innermost pointer type. 4089 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4090 PT = T; 4091 4092 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4093 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4094 } 4095 4096 const RecordType *RT = T->getAs<RecordType>(); 4097 if (!RT) 4098 return false; 4099 4100 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4101 4102 // We can't answer whether something is abstract until it has a 4103 // definition. If it's currently being defined, we'll walk back 4104 // over all the declarations when we have a full definition. 4105 const CXXRecordDecl *Def = RD->getDefinition(); 4106 if (!Def || Def->isBeingDefined()) 4107 return false; 4108 4109 if (!RD->isAbstract()) 4110 return false; 4111 4112 Diagnoser.diagnose(*this, Loc, T); 4113 DiagnoseAbstractType(RD); 4114 4115 return true; 4116} 4117 4118void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4119 // Check if we've already emitted the list of pure virtual functions 4120 // for this class. 4121 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4122 return; 4123 4124 // If the diagnostic is suppressed, don't emit the notes. We're only 4125 // going to emit them once, so try to attach them to a diagnostic we're 4126 // actually going to show. 4127 if (Diags.isLastDiagnosticIgnored()) 4128 return; 4129 4130 CXXFinalOverriderMap FinalOverriders; 4131 RD->getFinalOverriders(FinalOverriders); 4132 4133 // Keep a set of seen pure methods so we won't diagnose the same method 4134 // more than once. 4135 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4136 4137 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4138 MEnd = FinalOverriders.end(); 4139 M != MEnd; 4140 ++M) { 4141 for (OverridingMethods::iterator SO = M->second.begin(), 4142 SOEnd = M->second.end(); 4143 SO != SOEnd; ++SO) { 4144 // C++ [class.abstract]p4: 4145 // A class is abstract if it contains or inherits at least one 4146 // pure virtual function for which the final overrider is pure 4147 // virtual. 4148 4149 // 4150 if (SO->second.size() != 1) 4151 continue; 4152 4153 if (!SO->second.front().Method->isPure()) 4154 continue; 4155 4156 if (!SeenPureMethods.insert(SO->second.front().Method)) 4157 continue; 4158 4159 Diag(SO->second.front().Method->getLocation(), 4160 diag::note_pure_virtual_function) 4161 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4162 } 4163 } 4164 4165 if (!PureVirtualClassDiagSet) 4166 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4167 PureVirtualClassDiagSet->insert(RD); 4168} 4169 4170namespace { 4171struct AbstractUsageInfo { 4172 Sema &S; 4173 CXXRecordDecl *Record; 4174 CanQualType AbstractType; 4175 bool Invalid; 4176 4177 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4178 : S(S), Record(Record), 4179 AbstractType(S.Context.getCanonicalType( 4180 S.Context.getTypeDeclType(Record))), 4181 Invalid(false) {} 4182 4183 void DiagnoseAbstractType() { 4184 if (Invalid) return; 4185 S.DiagnoseAbstractType(Record); 4186 Invalid = true; 4187 } 4188 4189 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4190}; 4191 4192struct CheckAbstractUsage { 4193 AbstractUsageInfo &Info; 4194 const NamedDecl *Ctx; 4195 4196 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4197 : Info(Info), Ctx(Ctx) {} 4198 4199 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4200 switch (TL.getTypeLocClass()) { 4201#define ABSTRACT_TYPELOC(CLASS, PARENT) 4202#define TYPELOC(CLASS, PARENT) \ 4203 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4204#include "clang/AST/TypeLocNodes.def" 4205 } 4206 } 4207 4208 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4209 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 4210 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4211 if (!TL.getArg(I)) 4212 continue; 4213 4214 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 4215 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4216 } 4217 } 4218 4219 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4220 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4221 } 4222 4223 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4224 // Visit the type parameters from a permissive context. 4225 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4226 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4227 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4228 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4229 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4230 // TODO: other template argument types? 4231 } 4232 } 4233 4234 // Visit pointee types from a permissive context. 4235#define CheckPolymorphic(Type) \ 4236 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4237 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4238 } 4239 CheckPolymorphic(PointerTypeLoc) 4240 CheckPolymorphic(ReferenceTypeLoc) 4241 CheckPolymorphic(MemberPointerTypeLoc) 4242 CheckPolymorphic(BlockPointerTypeLoc) 4243 CheckPolymorphic(AtomicTypeLoc) 4244 4245 /// Handle all the types we haven't given a more specific 4246 /// implementation for above. 4247 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4248 // Every other kind of type that we haven't called out already 4249 // that has an inner type is either (1) sugar or (2) contains that 4250 // inner type in some way as a subobject. 4251 if (TypeLoc Next = TL.getNextTypeLoc()) 4252 return Visit(Next, Sel); 4253 4254 // If there's no inner type and we're in a permissive context, 4255 // don't diagnose. 4256 if (Sel == Sema::AbstractNone) return; 4257 4258 // Check whether the type matches the abstract type. 4259 QualType T = TL.getType(); 4260 if (T->isArrayType()) { 4261 Sel = Sema::AbstractArrayType; 4262 T = Info.S.Context.getBaseElementType(T); 4263 } 4264 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4265 if (CT != Info.AbstractType) return; 4266 4267 // It matched; do some magic. 4268 if (Sel == Sema::AbstractArrayType) { 4269 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4270 << T << TL.getSourceRange(); 4271 } else { 4272 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4273 << Sel << T << TL.getSourceRange(); 4274 } 4275 Info.DiagnoseAbstractType(); 4276 } 4277}; 4278 4279void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4280 Sema::AbstractDiagSelID Sel) { 4281 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4282} 4283 4284} 4285 4286/// Check for invalid uses of an abstract type in a method declaration. 4287static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4288 CXXMethodDecl *MD) { 4289 // No need to do the check on definitions, which require that 4290 // the return/param types be complete. 4291 if (MD->doesThisDeclarationHaveABody()) 4292 return; 4293 4294 // For safety's sake, just ignore it if we don't have type source 4295 // information. This should never happen for non-implicit methods, 4296 // but... 4297 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4298 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4299} 4300 4301/// Check for invalid uses of an abstract type within a class definition. 4302static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4303 CXXRecordDecl *RD) { 4304 for (CXXRecordDecl::decl_iterator 4305 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 4306 Decl *D = *I; 4307 if (D->isImplicit()) continue; 4308 4309 // Methods and method templates. 4310 if (isa<CXXMethodDecl>(D)) { 4311 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4312 } else if (isa<FunctionTemplateDecl>(D)) { 4313 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4314 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4315 4316 // Fields and static variables. 4317 } else if (isa<FieldDecl>(D)) { 4318 FieldDecl *FD = cast<FieldDecl>(D); 4319 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4320 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4321 } else if (isa<VarDecl>(D)) { 4322 VarDecl *VD = cast<VarDecl>(D); 4323 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4324 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4325 4326 // Nested classes and class templates. 4327 } else if (isa<CXXRecordDecl>(D)) { 4328 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4329 } else if (isa<ClassTemplateDecl>(D)) { 4330 CheckAbstractClassUsage(Info, 4331 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4332 } 4333 } 4334} 4335 4336/// \brief Perform semantic checks on a class definition that has been 4337/// completing, introducing implicitly-declared members, checking for 4338/// abstract types, etc. 4339void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4340 if (!Record) 4341 return; 4342 4343 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4344 AbstractUsageInfo Info(*this, Record); 4345 CheckAbstractClassUsage(Info, Record); 4346 } 4347 4348 // If this is not an aggregate type and has no user-declared constructor, 4349 // complain about any non-static data members of reference or const scalar 4350 // type, since they will never get initializers. 4351 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4352 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4353 !Record->isLambda()) { 4354 bool Complained = false; 4355 for (RecordDecl::field_iterator F = Record->field_begin(), 4356 FEnd = Record->field_end(); 4357 F != FEnd; ++F) { 4358 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4359 continue; 4360 4361 if (F->getType()->isReferenceType() || 4362 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4363 if (!Complained) { 4364 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4365 << Record->getTagKind() << Record; 4366 Complained = true; 4367 } 4368 4369 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4370 << F->getType()->isReferenceType() 4371 << F->getDeclName(); 4372 } 4373 } 4374 } 4375 4376 if (Record->isDynamicClass() && !Record->isDependentType()) 4377 DynamicClasses.push_back(Record); 4378 4379 if (Record->getIdentifier()) { 4380 // C++ [class.mem]p13: 4381 // If T is the name of a class, then each of the following shall have a 4382 // name different from T: 4383 // - every member of every anonymous union that is a member of class T. 4384 // 4385 // C++ [class.mem]p14: 4386 // In addition, if class T has a user-declared constructor (12.1), every 4387 // non-static data member of class T shall have a name different from T. 4388 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4389 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4390 ++I) { 4391 NamedDecl *D = *I; 4392 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4393 isa<IndirectFieldDecl>(D)) { 4394 Diag(D->getLocation(), diag::err_member_name_of_class) 4395 << D->getDeclName(); 4396 break; 4397 } 4398 } 4399 } 4400 4401 // Warn if the class has virtual methods but non-virtual public destructor. 4402 if (Record->isPolymorphic() && !Record->isDependentType()) { 4403 CXXDestructorDecl *dtor = Record->getDestructor(); 4404 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 4405 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4406 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4407 } 4408 4409 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) { 4410 Diag(Record->getLocation(), diag::warn_abstract_final_class); 4411 DiagnoseAbstractType(Record); 4412 } 4413 4414 if (!Record->isDependentType()) { 4415 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4416 MEnd = Record->method_end(); 4417 M != MEnd; ++M) { 4418 // See if a method overloads virtual methods in a base 4419 // class without overriding any. 4420 if (!M->isStatic()) 4421 DiagnoseHiddenVirtualMethods(*M); 4422 4423 // Check whether the explicitly-defaulted special members are valid. 4424 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4425 CheckExplicitlyDefaultedSpecialMember(*M); 4426 4427 // For an explicitly defaulted or deleted special member, we defer 4428 // determining triviality until the class is complete. That time is now! 4429 if (!M->isImplicit() && !M->isUserProvided()) { 4430 CXXSpecialMember CSM = getSpecialMember(*M); 4431 if (CSM != CXXInvalid) { 4432 M->setTrivial(SpecialMemberIsTrivial(*M, CSM)); 4433 4434 // Inform the class that we've finished declaring this member. 4435 Record->finishedDefaultedOrDeletedMember(*M); 4436 } 4437 } 4438 } 4439 } 4440 4441 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4442 // function that is not a constructor declares that member function to be 4443 // const. [...] The class of which that function is a member shall be 4444 // a literal type. 4445 // 4446 // If the class has virtual bases, any constexpr members will already have 4447 // been diagnosed by the checks performed on the member declaration, so 4448 // suppress this (less useful) diagnostic. 4449 // 4450 // We delay this until we know whether an explicitly-defaulted (or deleted) 4451 // destructor for the class is trivial. 4452 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4453 !Record->isLiteral() && !Record->getNumVBases()) { 4454 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4455 MEnd = Record->method_end(); 4456 M != MEnd; ++M) { 4457 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 4458 switch (Record->getTemplateSpecializationKind()) { 4459 case TSK_ImplicitInstantiation: 4460 case TSK_ExplicitInstantiationDeclaration: 4461 case TSK_ExplicitInstantiationDefinition: 4462 // If a template instantiates to a non-literal type, but its members 4463 // instantiate to constexpr functions, the template is technically 4464 // ill-formed, but we allow it for sanity. 4465 continue; 4466 4467 case TSK_Undeclared: 4468 case TSK_ExplicitSpecialization: 4469 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4470 diag::err_constexpr_method_non_literal); 4471 break; 4472 } 4473 4474 // Only produce one error per class. 4475 break; 4476 } 4477 } 4478 } 4479 4480 // Check to see if we're trying to lay out a struct using the ms_struct 4481 // attribute that is dynamic. 4482 if (Record->isMsStruct(Context) && Record->isDynamicClass()) { 4483 Diag(Record->getLocation(), diag::warn_pragma_ms_struct_failed); 4484 Record->dropAttr<MsStructAttr>(); 4485 } 4486 4487 // Declare inheriting constructors. We do this eagerly here because: 4488 // - The standard requires an eager diagnostic for conflicting inheriting 4489 // constructors from different classes. 4490 // - The lazy declaration of the other implicit constructors is so as to not 4491 // waste space and performance on classes that are not meant to be 4492 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4493 // have inheriting constructors. 4494 DeclareInheritingConstructors(Record); 4495} 4496 4497/// Is the special member function which would be selected to perform the 4498/// specified operation on the specified class type a constexpr constructor? 4499static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4500 Sema::CXXSpecialMember CSM, 4501 bool ConstArg) { 4502 Sema::SpecialMemberOverloadResult *SMOR = 4503 S.LookupSpecialMember(ClassDecl, CSM, ConstArg, 4504 false, false, false, false); 4505 if (!SMOR || !SMOR->getMethod()) 4506 // A constructor we wouldn't select can't be "involved in initializing" 4507 // anything. 4508 return true; 4509 return SMOR->getMethod()->isConstexpr(); 4510} 4511 4512/// Determine whether the specified special member function would be constexpr 4513/// if it were implicitly defined. 4514static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4515 Sema::CXXSpecialMember CSM, 4516 bool ConstArg) { 4517 if (!S.getLangOpts().CPlusPlus11) 4518 return false; 4519 4520 // C++11 [dcl.constexpr]p4: 4521 // In the definition of a constexpr constructor [...] 4522 bool Ctor = true; 4523 switch (CSM) { 4524 case Sema::CXXDefaultConstructor: 4525 // Since default constructor lookup is essentially trivial (and cannot 4526 // involve, for instance, template instantiation), we compute whether a 4527 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4528 // 4529 // This is important for performance; we need to know whether the default 4530 // constructor is constexpr to determine whether the type is a literal type. 4531 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4532 4533 case Sema::CXXCopyConstructor: 4534 case Sema::CXXMoveConstructor: 4535 // For copy or move constructors, we need to perform overload resolution. 4536 break; 4537 4538 case Sema::CXXCopyAssignment: 4539 case Sema::CXXMoveAssignment: 4540 if (!S.getLangOpts().CPlusPlus1y) 4541 return false; 4542 // In C++1y, we need to perform overload resolution. 4543 Ctor = false; 4544 break; 4545 4546 case Sema::CXXDestructor: 4547 case Sema::CXXInvalid: 4548 return false; 4549 } 4550 4551 // -- if the class is a non-empty union, or for each non-empty anonymous 4552 // union member of a non-union class, exactly one non-static data member 4553 // shall be initialized; [DR1359] 4554 // 4555 // If we squint, this is guaranteed, since exactly one non-static data member 4556 // will be initialized (if the constructor isn't deleted), we just don't know 4557 // which one. 4558 if (Ctor && ClassDecl->isUnion()) 4559 return true; 4560 4561 // -- the class shall not have any virtual base classes; 4562 if (Ctor && ClassDecl->getNumVBases()) 4563 return false; 4564 4565 // C++1y [class.copy]p26: 4566 // -- [the class] is a literal type, and 4567 if (!Ctor && !ClassDecl->isLiteral()) 4568 return false; 4569 4570 // -- every constructor involved in initializing [...] base class 4571 // sub-objects shall be a constexpr constructor; 4572 // -- the assignment operator selected to copy/move each direct base 4573 // class is a constexpr function, and 4574 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4575 BEnd = ClassDecl->bases_end(); 4576 B != BEnd; ++B) { 4577 const RecordType *BaseType = B->getType()->getAs<RecordType>(); 4578 if (!BaseType) continue; 4579 4580 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4581 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg)) 4582 return false; 4583 } 4584 4585 // -- every constructor involved in initializing non-static data members 4586 // [...] shall be a constexpr constructor; 4587 // -- every non-static data member and base class sub-object shall be 4588 // initialized 4589 // -- for each non-stastic data member of X that is of class type (or array 4590 // thereof), the assignment operator selected to copy/move that member is 4591 // a constexpr function 4592 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4593 FEnd = ClassDecl->field_end(); 4594 F != FEnd; ++F) { 4595 if (F->isInvalidDecl()) 4596 continue; 4597 if (const RecordType *RecordTy = 4598 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4599 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4600 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg)) 4601 return false; 4602 } 4603 } 4604 4605 // All OK, it's constexpr! 4606 return true; 4607} 4608 4609static Sema::ImplicitExceptionSpecification 4610computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4611 switch (S.getSpecialMember(MD)) { 4612 case Sema::CXXDefaultConstructor: 4613 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4614 case Sema::CXXCopyConstructor: 4615 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4616 case Sema::CXXCopyAssignment: 4617 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4618 case Sema::CXXMoveConstructor: 4619 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4620 case Sema::CXXMoveAssignment: 4621 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4622 case Sema::CXXDestructor: 4623 return S.ComputeDefaultedDtorExceptionSpec(MD); 4624 case Sema::CXXInvalid: 4625 break; 4626 } 4627 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4628 "only special members have implicit exception specs"); 4629 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4630} 4631 4632static void 4633updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT, 4634 const Sema::ImplicitExceptionSpecification &ExceptSpec) { 4635 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4636 ExceptSpec.getEPI(EPI); 4637 FD->setType(S.Context.getFunctionType(FPT->getResultType(), 4638 FPT->getArgTypes(), EPI)); 4639} 4640 4641static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 4642 CXXMethodDecl *MD) { 4643 FunctionProtoType::ExtProtoInfo EPI; 4644 4645 // Build an exception specification pointing back at this member. 4646 EPI.ExceptionSpecType = EST_Unevaluated; 4647 EPI.ExceptionSpecDecl = MD; 4648 4649 // Set the calling convention to the default for C++ instance methods. 4650 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 4651 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4652 /*IsCXXMethod=*/true)); 4653 return EPI; 4654} 4655 4656void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4657 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4658 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4659 return; 4660 4661 // Evaluate the exception specification. 4662 ImplicitExceptionSpecification ExceptSpec = 4663 computeImplicitExceptionSpec(*this, Loc, MD); 4664 4665 // Update the type of the special member to use it. 4666 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4667 4668 // A user-provided destructor can be defined outside the class. When that 4669 // happens, be sure to update the exception specification on both 4670 // declarations. 4671 const FunctionProtoType *CanonicalFPT = 4672 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4673 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4674 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4675 CanonicalFPT, ExceptSpec); 4676} 4677 4678void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4679 CXXRecordDecl *RD = MD->getParent(); 4680 CXXSpecialMember CSM = getSpecialMember(MD); 4681 4682 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4683 "not an explicitly-defaulted special member"); 4684 4685 // Whether this was the first-declared instance of the constructor. 4686 // This affects whether we implicitly add an exception spec and constexpr. 4687 bool First = MD == MD->getCanonicalDecl(); 4688 4689 bool HadError = false; 4690 4691 // C++11 [dcl.fct.def.default]p1: 4692 // A function that is explicitly defaulted shall 4693 // -- be a special member function (checked elsewhere), 4694 // -- have the same type (except for ref-qualifiers, and except that a 4695 // copy operation can take a non-const reference) as an implicit 4696 // declaration, and 4697 // -- not have default arguments. 4698 unsigned ExpectedParams = 1; 4699 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4700 ExpectedParams = 0; 4701 if (MD->getNumParams() != ExpectedParams) { 4702 // This also checks for default arguments: a copy or move constructor with a 4703 // default argument is classified as a default constructor, and assignment 4704 // operations and destructors can't have default arguments. 4705 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4706 << CSM << MD->getSourceRange(); 4707 HadError = true; 4708 } else if (MD->isVariadic()) { 4709 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4710 << CSM << MD->getSourceRange(); 4711 HadError = true; 4712 } 4713 4714 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4715 4716 bool CanHaveConstParam = false; 4717 if (CSM == CXXCopyConstructor) 4718 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4719 else if (CSM == CXXCopyAssignment) 4720 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4721 4722 QualType ReturnType = Context.VoidTy; 4723 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4724 // Check for return type matching. 4725 ReturnType = Type->getResultType(); 4726 QualType ExpectedReturnType = 4727 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4728 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4729 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4730 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4731 HadError = true; 4732 } 4733 4734 // A defaulted special member cannot have cv-qualifiers. 4735 if (Type->getTypeQuals()) { 4736 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4737 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y; 4738 HadError = true; 4739 } 4740 } 4741 4742 // Check for parameter type matching. 4743 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType(); 4744 bool HasConstParam = false; 4745 if (ExpectedParams && ArgType->isReferenceType()) { 4746 // Argument must be reference to possibly-const T. 4747 QualType ReferentType = ArgType->getPointeeType(); 4748 HasConstParam = ReferentType.isConstQualified(); 4749 4750 if (ReferentType.isVolatileQualified()) { 4751 Diag(MD->getLocation(), 4752 diag::err_defaulted_special_member_volatile_param) << CSM; 4753 HadError = true; 4754 } 4755 4756 if (HasConstParam && !CanHaveConstParam) { 4757 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4758 Diag(MD->getLocation(), 4759 diag::err_defaulted_special_member_copy_const_param) 4760 << (CSM == CXXCopyAssignment); 4761 // FIXME: Explain why this special member can't be const. 4762 } else { 4763 Diag(MD->getLocation(), 4764 diag::err_defaulted_special_member_move_const_param) 4765 << (CSM == CXXMoveAssignment); 4766 } 4767 HadError = true; 4768 } 4769 } else if (ExpectedParams) { 4770 // A copy assignment operator can take its argument by value, but a 4771 // defaulted one cannot. 4772 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4773 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4774 HadError = true; 4775 } 4776 4777 // C++11 [dcl.fct.def.default]p2: 4778 // An explicitly-defaulted function may be declared constexpr only if it 4779 // would have been implicitly declared as constexpr, 4780 // Do not apply this rule to members of class templates, since core issue 1358 4781 // makes such functions always instantiate to constexpr functions. For 4782 // functions which cannot be constexpr (for non-constructors in C++11 and for 4783 // destructors in C++1y), this is checked elsewhere. 4784 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4785 HasConstParam); 4786 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD) 4787 : isa<CXXConstructorDecl>(MD)) && 4788 MD->isConstexpr() && !Constexpr && 4789 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4790 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4791 // FIXME: Explain why the special member can't be constexpr. 4792 HadError = true; 4793 } 4794 4795 // and may have an explicit exception-specification only if it is compatible 4796 // with the exception-specification on the implicit declaration. 4797 if (Type->hasExceptionSpec()) { 4798 // Delay the check if this is the first declaration of the special member, 4799 // since we may not have parsed some necessary in-class initializers yet. 4800 if (First) { 4801 // If the exception specification needs to be instantiated, do so now, 4802 // before we clobber it with an EST_Unevaluated specification below. 4803 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4804 InstantiateExceptionSpec(MD->getLocStart(), MD); 4805 Type = MD->getType()->getAs<FunctionProtoType>(); 4806 } 4807 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4808 } else 4809 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4810 } 4811 4812 // If a function is explicitly defaulted on its first declaration, 4813 if (First) { 4814 // -- it is implicitly considered to be constexpr if the implicit 4815 // definition would be, 4816 MD->setConstexpr(Constexpr); 4817 4818 // -- it is implicitly considered to have the same exception-specification 4819 // as if it had been implicitly declared, 4820 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4821 EPI.ExceptionSpecType = EST_Unevaluated; 4822 EPI.ExceptionSpecDecl = MD; 4823 MD->setType(Context.getFunctionType(ReturnType, 4824 ArrayRef<QualType>(&ArgType, 4825 ExpectedParams), 4826 EPI)); 4827 } 4828 4829 if (ShouldDeleteSpecialMember(MD, CSM)) { 4830 if (First) { 4831 SetDeclDeleted(MD, MD->getLocation()); 4832 } else { 4833 // C++11 [dcl.fct.def.default]p4: 4834 // [For a] user-provided explicitly-defaulted function [...] if such a 4835 // function is implicitly defined as deleted, the program is ill-formed. 4836 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4837 HadError = true; 4838 } 4839 } 4840 4841 if (HadError) 4842 MD->setInvalidDecl(); 4843} 4844 4845/// Check whether the exception specification provided for an 4846/// explicitly-defaulted special member matches the exception specification 4847/// that would have been generated for an implicit special member, per 4848/// C++11 [dcl.fct.def.default]p2. 4849void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 4850 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 4851 // Compute the implicit exception specification. 4852 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4853 /*IsCXXMethod=*/true); 4854 FunctionProtoType::ExtProtoInfo EPI(CC); 4855 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4856 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 4857 Context.getFunctionType(Context.VoidTy, None, EPI)); 4858 4859 // Ensure that it matches. 4860 CheckEquivalentExceptionSpec( 4861 PDiag(diag::err_incorrect_defaulted_exception_spec) 4862 << getSpecialMember(MD), PDiag(), 4863 ImplicitType, SourceLocation(), 4864 SpecifiedType, MD->getLocation()); 4865} 4866 4867void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() { 4868 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size(); 4869 I != N; ++I) 4870 CheckExplicitlyDefaultedMemberExceptionSpec( 4871 DelayedDefaultedMemberExceptionSpecs[I].first, 4872 DelayedDefaultedMemberExceptionSpecs[I].second); 4873 4874 DelayedDefaultedMemberExceptionSpecs.clear(); 4875} 4876 4877namespace { 4878struct SpecialMemberDeletionInfo { 4879 Sema &S; 4880 CXXMethodDecl *MD; 4881 Sema::CXXSpecialMember CSM; 4882 bool Diagnose; 4883 4884 // Properties of the special member, computed for convenience. 4885 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg; 4886 SourceLocation Loc; 4887 4888 bool AllFieldsAreConst; 4889 4890 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4891 Sema::CXXSpecialMember CSM, bool Diagnose) 4892 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4893 IsConstructor(false), IsAssignment(false), IsMove(false), 4894 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()), 4895 AllFieldsAreConst(true) { 4896 switch (CSM) { 4897 case Sema::CXXDefaultConstructor: 4898 case Sema::CXXCopyConstructor: 4899 IsConstructor = true; 4900 break; 4901 case Sema::CXXMoveConstructor: 4902 IsConstructor = true; 4903 IsMove = true; 4904 break; 4905 case Sema::CXXCopyAssignment: 4906 IsAssignment = true; 4907 break; 4908 case Sema::CXXMoveAssignment: 4909 IsAssignment = true; 4910 IsMove = true; 4911 break; 4912 case Sema::CXXDestructor: 4913 break; 4914 case Sema::CXXInvalid: 4915 llvm_unreachable("invalid special member kind"); 4916 } 4917 4918 if (MD->getNumParams()) { 4919 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4920 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified(); 4921 } 4922 } 4923 4924 bool inUnion() const { return MD->getParent()->isUnion(); } 4925 4926 /// Look up the corresponding special member in the given class. 4927 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4928 unsigned Quals) { 4929 unsigned TQ = MD->getTypeQualifiers(); 4930 // cv-qualifiers on class members don't affect default ctor / dtor calls. 4931 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4932 Quals = 0; 4933 return S.LookupSpecialMember(Class, CSM, 4934 ConstArg || (Quals & Qualifiers::Const), 4935 VolatileArg || (Quals & Qualifiers::Volatile), 4936 MD->getRefQualifier() == RQ_RValue, 4937 TQ & Qualifiers::Const, 4938 TQ & Qualifiers::Volatile); 4939 } 4940 4941 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4942 4943 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4944 bool shouldDeleteForField(FieldDecl *FD); 4945 bool shouldDeleteForAllConstMembers(); 4946 4947 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4948 unsigned Quals); 4949 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4950 Sema::SpecialMemberOverloadResult *SMOR, 4951 bool IsDtorCallInCtor); 4952 4953 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4954}; 4955} 4956 4957/// Is the given special member inaccessible when used on the given 4958/// sub-object. 4959bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4960 CXXMethodDecl *target) { 4961 /// If we're operating on a base class, the object type is the 4962 /// type of this special member. 4963 QualType objectTy; 4964 AccessSpecifier access = target->getAccess(); 4965 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 4966 objectTy = S.Context.getTypeDeclType(MD->getParent()); 4967 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 4968 4969 // If we're operating on a field, the object type is the type of the field. 4970 } else { 4971 objectTy = S.Context.getTypeDeclType(target->getParent()); 4972 } 4973 4974 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 4975} 4976 4977/// Check whether we should delete a special member due to the implicit 4978/// definition containing a call to a special member of a subobject. 4979bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 4980 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 4981 bool IsDtorCallInCtor) { 4982 CXXMethodDecl *Decl = SMOR->getMethod(); 4983 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4984 4985 int DiagKind = -1; 4986 4987 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 4988 DiagKind = !Decl ? 0 : 1; 4989 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4990 DiagKind = 2; 4991 else if (!isAccessible(Subobj, Decl)) 4992 DiagKind = 3; 4993 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 4994 !Decl->isTrivial()) { 4995 // A member of a union must have a trivial corresponding special member. 4996 // As a weird special case, a destructor call from a union's constructor 4997 // must be accessible and non-deleted, but need not be trivial. Such a 4998 // destructor is never actually called, but is semantically checked as 4999 // if it were. 5000 DiagKind = 4; 5001 } 5002 5003 if (DiagKind == -1) 5004 return false; 5005 5006 if (Diagnose) { 5007 if (Field) { 5008 S.Diag(Field->getLocation(), 5009 diag::note_deleted_special_member_class_subobject) 5010 << CSM << MD->getParent() << /*IsField*/true 5011 << Field << DiagKind << IsDtorCallInCtor; 5012 } else { 5013 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5014 S.Diag(Base->getLocStart(), 5015 diag::note_deleted_special_member_class_subobject) 5016 << CSM << MD->getParent() << /*IsField*/false 5017 << Base->getType() << DiagKind << IsDtorCallInCtor; 5018 } 5019 5020 if (DiagKind == 1) 5021 S.NoteDeletedFunction(Decl); 5022 // FIXME: Explain inaccessibility if DiagKind == 3. 5023 } 5024 5025 return true; 5026} 5027 5028/// Check whether we should delete a special member function due to having a 5029/// direct or virtual base class or non-static data member of class type M. 5030bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5031 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5032 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5033 5034 // C++11 [class.ctor]p5: 5035 // -- any direct or virtual base class, or non-static data member with no 5036 // brace-or-equal-initializer, has class type M (or array thereof) and 5037 // either M has no default constructor or overload resolution as applied 5038 // to M's default constructor results in an ambiguity or in a function 5039 // that is deleted or inaccessible 5040 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5041 // -- a direct or virtual base class B that cannot be copied/moved because 5042 // overload resolution, as applied to B's corresponding special member, 5043 // results in an ambiguity or a function that is deleted or inaccessible 5044 // from the defaulted special member 5045 // C++11 [class.dtor]p5: 5046 // -- any direct or virtual base class [...] has a type with a destructor 5047 // that is deleted or inaccessible 5048 if (!(CSM == Sema::CXXDefaultConstructor && 5049 Field && Field->hasInClassInitializer()) && 5050 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false)) 5051 return true; 5052 5053 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5054 // -- any direct or virtual base class or non-static data member has a 5055 // type with a destructor that is deleted or inaccessible 5056 if (IsConstructor) { 5057 Sema::SpecialMemberOverloadResult *SMOR = 5058 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5059 false, false, false, false, false); 5060 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5061 return true; 5062 } 5063 5064 return false; 5065} 5066 5067/// Check whether we should delete a special member function due to the class 5068/// having a particular direct or virtual base class. 5069bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5070 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5071 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5072} 5073 5074/// Check whether we should delete a special member function due to the class 5075/// having a particular non-static data member. 5076bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5077 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5078 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5079 5080 if (CSM == Sema::CXXDefaultConstructor) { 5081 // For a default constructor, all references must be initialized in-class 5082 // and, if a union, it must have a non-const member. 5083 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5084 if (Diagnose) 5085 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5086 << MD->getParent() << FD << FieldType << /*Reference*/0; 5087 return true; 5088 } 5089 // C++11 [class.ctor]p5: any non-variant non-static data member of 5090 // const-qualified type (or array thereof) with no 5091 // brace-or-equal-initializer does not have a user-provided default 5092 // constructor. 5093 if (!inUnion() && FieldType.isConstQualified() && 5094 !FD->hasInClassInitializer() && 5095 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5096 if (Diagnose) 5097 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5098 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5099 return true; 5100 } 5101 5102 if (inUnion() && !FieldType.isConstQualified()) 5103 AllFieldsAreConst = false; 5104 } else if (CSM == Sema::CXXCopyConstructor) { 5105 // For a copy constructor, data members must not be of rvalue reference 5106 // type. 5107 if (FieldType->isRValueReferenceType()) { 5108 if (Diagnose) 5109 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5110 << MD->getParent() << FD << FieldType; 5111 return true; 5112 } 5113 } else if (IsAssignment) { 5114 // For an assignment operator, data members must not be of reference type. 5115 if (FieldType->isReferenceType()) { 5116 if (Diagnose) 5117 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5118 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5119 return true; 5120 } 5121 if (!FieldRecord && FieldType.isConstQualified()) { 5122 // C++11 [class.copy]p23: 5123 // -- a non-static data member of const non-class type (or array thereof) 5124 if (Diagnose) 5125 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5126 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5127 return true; 5128 } 5129 } 5130 5131 if (FieldRecord) { 5132 // Some additional restrictions exist on the variant members. 5133 if (!inUnion() && FieldRecord->isUnion() && 5134 FieldRecord->isAnonymousStructOrUnion()) { 5135 bool AllVariantFieldsAreConst = true; 5136 5137 // FIXME: Handle anonymous unions declared within anonymous unions. 5138 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 5139 UE = FieldRecord->field_end(); 5140 UI != UE; ++UI) { 5141 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5142 5143 if (!UnionFieldType.isConstQualified()) 5144 AllVariantFieldsAreConst = false; 5145 5146 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5147 if (UnionFieldRecord && 5148 shouldDeleteForClassSubobject(UnionFieldRecord, *UI, 5149 UnionFieldType.getCVRQualifiers())) 5150 return true; 5151 } 5152 5153 // At least one member in each anonymous union must be non-const 5154 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5155 FieldRecord->field_begin() != FieldRecord->field_end()) { 5156 if (Diagnose) 5157 S.Diag(FieldRecord->getLocation(), 5158 diag::note_deleted_default_ctor_all_const) 5159 << MD->getParent() << /*anonymous union*/1; 5160 return true; 5161 } 5162 5163 // Don't check the implicit member of the anonymous union type. 5164 // This is technically non-conformant, but sanity demands it. 5165 return false; 5166 } 5167 5168 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5169 FieldType.getCVRQualifiers())) 5170 return true; 5171 } 5172 5173 return false; 5174} 5175 5176/// C++11 [class.ctor] p5: 5177/// A defaulted default constructor for a class X is defined as deleted if 5178/// X is a union and all of its variant members are of const-qualified type. 5179bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5180 // This is a silly definition, because it gives an empty union a deleted 5181 // default constructor. Don't do that. 5182 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5183 (MD->getParent()->field_begin() != MD->getParent()->field_end())) { 5184 if (Diagnose) 5185 S.Diag(MD->getParent()->getLocation(), 5186 diag::note_deleted_default_ctor_all_const) 5187 << MD->getParent() << /*not anonymous union*/0; 5188 return true; 5189 } 5190 return false; 5191} 5192 5193/// Determine whether a defaulted special member function should be defined as 5194/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5195/// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5196bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5197 bool Diagnose) { 5198 if (MD->isInvalidDecl()) 5199 return false; 5200 CXXRecordDecl *RD = MD->getParent(); 5201 assert(!RD->isDependentType() && "do deletion after instantiation"); 5202 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5203 return false; 5204 5205 // C++11 [expr.lambda.prim]p19: 5206 // The closure type associated with a lambda-expression has a 5207 // deleted (8.4.3) default constructor and a deleted copy 5208 // assignment operator. 5209 if (RD->isLambda() && 5210 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5211 if (Diagnose) 5212 Diag(RD->getLocation(), diag::note_lambda_decl); 5213 return true; 5214 } 5215 5216 // For an anonymous struct or union, the copy and assignment special members 5217 // will never be used, so skip the check. For an anonymous union declared at 5218 // namespace scope, the constructor and destructor are used. 5219 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5220 RD->isAnonymousStructOrUnion()) 5221 return false; 5222 5223 // C++11 [class.copy]p7, p18: 5224 // If the class definition declares a move constructor or move assignment 5225 // operator, an implicitly declared copy constructor or copy assignment 5226 // operator is defined as deleted. 5227 if (MD->isImplicit() && 5228 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5229 CXXMethodDecl *UserDeclaredMove = 0; 5230 5231 // In Microsoft mode, a user-declared move only causes the deletion of the 5232 // corresponding copy operation, not both copy operations. 5233 if (RD->hasUserDeclaredMoveConstructor() && 5234 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) { 5235 if (!Diagnose) return true; 5236 5237 // Find any user-declared move constructor. 5238 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 5239 E = RD->ctor_end(); I != E; ++I) { 5240 if (I->isMoveConstructor()) { 5241 UserDeclaredMove = *I; 5242 break; 5243 } 5244 } 5245 assert(UserDeclaredMove); 5246 } else if (RD->hasUserDeclaredMoveAssignment() && 5247 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) { 5248 if (!Diagnose) return true; 5249 5250 // Find any user-declared move assignment operator. 5251 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 5252 E = RD->method_end(); I != E; ++I) { 5253 if (I->isMoveAssignmentOperator()) { 5254 UserDeclaredMove = *I; 5255 break; 5256 } 5257 } 5258 assert(UserDeclaredMove); 5259 } 5260 5261 if (UserDeclaredMove) { 5262 Diag(UserDeclaredMove->getLocation(), 5263 diag::note_deleted_copy_user_declared_move) 5264 << (CSM == CXXCopyAssignment) << RD 5265 << UserDeclaredMove->isMoveAssignmentOperator(); 5266 return true; 5267 } 5268 } 5269 5270 // Do access control from the special member function 5271 ContextRAII MethodContext(*this, MD); 5272 5273 // C++11 [class.dtor]p5: 5274 // -- for a virtual destructor, lookup of the non-array deallocation function 5275 // results in an ambiguity or in a function that is deleted or inaccessible 5276 if (CSM == CXXDestructor && MD->isVirtual()) { 5277 FunctionDecl *OperatorDelete = 0; 5278 DeclarationName Name = 5279 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5280 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5281 OperatorDelete, false)) { 5282 if (Diagnose) 5283 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5284 return true; 5285 } 5286 } 5287 5288 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5289 5290 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5291 BE = RD->bases_end(); BI != BE; ++BI) 5292 if (!BI->isVirtual() && 5293 SMI.shouldDeleteForBase(BI)) 5294 return true; 5295 5296 // Per DR1611, do not consider virtual bases of constructors of abstract 5297 // classes, since we are not going to construct them. 5298 if (!RD->isAbstract() || !SMI.IsConstructor) { 5299 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 5300 BE = RD->vbases_end(); 5301 BI != BE; ++BI) 5302 if (SMI.shouldDeleteForBase(BI)) 5303 return true; 5304 } 5305 5306 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5307 FE = RD->field_end(); FI != FE; ++FI) 5308 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5309 SMI.shouldDeleteForField(*FI)) 5310 return true; 5311 5312 if (SMI.shouldDeleteForAllConstMembers()) 5313 return true; 5314 5315 return false; 5316} 5317 5318/// Perform lookup for a special member of the specified kind, and determine 5319/// whether it is trivial. If the triviality can be determined without the 5320/// lookup, skip it. This is intended for use when determining whether a 5321/// special member of a containing object is trivial, and thus does not ever 5322/// perform overload resolution for default constructors. 5323/// 5324/// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5325/// member that was most likely to be intended to be trivial, if any. 5326static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5327 Sema::CXXSpecialMember CSM, unsigned Quals, 5328 CXXMethodDecl **Selected) { 5329 if (Selected) 5330 *Selected = 0; 5331 5332 switch (CSM) { 5333 case Sema::CXXInvalid: 5334 llvm_unreachable("not a special member"); 5335 5336 case Sema::CXXDefaultConstructor: 5337 // C++11 [class.ctor]p5: 5338 // A default constructor is trivial if: 5339 // - all the [direct subobjects] have trivial default constructors 5340 // 5341 // Note, no overload resolution is performed in this case. 5342 if (RD->hasTrivialDefaultConstructor()) 5343 return true; 5344 5345 if (Selected) { 5346 // If there's a default constructor which could have been trivial, dig it 5347 // out. Otherwise, if there's any user-provided default constructor, point 5348 // to that as an example of why there's not a trivial one. 5349 CXXConstructorDecl *DefCtor = 0; 5350 if (RD->needsImplicitDefaultConstructor()) 5351 S.DeclareImplicitDefaultConstructor(RD); 5352 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), 5353 CE = RD->ctor_end(); CI != CE; ++CI) { 5354 if (!CI->isDefaultConstructor()) 5355 continue; 5356 DefCtor = *CI; 5357 if (!DefCtor->isUserProvided()) 5358 break; 5359 } 5360 5361 *Selected = DefCtor; 5362 } 5363 5364 return false; 5365 5366 case Sema::CXXDestructor: 5367 // C++11 [class.dtor]p5: 5368 // A destructor is trivial if: 5369 // - all the direct [subobjects] have trivial destructors 5370 if (RD->hasTrivialDestructor()) 5371 return true; 5372 5373 if (Selected) { 5374 if (RD->needsImplicitDestructor()) 5375 S.DeclareImplicitDestructor(RD); 5376 *Selected = RD->getDestructor(); 5377 } 5378 5379 return false; 5380 5381 case Sema::CXXCopyConstructor: 5382 // C++11 [class.copy]p12: 5383 // A copy constructor is trivial if: 5384 // - the constructor selected to copy each direct [subobject] is trivial 5385 if (RD->hasTrivialCopyConstructor()) { 5386 if (Quals == Qualifiers::Const) 5387 // We must either select the trivial copy constructor or reach an 5388 // ambiguity; no need to actually perform overload resolution. 5389 return true; 5390 } else if (!Selected) { 5391 return false; 5392 } 5393 // In C++98, we are not supposed to perform overload resolution here, but we 5394 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5395 // cases like B as having a non-trivial copy constructor: 5396 // struct A { template<typename T> A(T&); }; 5397 // struct B { mutable A a; }; 5398 goto NeedOverloadResolution; 5399 5400 case Sema::CXXCopyAssignment: 5401 // C++11 [class.copy]p25: 5402 // A copy assignment operator is trivial if: 5403 // - the assignment operator selected to copy each direct [subobject] is 5404 // trivial 5405 if (RD->hasTrivialCopyAssignment()) { 5406 if (Quals == Qualifiers::Const) 5407 return true; 5408 } else if (!Selected) { 5409 return false; 5410 } 5411 // In C++98, we are not supposed to perform overload resolution here, but we 5412 // treat that as a language defect. 5413 goto NeedOverloadResolution; 5414 5415 case Sema::CXXMoveConstructor: 5416 case Sema::CXXMoveAssignment: 5417 NeedOverloadResolution: 5418 Sema::SpecialMemberOverloadResult *SMOR = 5419 S.LookupSpecialMember(RD, CSM, 5420 Quals & Qualifiers::Const, 5421 Quals & Qualifiers::Volatile, 5422 /*RValueThis*/false, /*ConstThis*/false, 5423 /*VolatileThis*/false); 5424 5425 // The standard doesn't describe how to behave if the lookup is ambiguous. 5426 // We treat it as not making the member non-trivial, just like the standard 5427 // mandates for the default constructor. This should rarely matter, because 5428 // the member will also be deleted. 5429 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5430 return true; 5431 5432 if (!SMOR->getMethod()) { 5433 assert(SMOR->getKind() == 5434 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5435 return false; 5436 } 5437 5438 // We deliberately don't check if we found a deleted special member. We're 5439 // not supposed to! 5440 if (Selected) 5441 *Selected = SMOR->getMethod(); 5442 return SMOR->getMethod()->isTrivial(); 5443 } 5444 5445 llvm_unreachable("unknown special method kind"); 5446} 5447 5448static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5449 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end(); 5450 CI != CE; ++CI) 5451 if (!CI->isImplicit()) 5452 return *CI; 5453 5454 // Look for constructor templates. 5455 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5456 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5457 if (CXXConstructorDecl *CD = 5458 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5459 return CD; 5460 } 5461 5462 return 0; 5463} 5464 5465/// The kind of subobject we are checking for triviality. The values of this 5466/// enumeration are used in diagnostics. 5467enum TrivialSubobjectKind { 5468 /// The subobject is a base class. 5469 TSK_BaseClass, 5470 /// The subobject is a non-static data member. 5471 TSK_Field, 5472 /// The object is actually the complete object. 5473 TSK_CompleteObject 5474}; 5475 5476/// Check whether the special member selected for a given type would be trivial. 5477static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5478 QualType SubType, 5479 Sema::CXXSpecialMember CSM, 5480 TrivialSubobjectKind Kind, 5481 bool Diagnose) { 5482 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5483 if (!SubRD) 5484 return true; 5485 5486 CXXMethodDecl *Selected; 5487 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5488 Diagnose ? &Selected : 0)) 5489 return true; 5490 5491 if (Diagnose) { 5492 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5493 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5494 << Kind << SubType.getUnqualifiedType(); 5495 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5496 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5497 } else if (!Selected) 5498 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5499 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5500 else if (Selected->isUserProvided()) { 5501 if (Kind == TSK_CompleteObject) 5502 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5503 << Kind << SubType.getUnqualifiedType() << CSM; 5504 else { 5505 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5506 << Kind << SubType.getUnqualifiedType() << CSM; 5507 S.Diag(Selected->getLocation(), diag::note_declared_at); 5508 } 5509 } else { 5510 if (Kind != TSK_CompleteObject) 5511 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5512 << Kind << SubType.getUnqualifiedType() << CSM; 5513 5514 // Explain why the defaulted or deleted special member isn't trivial. 5515 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5516 } 5517 } 5518 5519 return false; 5520} 5521 5522/// Check whether the members of a class type allow a special member to be 5523/// trivial. 5524static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5525 Sema::CXXSpecialMember CSM, 5526 bool ConstArg, bool Diagnose) { 5527 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5528 FE = RD->field_end(); FI != FE; ++FI) { 5529 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5530 continue; 5531 5532 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5533 5534 // Pretend anonymous struct or union members are members of this class. 5535 if (FI->isAnonymousStructOrUnion()) { 5536 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5537 CSM, ConstArg, Diagnose)) 5538 return false; 5539 continue; 5540 } 5541 5542 // C++11 [class.ctor]p5: 5543 // A default constructor is trivial if [...] 5544 // -- no non-static data member of its class has a 5545 // brace-or-equal-initializer 5546 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5547 if (Diagnose) 5548 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI; 5549 return false; 5550 } 5551 5552 // Objective C ARC 4.3.5: 5553 // [...] nontrivally ownership-qualified types are [...] not trivially 5554 // default constructible, copy constructible, move constructible, copy 5555 // assignable, move assignable, or destructible [...] 5556 if (S.getLangOpts().ObjCAutoRefCount && 5557 FieldType.hasNonTrivialObjCLifetime()) { 5558 if (Diagnose) 5559 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5560 << RD << FieldType.getObjCLifetime(); 5561 return false; 5562 } 5563 5564 if (ConstArg && !FI->isMutable()) 5565 FieldType.addConst(); 5566 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM, 5567 TSK_Field, Diagnose)) 5568 return false; 5569 } 5570 5571 return true; 5572} 5573 5574/// Diagnose why the specified class does not have a trivial special member of 5575/// the given kind. 5576void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5577 QualType Ty = Context.getRecordType(RD); 5578 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) 5579 Ty.addConst(); 5580 5581 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM, 5582 TSK_CompleteObject, /*Diagnose*/true); 5583} 5584 5585/// Determine whether a defaulted or deleted special member function is trivial, 5586/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5587/// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5588bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5589 bool Diagnose) { 5590 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5591 5592 CXXRecordDecl *RD = MD->getParent(); 5593 5594 bool ConstArg = false; 5595 5596 // C++11 [class.copy]p12, p25: 5597 // A [special member] is trivial if its declared parameter type is the same 5598 // as if it had been implicitly declared [...] 5599 switch (CSM) { 5600 case CXXDefaultConstructor: 5601 case CXXDestructor: 5602 // Trivial default constructors and destructors cannot have parameters. 5603 break; 5604 5605 case CXXCopyConstructor: 5606 case CXXCopyAssignment: { 5607 // Trivial copy operations always have const, non-volatile parameter types. 5608 ConstArg = true; 5609 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5610 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5611 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5612 if (Diagnose) 5613 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5614 << Param0->getSourceRange() << Param0->getType() 5615 << Context.getLValueReferenceType( 5616 Context.getRecordType(RD).withConst()); 5617 return false; 5618 } 5619 break; 5620 } 5621 5622 case CXXMoveConstructor: 5623 case CXXMoveAssignment: { 5624 // Trivial move operations always have non-cv-qualified parameters. 5625 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5626 const RValueReferenceType *RT = 5627 Param0->getType()->getAs<RValueReferenceType>(); 5628 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5629 if (Diagnose) 5630 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5631 << Param0->getSourceRange() << Param0->getType() 5632 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5633 return false; 5634 } 5635 break; 5636 } 5637 5638 case CXXInvalid: 5639 llvm_unreachable("not a special member"); 5640 } 5641 5642 // FIXME: We require that the parameter-declaration-clause is equivalent to 5643 // that of an implicit declaration, not just that the declared parameter type 5644 // matches, in order to prevent absuridities like a function simultaneously 5645 // being a trivial copy constructor and a non-trivial default constructor. 5646 // This issue has not yet been assigned a core issue number. 5647 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5648 if (Diagnose) 5649 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5650 diag::note_nontrivial_default_arg) 5651 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5652 return false; 5653 } 5654 if (MD->isVariadic()) { 5655 if (Diagnose) 5656 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5657 return false; 5658 } 5659 5660 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5661 // A copy/move [constructor or assignment operator] is trivial if 5662 // -- the [member] selected to copy/move each direct base class subobject 5663 // is trivial 5664 // 5665 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5666 // A [default constructor or destructor] is trivial if 5667 // -- all the direct base classes have trivial [default constructors or 5668 // destructors] 5669 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5670 BE = RD->bases_end(); BI != BE; ++BI) 5671 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), 5672 ConstArg ? BI->getType().withConst() 5673 : BI->getType(), 5674 CSM, TSK_BaseClass, Diagnose)) 5675 return false; 5676 5677 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5678 // A copy/move [constructor or assignment operator] for a class X is 5679 // trivial if 5680 // -- for each non-static data member of X that is of class type (or array 5681 // thereof), the constructor selected to copy/move that member is 5682 // trivial 5683 // 5684 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5685 // A [default constructor or destructor] is trivial if 5686 // -- for all of the non-static data members of its class that are of class 5687 // type (or array thereof), each such class has a trivial [default 5688 // constructor or destructor] 5689 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5690 return false; 5691 5692 // C++11 [class.dtor]p5: 5693 // A destructor is trivial if [...] 5694 // -- the destructor is not virtual 5695 if (CSM == CXXDestructor && MD->isVirtual()) { 5696 if (Diagnose) 5697 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5698 return false; 5699 } 5700 5701 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5702 // A [special member] for class X is trivial if [...] 5703 // -- class X has no virtual functions and no virtual base classes 5704 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5705 if (!Diagnose) 5706 return false; 5707 5708 if (RD->getNumVBases()) { 5709 // Check for virtual bases. We already know that the corresponding 5710 // member in all bases is trivial, so vbases must all be direct. 5711 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5712 assert(BS.isVirtual()); 5713 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5714 return false; 5715 } 5716 5717 // Must have a virtual method. 5718 for (CXXRecordDecl::method_iterator MI = RD->method_begin(), 5719 ME = RD->method_end(); MI != ME; ++MI) { 5720 if (MI->isVirtual()) { 5721 SourceLocation MLoc = MI->getLocStart(); 5722 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5723 return false; 5724 } 5725 } 5726 5727 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5728 } 5729 5730 // Looks like it's trivial! 5731 return true; 5732} 5733 5734/// \brief Data used with FindHiddenVirtualMethod 5735namespace { 5736 struct FindHiddenVirtualMethodData { 5737 Sema *S; 5738 CXXMethodDecl *Method; 5739 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5740 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5741 }; 5742} 5743 5744/// \brief Check whether any most overriden method from MD in Methods 5745static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5746 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5747 if (MD->size_overridden_methods() == 0) 5748 return Methods.count(MD->getCanonicalDecl()); 5749 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5750 E = MD->end_overridden_methods(); 5751 I != E; ++I) 5752 if (CheckMostOverridenMethods(*I, Methods)) 5753 return true; 5754 return false; 5755} 5756 5757/// \brief Member lookup function that determines whether a given C++ 5758/// method overloads virtual methods in a base class without overriding any, 5759/// to be used with CXXRecordDecl::lookupInBases(). 5760static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5761 CXXBasePath &Path, 5762 void *UserData) { 5763 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5764 5765 FindHiddenVirtualMethodData &Data 5766 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5767 5768 DeclarationName Name = Data.Method->getDeclName(); 5769 assert(Name.getNameKind() == DeclarationName::Identifier); 5770 5771 bool foundSameNameMethod = false; 5772 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5773 for (Path.Decls = BaseRecord->lookup(Name); 5774 !Path.Decls.empty(); 5775 Path.Decls = Path.Decls.slice(1)) { 5776 NamedDecl *D = Path.Decls.front(); 5777 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5778 MD = MD->getCanonicalDecl(); 5779 foundSameNameMethod = true; 5780 // Interested only in hidden virtual methods. 5781 if (!MD->isVirtual()) 5782 continue; 5783 // If the method we are checking overrides a method from its base 5784 // don't warn about the other overloaded methods. 5785 if (!Data.S->IsOverload(Data.Method, MD, false)) 5786 return true; 5787 // Collect the overload only if its hidden. 5788 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5789 overloadedMethods.push_back(MD); 5790 } 5791 } 5792 5793 if (foundSameNameMethod) 5794 Data.OverloadedMethods.append(overloadedMethods.begin(), 5795 overloadedMethods.end()); 5796 return foundSameNameMethod; 5797} 5798 5799/// \brief Add the most overriden methods from MD to Methods 5800static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5801 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5802 if (MD->size_overridden_methods() == 0) 5803 Methods.insert(MD->getCanonicalDecl()); 5804 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5805 E = MD->end_overridden_methods(); 5806 I != E; ++I) 5807 AddMostOverridenMethods(*I, Methods); 5808} 5809 5810/// \brief Check if a method overloads virtual methods in a base class without 5811/// overriding any. 5812void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 5813 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5814 if (!MD->getDeclName().isIdentifier()) 5815 return; 5816 5817 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5818 /*bool RecordPaths=*/false, 5819 /*bool DetectVirtual=*/false); 5820 FindHiddenVirtualMethodData Data; 5821 Data.Method = MD; 5822 Data.S = this; 5823 5824 // Keep the base methods that were overriden or introduced in the subclass 5825 // by 'using' in a set. A base method not in this set is hidden. 5826 CXXRecordDecl *DC = MD->getParent(); 5827 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5828 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5829 NamedDecl *ND = *I; 5830 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5831 ND = shad->getTargetDecl(); 5832 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5833 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5834 } 5835 5836 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 5837 OverloadedMethods = Data.OverloadedMethods; 5838} 5839 5840void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 5841 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5842 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 5843 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 5844 PartialDiagnostic PD = PDiag( 5845 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5846 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 5847 Diag(overloadedMD->getLocation(), PD); 5848 } 5849} 5850 5851/// \brief Diagnose methods which overload virtual methods in a base class 5852/// without overriding any. 5853void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 5854 if (MD->isInvalidDecl()) 5855 return; 5856 5857 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5858 MD->getLocation()) == DiagnosticsEngine::Ignored) 5859 return; 5860 5861 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5862 FindHiddenVirtualMethods(MD, OverloadedMethods); 5863 if (!OverloadedMethods.empty()) { 5864 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5865 << MD << (OverloadedMethods.size() > 1); 5866 5867 NoteHiddenVirtualMethods(MD, OverloadedMethods); 5868 } 5869} 5870 5871void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5872 Decl *TagDecl, 5873 SourceLocation LBrac, 5874 SourceLocation RBrac, 5875 AttributeList *AttrList) { 5876 if (!TagDecl) 5877 return; 5878 5879 AdjustDeclIfTemplate(TagDecl); 5880 5881 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5882 if (l->getKind() != AttributeList::AT_Visibility) 5883 continue; 5884 l->setInvalid(); 5885 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5886 l->getName(); 5887 } 5888 5889 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5890 // strict aliasing violation! 5891 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5892 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5893 5894 CheckCompletedCXXClass( 5895 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5896} 5897 5898/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5899/// special functions, such as the default constructor, copy 5900/// constructor, or destructor, to the given C++ class (C++ 5901/// [special]p1). This routine can only be executed just before the 5902/// definition of the class is complete. 5903void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5904 if (!ClassDecl->hasUserDeclaredConstructor()) 5905 ++ASTContext::NumImplicitDefaultConstructors; 5906 5907 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 5908 ++ASTContext::NumImplicitCopyConstructors; 5909 5910 // If the properties or semantics of the copy constructor couldn't be 5911 // determined while the class was being declared, force a declaration 5912 // of it now. 5913 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 5914 DeclareImplicitCopyConstructor(ClassDecl); 5915 } 5916 5917 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 5918 ++ASTContext::NumImplicitMoveConstructors; 5919 5920 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 5921 DeclareImplicitMoveConstructor(ClassDecl); 5922 } 5923 5924 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5925 ++ASTContext::NumImplicitCopyAssignmentOperators; 5926 5927 // If we have a dynamic class, then the copy assignment operator may be 5928 // virtual, so we have to declare it immediately. This ensures that, e.g., 5929 // it shows up in the right place in the vtable and that we diagnose 5930 // problems with the implicit exception specification. 5931 if (ClassDecl->isDynamicClass() || 5932 ClassDecl->needsOverloadResolutionForCopyAssignment()) 5933 DeclareImplicitCopyAssignment(ClassDecl); 5934 } 5935 5936 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 5937 ++ASTContext::NumImplicitMoveAssignmentOperators; 5938 5939 // Likewise for the move assignment operator. 5940 if (ClassDecl->isDynamicClass() || 5941 ClassDecl->needsOverloadResolutionForMoveAssignment()) 5942 DeclareImplicitMoveAssignment(ClassDecl); 5943 } 5944 5945 if (!ClassDecl->hasUserDeclaredDestructor()) { 5946 ++ASTContext::NumImplicitDestructors; 5947 5948 // If we have a dynamic class, then the destructor may be virtual, so we 5949 // have to declare the destructor immediately. This ensures that, e.g., it 5950 // shows up in the right place in the vtable and that we diagnose problems 5951 // with the implicit exception specification. 5952 if (ClassDecl->isDynamicClass() || 5953 ClassDecl->needsOverloadResolutionForDestructor()) 5954 DeclareImplicitDestructor(ClassDecl); 5955 } 5956} 5957 5958void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5959 if (!D) 5960 return; 5961 5962 int NumParamList = D->getNumTemplateParameterLists(); 5963 for (int i = 0; i < NumParamList; i++) { 5964 TemplateParameterList* Params = D->getTemplateParameterList(i); 5965 for (TemplateParameterList::iterator Param = Params->begin(), 5966 ParamEnd = Params->end(); 5967 Param != ParamEnd; ++Param) { 5968 NamedDecl *Named = cast<NamedDecl>(*Param); 5969 if (Named->getDeclName()) { 5970 S->AddDecl(Named); 5971 IdResolver.AddDecl(Named); 5972 } 5973 } 5974 } 5975} 5976 5977void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 5978 if (!D) 5979 return; 5980 5981 TemplateParameterList *Params = 0; 5982 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 5983 Params = Template->getTemplateParameters(); 5984 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5985 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 5986 Params = PartialSpec->getTemplateParameters(); 5987 else 5988 return; 5989 5990 for (TemplateParameterList::iterator Param = Params->begin(), 5991 ParamEnd = Params->end(); 5992 Param != ParamEnd; ++Param) { 5993 NamedDecl *Named = cast<NamedDecl>(*Param); 5994 if (Named->getDeclName()) { 5995 S->AddDecl(Named); 5996 IdResolver.AddDecl(Named); 5997 } 5998 } 5999} 6000 6001void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6002 if (!RecordD) return; 6003 AdjustDeclIfTemplate(RecordD); 6004 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6005 PushDeclContext(S, Record); 6006} 6007 6008void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6009 if (!RecordD) return; 6010 PopDeclContext(); 6011} 6012 6013/// ActOnStartDelayedCXXMethodDeclaration - We have completed 6014/// parsing a top-level (non-nested) C++ class, and we are now 6015/// parsing those parts of the given Method declaration that could 6016/// not be parsed earlier (C++ [class.mem]p2), such as default 6017/// arguments. This action should enter the scope of the given 6018/// Method declaration as if we had just parsed the qualified method 6019/// name. However, it should not bring the parameters into scope; 6020/// that will be performed by ActOnDelayedCXXMethodParameter. 6021void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6022} 6023 6024/// ActOnDelayedCXXMethodParameter - We've already started a delayed 6025/// C++ method declaration. We're (re-)introducing the given 6026/// function parameter into scope for use in parsing later parts of 6027/// the method declaration. For example, we could see an 6028/// ActOnParamDefaultArgument event for this parameter. 6029void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6030 if (!ParamD) 6031 return; 6032 6033 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6034 6035 // If this parameter has an unparsed default argument, clear it out 6036 // to make way for the parsed default argument. 6037 if (Param->hasUnparsedDefaultArg()) 6038 Param->setDefaultArg(0); 6039 6040 S->AddDecl(Param); 6041 if (Param->getDeclName()) 6042 IdResolver.AddDecl(Param); 6043} 6044 6045/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6046/// processing the delayed method declaration for Method. The method 6047/// declaration is now considered finished. There may be a separate 6048/// ActOnStartOfFunctionDef action later (not necessarily 6049/// immediately!) for this method, if it was also defined inside the 6050/// class body. 6051void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6052 if (!MethodD) 6053 return; 6054 6055 AdjustDeclIfTemplate(MethodD); 6056 6057 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6058 6059 // Now that we have our default arguments, check the constructor 6060 // again. It could produce additional diagnostics or affect whether 6061 // the class has implicitly-declared destructors, among other 6062 // things. 6063 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6064 CheckConstructor(Constructor); 6065 6066 // Check the default arguments, which we may have added. 6067 if (!Method->isInvalidDecl()) 6068 CheckCXXDefaultArguments(Method); 6069} 6070 6071/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6072/// the well-formedness of the constructor declarator @p D with type @p 6073/// R. If there are any errors in the declarator, this routine will 6074/// emit diagnostics and set the invalid bit to true. In any case, the type 6075/// will be updated to reflect a well-formed type for the constructor and 6076/// returned. 6077QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6078 StorageClass &SC) { 6079 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6080 6081 // C++ [class.ctor]p3: 6082 // A constructor shall not be virtual (10.3) or static (9.4). A 6083 // constructor can be invoked for a const, volatile or const 6084 // volatile object. A constructor shall not be declared const, 6085 // volatile, or const volatile (9.3.2). 6086 if (isVirtual) { 6087 if (!D.isInvalidType()) 6088 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6089 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6090 << SourceRange(D.getIdentifierLoc()); 6091 D.setInvalidType(); 6092 } 6093 if (SC == SC_Static) { 6094 if (!D.isInvalidType()) 6095 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6096 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6097 << SourceRange(D.getIdentifierLoc()); 6098 D.setInvalidType(); 6099 SC = SC_None; 6100 } 6101 6102 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6103 if (FTI.TypeQuals != 0) { 6104 if (FTI.TypeQuals & Qualifiers::Const) 6105 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6106 << "const" << SourceRange(D.getIdentifierLoc()); 6107 if (FTI.TypeQuals & Qualifiers::Volatile) 6108 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6109 << "volatile" << SourceRange(D.getIdentifierLoc()); 6110 if (FTI.TypeQuals & Qualifiers::Restrict) 6111 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6112 << "restrict" << SourceRange(D.getIdentifierLoc()); 6113 D.setInvalidType(); 6114 } 6115 6116 // C++0x [class.ctor]p4: 6117 // A constructor shall not be declared with a ref-qualifier. 6118 if (FTI.hasRefQualifier()) { 6119 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6120 << FTI.RefQualifierIsLValueRef 6121 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6122 D.setInvalidType(); 6123 } 6124 6125 // Rebuild the function type "R" without any type qualifiers (in 6126 // case any of the errors above fired) and with "void" as the 6127 // return type, since constructors don't have return types. 6128 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6129 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 6130 return R; 6131 6132 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6133 EPI.TypeQuals = 0; 6134 EPI.RefQualifier = RQ_None; 6135 6136 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI); 6137} 6138 6139/// CheckConstructor - Checks a fully-formed constructor for 6140/// well-formedness, issuing any diagnostics required. Returns true if 6141/// the constructor declarator is invalid. 6142void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6143 CXXRecordDecl *ClassDecl 6144 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6145 if (!ClassDecl) 6146 return Constructor->setInvalidDecl(); 6147 6148 // C++ [class.copy]p3: 6149 // A declaration of a constructor for a class X is ill-formed if 6150 // its first parameter is of type (optionally cv-qualified) X and 6151 // either there are no other parameters or else all other 6152 // parameters have default arguments. 6153 if (!Constructor->isInvalidDecl() && 6154 ((Constructor->getNumParams() == 1) || 6155 (Constructor->getNumParams() > 1 && 6156 Constructor->getParamDecl(1)->hasDefaultArg())) && 6157 Constructor->getTemplateSpecializationKind() 6158 != TSK_ImplicitInstantiation) { 6159 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6160 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6161 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6162 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6163 const char *ConstRef 6164 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6165 : " const &"; 6166 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6167 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6168 6169 // FIXME: Rather that making the constructor invalid, we should endeavor 6170 // to fix the type. 6171 Constructor->setInvalidDecl(); 6172 } 6173 } 6174} 6175 6176/// CheckDestructor - Checks a fully-formed destructor definition for 6177/// well-formedness, issuing any diagnostics required. Returns true 6178/// on error. 6179bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6180 CXXRecordDecl *RD = Destructor->getParent(); 6181 6182 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6183 SourceLocation Loc; 6184 6185 if (!Destructor->isImplicit()) 6186 Loc = Destructor->getLocation(); 6187 else 6188 Loc = RD->getLocation(); 6189 6190 // If we have a virtual destructor, look up the deallocation function 6191 FunctionDecl *OperatorDelete = 0; 6192 DeclarationName Name = 6193 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6194 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6195 return true; 6196 6197 MarkFunctionReferenced(Loc, OperatorDelete); 6198 6199 Destructor->setOperatorDelete(OperatorDelete); 6200 } 6201 6202 return false; 6203} 6204 6205static inline bool 6206FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 6207 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 6208 FTI.ArgInfo[0].Param && 6209 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 6210} 6211 6212/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6213/// the well-formednes of the destructor declarator @p D with type @p 6214/// R. If there are any errors in the declarator, this routine will 6215/// emit diagnostics and set the declarator to invalid. Even if this happens, 6216/// will be updated to reflect a well-formed type for the destructor and 6217/// returned. 6218QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6219 StorageClass& SC) { 6220 // C++ [class.dtor]p1: 6221 // [...] A typedef-name that names a class is a class-name 6222 // (7.1.3); however, a typedef-name that names a class shall not 6223 // be used as the identifier in the declarator for a destructor 6224 // declaration. 6225 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6226 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6227 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6228 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6229 else if (const TemplateSpecializationType *TST = 6230 DeclaratorType->getAs<TemplateSpecializationType>()) 6231 if (TST->isTypeAlias()) 6232 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6233 << DeclaratorType << 1; 6234 6235 // C++ [class.dtor]p2: 6236 // A destructor is used to destroy objects of its class type. A 6237 // destructor takes no parameters, and no return type can be 6238 // specified for it (not even void). The address of a destructor 6239 // shall not be taken. A destructor shall not be static. A 6240 // destructor can be invoked for a const, volatile or const 6241 // volatile object. A destructor shall not be declared const, 6242 // volatile or const volatile (9.3.2). 6243 if (SC == SC_Static) { 6244 if (!D.isInvalidType()) 6245 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6246 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6247 << SourceRange(D.getIdentifierLoc()) 6248 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6249 6250 SC = SC_None; 6251 } 6252 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6253 // Destructors don't have return types, but the parser will 6254 // happily parse something like: 6255 // 6256 // class X { 6257 // float ~X(); 6258 // }; 6259 // 6260 // The return type will be eliminated later. 6261 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6262 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6263 << SourceRange(D.getIdentifierLoc()); 6264 } 6265 6266 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6267 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6268 if (FTI.TypeQuals & Qualifiers::Const) 6269 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6270 << "const" << SourceRange(D.getIdentifierLoc()); 6271 if (FTI.TypeQuals & Qualifiers::Volatile) 6272 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6273 << "volatile" << SourceRange(D.getIdentifierLoc()); 6274 if (FTI.TypeQuals & Qualifiers::Restrict) 6275 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6276 << "restrict" << SourceRange(D.getIdentifierLoc()); 6277 D.setInvalidType(); 6278 } 6279 6280 // C++0x [class.dtor]p2: 6281 // A destructor shall not be declared with a ref-qualifier. 6282 if (FTI.hasRefQualifier()) { 6283 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6284 << FTI.RefQualifierIsLValueRef 6285 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6286 D.setInvalidType(); 6287 } 6288 6289 // Make sure we don't have any parameters. 6290 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 6291 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6292 6293 // Delete the parameters. 6294 FTI.freeArgs(); 6295 D.setInvalidType(); 6296 } 6297 6298 // Make sure the destructor isn't variadic. 6299 if (FTI.isVariadic) { 6300 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6301 D.setInvalidType(); 6302 } 6303 6304 // Rebuild the function type "R" without any type qualifiers or 6305 // parameters (in case any of the errors above fired) and with 6306 // "void" as the return type, since destructors don't have return 6307 // types. 6308 if (!D.isInvalidType()) 6309 return R; 6310 6311 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6312 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6313 EPI.Variadic = false; 6314 EPI.TypeQuals = 0; 6315 EPI.RefQualifier = RQ_None; 6316 return Context.getFunctionType(Context.VoidTy, None, EPI); 6317} 6318 6319/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6320/// well-formednes of the conversion function declarator @p D with 6321/// type @p R. If there are any errors in the declarator, this routine 6322/// will emit diagnostics and return true. Otherwise, it will return 6323/// false. Either way, the type @p R will be updated to reflect a 6324/// well-formed type for the conversion operator. 6325void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6326 StorageClass& SC) { 6327 // C++ [class.conv.fct]p1: 6328 // Neither parameter types nor return type can be specified. The 6329 // type of a conversion function (8.3.5) is "function taking no 6330 // parameter returning conversion-type-id." 6331 if (SC == SC_Static) { 6332 if (!D.isInvalidType()) 6333 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6334 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6335 << D.getName().getSourceRange(); 6336 D.setInvalidType(); 6337 SC = SC_None; 6338 } 6339 6340 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6341 6342 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6343 // Conversion functions don't have return types, but the parser will 6344 // happily parse something like: 6345 // 6346 // class X { 6347 // float operator bool(); 6348 // }; 6349 // 6350 // The return type will be changed later anyway. 6351 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6352 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6353 << SourceRange(D.getIdentifierLoc()); 6354 D.setInvalidType(); 6355 } 6356 6357 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6358 6359 // Make sure we don't have any parameters. 6360 if (Proto->getNumArgs() > 0) { 6361 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6362 6363 // Delete the parameters. 6364 D.getFunctionTypeInfo().freeArgs(); 6365 D.setInvalidType(); 6366 } else if (Proto->isVariadic()) { 6367 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6368 D.setInvalidType(); 6369 } 6370 6371 // Diagnose "&operator bool()" and other such nonsense. This 6372 // is actually a gcc extension which we don't support. 6373 if (Proto->getResultType() != ConvType) { 6374 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6375 << Proto->getResultType(); 6376 D.setInvalidType(); 6377 ConvType = Proto->getResultType(); 6378 } 6379 6380 // C++ [class.conv.fct]p4: 6381 // The conversion-type-id shall not represent a function type nor 6382 // an array type. 6383 if (ConvType->isArrayType()) { 6384 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6385 ConvType = Context.getPointerType(ConvType); 6386 D.setInvalidType(); 6387 } else if (ConvType->isFunctionType()) { 6388 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6389 ConvType = Context.getPointerType(ConvType); 6390 D.setInvalidType(); 6391 } 6392 6393 // Rebuild the function type "R" without any parameters (in case any 6394 // of the errors above fired) and with the conversion type as the 6395 // return type. 6396 if (D.isInvalidType()) 6397 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6398 6399 // C++0x explicit conversion operators. 6400 if (D.getDeclSpec().isExplicitSpecified()) 6401 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6402 getLangOpts().CPlusPlus11 ? 6403 diag::warn_cxx98_compat_explicit_conversion_functions : 6404 diag::ext_explicit_conversion_functions) 6405 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6406} 6407 6408/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6409/// the declaration of the given C++ conversion function. This routine 6410/// is responsible for recording the conversion function in the C++ 6411/// class, if possible. 6412Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6413 assert(Conversion && "Expected to receive a conversion function declaration"); 6414 6415 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6416 6417 // Make sure we aren't redeclaring the conversion function. 6418 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6419 6420 // C++ [class.conv.fct]p1: 6421 // [...] A conversion function is never used to convert a 6422 // (possibly cv-qualified) object to the (possibly cv-qualified) 6423 // same object type (or a reference to it), to a (possibly 6424 // cv-qualified) base class of that type (or a reference to it), 6425 // or to (possibly cv-qualified) void. 6426 // FIXME: Suppress this warning if the conversion function ends up being a 6427 // virtual function that overrides a virtual function in a base class. 6428 QualType ClassType 6429 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6430 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6431 ConvType = ConvTypeRef->getPointeeType(); 6432 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6433 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6434 /* Suppress diagnostics for instantiations. */; 6435 else if (ConvType->isRecordType()) { 6436 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6437 if (ConvType == ClassType) 6438 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6439 << ClassType; 6440 else if (IsDerivedFrom(ClassType, ConvType)) 6441 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6442 << ClassType << ConvType; 6443 } else if (ConvType->isVoidType()) { 6444 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6445 << ClassType << ConvType; 6446 } 6447 6448 if (FunctionTemplateDecl *ConversionTemplate 6449 = Conversion->getDescribedFunctionTemplate()) 6450 return ConversionTemplate; 6451 6452 return Conversion; 6453} 6454 6455//===----------------------------------------------------------------------===// 6456// Namespace Handling 6457//===----------------------------------------------------------------------===// 6458 6459/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6460/// reopened. 6461static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6462 SourceLocation Loc, 6463 IdentifierInfo *II, bool *IsInline, 6464 NamespaceDecl *PrevNS) { 6465 assert(*IsInline != PrevNS->isInline()); 6466 6467 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6468 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6469 // inline namespaces, with the intention of bringing names into namespace std. 6470 // 6471 // We support this just well enough to get that case working; this is not 6472 // sufficient to support reopening namespaces as inline in general. 6473 if (*IsInline && II && II->getName().startswith("__atomic") && 6474 S.getSourceManager().isInSystemHeader(Loc)) { 6475 // Mark all prior declarations of the namespace as inline. 6476 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6477 NS = NS->getPreviousDecl()) 6478 NS->setInline(*IsInline); 6479 // Patch up the lookup table for the containing namespace. This isn't really 6480 // correct, but it's good enough for this particular case. 6481 for (DeclContext::decl_iterator I = PrevNS->decls_begin(), 6482 E = PrevNS->decls_end(); I != E; ++I) 6483 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) 6484 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6485 return; 6486 } 6487 6488 if (PrevNS->isInline()) 6489 // The user probably just forgot the 'inline', so suggest that it 6490 // be added back. 6491 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6492 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6493 else 6494 S.Diag(Loc, diag::err_inline_namespace_mismatch) 6495 << IsInline; 6496 6497 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6498 *IsInline = PrevNS->isInline(); 6499} 6500 6501/// ActOnStartNamespaceDef - This is called at the start of a namespace 6502/// definition. 6503Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6504 SourceLocation InlineLoc, 6505 SourceLocation NamespaceLoc, 6506 SourceLocation IdentLoc, 6507 IdentifierInfo *II, 6508 SourceLocation LBrace, 6509 AttributeList *AttrList) { 6510 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6511 // For anonymous namespace, take the location of the left brace. 6512 SourceLocation Loc = II ? IdentLoc : LBrace; 6513 bool IsInline = InlineLoc.isValid(); 6514 bool IsInvalid = false; 6515 bool IsStd = false; 6516 bool AddToKnown = false; 6517 Scope *DeclRegionScope = NamespcScope->getParent(); 6518 6519 NamespaceDecl *PrevNS = 0; 6520 if (II) { 6521 // C++ [namespace.def]p2: 6522 // The identifier in an original-namespace-definition shall not 6523 // have been previously defined in the declarative region in 6524 // which the original-namespace-definition appears. The 6525 // identifier in an original-namespace-definition is the name of 6526 // the namespace. Subsequently in that declarative region, it is 6527 // treated as an original-namespace-name. 6528 // 6529 // Since namespace names are unique in their scope, and we don't 6530 // look through using directives, just look for any ordinary names. 6531 6532 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6533 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6534 Decl::IDNS_Namespace; 6535 NamedDecl *PrevDecl = 0; 6536 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6537 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6538 ++I) { 6539 if ((*I)->getIdentifierNamespace() & IDNS) { 6540 PrevDecl = *I; 6541 break; 6542 } 6543 } 6544 6545 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6546 6547 if (PrevNS) { 6548 // This is an extended namespace definition. 6549 if (IsInline != PrevNS->isInline()) 6550 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6551 &IsInline, PrevNS); 6552 } else if (PrevDecl) { 6553 // This is an invalid name redefinition. 6554 Diag(Loc, diag::err_redefinition_different_kind) 6555 << II; 6556 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6557 IsInvalid = true; 6558 // Continue on to push Namespc as current DeclContext and return it. 6559 } else if (II->isStr("std") && 6560 CurContext->getRedeclContext()->isTranslationUnit()) { 6561 // This is the first "real" definition of the namespace "std", so update 6562 // our cache of the "std" namespace to point at this definition. 6563 PrevNS = getStdNamespace(); 6564 IsStd = true; 6565 AddToKnown = !IsInline; 6566 } else { 6567 // We've seen this namespace for the first time. 6568 AddToKnown = !IsInline; 6569 } 6570 } else { 6571 // Anonymous namespaces. 6572 6573 // Determine whether the parent already has an anonymous namespace. 6574 DeclContext *Parent = CurContext->getRedeclContext(); 6575 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6576 PrevNS = TU->getAnonymousNamespace(); 6577 } else { 6578 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6579 PrevNS = ND->getAnonymousNamespace(); 6580 } 6581 6582 if (PrevNS && IsInline != PrevNS->isInline()) 6583 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6584 &IsInline, PrevNS); 6585 } 6586 6587 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6588 StartLoc, Loc, II, PrevNS); 6589 if (IsInvalid) 6590 Namespc->setInvalidDecl(); 6591 6592 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6593 6594 // FIXME: Should we be merging attributes? 6595 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6596 PushNamespaceVisibilityAttr(Attr, Loc); 6597 6598 if (IsStd) 6599 StdNamespace = Namespc; 6600 if (AddToKnown) 6601 KnownNamespaces[Namespc] = false; 6602 6603 if (II) { 6604 PushOnScopeChains(Namespc, DeclRegionScope); 6605 } else { 6606 // Link the anonymous namespace into its parent. 6607 DeclContext *Parent = CurContext->getRedeclContext(); 6608 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6609 TU->setAnonymousNamespace(Namespc); 6610 } else { 6611 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6612 } 6613 6614 CurContext->addDecl(Namespc); 6615 6616 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6617 // behaves as if it were replaced by 6618 // namespace unique { /* empty body */ } 6619 // using namespace unique; 6620 // namespace unique { namespace-body } 6621 // where all occurrences of 'unique' in a translation unit are 6622 // replaced by the same identifier and this identifier differs 6623 // from all other identifiers in the entire program. 6624 6625 // We just create the namespace with an empty name and then add an 6626 // implicit using declaration, just like the standard suggests. 6627 // 6628 // CodeGen enforces the "universally unique" aspect by giving all 6629 // declarations semantically contained within an anonymous 6630 // namespace internal linkage. 6631 6632 if (!PrevNS) { 6633 UsingDirectiveDecl* UD 6634 = UsingDirectiveDecl::Create(Context, Parent, 6635 /* 'using' */ LBrace, 6636 /* 'namespace' */ SourceLocation(), 6637 /* qualifier */ NestedNameSpecifierLoc(), 6638 /* identifier */ SourceLocation(), 6639 Namespc, 6640 /* Ancestor */ Parent); 6641 UD->setImplicit(); 6642 Parent->addDecl(UD); 6643 } 6644 } 6645 6646 ActOnDocumentableDecl(Namespc); 6647 6648 // Although we could have an invalid decl (i.e. the namespace name is a 6649 // redefinition), push it as current DeclContext and try to continue parsing. 6650 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6651 // for the namespace has the declarations that showed up in that particular 6652 // namespace definition. 6653 PushDeclContext(NamespcScope, Namespc); 6654 return Namespc; 6655} 6656 6657/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6658/// is a namespace alias, returns the namespace it points to. 6659static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6660 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6661 return AD->getNamespace(); 6662 return dyn_cast_or_null<NamespaceDecl>(D); 6663} 6664 6665/// ActOnFinishNamespaceDef - This callback is called after a namespace is 6666/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6667void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6668 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6669 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6670 Namespc->setRBraceLoc(RBrace); 6671 PopDeclContext(); 6672 if (Namespc->hasAttr<VisibilityAttr>()) 6673 PopPragmaVisibility(true, RBrace); 6674} 6675 6676CXXRecordDecl *Sema::getStdBadAlloc() const { 6677 return cast_or_null<CXXRecordDecl>( 6678 StdBadAlloc.get(Context.getExternalSource())); 6679} 6680 6681NamespaceDecl *Sema::getStdNamespace() const { 6682 return cast_or_null<NamespaceDecl>( 6683 StdNamespace.get(Context.getExternalSource())); 6684} 6685 6686/// \brief Retrieve the special "std" namespace, which may require us to 6687/// implicitly define the namespace. 6688NamespaceDecl *Sema::getOrCreateStdNamespace() { 6689 if (!StdNamespace) { 6690 // The "std" namespace has not yet been defined, so build one implicitly. 6691 StdNamespace = NamespaceDecl::Create(Context, 6692 Context.getTranslationUnitDecl(), 6693 /*Inline=*/false, 6694 SourceLocation(), SourceLocation(), 6695 &PP.getIdentifierTable().get("std"), 6696 /*PrevDecl=*/0); 6697 getStdNamespace()->setImplicit(true); 6698 } 6699 6700 return getStdNamespace(); 6701} 6702 6703bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6704 assert(getLangOpts().CPlusPlus && 6705 "Looking for std::initializer_list outside of C++."); 6706 6707 // We're looking for implicit instantiations of 6708 // template <typename E> class std::initializer_list. 6709 6710 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6711 return false; 6712 6713 ClassTemplateDecl *Template = 0; 6714 const TemplateArgument *Arguments = 0; 6715 6716 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6717 6718 ClassTemplateSpecializationDecl *Specialization = 6719 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6720 if (!Specialization) 6721 return false; 6722 6723 Template = Specialization->getSpecializedTemplate(); 6724 Arguments = Specialization->getTemplateArgs().data(); 6725 } else if (const TemplateSpecializationType *TST = 6726 Ty->getAs<TemplateSpecializationType>()) { 6727 Template = dyn_cast_or_null<ClassTemplateDecl>( 6728 TST->getTemplateName().getAsTemplateDecl()); 6729 Arguments = TST->getArgs(); 6730 } 6731 if (!Template) 6732 return false; 6733 6734 if (!StdInitializerList) { 6735 // Haven't recognized std::initializer_list yet, maybe this is it. 6736 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6737 if (TemplateClass->getIdentifier() != 6738 &PP.getIdentifierTable().get("initializer_list") || 6739 !getStdNamespace()->InEnclosingNamespaceSetOf( 6740 TemplateClass->getDeclContext())) 6741 return false; 6742 // This is a template called std::initializer_list, but is it the right 6743 // template? 6744 TemplateParameterList *Params = Template->getTemplateParameters(); 6745 if (Params->getMinRequiredArguments() != 1) 6746 return false; 6747 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6748 return false; 6749 6750 // It's the right template. 6751 StdInitializerList = Template; 6752 } 6753 6754 if (Template != StdInitializerList) 6755 return false; 6756 6757 // This is an instance of std::initializer_list. Find the argument type. 6758 if (Element) 6759 *Element = Arguments[0].getAsType(); 6760 return true; 6761} 6762 6763static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6764 NamespaceDecl *Std = S.getStdNamespace(); 6765 if (!Std) { 6766 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6767 return 0; 6768 } 6769 6770 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6771 Loc, Sema::LookupOrdinaryName); 6772 if (!S.LookupQualifiedName(Result, Std)) { 6773 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6774 return 0; 6775 } 6776 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6777 if (!Template) { 6778 Result.suppressDiagnostics(); 6779 // We found something weird. Complain about the first thing we found. 6780 NamedDecl *Found = *Result.begin(); 6781 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6782 return 0; 6783 } 6784 6785 // We found some template called std::initializer_list. Now verify that it's 6786 // correct. 6787 TemplateParameterList *Params = Template->getTemplateParameters(); 6788 if (Params->getMinRequiredArguments() != 1 || 6789 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6790 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6791 return 0; 6792 } 6793 6794 return Template; 6795} 6796 6797QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6798 if (!StdInitializerList) { 6799 StdInitializerList = LookupStdInitializerList(*this, Loc); 6800 if (!StdInitializerList) 6801 return QualType(); 6802 } 6803 6804 TemplateArgumentListInfo Args(Loc, Loc); 6805 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6806 Context.getTrivialTypeSourceInfo(Element, 6807 Loc))); 6808 return Context.getCanonicalType( 6809 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6810} 6811 6812bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6813 // C++ [dcl.init.list]p2: 6814 // A constructor is an initializer-list constructor if its first parameter 6815 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6816 // std::initializer_list<E> for some type E, and either there are no other 6817 // parameters or else all other parameters have default arguments. 6818 if (Ctor->getNumParams() < 1 || 6819 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6820 return false; 6821 6822 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6823 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6824 ArgType = RT->getPointeeType().getUnqualifiedType(); 6825 6826 return isStdInitializerList(ArgType, 0); 6827} 6828 6829/// \brief Determine whether a using statement is in a context where it will be 6830/// apply in all contexts. 6831static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6832 switch (CurContext->getDeclKind()) { 6833 case Decl::TranslationUnit: 6834 return true; 6835 case Decl::LinkageSpec: 6836 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6837 default: 6838 return false; 6839 } 6840} 6841 6842namespace { 6843 6844// Callback to only accept typo corrections that are namespaces. 6845class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6846public: 6847 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE { 6848 if (NamedDecl *ND = candidate.getCorrectionDecl()) 6849 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6850 return false; 6851 } 6852}; 6853 6854} 6855 6856static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6857 CXXScopeSpec &SS, 6858 SourceLocation IdentLoc, 6859 IdentifierInfo *Ident) { 6860 NamespaceValidatorCCC Validator; 6861 R.clear(); 6862 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6863 R.getLookupKind(), Sc, &SS, 6864 Validator)) { 6865 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 6866 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6867 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 6868 Ident->getName().equals(CorrectedStr); 6869 S.diagnoseTypo(Corrected, 6870 S.PDiag(diag::err_using_directive_member_suggest) 6871 << Ident << DC << DroppedSpecifier << SS.getRange(), 6872 S.PDiag(diag::note_namespace_defined_here)); 6873 } else { 6874 S.diagnoseTypo(Corrected, 6875 S.PDiag(diag::err_using_directive_suggest) << Ident, 6876 S.PDiag(diag::note_namespace_defined_here)); 6877 } 6878 R.addDecl(Corrected.getCorrectionDecl()); 6879 return true; 6880 } 6881 return false; 6882} 6883 6884Decl *Sema::ActOnUsingDirective(Scope *S, 6885 SourceLocation UsingLoc, 6886 SourceLocation NamespcLoc, 6887 CXXScopeSpec &SS, 6888 SourceLocation IdentLoc, 6889 IdentifierInfo *NamespcName, 6890 AttributeList *AttrList) { 6891 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6892 assert(NamespcName && "Invalid NamespcName."); 6893 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6894 6895 // This can only happen along a recovery path. 6896 while (S->getFlags() & Scope::TemplateParamScope) 6897 S = S->getParent(); 6898 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6899 6900 UsingDirectiveDecl *UDir = 0; 6901 NestedNameSpecifier *Qualifier = 0; 6902 if (SS.isSet()) 6903 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6904 6905 // Lookup namespace name. 6906 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6907 LookupParsedName(R, S, &SS); 6908 if (R.isAmbiguous()) 6909 return 0; 6910 6911 if (R.empty()) { 6912 R.clear(); 6913 // Allow "using namespace std;" or "using namespace ::std;" even if 6914 // "std" hasn't been defined yet, for GCC compatibility. 6915 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6916 NamespcName->isStr("std")) { 6917 Diag(IdentLoc, diag::ext_using_undefined_std); 6918 R.addDecl(getOrCreateStdNamespace()); 6919 R.resolveKind(); 6920 } 6921 // Otherwise, attempt typo correction. 6922 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6923 } 6924 6925 if (!R.empty()) { 6926 NamedDecl *Named = R.getFoundDecl(); 6927 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6928 && "expected namespace decl"); 6929 // C++ [namespace.udir]p1: 6930 // A using-directive specifies that the names in the nominated 6931 // namespace can be used in the scope in which the 6932 // using-directive appears after the using-directive. During 6933 // unqualified name lookup (3.4.1), the names appear as if they 6934 // were declared in the nearest enclosing namespace which 6935 // contains both the using-directive and the nominated 6936 // namespace. [Note: in this context, "contains" means "contains 6937 // directly or indirectly". ] 6938 6939 // Find enclosing context containing both using-directive and 6940 // nominated namespace. 6941 NamespaceDecl *NS = getNamespaceDecl(Named); 6942 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6943 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6944 CommonAncestor = CommonAncestor->getParent(); 6945 6946 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6947 SS.getWithLocInContext(Context), 6948 IdentLoc, Named, CommonAncestor); 6949 6950 if (IsUsingDirectiveInToplevelContext(CurContext) && 6951 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6952 Diag(IdentLoc, diag::warn_using_directive_in_header); 6953 } 6954 6955 PushUsingDirective(S, UDir); 6956 } else { 6957 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6958 } 6959 6960 if (UDir) 6961 ProcessDeclAttributeList(S, UDir, AttrList); 6962 6963 return UDir; 6964} 6965 6966void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 6967 // If the scope has an associated entity and the using directive is at 6968 // namespace or translation unit scope, add the UsingDirectiveDecl into 6969 // its lookup structure so qualified name lookup can find it. 6970 DeclContext *Ctx = S->getEntity(); 6971 if (Ctx && !Ctx->isFunctionOrMethod()) 6972 Ctx->addDecl(UDir); 6973 else 6974 // Otherwise, it is at block sope. The using-directives will affect lookup 6975 // only to the end of the scope. 6976 S->PushUsingDirective(UDir); 6977} 6978 6979 6980Decl *Sema::ActOnUsingDeclaration(Scope *S, 6981 AccessSpecifier AS, 6982 bool HasUsingKeyword, 6983 SourceLocation UsingLoc, 6984 CXXScopeSpec &SS, 6985 UnqualifiedId &Name, 6986 AttributeList *AttrList, 6987 bool HasTypenameKeyword, 6988 SourceLocation TypenameLoc) { 6989 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6990 6991 switch (Name.getKind()) { 6992 case UnqualifiedId::IK_ImplicitSelfParam: 6993 case UnqualifiedId::IK_Identifier: 6994 case UnqualifiedId::IK_OperatorFunctionId: 6995 case UnqualifiedId::IK_LiteralOperatorId: 6996 case UnqualifiedId::IK_ConversionFunctionId: 6997 break; 6998 6999 case UnqualifiedId::IK_ConstructorName: 7000 case UnqualifiedId::IK_ConstructorTemplateId: 7001 // C++11 inheriting constructors. 7002 Diag(Name.getLocStart(), 7003 getLangOpts().CPlusPlus11 ? 7004 diag::warn_cxx98_compat_using_decl_constructor : 7005 diag::err_using_decl_constructor) 7006 << SS.getRange(); 7007 7008 if (getLangOpts().CPlusPlus11) break; 7009 7010 return 0; 7011 7012 case UnqualifiedId::IK_DestructorName: 7013 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7014 << SS.getRange(); 7015 return 0; 7016 7017 case UnqualifiedId::IK_TemplateId: 7018 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7019 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7020 return 0; 7021 } 7022 7023 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7024 DeclarationName TargetName = TargetNameInfo.getName(); 7025 if (!TargetName) 7026 return 0; 7027 7028 // Warn about access declarations. 7029 if (!HasUsingKeyword) { 7030 Diag(Name.getLocStart(), 7031 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7032 : diag::warn_access_decl_deprecated) 7033 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7034 } 7035 7036 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7037 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7038 return 0; 7039 7040 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7041 TargetNameInfo, AttrList, 7042 /* IsInstantiation */ false, 7043 HasTypenameKeyword, TypenameLoc); 7044 if (UD) 7045 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7046 7047 return UD; 7048} 7049 7050/// \brief Determine whether a using declaration considers the given 7051/// declarations as "equivalent", e.g., if they are redeclarations of 7052/// the same entity or are both typedefs of the same type. 7053static bool 7054IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 7055 bool &SuppressRedeclaration) { 7056 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 7057 SuppressRedeclaration = false; 7058 return true; 7059 } 7060 7061 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7062 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 7063 SuppressRedeclaration = true; 7064 return Context.hasSameType(TD1->getUnderlyingType(), 7065 TD2->getUnderlyingType()); 7066 } 7067 7068 return false; 7069} 7070 7071 7072/// Determines whether to create a using shadow decl for a particular 7073/// decl, given the set of decls existing prior to this using lookup. 7074bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7075 const LookupResult &Previous) { 7076 // Diagnose finding a decl which is not from a base class of the 7077 // current class. We do this now because there are cases where this 7078 // function will silently decide not to build a shadow decl, which 7079 // will pre-empt further diagnostics. 7080 // 7081 // We don't need to do this in C++0x because we do the check once on 7082 // the qualifier. 7083 // 7084 // FIXME: diagnose the following if we care enough: 7085 // struct A { int foo; }; 7086 // struct B : A { using A::foo; }; 7087 // template <class T> struct C : A {}; 7088 // template <class T> struct D : C<T> { using B::foo; } // <--- 7089 // This is invalid (during instantiation) in C++03 because B::foo 7090 // resolves to the using decl in B, which is not a base class of D<T>. 7091 // We can't diagnose it immediately because C<T> is an unknown 7092 // specialization. The UsingShadowDecl in D<T> then points directly 7093 // to A::foo, which will look well-formed when we instantiate. 7094 // The right solution is to not collapse the shadow-decl chain. 7095 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7096 DeclContext *OrigDC = Orig->getDeclContext(); 7097 7098 // Handle enums and anonymous structs. 7099 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7100 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7101 while (OrigRec->isAnonymousStructOrUnion()) 7102 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7103 7104 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7105 if (OrigDC == CurContext) { 7106 Diag(Using->getLocation(), 7107 diag::err_using_decl_nested_name_specifier_is_current_class) 7108 << Using->getQualifierLoc().getSourceRange(); 7109 Diag(Orig->getLocation(), diag::note_using_decl_target); 7110 return true; 7111 } 7112 7113 Diag(Using->getQualifierLoc().getBeginLoc(), 7114 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7115 << Using->getQualifier() 7116 << cast<CXXRecordDecl>(CurContext) 7117 << Using->getQualifierLoc().getSourceRange(); 7118 Diag(Orig->getLocation(), diag::note_using_decl_target); 7119 return true; 7120 } 7121 } 7122 7123 if (Previous.empty()) return false; 7124 7125 NamedDecl *Target = Orig; 7126 if (isa<UsingShadowDecl>(Target)) 7127 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7128 7129 // If the target happens to be one of the previous declarations, we 7130 // don't have a conflict. 7131 // 7132 // FIXME: but we might be increasing its access, in which case we 7133 // should redeclare it. 7134 NamedDecl *NonTag = 0, *Tag = 0; 7135 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7136 I != E; ++I) { 7137 NamedDecl *D = (*I)->getUnderlyingDecl(); 7138 bool Result; 7139 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 7140 return Result; 7141 7142 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7143 } 7144 7145 if (Target->isFunctionOrFunctionTemplate()) { 7146 FunctionDecl *FD; 7147 if (isa<FunctionTemplateDecl>(Target)) 7148 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 7149 else 7150 FD = cast<FunctionDecl>(Target); 7151 7152 NamedDecl *OldDecl = 0; 7153 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 7154 case Ovl_Overload: 7155 return false; 7156 7157 case Ovl_NonFunction: 7158 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7159 break; 7160 7161 // We found a decl with the exact signature. 7162 case Ovl_Match: 7163 // If we're in a record, we want to hide the target, so we 7164 // return true (without a diagnostic) to tell the caller not to 7165 // build a shadow decl. 7166 if (CurContext->isRecord()) 7167 return true; 7168 7169 // If we're not in a record, this is an error. 7170 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7171 break; 7172 } 7173 7174 Diag(Target->getLocation(), diag::note_using_decl_target); 7175 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7176 return true; 7177 } 7178 7179 // Target is not a function. 7180 7181 if (isa<TagDecl>(Target)) { 7182 // No conflict between a tag and a non-tag. 7183 if (!Tag) return false; 7184 7185 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7186 Diag(Target->getLocation(), diag::note_using_decl_target); 7187 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7188 return true; 7189 } 7190 7191 // No conflict between a tag and a non-tag. 7192 if (!NonTag) return false; 7193 7194 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7195 Diag(Target->getLocation(), diag::note_using_decl_target); 7196 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7197 return true; 7198} 7199 7200/// Builds a shadow declaration corresponding to a 'using' declaration. 7201UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7202 UsingDecl *UD, 7203 NamedDecl *Orig) { 7204 7205 // If we resolved to another shadow declaration, just coalesce them. 7206 NamedDecl *Target = Orig; 7207 if (isa<UsingShadowDecl>(Target)) { 7208 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7209 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7210 } 7211 7212 UsingShadowDecl *Shadow 7213 = UsingShadowDecl::Create(Context, CurContext, 7214 UD->getLocation(), UD, Target); 7215 UD->addShadowDecl(Shadow); 7216 7217 Shadow->setAccess(UD->getAccess()); 7218 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7219 Shadow->setInvalidDecl(); 7220 7221 if (S) 7222 PushOnScopeChains(Shadow, S); 7223 else 7224 CurContext->addDecl(Shadow); 7225 7226 7227 return Shadow; 7228} 7229 7230/// Hides a using shadow declaration. This is required by the current 7231/// using-decl implementation when a resolvable using declaration in a 7232/// class is followed by a declaration which would hide or override 7233/// one or more of the using decl's targets; for example: 7234/// 7235/// struct Base { void foo(int); }; 7236/// struct Derived : Base { 7237/// using Base::foo; 7238/// void foo(int); 7239/// }; 7240/// 7241/// The governing language is C++03 [namespace.udecl]p12: 7242/// 7243/// When a using-declaration brings names from a base class into a 7244/// derived class scope, member functions in the derived class 7245/// override and/or hide member functions with the same name and 7246/// parameter types in a base class (rather than conflicting). 7247/// 7248/// There are two ways to implement this: 7249/// (1) optimistically create shadow decls when they're not hidden 7250/// by existing declarations, or 7251/// (2) don't create any shadow decls (or at least don't make them 7252/// visible) until we've fully parsed/instantiated the class. 7253/// The problem with (1) is that we might have to retroactively remove 7254/// a shadow decl, which requires several O(n) operations because the 7255/// decl structures are (very reasonably) not designed for removal. 7256/// (2) avoids this but is very fiddly and phase-dependent. 7257void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7258 if (Shadow->getDeclName().getNameKind() == 7259 DeclarationName::CXXConversionFunctionName) 7260 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7261 7262 // Remove it from the DeclContext... 7263 Shadow->getDeclContext()->removeDecl(Shadow); 7264 7265 // ...and the scope, if applicable... 7266 if (S) { 7267 S->RemoveDecl(Shadow); 7268 IdResolver.RemoveDecl(Shadow); 7269 } 7270 7271 // ...and the using decl. 7272 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7273 7274 // TODO: complain somehow if Shadow was used. It shouldn't 7275 // be possible for this to happen, because...? 7276} 7277 7278namespace { 7279class UsingValidatorCCC : public CorrectionCandidateCallback { 7280public: 7281 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation) 7282 : HasTypenameKeyword(HasTypenameKeyword), 7283 IsInstantiation(IsInstantiation) {} 7284 7285 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE { 7286 NamedDecl *ND = Candidate.getCorrectionDecl(); 7287 7288 // Keywords are not valid here. 7289 if (!ND || isa<NamespaceDecl>(ND)) 7290 return false; 7291 7292 // Completely unqualified names are invalid for a 'using' declaration. 7293 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7294 return false; 7295 7296 if (isa<TypeDecl>(ND)) 7297 return HasTypenameKeyword || !IsInstantiation; 7298 7299 return !HasTypenameKeyword; 7300 } 7301 7302private: 7303 bool HasTypenameKeyword; 7304 bool IsInstantiation; 7305}; 7306} // end anonymous namespace 7307 7308/// Builds a using declaration. 7309/// 7310/// \param IsInstantiation - Whether this call arises from an 7311/// instantiation of an unresolved using declaration. We treat 7312/// the lookup differently for these declarations. 7313NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7314 SourceLocation UsingLoc, 7315 CXXScopeSpec &SS, 7316 const DeclarationNameInfo &NameInfo, 7317 AttributeList *AttrList, 7318 bool IsInstantiation, 7319 bool HasTypenameKeyword, 7320 SourceLocation TypenameLoc) { 7321 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7322 SourceLocation IdentLoc = NameInfo.getLoc(); 7323 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7324 7325 // FIXME: We ignore attributes for now. 7326 7327 if (SS.isEmpty()) { 7328 Diag(IdentLoc, diag::err_using_requires_qualname); 7329 return 0; 7330 } 7331 7332 // Do the redeclaration lookup in the current scope. 7333 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7334 ForRedeclaration); 7335 Previous.setHideTags(false); 7336 if (S) { 7337 LookupName(Previous, S); 7338 7339 // It is really dumb that we have to do this. 7340 LookupResult::Filter F = Previous.makeFilter(); 7341 while (F.hasNext()) { 7342 NamedDecl *D = F.next(); 7343 if (!isDeclInScope(D, CurContext, S)) 7344 F.erase(); 7345 } 7346 F.done(); 7347 } else { 7348 assert(IsInstantiation && "no scope in non-instantiation"); 7349 assert(CurContext->isRecord() && "scope not record in instantiation"); 7350 LookupQualifiedName(Previous, CurContext); 7351 } 7352 7353 // Check for invalid redeclarations. 7354 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7355 SS, IdentLoc, Previous)) 7356 return 0; 7357 7358 // Check for bad qualifiers. 7359 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 7360 return 0; 7361 7362 DeclContext *LookupContext = computeDeclContext(SS); 7363 NamedDecl *D; 7364 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7365 if (!LookupContext) { 7366 if (HasTypenameKeyword) { 7367 // FIXME: not all declaration name kinds are legal here 7368 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7369 UsingLoc, TypenameLoc, 7370 QualifierLoc, 7371 IdentLoc, NameInfo.getName()); 7372 } else { 7373 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7374 QualifierLoc, NameInfo); 7375 } 7376 } else { 7377 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 7378 NameInfo, HasTypenameKeyword); 7379 } 7380 D->setAccess(AS); 7381 CurContext->addDecl(D); 7382 7383 if (!LookupContext) return D; 7384 UsingDecl *UD = cast<UsingDecl>(D); 7385 7386 if (RequireCompleteDeclContext(SS, LookupContext)) { 7387 UD->setInvalidDecl(); 7388 return UD; 7389 } 7390 7391 // The normal rules do not apply to inheriting constructor declarations. 7392 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7393 if (CheckInheritingConstructorUsingDecl(UD)) 7394 UD->setInvalidDecl(); 7395 return UD; 7396 } 7397 7398 // Otherwise, look up the target name. 7399 7400 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7401 7402 // Unlike most lookups, we don't always want to hide tag 7403 // declarations: tag names are visible through the using declaration 7404 // even if hidden by ordinary names, *except* in a dependent context 7405 // where it's important for the sanity of two-phase lookup. 7406 if (!IsInstantiation) 7407 R.setHideTags(false); 7408 7409 // For the purposes of this lookup, we have a base object type 7410 // equal to that of the current context. 7411 if (CurContext->isRecord()) { 7412 R.setBaseObjectType( 7413 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7414 } 7415 7416 LookupQualifiedName(R, LookupContext); 7417 7418 // Try to correct typos if possible. 7419 if (R.empty()) { 7420 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation); 7421 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(), 7422 R.getLookupKind(), S, &SS, CCC)){ 7423 // We reject any correction for which ND would be NULL. 7424 NamedDecl *ND = Corrected.getCorrectionDecl(); 7425 R.setLookupName(Corrected.getCorrection()); 7426 R.addDecl(ND); 7427 // We reject candidates where DroppedSpecifier == true, hence the 7428 // literal '0' below. 7429 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 7430 << NameInfo.getName() << LookupContext << 0 7431 << SS.getRange()); 7432 } else { 7433 Diag(IdentLoc, diag::err_no_member) 7434 << NameInfo.getName() << LookupContext << SS.getRange(); 7435 UD->setInvalidDecl(); 7436 return UD; 7437 } 7438 } 7439 7440 if (R.isAmbiguous()) { 7441 UD->setInvalidDecl(); 7442 return UD; 7443 } 7444 7445 if (HasTypenameKeyword) { 7446 // If we asked for a typename and got a non-type decl, error out. 7447 if (!R.getAsSingle<TypeDecl>()) { 7448 Diag(IdentLoc, diag::err_using_typename_non_type); 7449 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7450 Diag((*I)->getUnderlyingDecl()->getLocation(), 7451 diag::note_using_decl_target); 7452 UD->setInvalidDecl(); 7453 return UD; 7454 } 7455 } else { 7456 // If we asked for a non-typename and we got a type, error out, 7457 // but only if this is an instantiation of an unresolved using 7458 // decl. Otherwise just silently find the type name. 7459 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7460 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7461 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7462 UD->setInvalidDecl(); 7463 return UD; 7464 } 7465 } 7466 7467 // C++0x N2914 [namespace.udecl]p6: 7468 // A using-declaration shall not name a namespace. 7469 if (R.getAsSingle<NamespaceDecl>()) { 7470 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7471 << SS.getRange(); 7472 UD->setInvalidDecl(); 7473 return UD; 7474 } 7475 7476 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7477 if (!CheckUsingShadowDecl(UD, *I, Previous)) 7478 BuildUsingShadowDecl(S, UD, *I); 7479 } 7480 7481 return UD; 7482} 7483 7484/// Additional checks for a using declaration referring to a constructor name. 7485bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7486 assert(!UD->hasTypename() && "expecting a constructor name"); 7487 7488 const Type *SourceType = UD->getQualifier()->getAsType(); 7489 assert(SourceType && 7490 "Using decl naming constructor doesn't have type in scope spec."); 7491 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7492 7493 // Check whether the named type is a direct base class. 7494 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 7495 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 7496 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 7497 BaseIt != BaseE; ++BaseIt) { 7498 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 7499 if (CanonicalSourceType == BaseType) 7500 break; 7501 if (BaseIt->getType()->isDependentType()) 7502 break; 7503 } 7504 7505 if (BaseIt == BaseE) { 7506 // Did not find SourceType in the bases. 7507 Diag(UD->getUsingLoc(), 7508 diag::err_using_decl_constructor_not_in_direct_base) 7509 << UD->getNameInfo().getSourceRange() 7510 << QualType(SourceType, 0) << TargetClass; 7511 return true; 7512 } 7513 7514 if (!CurContext->isDependentContext()) 7515 BaseIt->setInheritConstructors(); 7516 7517 return false; 7518} 7519 7520/// Checks that the given using declaration is not an invalid 7521/// redeclaration. Note that this is checking only for the using decl 7522/// itself, not for any ill-formedness among the UsingShadowDecls. 7523bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7524 bool HasTypenameKeyword, 7525 const CXXScopeSpec &SS, 7526 SourceLocation NameLoc, 7527 const LookupResult &Prev) { 7528 // C++03 [namespace.udecl]p8: 7529 // C++0x [namespace.udecl]p10: 7530 // A using-declaration is a declaration and can therefore be used 7531 // repeatedly where (and only where) multiple declarations are 7532 // allowed. 7533 // 7534 // That's in non-member contexts. 7535 if (!CurContext->getRedeclContext()->isRecord()) 7536 return false; 7537 7538 NestedNameSpecifier *Qual 7539 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 7540 7541 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7542 NamedDecl *D = *I; 7543 7544 bool DTypename; 7545 NestedNameSpecifier *DQual; 7546 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7547 DTypename = UD->hasTypename(); 7548 DQual = UD->getQualifier(); 7549 } else if (UnresolvedUsingValueDecl *UD 7550 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7551 DTypename = false; 7552 DQual = UD->getQualifier(); 7553 } else if (UnresolvedUsingTypenameDecl *UD 7554 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7555 DTypename = true; 7556 DQual = UD->getQualifier(); 7557 } else continue; 7558 7559 // using decls differ if one says 'typename' and the other doesn't. 7560 // FIXME: non-dependent using decls? 7561 if (HasTypenameKeyword != DTypename) continue; 7562 7563 // using decls differ if they name different scopes (but note that 7564 // template instantiation can cause this check to trigger when it 7565 // didn't before instantiation). 7566 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7567 Context.getCanonicalNestedNameSpecifier(DQual)) 7568 continue; 7569 7570 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7571 Diag(D->getLocation(), diag::note_using_decl) << 1; 7572 return true; 7573 } 7574 7575 return false; 7576} 7577 7578 7579/// Checks that the given nested-name qualifier used in a using decl 7580/// in the current context is appropriately related to the current 7581/// scope. If an error is found, diagnoses it and returns true. 7582bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7583 const CXXScopeSpec &SS, 7584 SourceLocation NameLoc) { 7585 DeclContext *NamedContext = computeDeclContext(SS); 7586 7587 if (!CurContext->isRecord()) { 7588 // C++03 [namespace.udecl]p3: 7589 // C++0x [namespace.udecl]p8: 7590 // A using-declaration for a class member shall be a member-declaration. 7591 7592 // If we weren't able to compute a valid scope, it must be a 7593 // dependent class scope. 7594 if (!NamedContext || NamedContext->isRecord()) { 7595 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7596 << SS.getRange(); 7597 return true; 7598 } 7599 7600 // Otherwise, everything is known to be fine. 7601 return false; 7602 } 7603 7604 // The current scope is a record. 7605 7606 // If the named context is dependent, we can't decide much. 7607 if (!NamedContext) { 7608 // FIXME: in C++0x, we can diagnose if we can prove that the 7609 // nested-name-specifier does not refer to a base class, which is 7610 // still possible in some cases. 7611 7612 // Otherwise we have to conservatively report that things might be 7613 // okay. 7614 return false; 7615 } 7616 7617 if (!NamedContext->isRecord()) { 7618 // Ideally this would point at the last name in the specifier, 7619 // but we don't have that level of source info. 7620 Diag(SS.getRange().getBegin(), 7621 diag::err_using_decl_nested_name_specifier_is_not_class) 7622 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 7623 return true; 7624 } 7625 7626 if (!NamedContext->isDependentContext() && 7627 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7628 return true; 7629 7630 if (getLangOpts().CPlusPlus11) { 7631 // C++0x [namespace.udecl]p3: 7632 // In a using-declaration used as a member-declaration, the 7633 // nested-name-specifier shall name a base class of the class 7634 // being defined. 7635 7636 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7637 cast<CXXRecordDecl>(NamedContext))) { 7638 if (CurContext == NamedContext) { 7639 Diag(NameLoc, 7640 diag::err_using_decl_nested_name_specifier_is_current_class) 7641 << SS.getRange(); 7642 return true; 7643 } 7644 7645 Diag(SS.getRange().getBegin(), 7646 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7647 << (NestedNameSpecifier*) SS.getScopeRep() 7648 << cast<CXXRecordDecl>(CurContext) 7649 << SS.getRange(); 7650 return true; 7651 } 7652 7653 return false; 7654 } 7655 7656 // C++03 [namespace.udecl]p4: 7657 // A using-declaration used as a member-declaration shall refer 7658 // to a member of a base class of the class being defined [etc.]. 7659 7660 // Salient point: SS doesn't have to name a base class as long as 7661 // lookup only finds members from base classes. Therefore we can 7662 // diagnose here only if we can prove that that can't happen, 7663 // i.e. if the class hierarchies provably don't intersect. 7664 7665 // TODO: it would be nice if "definitely valid" results were cached 7666 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7667 // need to be repeated. 7668 7669 struct UserData { 7670 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7671 7672 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7673 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7674 Data->Bases.insert(Base); 7675 return true; 7676 } 7677 7678 bool hasDependentBases(const CXXRecordDecl *Class) { 7679 return !Class->forallBases(collect, this); 7680 } 7681 7682 /// Returns true if the base is dependent or is one of the 7683 /// accumulated base classes. 7684 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7685 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7686 return !Data->Bases.count(Base); 7687 } 7688 7689 bool mightShareBases(const CXXRecordDecl *Class) { 7690 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7691 } 7692 }; 7693 7694 UserData Data; 7695 7696 // Returns false if we find a dependent base. 7697 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7698 return false; 7699 7700 // Returns false if the class has a dependent base or if it or one 7701 // of its bases is present in the base set of the current context. 7702 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7703 return false; 7704 7705 Diag(SS.getRange().getBegin(), 7706 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7707 << (NestedNameSpecifier*) SS.getScopeRep() 7708 << cast<CXXRecordDecl>(CurContext) 7709 << SS.getRange(); 7710 7711 return true; 7712} 7713 7714Decl *Sema::ActOnAliasDeclaration(Scope *S, 7715 AccessSpecifier AS, 7716 MultiTemplateParamsArg TemplateParamLists, 7717 SourceLocation UsingLoc, 7718 UnqualifiedId &Name, 7719 AttributeList *AttrList, 7720 TypeResult Type) { 7721 // Skip up to the relevant declaration scope. 7722 while (S->getFlags() & Scope::TemplateParamScope) 7723 S = S->getParent(); 7724 assert((S->getFlags() & Scope::DeclScope) && 7725 "got alias-declaration outside of declaration scope"); 7726 7727 if (Type.isInvalid()) 7728 return 0; 7729 7730 bool Invalid = false; 7731 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7732 TypeSourceInfo *TInfo = 0; 7733 GetTypeFromParser(Type.get(), &TInfo); 7734 7735 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7736 return 0; 7737 7738 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7739 UPPC_DeclarationType)) { 7740 Invalid = true; 7741 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7742 TInfo->getTypeLoc().getBeginLoc()); 7743 } 7744 7745 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7746 LookupName(Previous, S); 7747 7748 // Warn about shadowing the name of a template parameter. 7749 if (Previous.isSingleResult() && 7750 Previous.getFoundDecl()->isTemplateParameter()) { 7751 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7752 Previous.clear(); 7753 } 7754 7755 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7756 "name in alias declaration must be an identifier"); 7757 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7758 Name.StartLocation, 7759 Name.Identifier, TInfo); 7760 7761 NewTD->setAccess(AS); 7762 7763 if (Invalid) 7764 NewTD->setInvalidDecl(); 7765 7766 ProcessDeclAttributeList(S, NewTD, AttrList); 7767 7768 CheckTypedefForVariablyModifiedType(S, NewTD); 7769 Invalid |= NewTD->isInvalidDecl(); 7770 7771 bool Redeclaration = false; 7772 7773 NamedDecl *NewND; 7774 if (TemplateParamLists.size()) { 7775 TypeAliasTemplateDecl *OldDecl = 0; 7776 TemplateParameterList *OldTemplateParams = 0; 7777 7778 if (TemplateParamLists.size() != 1) { 7779 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7780 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7781 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7782 } 7783 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7784 7785 // Only consider previous declarations in the same scope. 7786 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7787 /*ExplicitInstantiationOrSpecialization*/false); 7788 if (!Previous.empty()) { 7789 Redeclaration = true; 7790 7791 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7792 if (!OldDecl && !Invalid) { 7793 Diag(UsingLoc, diag::err_redefinition_different_kind) 7794 << Name.Identifier; 7795 7796 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7797 if (OldD->getLocation().isValid()) 7798 Diag(OldD->getLocation(), diag::note_previous_definition); 7799 7800 Invalid = true; 7801 } 7802 7803 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7804 if (TemplateParameterListsAreEqual(TemplateParams, 7805 OldDecl->getTemplateParameters(), 7806 /*Complain=*/true, 7807 TPL_TemplateMatch)) 7808 OldTemplateParams = OldDecl->getTemplateParameters(); 7809 else 7810 Invalid = true; 7811 7812 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7813 if (!Invalid && 7814 !Context.hasSameType(OldTD->getUnderlyingType(), 7815 NewTD->getUnderlyingType())) { 7816 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7817 // but we can't reasonably accept it. 7818 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7819 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7820 if (OldTD->getLocation().isValid()) 7821 Diag(OldTD->getLocation(), diag::note_previous_definition); 7822 Invalid = true; 7823 } 7824 } 7825 } 7826 7827 // Merge any previous default template arguments into our parameters, 7828 // and check the parameter list. 7829 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7830 TPC_TypeAliasTemplate)) 7831 return 0; 7832 7833 TypeAliasTemplateDecl *NewDecl = 7834 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7835 Name.Identifier, TemplateParams, 7836 NewTD); 7837 7838 NewDecl->setAccess(AS); 7839 7840 if (Invalid) 7841 NewDecl->setInvalidDecl(); 7842 else if (OldDecl) 7843 NewDecl->setPreviousDecl(OldDecl); 7844 7845 NewND = NewDecl; 7846 } else { 7847 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7848 NewND = NewTD; 7849 } 7850 7851 if (!Redeclaration) 7852 PushOnScopeChains(NewND, S); 7853 7854 ActOnDocumentableDecl(NewND); 7855 return NewND; 7856} 7857 7858Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7859 SourceLocation NamespaceLoc, 7860 SourceLocation AliasLoc, 7861 IdentifierInfo *Alias, 7862 CXXScopeSpec &SS, 7863 SourceLocation IdentLoc, 7864 IdentifierInfo *Ident) { 7865 7866 // Lookup the namespace name. 7867 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7868 LookupParsedName(R, S, &SS); 7869 7870 // Check if we have a previous declaration with the same name. 7871 NamedDecl *PrevDecl 7872 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7873 ForRedeclaration); 7874 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7875 PrevDecl = 0; 7876 7877 if (PrevDecl) { 7878 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7879 // We already have an alias with the same name that points to the same 7880 // namespace, so don't create a new one. 7881 // FIXME: At some point, we'll want to create the (redundant) 7882 // declaration to maintain better source information. 7883 if (!R.isAmbiguous() && !R.empty() && 7884 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7885 return 0; 7886 } 7887 7888 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7889 diag::err_redefinition_different_kind; 7890 Diag(AliasLoc, DiagID) << Alias; 7891 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7892 return 0; 7893 } 7894 7895 if (R.isAmbiguous()) 7896 return 0; 7897 7898 if (R.empty()) { 7899 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 7900 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7901 return 0; 7902 } 7903 } 7904 7905 NamespaceAliasDecl *AliasDecl = 7906 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 7907 Alias, SS.getWithLocInContext(Context), 7908 IdentLoc, R.getFoundDecl()); 7909 7910 PushOnScopeChains(AliasDecl, S); 7911 return AliasDecl; 7912} 7913 7914Sema::ImplicitExceptionSpecification 7915Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 7916 CXXMethodDecl *MD) { 7917 CXXRecordDecl *ClassDecl = MD->getParent(); 7918 7919 // C++ [except.spec]p14: 7920 // An implicitly declared special member function (Clause 12) shall have an 7921 // exception-specification. [...] 7922 ImplicitExceptionSpecification ExceptSpec(*this); 7923 if (ClassDecl->isInvalidDecl()) 7924 return ExceptSpec; 7925 7926 // Direct base-class constructors. 7927 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7928 BEnd = ClassDecl->bases_end(); 7929 B != BEnd; ++B) { 7930 if (B->isVirtual()) // Handled below. 7931 continue; 7932 7933 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7934 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7935 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7936 // If this is a deleted function, add it anyway. This might be conformant 7937 // with the standard. This might not. I'm not sure. It might not matter. 7938 if (Constructor) 7939 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7940 } 7941 } 7942 7943 // Virtual base-class constructors. 7944 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7945 BEnd = ClassDecl->vbases_end(); 7946 B != BEnd; ++B) { 7947 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7948 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7949 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7950 // If this is a deleted function, add it anyway. This might be conformant 7951 // with the standard. This might not. I'm not sure. It might not matter. 7952 if (Constructor) 7953 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7954 } 7955 } 7956 7957 // Field constructors. 7958 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7959 FEnd = ClassDecl->field_end(); 7960 F != FEnd; ++F) { 7961 if (F->hasInClassInitializer()) { 7962 if (Expr *E = F->getInClassInitializer()) 7963 ExceptSpec.CalledExpr(E); 7964 else if (!F->isInvalidDecl()) 7965 // DR1351: 7966 // If the brace-or-equal-initializer of a non-static data member 7967 // invokes a defaulted default constructor of its class or of an 7968 // enclosing class in a potentially evaluated subexpression, the 7969 // program is ill-formed. 7970 // 7971 // This resolution is unworkable: the exception specification of the 7972 // default constructor can be needed in an unevaluated context, in 7973 // particular, in the operand of a noexcept-expression, and we can be 7974 // unable to compute an exception specification for an enclosed class. 7975 // 7976 // We do not allow an in-class initializer to require the evaluation 7977 // of the exception specification for any in-class initializer whose 7978 // definition is not lexically complete. 7979 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 7980 } else if (const RecordType *RecordTy 7981 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7982 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7983 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7984 // If this is a deleted function, add it anyway. This might be conformant 7985 // with the standard. This might not. I'm not sure. It might not matter. 7986 // In particular, the problem is that this function never gets called. It 7987 // might just be ill-formed because this function attempts to refer to 7988 // a deleted function here. 7989 if (Constructor) 7990 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7991 } 7992 } 7993 7994 return ExceptSpec; 7995} 7996 7997Sema::ImplicitExceptionSpecification 7998Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 7999 CXXRecordDecl *ClassDecl = CD->getParent(); 8000 8001 // C++ [except.spec]p14: 8002 // An inheriting constructor [...] shall have an exception-specification. [...] 8003 ImplicitExceptionSpecification ExceptSpec(*this); 8004 if (ClassDecl->isInvalidDecl()) 8005 return ExceptSpec; 8006 8007 // Inherited constructor. 8008 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8009 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8010 // FIXME: Copying or moving the parameters could add extra exceptions to the 8011 // set, as could the default arguments for the inherited constructor. This 8012 // will be addressed when we implement the resolution of core issue 1351. 8013 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8014 8015 // Direct base-class constructors. 8016 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8017 BEnd = ClassDecl->bases_end(); 8018 B != BEnd; ++B) { 8019 if (B->isVirtual()) // Handled below. 8020 continue; 8021 8022 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8023 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8024 if (BaseClassDecl == InheritedDecl) 8025 continue; 8026 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8027 if (Constructor) 8028 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 8029 } 8030 } 8031 8032 // Virtual base-class constructors. 8033 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8034 BEnd = ClassDecl->vbases_end(); 8035 B != BEnd; ++B) { 8036 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8037 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8038 if (BaseClassDecl == InheritedDecl) 8039 continue; 8040 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8041 if (Constructor) 8042 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 8043 } 8044 } 8045 8046 // Field constructors. 8047 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8048 FEnd = ClassDecl->field_end(); 8049 F != FEnd; ++F) { 8050 if (F->hasInClassInitializer()) { 8051 if (Expr *E = F->getInClassInitializer()) 8052 ExceptSpec.CalledExpr(E); 8053 else if (!F->isInvalidDecl()) 8054 Diag(CD->getLocation(), 8055 diag::err_in_class_initializer_references_def_ctor) << CD; 8056 } else if (const RecordType *RecordTy 8057 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8058 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8059 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8060 if (Constructor) 8061 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8062 } 8063 } 8064 8065 return ExceptSpec; 8066} 8067 8068namespace { 8069/// RAII object to register a special member as being currently declared. 8070struct DeclaringSpecialMember { 8071 Sema &S; 8072 Sema::SpecialMemberDecl D; 8073 bool WasAlreadyBeingDeclared; 8074 8075 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8076 : S(S), D(RD, CSM) { 8077 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 8078 if (WasAlreadyBeingDeclared) 8079 // This almost never happens, but if it does, ensure that our cache 8080 // doesn't contain a stale result. 8081 S.SpecialMemberCache.clear(); 8082 8083 // FIXME: Register a note to be produced if we encounter an error while 8084 // declaring the special member. 8085 } 8086 ~DeclaringSpecialMember() { 8087 if (!WasAlreadyBeingDeclared) 8088 S.SpecialMembersBeingDeclared.erase(D); 8089 } 8090 8091 /// \brief Are we already trying to declare this special member? 8092 bool isAlreadyBeingDeclared() const { 8093 return WasAlreadyBeingDeclared; 8094 } 8095}; 8096} 8097 8098CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8099 CXXRecordDecl *ClassDecl) { 8100 // C++ [class.ctor]p5: 8101 // A default constructor for a class X is a constructor of class X 8102 // that can be called without an argument. If there is no 8103 // user-declared constructor for class X, a default constructor is 8104 // implicitly declared. An implicitly-declared default constructor 8105 // is an inline public member of its class. 8106 assert(ClassDecl->needsImplicitDefaultConstructor() && 8107 "Should not build implicit default constructor!"); 8108 8109 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8110 if (DSM.isAlreadyBeingDeclared()) 8111 return 0; 8112 8113 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8114 CXXDefaultConstructor, 8115 false); 8116 8117 // Create the actual constructor declaration. 8118 CanQualType ClassType 8119 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8120 SourceLocation ClassLoc = ClassDecl->getLocation(); 8121 DeclarationName Name 8122 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8123 DeclarationNameInfo NameInfo(Name, ClassLoc); 8124 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8125 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 8126 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8127 Constexpr); 8128 DefaultCon->setAccess(AS_public); 8129 DefaultCon->setDefaulted(); 8130 DefaultCon->setImplicit(); 8131 8132 // Build an exception specification pointing back at this constructor. 8133 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8134 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8135 8136 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8137 // constructors is easy to compute. 8138 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8139 8140 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8141 SetDeclDeleted(DefaultCon, ClassLoc); 8142 8143 // Note that we have declared this constructor. 8144 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8145 8146 if (Scope *S = getScopeForContext(ClassDecl)) 8147 PushOnScopeChains(DefaultCon, S, false); 8148 ClassDecl->addDecl(DefaultCon); 8149 8150 return DefaultCon; 8151} 8152 8153void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8154 CXXConstructorDecl *Constructor) { 8155 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8156 !Constructor->doesThisDeclarationHaveABody() && 8157 !Constructor->isDeleted()) && 8158 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8159 8160 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8161 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8162 8163 SynthesizedFunctionScope Scope(*this, Constructor); 8164 DiagnosticErrorTrap Trap(Diags); 8165 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8166 Trap.hasErrorOccurred()) { 8167 Diag(CurrentLocation, diag::note_member_synthesized_at) 8168 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8169 Constructor->setInvalidDecl(); 8170 return; 8171 } 8172 8173 SourceLocation Loc = Constructor->getLocation(); 8174 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8175 8176 Constructor->markUsed(Context); 8177 MarkVTableUsed(CurrentLocation, ClassDecl); 8178 8179 if (ASTMutationListener *L = getASTMutationListener()) { 8180 L->CompletedImplicitDefinition(Constructor); 8181 } 8182} 8183 8184void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8185 // Check that any explicitly-defaulted methods have exception specifications 8186 // compatible with their implicit exception specifications. 8187 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs(); 8188 8189 // Once all the member initializers are processed, perform checks to see if 8190 // any unintialized use is happeneing. 8191 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, 8192 D->getLocation()) 8193 == DiagnosticsEngine::Ignored) 8194 return; 8195 8196 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D); 8197 if (!RD) return; 8198 8199 // Holds fields that are uninitialized. 8200 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 8201 8202 // In the beginning, every field is uninitialized. 8203 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end(); 8204 I != E; ++I) { 8205 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) { 8206 UninitializedFields.insert(FD); 8207 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) { 8208 UninitializedFields.insert(IFD->getAnonField()); 8209 } 8210 } 8211 8212 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end(); 8213 I != E; ++I) { 8214 FieldDecl *FD = dyn_cast<FieldDecl>(*I); 8215 if (!FD) 8216 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) 8217 FD = IFD->getAnonField(); 8218 8219 if (!FD) 8220 continue; 8221 8222 Expr *InitExpr = FD->getInClassInitializer(); 8223 if (!InitExpr) { 8224 // Uninitialized reference types will give an error. 8225 // Record types with an initializer are default initialized. 8226 QualType FieldType = FD->getType(); 8227 if (FieldType->isReferenceType() || FieldType->isRecordType()) 8228 UninitializedFields.erase(FD); 8229 continue; 8230 } 8231 8232 CheckInitExprContainsUninitializedFields( 8233 *this, InitExpr, FD, UninitializedFields, 8234 UninitializedFields.count(FD)/*WarnOnSelfReference*/); 8235 8236 UninitializedFields.erase(FD); 8237 } 8238} 8239 8240namespace { 8241/// Information on inheriting constructors to declare. 8242class InheritingConstructorInfo { 8243public: 8244 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8245 : SemaRef(SemaRef), Derived(Derived) { 8246 // Mark the constructors that we already have in the derived class. 8247 // 8248 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8249 // unless there is a user-declared constructor with the same signature in 8250 // the class where the using-declaration appears. 8251 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8252 } 8253 8254 void inheritAll(CXXRecordDecl *RD) { 8255 visitAll(RD, &InheritingConstructorInfo::inherit); 8256 } 8257 8258private: 8259 /// Information about an inheriting constructor. 8260 struct InheritingConstructor { 8261 InheritingConstructor() 8262 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {} 8263 8264 /// If \c true, a constructor with this signature is already declared 8265 /// in the derived class. 8266 bool DeclaredInDerived; 8267 8268 /// The constructor which is inherited. 8269 const CXXConstructorDecl *BaseCtor; 8270 8271 /// The derived constructor we declared. 8272 CXXConstructorDecl *DerivedCtor; 8273 }; 8274 8275 /// Inheriting constructors with a given canonical type. There can be at 8276 /// most one such non-template constructor, and any number of templated 8277 /// constructors. 8278 struct InheritingConstructorsForType { 8279 InheritingConstructor NonTemplate; 8280 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8281 Templates; 8282 8283 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8284 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8285 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8286 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8287 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8288 false, S.TPL_TemplateMatch)) 8289 return Templates[I].second; 8290 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8291 return Templates.back().second; 8292 } 8293 8294 return NonTemplate; 8295 } 8296 }; 8297 8298 /// Get or create the inheriting constructor record for a constructor. 8299 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8300 QualType CtorType) { 8301 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8302 .getEntry(SemaRef, Ctor); 8303 } 8304 8305 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8306 8307 /// Process all constructors for a class. 8308 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8309 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(), 8310 CtorE = RD->ctor_end(); 8311 CtorIt != CtorE; ++CtorIt) 8312 (this->*Callback)(*CtorIt); 8313 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8314 I(RD->decls_begin()), E(RD->decls_end()); 8315 I != E; ++I) { 8316 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8317 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8318 (this->*Callback)(CD); 8319 } 8320 } 8321 8322 /// Note that a constructor (or constructor template) was declared in Derived. 8323 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8324 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8325 } 8326 8327 /// Inherit a single constructor. 8328 void inherit(const CXXConstructorDecl *Ctor) { 8329 const FunctionProtoType *CtorType = 8330 Ctor->getType()->castAs<FunctionProtoType>(); 8331 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes()); 8332 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8333 8334 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8335 8336 // Core issue (no number yet): the ellipsis is always discarded. 8337 if (EPI.Variadic) { 8338 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8339 SemaRef.Diag(Ctor->getLocation(), 8340 diag::note_using_decl_constructor_ellipsis); 8341 EPI.Variadic = false; 8342 } 8343 8344 // Declare a constructor for each number of parameters. 8345 // 8346 // C++11 [class.inhctor]p1: 8347 // The candidate set of inherited constructors from the class X named in 8348 // the using-declaration consists of [... modulo defects ...] for each 8349 // constructor or constructor template of X, the set of constructors or 8350 // constructor templates that results from omitting any ellipsis parameter 8351 // specification and successively omitting parameters with a default 8352 // argument from the end of the parameter-type-list 8353 unsigned MinParams = minParamsToInherit(Ctor); 8354 unsigned Params = Ctor->getNumParams(); 8355 if (Params >= MinParams) { 8356 do 8357 declareCtor(UsingLoc, Ctor, 8358 SemaRef.Context.getFunctionType( 8359 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI)); 8360 while (Params > MinParams && 8361 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8362 } 8363 } 8364 8365 /// Find the using-declaration which specified that we should inherit the 8366 /// constructors of \p Base. 8367 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8368 // No fancy lookup required; just look for the base constructor name 8369 // directly within the derived class. 8370 ASTContext &Context = SemaRef.Context; 8371 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8372 Context.getCanonicalType(Context.getRecordType(Base))); 8373 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8374 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8375 } 8376 8377 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8378 // C++11 [class.inhctor]p3: 8379 // [F]or each constructor template in the candidate set of inherited 8380 // constructors, a constructor template is implicitly declared 8381 if (Ctor->getDescribedFunctionTemplate()) 8382 return 0; 8383 8384 // For each non-template constructor in the candidate set of inherited 8385 // constructors other than a constructor having no parameters or a 8386 // copy/move constructor having a single parameter, a constructor is 8387 // implicitly declared [...] 8388 if (Ctor->getNumParams() == 0) 8389 return 1; 8390 if (Ctor->isCopyOrMoveConstructor()) 8391 return 2; 8392 8393 // Per discussion on core reflector, never inherit a constructor which 8394 // would become a default, copy, or move constructor of Derived either. 8395 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8396 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8397 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8398 } 8399 8400 /// Declare a single inheriting constructor, inheriting the specified 8401 /// constructor, with the given type. 8402 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8403 QualType DerivedType) { 8404 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8405 8406 // C++11 [class.inhctor]p3: 8407 // ... a constructor is implicitly declared with the same constructor 8408 // characteristics unless there is a user-declared constructor with 8409 // the same signature in the class where the using-declaration appears 8410 if (Entry.DeclaredInDerived) 8411 return; 8412 8413 // C++11 [class.inhctor]p7: 8414 // If two using-declarations declare inheriting constructors with the 8415 // same signature, the program is ill-formed 8416 if (Entry.DerivedCtor) { 8417 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8418 // Only diagnose this once per constructor. 8419 if (Entry.DerivedCtor->isInvalidDecl()) 8420 return; 8421 Entry.DerivedCtor->setInvalidDecl(); 8422 8423 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8424 SemaRef.Diag(BaseCtor->getLocation(), 8425 diag::note_using_decl_constructor_conflict_current_ctor); 8426 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8427 diag::note_using_decl_constructor_conflict_previous_ctor); 8428 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8429 diag::note_using_decl_constructor_conflict_previous_using); 8430 } else { 8431 // Core issue (no number): if the same inheriting constructor is 8432 // produced by multiple base class constructors from the same base 8433 // class, the inheriting constructor is defined as deleted. 8434 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8435 } 8436 8437 return; 8438 } 8439 8440 ASTContext &Context = SemaRef.Context; 8441 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8442 Context.getCanonicalType(Context.getRecordType(Derived))); 8443 DeclarationNameInfo NameInfo(Name, UsingLoc); 8444 8445 TemplateParameterList *TemplateParams = 0; 8446 if (const FunctionTemplateDecl *FTD = 8447 BaseCtor->getDescribedFunctionTemplate()) { 8448 TemplateParams = FTD->getTemplateParameters(); 8449 // We're reusing template parameters from a different DeclContext. This 8450 // is questionable at best, but works out because the template depth in 8451 // both places is guaranteed to be 0. 8452 // FIXME: Rebuild the template parameters in the new context, and 8453 // transform the function type to refer to them. 8454 } 8455 8456 // Build type source info pointing at the using-declaration. This is 8457 // required by template instantiation. 8458 TypeSourceInfo *TInfo = 8459 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8460 FunctionProtoTypeLoc ProtoLoc = 8461 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8462 8463 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8464 Context, Derived, UsingLoc, NameInfo, DerivedType, 8465 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8466 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8467 8468 // Build an unevaluated exception specification for this constructor. 8469 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8470 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8471 EPI.ExceptionSpecType = EST_Unevaluated; 8472 EPI.ExceptionSpecDecl = DerivedCtor; 8473 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(), 8474 FPT->getArgTypes(), EPI)); 8475 8476 // Build the parameter declarations. 8477 SmallVector<ParmVarDecl *, 16> ParamDecls; 8478 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) { 8479 TypeSourceInfo *TInfo = 8480 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc); 8481 ParmVarDecl *PD = ParmVarDecl::Create( 8482 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0, 8483 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0); 8484 PD->setScopeInfo(0, I); 8485 PD->setImplicit(); 8486 ParamDecls.push_back(PD); 8487 ProtoLoc.setArg(I, PD); 8488 } 8489 8490 // Set up the new constructor. 8491 DerivedCtor->setAccess(BaseCtor->getAccess()); 8492 DerivedCtor->setParams(ParamDecls); 8493 DerivedCtor->setInheritedConstructor(BaseCtor); 8494 if (BaseCtor->isDeleted()) 8495 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8496 8497 // If this is a constructor template, build the template declaration. 8498 if (TemplateParams) { 8499 FunctionTemplateDecl *DerivedTemplate = 8500 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8501 TemplateParams, DerivedCtor); 8502 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8503 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8504 Derived->addDecl(DerivedTemplate); 8505 } else { 8506 Derived->addDecl(DerivedCtor); 8507 } 8508 8509 Entry.BaseCtor = BaseCtor; 8510 Entry.DerivedCtor = DerivedCtor; 8511 } 8512 8513 Sema &SemaRef; 8514 CXXRecordDecl *Derived; 8515 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8516 MapType Map; 8517}; 8518} 8519 8520void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8521 // Defer declaring the inheriting constructors until the class is 8522 // instantiated. 8523 if (ClassDecl->isDependentContext()) 8524 return; 8525 8526 // Find base classes from which we might inherit constructors. 8527 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8528 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 8529 BaseE = ClassDecl->bases_end(); 8530 BaseIt != BaseE; ++BaseIt) 8531 if (BaseIt->getInheritConstructors()) 8532 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl()); 8533 8534 // Go no further if we're not inheriting any constructors. 8535 if (InheritedBases.empty()) 8536 return; 8537 8538 // Declare the inherited constructors. 8539 InheritingConstructorInfo ICI(*this, ClassDecl); 8540 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8541 ICI.inheritAll(InheritedBases[I]); 8542} 8543 8544void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8545 CXXConstructorDecl *Constructor) { 8546 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8547 assert(Constructor->getInheritedConstructor() && 8548 !Constructor->doesThisDeclarationHaveABody() && 8549 !Constructor->isDeleted()); 8550 8551 SynthesizedFunctionScope Scope(*this, Constructor); 8552 DiagnosticErrorTrap Trap(Diags); 8553 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8554 Trap.hasErrorOccurred()) { 8555 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8556 << Context.getTagDeclType(ClassDecl); 8557 Constructor->setInvalidDecl(); 8558 return; 8559 } 8560 8561 SourceLocation Loc = Constructor->getLocation(); 8562 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8563 8564 Constructor->markUsed(Context); 8565 MarkVTableUsed(CurrentLocation, ClassDecl); 8566 8567 if (ASTMutationListener *L = getASTMutationListener()) { 8568 L->CompletedImplicitDefinition(Constructor); 8569 } 8570} 8571 8572 8573Sema::ImplicitExceptionSpecification 8574Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8575 CXXRecordDecl *ClassDecl = MD->getParent(); 8576 8577 // C++ [except.spec]p14: 8578 // An implicitly declared special member function (Clause 12) shall have 8579 // an exception-specification. 8580 ImplicitExceptionSpecification ExceptSpec(*this); 8581 if (ClassDecl->isInvalidDecl()) 8582 return ExceptSpec; 8583 8584 // Direct base-class destructors. 8585 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8586 BEnd = ClassDecl->bases_end(); 8587 B != BEnd; ++B) { 8588 if (B->isVirtual()) // Handled below. 8589 continue; 8590 8591 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8592 ExceptSpec.CalledDecl(B->getLocStart(), 8593 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8594 } 8595 8596 // Virtual base-class destructors. 8597 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8598 BEnd = ClassDecl->vbases_end(); 8599 B != BEnd; ++B) { 8600 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8601 ExceptSpec.CalledDecl(B->getLocStart(), 8602 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8603 } 8604 8605 // Field destructors. 8606 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8607 FEnd = ClassDecl->field_end(); 8608 F != FEnd; ++F) { 8609 if (const RecordType *RecordTy 8610 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8611 ExceptSpec.CalledDecl(F->getLocation(), 8612 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8613 } 8614 8615 return ExceptSpec; 8616} 8617 8618CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8619 // C++ [class.dtor]p2: 8620 // If a class has no user-declared destructor, a destructor is 8621 // declared implicitly. An implicitly-declared destructor is an 8622 // inline public member of its class. 8623 assert(ClassDecl->needsImplicitDestructor()); 8624 8625 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8626 if (DSM.isAlreadyBeingDeclared()) 8627 return 0; 8628 8629 // Create the actual destructor declaration. 8630 CanQualType ClassType 8631 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8632 SourceLocation ClassLoc = ClassDecl->getLocation(); 8633 DeclarationName Name 8634 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8635 DeclarationNameInfo NameInfo(Name, ClassLoc); 8636 CXXDestructorDecl *Destructor 8637 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8638 QualType(), 0, /*isInline=*/true, 8639 /*isImplicitlyDeclared=*/true); 8640 Destructor->setAccess(AS_public); 8641 Destructor->setDefaulted(); 8642 Destructor->setImplicit(); 8643 8644 // Build an exception specification pointing back at this destructor. 8645 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 8646 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8647 8648 AddOverriddenMethods(ClassDecl, Destructor); 8649 8650 // We don't need to use SpecialMemberIsTrivial here; triviality for 8651 // destructors is easy to compute. 8652 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8653 8654 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8655 SetDeclDeleted(Destructor, ClassLoc); 8656 8657 // Note that we have declared this destructor. 8658 ++ASTContext::NumImplicitDestructorsDeclared; 8659 8660 // Introduce this destructor into its scope. 8661 if (Scope *S = getScopeForContext(ClassDecl)) 8662 PushOnScopeChains(Destructor, S, false); 8663 ClassDecl->addDecl(Destructor); 8664 8665 return Destructor; 8666} 8667 8668void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8669 CXXDestructorDecl *Destructor) { 8670 assert((Destructor->isDefaulted() && 8671 !Destructor->doesThisDeclarationHaveABody() && 8672 !Destructor->isDeleted()) && 8673 "DefineImplicitDestructor - call it for implicit default dtor"); 8674 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8675 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8676 8677 if (Destructor->isInvalidDecl()) 8678 return; 8679 8680 SynthesizedFunctionScope Scope(*this, Destructor); 8681 8682 DiagnosticErrorTrap Trap(Diags); 8683 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8684 Destructor->getParent()); 8685 8686 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8687 Diag(CurrentLocation, diag::note_member_synthesized_at) 8688 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8689 8690 Destructor->setInvalidDecl(); 8691 return; 8692 } 8693 8694 SourceLocation Loc = Destructor->getLocation(); 8695 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8696 Destructor->markUsed(Context); 8697 MarkVTableUsed(CurrentLocation, ClassDecl); 8698 8699 if (ASTMutationListener *L = getASTMutationListener()) { 8700 L->CompletedImplicitDefinition(Destructor); 8701 } 8702} 8703 8704/// \brief Perform any semantic analysis which needs to be delayed until all 8705/// pending class member declarations have been parsed. 8706void Sema::ActOnFinishCXXMemberDecls() { 8707 // If the context is an invalid C++ class, just suppress these checks. 8708 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8709 if (Record->isInvalidDecl()) { 8710 DelayedDestructorExceptionSpecChecks.clear(); 8711 return; 8712 } 8713 } 8714 8715 // Perform any deferred checking of exception specifications for virtual 8716 // destructors. 8717 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size(); 8718 i != e; ++i) { 8719 const CXXDestructorDecl *Dtor = 8720 DelayedDestructorExceptionSpecChecks[i].first; 8721 assert(!Dtor->getParent()->isDependentType() && 8722 "Should not ever add destructors of templates into the list."); 8723 CheckOverridingFunctionExceptionSpec(Dtor, 8724 DelayedDestructorExceptionSpecChecks[i].second); 8725 } 8726 DelayedDestructorExceptionSpecChecks.clear(); 8727} 8728 8729void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8730 CXXDestructorDecl *Destructor) { 8731 assert(getLangOpts().CPlusPlus11 && 8732 "adjusting dtor exception specs was introduced in c++11"); 8733 8734 // C++11 [class.dtor]p3: 8735 // A declaration of a destructor that does not have an exception- 8736 // specification is implicitly considered to have the same exception- 8737 // specification as an implicit declaration. 8738 const FunctionProtoType *DtorType = Destructor->getType()-> 8739 getAs<FunctionProtoType>(); 8740 if (DtorType->hasExceptionSpec()) 8741 return; 8742 8743 // Replace the destructor's type, building off the existing one. Fortunately, 8744 // the only thing of interest in the destructor type is its extended info. 8745 // The return and arguments are fixed. 8746 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8747 EPI.ExceptionSpecType = EST_Unevaluated; 8748 EPI.ExceptionSpecDecl = Destructor; 8749 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8750 8751 // FIXME: If the destructor has a body that could throw, and the newly created 8752 // spec doesn't allow exceptions, we should emit a warning, because this 8753 // change in behavior can break conforming C++03 programs at runtime. 8754 // However, we don't have a body or an exception specification yet, so it 8755 // needs to be done somewhere else. 8756} 8757 8758namespace { 8759/// \brief An abstract base class for all helper classes used in building the 8760// copy/move operators. These classes serve as factory functions and help us 8761// avoid using the same Expr* in the AST twice. 8762class ExprBuilder { 8763 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8764 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8765 8766protected: 8767 static Expr *assertNotNull(Expr *E) { 8768 assert(E && "Expression construction must not fail."); 8769 return E; 8770 } 8771 8772public: 8773 ExprBuilder() {} 8774 virtual ~ExprBuilder() {} 8775 8776 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 8777}; 8778 8779class RefBuilder: public ExprBuilder { 8780 VarDecl *Var; 8781 QualType VarType; 8782 8783public: 8784 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8785 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take()); 8786 } 8787 8788 RefBuilder(VarDecl *Var, QualType VarType) 8789 : Var(Var), VarType(VarType) {} 8790}; 8791 8792class ThisBuilder: public ExprBuilder { 8793public: 8794 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8795 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>()); 8796 } 8797}; 8798 8799class CastBuilder: public ExprBuilder { 8800 const ExprBuilder &Builder; 8801 QualType Type; 8802 ExprValueKind Kind; 8803 const CXXCastPath &Path; 8804 8805public: 8806 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8807 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 8808 CK_UncheckedDerivedToBase, Kind, 8809 &Path).take()); 8810 } 8811 8812 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 8813 const CXXCastPath &Path) 8814 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 8815}; 8816 8817class DerefBuilder: public ExprBuilder { 8818 const ExprBuilder &Builder; 8819 8820public: 8821 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8822 return assertNotNull( 8823 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take()); 8824 } 8825 8826 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8827}; 8828 8829class MemberBuilder: public ExprBuilder { 8830 const ExprBuilder &Builder; 8831 QualType Type; 8832 CXXScopeSpec SS; 8833 bool IsArrow; 8834 LookupResult &MemberLookup; 8835 8836public: 8837 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8838 return assertNotNull(S.BuildMemberReferenceExpr( 8839 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0, 8840 MemberLookup, 0).take()); 8841 } 8842 8843 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 8844 LookupResult &MemberLookup) 8845 : Builder(Builder), Type(Type), IsArrow(IsArrow), 8846 MemberLookup(MemberLookup) {} 8847}; 8848 8849class MoveCastBuilder: public ExprBuilder { 8850 const ExprBuilder &Builder; 8851 8852public: 8853 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8854 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 8855 } 8856 8857 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8858}; 8859 8860class LvalueConvBuilder: public ExprBuilder { 8861 const ExprBuilder &Builder; 8862 8863public: 8864 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8865 return assertNotNull( 8866 S.DefaultLvalueConversion(Builder.build(S, Loc)).take()); 8867 } 8868 8869 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8870}; 8871 8872class SubscriptBuilder: public ExprBuilder { 8873 const ExprBuilder &Base; 8874 const ExprBuilder &Index; 8875 8876public: 8877 virtual Expr *build(Sema &S, SourceLocation Loc) const 8878 LLVM_OVERRIDE { 8879 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 8880 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take()); 8881 } 8882 8883 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 8884 : Base(Base), Index(Index) {} 8885}; 8886 8887} // end anonymous namespace 8888 8889/// When generating a defaulted copy or move assignment operator, if a field 8890/// should be copied with __builtin_memcpy rather than via explicit assignments, 8891/// do so. This optimization only applies for arrays of scalars, and for arrays 8892/// of class type where the selected copy/move-assignment operator is trivial. 8893static StmtResult 8894buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 8895 const ExprBuilder &ToB, const ExprBuilder &FromB) { 8896 // Compute the size of the memory buffer to be copied. 8897 QualType SizeType = S.Context.getSizeType(); 8898 llvm::APInt Size(S.Context.getTypeSize(SizeType), 8899 S.Context.getTypeSizeInChars(T).getQuantity()); 8900 8901 // Take the address of the field references for "from" and "to". We 8902 // directly construct UnaryOperators here because semantic analysis 8903 // does not permit us to take the address of an xvalue. 8904 Expr *From = FromB.build(S, Loc); 8905 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 8906 S.Context.getPointerType(From->getType()), 8907 VK_RValue, OK_Ordinary, Loc); 8908 Expr *To = ToB.build(S, Loc); 8909 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 8910 S.Context.getPointerType(To->getType()), 8911 VK_RValue, OK_Ordinary, Loc); 8912 8913 const Type *E = T->getBaseElementTypeUnsafe(); 8914 bool NeedsCollectableMemCpy = 8915 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 8916 8917 // Create a reference to the __builtin_objc_memmove_collectable function 8918 StringRef MemCpyName = NeedsCollectableMemCpy ? 8919 "__builtin_objc_memmove_collectable" : 8920 "__builtin_memcpy"; 8921 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 8922 Sema::LookupOrdinaryName); 8923 S.LookupName(R, S.TUScope, true); 8924 8925 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 8926 if (!MemCpy) 8927 // Something went horribly wrong earlier, and we will have complained 8928 // about it. 8929 return StmtError(); 8930 8931 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 8932 VK_RValue, Loc, 0); 8933 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 8934 8935 Expr *CallArgs[] = { 8936 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 8937 }; 8938 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(), 8939 Loc, CallArgs, Loc); 8940 8941 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8942 return S.Owned(Call.takeAs<Stmt>()); 8943} 8944 8945/// \brief Builds a statement that copies/moves the given entity from \p From to 8946/// \c To. 8947/// 8948/// This routine is used to copy/move the members of a class with an 8949/// implicitly-declared copy/move assignment operator. When the entities being 8950/// copied are arrays, this routine builds for loops to copy them. 8951/// 8952/// \param S The Sema object used for type-checking. 8953/// 8954/// \param Loc The location where the implicit copy/move is being generated. 8955/// 8956/// \param T The type of the expressions being copied/moved. Both expressions 8957/// must have this type. 8958/// 8959/// \param To The expression we are copying/moving to. 8960/// 8961/// \param From The expression we are copying/moving from. 8962/// 8963/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 8964/// Otherwise, it's a non-static member subobject. 8965/// 8966/// \param Copying Whether we're copying or moving. 8967/// 8968/// \param Depth Internal parameter recording the depth of the recursion. 8969/// 8970/// \returns A statement or a loop that copies the expressions, or StmtResult(0) 8971/// if a memcpy should be used instead. 8972static StmtResult 8973buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 8974 const ExprBuilder &To, const ExprBuilder &From, 8975 bool CopyingBaseSubobject, bool Copying, 8976 unsigned Depth = 0) { 8977 // C++11 [class.copy]p28: 8978 // Each subobject is assigned in the manner appropriate to its type: 8979 // 8980 // - if the subobject is of class type, as if by a call to operator= with 8981 // the subobject as the object expression and the corresponding 8982 // subobject of x as a single function argument (as if by explicit 8983 // qualification; that is, ignoring any possible virtual overriding 8984 // functions in more derived classes); 8985 // 8986 // C++03 [class.copy]p13: 8987 // - if the subobject is of class type, the copy assignment operator for 8988 // the class is used (as if by explicit qualification; that is, 8989 // ignoring any possible virtual overriding functions in more derived 8990 // classes); 8991 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 8992 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8993 8994 // Look for operator=. 8995 DeclarationName Name 8996 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8997 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 8998 S.LookupQualifiedName(OpLookup, ClassDecl, false); 8999 9000 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9001 // operator. 9002 if (!S.getLangOpts().CPlusPlus11) { 9003 LookupResult::Filter F = OpLookup.makeFilter(); 9004 while (F.hasNext()) { 9005 NamedDecl *D = F.next(); 9006 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9007 if (Method->isCopyAssignmentOperator() || 9008 (!Copying && Method->isMoveAssignmentOperator())) 9009 continue; 9010 9011 F.erase(); 9012 } 9013 F.done(); 9014 } 9015 9016 // Suppress the protected check (C++ [class.protected]) for each of the 9017 // assignment operators we found. This strange dance is required when 9018 // we're assigning via a base classes's copy-assignment operator. To 9019 // ensure that we're getting the right base class subobject (without 9020 // ambiguities), we need to cast "this" to that subobject type; to 9021 // ensure that we don't go through the virtual call mechanism, we need 9022 // to qualify the operator= name with the base class (see below). However, 9023 // this means that if the base class has a protected copy assignment 9024 // operator, the protected member access check will fail. So, we 9025 // rewrite "protected" access to "public" access in this case, since we 9026 // know by construction that we're calling from a derived class. 9027 if (CopyingBaseSubobject) { 9028 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9029 L != LEnd; ++L) { 9030 if (L.getAccess() == AS_protected) 9031 L.setAccess(AS_public); 9032 } 9033 } 9034 9035 // Create the nested-name-specifier that will be used to qualify the 9036 // reference to operator=; this is required to suppress the virtual 9037 // call mechanism. 9038 CXXScopeSpec SS; 9039 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9040 SS.MakeTrivial(S.Context, 9041 NestedNameSpecifier::Create(S.Context, 0, false, 9042 CanonicalT), 9043 Loc); 9044 9045 // Create the reference to operator=. 9046 ExprResult OpEqualRef 9047 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9048 SS, /*TemplateKWLoc=*/SourceLocation(), 9049 /*FirstQualifierInScope=*/0, 9050 OpLookup, 9051 /*TemplateArgs=*/0, 9052 /*SuppressQualifierCheck=*/true); 9053 if (OpEqualRef.isInvalid()) 9054 return StmtError(); 9055 9056 // Build the call to the assignment operator. 9057 9058 Expr *FromInst = From.build(S, Loc); 9059 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 9060 OpEqualRef.takeAs<Expr>(), 9061 Loc, FromInst, Loc); 9062 if (Call.isInvalid()) 9063 return StmtError(); 9064 9065 // If we built a call to a trivial 'operator=' while copying an array, 9066 // bail out. We'll replace the whole shebang with a memcpy. 9067 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9068 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9069 return StmtResult((Stmt*)0); 9070 9071 // Convert to an expression-statement, and clean up any produced 9072 // temporaries. 9073 return S.ActOnExprStmt(Call); 9074 } 9075 9076 // - if the subobject is of scalar type, the built-in assignment 9077 // operator is used. 9078 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9079 if (!ArrayTy) { 9080 ExprResult Assignment = S.CreateBuiltinBinOp( 9081 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9082 if (Assignment.isInvalid()) 9083 return StmtError(); 9084 return S.ActOnExprStmt(Assignment); 9085 } 9086 9087 // - if the subobject is an array, each element is assigned, in the 9088 // manner appropriate to the element type; 9089 9090 // Construct a loop over the array bounds, e.g., 9091 // 9092 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9093 // 9094 // that will copy each of the array elements. 9095 QualType SizeType = S.Context.getSizeType(); 9096 9097 // Create the iteration variable. 9098 IdentifierInfo *IterationVarName = 0; 9099 { 9100 SmallString<8> Str; 9101 llvm::raw_svector_ostream OS(Str); 9102 OS << "__i" << Depth; 9103 IterationVarName = &S.Context.Idents.get(OS.str()); 9104 } 9105 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9106 IterationVarName, SizeType, 9107 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9108 SC_None); 9109 9110 // Initialize the iteration variable to zero. 9111 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9112 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9113 9114 // Creates a reference to the iteration variable. 9115 RefBuilder IterationVarRef(IterationVar, SizeType); 9116 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9117 9118 // Create the DeclStmt that holds the iteration variable. 9119 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9120 9121 // Subscript the "from" and "to" expressions with the iteration variable. 9122 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9123 MoveCastBuilder FromIndexMove(FromIndexCopy); 9124 const ExprBuilder *FromIndex; 9125 if (Copying) 9126 FromIndex = &FromIndexCopy; 9127 else 9128 FromIndex = &FromIndexMove; 9129 9130 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9131 9132 // Build the copy/move for an individual element of the array. 9133 StmtResult Copy = 9134 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9135 ToIndex, *FromIndex, CopyingBaseSubobject, 9136 Copying, Depth + 1); 9137 // Bail out if copying fails or if we determined that we should use memcpy. 9138 if (Copy.isInvalid() || !Copy.get()) 9139 return Copy; 9140 9141 // Create the comparison against the array bound. 9142 llvm::APInt Upper 9143 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9144 Expr *Comparison 9145 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9146 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9147 BO_NE, S.Context.BoolTy, 9148 VK_RValue, OK_Ordinary, Loc, false); 9149 9150 // Create the pre-increment of the iteration variable. 9151 Expr *Increment 9152 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9153 SizeType, VK_LValue, OK_Ordinary, Loc); 9154 9155 // Construct the loop that copies all elements of this array. 9156 return S.ActOnForStmt(Loc, Loc, InitStmt, 9157 S.MakeFullExpr(Comparison), 9158 0, S.MakeFullDiscardedValueExpr(Increment), 9159 Loc, Copy.take()); 9160} 9161 9162static StmtResult 9163buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9164 const ExprBuilder &To, const ExprBuilder &From, 9165 bool CopyingBaseSubobject, bool Copying) { 9166 // Maybe we should use a memcpy? 9167 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9168 T.isTriviallyCopyableType(S.Context)) 9169 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9170 9171 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9172 CopyingBaseSubobject, 9173 Copying, 0)); 9174 9175 // If we ended up picking a trivial assignment operator for an array of a 9176 // non-trivially-copyable class type, just emit a memcpy. 9177 if (!Result.isInvalid() && !Result.get()) 9178 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9179 9180 return Result; 9181} 9182 9183Sema::ImplicitExceptionSpecification 9184Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9185 CXXRecordDecl *ClassDecl = MD->getParent(); 9186 9187 ImplicitExceptionSpecification ExceptSpec(*this); 9188 if (ClassDecl->isInvalidDecl()) 9189 return ExceptSpec; 9190 9191 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9192 assert(T->getNumArgs() == 1 && "not a copy assignment op"); 9193 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 9194 9195 // C++ [except.spec]p14: 9196 // An implicitly declared special member function (Clause 12) shall have an 9197 // exception-specification. [...] 9198 9199 // It is unspecified whether or not an implicit copy assignment operator 9200 // attempts to deduplicate calls to assignment operators of virtual bases are 9201 // made. As such, this exception specification is effectively unspecified. 9202 // Based on a similar decision made for constness in C++0x, we're erring on 9203 // the side of assuming such calls to be made regardless of whether they 9204 // actually happen. 9205 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9206 BaseEnd = ClassDecl->bases_end(); 9207 Base != BaseEnd; ++Base) { 9208 if (Base->isVirtual()) 9209 continue; 9210 9211 CXXRecordDecl *BaseClassDecl 9212 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9213 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9214 ArgQuals, false, 0)) 9215 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 9216 } 9217 9218 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9219 BaseEnd = ClassDecl->vbases_end(); 9220 Base != BaseEnd; ++Base) { 9221 CXXRecordDecl *BaseClassDecl 9222 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9223 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9224 ArgQuals, false, 0)) 9225 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 9226 } 9227 9228 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9229 FieldEnd = ClassDecl->field_end(); 9230 Field != FieldEnd; 9231 ++Field) { 9232 QualType FieldType = Context.getBaseElementType(Field->getType()); 9233 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9234 if (CXXMethodDecl *CopyAssign = 9235 LookupCopyingAssignment(FieldClassDecl, 9236 ArgQuals | FieldType.getCVRQualifiers(), 9237 false, 0)) 9238 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9239 } 9240 } 9241 9242 return ExceptSpec; 9243} 9244 9245CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9246 // Note: The following rules are largely analoguous to the copy 9247 // constructor rules. Note that virtual bases are not taken into account 9248 // for determining the argument type of the operator. Note also that 9249 // operators taking an object instead of a reference are allowed. 9250 assert(ClassDecl->needsImplicitCopyAssignment()); 9251 9252 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9253 if (DSM.isAlreadyBeingDeclared()) 9254 return 0; 9255 9256 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9257 QualType RetType = Context.getLValueReferenceType(ArgType); 9258 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9259 if (Const) 9260 ArgType = ArgType.withConst(); 9261 ArgType = Context.getLValueReferenceType(ArgType); 9262 9263 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9264 CXXCopyAssignment, 9265 Const); 9266 9267 // An implicitly-declared copy assignment operator is an inline public 9268 // member of its class. 9269 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9270 SourceLocation ClassLoc = ClassDecl->getLocation(); 9271 DeclarationNameInfo NameInfo(Name, ClassLoc); 9272 CXXMethodDecl *CopyAssignment = 9273 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9274 /*TInfo=*/ 0, /*StorageClass=*/ SC_None, 9275 /*isInline=*/ true, Constexpr, SourceLocation()); 9276 CopyAssignment->setAccess(AS_public); 9277 CopyAssignment->setDefaulted(); 9278 CopyAssignment->setImplicit(); 9279 9280 // Build an exception specification pointing back at this member. 9281 FunctionProtoType::ExtProtoInfo EPI = 9282 getImplicitMethodEPI(*this, CopyAssignment); 9283 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9284 9285 // Add the parameter to the operator. 9286 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9287 ClassLoc, ClassLoc, /*Id=*/0, 9288 ArgType, /*TInfo=*/0, 9289 SC_None, 0); 9290 CopyAssignment->setParams(FromParam); 9291 9292 AddOverriddenMethods(ClassDecl, CopyAssignment); 9293 9294 CopyAssignment->setTrivial( 9295 ClassDecl->needsOverloadResolutionForCopyAssignment() 9296 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9297 : ClassDecl->hasTrivialCopyAssignment()); 9298 9299 // C++11 [class.copy]p19: 9300 // .... If the class definition does not explicitly declare a copy 9301 // assignment operator, there is no user-declared move constructor, and 9302 // there is no user-declared move assignment operator, a copy assignment 9303 // operator is implicitly declared as defaulted. 9304 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9305 SetDeclDeleted(CopyAssignment, ClassLoc); 9306 9307 // Note that we have added this copy-assignment operator. 9308 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9309 9310 if (Scope *S = getScopeForContext(ClassDecl)) 9311 PushOnScopeChains(CopyAssignment, S, false); 9312 ClassDecl->addDecl(CopyAssignment); 9313 9314 return CopyAssignment; 9315} 9316 9317/// Diagnose an implicit copy operation for a class which is odr-used, but 9318/// which is deprecated because the class has a user-declared copy constructor, 9319/// copy assignment operator, or destructor. 9320static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 9321 SourceLocation UseLoc) { 9322 assert(CopyOp->isImplicit()); 9323 9324 CXXRecordDecl *RD = CopyOp->getParent(); 9325 CXXMethodDecl *UserDeclaredOperation = 0; 9326 9327 // In Microsoft mode, assignment operations don't affect constructors and 9328 // vice versa. 9329 if (RD->hasUserDeclaredDestructor()) { 9330 UserDeclaredOperation = RD->getDestructor(); 9331 } else if (!isa<CXXConstructorDecl>(CopyOp) && 9332 RD->hasUserDeclaredCopyConstructor() && 9333 !S.getLangOpts().MicrosoftMode) { 9334 // Find any user-declared copy constructor. 9335 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 9336 E = RD->ctor_end(); I != E; ++I) { 9337 if (I->isCopyConstructor()) { 9338 UserDeclaredOperation = *I; 9339 break; 9340 } 9341 } 9342 assert(UserDeclaredOperation); 9343 } else if (isa<CXXConstructorDecl>(CopyOp) && 9344 RD->hasUserDeclaredCopyAssignment() && 9345 !S.getLangOpts().MicrosoftMode) { 9346 // Find any user-declared move assignment operator. 9347 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 9348 E = RD->method_end(); I != E; ++I) { 9349 if (I->isCopyAssignmentOperator()) { 9350 UserDeclaredOperation = *I; 9351 break; 9352 } 9353 } 9354 assert(UserDeclaredOperation); 9355 } 9356 9357 if (UserDeclaredOperation) { 9358 S.Diag(UserDeclaredOperation->getLocation(), 9359 diag::warn_deprecated_copy_operation) 9360 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 9361 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 9362 S.Diag(UseLoc, diag::note_member_synthesized_at) 9363 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 9364 : Sema::CXXCopyAssignment) 9365 << RD; 9366 } 9367} 9368 9369void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 9370 CXXMethodDecl *CopyAssignOperator) { 9371 assert((CopyAssignOperator->isDefaulted() && 9372 CopyAssignOperator->isOverloadedOperator() && 9373 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 9374 !CopyAssignOperator->doesThisDeclarationHaveABody() && 9375 !CopyAssignOperator->isDeleted()) && 9376 "DefineImplicitCopyAssignment called for wrong function"); 9377 9378 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 9379 9380 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 9381 CopyAssignOperator->setInvalidDecl(); 9382 return; 9383 } 9384 9385 // C++11 [class.copy]p18: 9386 // The [definition of an implicitly declared copy assignment operator] is 9387 // deprecated if the class has a user-declared copy constructor or a 9388 // user-declared destructor. 9389 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 9390 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 9391 9392 CopyAssignOperator->markUsed(Context); 9393 9394 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 9395 DiagnosticErrorTrap Trap(Diags); 9396 9397 // C++0x [class.copy]p30: 9398 // The implicitly-defined or explicitly-defaulted copy assignment operator 9399 // for a non-union class X performs memberwise copy assignment of its 9400 // subobjects. The direct base classes of X are assigned first, in the 9401 // order of their declaration in the base-specifier-list, and then the 9402 // immediate non-static data members of X are assigned, in the order in 9403 // which they were declared in the class definition. 9404 9405 // The statements that form the synthesized function body. 9406 SmallVector<Stmt*, 8> Statements; 9407 9408 // The parameter for the "other" object, which we are copying from. 9409 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 9410 Qualifiers OtherQuals = Other->getType().getQualifiers(); 9411 QualType OtherRefType = Other->getType(); 9412 if (const LValueReferenceType *OtherRef 9413 = OtherRefType->getAs<LValueReferenceType>()) { 9414 OtherRefType = OtherRef->getPointeeType(); 9415 OtherQuals = OtherRefType.getQualifiers(); 9416 } 9417 9418 // Our location for everything implicitly-generated. 9419 SourceLocation Loc = CopyAssignOperator->getLocation(); 9420 9421 // Builds a DeclRefExpr for the "other" object. 9422 RefBuilder OtherRef(Other, OtherRefType); 9423 9424 // Builds the "this" pointer. 9425 ThisBuilder This; 9426 9427 // Assign base classes. 9428 bool Invalid = false; 9429 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9430 E = ClassDecl->bases_end(); Base != E; ++Base) { 9431 // Form the assignment: 9432 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 9433 QualType BaseType = Base->getType().getUnqualifiedType(); 9434 if (!BaseType->isRecordType()) { 9435 Invalid = true; 9436 continue; 9437 } 9438 9439 CXXCastPath BasePath; 9440 BasePath.push_back(Base); 9441 9442 // Construct the "from" expression, which is an implicit cast to the 9443 // appropriately-qualified base type. 9444 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 9445 VK_LValue, BasePath); 9446 9447 // Dereference "this". 9448 DerefBuilder DerefThis(This); 9449 CastBuilder To(DerefThis, 9450 Context.getCVRQualifiedType( 9451 BaseType, CopyAssignOperator->getTypeQualifiers()), 9452 VK_LValue, BasePath); 9453 9454 // Build the copy. 9455 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 9456 To, From, 9457 /*CopyingBaseSubobject=*/true, 9458 /*Copying=*/true); 9459 if (Copy.isInvalid()) { 9460 Diag(CurrentLocation, diag::note_member_synthesized_at) 9461 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9462 CopyAssignOperator->setInvalidDecl(); 9463 return; 9464 } 9465 9466 // Success! Record the copy. 9467 Statements.push_back(Copy.takeAs<Expr>()); 9468 } 9469 9470 // Assign non-static members. 9471 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9472 FieldEnd = ClassDecl->field_end(); 9473 Field != FieldEnd; ++Field) { 9474 if (Field->isUnnamedBitfield()) 9475 continue; 9476 9477 if (Field->isInvalidDecl()) { 9478 Invalid = true; 9479 continue; 9480 } 9481 9482 // Check for members of reference type; we can't copy those. 9483 if (Field->getType()->isReferenceType()) { 9484 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9485 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9486 Diag(Field->getLocation(), diag::note_declared_at); 9487 Diag(CurrentLocation, diag::note_member_synthesized_at) 9488 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9489 Invalid = true; 9490 continue; 9491 } 9492 9493 // Check for members of const-qualified, non-class type. 9494 QualType BaseType = Context.getBaseElementType(Field->getType()); 9495 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9496 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9497 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9498 Diag(Field->getLocation(), diag::note_declared_at); 9499 Diag(CurrentLocation, diag::note_member_synthesized_at) 9500 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9501 Invalid = true; 9502 continue; 9503 } 9504 9505 // Suppress assigning zero-width bitfields. 9506 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9507 continue; 9508 9509 QualType FieldType = Field->getType().getNonReferenceType(); 9510 if (FieldType->isIncompleteArrayType()) { 9511 assert(ClassDecl->hasFlexibleArrayMember() && 9512 "Incomplete array type is not valid"); 9513 continue; 9514 } 9515 9516 // Build references to the field in the object we're copying from and to. 9517 CXXScopeSpec SS; // Intentionally empty 9518 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9519 LookupMemberName); 9520 MemberLookup.addDecl(*Field); 9521 MemberLookup.resolveKind(); 9522 9523 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 9524 9525 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 9526 9527 // Build the copy of this field. 9528 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 9529 To, From, 9530 /*CopyingBaseSubobject=*/false, 9531 /*Copying=*/true); 9532 if (Copy.isInvalid()) { 9533 Diag(CurrentLocation, diag::note_member_synthesized_at) 9534 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9535 CopyAssignOperator->setInvalidDecl(); 9536 return; 9537 } 9538 9539 // Success! Record the copy. 9540 Statements.push_back(Copy.takeAs<Stmt>()); 9541 } 9542 9543 if (!Invalid) { 9544 // Add a "return *this;" 9545 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9546 9547 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9548 if (Return.isInvalid()) 9549 Invalid = true; 9550 else { 9551 Statements.push_back(Return.takeAs<Stmt>()); 9552 9553 if (Trap.hasErrorOccurred()) { 9554 Diag(CurrentLocation, diag::note_member_synthesized_at) 9555 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9556 Invalid = true; 9557 } 9558 } 9559 } 9560 9561 if (Invalid) { 9562 CopyAssignOperator->setInvalidDecl(); 9563 return; 9564 } 9565 9566 StmtResult Body; 9567 { 9568 CompoundScopeRAII CompoundScope(*this); 9569 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9570 /*isStmtExpr=*/false); 9571 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9572 } 9573 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 9574 9575 if (ASTMutationListener *L = getASTMutationListener()) { 9576 L->CompletedImplicitDefinition(CopyAssignOperator); 9577 } 9578} 9579 9580Sema::ImplicitExceptionSpecification 9581Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9582 CXXRecordDecl *ClassDecl = MD->getParent(); 9583 9584 ImplicitExceptionSpecification ExceptSpec(*this); 9585 if (ClassDecl->isInvalidDecl()) 9586 return ExceptSpec; 9587 9588 // C++0x [except.spec]p14: 9589 // An implicitly declared special member function (Clause 12) shall have an 9590 // exception-specification. [...] 9591 9592 // It is unspecified whether or not an implicit move assignment operator 9593 // attempts to deduplicate calls to assignment operators of virtual bases are 9594 // made. As such, this exception specification is effectively unspecified. 9595 // Based on a similar decision made for constness in C++0x, we're erring on 9596 // the side of assuming such calls to be made regardless of whether they 9597 // actually happen. 9598 // Note that a move constructor is not implicitly declared when there are 9599 // virtual bases, but it can still be user-declared and explicitly defaulted. 9600 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9601 BaseEnd = ClassDecl->bases_end(); 9602 Base != BaseEnd; ++Base) { 9603 if (Base->isVirtual()) 9604 continue; 9605 9606 CXXRecordDecl *BaseClassDecl 9607 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9608 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9609 0, false, 0)) 9610 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9611 } 9612 9613 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9614 BaseEnd = ClassDecl->vbases_end(); 9615 Base != BaseEnd; ++Base) { 9616 CXXRecordDecl *BaseClassDecl 9617 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9618 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9619 0, false, 0)) 9620 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9621 } 9622 9623 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9624 FieldEnd = ClassDecl->field_end(); 9625 Field != FieldEnd; 9626 ++Field) { 9627 QualType FieldType = Context.getBaseElementType(Field->getType()); 9628 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9629 if (CXXMethodDecl *MoveAssign = 9630 LookupMovingAssignment(FieldClassDecl, 9631 FieldType.getCVRQualifiers(), 9632 false, 0)) 9633 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 9634 } 9635 } 9636 9637 return ExceptSpec; 9638} 9639 9640/// Determine whether the class type has any direct or indirect virtual base 9641/// classes which have a non-trivial move assignment operator. 9642static bool 9643hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) { 9644 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9645 BaseEnd = ClassDecl->vbases_end(); 9646 Base != BaseEnd; ++Base) { 9647 CXXRecordDecl *BaseClass = 9648 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9649 9650 // Try to declare the move assignment. If it would be deleted, then the 9651 // class does not have a non-trivial move assignment. 9652 if (BaseClass->needsImplicitMoveAssignment()) 9653 S.DeclareImplicitMoveAssignment(BaseClass); 9654 9655 if (BaseClass->hasNonTrivialMoveAssignment()) 9656 return true; 9657 } 9658 9659 return false; 9660} 9661 9662/// Determine whether the given type either has a move constructor or is 9663/// trivially copyable. 9664static bool 9665hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) { 9666 Type = S.Context.getBaseElementType(Type); 9667 9668 // FIXME: Technically, non-trivially-copyable non-class types, such as 9669 // reference types, are supposed to return false here, but that appears 9670 // to be a standard defect. 9671 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl(); 9672 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl()) 9673 return true; 9674 9675 if (Type.isTriviallyCopyableType(S.Context)) 9676 return true; 9677 9678 if (IsConstructor) { 9679 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to 9680 // give the right answer. 9681 if (ClassDecl->needsImplicitMoveConstructor()) 9682 S.DeclareImplicitMoveConstructor(ClassDecl); 9683 return ClassDecl->hasMoveConstructor(); 9684 } 9685 9686 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to 9687 // give the right answer. 9688 if (ClassDecl->needsImplicitMoveAssignment()) 9689 S.DeclareImplicitMoveAssignment(ClassDecl); 9690 return ClassDecl->hasMoveAssignment(); 9691} 9692 9693/// Determine whether all non-static data members and direct or virtual bases 9694/// of class \p ClassDecl have either a move operation, or are trivially 9695/// copyable. 9696static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl, 9697 bool IsConstructor) { 9698 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9699 BaseEnd = ClassDecl->bases_end(); 9700 Base != BaseEnd; ++Base) { 9701 if (Base->isVirtual()) 9702 continue; 9703 9704 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9705 return false; 9706 } 9707 9708 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9709 BaseEnd = ClassDecl->vbases_end(); 9710 Base != BaseEnd; ++Base) { 9711 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9712 return false; 9713 } 9714 9715 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9716 FieldEnd = ClassDecl->field_end(); 9717 Field != FieldEnd; ++Field) { 9718 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor)) 9719 return false; 9720 } 9721 9722 return true; 9723} 9724 9725CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9726 // C++11 [class.copy]p20: 9727 // If the definition of a class X does not explicitly declare a move 9728 // assignment operator, one will be implicitly declared as defaulted 9729 // if and only if: 9730 // 9731 // - [first 4 bullets] 9732 assert(ClassDecl->needsImplicitMoveAssignment()); 9733 9734 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9735 if (DSM.isAlreadyBeingDeclared()) 9736 return 0; 9737 9738 // [Checked after we build the declaration] 9739 // - the move assignment operator would not be implicitly defined as 9740 // deleted, 9741 9742 // [DR1402]: 9743 // - X has no direct or indirect virtual base class with a non-trivial 9744 // move assignment operator, and 9745 // - each of X's non-static data members and direct or virtual base classes 9746 // has a type that either has a move assignment operator or is trivially 9747 // copyable. 9748 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) || 9749 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) { 9750 ClassDecl->setFailedImplicitMoveAssignment(); 9751 return 0; 9752 } 9753 9754 // Note: The following rules are largely analoguous to the move 9755 // constructor rules. 9756 9757 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9758 QualType RetType = Context.getLValueReferenceType(ArgType); 9759 ArgType = Context.getRValueReferenceType(ArgType); 9760 9761 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9762 CXXMoveAssignment, 9763 false); 9764 9765 // An implicitly-declared move assignment operator is an inline public 9766 // member of its class. 9767 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9768 SourceLocation ClassLoc = ClassDecl->getLocation(); 9769 DeclarationNameInfo NameInfo(Name, ClassLoc); 9770 CXXMethodDecl *MoveAssignment = 9771 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9772 /*TInfo=*/0, /*StorageClass=*/SC_None, 9773 /*isInline=*/true, Constexpr, SourceLocation()); 9774 MoveAssignment->setAccess(AS_public); 9775 MoveAssignment->setDefaulted(); 9776 MoveAssignment->setImplicit(); 9777 9778 // Build an exception specification pointing back at this member. 9779 FunctionProtoType::ExtProtoInfo EPI = 9780 getImplicitMethodEPI(*this, MoveAssignment); 9781 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9782 9783 // Add the parameter to the operator. 9784 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9785 ClassLoc, ClassLoc, /*Id=*/0, 9786 ArgType, /*TInfo=*/0, 9787 SC_None, 0); 9788 MoveAssignment->setParams(FromParam); 9789 9790 AddOverriddenMethods(ClassDecl, MoveAssignment); 9791 9792 MoveAssignment->setTrivial( 9793 ClassDecl->needsOverloadResolutionForMoveAssignment() 9794 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9795 : ClassDecl->hasTrivialMoveAssignment()); 9796 9797 // C++0x [class.copy]p9: 9798 // If the definition of a class X does not explicitly declare a move 9799 // assignment operator, one will be implicitly declared as defaulted if and 9800 // only if: 9801 // [...] 9802 // - the move assignment operator would not be implicitly defined as 9803 // deleted. 9804 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9805 // Cache this result so that we don't try to generate this over and over 9806 // on every lookup, leaking memory and wasting time. 9807 ClassDecl->setFailedImplicitMoveAssignment(); 9808 return 0; 9809 } 9810 9811 // Note that we have added this copy-assignment operator. 9812 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9813 9814 if (Scope *S = getScopeForContext(ClassDecl)) 9815 PushOnScopeChains(MoveAssignment, S, false); 9816 ClassDecl->addDecl(MoveAssignment); 9817 9818 return MoveAssignment; 9819} 9820 9821void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 9822 CXXMethodDecl *MoveAssignOperator) { 9823 assert((MoveAssignOperator->isDefaulted() && 9824 MoveAssignOperator->isOverloadedOperator() && 9825 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 9826 !MoveAssignOperator->doesThisDeclarationHaveABody() && 9827 !MoveAssignOperator->isDeleted()) && 9828 "DefineImplicitMoveAssignment called for wrong function"); 9829 9830 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 9831 9832 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 9833 MoveAssignOperator->setInvalidDecl(); 9834 return; 9835 } 9836 9837 MoveAssignOperator->markUsed(Context); 9838 9839 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 9840 DiagnosticErrorTrap Trap(Diags); 9841 9842 // C++0x [class.copy]p28: 9843 // The implicitly-defined or move assignment operator for a non-union class 9844 // X performs memberwise move assignment of its subobjects. The direct base 9845 // classes of X are assigned first, in the order of their declaration in the 9846 // base-specifier-list, and then the immediate non-static data members of X 9847 // are assigned, in the order in which they were declared in the class 9848 // definition. 9849 9850 // The statements that form the synthesized function body. 9851 SmallVector<Stmt*, 8> Statements; 9852 9853 // The parameter for the "other" object, which we are move from. 9854 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 9855 QualType OtherRefType = Other->getType()-> 9856 getAs<RValueReferenceType>()->getPointeeType(); 9857 assert(!OtherRefType.getQualifiers() && 9858 "Bad argument type of defaulted move assignment"); 9859 9860 // Our location for everything implicitly-generated. 9861 SourceLocation Loc = MoveAssignOperator->getLocation(); 9862 9863 // Builds a reference to the "other" object. 9864 RefBuilder OtherRef(Other, OtherRefType); 9865 // Cast to rvalue. 9866 MoveCastBuilder MoveOther(OtherRef); 9867 9868 // Builds the "this" pointer. 9869 ThisBuilder This; 9870 9871 // Assign base classes. 9872 bool Invalid = false; 9873 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9874 E = ClassDecl->bases_end(); Base != E; ++Base) { 9875 // Form the assignment: 9876 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 9877 QualType BaseType = Base->getType().getUnqualifiedType(); 9878 if (!BaseType->isRecordType()) { 9879 Invalid = true; 9880 continue; 9881 } 9882 9883 CXXCastPath BasePath; 9884 BasePath.push_back(Base); 9885 9886 // Construct the "from" expression, which is an implicit cast to the 9887 // appropriately-qualified base type. 9888 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 9889 9890 // Dereference "this". 9891 DerefBuilder DerefThis(This); 9892 9893 // Implicitly cast "this" to the appropriately-qualified base type. 9894 CastBuilder To(DerefThis, 9895 Context.getCVRQualifiedType( 9896 BaseType, MoveAssignOperator->getTypeQualifiers()), 9897 VK_LValue, BasePath); 9898 9899 // Build the move. 9900 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 9901 To, From, 9902 /*CopyingBaseSubobject=*/true, 9903 /*Copying=*/false); 9904 if (Move.isInvalid()) { 9905 Diag(CurrentLocation, diag::note_member_synthesized_at) 9906 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9907 MoveAssignOperator->setInvalidDecl(); 9908 return; 9909 } 9910 9911 // Success! Record the move. 9912 Statements.push_back(Move.takeAs<Expr>()); 9913 } 9914 9915 // Assign non-static members. 9916 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9917 FieldEnd = ClassDecl->field_end(); 9918 Field != FieldEnd; ++Field) { 9919 if (Field->isUnnamedBitfield()) 9920 continue; 9921 9922 if (Field->isInvalidDecl()) { 9923 Invalid = true; 9924 continue; 9925 } 9926 9927 // Check for members of reference type; we can't move those. 9928 if (Field->getType()->isReferenceType()) { 9929 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9930 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9931 Diag(Field->getLocation(), diag::note_declared_at); 9932 Diag(CurrentLocation, diag::note_member_synthesized_at) 9933 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9934 Invalid = true; 9935 continue; 9936 } 9937 9938 // Check for members of const-qualified, non-class type. 9939 QualType BaseType = Context.getBaseElementType(Field->getType()); 9940 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9941 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9942 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9943 Diag(Field->getLocation(), diag::note_declared_at); 9944 Diag(CurrentLocation, diag::note_member_synthesized_at) 9945 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9946 Invalid = true; 9947 continue; 9948 } 9949 9950 // Suppress assigning zero-width bitfields. 9951 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9952 continue; 9953 9954 QualType FieldType = Field->getType().getNonReferenceType(); 9955 if (FieldType->isIncompleteArrayType()) { 9956 assert(ClassDecl->hasFlexibleArrayMember() && 9957 "Incomplete array type is not valid"); 9958 continue; 9959 } 9960 9961 // Build references to the field in the object we're copying from and to. 9962 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9963 LookupMemberName); 9964 MemberLookup.addDecl(*Field); 9965 MemberLookup.resolveKind(); 9966 MemberBuilder From(MoveOther, OtherRefType, 9967 /*IsArrow=*/false, MemberLookup); 9968 MemberBuilder To(This, getCurrentThisType(), 9969 /*IsArrow=*/true, MemberLookup); 9970 9971 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 9972 "Member reference with rvalue base must be rvalue except for reference " 9973 "members, which aren't allowed for move assignment."); 9974 9975 // Build the move of this field. 9976 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 9977 To, From, 9978 /*CopyingBaseSubobject=*/false, 9979 /*Copying=*/false); 9980 if (Move.isInvalid()) { 9981 Diag(CurrentLocation, diag::note_member_synthesized_at) 9982 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9983 MoveAssignOperator->setInvalidDecl(); 9984 return; 9985 } 9986 9987 // Success! Record the copy. 9988 Statements.push_back(Move.takeAs<Stmt>()); 9989 } 9990 9991 if (!Invalid) { 9992 // Add a "return *this;" 9993 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9994 9995 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9996 if (Return.isInvalid()) 9997 Invalid = true; 9998 else { 9999 Statements.push_back(Return.takeAs<Stmt>()); 10000 10001 if (Trap.hasErrorOccurred()) { 10002 Diag(CurrentLocation, diag::note_member_synthesized_at) 10003 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10004 Invalid = true; 10005 } 10006 } 10007 } 10008 10009 if (Invalid) { 10010 MoveAssignOperator->setInvalidDecl(); 10011 return; 10012 } 10013 10014 StmtResult Body; 10015 { 10016 CompoundScopeRAII CompoundScope(*this); 10017 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10018 /*isStmtExpr=*/false); 10019 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10020 } 10021 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 10022 10023 if (ASTMutationListener *L = getASTMutationListener()) { 10024 L->CompletedImplicitDefinition(MoveAssignOperator); 10025 } 10026} 10027 10028Sema::ImplicitExceptionSpecification 10029Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10030 CXXRecordDecl *ClassDecl = MD->getParent(); 10031 10032 ImplicitExceptionSpecification ExceptSpec(*this); 10033 if (ClassDecl->isInvalidDecl()) 10034 return ExceptSpec; 10035 10036 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10037 assert(T->getNumArgs() >= 1 && "not a copy ctor"); 10038 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 10039 10040 // C++ [except.spec]p14: 10041 // An implicitly declared special member function (Clause 12) shall have an 10042 // exception-specification. [...] 10043 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 10044 BaseEnd = ClassDecl->bases_end(); 10045 Base != BaseEnd; 10046 ++Base) { 10047 // Virtual bases are handled below. 10048 if (Base->isVirtual()) 10049 continue; 10050 10051 CXXRecordDecl *BaseClassDecl 10052 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 10053 if (CXXConstructorDecl *CopyConstructor = 10054 LookupCopyingConstructor(BaseClassDecl, Quals)) 10055 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 10056 } 10057 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 10058 BaseEnd = ClassDecl->vbases_end(); 10059 Base != BaseEnd; 10060 ++Base) { 10061 CXXRecordDecl *BaseClassDecl 10062 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 10063 if (CXXConstructorDecl *CopyConstructor = 10064 LookupCopyingConstructor(BaseClassDecl, Quals)) 10065 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 10066 } 10067 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 10068 FieldEnd = ClassDecl->field_end(); 10069 Field != FieldEnd; 10070 ++Field) { 10071 QualType FieldType = Context.getBaseElementType(Field->getType()); 10072 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10073 if (CXXConstructorDecl *CopyConstructor = 10074 LookupCopyingConstructor(FieldClassDecl, 10075 Quals | FieldType.getCVRQualifiers())) 10076 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10077 } 10078 } 10079 10080 return ExceptSpec; 10081} 10082 10083CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10084 CXXRecordDecl *ClassDecl) { 10085 // C++ [class.copy]p4: 10086 // If the class definition does not explicitly declare a copy 10087 // constructor, one is declared implicitly. 10088 assert(ClassDecl->needsImplicitCopyConstructor()); 10089 10090 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10091 if (DSM.isAlreadyBeingDeclared()) 10092 return 0; 10093 10094 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10095 QualType ArgType = ClassType; 10096 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10097 if (Const) 10098 ArgType = ArgType.withConst(); 10099 ArgType = Context.getLValueReferenceType(ArgType); 10100 10101 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10102 CXXCopyConstructor, 10103 Const); 10104 10105 DeclarationName Name 10106 = Context.DeclarationNames.getCXXConstructorName( 10107 Context.getCanonicalType(ClassType)); 10108 SourceLocation ClassLoc = ClassDecl->getLocation(); 10109 DeclarationNameInfo NameInfo(Name, ClassLoc); 10110 10111 // An implicitly-declared copy constructor is an inline public 10112 // member of its class. 10113 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10114 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 10115 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10116 Constexpr); 10117 CopyConstructor->setAccess(AS_public); 10118 CopyConstructor->setDefaulted(); 10119 10120 // Build an exception specification pointing back at this member. 10121 FunctionProtoType::ExtProtoInfo EPI = 10122 getImplicitMethodEPI(*this, CopyConstructor); 10123 CopyConstructor->setType( 10124 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10125 10126 // Add the parameter to the constructor. 10127 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10128 ClassLoc, ClassLoc, 10129 /*IdentifierInfo=*/0, 10130 ArgType, /*TInfo=*/0, 10131 SC_None, 0); 10132 CopyConstructor->setParams(FromParam); 10133 10134 CopyConstructor->setTrivial( 10135 ClassDecl->needsOverloadResolutionForCopyConstructor() 10136 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10137 : ClassDecl->hasTrivialCopyConstructor()); 10138 10139 // C++11 [class.copy]p8: 10140 // ... If the class definition does not explicitly declare a copy 10141 // constructor, there is no user-declared move constructor, and there is no 10142 // user-declared move assignment operator, a copy constructor is implicitly 10143 // declared as defaulted. 10144 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10145 SetDeclDeleted(CopyConstructor, ClassLoc); 10146 10147 // Note that we have declared this constructor. 10148 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10149 10150 if (Scope *S = getScopeForContext(ClassDecl)) 10151 PushOnScopeChains(CopyConstructor, S, false); 10152 ClassDecl->addDecl(CopyConstructor); 10153 10154 return CopyConstructor; 10155} 10156 10157void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10158 CXXConstructorDecl *CopyConstructor) { 10159 assert((CopyConstructor->isDefaulted() && 10160 CopyConstructor->isCopyConstructor() && 10161 !CopyConstructor->doesThisDeclarationHaveABody() && 10162 !CopyConstructor->isDeleted()) && 10163 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10164 10165 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10166 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10167 10168 // C++11 [class.copy]p7: 10169 // The [definition of an implicitly declared copy constructor] is 10170 // deprecated if the class has a user-declared copy assignment operator 10171 // or a user-declared destructor. 10172 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10173 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10174 10175 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10176 DiagnosticErrorTrap Trap(Diags); 10177 10178 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10179 Trap.hasErrorOccurred()) { 10180 Diag(CurrentLocation, diag::note_member_synthesized_at) 10181 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10182 CopyConstructor->setInvalidDecl(); 10183 } else { 10184 Sema::CompoundScopeRAII CompoundScope(*this); 10185 CopyConstructor->setBody(ActOnCompoundStmt( 10186 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None, 10187 /*isStmtExpr=*/ false).takeAs<Stmt>()); 10188 } 10189 10190 CopyConstructor->markUsed(Context); 10191 if (ASTMutationListener *L = getASTMutationListener()) { 10192 L->CompletedImplicitDefinition(CopyConstructor); 10193 } 10194} 10195 10196Sema::ImplicitExceptionSpecification 10197Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10198 CXXRecordDecl *ClassDecl = MD->getParent(); 10199 10200 // C++ [except.spec]p14: 10201 // An implicitly declared special member function (Clause 12) shall have an 10202 // exception-specification. [...] 10203 ImplicitExceptionSpecification ExceptSpec(*this); 10204 if (ClassDecl->isInvalidDecl()) 10205 return ExceptSpec; 10206 10207 // Direct base-class constructors. 10208 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 10209 BEnd = ClassDecl->bases_end(); 10210 B != BEnd; ++B) { 10211 if (B->isVirtual()) // Handled below. 10212 continue; 10213 10214 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 10215 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10216 CXXConstructorDecl *Constructor = 10217 LookupMovingConstructor(BaseClassDecl, 0); 10218 // If this is a deleted function, add it anyway. This might be conformant 10219 // with the standard. This might not. I'm not sure. It might not matter. 10220 if (Constructor) 10221 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 10222 } 10223 } 10224 10225 // Virtual base-class constructors. 10226 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 10227 BEnd = ClassDecl->vbases_end(); 10228 B != BEnd; ++B) { 10229 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 10230 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10231 CXXConstructorDecl *Constructor = 10232 LookupMovingConstructor(BaseClassDecl, 0); 10233 // If this is a deleted function, add it anyway. This might be conformant 10234 // with the standard. This might not. I'm not sure. It might not matter. 10235 if (Constructor) 10236 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 10237 } 10238 } 10239 10240 // Field constructors. 10241 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 10242 FEnd = ClassDecl->field_end(); 10243 F != FEnd; ++F) { 10244 QualType FieldType = Context.getBaseElementType(F->getType()); 10245 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10246 CXXConstructorDecl *Constructor = 10247 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10248 // If this is a deleted function, add it anyway. This might be conformant 10249 // with the standard. This might not. I'm not sure. It might not matter. 10250 // In particular, the problem is that this function never gets called. It 10251 // might just be ill-formed because this function attempts to refer to 10252 // a deleted function here. 10253 if (Constructor) 10254 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10255 } 10256 } 10257 10258 return ExceptSpec; 10259} 10260 10261CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10262 CXXRecordDecl *ClassDecl) { 10263 // C++11 [class.copy]p9: 10264 // If the definition of a class X does not explicitly declare a move 10265 // constructor, one will be implicitly declared as defaulted if and only if: 10266 // 10267 // - [first 4 bullets] 10268 assert(ClassDecl->needsImplicitMoveConstructor()); 10269 10270 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10271 if (DSM.isAlreadyBeingDeclared()) 10272 return 0; 10273 10274 // [Checked after we build the declaration] 10275 // - the move assignment operator would not be implicitly defined as 10276 // deleted, 10277 10278 // [DR1402]: 10279 // - each of X's non-static data members and direct or virtual base classes 10280 // has a type that either has a move constructor or is trivially copyable. 10281 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) { 10282 ClassDecl->setFailedImplicitMoveConstructor(); 10283 return 0; 10284 } 10285 10286 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10287 QualType ArgType = Context.getRValueReferenceType(ClassType); 10288 10289 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10290 CXXMoveConstructor, 10291 false); 10292 10293 DeclarationName Name 10294 = Context.DeclarationNames.getCXXConstructorName( 10295 Context.getCanonicalType(ClassType)); 10296 SourceLocation ClassLoc = ClassDecl->getLocation(); 10297 DeclarationNameInfo NameInfo(Name, ClassLoc); 10298 10299 // C++11 [class.copy]p11: 10300 // An implicitly-declared copy/move constructor is an inline public 10301 // member of its class. 10302 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10303 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 10304 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10305 Constexpr); 10306 MoveConstructor->setAccess(AS_public); 10307 MoveConstructor->setDefaulted(); 10308 10309 // Build an exception specification pointing back at this member. 10310 FunctionProtoType::ExtProtoInfo EPI = 10311 getImplicitMethodEPI(*this, MoveConstructor); 10312 MoveConstructor->setType( 10313 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10314 10315 // Add the parameter to the constructor. 10316 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10317 ClassLoc, ClassLoc, 10318 /*IdentifierInfo=*/0, 10319 ArgType, /*TInfo=*/0, 10320 SC_None, 0); 10321 MoveConstructor->setParams(FromParam); 10322 10323 MoveConstructor->setTrivial( 10324 ClassDecl->needsOverloadResolutionForMoveConstructor() 10325 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10326 : ClassDecl->hasTrivialMoveConstructor()); 10327 10328 // C++0x [class.copy]p9: 10329 // If the definition of a class X does not explicitly declare a move 10330 // constructor, one will be implicitly declared as defaulted if and only if: 10331 // [...] 10332 // - the move constructor would not be implicitly defined as deleted. 10333 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10334 // Cache this result so that we don't try to generate this over and over 10335 // on every lookup, leaking memory and wasting time. 10336 ClassDecl->setFailedImplicitMoveConstructor(); 10337 return 0; 10338 } 10339 10340 // Note that we have declared this constructor. 10341 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10342 10343 if (Scope *S = getScopeForContext(ClassDecl)) 10344 PushOnScopeChains(MoveConstructor, S, false); 10345 ClassDecl->addDecl(MoveConstructor); 10346 10347 return MoveConstructor; 10348} 10349 10350void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 10351 CXXConstructorDecl *MoveConstructor) { 10352 assert((MoveConstructor->isDefaulted() && 10353 MoveConstructor->isMoveConstructor() && 10354 !MoveConstructor->doesThisDeclarationHaveABody() && 10355 !MoveConstructor->isDeleted()) && 10356 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 10357 10358 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 10359 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 10360 10361 SynthesizedFunctionScope Scope(*this, MoveConstructor); 10362 DiagnosticErrorTrap Trap(Diags); 10363 10364 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10365 Trap.hasErrorOccurred()) { 10366 Diag(CurrentLocation, diag::note_member_synthesized_at) 10367 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10368 MoveConstructor->setInvalidDecl(); 10369 } else { 10370 Sema::CompoundScopeRAII CompoundScope(*this); 10371 MoveConstructor->setBody(ActOnCompoundStmt( 10372 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None, 10373 /*isStmtExpr=*/ false).takeAs<Stmt>()); 10374 } 10375 10376 MoveConstructor->markUsed(Context); 10377 10378 if (ASTMutationListener *L = getASTMutationListener()) { 10379 L->CompletedImplicitDefinition(MoveConstructor); 10380 } 10381} 10382 10383bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10384 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10385} 10386 10387void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10388 SourceLocation CurrentLocation, 10389 CXXConversionDecl *Conv) { 10390 CXXRecordDecl *Lambda = Conv->getParent(); 10391 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 10392 // If we are defining a specialization of a conversion to function-ptr 10393 // cache the deduced template arguments for this specialization 10394 // so that we can use them to retrieve the corresponding call-operator 10395 // and static-invoker. 10396 const TemplateArgumentList *DeducedTemplateArgs = 0; 10397 10398 10399 // Retrieve the corresponding call-operator specialization. 10400 if (Lambda->isGenericLambda()) { 10401 assert(Conv->isFunctionTemplateSpecialization()); 10402 FunctionTemplateDecl *CallOpTemplate = 10403 CallOp->getDescribedFunctionTemplate(); 10404 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 10405 void *InsertPos = 0; 10406 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 10407 DeducedTemplateArgs->data(), 10408 DeducedTemplateArgs->size(), 10409 InsertPos); 10410 assert(CallOpSpec && 10411 "Conversion operator must have a corresponding call operator"); 10412 CallOp = cast<CXXMethodDecl>(CallOpSpec); 10413 } 10414 // Mark the call operator referenced (and add to pending instantiations 10415 // if necessary). 10416 // For both the conversion and static-invoker template specializations 10417 // we construct their body's in this function, so no need to add them 10418 // to the PendingInstantiations. 10419 MarkFunctionReferenced(CurrentLocation, CallOp); 10420 10421 SynthesizedFunctionScope Scope(*this, Conv); 10422 DiagnosticErrorTrap Trap(Diags); 10423 10424 // Retreive the static invoker... 10425 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 10426 // ... and get the corresponding specialization for a generic lambda. 10427 if (Lambda->isGenericLambda()) { 10428 assert(DeducedTemplateArgs && 10429 "Must have deduced template arguments from Conversion Operator"); 10430 FunctionTemplateDecl *InvokeTemplate = 10431 Invoker->getDescribedFunctionTemplate(); 10432 void *InsertPos = 0; 10433 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 10434 DeducedTemplateArgs->data(), 10435 DeducedTemplateArgs->size(), 10436 InsertPos); 10437 assert(InvokeSpec && 10438 "Must have a corresponding static invoker specialization"); 10439 Invoker = cast<CXXMethodDecl>(InvokeSpec); 10440 } 10441 // Construct the body of the conversion function { return __invoke; }. 10442 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 10443 VK_LValue, Conv->getLocation()).take(); 10444 assert(FunctionRef && "Can't refer to __invoke function?"); 10445 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 10446 Conv->setBody(new (Context) CompoundStmt(Context, Return, 10447 Conv->getLocation(), 10448 Conv->getLocation())); 10449 10450 Conv->markUsed(Context); 10451 Conv->setReferenced(); 10452 10453 // Fill in the __invoke function with a dummy implementation. IR generation 10454 // will fill in the actual details. 10455 Invoker->markUsed(Context); 10456 Invoker->setReferenced(); 10457 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 10458 10459 if (ASTMutationListener *L = getASTMutationListener()) { 10460 L->CompletedImplicitDefinition(Conv); 10461 L->CompletedImplicitDefinition(Invoker); 10462 } 10463} 10464 10465 10466 10467void Sema::DefineImplicitLambdaToBlockPointerConversion( 10468 SourceLocation CurrentLocation, 10469 CXXConversionDecl *Conv) 10470{ 10471 assert(!Conv->getParent()->isGenericLambda()); 10472 10473 Conv->markUsed(Context); 10474 10475 SynthesizedFunctionScope Scope(*this, Conv); 10476 DiagnosticErrorTrap Trap(Diags); 10477 10478 // Copy-initialize the lambda object as needed to capture it. 10479 Expr *This = ActOnCXXThis(CurrentLocation).take(); 10480 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 10481 10482 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 10483 Conv->getLocation(), 10484 Conv, DerefThis); 10485 10486 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 10487 // behavior. Note that only the general conversion function does this 10488 // (since it's unusable otherwise); in the case where we inline the 10489 // block literal, it has block literal lifetime semantics. 10490 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 10491 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 10492 CK_CopyAndAutoreleaseBlockObject, 10493 BuildBlock.get(), 0, VK_RValue); 10494 10495 if (BuildBlock.isInvalid()) { 10496 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10497 Conv->setInvalidDecl(); 10498 return; 10499 } 10500 10501 // Create the return statement that returns the block from the conversion 10502 // function. 10503 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 10504 if (Return.isInvalid()) { 10505 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10506 Conv->setInvalidDecl(); 10507 return; 10508 } 10509 10510 // Set the body of the conversion function. 10511 Stmt *ReturnS = Return.take(); 10512 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 10513 Conv->getLocation(), 10514 Conv->getLocation())); 10515 10516 // We're done; notify the mutation listener, if any. 10517 if (ASTMutationListener *L = getASTMutationListener()) { 10518 L->CompletedImplicitDefinition(Conv); 10519 } 10520} 10521 10522/// \brief Determine whether the given list arguments contains exactly one 10523/// "real" (non-default) argument. 10524static bool hasOneRealArgument(MultiExprArg Args) { 10525 switch (Args.size()) { 10526 case 0: 10527 return false; 10528 10529 default: 10530 if (!Args[1]->isDefaultArgument()) 10531 return false; 10532 10533 // fall through 10534 case 1: 10535 return !Args[0]->isDefaultArgument(); 10536 } 10537 10538 return false; 10539} 10540 10541ExprResult 10542Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10543 CXXConstructorDecl *Constructor, 10544 MultiExprArg ExprArgs, 10545 bool HadMultipleCandidates, 10546 bool IsListInitialization, 10547 bool RequiresZeroInit, 10548 unsigned ConstructKind, 10549 SourceRange ParenRange) { 10550 bool Elidable = false; 10551 10552 // C++0x [class.copy]p34: 10553 // When certain criteria are met, an implementation is allowed to 10554 // omit the copy/move construction of a class object, even if the 10555 // copy/move constructor and/or destructor for the object have 10556 // side effects. [...] 10557 // - when a temporary class object that has not been bound to a 10558 // reference (12.2) would be copied/moved to a class object 10559 // with the same cv-unqualified type, the copy/move operation 10560 // can be omitted by constructing the temporary object 10561 // directly into the target of the omitted copy/move 10562 if (ConstructKind == CXXConstructExpr::CK_Complete && 10563 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10564 Expr *SubExpr = ExprArgs[0]; 10565 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10566 } 10567 10568 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10569 Elidable, ExprArgs, HadMultipleCandidates, 10570 IsListInitialization, RequiresZeroInit, 10571 ConstructKind, ParenRange); 10572} 10573 10574/// BuildCXXConstructExpr - Creates a complete call to a constructor, 10575/// including handling of its default argument expressions. 10576ExprResult 10577Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10578 CXXConstructorDecl *Constructor, bool Elidable, 10579 MultiExprArg ExprArgs, 10580 bool HadMultipleCandidates, 10581 bool IsListInitialization, 10582 bool RequiresZeroInit, 10583 unsigned ConstructKind, 10584 SourceRange ParenRange) { 10585 MarkFunctionReferenced(ConstructLoc, Constructor); 10586 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 10587 Constructor, Elidable, ExprArgs, 10588 HadMultipleCandidates, 10589 IsListInitialization, RequiresZeroInit, 10590 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10591 ParenRange)); 10592} 10593 10594void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10595 if (VD->isInvalidDecl()) return; 10596 10597 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10598 if (ClassDecl->isInvalidDecl()) return; 10599 if (ClassDecl->hasIrrelevantDestructor()) return; 10600 if (ClassDecl->isDependentContext()) return; 10601 10602 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10603 MarkFunctionReferenced(VD->getLocation(), Destructor); 10604 CheckDestructorAccess(VD->getLocation(), Destructor, 10605 PDiag(diag::err_access_dtor_var) 10606 << VD->getDeclName() 10607 << VD->getType()); 10608 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10609 10610 if (!VD->hasGlobalStorage()) return; 10611 10612 // Emit warning for non-trivial dtor in global scope (a real global, 10613 // class-static, function-static). 10614 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10615 10616 // TODO: this should be re-enabled for static locals by !CXAAtExit 10617 if (!VD->isStaticLocal()) 10618 Diag(VD->getLocation(), diag::warn_global_destructor); 10619} 10620 10621/// \brief Given a constructor and the set of arguments provided for the 10622/// constructor, convert the arguments and add any required default arguments 10623/// to form a proper call to this constructor. 10624/// 10625/// \returns true if an error occurred, false otherwise. 10626bool 10627Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10628 MultiExprArg ArgsPtr, 10629 SourceLocation Loc, 10630 SmallVectorImpl<Expr*> &ConvertedArgs, 10631 bool AllowExplicit, 10632 bool IsListInitialization) { 10633 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10634 unsigned NumArgs = ArgsPtr.size(); 10635 Expr **Args = ArgsPtr.data(); 10636 10637 const FunctionProtoType *Proto 10638 = Constructor->getType()->getAs<FunctionProtoType>(); 10639 assert(Proto && "Constructor without a prototype?"); 10640 unsigned NumArgsInProto = Proto->getNumArgs(); 10641 10642 // If too few arguments are available, we'll fill in the rest with defaults. 10643 if (NumArgs < NumArgsInProto) 10644 ConvertedArgs.reserve(NumArgsInProto); 10645 else 10646 ConvertedArgs.reserve(NumArgs); 10647 10648 VariadicCallType CallType = 10649 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10650 SmallVector<Expr *, 8> AllArgs; 10651 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10652 Proto, 0, 10653 llvm::makeArrayRef(Args, NumArgs), 10654 AllArgs, 10655 CallType, AllowExplicit, 10656 IsListInitialization); 10657 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 10658 10659 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 10660 10661 CheckConstructorCall(Constructor, 10662 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 10663 AllArgs.size()), 10664 Proto, Loc); 10665 10666 return Invalid; 10667} 10668 10669static inline bool 10670CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 10671 const FunctionDecl *FnDecl) { 10672 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 10673 if (isa<NamespaceDecl>(DC)) { 10674 return SemaRef.Diag(FnDecl->getLocation(), 10675 diag::err_operator_new_delete_declared_in_namespace) 10676 << FnDecl->getDeclName(); 10677 } 10678 10679 if (isa<TranslationUnitDecl>(DC) && 10680 FnDecl->getStorageClass() == SC_Static) { 10681 return SemaRef.Diag(FnDecl->getLocation(), 10682 diag::err_operator_new_delete_declared_static) 10683 << FnDecl->getDeclName(); 10684 } 10685 10686 return false; 10687} 10688 10689static inline bool 10690CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 10691 CanQualType ExpectedResultType, 10692 CanQualType ExpectedFirstParamType, 10693 unsigned DependentParamTypeDiag, 10694 unsigned InvalidParamTypeDiag) { 10695 QualType ResultType = 10696 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 10697 10698 // Check that the result type is not dependent. 10699 if (ResultType->isDependentType()) 10700 return SemaRef.Diag(FnDecl->getLocation(), 10701 diag::err_operator_new_delete_dependent_result_type) 10702 << FnDecl->getDeclName() << ExpectedResultType; 10703 10704 // Check that the result type is what we expect. 10705 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 10706 return SemaRef.Diag(FnDecl->getLocation(), 10707 diag::err_operator_new_delete_invalid_result_type) 10708 << FnDecl->getDeclName() << ExpectedResultType; 10709 10710 // A function template must have at least 2 parameters. 10711 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 10712 return SemaRef.Diag(FnDecl->getLocation(), 10713 diag::err_operator_new_delete_template_too_few_parameters) 10714 << FnDecl->getDeclName(); 10715 10716 // The function decl must have at least 1 parameter. 10717 if (FnDecl->getNumParams() == 0) 10718 return SemaRef.Diag(FnDecl->getLocation(), 10719 diag::err_operator_new_delete_too_few_parameters) 10720 << FnDecl->getDeclName(); 10721 10722 // Check the first parameter type is not dependent. 10723 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10724 if (FirstParamType->isDependentType()) 10725 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10726 << FnDecl->getDeclName() << ExpectedFirstParamType; 10727 10728 // Check that the first parameter type is what we expect. 10729 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10730 ExpectedFirstParamType) 10731 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10732 << FnDecl->getDeclName() << ExpectedFirstParamType; 10733 10734 return false; 10735} 10736 10737static bool 10738CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10739 // C++ [basic.stc.dynamic.allocation]p1: 10740 // A program is ill-formed if an allocation function is declared in a 10741 // namespace scope other than global scope or declared static in global 10742 // scope. 10743 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10744 return true; 10745 10746 CanQualType SizeTy = 10747 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10748 10749 // C++ [basic.stc.dynamic.allocation]p1: 10750 // The return type shall be void*. The first parameter shall have type 10751 // std::size_t. 10752 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10753 SizeTy, 10754 diag::err_operator_new_dependent_param_type, 10755 diag::err_operator_new_param_type)) 10756 return true; 10757 10758 // C++ [basic.stc.dynamic.allocation]p1: 10759 // The first parameter shall not have an associated default argument. 10760 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10761 return SemaRef.Diag(FnDecl->getLocation(), 10762 diag::err_operator_new_default_arg) 10763 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10764 10765 return false; 10766} 10767 10768static bool 10769CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10770 // C++ [basic.stc.dynamic.deallocation]p1: 10771 // A program is ill-formed if deallocation functions are declared in a 10772 // namespace scope other than global scope or declared static in global 10773 // scope. 10774 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10775 return true; 10776 10777 // C++ [basic.stc.dynamic.deallocation]p2: 10778 // Each deallocation function shall return void and its first parameter 10779 // shall be void*. 10780 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10781 SemaRef.Context.VoidPtrTy, 10782 diag::err_operator_delete_dependent_param_type, 10783 diag::err_operator_delete_param_type)) 10784 return true; 10785 10786 return false; 10787} 10788 10789/// CheckOverloadedOperatorDeclaration - Check whether the declaration 10790/// of this overloaded operator is well-formed. If so, returns false; 10791/// otherwise, emits appropriate diagnostics and returns true. 10792bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10793 assert(FnDecl && FnDecl->isOverloadedOperator() && 10794 "Expected an overloaded operator declaration"); 10795 10796 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10797 10798 // C++ [over.oper]p5: 10799 // The allocation and deallocation functions, operator new, 10800 // operator new[], operator delete and operator delete[], are 10801 // described completely in 3.7.3. The attributes and restrictions 10802 // found in the rest of this subclause do not apply to them unless 10803 // explicitly stated in 3.7.3. 10804 if (Op == OO_Delete || Op == OO_Array_Delete) 10805 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10806 10807 if (Op == OO_New || Op == OO_Array_New) 10808 return CheckOperatorNewDeclaration(*this, FnDecl); 10809 10810 // C++ [over.oper]p6: 10811 // An operator function shall either be a non-static member 10812 // function or be a non-member function and have at least one 10813 // parameter whose type is a class, a reference to a class, an 10814 // enumeration, or a reference to an enumeration. 10815 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 10816 if (MethodDecl->isStatic()) 10817 return Diag(FnDecl->getLocation(), 10818 diag::err_operator_overload_static) << FnDecl->getDeclName(); 10819 } else { 10820 bool ClassOrEnumParam = false; 10821 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10822 ParamEnd = FnDecl->param_end(); 10823 Param != ParamEnd; ++Param) { 10824 QualType ParamType = (*Param)->getType().getNonReferenceType(); 10825 if (ParamType->isDependentType() || ParamType->isRecordType() || 10826 ParamType->isEnumeralType()) { 10827 ClassOrEnumParam = true; 10828 break; 10829 } 10830 } 10831 10832 if (!ClassOrEnumParam) 10833 return Diag(FnDecl->getLocation(), 10834 diag::err_operator_overload_needs_class_or_enum) 10835 << FnDecl->getDeclName(); 10836 } 10837 10838 // C++ [over.oper]p8: 10839 // An operator function cannot have default arguments (8.3.6), 10840 // except where explicitly stated below. 10841 // 10842 // Only the function-call operator allows default arguments 10843 // (C++ [over.call]p1). 10844 if (Op != OO_Call) { 10845 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10846 Param != FnDecl->param_end(); ++Param) { 10847 if ((*Param)->hasDefaultArg()) 10848 return Diag((*Param)->getLocation(), 10849 diag::err_operator_overload_default_arg) 10850 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 10851 } 10852 } 10853 10854 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 10855 { false, false, false } 10856#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 10857 , { Unary, Binary, MemberOnly } 10858#include "clang/Basic/OperatorKinds.def" 10859 }; 10860 10861 bool CanBeUnaryOperator = OperatorUses[Op][0]; 10862 bool CanBeBinaryOperator = OperatorUses[Op][1]; 10863 bool MustBeMemberOperator = OperatorUses[Op][2]; 10864 10865 // C++ [over.oper]p8: 10866 // [...] Operator functions cannot have more or fewer parameters 10867 // than the number required for the corresponding operator, as 10868 // described in the rest of this subclause. 10869 unsigned NumParams = FnDecl->getNumParams() 10870 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 10871 if (Op != OO_Call && 10872 ((NumParams == 1 && !CanBeUnaryOperator) || 10873 (NumParams == 2 && !CanBeBinaryOperator) || 10874 (NumParams < 1) || (NumParams > 2))) { 10875 // We have the wrong number of parameters. 10876 unsigned ErrorKind; 10877 if (CanBeUnaryOperator && CanBeBinaryOperator) { 10878 ErrorKind = 2; // 2 -> unary or binary. 10879 } else if (CanBeUnaryOperator) { 10880 ErrorKind = 0; // 0 -> unary 10881 } else { 10882 assert(CanBeBinaryOperator && 10883 "All non-call overloaded operators are unary or binary!"); 10884 ErrorKind = 1; // 1 -> binary 10885 } 10886 10887 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 10888 << FnDecl->getDeclName() << NumParams << ErrorKind; 10889 } 10890 10891 // Overloaded operators other than operator() cannot be variadic. 10892 if (Op != OO_Call && 10893 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 10894 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 10895 << FnDecl->getDeclName(); 10896 } 10897 10898 // Some operators must be non-static member functions. 10899 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 10900 return Diag(FnDecl->getLocation(), 10901 diag::err_operator_overload_must_be_member) 10902 << FnDecl->getDeclName(); 10903 } 10904 10905 // C++ [over.inc]p1: 10906 // The user-defined function called operator++ implements the 10907 // prefix and postfix ++ operator. If this function is a member 10908 // function with no parameters, or a non-member function with one 10909 // parameter of class or enumeration type, it defines the prefix 10910 // increment operator ++ for objects of that type. If the function 10911 // is a member function with one parameter (which shall be of type 10912 // int) or a non-member function with two parameters (the second 10913 // of which shall be of type int), it defines the postfix 10914 // increment operator ++ for objects of that type. 10915 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 10916 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 10917 bool ParamIsInt = false; 10918 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 10919 ParamIsInt = BT->getKind() == BuiltinType::Int; 10920 10921 if (!ParamIsInt) 10922 return Diag(LastParam->getLocation(), 10923 diag::err_operator_overload_post_incdec_must_be_int) 10924 << LastParam->getType() << (Op == OO_MinusMinus); 10925 } 10926 10927 return false; 10928} 10929 10930/// CheckLiteralOperatorDeclaration - Check whether the declaration 10931/// of this literal operator function is well-formed. If so, returns 10932/// false; otherwise, emits appropriate diagnostics and returns true. 10933bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 10934 if (isa<CXXMethodDecl>(FnDecl)) { 10935 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 10936 << FnDecl->getDeclName(); 10937 return true; 10938 } 10939 10940 if (FnDecl->isExternC()) { 10941 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 10942 return true; 10943 } 10944 10945 bool Valid = false; 10946 10947 // This might be the definition of a literal operator template. 10948 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 10949 // This might be a specialization of a literal operator template. 10950 if (!TpDecl) 10951 TpDecl = FnDecl->getPrimaryTemplate(); 10952 10953 // template <char...> type operator "" name() and 10954 // template <class T, T...> type operator "" name() are the only valid 10955 // template signatures, and the only valid signatures with no parameters. 10956 if (TpDecl) { 10957 if (FnDecl->param_size() == 0) { 10958 // Must have one or two template parameters 10959 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 10960 if (Params->size() == 1) { 10961 NonTypeTemplateParmDecl *PmDecl = 10962 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 10963 10964 // The template parameter must be a char parameter pack. 10965 if (PmDecl && PmDecl->isTemplateParameterPack() && 10966 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 10967 Valid = true; 10968 } else if (Params->size() == 2) { 10969 TemplateTypeParmDecl *PmType = 10970 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 10971 NonTypeTemplateParmDecl *PmArgs = 10972 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 10973 10974 // The second template parameter must be a parameter pack with the 10975 // first template parameter as its type. 10976 if (PmType && PmArgs && 10977 !PmType->isTemplateParameterPack() && 10978 PmArgs->isTemplateParameterPack()) { 10979 const TemplateTypeParmType *TArgs = 10980 PmArgs->getType()->getAs<TemplateTypeParmType>(); 10981 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 10982 TArgs->getIndex() == PmType->getIndex()) { 10983 Valid = true; 10984 if (ActiveTemplateInstantiations.empty()) 10985 Diag(FnDecl->getLocation(), 10986 diag::ext_string_literal_operator_template); 10987 } 10988 } 10989 } 10990 } 10991 } else if (FnDecl->param_size()) { 10992 // Check the first parameter 10993 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10994 10995 QualType T = (*Param)->getType().getUnqualifiedType(); 10996 10997 // unsigned long long int, long double, and any character type are allowed 10998 // as the only parameters. 10999 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11000 Context.hasSameType(T, Context.LongDoubleTy) || 11001 Context.hasSameType(T, Context.CharTy) || 11002 Context.hasSameType(T, Context.WideCharTy) || 11003 Context.hasSameType(T, Context.Char16Ty) || 11004 Context.hasSameType(T, Context.Char32Ty)) { 11005 if (++Param == FnDecl->param_end()) 11006 Valid = true; 11007 goto FinishedParams; 11008 } 11009 11010 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11011 const PointerType *PT = T->getAs<PointerType>(); 11012 if (!PT) 11013 goto FinishedParams; 11014 T = PT->getPointeeType(); 11015 if (!T.isConstQualified() || T.isVolatileQualified()) 11016 goto FinishedParams; 11017 T = T.getUnqualifiedType(); 11018 11019 // Move on to the second parameter; 11020 ++Param; 11021 11022 // If there is no second parameter, the first must be a const char * 11023 if (Param == FnDecl->param_end()) { 11024 if (Context.hasSameType(T, Context.CharTy)) 11025 Valid = true; 11026 goto FinishedParams; 11027 } 11028 11029 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11030 // are allowed as the first parameter to a two-parameter function 11031 if (!(Context.hasSameType(T, Context.CharTy) || 11032 Context.hasSameType(T, Context.WideCharTy) || 11033 Context.hasSameType(T, Context.Char16Ty) || 11034 Context.hasSameType(T, Context.Char32Ty))) 11035 goto FinishedParams; 11036 11037 // The second and final parameter must be an std::size_t 11038 T = (*Param)->getType().getUnqualifiedType(); 11039 if (Context.hasSameType(T, Context.getSizeType()) && 11040 ++Param == FnDecl->param_end()) 11041 Valid = true; 11042 } 11043 11044 // FIXME: This diagnostic is absolutely terrible. 11045FinishedParams: 11046 if (!Valid) { 11047 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11048 << FnDecl->getDeclName(); 11049 return true; 11050 } 11051 11052 // A parameter-declaration-clause containing a default argument is not 11053 // equivalent to any of the permitted forms. 11054 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 11055 ParamEnd = FnDecl->param_end(); 11056 Param != ParamEnd; ++Param) { 11057 if ((*Param)->hasDefaultArg()) { 11058 Diag((*Param)->getDefaultArgRange().getBegin(), 11059 diag::err_literal_operator_default_argument) 11060 << (*Param)->getDefaultArgRange(); 11061 break; 11062 } 11063 } 11064 11065 StringRef LiteralName 11066 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11067 if (LiteralName[0] != '_') { 11068 // C++11 [usrlit.suffix]p1: 11069 // Literal suffix identifiers that do not start with an underscore 11070 // are reserved for future standardization. 11071 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11072 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11073 } 11074 11075 return false; 11076} 11077 11078/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11079/// linkage specification, including the language and (if present) 11080/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 11081/// the location of the language string literal, which is provided 11082/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 11083/// the '{' brace. Otherwise, this linkage specification does not 11084/// have any braces. 11085Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11086 SourceLocation LangLoc, 11087 StringRef Lang, 11088 SourceLocation LBraceLoc) { 11089 LinkageSpecDecl::LanguageIDs Language; 11090 if (Lang == "\"C\"") 11091 Language = LinkageSpecDecl::lang_c; 11092 else if (Lang == "\"C++\"") 11093 Language = LinkageSpecDecl::lang_cxx; 11094 else { 11095 Diag(LangLoc, diag::err_bad_language); 11096 return 0; 11097 } 11098 11099 // FIXME: Add all the various semantics of linkage specifications 11100 11101 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 11102 ExternLoc, LangLoc, Language, 11103 LBraceLoc.isValid()); 11104 CurContext->addDecl(D); 11105 PushDeclContext(S, D); 11106 return D; 11107} 11108 11109/// ActOnFinishLinkageSpecification - Complete the definition of 11110/// the C++ linkage specification LinkageSpec. If RBraceLoc is 11111/// valid, it's the position of the closing '}' brace in a linkage 11112/// specification that uses braces. 11113Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11114 Decl *LinkageSpec, 11115 SourceLocation RBraceLoc) { 11116 if (LinkageSpec) { 11117 if (RBraceLoc.isValid()) { 11118 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11119 LSDecl->setRBraceLoc(RBraceLoc); 11120 } 11121 PopDeclContext(); 11122 } 11123 return LinkageSpec; 11124} 11125 11126Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11127 AttributeList *AttrList, 11128 SourceLocation SemiLoc) { 11129 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11130 // Attribute declarations appertain to empty declaration so we handle 11131 // them here. 11132 if (AttrList) 11133 ProcessDeclAttributeList(S, ED, AttrList); 11134 11135 CurContext->addDecl(ED); 11136 return ED; 11137} 11138 11139/// \brief Perform semantic analysis for the variable declaration that 11140/// occurs within a C++ catch clause, returning the newly-created 11141/// variable. 11142VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11143 TypeSourceInfo *TInfo, 11144 SourceLocation StartLoc, 11145 SourceLocation Loc, 11146 IdentifierInfo *Name) { 11147 bool Invalid = false; 11148 QualType ExDeclType = TInfo->getType(); 11149 11150 // Arrays and functions decay. 11151 if (ExDeclType->isArrayType()) 11152 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11153 else if (ExDeclType->isFunctionType()) 11154 ExDeclType = Context.getPointerType(ExDeclType); 11155 11156 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11157 // The exception-declaration shall not denote a pointer or reference to an 11158 // incomplete type, other than [cv] void*. 11159 // N2844 forbids rvalue references. 11160 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11161 Diag(Loc, diag::err_catch_rvalue_ref); 11162 Invalid = true; 11163 } 11164 11165 QualType BaseType = ExDeclType; 11166 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11167 unsigned DK = diag::err_catch_incomplete; 11168 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11169 BaseType = Ptr->getPointeeType(); 11170 Mode = 1; 11171 DK = diag::err_catch_incomplete_ptr; 11172 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11173 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11174 BaseType = Ref->getPointeeType(); 11175 Mode = 2; 11176 DK = diag::err_catch_incomplete_ref; 11177 } 11178 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11179 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11180 Invalid = true; 11181 11182 if (!Invalid && !ExDeclType->isDependentType() && 11183 RequireNonAbstractType(Loc, ExDeclType, 11184 diag::err_abstract_type_in_decl, 11185 AbstractVariableType)) 11186 Invalid = true; 11187 11188 // Only the non-fragile NeXT runtime currently supports C++ catches 11189 // of ObjC types, and no runtime supports catching ObjC types by value. 11190 if (!Invalid && getLangOpts().ObjC1) { 11191 QualType T = ExDeclType; 11192 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11193 T = RT->getPointeeType(); 11194 11195 if (T->isObjCObjectType()) { 11196 Diag(Loc, diag::err_objc_object_catch); 11197 Invalid = true; 11198 } else if (T->isObjCObjectPointerType()) { 11199 // FIXME: should this be a test for macosx-fragile specifically? 11200 if (getLangOpts().ObjCRuntime.isFragile()) 11201 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11202 } 11203 } 11204 11205 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11206 ExDeclType, TInfo, SC_None); 11207 ExDecl->setExceptionVariable(true); 11208 11209 // In ARC, infer 'retaining' for variables of retainable type. 11210 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11211 Invalid = true; 11212 11213 if (!Invalid && !ExDeclType->isDependentType()) { 11214 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11215 // Insulate this from anything else we might currently be parsing. 11216 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11217 11218 // C++ [except.handle]p16: 11219 // The object declared in an exception-declaration or, if the 11220 // exception-declaration does not specify a name, a temporary (12.2) is 11221 // copy-initialized (8.5) from the exception object. [...] 11222 // The object is destroyed when the handler exits, after the destruction 11223 // of any automatic objects initialized within the handler. 11224 // 11225 // We just pretend to initialize the object with itself, then make sure 11226 // it can be destroyed later. 11227 QualType initType = ExDeclType; 11228 11229 InitializedEntity entity = 11230 InitializedEntity::InitializeVariable(ExDecl); 11231 InitializationKind initKind = 11232 InitializationKind::CreateCopy(Loc, SourceLocation()); 11233 11234 Expr *opaqueValue = 11235 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11236 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11237 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11238 if (result.isInvalid()) 11239 Invalid = true; 11240 else { 11241 // If the constructor used was non-trivial, set this as the 11242 // "initializer". 11243 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>(); 11244 if (!construct->getConstructor()->isTrivial()) { 11245 Expr *init = MaybeCreateExprWithCleanups(construct); 11246 ExDecl->setInit(init); 11247 } 11248 11249 // And make sure it's destructable. 11250 FinalizeVarWithDestructor(ExDecl, recordType); 11251 } 11252 } 11253 } 11254 11255 if (Invalid) 11256 ExDecl->setInvalidDecl(); 11257 11258 return ExDecl; 11259} 11260 11261/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11262/// handler. 11263Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11264 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11265 bool Invalid = D.isInvalidType(); 11266 11267 // Check for unexpanded parameter packs. 11268 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11269 UPPC_ExceptionType)) { 11270 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11271 D.getIdentifierLoc()); 11272 Invalid = true; 11273 } 11274 11275 IdentifierInfo *II = D.getIdentifier(); 11276 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11277 LookupOrdinaryName, 11278 ForRedeclaration)) { 11279 // The scope should be freshly made just for us. There is just no way 11280 // it contains any previous declaration. 11281 assert(!S->isDeclScope(PrevDecl)); 11282 if (PrevDecl->isTemplateParameter()) { 11283 // Maybe we will complain about the shadowed template parameter. 11284 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11285 PrevDecl = 0; 11286 } 11287 } 11288 11289 if (D.getCXXScopeSpec().isSet() && !Invalid) { 11290 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 11291 << D.getCXXScopeSpec().getRange(); 11292 Invalid = true; 11293 } 11294 11295 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 11296 D.getLocStart(), 11297 D.getIdentifierLoc(), 11298 D.getIdentifier()); 11299 if (Invalid) 11300 ExDecl->setInvalidDecl(); 11301 11302 // Add the exception declaration into this scope. 11303 if (II) 11304 PushOnScopeChains(ExDecl, S); 11305 else 11306 CurContext->addDecl(ExDecl); 11307 11308 ProcessDeclAttributes(S, ExDecl, D); 11309 return ExDecl; 11310} 11311 11312Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11313 Expr *AssertExpr, 11314 Expr *AssertMessageExpr, 11315 SourceLocation RParenLoc) { 11316 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 11317 11318 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 11319 return 0; 11320 11321 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 11322 AssertMessage, RParenLoc, false); 11323} 11324 11325Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11326 Expr *AssertExpr, 11327 StringLiteral *AssertMessage, 11328 SourceLocation RParenLoc, 11329 bool Failed) { 11330 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 11331 !Failed) { 11332 // In a static_assert-declaration, the constant-expression shall be a 11333 // constant expression that can be contextually converted to bool. 11334 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 11335 if (Converted.isInvalid()) 11336 Failed = true; 11337 11338 llvm::APSInt Cond; 11339 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 11340 diag::err_static_assert_expression_is_not_constant, 11341 /*AllowFold=*/false).isInvalid()) 11342 Failed = true; 11343 11344 if (!Failed && !Cond) { 11345 SmallString<256> MsgBuffer; 11346 llvm::raw_svector_ostream Msg(MsgBuffer); 11347 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 11348 Diag(StaticAssertLoc, diag::err_static_assert_failed) 11349 << Msg.str() << AssertExpr->getSourceRange(); 11350 Failed = true; 11351 } 11352 } 11353 11354 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 11355 AssertExpr, AssertMessage, RParenLoc, 11356 Failed); 11357 11358 CurContext->addDecl(Decl); 11359 return Decl; 11360} 11361 11362/// \brief Perform semantic analysis of the given friend type declaration. 11363/// 11364/// \returns A friend declaration that. 11365FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 11366 SourceLocation FriendLoc, 11367 TypeSourceInfo *TSInfo) { 11368 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 11369 11370 QualType T = TSInfo->getType(); 11371 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 11372 11373 // C++03 [class.friend]p2: 11374 // An elaborated-type-specifier shall be used in a friend declaration 11375 // for a class.* 11376 // 11377 // * The class-key of the elaborated-type-specifier is required. 11378 if (!ActiveTemplateInstantiations.empty()) { 11379 // Do not complain about the form of friend template types during 11380 // template instantiation; we will already have complained when the 11381 // template was declared. 11382 } else { 11383 if (!T->isElaboratedTypeSpecifier()) { 11384 // If we evaluated the type to a record type, suggest putting 11385 // a tag in front. 11386 if (const RecordType *RT = T->getAs<RecordType>()) { 11387 RecordDecl *RD = RT->getDecl(); 11388 11389 std::string InsertionText = std::string(" ") + RD->getKindName(); 11390 11391 Diag(TypeRange.getBegin(), 11392 getLangOpts().CPlusPlus11 ? 11393 diag::warn_cxx98_compat_unelaborated_friend_type : 11394 diag::ext_unelaborated_friend_type) 11395 << (unsigned) RD->getTagKind() 11396 << T 11397 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 11398 InsertionText); 11399 } else { 11400 Diag(FriendLoc, 11401 getLangOpts().CPlusPlus11 ? 11402 diag::warn_cxx98_compat_nonclass_type_friend : 11403 diag::ext_nonclass_type_friend) 11404 << T 11405 << TypeRange; 11406 } 11407 } else if (T->getAs<EnumType>()) { 11408 Diag(FriendLoc, 11409 getLangOpts().CPlusPlus11 ? 11410 diag::warn_cxx98_compat_enum_friend : 11411 diag::ext_enum_friend) 11412 << T 11413 << TypeRange; 11414 } 11415 11416 // C++11 [class.friend]p3: 11417 // A friend declaration that does not declare a function shall have one 11418 // of the following forms: 11419 // friend elaborated-type-specifier ; 11420 // friend simple-type-specifier ; 11421 // friend typename-specifier ; 11422 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 11423 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 11424 } 11425 11426 // If the type specifier in a friend declaration designates a (possibly 11427 // cv-qualified) class type, that class is declared as a friend; otherwise, 11428 // the friend declaration is ignored. 11429 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 11430} 11431 11432/// Handle a friend tag declaration where the scope specifier was 11433/// templated. 11434Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 11435 unsigned TagSpec, SourceLocation TagLoc, 11436 CXXScopeSpec &SS, 11437 IdentifierInfo *Name, 11438 SourceLocation NameLoc, 11439 AttributeList *Attr, 11440 MultiTemplateParamsArg TempParamLists) { 11441 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11442 11443 bool isExplicitSpecialization = false; 11444 bool Invalid = false; 11445 11446 if (TemplateParameterList *TemplateParams = 11447 MatchTemplateParametersToScopeSpecifier( 11448 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true, 11449 isExplicitSpecialization, Invalid)) { 11450 if (TemplateParams->size() > 0) { 11451 // This is a declaration of a class template. 11452 if (Invalid) 11453 return 0; 11454 11455 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 11456 SS, Name, NameLoc, Attr, 11457 TemplateParams, AS_public, 11458 /*ModulePrivateLoc=*/SourceLocation(), 11459 TempParamLists.size() - 1, 11460 TempParamLists.data()).take(); 11461 } else { 11462 // The "template<>" header is extraneous. 11463 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11464 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11465 isExplicitSpecialization = true; 11466 } 11467 } 11468 11469 if (Invalid) return 0; 11470 11471 bool isAllExplicitSpecializations = true; 11472 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 11473 if (TempParamLists[I]->size()) { 11474 isAllExplicitSpecializations = false; 11475 break; 11476 } 11477 } 11478 11479 // FIXME: don't ignore attributes. 11480 11481 // If it's explicit specializations all the way down, just forget 11482 // about the template header and build an appropriate non-templated 11483 // friend. TODO: for source fidelity, remember the headers. 11484 if (isAllExplicitSpecializations) { 11485 if (SS.isEmpty()) { 11486 bool Owned = false; 11487 bool IsDependent = false; 11488 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 11489 Attr, AS_public, 11490 /*ModulePrivateLoc=*/SourceLocation(), 11491 MultiTemplateParamsArg(), Owned, IsDependent, 11492 /*ScopedEnumKWLoc=*/SourceLocation(), 11493 /*ScopedEnumUsesClassTag=*/false, 11494 /*UnderlyingType=*/TypeResult()); 11495 } 11496 11497 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11498 ElaboratedTypeKeyword Keyword 11499 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11500 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 11501 *Name, NameLoc); 11502 if (T.isNull()) 11503 return 0; 11504 11505 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11506 if (isa<DependentNameType>(T)) { 11507 DependentNameTypeLoc TL = 11508 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11509 TL.setElaboratedKeywordLoc(TagLoc); 11510 TL.setQualifierLoc(QualifierLoc); 11511 TL.setNameLoc(NameLoc); 11512 } else { 11513 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11514 TL.setElaboratedKeywordLoc(TagLoc); 11515 TL.setQualifierLoc(QualifierLoc); 11516 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 11517 } 11518 11519 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11520 TSI, FriendLoc, TempParamLists); 11521 Friend->setAccess(AS_public); 11522 CurContext->addDecl(Friend); 11523 return Friend; 11524 } 11525 11526 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 11527 11528 11529 11530 // Handle the case of a templated-scope friend class. e.g. 11531 // template <class T> class A<T>::B; 11532 // FIXME: we don't support these right now. 11533 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11534 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 11535 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11536 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11537 TL.setElaboratedKeywordLoc(TagLoc); 11538 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11539 TL.setNameLoc(NameLoc); 11540 11541 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11542 TSI, FriendLoc, TempParamLists); 11543 Friend->setAccess(AS_public); 11544 Friend->setUnsupportedFriend(true); 11545 CurContext->addDecl(Friend); 11546 return Friend; 11547} 11548 11549 11550/// Handle a friend type declaration. This works in tandem with 11551/// ActOnTag. 11552/// 11553/// Notes on friend class templates: 11554/// 11555/// We generally treat friend class declarations as if they were 11556/// declaring a class. So, for example, the elaborated type specifier 11557/// in a friend declaration is required to obey the restrictions of a 11558/// class-head (i.e. no typedefs in the scope chain), template 11559/// parameters are required to match up with simple template-ids, &c. 11560/// However, unlike when declaring a template specialization, it's 11561/// okay to refer to a template specialization without an empty 11562/// template parameter declaration, e.g. 11563/// friend class A<T>::B<unsigned>; 11564/// We permit this as a special case; if there are any template 11565/// parameters present at all, require proper matching, i.e. 11566/// template <> template \<class T> friend class A<int>::B; 11567Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 11568 MultiTemplateParamsArg TempParams) { 11569 SourceLocation Loc = DS.getLocStart(); 11570 11571 assert(DS.isFriendSpecified()); 11572 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11573 11574 // Try to convert the decl specifier to a type. This works for 11575 // friend templates because ActOnTag never produces a ClassTemplateDecl 11576 // for a TUK_Friend. 11577 Declarator TheDeclarator(DS, Declarator::MemberContext); 11578 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11579 QualType T = TSI->getType(); 11580 if (TheDeclarator.isInvalidType()) 11581 return 0; 11582 11583 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11584 return 0; 11585 11586 // This is definitely an error in C++98. It's probably meant to 11587 // be forbidden in C++0x, too, but the specification is just 11588 // poorly written. 11589 // 11590 // The problem is with declarations like the following: 11591 // template <T> friend A<T>::foo; 11592 // where deciding whether a class C is a friend or not now hinges 11593 // on whether there exists an instantiation of A that causes 11594 // 'foo' to equal C. There are restrictions on class-heads 11595 // (which we declare (by fiat) elaborated friend declarations to 11596 // be) that makes this tractable. 11597 // 11598 // FIXME: handle "template <> friend class A<T>;", which 11599 // is possibly well-formed? Who even knows? 11600 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11601 Diag(Loc, diag::err_tagless_friend_type_template) 11602 << DS.getSourceRange(); 11603 return 0; 11604 } 11605 11606 // C++98 [class.friend]p1: A friend of a class is a function 11607 // or class that is not a member of the class . . . 11608 // This is fixed in DR77, which just barely didn't make the C++03 11609 // deadline. It's also a very silly restriction that seriously 11610 // affects inner classes and which nobody else seems to implement; 11611 // thus we never diagnose it, not even in -pedantic. 11612 // 11613 // But note that we could warn about it: it's always useless to 11614 // friend one of your own members (it's not, however, worthless to 11615 // friend a member of an arbitrary specialization of your template). 11616 11617 Decl *D; 11618 if (unsigned NumTempParamLists = TempParams.size()) 11619 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11620 NumTempParamLists, 11621 TempParams.data(), 11622 TSI, 11623 DS.getFriendSpecLoc()); 11624 else 11625 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11626 11627 if (!D) 11628 return 0; 11629 11630 D->setAccess(AS_public); 11631 CurContext->addDecl(D); 11632 11633 return D; 11634} 11635 11636NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11637 MultiTemplateParamsArg TemplateParams) { 11638 const DeclSpec &DS = D.getDeclSpec(); 11639 11640 assert(DS.isFriendSpecified()); 11641 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11642 11643 SourceLocation Loc = D.getIdentifierLoc(); 11644 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11645 11646 // C++ [class.friend]p1 11647 // A friend of a class is a function or class.... 11648 // Note that this sees through typedefs, which is intended. 11649 // It *doesn't* see through dependent types, which is correct 11650 // according to [temp.arg.type]p3: 11651 // If a declaration acquires a function type through a 11652 // type dependent on a template-parameter and this causes 11653 // a declaration that does not use the syntactic form of a 11654 // function declarator to have a function type, the program 11655 // is ill-formed. 11656 if (!TInfo->getType()->isFunctionType()) { 11657 Diag(Loc, diag::err_unexpected_friend); 11658 11659 // It might be worthwhile to try to recover by creating an 11660 // appropriate declaration. 11661 return 0; 11662 } 11663 11664 // C++ [namespace.memdef]p3 11665 // - If a friend declaration in a non-local class first declares a 11666 // class or function, the friend class or function is a member 11667 // of the innermost enclosing namespace. 11668 // - The name of the friend is not found by simple name lookup 11669 // until a matching declaration is provided in that namespace 11670 // scope (either before or after the class declaration granting 11671 // friendship). 11672 // - If a friend function is called, its name may be found by the 11673 // name lookup that considers functions from namespaces and 11674 // classes associated with the types of the function arguments. 11675 // - When looking for a prior declaration of a class or a function 11676 // declared as a friend, scopes outside the innermost enclosing 11677 // namespace scope are not considered. 11678 11679 CXXScopeSpec &SS = D.getCXXScopeSpec(); 11680 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 11681 DeclarationName Name = NameInfo.getName(); 11682 assert(Name); 11683 11684 // Check for unexpanded parameter packs. 11685 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 11686 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 11687 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 11688 return 0; 11689 11690 // The context we found the declaration in, or in which we should 11691 // create the declaration. 11692 DeclContext *DC; 11693 Scope *DCScope = S; 11694 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11695 ForRedeclaration); 11696 11697 // There are five cases here. 11698 // - There's no scope specifier and we're in a local class. Only look 11699 // for functions declared in the immediately-enclosing block scope. 11700 // We recover from invalid scope qualifiers as if they just weren't there. 11701 FunctionDecl *FunctionContainingLocalClass = 0; 11702 if ((SS.isInvalid() || !SS.isSet()) && 11703 (FunctionContainingLocalClass = 11704 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 11705 // C++11 [class.friend]p11: 11706 // If a friend declaration appears in a local class and the name 11707 // specified is an unqualified name, a prior declaration is 11708 // looked up without considering scopes that are outside the 11709 // innermost enclosing non-class scope. For a friend function 11710 // declaration, if there is no prior declaration, the program is 11711 // ill-formed. 11712 11713 // Find the innermost enclosing non-class scope. This is the block 11714 // scope containing the local class definition (or for a nested class, 11715 // the outer local class). 11716 DCScope = S->getFnParent(); 11717 11718 // Look up the function name in the scope. 11719 Previous.clear(LookupLocalFriendName); 11720 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 11721 11722 if (!Previous.empty()) { 11723 // All possible previous declarations must have the same context: 11724 // either they were declared at block scope or they are members of 11725 // one of the enclosing local classes. 11726 DC = Previous.getRepresentativeDecl()->getDeclContext(); 11727 } else { 11728 // This is ill-formed, but provide the context that we would have 11729 // declared the function in, if we were permitted to, for error recovery. 11730 DC = FunctionContainingLocalClass; 11731 } 11732 adjustContextForLocalExternDecl(DC); 11733 11734 // C++ [class.friend]p6: 11735 // A function can be defined in a friend declaration of a class if and 11736 // only if the class is a non-local class (9.8), the function name is 11737 // unqualified, and the function has namespace scope. 11738 if (D.isFunctionDefinition()) { 11739 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11740 } 11741 11742 // - There's no scope specifier, in which case we just go to the 11743 // appropriate scope and look for a function or function template 11744 // there as appropriate. 11745 } else if (SS.isInvalid() || !SS.isSet()) { 11746 // C++11 [namespace.memdef]p3: 11747 // If the name in a friend declaration is neither qualified nor 11748 // a template-id and the declaration is a function or an 11749 // elaborated-type-specifier, the lookup to determine whether 11750 // the entity has been previously declared shall not consider 11751 // any scopes outside the innermost enclosing namespace. 11752 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 11753 11754 // Find the appropriate context according to the above. 11755 DC = CurContext; 11756 11757 // Skip class contexts. If someone can cite chapter and verse 11758 // for this behavior, that would be nice --- it's what GCC and 11759 // EDG do, and it seems like a reasonable intent, but the spec 11760 // really only says that checks for unqualified existing 11761 // declarations should stop at the nearest enclosing namespace, 11762 // not that they should only consider the nearest enclosing 11763 // namespace. 11764 while (DC->isRecord()) 11765 DC = DC->getParent(); 11766 11767 DeclContext *LookupDC = DC; 11768 while (LookupDC->isTransparentContext()) 11769 LookupDC = LookupDC->getParent(); 11770 11771 while (true) { 11772 LookupQualifiedName(Previous, LookupDC); 11773 11774 if (!Previous.empty()) { 11775 DC = LookupDC; 11776 break; 11777 } 11778 11779 if (isTemplateId) { 11780 if (isa<TranslationUnitDecl>(LookupDC)) break; 11781 } else { 11782 if (LookupDC->isFileContext()) break; 11783 } 11784 LookupDC = LookupDC->getParent(); 11785 } 11786 11787 DCScope = getScopeForDeclContext(S, DC); 11788 11789 // - There's a non-dependent scope specifier, in which case we 11790 // compute it and do a previous lookup there for a function 11791 // or function template. 11792 } else if (!SS.getScopeRep()->isDependent()) { 11793 DC = computeDeclContext(SS); 11794 if (!DC) return 0; 11795 11796 if (RequireCompleteDeclContext(SS, DC)) return 0; 11797 11798 LookupQualifiedName(Previous, DC); 11799 11800 // Ignore things found implicitly in the wrong scope. 11801 // TODO: better diagnostics for this case. Suggesting the right 11802 // qualified scope would be nice... 11803 LookupResult::Filter F = Previous.makeFilter(); 11804 while (F.hasNext()) { 11805 NamedDecl *D = F.next(); 11806 if (!DC->InEnclosingNamespaceSetOf( 11807 D->getDeclContext()->getRedeclContext())) 11808 F.erase(); 11809 } 11810 F.done(); 11811 11812 if (Previous.empty()) { 11813 D.setInvalidType(); 11814 Diag(Loc, diag::err_qualified_friend_not_found) 11815 << Name << TInfo->getType(); 11816 return 0; 11817 } 11818 11819 // C++ [class.friend]p1: A friend of a class is a function or 11820 // class that is not a member of the class . . . 11821 if (DC->Equals(CurContext)) 11822 Diag(DS.getFriendSpecLoc(), 11823 getLangOpts().CPlusPlus11 ? 11824 diag::warn_cxx98_compat_friend_is_member : 11825 diag::err_friend_is_member); 11826 11827 if (D.isFunctionDefinition()) { 11828 // C++ [class.friend]p6: 11829 // A function can be defined in a friend declaration of a class if and 11830 // only if the class is a non-local class (9.8), the function name is 11831 // unqualified, and the function has namespace scope. 11832 SemaDiagnosticBuilder DB 11833 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 11834 11835 DB << SS.getScopeRep(); 11836 if (DC->isFileContext()) 11837 DB << FixItHint::CreateRemoval(SS.getRange()); 11838 SS.clear(); 11839 } 11840 11841 // - There's a scope specifier that does not match any template 11842 // parameter lists, in which case we use some arbitrary context, 11843 // create a method or method template, and wait for instantiation. 11844 // - There's a scope specifier that does match some template 11845 // parameter lists, which we don't handle right now. 11846 } else { 11847 if (D.isFunctionDefinition()) { 11848 // C++ [class.friend]p6: 11849 // A function can be defined in a friend declaration of a class if and 11850 // only if the class is a non-local class (9.8), the function name is 11851 // unqualified, and the function has namespace scope. 11852 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 11853 << SS.getScopeRep(); 11854 } 11855 11856 DC = CurContext; 11857 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 11858 } 11859 11860 if (!DC->isRecord()) { 11861 // This implies that it has to be an operator or function. 11862 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 11863 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 11864 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 11865 Diag(Loc, diag::err_introducing_special_friend) << 11866 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 11867 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 11868 return 0; 11869 } 11870 } 11871 11872 // FIXME: This is an egregious hack to cope with cases where the scope stack 11873 // does not contain the declaration context, i.e., in an out-of-line 11874 // definition of a class. 11875 Scope FakeDCScope(S, Scope::DeclScope, Diags); 11876 if (!DCScope) { 11877 FakeDCScope.setEntity(DC); 11878 DCScope = &FakeDCScope; 11879 } 11880 11881 bool AddToScope = true; 11882 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 11883 TemplateParams, AddToScope); 11884 if (!ND) return 0; 11885 11886 assert(ND->getLexicalDeclContext() == CurContext); 11887 11888 // If we performed typo correction, we might have added a scope specifier 11889 // and changed the decl context. 11890 DC = ND->getDeclContext(); 11891 11892 // Add the function declaration to the appropriate lookup tables, 11893 // adjusting the redeclarations list as necessary. We don't 11894 // want to do this yet if the friending class is dependent. 11895 // 11896 // Also update the scope-based lookup if the target context's 11897 // lookup context is in lexical scope. 11898 if (!CurContext->isDependentContext()) { 11899 DC = DC->getRedeclContext(); 11900 DC->makeDeclVisibleInContext(ND); 11901 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11902 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 11903 } 11904 11905 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 11906 D.getIdentifierLoc(), ND, 11907 DS.getFriendSpecLoc()); 11908 FrD->setAccess(AS_public); 11909 CurContext->addDecl(FrD); 11910 11911 if (ND->isInvalidDecl()) { 11912 FrD->setInvalidDecl(); 11913 } else { 11914 if (DC->isRecord()) CheckFriendAccess(ND); 11915 11916 FunctionDecl *FD; 11917 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 11918 FD = FTD->getTemplatedDecl(); 11919 else 11920 FD = cast<FunctionDecl>(ND); 11921 11922 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 11923 // default argument expression, that declaration shall be a definition 11924 // and shall be the only declaration of the function or function 11925 // template in the translation unit. 11926 if (functionDeclHasDefaultArgument(FD)) { 11927 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 11928 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 11929 Diag(OldFD->getLocation(), diag::note_previous_declaration); 11930 } else if (!D.isFunctionDefinition()) 11931 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 11932 } 11933 11934 // Mark templated-scope function declarations as unsupported. 11935 if (FD->getNumTemplateParameterLists()) 11936 FrD->setUnsupportedFriend(true); 11937 } 11938 11939 return ND; 11940} 11941 11942void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 11943 AdjustDeclIfTemplate(Dcl); 11944 11945 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 11946 if (!Fn) { 11947 Diag(DelLoc, diag::err_deleted_non_function); 11948 return; 11949 } 11950 11951 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 11952 // Don't consider the implicit declaration we generate for explicit 11953 // specializations. FIXME: Do not generate these implicit declarations. 11954 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization 11955 || Prev->getPreviousDecl()) && !Prev->isDefined()) { 11956 Diag(DelLoc, diag::err_deleted_decl_not_first); 11957 Diag(Prev->getLocation(), diag::note_previous_declaration); 11958 } 11959 // If the declaration wasn't the first, we delete the function anyway for 11960 // recovery. 11961 Fn = Fn->getCanonicalDecl(); 11962 } 11963 11964 if (Fn->isDeleted()) 11965 return; 11966 11967 // See if we're deleting a function which is already known to override a 11968 // non-deleted virtual function. 11969 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 11970 bool IssuedDiagnostic = false; 11971 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 11972 E = MD->end_overridden_methods(); 11973 I != E; ++I) { 11974 if (!(*MD->begin_overridden_methods())->isDeleted()) { 11975 if (!IssuedDiagnostic) { 11976 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 11977 IssuedDiagnostic = true; 11978 } 11979 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 11980 } 11981 } 11982 } 11983 11984 Fn->setDeletedAsWritten(); 11985} 11986 11987void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 11988 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 11989 11990 if (MD) { 11991 if (MD->getParent()->isDependentType()) { 11992 MD->setDefaulted(); 11993 MD->setExplicitlyDefaulted(); 11994 return; 11995 } 11996 11997 CXXSpecialMember Member = getSpecialMember(MD); 11998 if (Member == CXXInvalid) { 11999 if (!MD->isInvalidDecl()) 12000 Diag(DefaultLoc, diag::err_default_special_members); 12001 return; 12002 } 12003 12004 MD->setDefaulted(); 12005 MD->setExplicitlyDefaulted(); 12006 12007 // If this definition appears within the record, do the checking when 12008 // the record is complete. 12009 const FunctionDecl *Primary = MD; 12010 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12011 // Find the uninstantiated declaration that actually had the '= default' 12012 // on it. 12013 Pattern->isDefined(Primary); 12014 12015 // If the method was defaulted on its first declaration, we will have 12016 // already performed the checking in CheckCompletedCXXClass. Such a 12017 // declaration doesn't trigger an implicit definition. 12018 if (Primary == Primary->getCanonicalDecl()) 12019 return; 12020 12021 CheckExplicitlyDefaultedSpecialMember(MD); 12022 12023 // The exception specification is needed because we are defining the 12024 // function. 12025 ResolveExceptionSpec(DefaultLoc, 12026 MD->getType()->castAs<FunctionProtoType>()); 12027 12028 if (MD->isInvalidDecl()) 12029 return; 12030 12031 switch (Member) { 12032 case CXXDefaultConstructor: 12033 DefineImplicitDefaultConstructor(DefaultLoc, 12034 cast<CXXConstructorDecl>(MD)); 12035 break; 12036 case CXXCopyConstructor: 12037 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12038 break; 12039 case CXXCopyAssignment: 12040 DefineImplicitCopyAssignment(DefaultLoc, MD); 12041 break; 12042 case CXXDestructor: 12043 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12044 break; 12045 case CXXMoveConstructor: 12046 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12047 break; 12048 case CXXMoveAssignment: 12049 DefineImplicitMoveAssignment(DefaultLoc, MD); 12050 break; 12051 case CXXInvalid: 12052 llvm_unreachable("Invalid special member."); 12053 } 12054 } else { 12055 Diag(DefaultLoc, diag::err_default_special_members); 12056 } 12057} 12058 12059static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12060 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12061 Stmt *SubStmt = *CI; 12062 if (!SubStmt) 12063 continue; 12064 if (isa<ReturnStmt>(SubStmt)) 12065 Self.Diag(SubStmt->getLocStart(), 12066 diag::err_return_in_constructor_handler); 12067 if (!isa<Expr>(SubStmt)) 12068 SearchForReturnInStmt(Self, SubStmt); 12069 } 12070} 12071 12072void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12073 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12074 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12075 SearchForReturnInStmt(*this, Handler); 12076 } 12077} 12078 12079bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12080 const CXXMethodDecl *Old) { 12081 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12082 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12083 12084 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12085 12086 // If the calling conventions match, everything is fine 12087 if (NewCC == OldCC) 12088 return false; 12089 12090 Diag(New->getLocation(), 12091 diag::err_conflicting_overriding_cc_attributes) 12092 << New->getDeclName() << New->getType() << Old->getType(); 12093 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12094 return true; 12095} 12096 12097bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12098 const CXXMethodDecl *Old) { 12099 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 12100 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 12101 12102 if (Context.hasSameType(NewTy, OldTy) || 12103 NewTy->isDependentType() || OldTy->isDependentType()) 12104 return false; 12105 12106 // Check if the return types are covariant 12107 QualType NewClassTy, OldClassTy; 12108 12109 /// Both types must be pointers or references to classes. 12110 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12111 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12112 NewClassTy = NewPT->getPointeeType(); 12113 OldClassTy = OldPT->getPointeeType(); 12114 } 12115 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12116 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12117 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12118 NewClassTy = NewRT->getPointeeType(); 12119 OldClassTy = OldRT->getPointeeType(); 12120 } 12121 } 12122 } 12123 12124 // The return types aren't either both pointers or references to a class type. 12125 if (NewClassTy.isNull()) { 12126 Diag(New->getLocation(), 12127 diag::err_different_return_type_for_overriding_virtual_function) 12128 << New->getDeclName() << NewTy << OldTy; 12129 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12130 12131 return true; 12132 } 12133 12134 // C++ [class.virtual]p6: 12135 // If the return type of D::f differs from the return type of B::f, the 12136 // class type in the return type of D::f shall be complete at the point of 12137 // declaration of D::f or shall be the class type D. 12138 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12139 if (!RT->isBeingDefined() && 12140 RequireCompleteType(New->getLocation(), NewClassTy, 12141 diag::err_covariant_return_incomplete, 12142 New->getDeclName())) 12143 return true; 12144 } 12145 12146 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12147 // Check if the new class derives from the old class. 12148 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12149 Diag(New->getLocation(), 12150 diag::err_covariant_return_not_derived) 12151 << New->getDeclName() << NewTy << OldTy; 12152 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12153 return true; 12154 } 12155 12156 // Check if we the conversion from derived to base is valid. 12157 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 12158 diag::err_covariant_return_inaccessible_base, 12159 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12160 // FIXME: Should this point to the return type? 12161 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 12162 // FIXME: this note won't trigger for delayed access control 12163 // diagnostics, and it's impossible to get an undelayed error 12164 // here from access control during the original parse because 12165 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12166 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12167 return true; 12168 } 12169 } 12170 12171 // The qualifiers of the return types must be the same. 12172 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12173 Diag(New->getLocation(), 12174 diag::err_covariant_return_type_different_qualifications) 12175 << New->getDeclName() << NewTy << OldTy; 12176 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12177 return true; 12178 }; 12179 12180 12181 // The new class type must have the same or less qualifiers as the old type. 12182 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12183 Diag(New->getLocation(), 12184 diag::err_covariant_return_type_class_type_more_qualified) 12185 << New->getDeclName() << NewTy << OldTy; 12186 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12187 return true; 12188 }; 12189 12190 return false; 12191} 12192 12193/// \brief Mark the given method pure. 12194/// 12195/// \param Method the method to be marked pure. 12196/// 12197/// \param InitRange the source range that covers the "0" initializer. 12198bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12199 SourceLocation EndLoc = InitRange.getEnd(); 12200 if (EndLoc.isValid()) 12201 Method->setRangeEnd(EndLoc); 12202 12203 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12204 Method->setPure(); 12205 return false; 12206 } 12207 12208 if (!Method->isInvalidDecl()) 12209 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12210 << Method->getDeclName() << InitRange; 12211 return true; 12212} 12213 12214/// \brief Determine whether the given declaration is a static data member. 12215static bool isStaticDataMember(const Decl *D) { 12216 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12217 return Var->isStaticDataMember(); 12218 12219 return false; 12220} 12221 12222/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12223/// an initializer for the out-of-line declaration 'Dcl'. The scope 12224/// is a fresh scope pushed for just this purpose. 12225/// 12226/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12227/// static data member of class X, names should be looked up in the scope of 12228/// class X. 12229void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12230 // If there is no declaration, there was an error parsing it. 12231 if (D == 0 || D->isInvalidDecl()) return; 12232 12233 // We should only get called for declarations with scope specifiers, like: 12234 // int foo::bar; 12235 assert(D->isOutOfLine()); 12236 EnterDeclaratorContext(S, D->getDeclContext()); 12237 12238 // If we are parsing the initializer for a static data member, push a 12239 // new expression evaluation context that is associated with this static 12240 // data member. 12241 if (isStaticDataMember(D)) 12242 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12243} 12244 12245/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12246/// initializer for the out-of-line declaration 'D'. 12247void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12248 // If there is no declaration, there was an error parsing it. 12249 if (D == 0 || D->isInvalidDecl()) return; 12250 12251 if (isStaticDataMember(D)) 12252 PopExpressionEvaluationContext(); 12253 12254 assert(D->isOutOfLine()); 12255 ExitDeclaratorContext(S); 12256} 12257 12258/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 12259/// C++ if/switch/while/for statement. 12260/// e.g: "if (int x = f()) {...}" 12261DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 12262 // C++ 6.4p2: 12263 // The declarator shall not specify a function or an array. 12264 // The type-specifier-seq shall not contain typedef and shall not declare a 12265 // new class or enumeration. 12266 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 12267 "Parser allowed 'typedef' as storage class of condition decl."); 12268 12269 Decl *Dcl = ActOnDeclarator(S, D); 12270 if (!Dcl) 12271 return true; 12272 12273 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 12274 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 12275 << D.getSourceRange(); 12276 return true; 12277 } 12278 12279 return Dcl; 12280} 12281 12282void Sema::LoadExternalVTableUses() { 12283 if (!ExternalSource) 12284 return; 12285 12286 SmallVector<ExternalVTableUse, 4> VTables; 12287 ExternalSource->ReadUsedVTables(VTables); 12288 SmallVector<VTableUse, 4> NewUses; 12289 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 12290 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 12291 = VTablesUsed.find(VTables[I].Record); 12292 // Even if a definition wasn't required before, it may be required now. 12293 if (Pos != VTablesUsed.end()) { 12294 if (!Pos->second && VTables[I].DefinitionRequired) 12295 Pos->second = true; 12296 continue; 12297 } 12298 12299 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 12300 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 12301 } 12302 12303 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 12304} 12305 12306void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 12307 bool DefinitionRequired) { 12308 // Ignore any vtable uses in unevaluated operands or for classes that do 12309 // not have a vtable. 12310 if (!Class->isDynamicClass() || Class->isDependentContext() || 12311 CurContext->isDependentContext() || isUnevaluatedContext()) 12312 return; 12313 12314 // Try to insert this class into the map. 12315 LoadExternalVTableUses(); 12316 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12317 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 12318 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 12319 if (!Pos.second) { 12320 // If we already had an entry, check to see if we are promoting this vtable 12321 // to required a definition. If so, we need to reappend to the VTableUses 12322 // list, since we may have already processed the first entry. 12323 if (DefinitionRequired && !Pos.first->second) { 12324 Pos.first->second = true; 12325 } else { 12326 // Otherwise, we can early exit. 12327 return; 12328 } 12329 } 12330 12331 // Local classes need to have their virtual members marked 12332 // immediately. For all other classes, we mark their virtual members 12333 // at the end of the translation unit. 12334 if (Class->isLocalClass()) 12335 MarkVirtualMembersReferenced(Loc, Class); 12336 else 12337 VTableUses.push_back(std::make_pair(Class, Loc)); 12338} 12339 12340bool Sema::DefineUsedVTables() { 12341 LoadExternalVTableUses(); 12342 if (VTableUses.empty()) 12343 return false; 12344 12345 // Note: The VTableUses vector could grow as a result of marking 12346 // the members of a class as "used", so we check the size each 12347 // time through the loop and prefer indices (which are stable) to 12348 // iterators (which are not). 12349 bool DefinedAnything = false; 12350 for (unsigned I = 0; I != VTableUses.size(); ++I) { 12351 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 12352 if (!Class) 12353 continue; 12354 12355 SourceLocation Loc = VTableUses[I].second; 12356 12357 bool DefineVTable = true; 12358 12359 // If this class has a key function, but that key function is 12360 // defined in another translation unit, we don't need to emit the 12361 // vtable even though we're using it. 12362 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 12363 if (KeyFunction && !KeyFunction->hasBody()) { 12364 // The key function is in another translation unit. 12365 DefineVTable = false; 12366 TemplateSpecializationKind TSK = 12367 KeyFunction->getTemplateSpecializationKind(); 12368 assert(TSK != TSK_ExplicitInstantiationDefinition && 12369 TSK != TSK_ImplicitInstantiation && 12370 "Instantiations don't have key functions"); 12371 (void)TSK; 12372 } else if (!KeyFunction) { 12373 // If we have a class with no key function that is the subject 12374 // of an explicit instantiation declaration, suppress the 12375 // vtable; it will live with the explicit instantiation 12376 // definition. 12377 bool IsExplicitInstantiationDeclaration 12378 = Class->getTemplateSpecializationKind() 12379 == TSK_ExplicitInstantiationDeclaration; 12380 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 12381 REnd = Class->redecls_end(); 12382 R != REnd; ++R) { 12383 TemplateSpecializationKind TSK 12384 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 12385 if (TSK == TSK_ExplicitInstantiationDeclaration) 12386 IsExplicitInstantiationDeclaration = true; 12387 else if (TSK == TSK_ExplicitInstantiationDefinition) { 12388 IsExplicitInstantiationDeclaration = false; 12389 break; 12390 } 12391 } 12392 12393 if (IsExplicitInstantiationDeclaration) 12394 DefineVTable = false; 12395 } 12396 12397 // The exception specifications for all virtual members may be needed even 12398 // if we are not providing an authoritative form of the vtable in this TU. 12399 // We may choose to emit it available_externally anyway. 12400 if (!DefineVTable) { 12401 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 12402 continue; 12403 } 12404 12405 // Mark all of the virtual members of this class as referenced, so 12406 // that we can build a vtable. Then, tell the AST consumer that a 12407 // vtable for this class is required. 12408 DefinedAnything = true; 12409 MarkVirtualMembersReferenced(Loc, Class); 12410 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12411 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 12412 12413 // Optionally warn if we're emitting a weak vtable. 12414 if (Class->isExternallyVisible() && 12415 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 12416 const FunctionDecl *KeyFunctionDef = 0; 12417 if (!KeyFunction || 12418 (KeyFunction->hasBody(KeyFunctionDef) && 12419 KeyFunctionDef->isInlined())) 12420 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 12421 TSK_ExplicitInstantiationDefinition 12422 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 12423 << Class; 12424 } 12425 } 12426 VTableUses.clear(); 12427 12428 return DefinedAnything; 12429} 12430 12431void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 12432 const CXXRecordDecl *RD) { 12433 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 12434 E = RD->method_end(); I != E; ++I) 12435 if ((*I)->isVirtual() && !(*I)->isPure()) 12436 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 12437} 12438 12439void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 12440 const CXXRecordDecl *RD) { 12441 // Mark all functions which will appear in RD's vtable as used. 12442 CXXFinalOverriderMap FinalOverriders; 12443 RD->getFinalOverriders(FinalOverriders); 12444 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 12445 E = FinalOverriders.end(); 12446 I != E; ++I) { 12447 for (OverridingMethods::const_iterator OI = I->second.begin(), 12448 OE = I->second.end(); 12449 OI != OE; ++OI) { 12450 assert(OI->second.size() > 0 && "no final overrider"); 12451 CXXMethodDecl *Overrider = OI->second.front().Method; 12452 12453 // C++ [basic.def.odr]p2: 12454 // [...] A virtual member function is used if it is not pure. [...] 12455 if (!Overrider->isPure()) 12456 MarkFunctionReferenced(Loc, Overrider); 12457 } 12458 } 12459 12460 // Only classes that have virtual bases need a VTT. 12461 if (RD->getNumVBases() == 0) 12462 return; 12463 12464 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 12465 e = RD->bases_end(); i != e; ++i) { 12466 const CXXRecordDecl *Base = 12467 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 12468 if (Base->getNumVBases() == 0) 12469 continue; 12470 MarkVirtualMembersReferenced(Loc, Base); 12471 } 12472} 12473 12474/// SetIvarInitializers - This routine builds initialization ASTs for the 12475/// Objective-C implementation whose ivars need be initialized. 12476void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 12477 if (!getLangOpts().CPlusPlus) 12478 return; 12479 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 12480 SmallVector<ObjCIvarDecl*, 8> ivars; 12481 CollectIvarsToConstructOrDestruct(OID, ivars); 12482 if (ivars.empty()) 12483 return; 12484 SmallVector<CXXCtorInitializer*, 32> AllToInit; 12485 for (unsigned i = 0; i < ivars.size(); i++) { 12486 FieldDecl *Field = ivars[i]; 12487 if (Field->isInvalidDecl()) 12488 continue; 12489 12490 CXXCtorInitializer *Member; 12491 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 12492 InitializationKind InitKind = 12493 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 12494 12495 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 12496 ExprResult MemberInit = 12497 InitSeq.Perform(*this, InitEntity, InitKind, None); 12498 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 12499 // Note, MemberInit could actually come back empty if no initialization 12500 // is required (e.g., because it would call a trivial default constructor) 12501 if (!MemberInit.get() || MemberInit.isInvalid()) 12502 continue; 12503 12504 Member = 12505 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 12506 SourceLocation(), 12507 MemberInit.takeAs<Expr>(), 12508 SourceLocation()); 12509 AllToInit.push_back(Member); 12510 12511 // Be sure that the destructor is accessible and is marked as referenced. 12512 if (const RecordType *RecordTy 12513 = Context.getBaseElementType(Field->getType()) 12514 ->getAs<RecordType>()) { 12515 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 12516 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 12517 MarkFunctionReferenced(Field->getLocation(), Destructor); 12518 CheckDestructorAccess(Field->getLocation(), Destructor, 12519 PDiag(diag::err_access_dtor_ivar) 12520 << Context.getBaseElementType(Field->getType())); 12521 } 12522 } 12523 } 12524 ObjCImplementation->setIvarInitializers(Context, 12525 AllToInit.data(), AllToInit.size()); 12526 } 12527} 12528 12529static 12530void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 12531 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 12532 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 12533 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 12534 Sema &S) { 12535 if (Ctor->isInvalidDecl()) 12536 return; 12537 12538 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 12539 12540 // Target may not be determinable yet, for instance if this is a dependent 12541 // call in an uninstantiated template. 12542 if (Target) { 12543 const FunctionDecl *FNTarget = 0; 12544 (void)Target->hasBody(FNTarget); 12545 Target = const_cast<CXXConstructorDecl*>( 12546 cast_or_null<CXXConstructorDecl>(FNTarget)); 12547 } 12548 12549 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 12550 // Avoid dereferencing a null pointer here. 12551 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 12552 12553 if (!Current.insert(Canonical)) 12554 return; 12555 12556 // We know that beyond here, we aren't chaining into a cycle. 12557 if (!Target || !Target->isDelegatingConstructor() || 12558 Target->isInvalidDecl() || Valid.count(TCanonical)) { 12559 Valid.insert(Current.begin(), Current.end()); 12560 Current.clear(); 12561 // We've hit a cycle. 12562 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 12563 Current.count(TCanonical)) { 12564 // If we haven't diagnosed this cycle yet, do so now. 12565 if (!Invalid.count(TCanonical)) { 12566 S.Diag((*Ctor->init_begin())->getSourceLocation(), 12567 diag::warn_delegating_ctor_cycle) 12568 << Ctor; 12569 12570 // Don't add a note for a function delegating directly to itself. 12571 if (TCanonical != Canonical) 12572 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 12573 12574 CXXConstructorDecl *C = Target; 12575 while (C->getCanonicalDecl() != Canonical) { 12576 const FunctionDecl *FNTarget = 0; 12577 (void)C->getTargetConstructor()->hasBody(FNTarget); 12578 assert(FNTarget && "Ctor cycle through bodiless function"); 12579 12580 C = const_cast<CXXConstructorDecl*>( 12581 cast<CXXConstructorDecl>(FNTarget)); 12582 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12583 } 12584 } 12585 12586 Invalid.insert(Current.begin(), Current.end()); 12587 Current.clear(); 12588 } else { 12589 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12590 } 12591} 12592 12593 12594void Sema::CheckDelegatingCtorCycles() { 12595 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12596 12597 for (DelegatingCtorDeclsType::iterator 12598 I = DelegatingCtorDecls.begin(ExternalSource), 12599 E = DelegatingCtorDecls.end(); 12600 I != E; ++I) 12601 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 12602 12603 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 12604 CE = Invalid.end(); 12605 CI != CE; ++CI) 12606 (*CI)->setInvalidDecl(); 12607} 12608 12609namespace { 12610 /// \brief AST visitor that finds references to the 'this' expression. 12611 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 12612 Sema &S; 12613 12614 public: 12615 explicit FindCXXThisExpr(Sema &S) : S(S) { } 12616 12617 bool VisitCXXThisExpr(CXXThisExpr *E) { 12618 S.Diag(E->getLocation(), diag::err_this_static_member_func) 12619 << E->isImplicit(); 12620 return false; 12621 } 12622 }; 12623} 12624 12625bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 12626 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12627 if (!TSInfo) 12628 return false; 12629 12630 TypeLoc TL = TSInfo->getTypeLoc(); 12631 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12632 if (!ProtoTL) 12633 return false; 12634 12635 // C++11 [expr.prim.general]p3: 12636 // [The expression this] shall not appear before the optional 12637 // cv-qualifier-seq and it shall not appear within the declaration of a 12638 // static member function (although its type and value category are defined 12639 // within a static member function as they are within a non-static member 12640 // function). [ Note: this is because declaration matching does not occur 12641 // until the complete declarator is known. - end note ] 12642 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12643 FindCXXThisExpr Finder(*this); 12644 12645 // If the return type came after the cv-qualifier-seq, check it now. 12646 if (Proto->hasTrailingReturn() && 12647 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc())) 12648 return true; 12649 12650 // Check the exception specification. 12651 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 12652 return true; 12653 12654 return checkThisInStaticMemberFunctionAttributes(Method); 12655} 12656 12657bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 12658 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12659 if (!TSInfo) 12660 return false; 12661 12662 TypeLoc TL = TSInfo->getTypeLoc(); 12663 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12664 if (!ProtoTL) 12665 return false; 12666 12667 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12668 FindCXXThisExpr Finder(*this); 12669 12670 switch (Proto->getExceptionSpecType()) { 12671 case EST_Uninstantiated: 12672 case EST_Unevaluated: 12673 case EST_BasicNoexcept: 12674 case EST_DynamicNone: 12675 case EST_MSAny: 12676 case EST_None: 12677 break; 12678 12679 case EST_ComputedNoexcept: 12680 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 12681 return true; 12682 12683 case EST_Dynamic: 12684 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 12685 EEnd = Proto->exception_end(); 12686 E != EEnd; ++E) { 12687 if (!Finder.TraverseType(*E)) 12688 return true; 12689 } 12690 break; 12691 } 12692 12693 return false; 12694} 12695 12696bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 12697 FindCXXThisExpr Finder(*this); 12698 12699 // Check attributes. 12700 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end(); 12701 A != AEnd; ++A) { 12702 // FIXME: This should be emitted by tblgen. 12703 Expr *Arg = 0; 12704 ArrayRef<Expr *> Args; 12705 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A)) 12706 Arg = G->getArg(); 12707 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A)) 12708 Arg = G->getArg(); 12709 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A)) 12710 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 12711 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A)) 12712 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 12713 else if (ExclusiveLockFunctionAttr *ELF 12714 = dyn_cast<ExclusiveLockFunctionAttr>(*A)) 12715 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 12716 else if (SharedLockFunctionAttr *SLF 12717 = dyn_cast<SharedLockFunctionAttr>(*A)) 12718 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 12719 else if (ExclusiveTrylockFunctionAttr *ETLF 12720 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) { 12721 Arg = ETLF->getSuccessValue(); 12722 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 12723 } else if (SharedTrylockFunctionAttr *STLF 12724 = dyn_cast<SharedTrylockFunctionAttr>(*A)) { 12725 Arg = STLF->getSuccessValue(); 12726 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 12727 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A)) 12728 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 12729 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A)) 12730 Arg = LR->getArg(); 12731 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A)) 12732 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 12733 else if (ExclusiveLocksRequiredAttr *ELR 12734 = dyn_cast<ExclusiveLocksRequiredAttr>(*A)) 12735 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size()); 12736 else if (SharedLocksRequiredAttr *SLR 12737 = dyn_cast<SharedLocksRequiredAttr>(*A)) 12738 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size()); 12739 12740 if (Arg && !Finder.TraverseStmt(Arg)) 12741 return true; 12742 12743 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12744 if (!Finder.TraverseStmt(Args[I])) 12745 return true; 12746 } 12747 } 12748 12749 return false; 12750} 12751 12752void 12753Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12754 ArrayRef<ParsedType> DynamicExceptions, 12755 ArrayRef<SourceRange> DynamicExceptionRanges, 12756 Expr *NoexceptExpr, 12757 SmallVectorImpl<QualType> &Exceptions, 12758 FunctionProtoType::ExtProtoInfo &EPI) { 12759 Exceptions.clear(); 12760 EPI.ExceptionSpecType = EST; 12761 if (EST == EST_Dynamic) { 12762 Exceptions.reserve(DynamicExceptions.size()); 12763 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12764 // FIXME: Preserve type source info. 12765 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12766 12767 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12768 collectUnexpandedParameterPacks(ET, Unexpanded); 12769 if (!Unexpanded.empty()) { 12770 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 12771 UPPC_ExceptionType, 12772 Unexpanded); 12773 continue; 12774 } 12775 12776 // Check that the type is valid for an exception spec, and 12777 // drop it if not. 12778 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 12779 Exceptions.push_back(ET); 12780 } 12781 EPI.NumExceptions = Exceptions.size(); 12782 EPI.Exceptions = Exceptions.data(); 12783 return; 12784 } 12785 12786 if (EST == EST_ComputedNoexcept) { 12787 // If an error occurred, there's no expression here. 12788 if (NoexceptExpr) { 12789 assert((NoexceptExpr->isTypeDependent() || 12790 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 12791 Context.BoolTy) && 12792 "Parser should have made sure that the expression is boolean"); 12793 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 12794 EPI.ExceptionSpecType = EST_BasicNoexcept; 12795 return; 12796 } 12797 12798 if (!NoexceptExpr->isValueDependent()) 12799 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 12800 diag::err_noexcept_needs_constant_expression, 12801 /*AllowFold*/ false).take(); 12802 EPI.NoexceptExpr = NoexceptExpr; 12803 } 12804 return; 12805 } 12806} 12807 12808/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 12809Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 12810 // Implicitly declared functions (e.g. copy constructors) are 12811 // __host__ __device__ 12812 if (D->isImplicit()) 12813 return CFT_HostDevice; 12814 12815 if (D->hasAttr<CUDAGlobalAttr>()) 12816 return CFT_Global; 12817 12818 if (D->hasAttr<CUDADeviceAttr>()) { 12819 if (D->hasAttr<CUDAHostAttr>()) 12820 return CFT_HostDevice; 12821 return CFT_Device; 12822 } 12823 12824 return CFT_Host; 12825} 12826 12827bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 12828 CUDAFunctionTarget CalleeTarget) { 12829 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 12830 // Callable from the device only." 12831 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 12832 return true; 12833 12834 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 12835 // Callable from the host only." 12836 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 12837 // Callable from the host only." 12838 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 12839 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 12840 return true; 12841 12842 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 12843 return true; 12844 12845 return false; 12846} 12847 12848/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 12849/// 12850MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 12851 SourceLocation DeclStart, 12852 Declarator &D, Expr *BitWidth, 12853 InClassInitStyle InitStyle, 12854 AccessSpecifier AS, 12855 AttributeList *MSPropertyAttr) { 12856 IdentifierInfo *II = D.getIdentifier(); 12857 if (!II) { 12858 Diag(DeclStart, diag::err_anonymous_property); 12859 return NULL; 12860 } 12861 SourceLocation Loc = D.getIdentifierLoc(); 12862 12863 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12864 QualType T = TInfo->getType(); 12865 if (getLangOpts().CPlusPlus) { 12866 CheckExtraCXXDefaultArguments(D); 12867 12868 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12869 UPPC_DataMemberType)) { 12870 D.setInvalidType(); 12871 T = Context.IntTy; 12872 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12873 } 12874 } 12875 12876 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12877 12878 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12879 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12880 diag::err_invalid_thread) 12881 << DeclSpec::getSpecifierName(TSCS); 12882 12883 // Check to see if this name was declared as a member previously 12884 NamedDecl *PrevDecl = 0; 12885 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12886 LookupName(Previous, S); 12887 switch (Previous.getResultKind()) { 12888 case LookupResult::Found: 12889 case LookupResult::FoundUnresolvedValue: 12890 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12891 break; 12892 12893 case LookupResult::FoundOverloaded: 12894 PrevDecl = Previous.getRepresentativeDecl(); 12895 break; 12896 12897 case LookupResult::NotFound: 12898 case LookupResult::NotFoundInCurrentInstantiation: 12899 case LookupResult::Ambiguous: 12900 break; 12901 } 12902 12903 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12904 // Maybe we will complain about the shadowed template parameter. 12905 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12906 // Just pretend that we didn't see the previous declaration. 12907 PrevDecl = 0; 12908 } 12909 12910 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12911 PrevDecl = 0; 12912 12913 SourceLocation TSSL = D.getLocStart(); 12914 MSPropertyDecl *NewPD; 12915 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 12916 NewPD = new (Context) MSPropertyDecl(Record, Loc, 12917 II, T, TInfo, TSSL, 12918 Data.GetterId, Data.SetterId); 12919 ProcessDeclAttributes(TUScope, NewPD, D); 12920 NewPD->setAccess(AS); 12921 12922 if (NewPD->isInvalidDecl()) 12923 Record->setInvalidDecl(); 12924 12925 if (D.getDeclSpec().isModulePrivateSpecified()) 12926 NewPD->setModulePrivate(); 12927 12928 if (NewPD->isInvalidDecl() && PrevDecl) { 12929 // Don't introduce NewFD into scope; there's already something 12930 // with the same name in the same scope. 12931 } else if (II) { 12932 PushOnScopeChains(NewPD, S); 12933 } else 12934 Record->addDecl(NewPD); 12935 12936 return NewPD; 12937} 12938