SemaDeclCXX.cpp revision b2b5658a8e4ad566303ec98caceaa3485e7635f7
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/Sema/CXXFieldCollector.h" 16#include "clang/Sema/Scope.h" 17#include "clang/Sema/Initialization.h" 18#include "clang/Sema/Lookup.h" 19#include "clang/AST/ASTConsumer.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/ASTMutationListener.h" 22#include "clang/AST/CharUnits.h" 23#include "clang/AST/CXXInheritance.h" 24#include "clang/AST/DeclVisitor.h" 25#include "clang/AST/ExprCXX.h" 26#include "clang/AST/RecordLayout.h" 27#include "clang/AST/StmtVisitor.h" 28#include "clang/AST/TypeLoc.h" 29#include "clang/AST/TypeOrdering.h" 30#include "clang/Sema/DeclSpec.h" 31#include "clang/Sema/ParsedTemplate.h" 32#include "clang/Basic/PartialDiagnostic.h" 33#include "clang/Lex/Preprocessor.h" 34#include "llvm/ADT/DenseSet.h" 35#include "llvm/ADT/STLExtras.h" 36#include <map> 37#include <set> 38 39using namespace clang; 40 41//===----------------------------------------------------------------------===// 42// CheckDefaultArgumentVisitor 43//===----------------------------------------------------------------------===// 44 45namespace { 46 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 47 /// the default argument of a parameter to determine whether it 48 /// contains any ill-formed subexpressions. For example, this will 49 /// diagnose the use of local variables or parameters within the 50 /// default argument expression. 51 class CheckDefaultArgumentVisitor 52 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 53 Expr *DefaultArg; 54 Sema *S; 55 56 public: 57 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 58 : DefaultArg(defarg), S(s) {} 59 60 bool VisitExpr(Expr *Node); 61 bool VisitDeclRefExpr(DeclRefExpr *DRE); 62 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 63 }; 64 65 /// VisitExpr - Visit all of the children of this expression. 66 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 67 bool IsInvalid = false; 68 for (Stmt::child_range I = Node->children(); I; ++I) 69 IsInvalid |= Visit(*I); 70 return IsInvalid; 71 } 72 73 /// VisitDeclRefExpr - Visit a reference to a declaration, to 74 /// determine whether this declaration can be used in the default 75 /// argument expression. 76 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 77 NamedDecl *Decl = DRE->getDecl(); 78 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 79 // C++ [dcl.fct.default]p9 80 // Default arguments are evaluated each time the function is 81 // called. The order of evaluation of function arguments is 82 // unspecified. Consequently, parameters of a function shall not 83 // be used in default argument expressions, even if they are not 84 // evaluated. Parameters of a function declared before a default 85 // argument expression are in scope and can hide namespace and 86 // class member names. 87 return S->Diag(DRE->getSourceRange().getBegin(), 88 diag::err_param_default_argument_references_param) 89 << Param->getDeclName() << DefaultArg->getSourceRange(); 90 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 91 // C++ [dcl.fct.default]p7 92 // Local variables shall not be used in default argument 93 // expressions. 94 if (VDecl->isLocalVarDecl()) 95 return S->Diag(DRE->getSourceRange().getBegin(), 96 diag::err_param_default_argument_references_local) 97 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 98 } 99 100 return false; 101 } 102 103 /// VisitCXXThisExpr - Visit a C++ "this" expression. 104 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 105 // C++ [dcl.fct.default]p8: 106 // The keyword this shall not be used in a default argument of a 107 // member function. 108 return S->Diag(ThisE->getSourceRange().getBegin(), 109 diag::err_param_default_argument_references_this) 110 << ThisE->getSourceRange(); 111 } 112} 113 114void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) { 115 assert(Context && "ImplicitExceptionSpecification without an ASTContext"); 116 // If we have an MSAny or unknown spec already, don't bother. 117 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed) 118 return; 119 120 const FunctionProtoType *Proto 121 = Method->getType()->getAs<FunctionProtoType>(); 122 123 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 124 125 // If this function can throw any exceptions, make a note of that. 126 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) { 127 ClearExceptions(); 128 ComputedEST = EST; 129 return; 130 } 131 132 // FIXME: If the call to this decl is using any of its default arguments, we 133 // need to search them for potentially-throwing calls. 134 135 // If this function has a basic noexcept, it doesn't affect the outcome. 136 if (EST == EST_BasicNoexcept) 137 return; 138 139 // If we have a throw-all spec at this point, ignore the function. 140 if (ComputedEST == EST_None) 141 return; 142 143 // If we're still at noexcept(true) and there's a nothrow() callee, 144 // change to that specification. 145 if (EST == EST_DynamicNone) { 146 if (ComputedEST == EST_BasicNoexcept) 147 ComputedEST = EST_DynamicNone; 148 return; 149 } 150 151 // Check out noexcept specs. 152 if (EST == EST_ComputedNoexcept) { 153 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context); 154 assert(NR != FunctionProtoType::NR_NoNoexcept && 155 "Must have noexcept result for EST_ComputedNoexcept."); 156 assert(NR != FunctionProtoType::NR_Dependent && 157 "Should not generate implicit declarations for dependent cases, " 158 "and don't know how to handle them anyway."); 159 160 // noexcept(false) -> no spec on the new function 161 if (NR == FunctionProtoType::NR_Throw) { 162 ClearExceptions(); 163 ComputedEST = EST_None; 164 } 165 // noexcept(true) won't change anything either. 166 return; 167 } 168 169 assert(EST == EST_Dynamic && "EST case not considered earlier."); 170 assert(ComputedEST != EST_None && 171 "Shouldn't collect exceptions when throw-all is guaranteed."); 172 ComputedEST = EST_Dynamic; 173 // Record the exceptions in this function's exception specification. 174 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 175 EEnd = Proto->exception_end(); 176 E != EEnd; ++E) 177 if (ExceptionsSeen.insert(Context->getCanonicalType(*E))) 178 Exceptions.push_back(*E); 179} 180 181void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 182 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed) 183 return; 184 185 // FIXME: 186 // 187 // C++0x [except.spec]p14: 188 // [An] implicit exception-specification specifies the type-id T if and 189 // only if T is allowed by the exception-specification of a function directly 190 // invoked by f's implicit definition; f shall allow all exceptions if any 191 // function it directly invokes allows all exceptions, and f shall allow no 192 // exceptions if every function it directly invokes allows no exceptions. 193 // 194 // Note in particular that if an implicit exception-specification is generated 195 // for a function containing a throw-expression, that specification can still 196 // be noexcept(true). 197 // 198 // Note also that 'directly invoked' is not defined in the standard, and there 199 // is no indication that we should only consider potentially-evaluated calls. 200 // 201 // Ultimately we should implement the intent of the standard: the exception 202 // specification should be the set of exceptions which can be thrown by the 203 // implicit definition. For now, we assume that any non-nothrow expression can 204 // throw any exception. 205 206 if (E->CanThrow(*Context)) 207 ComputedEST = EST_None; 208} 209 210bool 211Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 212 SourceLocation EqualLoc) { 213 if (RequireCompleteType(Param->getLocation(), Param->getType(), 214 diag::err_typecheck_decl_incomplete_type)) { 215 Param->setInvalidDecl(); 216 return true; 217 } 218 219 // C++ [dcl.fct.default]p5 220 // A default argument expression is implicitly converted (clause 221 // 4) to the parameter type. The default argument expression has 222 // the same semantic constraints as the initializer expression in 223 // a declaration of a variable of the parameter type, using the 224 // copy-initialization semantics (8.5). 225 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 226 Param); 227 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 228 EqualLoc); 229 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 230 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 231 MultiExprArg(*this, &Arg, 1)); 232 if (Result.isInvalid()) 233 return true; 234 Arg = Result.takeAs<Expr>(); 235 236 CheckImplicitConversions(Arg, EqualLoc); 237 Arg = MaybeCreateExprWithCleanups(Arg); 238 239 // Okay: add the default argument to the parameter 240 Param->setDefaultArg(Arg); 241 242 // We have already instantiated this parameter; provide each of the 243 // instantiations with the uninstantiated default argument. 244 UnparsedDefaultArgInstantiationsMap::iterator InstPos 245 = UnparsedDefaultArgInstantiations.find(Param); 246 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 247 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 248 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 249 250 // We're done tracking this parameter's instantiations. 251 UnparsedDefaultArgInstantiations.erase(InstPos); 252 } 253 254 return false; 255} 256 257/// ActOnParamDefaultArgument - Check whether the default argument 258/// provided for a function parameter is well-formed. If so, attach it 259/// to the parameter declaration. 260void 261Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 262 Expr *DefaultArg) { 263 if (!param || !DefaultArg) 264 return; 265 266 ParmVarDecl *Param = cast<ParmVarDecl>(param); 267 UnparsedDefaultArgLocs.erase(Param); 268 269 // Default arguments are only permitted in C++ 270 if (!getLangOptions().CPlusPlus) { 271 Diag(EqualLoc, diag::err_param_default_argument) 272 << DefaultArg->getSourceRange(); 273 Param->setInvalidDecl(); 274 return; 275 } 276 277 // Check for unexpanded parameter packs. 278 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 279 Param->setInvalidDecl(); 280 return; 281 } 282 283 // Check that the default argument is well-formed 284 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 285 if (DefaultArgChecker.Visit(DefaultArg)) { 286 Param->setInvalidDecl(); 287 return; 288 } 289 290 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 291} 292 293/// ActOnParamUnparsedDefaultArgument - We've seen a default 294/// argument for a function parameter, but we can't parse it yet 295/// because we're inside a class definition. Note that this default 296/// argument will be parsed later. 297void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 298 SourceLocation EqualLoc, 299 SourceLocation ArgLoc) { 300 if (!param) 301 return; 302 303 ParmVarDecl *Param = cast<ParmVarDecl>(param); 304 if (Param) 305 Param->setUnparsedDefaultArg(); 306 307 UnparsedDefaultArgLocs[Param] = ArgLoc; 308} 309 310/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 311/// the default argument for the parameter param failed. 312void Sema::ActOnParamDefaultArgumentError(Decl *param) { 313 if (!param) 314 return; 315 316 ParmVarDecl *Param = cast<ParmVarDecl>(param); 317 318 Param->setInvalidDecl(); 319 320 UnparsedDefaultArgLocs.erase(Param); 321} 322 323/// CheckExtraCXXDefaultArguments - Check for any extra default 324/// arguments in the declarator, which is not a function declaration 325/// or definition and therefore is not permitted to have default 326/// arguments. This routine should be invoked for every declarator 327/// that is not a function declaration or definition. 328void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 329 // C++ [dcl.fct.default]p3 330 // A default argument expression shall be specified only in the 331 // parameter-declaration-clause of a function declaration or in a 332 // template-parameter (14.1). It shall not be specified for a 333 // parameter pack. If it is specified in a 334 // parameter-declaration-clause, it shall not occur within a 335 // declarator or abstract-declarator of a parameter-declaration. 336 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 337 DeclaratorChunk &chunk = D.getTypeObject(i); 338 if (chunk.Kind == DeclaratorChunk::Function) { 339 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 340 ParmVarDecl *Param = 341 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 342 if (Param->hasUnparsedDefaultArg()) { 343 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 344 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 345 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 346 delete Toks; 347 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 348 } else if (Param->getDefaultArg()) { 349 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 350 << Param->getDefaultArg()->getSourceRange(); 351 Param->setDefaultArg(0); 352 } 353 } 354 } 355 } 356} 357 358// MergeCXXFunctionDecl - Merge two declarations of the same C++ 359// function, once we already know that they have the same 360// type. Subroutine of MergeFunctionDecl. Returns true if there was an 361// error, false otherwise. 362bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 363 bool Invalid = false; 364 365 // C++ [dcl.fct.default]p4: 366 // For non-template functions, default arguments can be added in 367 // later declarations of a function in the same 368 // scope. Declarations in different scopes have completely 369 // distinct sets of default arguments. That is, declarations in 370 // inner scopes do not acquire default arguments from 371 // declarations in outer scopes, and vice versa. In a given 372 // function declaration, all parameters subsequent to a 373 // parameter with a default argument shall have default 374 // arguments supplied in this or previous declarations. A 375 // default argument shall not be redefined by a later 376 // declaration (not even to the same value). 377 // 378 // C++ [dcl.fct.default]p6: 379 // Except for member functions of class templates, the default arguments 380 // in a member function definition that appears outside of the class 381 // definition are added to the set of default arguments provided by the 382 // member function declaration in the class definition. 383 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 384 ParmVarDecl *OldParam = Old->getParamDecl(p); 385 ParmVarDecl *NewParam = New->getParamDecl(p); 386 387 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 388 389 unsigned DiagDefaultParamID = 390 diag::err_param_default_argument_redefinition; 391 392 // MSVC accepts that default parameters be redefined for member functions 393 // of template class. The new default parameter's value is ignored. 394 Invalid = true; 395 if (getLangOptions().Microsoft) { 396 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 397 if (MD && MD->getParent()->getDescribedClassTemplate()) { 398 // Merge the old default argument into the new parameter. 399 NewParam->setHasInheritedDefaultArg(); 400 if (OldParam->hasUninstantiatedDefaultArg()) 401 NewParam->setUninstantiatedDefaultArg( 402 OldParam->getUninstantiatedDefaultArg()); 403 else 404 NewParam->setDefaultArg(OldParam->getInit()); 405 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 406 Invalid = false; 407 } 408 } 409 410 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 411 // hint here. Alternatively, we could walk the type-source information 412 // for NewParam to find the last source location in the type... but it 413 // isn't worth the effort right now. This is the kind of test case that 414 // is hard to get right: 415 // int f(int); 416 // void g(int (*fp)(int) = f); 417 // void g(int (*fp)(int) = &f); 418 Diag(NewParam->getLocation(), DiagDefaultParamID) 419 << NewParam->getDefaultArgRange(); 420 421 // Look for the function declaration where the default argument was 422 // actually written, which may be a declaration prior to Old. 423 for (FunctionDecl *Older = Old->getPreviousDeclaration(); 424 Older; Older = Older->getPreviousDeclaration()) { 425 if (!Older->getParamDecl(p)->hasDefaultArg()) 426 break; 427 428 OldParam = Older->getParamDecl(p); 429 } 430 431 Diag(OldParam->getLocation(), diag::note_previous_definition) 432 << OldParam->getDefaultArgRange(); 433 } else if (OldParam->hasDefaultArg()) { 434 // Merge the old default argument into the new parameter. 435 // It's important to use getInit() here; getDefaultArg() 436 // strips off any top-level ExprWithCleanups. 437 NewParam->setHasInheritedDefaultArg(); 438 if (OldParam->hasUninstantiatedDefaultArg()) 439 NewParam->setUninstantiatedDefaultArg( 440 OldParam->getUninstantiatedDefaultArg()); 441 else 442 NewParam->setDefaultArg(OldParam->getInit()); 443 } else if (NewParam->hasDefaultArg()) { 444 if (New->getDescribedFunctionTemplate()) { 445 // Paragraph 4, quoted above, only applies to non-template functions. 446 Diag(NewParam->getLocation(), 447 diag::err_param_default_argument_template_redecl) 448 << NewParam->getDefaultArgRange(); 449 Diag(Old->getLocation(), diag::note_template_prev_declaration) 450 << false; 451 } else if (New->getTemplateSpecializationKind() 452 != TSK_ImplicitInstantiation && 453 New->getTemplateSpecializationKind() != TSK_Undeclared) { 454 // C++ [temp.expr.spec]p21: 455 // Default function arguments shall not be specified in a declaration 456 // or a definition for one of the following explicit specializations: 457 // - the explicit specialization of a function template; 458 // - the explicit specialization of a member function template; 459 // - the explicit specialization of a member function of a class 460 // template where the class template specialization to which the 461 // member function specialization belongs is implicitly 462 // instantiated. 463 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 464 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 465 << New->getDeclName() 466 << NewParam->getDefaultArgRange(); 467 } else if (New->getDeclContext()->isDependentContext()) { 468 // C++ [dcl.fct.default]p6 (DR217): 469 // Default arguments for a member function of a class template shall 470 // be specified on the initial declaration of the member function 471 // within the class template. 472 // 473 // Reading the tea leaves a bit in DR217 and its reference to DR205 474 // leads me to the conclusion that one cannot add default function 475 // arguments for an out-of-line definition of a member function of a 476 // dependent type. 477 int WhichKind = 2; 478 if (CXXRecordDecl *Record 479 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 480 if (Record->getDescribedClassTemplate()) 481 WhichKind = 0; 482 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 483 WhichKind = 1; 484 else 485 WhichKind = 2; 486 } 487 488 Diag(NewParam->getLocation(), 489 diag::err_param_default_argument_member_template_redecl) 490 << WhichKind 491 << NewParam->getDefaultArgRange(); 492 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) { 493 CXXSpecialMember NewSM = getSpecialMember(Ctor), 494 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old)); 495 if (NewSM != OldSM) { 496 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special) 497 << NewParam->getDefaultArgRange() << NewSM; 498 Diag(Old->getLocation(), diag::note_previous_declaration_special) 499 << OldSM; 500 } 501 } 502 } 503 } 504 505 if (CheckEquivalentExceptionSpec(Old, New)) 506 Invalid = true; 507 508 return Invalid; 509} 510 511/// \brief Merge the exception specifications of two variable declarations. 512/// 513/// This is called when there's a redeclaration of a VarDecl. The function 514/// checks if the redeclaration might have an exception specification and 515/// validates compatibility and merges the specs if necessary. 516void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 517 // Shortcut if exceptions are disabled. 518 if (!getLangOptions().CXXExceptions) 519 return; 520 521 assert(Context.hasSameType(New->getType(), Old->getType()) && 522 "Should only be called if types are otherwise the same."); 523 524 QualType NewType = New->getType(); 525 QualType OldType = Old->getType(); 526 527 // We're only interested in pointers and references to functions, as well 528 // as pointers to member functions. 529 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 530 NewType = R->getPointeeType(); 531 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 532 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 533 NewType = P->getPointeeType(); 534 OldType = OldType->getAs<PointerType>()->getPointeeType(); 535 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 536 NewType = M->getPointeeType(); 537 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 538 } 539 540 if (!NewType->isFunctionProtoType()) 541 return; 542 543 // There's lots of special cases for functions. For function pointers, system 544 // libraries are hopefully not as broken so that we don't need these 545 // workarounds. 546 if (CheckEquivalentExceptionSpec( 547 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 548 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 549 New->setInvalidDecl(); 550 } 551} 552 553/// CheckCXXDefaultArguments - Verify that the default arguments for a 554/// function declaration are well-formed according to C++ 555/// [dcl.fct.default]. 556void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 557 unsigned NumParams = FD->getNumParams(); 558 unsigned p; 559 560 // Find first parameter with a default argument 561 for (p = 0; p < NumParams; ++p) { 562 ParmVarDecl *Param = FD->getParamDecl(p); 563 if (Param->hasDefaultArg()) 564 break; 565 } 566 567 // C++ [dcl.fct.default]p4: 568 // In a given function declaration, all parameters 569 // subsequent to a parameter with a default argument shall 570 // have default arguments supplied in this or previous 571 // declarations. A default argument shall not be redefined 572 // by a later declaration (not even to the same value). 573 unsigned LastMissingDefaultArg = 0; 574 for (; p < NumParams; ++p) { 575 ParmVarDecl *Param = FD->getParamDecl(p); 576 if (!Param->hasDefaultArg()) { 577 if (Param->isInvalidDecl()) 578 /* We already complained about this parameter. */; 579 else if (Param->getIdentifier()) 580 Diag(Param->getLocation(), 581 diag::err_param_default_argument_missing_name) 582 << Param->getIdentifier(); 583 else 584 Diag(Param->getLocation(), 585 diag::err_param_default_argument_missing); 586 587 LastMissingDefaultArg = p; 588 } 589 } 590 591 if (LastMissingDefaultArg > 0) { 592 // Some default arguments were missing. Clear out all of the 593 // default arguments up to (and including) the last missing 594 // default argument, so that we leave the function parameters 595 // in a semantically valid state. 596 for (p = 0; p <= LastMissingDefaultArg; ++p) { 597 ParmVarDecl *Param = FD->getParamDecl(p); 598 if (Param->hasDefaultArg()) { 599 Param->setDefaultArg(0); 600 } 601 } 602 } 603} 604 605/// isCurrentClassName - Determine whether the identifier II is the 606/// name of the class type currently being defined. In the case of 607/// nested classes, this will only return true if II is the name of 608/// the innermost class. 609bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 610 const CXXScopeSpec *SS) { 611 assert(getLangOptions().CPlusPlus && "No class names in C!"); 612 613 CXXRecordDecl *CurDecl; 614 if (SS && SS->isSet() && !SS->isInvalid()) { 615 DeclContext *DC = computeDeclContext(*SS, true); 616 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 617 } else 618 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 619 620 if (CurDecl && CurDecl->getIdentifier()) 621 return &II == CurDecl->getIdentifier(); 622 else 623 return false; 624} 625 626/// \brief Check the validity of a C++ base class specifier. 627/// 628/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 629/// and returns NULL otherwise. 630CXXBaseSpecifier * 631Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 632 SourceRange SpecifierRange, 633 bool Virtual, AccessSpecifier Access, 634 TypeSourceInfo *TInfo, 635 SourceLocation EllipsisLoc) { 636 QualType BaseType = TInfo->getType(); 637 638 // C++ [class.union]p1: 639 // A union shall not have base classes. 640 if (Class->isUnion()) { 641 Diag(Class->getLocation(), diag::err_base_clause_on_union) 642 << SpecifierRange; 643 return 0; 644 } 645 646 if (EllipsisLoc.isValid() && 647 !TInfo->getType()->containsUnexpandedParameterPack()) { 648 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 649 << TInfo->getTypeLoc().getSourceRange(); 650 EllipsisLoc = SourceLocation(); 651 } 652 653 if (BaseType->isDependentType()) 654 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 655 Class->getTagKind() == TTK_Class, 656 Access, TInfo, EllipsisLoc); 657 658 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 659 660 // Base specifiers must be record types. 661 if (!BaseType->isRecordType()) { 662 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 663 return 0; 664 } 665 666 // C++ [class.union]p1: 667 // A union shall not be used as a base class. 668 if (BaseType->isUnionType()) { 669 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 670 return 0; 671 } 672 673 // C++ [class.derived]p2: 674 // The class-name in a base-specifier shall not be an incompletely 675 // defined class. 676 if (RequireCompleteType(BaseLoc, BaseType, 677 PDiag(diag::err_incomplete_base_class) 678 << SpecifierRange)) { 679 Class->setInvalidDecl(); 680 return 0; 681 } 682 683 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 684 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 685 assert(BaseDecl && "Record type has no declaration"); 686 BaseDecl = BaseDecl->getDefinition(); 687 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 688 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 689 assert(CXXBaseDecl && "Base type is not a C++ type"); 690 691 // C++ [class]p3: 692 // If a class is marked final and it appears as a base-type-specifier in 693 // base-clause, the program is ill-formed. 694 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 695 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 696 << CXXBaseDecl->getDeclName(); 697 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 698 << CXXBaseDecl->getDeclName(); 699 return 0; 700 } 701 702 if (BaseDecl->isInvalidDecl()) 703 Class->setInvalidDecl(); 704 705 // Create the base specifier. 706 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 707 Class->getTagKind() == TTK_Class, 708 Access, TInfo, EllipsisLoc); 709} 710 711/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 712/// one entry in the base class list of a class specifier, for 713/// example: 714/// class foo : public bar, virtual private baz { 715/// 'public bar' and 'virtual private baz' are each base-specifiers. 716BaseResult 717Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 718 bool Virtual, AccessSpecifier Access, 719 ParsedType basetype, SourceLocation BaseLoc, 720 SourceLocation EllipsisLoc) { 721 if (!classdecl) 722 return true; 723 724 AdjustDeclIfTemplate(classdecl); 725 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 726 if (!Class) 727 return true; 728 729 TypeSourceInfo *TInfo = 0; 730 GetTypeFromParser(basetype, &TInfo); 731 732 if (EllipsisLoc.isInvalid() && 733 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 734 UPPC_BaseType)) 735 return true; 736 737 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 738 Virtual, Access, TInfo, 739 EllipsisLoc)) 740 return BaseSpec; 741 742 return true; 743} 744 745/// \brief Performs the actual work of attaching the given base class 746/// specifiers to a C++ class. 747bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 748 unsigned NumBases) { 749 if (NumBases == 0) 750 return false; 751 752 // Used to keep track of which base types we have already seen, so 753 // that we can properly diagnose redundant direct base types. Note 754 // that the key is always the unqualified canonical type of the base 755 // class. 756 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 757 758 // Copy non-redundant base specifiers into permanent storage. 759 unsigned NumGoodBases = 0; 760 bool Invalid = false; 761 for (unsigned idx = 0; idx < NumBases; ++idx) { 762 QualType NewBaseType 763 = Context.getCanonicalType(Bases[idx]->getType()); 764 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 765 if (KnownBaseTypes[NewBaseType]) { 766 // C++ [class.mi]p3: 767 // A class shall not be specified as a direct base class of a 768 // derived class more than once. 769 Diag(Bases[idx]->getSourceRange().getBegin(), 770 diag::err_duplicate_base_class) 771 << KnownBaseTypes[NewBaseType]->getType() 772 << Bases[idx]->getSourceRange(); 773 774 // Delete the duplicate base class specifier; we're going to 775 // overwrite its pointer later. 776 Context.Deallocate(Bases[idx]); 777 778 Invalid = true; 779 } else { 780 // Okay, add this new base class. 781 KnownBaseTypes[NewBaseType] = Bases[idx]; 782 Bases[NumGoodBases++] = Bases[idx]; 783 } 784 } 785 786 // Attach the remaining base class specifiers to the derived class. 787 Class->setBases(Bases, NumGoodBases); 788 789 // Delete the remaining (good) base class specifiers, since their 790 // data has been copied into the CXXRecordDecl. 791 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 792 Context.Deallocate(Bases[idx]); 793 794 return Invalid; 795} 796 797/// ActOnBaseSpecifiers - Attach the given base specifiers to the 798/// class, after checking whether there are any duplicate base 799/// classes. 800void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases, 801 unsigned NumBases) { 802 if (!ClassDecl || !Bases || !NumBases) 803 return; 804 805 AdjustDeclIfTemplate(ClassDecl); 806 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 807 (CXXBaseSpecifier**)(Bases), NumBases); 808} 809 810static CXXRecordDecl *GetClassForType(QualType T) { 811 if (const RecordType *RT = T->getAs<RecordType>()) 812 return cast<CXXRecordDecl>(RT->getDecl()); 813 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 814 return ICT->getDecl(); 815 else 816 return 0; 817} 818 819/// \brief Determine whether the type \p Derived is a C++ class that is 820/// derived from the type \p Base. 821bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 822 if (!getLangOptions().CPlusPlus) 823 return false; 824 825 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 826 if (!DerivedRD) 827 return false; 828 829 CXXRecordDecl *BaseRD = GetClassForType(Base); 830 if (!BaseRD) 831 return false; 832 833 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 834 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 835} 836 837/// \brief Determine whether the type \p Derived is a C++ class that is 838/// derived from the type \p Base. 839bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 840 if (!getLangOptions().CPlusPlus) 841 return false; 842 843 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 844 if (!DerivedRD) 845 return false; 846 847 CXXRecordDecl *BaseRD = GetClassForType(Base); 848 if (!BaseRD) 849 return false; 850 851 return DerivedRD->isDerivedFrom(BaseRD, Paths); 852} 853 854void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 855 CXXCastPath &BasePathArray) { 856 assert(BasePathArray.empty() && "Base path array must be empty!"); 857 assert(Paths.isRecordingPaths() && "Must record paths!"); 858 859 const CXXBasePath &Path = Paths.front(); 860 861 // We first go backward and check if we have a virtual base. 862 // FIXME: It would be better if CXXBasePath had the base specifier for 863 // the nearest virtual base. 864 unsigned Start = 0; 865 for (unsigned I = Path.size(); I != 0; --I) { 866 if (Path[I - 1].Base->isVirtual()) { 867 Start = I - 1; 868 break; 869 } 870 } 871 872 // Now add all bases. 873 for (unsigned I = Start, E = Path.size(); I != E; ++I) 874 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 875} 876 877/// \brief Determine whether the given base path includes a virtual 878/// base class. 879bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 880 for (CXXCastPath::const_iterator B = BasePath.begin(), 881 BEnd = BasePath.end(); 882 B != BEnd; ++B) 883 if ((*B)->isVirtual()) 884 return true; 885 886 return false; 887} 888 889/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 890/// conversion (where Derived and Base are class types) is 891/// well-formed, meaning that the conversion is unambiguous (and 892/// that all of the base classes are accessible). Returns true 893/// and emits a diagnostic if the code is ill-formed, returns false 894/// otherwise. Loc is the location where this routine should point to 895/// if there is an error, and Range is the source range to highlight 896/// if there is an error. 897bool 898Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 899 unsigned InaccessibleBaseID, 900 unsigned AmbigiousBaseConvID, 901 SourceLocation Loc, SourceRange Range, 902 DeclarationName Name, 903 CXXCastPath *BasePath) { 904 // First, determine whether the path from Derived to Base is 905 // ambiguous. This is slightly more expensive than checking whether 906 // the Derived to Base conversion exists, because here we need to 907 // explore multiple paths to determine if there is an ambiguity. 908 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 909 /*DetectVirtual=*/false); 910 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 911 assert(DerivationOkay && 912 "Can only be used with a derived-to-base conversion"); 913 (void)DerivationOkay; 914 915 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 916 if (InaccessibleBaseID) { 917 // Check that the base class can be accessed. 918 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 919 InaccessibleBaseID)) { 920 case AR_inaccessible: 921 return true; 922 case AR_accessible: 923 case AR_dependent: 924 case AR_delayed: 925 break; 926 } 927 } 928 929 // Build a base path if necessary. 930 if (BasePath) 931 BuildBasePathArray(Paths, *BasePath); 932 return false; 933 } 934 935 // We know that the derived-to-base conversion is ambiguous, and 936 // we're going to produce a diagnostic. Perform the derived-to-base 937 // search just one more time to compute all of the possible paths so 938 // that we can print them out. This is more expensive than any of 939 // the previous derived-to-base checks we've done, but at this point 940 // performance isn't as much of an issue. 941 Paths.clear(); 942 Paths.setRecordingPaths(true); 943 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 944 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 945 (void)StillOkay; 946 947 // Build up a textual representation of the ambiguous paths, e.g., 948 // D -> B -> A, that will be used to illustrate the ambiguous 949 // conversions in the diagnostic. We only print one of the paths 950 // to each base class subobject. 951 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 952 953 Diag(Loc, AmbigiousBaseConvID) 954 << Derived << Base << PathDisplayStr << Range << Name; 955 return true; 956} 957 958bool 959Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 960 SourceLocation Loc, SourceRange Range, 961 CXXCastPath *BasePath, 962 bool IgnoreAccess) { 963 return CheckDerivedToBaseConversion(Derived, Base, 964 IgnoreAccess ? 0 965 : diag::err_upcast_to_inaccessible_base, 966 diag::err_ambiguous_derived_to_base_conv, 967 Loc, Range, DeclarationName(), 968 BasePath); 969} 970 971 972/// @brief Builds a string representing ambiguous paths from a 973/// specific derived class to different subobjects of the same base 974/// class. 975/// 976/// This function builds a string that can be used in error messages 977/// to show the different paths that one can take through the 978/// inheritance hierarchy to go from the derived class to different 979/// subobjects of a base class. The result looks something like this: 980/// @code 981/// struct D -> struct B -> struct A 982/// struct D -> struct C -> struct A 983/// @endcode 984std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 985 std::string PathDisplayStr; 986 std::set<unsigned> DisplayedPaths; 987 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 988 Path != Paths.end(); ++Path) { 989 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 990 // We haven't displayed a path to this particular base 991 // class subobject yet. 992 PathDisplayStr += "\n "; 993 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 994 for (CXXBasePath::const_iterator Element = Path->begin(); 995 Element != Path->end(); ++Element) 996 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 997 } 998 } 999 1000 return PathDisplayStr; 1001} 1002 1003//===----------------------------------------------------------------------===// 1004// C++ class member Handling 1005//===----------------------------------------------------------------------===// 1006 1007/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1008Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1009 SourceLocation ASLoc, 1010 SourceLocation ColonLoc) { 1011 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1012 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1013 ASLoc, ColonLoc); 1014 CurContext->addHiddenDecl(ASDecl); 1015 return ASDecl; 1016} 1017 1018/// CheckOverrideControl - Check C++0x override control semantics. 1019void Sema::CheckOverrideControl(const Decl *D) { 1020 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1021 if (!MD || !MD->isVirtual()) 1022 return; 1023 1024 if (MD->isDependentContext()) 1025 return; 1026 1027 // C++0x [class.virtual]p3: 1028 // If a virtual function is marked with the virt-specifier override and does 1029 // not override a member function of a base class, 1030 // the program is ill-formed. 1031 bool HasOverriddenMethods = 1032 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1033 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) { 1034 Diag(MD->getLocation(), 1035 diag::err_function_marked_override_not_overriding) 1036 << MD->getDeclName(); 1037 return; 1038 } 1039} 1040 1041/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1042/// function overrides a virtual member function marked 'final', according to 1043/// C++0x [class.virtual]p3. 1044bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1045 const CXXMethodDecl *Old) { 1046 if (!Old->hasAttr<FinalAttr>()) 1047 return false; 1048 1049 Diag(New->getLocation(), diag::err_final_function_overridden) 1050 << New->getDeclName(); 1051 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1052 return true; 1053} 1054 1055/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1056/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1057/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1058/// one has been parsed, and 'HasDeferredInit' is true if an initializer is 1059/// present but parsing it has been deferred. 1060Decl * 1061Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1062 MultiTemplateParamsArg TemplateParameterLists, 1063 ExprTy *BW, const VirtSpecifiers &VS, 1064 ExprTy *InitExpr, bool HasDeferredInit, 1065 bool IsDefinition) { 1066 const DeclSpec &DS = D.getDeclSpec(); 1067 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1068 DeclarationName Name = NameInfo.getName(); 1069 SourceLocation Loc = NameInfo.getLoc(); 1070 1071 // For anonymous bitfields, the location should point to the type. 1072 if (Loc.isInvalid()) 1073 Loc = D.getSourceRange().getBegin(); 1074 1075 Expr *BitWidth = static_cast<Expr*>(BW); 1076 Expr *Init = static_cast<Expr*>(InitExpr); 1077 1078 assert(isa<CXXRecordDecl>(CurContext)); 1079 assert(!DS.isFriendSpecified()); 1080 assert(!Init || !HasDeferredInit); 1081 1082 bool isFunc = D.isDeclarationOfFunction(); 1083 1084 // C++ 9.2p6: A member shall not be declared to have automatic storage 1085 // duration (auto, register) or with the extern storage-class-specifier. 1086 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1087 // data members and cannot be applied to names declared const or static, 1088 // and cannot be applied to reference members. 1089 switch (DS.getStorageClassSpec()) { 1090 case DeclSpec::SCS_unspecified: 1091 case DeclSpec::SCS_typedef: 1092 case DeclSpec::SCS_static: 1093 // FALL THROUGH. 1094 break; 1095 case DeclSpec::SCS_mutable: 1096 if (isFunc) { 1097 if (DS.getStorageClassSpecLoc().isValid()) 1098 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1099 else 1100 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 1101 1102 // FIXME: It would be nicer if the keyword was ignored only for this 1103 // declarator. Otherwise we could get follow-up errors. 1104 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1105 } 1106 break; 1107 default: 1108 if (DS.getStorageClassSpecLoc().isValid()) 1109 Diag(DS.getStorageClassSpecLoc(), 1110 diag::err_storageclass_invalid_for_member); 1111 else 1112 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 1113 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1114 } 1115 1116 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1117 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1118 !isFunc); 1119 1120 Decl *Member; 1121 if (isInstField) { 1122 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1123 1124 if (SS.isSet() && !SS.isInvalid()) { 1125 // The user provided a superfluous scope specifier inside a class 1126 // definition: 1127 // 1128 // class X { 1129 // int X::member; 1130 // }; 1131 DeclContext *DC = 0; 1132 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext)) 1133 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification) 1134 << Name << FixItHint::CreateRemoval(SS.getRange()); 1135 else 1136 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1137 << Name << SS.getRange(); 1138 1139 SS.clear(); 1140 } 1141 1142 // FIXME: Check for template parameters! 1143 // FIXME: Check that the name is an identifier! 1144 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 1145 HasDeferredInit, AS); 1146 assert(Member && "HandleField never returns null"); 1147 } else { 1148 assert(!HasDeferredInit); 1149 1150 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition); 1151 if (!Member) { 1152 return 0; 1153 } 1154 1155 // Non-instance-fields can't have a bitfield. 1156 if (BitWidth) { 1157 if (Member->isInvalidDecl()) { 1158 // don't emit another diagnostic. 1159 } else if (isa<VarDecl>(Member)) { 1160 // C++ 9.6p3: A bit-field shall not be a static member. 1161 // "static member 'A' cannot be a bit-field" 1162 Diag(Loc, diag::err_static_not_bitfield) 1163 << Name << BitWidth->getSourceRange(); 1164 } else if (isa<TypedefDecl>(Member)) { 1165 // "typedef member 'x' cannot be a bit-field" 1166 Diag(Loc, diag::err_typedef_not_bitfield) 1167 << Name << BitWidth->getSourceRange(); 1168 } else { 1169 // A function typedef ("typedef int f(); f a;"). 1170 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1171 Diag(Loc, diag::err_not_integral_type_bitfield) 1172 << Name << cast<ValueDecl>(Member)->getType() 1173 << BitWidth->getSourceRange(); 1174 } 1175 1176 BitWidth = 0; 1177 Member->setInvalidDecl(); 1178 } 1179 1180 Member->setAccess(AS); 1181 1182 // If we have declared a member function template, set the access of the 1183 // templated declaration as well. 1184 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 1185 FunTmpl->getTemplatedDecl()->setAccess(AS); 1186 } 1187 1188 if (VS.isOverrideSpecified()) { 1189 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 1190 if (!MD || !MD->isVirtual()) { 1191 Diag(Member->getLocStart(), 1192 diag::override_keyword_only_allowed_on_virtual_member_functions) 1193 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc()); 1194 } else 1195 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 1196 } 1197 if (VS.isFinalSpecified()) { 1198 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 1199 if (!MD || !MD->isVirtual()) { 1200 Diag(Member->getLocStart(), 1201 diag::override_keyword_only_allowed_on_virtual_member_functions) 1202 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc()); 1203 } else 1204 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 1205 } 1206 1207 if (VS.getLastLocation().isValid()) { 1208 // Update the end location of a method that has a virt-specifiers. 1209 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 1210 MD->setRangeEnd(VS.getLastLocation()); 1211 } 1212 1213 CheckOverrideControl(Member); 1214 1215 assert((Name || isInstField) && "No identifier for non-field ?"); 1216 1217 if (Init) 1218 AddInitializerToDecl(Member, Init, false, 1219 DS.getTypeSpecType() == DeclSpec::TST_auto); 1220 else if (DS.getTypeSpecType() == DeclSpec::TST_auto && 1221 DS.getStorageClassSpec() == DeclSpec::SCS_static) { 1222 // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static 1223 // data member if a brace-or-equal-initializer is provided. 1224 Diag(Loc, diag::err_auto_var_requires_init) 1225 << Name << cast<ValueDecl>(Member)->getType(); 1226 Member->setInvalidDecl(); 1227 } 1228 1229 FinalizeDeclaration(Member); 1230 1231 if (isInstField) 1232 FieldCollector->Add(cast<FieldDecl>(Member)); 1233 return Member; 1234} 1235 1236/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 1237/// in-class initializer for a non-static C++ class member, and after 1238/// instantiating an in-class initializer in a class template. Such actions 1239/// are deferred until the class is complete. 1240void 1241Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc, 1242 Expr *InitExpr) { 1243 FieldDecl *FD = cast<FieldDecl>(D); 1244 1245 if (!InitExpr) { 1246 FD->setInvalidDecl(); 1247 FD->removeInClassInitializer(); 1248 return; 1249 } 1250 1251 ExprResult Init = InitExpr; 1252 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 1253 // FIXME: if there is no EqualLoc, this is list-initialization. 1254 Init = PerformCopyInitialization( 1255 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr); 1256 if (Init.isInvalid()) { 1257 FD->setInvalidDecl(); 1258 return; 1259 } 1260 1261 CheckImplicitConversions(Init.get(), EqualLoc); 1262 } 1263 1264 // C++0x [class.base.init]p7: 1265 // The initialization of each base and member constitutes a 1266 // full-expression. 1267 Init = MaybeCreateExprWithCleanups(Init); 1268 if (Init.isInvalid()) { 1269 FD->setInvalidDecl(); 1270 return; 1271 } 1272 1273 InitExpr = Init.release(); 1274 1275 FD->setInClassInitializer(InitExpr); 1276} 1277 1278/// \brief Find the direct and/or virtual base specifiers that 1279/// correspond to the given base type, for use in base initialization 1280/// within a constructor. 1281static bool FindBaseInitializer(Sema &SemaRef, 1282 CXXRecordDecl *ClassDecl, 1283 QualType BaseType, 1284 const CXXBaseSpecifier *&DirectBaseSpec, 1285 const CXXBaseSpecifier *&VirtualBaseSpec) { 1286 // First, check for a direct base class. 1287 DirectBaseSpec = 0; 1288 for (CXXRecordDecl::base_class_const_iterator Base 1289 = ClassDecl->bases_begin(); 1290 Base != ClassDecl->bases_end(); ++Base) { 1291 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 1292 // We found a direct base of this type. That's what we're 1293 // initializing. 1294 DirectBaseSpec = &*Base; 1295 break; 1296 } 1297 } 1298 1299 // Check for a virtual base class. 1300 // FIXME: We might be able to short-circuit this if we know in advance that 1301 // there are no virtual bases. 1302 VirtualBaseSpec = 0; 1303 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 1304 // We haven't found a base yet; search the class hierarchy for a 1305 // virtual base class. 1306 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1307 /*DetectVirtual=*/false); 1308 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 1309 BaseType, Paths)) { 1310 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1311 Path != Paths.end(); ++Path) { 1312 if (Path->back().Base->isVirtual()) { 1313 VirtualBaseSpec = Path->back().Base; 1314 break; 1315 } 1316 } 1317 } 1318 } 1319 1320 return DirectBaseSpec || VirtualBaseSpec; 1321} 1322 1323/// ActOnMemInitializer - Handle a C++ member initializer. 1324MemInitResult 1325Sema::ActOnMemInitializer(Decl *ConstructorD, 1326 Scope *S, 1327 CXXScopeSpec &SS, 1328 IdentifierInfo *MemberOrBase, 1329 ParsedType TemplateTypeTy, 1330 SourceLocation IdLoc, 1331 SourceLocation LParenLoc, 1332 ExprTy **Args, unsigned NumArgs, 1333 SourceLocation RParenLoc, 1334 SourceLocation EllipsisLoc) { 1335 if (!ConstructorD) 1336 return true; 1337 1338 AdjustDeclIfTemplate(ConstructorD); 1339 1340 CXXConstructorDecl *Constructor 1341 = dyn_cast<CXXConstructorDecl>(ConstructorD); 1342 if (!Constructor) { 1343 // The user wrote a constructor initializer on a function that is 1344 // not a C++ constructor. Ignore the error for now, because we may 1345 // have more member initializers coming; we'll diagnose it just 1346 // once in ActOnMemInitializers. 1347 return true; 1348 } 1349 1350 CXXRecordDecl *ClassDecl = Constructor->getParent(); 1351 1352 // C++ [class.base.init]p2: 1353 // Names in a mem-initializer-id are looked up in the scope of the 1354 // constructor's class and, if not found in that scope, are looked 1355 // up in the scope containing the constructor's definition. 1356 // [Note: if the constructor's class contains a member with the 1357 // same name as a direct or virtual base class of the class, a 1358 // mem-initializer-id naming the member or base class and composed 1359 // of a single identifier refers to the class member. A 1360 // mem-initializer-id for the hidden base class may be specified 1361 // using a qualified name. ] 1362 if (!SS.getScopeRep() && !TemplateTypeTy) { 1363 // Look for a member, first. 1364 FieldDecl *Member = 0; 1365 DeclContext::lookup_result Result 1366 = ClassDecl->lookup(MemberOrBase); 1367 if (Result.first != Result.second) { 1368 Member = dyn_cast<FieldDecl>(*Result.first); 1369 1370 if (Member) { 1371 if (EllipsisLoc.isValid()) 1372 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 1373 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1374 1375 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1376 LParenLoc, RParenLoc); 1377 } 1378 1379 // Handle anonymous union case. 1380 if (IndirectFieldDecl* IndirectField 1381 = dyn_cast<IndirectFieldDecl>(*Result.first)) { 1382 if (EllipsisLoc.isValid()) 1383 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 1384 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1385 1386 return BuildMemberInitializer(IndirectField, (Expr**)Args, 1387 NumArgs, IdLoc, 1388 LParenLoc, RParenLoc); 1389 } 1390 } 1391 } 1392 // It didn't name a member, so see if it names a class. 1393 QualType BaseType; 1394 TypeSourceInfo *TInfo = 0; 1395 1396 if (TemplateTypeTy) { 1397 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 1398 } else { 1399 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 1400 LookupParsedName(R, S, &SS); 1401 1402 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 1403 if (!TyD) { 1404 if (R.isAmbiguous()) return true; 1405 1406 // We don't want access-control diagnostics here. 1407 R.suppressDiagnostics(); 1408 1409 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 1410 bool NotUnknownSpecialization = false; 1411 DeclContext *DC = computeDeclContext(SS, false); 1412 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 1413 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 1414 1415 if (!NotUnknownSpecialization) { 1416 // When the scope specifier can refer to a member of an unknown 1417 // specialization, we take it as a type name. 1418 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 1419 SS.getWithLocInContext(Context), 1420 *MemberOrBase, IdLoc); 1421 if (BaseType.isNull()) 1422 return true; 1423 1424 R.clear(); 1425 R.setLookupName(MemberOrBase); 1426 } 1427 } 1428 1429 // If no results were found, try to correct typos. 1430 TypoCorrection Corr; 1431 if (R.empty() && BaseType.isNull() && 1432 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 1433 ClassDecl, false, CTC_NoKeywords))) { 1434 std::string CorrectedStr(Corr.getAsString(getLangOptions())); 1435 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions())); 1436 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 1437 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) { 1438 // We have found a non-static data member with a similar 1439 // name to what was typed; complain and initialize that 1440 // member. 1441 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1442 << MemberOrBase << true << CorrectedQuotedStr 1443 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1444 Diag(Member->getLocation(), diag::note_previous_decl) 1445 << CorrectedQuotedStr; 1446 1447 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1448 LParenLoc, RParenLoc); 1449 } 1450 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 1451 const CXXBaseSpecifier *DirectBaseSpec; 1452 const CXXBaseSpecifier *VirtualBaseSpec; 1453 if (FindBaseInitializer(*this, ClassDecl, 1454 Context.getTypeDeclType(Type), 1455 DirectBaseSpec, VirtualBaseSpec)) { 1456 // We have found a direct or virtual base class with a 1457 // similar name to what was typed; complain and initialize 1458 // that base class. 1459 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1460 << MemberOrBase << false << CorrectedQuotedStr 1461 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1462 1463 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 1464 : VirtualBaseSpec; 1465 Diag(BaseSpec->getSourceRange().getBegin(), 1466 diag::note_base_class_specified_here) 1467 << BaseSpec->getType() 1468 << BaseSpec->getSourceRange(); 1469 1470 TyD = Type; 1471 } 1472 } 1473 } 1474 1475 if (!TyD && BaseType.isNull()) { 1476 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 1477 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1478 return true; 1479 } 1480 } 1481 1482 if (BaseType.isNull()) { 1483 BaseType = Context.getTypeDeclType(TyD); 1484 if (SS.isSet()) { 1485 NestedNameSpecifier *Qualifier = 1486 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1487 1488 // FIXME: preserve source range information 1489 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 1490 } 1491 } 1492 } 1493 1494 if (!TInfo) 1495 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 1496 1497 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs, 1498 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc); 1499} 1500 1501/// Checks a member initializer expression for cases where reference (or 1502/// pointer) members are bound to by-value parameters (or their addresses). 1503static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 1504 Expr *Init, 1505 SourceLocation IdLoc) { 1506 QualType MemberTy = Member->getType(); 1507 1508 // We only handle pointers and references currently. 1509 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 1510 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 1511 return; 1512 1513 const bool IsPointer = MemberTy->isPointerType(); 1514 if (IsPointer) { 1515 if (const UnaryOperator *Op 1516 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 1517 // The only case we're worried about with pointers requires taking the 1518 // address. 1519 if (Op->getOpcode() != UO_AddrOf) 1520 return; 1521 1522 Init = Op->getSubExpr(); 1523 } else { 1524 // We only handle address-of expression initializers for pointers. 1525 return; 1526 } 1527 } 1528 1529 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) { 1530 // Taking the address of a temporary will be diagnosed as a hard error. 1531 if (IsPointer) 1532 return; 1533 1534 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary) 1535 << Member << Init->getSourceRange(); 1536 } else if (const DeclRefExpr *DRE 1537 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 1538 // We only warn when referring to a non-reference parameter declaration. 1539 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 1540 if (!Parameter || Parameter->getType()->isReferenceType()) 1541 return; 1542 1543 S.Diag(Init->getExprLoc(), 1544 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 1545 : diag::warn_bind_ref_member_to_parameter) 1546 << Member << Parameter << Init->getSourceRange(); 1547 } else { 1548 // Other initializers are fine. 1549 return; 1550 } 1551 1552 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 1553 << (unsigned)IsPointer; 1554} 1555 1556/// Checks an initializer expression for use of uninitialized fields, such as 1557/// containing the field that is being initialized. Returns true if there is an 1558/// uninitialized field was used an updates the SourceLocation parameter; false 1559/// otherwise. 1560static bool InitExprContainsUninitializedFields(const Stmt *S, 1561 const ValueDecl *LhsField, 1562 SourceLocation *L) { 1563 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField)); 1564 1565 if (isa<CallExpr>(S)) { 1566 // Do not descend into function calls or constructors, as the use 1567 // of an uninitialized field may be valid. One would have to inspect 1568 // the contents of the function/ctor to determine if it is safe or not. 1569 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers 1570 // may be safe, depending on what the function/ctor does. 1571 return false; 1572 } 1573 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) { 1574 const NamedDecl *RhsField = ME->getMemberDecl(); 1575 1576 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) { 1577 // The member expression points to a static data member. 1578 assert(VD->isStaticDataMember() && 1579 "Member points to non-static data member!"); 1580 (void)VD; 1581 return false; 1582 } 1583 1584 if (isa<EnumConstantDecl>(RhsField)) { 1585 // The member expression points to an enum. 1586 return false; 1587 } 1588 1589 if (RhsField == LhsField) { 1590 // Initializing a field with itself. Throw a warning. 1591 // But wait; there are exceptions! 1592 // Exception #1: The field may not belong to this record. 1593 // e.g. Foo(const Foo& rhs) : A(rhs.A) {} 1594 const Expr *base = ME->getBase(); 1595 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) { 1596 // Even though the field matches, it does not belong to this record. 1597 return false; 1598 } 1599 // None of the exceptions triggered; return true to indicate an 1600 // uninitialized field was used. 1601 *L = ME->getMemberLoc(); 1602 return true; 1603 } 1604 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) { 1605 // sizeof/alignof doesn't reference contents, do not warn. 1606 return false; 1607 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) { 1608 // address-of doesn't reference contents (the pointer may be dereferenced 1609 // in the same expression but it would be rare; and weird). 1610 if (UOE->getOpcode() == UO_AddrOf) 1611 return false; 1612 } 1613 for (Stmt::const_child_range it = S->children(); it; ++it) { 1614 if (!*it) { 1615 // An expression such as 'member(arg ?: "")' may trigger this. 1616 continue; 1617 } 1618 if (InitExprContainsUninitializedFields(*it, LhsField, L)) 1619 return true; 1620 } 1621 return false; 1622} 1623 1624MemInitResult 1625Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args, 1626 unsigned NumArgs, SourceLocation IdLoc, 1627 SourceLocation LParenLoc, 1628 SourceLocation RParenLoc) { 1629 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 1630 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 1631 assert((DirectMember || IndirectMember) && 1632 "Member must be a FieldDecl or IndirectFieldDecl"); 1633 1634 if (Member->isInvalidDecl()) 1635 return true; 1636 1637 // Diagnose value-uses of fields to initialize themselves, e.g. 1638 // foo(foo) 1639 // where foo is not also a parameter to the constructor. 1640 // TODO: implement -Wuninitialized and fold this into that framework. 1641 for (unsigned i = 0; i < NumArgs; ++i) { 1642 SourceLocation L; 1643 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) { 1644 // FIXME: Return true in the case when other fields are used before being 1645 // uninitialized. For example, let this field be the i'th field. When 1646 // initializing the i'th field, throw a warning if any of the >= i'th 1647 // fields are used, as they are not yet initialized. 1648 // Right now we are only handling the case where the i'th field uses 1649 // itself in its initializer. 1650 Diag(L, diag::warn_field_is_uninit); 1651 } 1652 } 1653 1654 bool HasDependentArg = false; 1655 for (unsigned i = 0; i < NumArgs; i++) 1656 HasDependentArg |= Args[i]->isTypeDependent(); 1657 1658 Expr *Init; 1659 if (Member->getType()->isDependentType() || HasDependentArg) { 1660 // Can't check initialization for a member of dependent type or when 1661 // any of the arguments are type-dependent expressions. 1662 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1663 RParenLoc, 1664 Member->getType().getNonReferenceType()); 1665 1666 DiscardCleanupsInEvaluationContext(); 1667 } else { 1668 // Initialize the member. 1669 InitializedEntity MemberEntity = 1670 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 1671 : InitializedEntity::InitializeMember(IndirectMember, 0); 1672 InitializationKind Kind = 1673 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc); 1674 1675 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 1676 1677 ExprResult MemberInit = 1678 InitSeq.Perform(*this, MemberEntity, Kind, 1679 MultiExprArg(*this, Args, NumArgs), 0); 1680 if (MemberInit.isInvalid()) 1681 return true; 1682 1683 CheckImplicitConversions(MemberInit.get(), LParenLoc); 1684 1685 // C++0x [class.base.init]p7: 1686 // The initialization of each base and member constitutes a 1687 // full-expression. 1688 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 1689 if (MemberInit.isInvalid()) 1690 return true; 1691 1692 // If we are in a dependent context, template instantiation will 1693 // perform this type-checking again. Just save the arguments that we 1694 // received in a ParenListExpr. 1695 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1696 // of the information that we have about the member 1697 // initializer. However, deconstructing the ASTs is a dicey process, 1698 // and this approach is far more likely to get the corner cases right. 1699 if (CurContext->isDependentContext()) { 1700 Init = new (Context) ParenListExpr( 1701 Context, LParenLoc, Args, NumArgs, RParenLoc, 1702 Member->getType().getNonReferenceType()); 1703 } else { 1704 Init = MemberInit.get(); 1705 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc); 1706 } 1707 } 1708 1709 if (DirectMember) { 1710 return new (Context) CXXCtorInitializer(Context, DirectMember, 1711 IdLoc, LParenLoc, Init, 1712 RParenLoc); 1713 } else { 1714 return new (Context) CXXCtorInitializer(Context, IndirectMember, 1715 IdLoc, LParenLoc, Init, 1716 RParenLoc); 1717 } 1718} 1719 1720MemInitResult 1721Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, 1722 Expr **Args, unsigned NumArgs, 1723 SourceLocation NameLoc, 1724 SourceLocation LParenLoc, 1725 SourceLocation RParenLoc, 1726 CXXRecordDecl *ClassDecl) { 1727 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 1728 if (!LangOpts.CPlusPlus0x) 1729 return Diag(Loc, diag::err_delegation_0x_only) 1730 << TInfo->getTypeLoc().getLocalSourceRange(); 1731 1732 // Initialize the object. 1733 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 1734 QualType(ClassDecl->getTypeForDecl(), 0)); 1735 InitializationKind Kind = 1736 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc); 1737 1738 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs); 1739 1740 ExprResult DelegationInit = 1741 InitSeq.Perform(*this, DelegationEntity, Kind, 1742 MultiExprArg(*this, Args, NumArgs), 0); 1743 if (DelegationInit.isInvalid()) 1744 return true; 1745 1746 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get()); 1747 CXXConstructorDecl *Constructor 1748 = ConExpr->getConstructor(); 1749 assert(Constructor && "Delegating constructor with no target?"); 1750 1751 CheckImplicitConversions(DelegationInit.get(), LParenLoc); 1752 1753 // C++0x [class.base.init]p7: 1754 // The initialization of each base and member constitutes a 1755 // full-expression. 1756 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit); 1757 if (DelegationInit.isInvalid()) 1758 return true; 1759 1760 assert(!CurContext->isDependentContext()); 1761 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor, 1762 DelegationInit.takeAs<Expr>(), 1763 RParenLoc); 1764} 1765 1766MemInitResult 1767Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 1768 Expr **Args, unsigned NumArgs, 1769 SourceLocation LParenLoc, SourceLocation RParenLoc, 1770 CXXRecordDecl *ClassDecl, 1771 SourceLocation EllipsisLoc) { 1772 bool HasDependentArg = false; 1773 for (unsigned i = 0; i < NumArgs; i++) 1774 HasDependentArg |= Args[i]->isTypeDependent(); 1775 1776 SourceLocation BaseLoc 1777 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 1778 1779 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 1780 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 1781 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1782 1783 // C++ [class.base.init]p2: 1784 // [...] Unless the mem-initializer-id names a nonstatic data 1785 // member of the constructor's class or a direct or virtual base 1786 // of that class, the mem-initializer is ill-formed. A 1787 // mem-initializer-list can initialize a base class using any 1788 // name that denotes that base class type. 1789 bool Dependent = BaseType->isDependentType() || HasDependentArg; 1790 1791 if (EllipsisLoc.isValid()) { 1792 // This is a pack expansion. 1793 if (!BaseType->containsUnexpandedParameterPack()) { 1794 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1795 << SourceRange(BaseLoc, RParenLoc); 1796 1797 EllipsisLoc = SourceLocation(); 1798 } 1799 } else { 1800 // Check for any unexpanded parameter packs. 1801 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 1802 return true; 1803 1804 for (unsigned I = 0; I != NumArgs; ++I) 1805 if (DiagnoseUnexpandedParameterPack(Args[I])) 1806 return true; 1807 } 1808 1809 // Check for direct and virtual base classes. 1810 const CXXBaseSpecifier *DirectBaseSpec = 0; 1811 const CXXBaseSpecifier *VirtualBaseSpec = 0; 1812 if (!Dependent) { 1813 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 1814 BaseType)) 1815 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc, 1816 LParenLoc, RParenLoc, ClassDecl); 1817 1818 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 1819 VirtualBaseSpec); 1820 1821 // C++ [base.class.init]p2: 1822 // Unless the mem-initializer-id names a nonstatic data member of the 1823 // constructor's class or a direct or virtual base of that class, the 1824 // mem-initializer is ill-formed. 1825 if (!DirectBaseSpec && !VirtualBaseSpec) { 1826 // If the class has any dependent bases, then it's possible that 1827 // one of those types will resolve to the same type as 1828 // BaseType. Therefore, just treat this as a dependent base 1829 // class initialization. FIXME: Should we try to check the 1830 // initialization anyway? It seems odd. 1831 if (ClassDecl->hasAnyDependentBases()) 1832 Dependent = true; 1833 else 1834 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 1835 << BaseType << Context.getTypeDeclType(ClassDecl) 1836 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1837 } 1838 } 1839 1840 if (Dependent) { 1841 // Can't check initialization for a base of dependent type or when 1842 // any of the arguments are type-dependent expressions. 1843 ExprResult BaseInit 1844 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1845 RParenLoc, BaseType)); 1846 1847 DiscardCleanupsInEvaluationContext(); 1848 1849 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 1850 /*IsVirtual=*/false, 1851 LParenLoc, 1852 BaseInit.takeAs<Expr>(), 1853 RParenLoc, 1854 EllipsisLoc); 1855 } 1856 1857 // C++ [base.class.init]p2: 1858 // If a mem-initializer-id is ambiguous because it designates both 1859 // a direct non-virtual base class and an inherited virtual base 1860 // class, the mem-initializer is ill-formed. 1861 if (DirectBaseSpec && VirtualBaseSpec) 1862 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 1863 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1864 1865 CXXBaseSpecifier *BaseSpec 1866 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 1867 if (!BaseSpec) 1868 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 1869 1870 // Initialize the base. 1871 InitializedEntity BaseEntity = 1872 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 1873 InitializationKind Kind = 1874 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc); 1875 1876 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 1877 1878 ExprResult BaseInit = 1879 InitSeq.Perform(*this, BaseEntity, Kind, 1880 MultiExprArg(*this, Args, NumArgs), 0); 1881 if (BaseInit.isInvalid()) 1882 return true; 1883 1884 CheckImplicitConversions(BaseInit.get(), LParenLoc); 1885 1886 // C++0x [class.base.init]p7: 1887 // The initialization of each base and member constitutes a 1888 // full-expression. 1889 BaseInit = MaybeCreateExprWithCleanups(BaseInit); 1890 if (BaseInit.isInvalid()) 1891 return true; 1892 1893 // If we are in a dependent context, template instantiation will 1894 // perform this type-checking again. Just save the arguments that we 1895 // received in a ParenListExpr. 1896 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1897 // of the information that we have about the base 1898 // initializer. However, deconstructing the ASTs is a dicey process, 1899 // and this approach is far more likely to get the corner cases right. 1900 if (CurContext->isDependentContext()) { 1901 ExprResult Init 1902 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1903 RParenLoc, BaseType)); 1904 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 1905 BaseSpec->isVirtual(), 1906 LParenLoc, 1907 Init.takeAs<Expr>(), 1908 RParenLoc, 1909 EllipsisLoc); 1910 } 1911 1912 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 1913 BaseSpec->isVirtual(), 1914 LParenLoc, 1915 BaseInit.takeAs<Expr>(), 1916 RParenLoc, 1917 EllipsisLoc); 1918} 1919 1920// Create a static_cast\<T&&>(expr). 1921static Expr *CastForMoving(Sema &SemaRef, Expr *E) { 1922 QualType ExprType = E->getType(); 1923 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType); 1924 SourceLocation ExprLoc = E->getLocStart(); 1925 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 1926 TargetType, ExprLoc); 1927 1928 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 1929 SourceRange(ExprLoc, ExprLoc), 1930 E->getSourceRange()).take(); 1931} 1932 1933/// ImplicitInitializerKind - How an implicit base or member initializer should 1934/// initialize its base or member. 1935enum ImplicitInitializerKind { 1936 IIK_Default, 1937 IIK_Copy, 1938 IIK_Move 1939}; 1940 1941static bool 1942BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 1943 ImplicitInitializerKind ImplicitInitKind, 1944 CXXBaseSpecifier *BaseSpec, 1945 bool IsInheritedVirtualBase, 1946 CXXCtorInitializer *&CXXBaseInit) { 1947 InitializedEntity InitEntity 1948 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 1949 IsInheritedVirtualBase); 1950 1951 ExprResult BaseInit; 1952 1953 switch (ImplicitInitKind) { 1954 case IIK_Default: { 1955 InitializationKind InitKind 1956 = InitializationKind::CreateDefault(Constructor->getLocation()); 1957 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 1958 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 1959 MultiExprArg(SemaRef, 0, 0)); 1960 break; 1961 } 1962 1963 case IIK_Move: 1964 case IIK_Copy: { 1965 bool Moving = ImplicitInitKind == IIK_Move; 1966 ParmVarDecl *Param = Constructor->getParamDecl(0); 1967 QualType ParamType = Param->getType().getNonReferenceType(); 1968 1969 Expr *CopyCtorArg = 1970 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param, 1971 Constructor->getLocation(), ParamType, 1972 VK_LValue, 0); 1973 1974 // Cast to the base class to avoid ambiguities. 1975 QualType ArgTy = 1976 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 1977 ParamType.getQualifiers()); 1978 1979 if (Moving) { 1980 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 1981 } 1982 1983 CXXCastPath BasePath; 1984 BasePath.push_back(BaseSpec); 1985 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 1986 CK_UncheckedDerivedToBase, 1987 Moving ? VK_XValue : VK_LValue, 1988 &BasePath).take(); 1989 1990 InitializationKind InitKind 1991 = InitializationKind::CreateDirect(Constructor->getLocation(), 1992 SourceLocation(), SourceLocation()); 1993 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 1994 &CopyCtorArg, 1); 1995 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 1996 MultiExprArg(&CopyCtorArg, 1)); 1997 break; 1998 } 1999 } 2000 2001 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 2002 if (BaseInit.isInvalid()) 2003 return true; 2004 2005 CXXBaseInit = 2006 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2007 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 2008 SourceLocation()), 2009 BaseSpec->isVirtual(), 2010 SourceLocation(), 2011 BaseInit.takeAs<Expr>(), 2012 SourceLocation(), 2013 SourceLocation()); 2014 2015 return false; 2016} 2017 2018static bool RefersToRValueRef(Expr *MemRef) { 2019 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 2020 return Referenced->getType()->isRValueReferenceType(); 2021} 2022 2023static bool 2024BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2025 ImplicitInitializerKind ImplicitInitKind, 2026 FieldDecl *Field, IndirectFieldDecl *Indirect, 2027 CXXCtorInitializer *&CXXMemberInit) { 2028 if (Field->isInvalidDecl()) 2029 return true; 2030 2031 SourceLocation Loc = Constructor->getLocation(); 2032 2033 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 2034 bool Moving = ImplicitInitKind == IIK_Move; 2035 ParmVarDecl *Param = Constructor->getParamDecl(0); 2036 QualType ParamType = Param->getType().getNonReferenceType(); 2037 2038 // Suppress copying zero-width bitfields. 2039 if (const Expr *Width = Field->getBitWidth()) 2040 if (Width->EvaluateAsInt(SemaRef.Context) == 0) 2041 return false; 2042 2043 Expr *MemberExprBase = 2044 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param, 2045 Loc, ParamType, VK_LValue, 0); 2046 2047 if (Moving) { 2048 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 2049 } 2050 2051 // Build a reference to this field within the parameter. 2052 CXXScopeSpec SS; 2053 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 2054 Sema::LookupMemberName); 2055 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 2056 : cast<ValueDecl>(Field), AS_public); 2057 MemberLookup.resolveKind(); 2058 ExprResult CtorArg 2059 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 2060 ParamType, Loc, 2061 /*IsArrow=*/false, 2062 SS, 2063 /*FirstQualifierInScope=*/0, 2064 MemberLookup, 2065 /*TemplateArgs=*/0); 2066 if (CtorArg.isInvalid()) 2067 return true; 2068 2069 // C++11 [class.copy]p15: 2070 // - if a member m has rvalue reference type T&&, it is direct-initialized 2071 // with static_cast<T&&>(x.m); 2072 if (RefersToRValueRef(CtorArg.get())) { 2073 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2074 } 2075 2076 // When the field we are copying is an array, create index variables for 2077 // each dimension of the array. We use these index variables to subscript 2078 // the source array, and other clients (e.g., CodeGen) will perform the 2079 // necessary iteration with these index variables. 2080 SmallVector<VarDecl *, 4> IndexVariables; 2081 QualType BaseType = Field->getType(); 2082 QualType SizeType = SemaRef.Context.getSizeType(); 2083 bool InitializingArray = false; 2084 while (const ConstantArrayType *Array 2085 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 2086 InitializingArray = true; 2087 // Create the iteration variable for this array index. 2088 IdentifierInfo *IterationVarName = 0; 2089 { 2090 llvm::SmallString<8> Str; 2091 llvm::raw_svector_ostream OS(Str); 2092 OS << "__i" << IndexVariables.size(); 2093 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 2094 } 2095 VarDecl *IterationVar 2096 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 2097 IterationVarName, SizeType, 2098 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 2099 SC_None, SC_None); 2100 IndexVariables.push_back(IterationVar); 2101 2102 // Create a reference to the iteration variable. 2103 ExprResult IterationVarRef 2104 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc); 2105 assert(!IterationVarRef.isInvalid() && 2106 "Reference to invented variable cannot fail!"); 2107 2108 // Subscript the array with this iteration variable. 2109 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 2110 IterationVarRef.take(), 2111 Loc); 2112 if (CtorArg.isInvalid()) 2113 return true; 2114 2115 BaseType = Array->getElementType(); 2116 } 2117 2118 // The array subscript expression is an lvalue, which is wrong for moving. 2119 if (Moving && InitializingArray) 2120 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2121 2122 // Construct the entity that we will be initializing. For an array, this 2123 // will be first element in the array, which may require several levels 2124 // of array-subscript entities. 2125 SmallVector<InitializedEntity, 4> Entities; 2126 Entities.reserve(1 + IndexVariables.size()); 2127 if (Indirect) 2128 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 2129 else 2130 Entities.push_back(InitializedEntity::InitializeMember(Field)); 2131 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 2132 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 2133 0, 2134 Entities.back())); 2135 2136 // Direct-initialize to use the copy constructor. 2137 InitializationKind InitKind = 2138 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 2139 2140 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 2141 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 2142 &CtorArgE, 1); 2143 2144 ExprResult MemberInit 2145 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 2146 MultiExprArg(&CtorArgE, 1)); 2147 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2148 if (MemberInit.isInvalid()) 2149 return true; 2150 2151 if (Indirect) { 2152 assert(IndexVariables.size() == 0 && 2153 "Indirect field improperly initialized"); 2154 CXXMemberInit 2155 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2156 Loc, Loc, 2157 MemberInit.takeAs<Expr>(), 2158 Loc); 2159 } else 2160 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 2161 Loc, MemberInit.takeAs<Expr>(), 2162 Loc, 2163 IndexVariables.data(), 2164 IndexVariables.size()); 2165 return false; 2166 } 2167 2168 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!"); 2169 2170 QualType FieldBaseElementType = 2171 SemaRef.Context.getBaseElementType(Field->getType()); 2172 2173 if (FieldBaseElementType->isRecordType()) { 2174 InitializedEntity InitEntity 2175 = Indirect? InitializedEntity::InitializeMember(Indirect) 2176 : InitializedEntity::InitializeMember(Field); 2177 InitializationKind InitKind = 2178 InitializationKind::CreateDefault(Loc); 2179 2180 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2181 ExprResult MemberInit = 2182 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2183 2184 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2185 if (MemberInit.isInvalid()) 2186 return true; 2187 2188 if (Indirect) 2189 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2190 Indirect, Loc, 2191 Loc, 2192 MemberInit.get(), 2193 Loc); 2194 else 2195 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2196 Field, Loc, Loc, 2197 MemberInit.get(), 2198 Loc); 2199 return false; 2200 } 2201 2202 if (!Field->getParent()->isUnion()) { 2203 if (FieldBaseElementType->isReferenceType()) { 2204 SemaRef.Diag(Constructor->getLocation(), 2205 diag::err_uninitialized_member_in_ctor) 2206 << (int)Constructor->isImplicit() 2207 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2208 << 0 << Field->getDeclName(); 2209 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2210 return true; 2211 } 2212 2213 if (FieldBaseElementType.isConstQualified()) { 2214 SemaRef.Diag(Constructor->getLocation(), 2215 diag::err_uninitialized_member_in_ctor) 2216 << (int)Constructor->isImplicit() 2217 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2218 << 1 << Field->getDeclName(); 2219 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2220 return true; 2221 } 2222 } 2223 2224 if (SemaRef.getLangOptions().ObjCAutoRefCount && 2225 FieldBaseElementType->isObjCRetainableType() && 2226 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 2227 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 2228 // Instant objects: 2229 // Default-initialize Objective-C pointers to NULL. 2230 CXXMemberInit 2231 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 2232 Loc, Loc, 2233 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 2234 Loc); 2235 return false; 2236 } 2237 2238 // Nothing to initialize. 2239 CXXMemberInit = 0; 2240 return false; 2241} 2242 2243namespace { 2244struct BaseAndFieldInfo { 2245 Sema &S; 2246 CXXConstructorDecl *Ctor; 2247 bool AnyErrorsInInits; 2248 ImplicitInitializerKind IIK; 2249 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 2250 SmallVector<CXXCtorInitializer*, 8> AllToInit; 2251 2252 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 2253 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 2254 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 2255 if (Generated && Ctor->isCopyConstructor()) 2256 IIK = IIK_Copy; 2257 else if (Generated && Ctor->isMoveConstructor()) 2258 IIK = IIK_Move; 2259 else 2260 IIK = IIK_Default; 2261 } 2262}; 2263} 2264 2265static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 2266 FieldDecl *Field, 2267 IndirectFieldDecl *Indirect = 0) { 2268 2269 // Overwhelmingly common case: we have a direct initializer for this field. 2270 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) { 2271 Info.AllToInit.push_back(Init); 2272 return false; 2273 } 2274 2275 // C++0x [class.base.init]p8: if the entity is a non-static data member that 2276 // has a brace-or-equal-initializer, the entity is initialized as specified 2277 // in [dcl.init]. 2278 if (Field->hasInClassInitializer()) { 2279 CXXCtorInitializer *Init; 2280 if (Indirect) 2281 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2282 SourceLocation(), 2283 SourceLocation(), 0, 2284 SourceLocation()); 2285 else 2286 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 2287 SourceLocation(), 2288 SourceLocation(), 0, 2289 SourceLocation()); 2290 Info.AllToInit.push_back(Init); 2291 return false; 2292 } 2293 2294 // Don't try to build an implicit initializer if there were semantic 2295 // errors in any of the initializers (and therefore we might be 2296 // missing some that the user actually wrote). 2297 if (Info.AnyErrorsInInits || Field->isInvalidDecl()) 2298 return false; 2299 2300 CXXCtorInitializer *Init = 0; 2301 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 2302 Indirect, Init)) 2303 return true; 2304 2305 if (Init) 2306 Info.AllToInit.push_back(Init); 2307 2308 return false; 2309} 2310 2311bool 2312Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 2313 CXXCtorInitializer *Initializer) { 2314 assert(Initializer->isDelegatingInitializer()); 2315 Constructor->setNumCtorInitializers(1); 2316 CXXCtorInitializer **initializer = 2317 new (Context) CXXCtorInitializer*[1]; 2318 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 2319 Constructor->setCtorInitializers(initializer); 2320 2321 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 2322 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor); 2323 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 2324 } 2325 2326 DelegatingCtorDecls.push_back(Constructor); 2327 2328 return false; 2329} 2330 2331/// \brief Determine whether the given indirect field declaration is somewhere 2332/// within an anonymous union. 2333static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 2334 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 2335 CEnd = F->chain_end(); 2336 C != CEnd; ++C) 2337 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 2338 if (Record->isUnion()) 2339 return true; 2340 2341 return false; 2342} 2343 2344bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, 2345 CXXCtorInitializer **Initializers, 2346 unsigned NumInitializers, 2347 bool AnyErrors) { 2348 if (Constructor->getDeclContext()->isDependentContext()) { 2349 // Just store the initializers as written, they will be checked during 2350 // instantiation. 2351 if (NumInitializers > 0) { 2352 Constructor->setNumCtorInitializers(NumInitializers); 2353 CXXCtorInitializer **baseOrMemberInitializers = 2354 new (Context) CXXCtorInitializer*[NumInitializers]; 2355 memcpy(baseOrMemberInitializers, Initializers, 2356 NumInitializers * sizeof(CXXCtorInitializer*)); 2357 Constructor->setCtorInitializers(baseOrMemberInitializers); 2358 } 2359 2360 return false; 2361 } 2362 2363 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 2364 2365 // We need to build the initializer AST according to order of construction 2366 // and not what user specified in the Initializers list. 2367 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 2368 if (!ClassDecl) 2369 return true; 2370 2371 bool HadError = false; 2372 2373 for (unsigned i = 0; i < NumInitializers; i++) { 2374 CXXCtorInitializer *Member = Initializers[i]; 2375 2376 if (Member->isBaseInitializer()) 2377 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 2378 else 2379 Info.AllBaseFields[Member->getAnyMember()] = Member; 2380 } 2381 2382 // Keep track of the direct virtual bases. 2383 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 2384 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 2385 E = ClassDecl->bases_end(); I != E; ++I) { 2386 if (I->isVirtual()) 2387 DirectVBases.insert(I); 2388 } 2389 2390 // Push virtual bases before others. 2391 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2392 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2393 2394 if (CXXCtorInitializer *Value 2395 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 2396 Info.AllToInit.push_back(Value); 2397 } else if (!AnyErrors) { 2398 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 2399 CXXCtorInitializer *CXXBaseInit; 2400 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 2401 VBase, IsInheritedVirtualBase, 2402 CXXBaseInit)) { 2403 HadError = true; 2404 continue; 2405 } 2406 2407 Info.AllToInit.push_back(CXXBaseInit); 2408 } 2409 } 2410 2411 // Non-virtual bases. 2412 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2413 E = ClassDecl->bases_end(); Base != E; ++Base) { 2414 // Virtuals are in the virtual base list and already constructed. 2415 if (Base->isVirtual()) 2416 continue; 2417 2418 if (CXXCtorInitializer *Value 2419 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 2420 Info.AllToInit.push_back(Value); 2421 } else if (!AnyErrors) { 2422 CXXCtorInitializer *CXXBaseInit; 2423 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 2424 Base, /*IsInheritedVirtualBase=*/false, 2425 CXXBaseInit)) { 2426 HadError = true; 2427 continue; 2428 } 2429 2430 Info.AllToInit.push_back(CXXBaseInit); 2431 } 2432 } 2433 2434 // Fields. 2435 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 2436 MemEnd = ClassDecl->decls_end(); 2437 Mem != MemEnd; ++Mem) { 2438 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 2439 if (F->getType()->isIncompleteArrayType()) { 2440 assert(ClassDecl->hasFlexibleArrayMember() && 2441 "Incomplete array type is not valid"); 2442 continue; 2443 } 2444 2445 // If we're not generating the implicit copy/move constructor, then we'll 2446 // handle anonymous struct/union fields based on their individual 2447 // indirect fields. 2448 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default) 2449 continue; 2450 2451 if (CollectFieldInitializer(*this, Info, F)) 2452 HadError = true; 2453 continue; 2454 } 2455 2456 // Beyond this point, we only consider default initialization. 2457 if (Info.IIK != IIK_Default) 2458 continue; 2459 2460 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 2461 if (F->getType()->isIncompleteArrayType()) { 2462 assert(ClassDecl->hasFlexibleArrayMember() && 2463 "Incomplete array type is not valid"); 2464 continue; 2465 } 2466 2467 // If this field is somewhere within an anonymous union, we only 2468 // initialize it if there's an explicit initializer. 2469 if (isWithinAnonymousUnion(F)) { 2470 if (CXXCtorInitializer *Init 2471 = Info.AllBaseFields.lookup(F->getAnonField())) { 2472 Info.AllToInit.push_back(Init); 2473 } 2474 2475 continue; 2476 } 2477 2478 // Initialize each field of an anonymous struct individually. 2479 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 2480 HadError = true; 2481 2482 continue; 2483 } 2484 } 2485 2486 NumInitializers = Info.AllToInit.size(); 2487 if (NumInitializers > 0) { 2488 Constructor->setNumCtorInitializers(NumInitializers); 2489 CXXCtorInitializer **baseOrMemberInitializers = 2490 new (Context) CXXCtorInitializer*[NumInitializers]; 2491 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 2492 NumInitializers * sizeof(CXXCtorInitializer*)); 2493 Constructor->setCtorInitializers(baseOrMemberInitializers); 2494 2495 // Constructors implicitly reference the base and member 2496 // destructors. 2497 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 2498 Constructor->getParent()); 2499 } 2500 2501 return HadError; 2502} 2503 2504static void *GetKeyForTopLevelField(FieldDecl *Field) { 2505 // For anonymous unions, use the class declaration as the key. 2506 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 2507 if (RT->getDecl()->isAnonymousStructOrUnion()) 2508 return static_cast<void *>(RT->getDecl()); 2509 } 2510 return static_cast<void *>(Field); 2511} 2512 2513static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 2514 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 2515} 2516 2517static void *GetKeyForMember(ASTContext &Context, 2518 CXXCtorInitializer *Member) { 2519 if (!Member->isAnyMemberInitializer()) 2520 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 2521 2522 // For fields injected into the class via declaration of an anonymous union, 2523 // use its anonymous union class declaration as the unique key. 2524 FieldDecl *Field = Member->getAnyMember(); 2525 2526 // If the field is a member of an anonymous struct or union, our key 2527 // is the anonymous record decl that's a direct child of the class. 2528 RecordDecl *RD = Field->getParent(); 2529 if (RD->isAnonymousStructOrUnion()) { 2530 while (true) { 2531 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext()); 2532 if (Parent->isAnonymousStructOrUnion()) 2533 RD = Parent; 2534 else 2535 break; 2536 } 2537 2538 return static_cast<void *>(RD); 2539 } 2540 2541 return static_cast<void *>(Field); 2542} 2543 2544static void 2545DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, 2546 const CXXConstructorDecl *Constructor, 2547 CXXCtorInitializer **Inits, 2548 unsigned NumInits) { 2549 if (Constructor->getDeclContext()->isDependentContext()) 2550 return; 2551 2552 // Don't check initializers order unless the warning is enabled at the 2553 // location of at least one initializer. 2554 bool ShouldCheckOrder = false; 2555 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 2556 CXXCtorInitializer *Init = Inits[InitIndex]; 2557 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 2558 Init->getSourceLocation()) 2559 != Diagnostic::Ignored) { 2560 ShouldCheckOrder = true; 2561 break; 2562 } 2563 } 2564 if (!ShouldCheckOrder) 2565 return; 2566 2567 // Build the list of bases and members in the order that they'll 2568 // actually be initialized. The explicit initializers should be in 2569 // this same order but may be missing things. 2570 SmallVector<const void*, 32> IdealInitKeys; 2571 2572 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 2573 2574 // 1. Virtual bases. 2575 for (CXXRecordDecl::base_class_const_iterator VBase = 2576 ClassDecl->vbases_begin(), 2577 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 2578 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 2579 2580 // 2. Non-virtual bases. 2581 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 2582 E = ClassDecl->bases_end(); Base != E; ++Base) { 2583 if (Base->isVirtual()) 2584 continue; 2585 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 2586 } 2587 2588 // 3. Direct fields. 2589 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2590 E = ClassDecl->field_end(); Field != E; ++Field) 2591 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field)); 2592 2593 unsigned NumIdealInits = IdealInitKeys.size(); 2594 unsigned IdealIndex = 0; 2595 2596 CXXCtorInitializer *PrevInit = 0; 2597 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 2598 CXXCtorInitializer *Init = Inits[InitIndex]; 2599 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 2600 2601 // Scan forward to try to find this initializer in the idealized 2602 // initializers list. 2603 for (; IdealIndex != NumIdealInits; ++IdealIndex) 2604 if (InitKey == IdealInitKeys[IdealIndex]) 2605 break; 2606 2607 // If we didn't find this initializer, it must be because we 2608 // scanned past it on a previous iteration. That can only 2609 // happen if we're out of order; emit a warning. 2610 if (IdealIndex == NumIdealInits && PrevInit) { 2611 Sema::SemaDiagnosticBuilder D = 2612 SemaRef.Diag(PrevInit->getSourceLocation(), 2613 diag::warn_initializer_out_of_order); 2614 2615 if (PrevInit->isAnyMemberInitializer()) 2616 D << 0 << PrevInit->getAnyMember()->getDeclName(); 2617 else 2618 D << 1 << PrevInit->getBaseClassInfo()->getType(); 2619 2620 if (Init->isAnyMemberInitializer()) 2621 D << 0 << Init->getAnyMember()->getDeclName(); 2622 else 2623 D << 1 << Init->getBaseClassInfo()->getType(); 2624 2625 // Move back to the initializer's location in the ideal list. 2626 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 2627 if (InitKey == IdealInitKeys[IdealIndex]) 2628 break; 2629 2630 assert(IdealIndex != NumIdealInits && 2631 "initializer not found in initializer list"); 2632 } 2633 2634 PrevInit = Init; 2635 } 2636} 2637 2638namespace { 2639bool CheckRedundantInit(Sema &S, 2640 CXXCtorInitializer *Init, 2641 CXXCtorInitializer *&PrevInit) { 2642 if (!PrevInit) { 2643 PrevInit = Init; 2644 return false; 2645 } 2646 2647 if (FieldDecl *Field = Init->getMember()) 2648 S.Diag(Init->getSourceLocation(), 2649 diag::err_multiple_mem_initialization) 2650 << Field->getDeclName() 2651 << Init->getSourceRange(); 2652 else { 2653 const Type *BaseClass = Init->getBaseClass(); 2654 assert(BaseClass && "neither field nor base"); 2655 S.Diag(Init->getSourceLocation(), 2656 diag::err_multiple_base_initialization) 2657 << QualType(BaseClass, 0) 2658 << Init->getSourceRange(); 2659 } 2660 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 2661 << 0 << PrevInit->getSourceRange(); 2662 2663 return true; 2664} 2665 2666typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 2667typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 2668 2669bool CheckRedundantUnionInit(Sema &S, 2670 CXXCtorInitializer *Init, 2671 RedundantUnionMap &Unions) { 2672 FieldDecl *Field = Init->getAnyMember(); 2673 RecordDecl *Parent = Field->getParent(); 2674 if (!Parent->isAnonymousStructOrUnion()) 2675 return false; 2676 2677 NamedDecl *Child = Field; 2678 do { 2679 if (Parent->isUnion()) { 2680 UnionEntry &En = Unions[Parent]; 2681 if (En.first && En.first != Child) { 2682 S.Diag(Init->getSourceLocation(), 2683 diag::err_multiple_mem_union_initialization) 2684 << Field->getDeclName() 2685 << Init->getSourceRange(); 2686 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 2687 << 0 << En.second->getSourceRange(); 2688 return true; 2689 } else if (!En.first) { 2690 En.first = Child; 2691 En.second = Init; 2692 } 2693 } 2694 2695 Child = Parent; 2696 Parent = cast<RecordDecl>(Parent->getDeclContext()); 2697 } while (Parent->isAnonymousStructOrUnion()); 2698 2699 return false; 2700} 2701} 2702 2703/// ActOnMemInitializers - Handle the member initializers for a constructor. 2704void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 2705 SourceLocation ColonLoc, 2706 MemInitTy **meminits, unsigned NumMemInits, 2707 bool AnyErrors) { 2708 if (!ConstructorDecl) 2709 return; 2710 2711 AdjustDeclIfTemplate(ConstructorDecl); 2712 2713 CXXConstructorDecl *Constructor 2714 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 2715 2716 if (!Constructor) { 2717 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 2718 return; 2719 } 2720 2721 CXXCtorInitializer **MemInits = 2722 reinterpret_cast<CXXCtorInitializer **>(meminits); 2723 2724 // Mapping for the duplicate initializers check. 2725 // For member initializers, this is keyed with a FieldDecl*. 2726 // For base initializers, this is keyed with a Type*. 2727 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 2728 2729 // Mapping for the inconsistent anonymous-union initializers check. 2730 RedundantUnionMap MemberUnions; 2731 2732 bool HadError = false; 2733 for (unsigned i = 0; i < NumMemInits; i++) { 2734 CXXCtorInitializer *Init = MemInits[i]; 2735 2736 // Set the source order index. 2737 Init->setSourceOrder(i); 2738 2739 if (Init->isAnyMemberInitializer()) { 2740 FieldDecl *Field = Init->getAnyMember(); 2741 if (CheckRedundantInit(*this, Init, Members[Field]) || 2742 CheckRedundantUnionInit(*this, Init, MemberUnions)) 2743 HadError = true; 2744 } else if (Init->isBaseInitializer()) { 2745 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 2746 if (CheckRedundantInit(*this, Init, Members[Key])) 2747 HadError = true; 2748 } else { 2749 assert(Init->isDelegatingInitializer()); 2750 // This must be the only initializer 2751 if (i != 0 || NumMemInits > 1) { 2752 Diag(MemInits[0]->getSourceLocation(), 2753 diag::err_delegating_initializer_alone) 2754 << MemInits[0]->getSourceRange(); 2755 HadError = true; 2756 // We will treat this as being the only initializer. 2757 } 2758 SetDelegatingInitializer(Constructor, MemInits[i]); 2759 // Return immediately as the initializer is set. 2760 return; 2761 } 2762 } 2763 2764 if (HadError) 2765 return; 2766 2767 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits); 2768 2769 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors); 2770} 2771 2772void 2773Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 2774 CXXRecordDecl *ClassDecl) { 2775 // Ignore dependent contexts. 2776 if (ClassDecl->isDependentContext()) 2777 return; 2778 2779 // FIXME: all the access-control diagnostics are positioned on the 2780 // field/base declaration. That's probably good; that said, the 2781 // user might reasonably want to know why the destructor is being 2782 // emitted, and we currently don't say. 2783 2784 // Non-static data members. 2785 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 2786 E = ClassDecl->field_end(); I != E; ++I) { 2787 FieldDecl *Field = *I; 2788 if (Field->isInvalidDecl()) 2789 continue; 2790 QualType FieldType = Context.getBaseElementType(Field->getType()); 2791 2792 const RecordType* RT = FieldType->getAs<RecordType>(); 2793 if (!RT) 2794 continue; 2795 2796 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2797 if (FieldClassDecl->isInvalidDecl()) 2798 continue; 2799 if (FieldClassDecl->hasTrivialDestructor()) 2800 continue; 2801 2802 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 2803 assert(Dtor && "No dtor found for FieldClassDecl!"); 2804 CheckDestructorAccess(Field->getLocation(), Dtor, 2805 PDiag(diag::err_access_dtor_field) 2806 << Field->getDeclName() 2807 << FieldType); 2808 2809 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2810 } 2811 2812 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 2813 2814 // Bases. 2815 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2816 E = ClassDecl->bases_end(); Base != E; ++Base) { 2817 // Bases are always records in a well-formed non-dependent class. 2818 const RecordType *RT = Base->getType()->getAs<RecordType>(); 2819 2820 // Remember direct virtual bases. 2821 if (Base->isVirtual()) 2822 DirectVirtualBases.insert(RT); 2823 2824 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2825 // If our base class is invalid, we probably can't get its dtor anyway. 2826 if (BaseClassDecl->isInvalidDecl()) 2827 continue; 2828 // Ignore trivial destructors. 2829 if (BaseClassDecl->hasTrivialDestructor()) 2830 continue; 2831 2832 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 2833 assert(Dtor && "No dtor found for BaseClassDecl!"); 2834 2835 // FIXME: caret should be on the start of the class name 2836 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor, 2837 PDiag(diag::err_access_dtor_base) 2838 << Base->getType() 2839 << Base->getSourceRange()); 2840 2841 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2842 } 2843 2844 // Virtual bases. 2845 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2846 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2847 2848 // Bases are always records in a well-formed non-dependent class. 2849 const RecordType *RT = VBase->getType()->getAs<RecordType>(); 2850 2851 // Ignore direct virtual bases. 2852 if (DirectVirtualBases.count(RT)) 2853 continue; 2854 2855 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2856 // If our base class is invalid, we probably can't get its dtor anyway. 2857 if (BaseClassDecl->isInvalidDecl()) 2858 continue; 2859 // Ignore trivial destructors. 2860 if (BaseClassDecl->hasTrivialDestructor()) 2861 continue; 2862 2863 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 2864 assert(Dtor && "No dtor found for BaseClassDecl!"); 2865 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 2866 PDiag(diag::err_access_dtor_vbase) 2867 << VBase->getType()); 2868 2869 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2870 } 2871} 2872 2873void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 2874 if (!CDtorDecl) 2875 return; 2876 2877 if (CXXConstructorDecl *Constructor 2878 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 2879 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 2880} 2881 2882bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2883 unsigned DiagID, AbstractDiagSelID SelID) { 2884 if (SelID == -1) 2885 return RequireNonAbstractType(Loc, T, PDiag(DiagID)); 2886 else 2887 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID); 2888} 2889 2890bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2891 const PartialDiagnostic &PD) { 2892 if (!getLangOptions().CPlusPlus) 2893 return false; 2894 2895 if (const ArrayType *AT = Context.getAsArrayType(T)) 2896 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 2897 2898 if (const PointerType *PT = T->getAs<PointerType>()) { 2899 // Find the innermost pointer type. 2900 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 2901 PT = T; 2902 2903 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 2904 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 2905 } 2906 2907 const RecordType *RT = T->getAs<RecordType>(); 2908 if (!RT) 2909 return false; 2910 2911 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2912 2913 // We can't answer whether something is abstract until it has a 2914 // definition. If it's currently being defined, we'll walk back 2915 // over all the declarations when we have a full definition. 2916 const CXXRecordDecl *Def = RD->getDefinition(); 2917 if (!Def || Def->isBeingDefined()) 2918 return false; 2919 2920 if (!RD->isAbstract()) 2921 return false; 2922 2923 Diag(Loc, PD) << RD->getDeclName(); 2924 DiagnoseAbstractType(RD); 2925 2926 return true; 2927} 2928 2929void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 2930 // Check if we've already emitted the list of pure virtual functions 2931 // for this class. 2932 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 2933 return; 2934 2935 CXXFinalOverriderMap FinalOverriders; 2936 RD->getFinalOverriders(FinalOverriders); 2937 2938 // Keep a set of seen pure methods so we won't diagnose the same method 2939 // more than once. 2940 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 2941 2942 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 2943 MEnd = FinalOverriders.end(); 2944 M != MEnd; 2945 ++M) { 2946 for (OverridingMethods::iterator SO = M->second.begin(), 2947 SOEnd = M->second.end(); 2948 SO != SOEnd; ++SO) { 2949 // C++ [class.abstract]p4: 2950 // A class is abstract if it contains or inherits at least one 2951 // pure virtual function for which the final overrider is pure 2952 // virtual. 2953 2954 // 2955 if (SO->second.size() != 1) 2956 continue; 2957 2958 if (!SO->second.front().Method->isPure()) 2959 continue; 2960 2961 if (!SeenPureMethods.insert(SO->second.front().Method)) 2962 continue; 2963 2964 Diag(SO->second.front().Method->getLocation(), 2965 diag::note_pure_virtual_function) 2966 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 2967 } 2968 } 2969 2970 if (!PureVirtualClassDiagSet) 2971 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 2972 PureVirtualClassDiagSet->insert(RD); 2973} 2974 2975namespace { 2976struct AbstractUsageInfo { 2977 Sema &S; 2978 CXXRecordDecl *Record; 2979 CanQualType AbstractType; 2980 bool Invalid; 2981 2982 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 2983 : S(S), Record(Record), 2984 AbstractType(S.Context.getCanonicalType( 2985 S.Context.getTypeDeclType(Record))), 2986 Invalid(false) {} 2987 2988 void DiagnoseAbstractType() { 2989 if (Invalid) return; 2990 S.DiagnoseAbstractType(Record); 2991 Invalid = true; 2992 } 2993 2994 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 2995}; 2996 2997struct CheckAbstractUsage { 2998 AbstractUsageInfo &Info; 2999 const NamedDecl *Ctx; 3000 3001 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 3002 : Info(Info), Ctx(Ctx) {} 3003 3004 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3005 switch (TL.getTypeLocClass()) { 3006#define ABSTRACT_TYPELOC(CLASS, PARENT) 3007#define TYPELOC(CLASS, PARENT) \ 3008 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break; 3009#include "clang/AST/TypeLocNodes.def" 3010 } 3011 } 3012 3013 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3014 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 3015 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3016 if (!TL.getArg(I)) 3017 continue; 3018 3019 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 3020 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 3021 } 3022 } 3023 3024 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3025 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 3026 } 3027 3028 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3029 // Visit the type parameters from a permissive context. 3030 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3031 TemplateArgumentLoc TAL = TL.getArgLoc(I); 3032 if (TAL.getArgument().getKind() == TemplateArgument::Type) 3033 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 3034 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 3035 // TODO: other template argument types? 3036 } 3037 } 3038 3039 // Visit pointee types from a permissive context. 3040#define CheckPolymorphic(Type) \ 3041 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 3042 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 3043 } 3044 CheckPolymorphic(PointerTypeLoc) 3045 CheckPolymorphic(ReferenceTypeLoc) 3046 CheckPolymorphic(MemberPointerTypeLoc) 3047 CheckPolymorphic(BlockPointerTypeLoc) 3048 3049 /// Handle all the types we haven't given a more specific 3050 /// implementation for above. 3051 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3052 // Every other kind of type that we haven't called out already 3053 // that has an inner type is either (1) sugar or (2) contains that 3054 // inner type in some way as a subobject. 3055 if (TypeLoc Next = TL.getNextTypeLoc()) 3056 return Visit(Next, Sel); 3057 3058 // If there's no inner type and we're in a permissive context, 3059 // don't diagnose. 3060 if (Sel == Sema::AbstractNone) return; 3061 3062 // Check whether the type matches the abstract type. 3063 QualType T = TL.getType(); 3064 if (T->isArrayType()) { 3065 Sel = Sema::AbstractArrayType; 3066 T = Info.S.Context.getBaseElementType(T); 3067 } 3068 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 3069 if (CT != Info.AbstractType) return; 3070 3071 // It matched; do some magic. 3072 if (Sel == Sema::AbstractArrayType) { 3073 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 3074 << T << TL.getSourceRange(); 3075 } else { 3076 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 3077 << Sel << T << TL.getSourceRange(); 3078 } 3079 Info.DiagnoseAbstractType(); 3080 } 3081}; 3082 3083void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 3084 Sema::AbstractDiagSelID Sel) { 3085 CheckAbstractUsage(*this, D).Visit(TL, Sel); 3086} 3087 3088} 3089 3090/// Check for invalid uses of an abstract type in a method declaration. 3091static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3092 CXXMethodDecl *MD) { 3093 // No need to do the check on definitions, which require that 3094 // the return/param types be complete. 3095 if (MD->doesThisDeclarationHaveABody()) 3096 return; 3097 3098 // For safety's sake, just ignore it if we don't have type source 3099 // information. This should never happen for non-implicit methods, 3100 // but... 3101 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 3102 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 3103} 3104 3105/// Check for invalid uses of an abstract type within a class definition. 3106static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3107 CXXRecordDecl *RD) { 3108 for (CXXRecordDecl::decl_iterator 3109 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 3110 Decl *D = *I; 3111 if (D->isImplicit()) continue; 3112 3113 // Methods and method templates. 3114 if (isa<CXXMethodDecl>(D)) { 3115 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 3116 } else if (isa<FunctionTemplateDecl>(D)) { 3117 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 3118 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 3119 3120 // Fields and static variables. 3121 } else if (isa<FieldDecl>(D)) { 3122 FieldDecl *FD = cast<FieldDecl>(D); 3123 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 3124 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 3125 } else if (isa<VarDecl>(D)) { 3126 VarDecl *VD = cast<VarDecl>(D); 3127 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 3128 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 3129 3130 // Nested classes and class templates. 3131 } else if (isa<CXXRecordDecl>(D)) { 3132 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 3133 } else if (isa<ClassTemplateDecl>(D)) { 3134 CheckAbstractClassUsage(Info, 3135 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 3136 } 3137 } 3138} 3139 3140/// \brief Perform semantic checks on a class definition that has been 3141/// completing, introducing implicitly-declared members, checking for 3142/// abstract types, etc. 3143void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 3144 if (!Record) 3145 return; 3146 3147 if (Record->isAbstract() && !Record->isInvalidDecl()) { 3148 AbstractUsageInfo Info(*this, Record); 3149 CheckAbstractClassUsage(Info, Record); 3150 } 3151 3152 // If this is not an aggregate type and has no user-declared constructor, 3153 // complain about any non-static data members of reference or const scalar 3154 // type, since they will never get initializers. 3155 if (!Record->isInvalidDecl() && !Record->isDependentType() && 3156 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) { 3157 bool Complained = false; 3158 for (RecordDecl::field_iterator F = Record->field_begin(), 3159 FEnd = Record->field_end(); 3160 F != FEnd; ++F) { 3161 if (F->hasInClassInitializer()) 3162 continue; 3163 3164 if (F->getType()->isReferenceType() || 3165 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 3166 if (!Complained) { 3167 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 3168 << Record->getTagKind() << Record; 3169 Complained = true; 3170 } 3171 3172 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 3173 << F->getType()->isReferenceType() 3174 << F->getDeclName(); 3175 } 3176 } 3177 } 3178 3179 if (Record->isDynamicClass() && !Record->isDependentType()) 3180 DynamicClasses.push_back(Record); 3181 3182 if (Record->getIdentifier()) { 3183 // C++ [class.mem]p13: 3184 // If T is the name of a class, then each of the following shall have a 3185 // name different from T: 3186 // - every member of every anonymous union that is a member of class T. 3187 // 3188 // C++ [class.mem]p14: 3189 // In addition, if class T has a user-declared constructor (12.1), every 3190 // non-static data member of class T shall have a name different from T. 3191 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 3192 R.first != R.second; ++R.first) { 3193 NamedDecl *D = *R.first; 3194 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 3195 isa<IndirectFieldDecl>(D)) { 3196 Diag(D->getLocation(), diag::err_member_name_of_class) 3197 << D->getDeclName(); 3198 break; 3199 } 3200 } 3201 } 3202 3203 // Warn if the class has virtual methods but non-virtual public destructor. 3204 if (Record->isPolymorphic() && !Record->isDependentType()) { 3205 CXXDestructorDecl *dtor = Record->getDestructor(); 3206 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 3207 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 3208 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 3209 } 3210 3211 // See if a method overloads virtual methods in a base 3212 /// class without overriding any. 3213 if (!Record->isDependentType()) { 3214 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 3215 MEnd = Record->method_end(); 3216 M != MEnd; ++M) { 3217 if (!(*M)->isStatic()) 3218 DiagnoseHiddenVirtualMethods(Record, *M); 3219 } 3220 } 3221 3222 // Declare inherited constructors. We do this eagerly here because: 3223 // - The standard requires an eager diagnostic for conflicting inherited 3224 // constructors from different classes. 3225 // - The lazy declaration of the other implicit constructors is so as to not 3226 // waste space and performance on classes that are not meant to be 3227 // instantiated (e.g. meta-functions). This doesn't apply to classes that 3228 // have inherited constructors. 3229 DeclareInheritedConstructors(Record); 3230 3231 if (!Record->isDependentType()) 3232 CheckExplicitlyDefaultedMethods(Record); 3233} 3234 3235void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) { 3236 for (CXXRecordDecl::method_iterator MI = Record->method_begin(), 3237 ME = Record->method_end(); 3238 MI != ME; ++MI) { 3239 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) { 3240 switch (getSpecialMember(*MI)) { 3241 case CXXDefaultConstructor: 3242 CheckExplicitlyDefaultedDefaultConstructor( 3243 cast<CXXConstructorDecl>(*MI)); 3244 break; 3245 3246 case CXXDestructor: 3247 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI)); 3248 break; 3249 3250 case CXXCopyConstructor: 3251 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI)); 3252 break; 3253 3254 case CXXCopyAssignment: 3255 CheckExplicitlyDefaultedCopyAssignment(*MI); 3256 break; 3257 3258 case CXXMoveConstructor: 3259 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI)); 3260 break; 3261 3262 case CXXMoveAssignment: 3263 CheckExplicitlyDefaultedMoveAssignment(*MI); 3264 break; 3265 3266 case CXXInvalid: 3267 llvm_unreachable("non-special member explicitly defaulted!"); 3268 } 3269 } 3270 } 3271 3272} 3273 3274void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) { 3275 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor()); 3276 3277 // Whether this was the first-declared instance of the constructor. 3278 // This affects whether we implicitly add an exception spec (and, eventually, 3279 // constexpr). It is also ill-formed to explicitly default a constructor such 3280 // that it would be deleted. (C++0x [decl.fct.def.default]) 3281 bool First = CD == CD->getCanonicalDecl(); 3282 3283 bool HadError = false; 3284 if (CD->getNumParams() != 0) { 3285 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params) 3286 << CD->getSourceRange(); 3287 HadError = true; 3288 } 3289 3290 ImplicitExceptionSpecification Spec 3291 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent()); 3292 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3293 if (EPI.ExceptionSpecType == EST_Delayed) { 3294 // Exception specification depends on some deferred part of the class. We'll 3295 // try again when the class's definition has been fully processed. 3296 return; 3297 } 3298 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(), 3299 *ExceptionType = Context.getFunctionType( 3300 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3301 3302 if (CtorType->hasExceptionSpec()) { 3303 if (CheckEquivalentExceptionSpec( 3304 PDiag(diag::err_incorrect_defaulted_exception_spec) 3305 << CXXDefaultConstructor, 3306 PDiag(), 3307 ExceptionType, SourceLocation(), 3308 CtorType, CD->getLocation())) { 3309 HadError = true; 3310 } 3311 } else if (First) { 3312 // We set the declaration to have the computed exception spec here. 3313 // We know there are no parameters. 3314 EPI.ExtInfo = CtorType->getExtInfo(); 3315 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 3316 } 3317 3318 if (HadError) { 3319 CD->setInvalidDecl(); 3320 return; 3321 } 3322 3323 if (ShouldDeleteDefaultConstructor(CD)) { 3324 if (First) { 3325 CD->setDeletedAsWritten(); 3326 } else { 3327 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes) 3328 << CXXDefaultConstructor; 3329 CD->setInvalidDecl(); 3330 } 3331 } 3332} 3333 3334void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) { 3335 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor()); 3336 3337 // Whether this was the first-declared instance of the constructor. 3338 bool First = CD == CD->getCanonicalDecl(); 3339 3340 bool HadError = false; 3341 if (CD->getNumParams() != 1) { 3342 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params) 3343 << CD->getSourceRange(); 3344 HadError = true; 3345 } 3346 3347 ImplicitExceptionSpecification Spec(Context); 3348 bool Const; 3349 llvm::tie(Spec, Const) = 3350 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent()); 3351 3352 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3353 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(), 3354 *ExceptionType = Context.getFunctionType( 3355 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3356 3357 // Check for parameter type matching. 3358 // This is a copy ctor so we know it's a cv-qualified reference to T. 3359 QualType ArgType = CtorType->getArgType(0); 3360 if (ArgType->getPointeeType().isVolatileQualified()) { 3361 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param); 3362 HadError = true; 3363 } 3364 if (ArgType->getPointeeType().isConstQualified() && !Const) { 3365 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param); 3366 HadError = true; 3367 } 3368 3369 if (CtorType->hasExceptionSpec()) { 3370 if (CheckEquivalentExceptionSpec( 3371 PDiag(diag::err_incorrect_defaulted_exception_spec) 3372 << CXXCopyConstructor, 3373 PDiag(), 3374 ExceptionType, SourceLocation(), 3375 CtorType, CD->getLocation())) { 3376 HadError = true; 3377 } 3378 } else if (First) { 3379 // We set the declaration to have the computed exception spec here. 3380 // We duplicate the one parameter type. 3381 EPI.ExtInfo = CtorType->getExtInfo(); 3382 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 3383 } 3384 3385 if (HadError) { 3386 CD->setInvalidDecl(); 3387 return; 3388 } 3389 3390 if (ShouldDeleteCopyConstructor(CD)) { 3391 if (First) { 3392 CD->setDeletedAsWritten(); 3393 } else { 3394 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes) 3395 << CXXCopyConstructor; 3396 CD->setInvalidDecl(); 3397 } 3398 } 3399} 3400 3401void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) { 3402 assert(MD->isExplicitlyDefaulted()); 3403 3404 // Whether this was the first-declared instance of the operator 3405 bool First = MD == MD->getCanonicalDecl(); 3406 3407 bool HadError = false; 3408 if (MD->getNumParams() != 1) { 3409 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params) 3410 << MD->getSourceRange(); 3411 HadError = true; 3412 } 3413 3414 QualType ReturnType = 3415 MD->getType()->getAs<FunctionType>()->getResultType(); 3416 if (!ReturnType->isLValueReferenceType() || 3417 !Context.hasSameType( 3418 Context.getCanonicalType(ReturnType->getPointeeType()), 3419 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) { 3420 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type); 3421 HadError = true; 3422 } 3423 3424 ImplicitExceptionSpecification Spec(Context); 3425 bool Const; 3426 llvm::tie(Spec, Const) = 3427 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent()); 3428 3429 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3430 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(), 3431 *ExceptionType = Context.getFunctionType( 3432 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3433 3434 QualType ArgType = OperType->getArgType(0); 3435 if (!ArgType->isLValueReferenceType()) { 3436 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 3437 HadError = true; 3438 } else { 3439 if (ArgType->getPointeeType().isVolatileQualified()) { 3440 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param); 3441 HadError = true; 3442 } 3443 if (ArgType->getPointeeType().isConstQualified() && !Const) { 3444 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param); 3445 HadError = true; 3446 } 3447 } 3448 3449 if (OperType->getTypeQuals()) { 3450 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals); 3451 HadError = true; 3452 } 3453 3454 if (OperType->hasExceptionSpec()) { 3455 if (CheckEquivalentExceptionSpec( 3456 PDiag(diag::err_incorrect_defaulted_exception_spec) 3457 << CXXCopyAssignment, 3458 PDiag(), 3459 ExceptionType, SourceLocation(), 3460 OperType, MD->getLocation())) { 3461 HadError = true; 3462 } 3463 } else if (First) { 3464 // We set the declaration to have the computed exception spec here. 3465 // We duplicate the one parameter type. 3466 EPI.RefQualifier = OperType->getRefQualifier(); 3467 EPI.ExtInfo = OperType->getExtInfo(); 3468 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI)); 3469 } 3470 3471 if (HadError) { 3472 MD->setInvalidDecl(); 3473 return; 3474 } 3475 3476 if (ShouldDeleteCopyAssignmentOperator(MD)) { 3477 if (First) { 3478 MD->setDeletedAsWritten(); 3479 } else { 3480 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) 3481 << CXXCopyAssignment; 3482 MD->setInvalidDecl(); 3483 } 3484 } 3485} 3486 3487void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) { 3488 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor()); 3489 3490 // Whether this was the first-declared instance of the constructor. 3491 bool First = CD == CD->getCanonicalDecl(); 3492 3493 bool HadError = false; 3494 if (CD->getNumParams() != 1) { 3495 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params) 3496 << CD->getSourceRange(); 3497 HadError = true; 3498 } 3499 3500 ImplicitExceptionSpecification Spec( 3501 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent())); 3502 3503 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3504 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(), 3505 *ExceptionType = Context.getFunctionType( 3506 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3507 3508 // Check for parameter type matching. 3509 // This is a move ctor so we know it's a cv-qualified rvalue reference to T. 3510 QualType ArgType = CtorType->getArgType(0); 3511 if (ArgType->getPointeeType().isVolatileQualified()) { 3512 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param); 3513 HadError = true; 3514 } 3515 if (ArgType->getPointeeType().isConstQualified()) { 3516 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param); 3517 HadError = true; 3518 } 3519 3520 if (CtorType->hasExceptionSpec()) { 3521 if (CheckEquivalentExceptionSpec( 3522 PDiag(diag::err_incorrect_defaulted_exception_spec) 3523 << CXXMoveConstructor, 3524 PDiag(), 3525 ExceptionType, SourceLocation(), 3526 CtorType, CD->getLocation())) { 3527 HadError = true; 3528 } 3529 } else if (First) { 3530 // We set the declaration to have the computed exception spec here. 3531 // We duplicate the one parameter type. 3532 EPI.ExtInfo = CtorType->getExtInfo(); 3533 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 3534 } 3535 3536 if (HadError) { 3537 CD->setInvalidDecl(); 3538 return; 3539 } 3540 3541 if (ShouldDeleteMoveConstructor(CD)) { 3542 if (First) { 3543 CD->setDeletedAsWritten(); 3544 } else { 3545 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes) 3546 << CXXMoveConstructor; 3547 CD->setInvalidDecl(); 3548 } 3549 } 3550} 3551 3552void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) { 3553 assert(MD->isExplicitlyDefaulted()); 3554 3555 // Whether this was the first-declared instance of the operator 3556 bool First = MD == MD->getCanonicalDecl(); 3557 3558 bool HadError = false; 3559 if (MD->getNumParams() != 1) { 3560 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params) 3561 << MD->getSourceRange(); 3562 HadError = true; 3563 } 3564 3565 QualType ReturnType = 3566 MD->getType()->getAs<FunctionType>()->getResultType(); 3567 if (!ReturnType->isLValueReferenceType() || 3568 !Context.hasSameType( 3569 Context.getCanonicalType(ReturnType->getPointeeType()), 3570 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) { 3571 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type); 3572 HadError = true; 3573 } 3574 3575 ImplicitExceptionSpecification Spec( 3576 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent())); 3577 3578 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3579 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(), 3580 *ExceptionType = Context.getFunctionType( 3581 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3582 3583 QualType ArgType = OperType->getArgType(0); 3584 if (!ArgType->isRValueReferenceType()) { 3585 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref); 3586 HadError = true; 3587 } else { 3588 if (ArgType->getPointeeType().isVolatileQualified()) { 3589 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param); 3590 HadError = true; 3591 } 3592 if (ArgType->getPointeeType().isConstQualified()) { 3593 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param); 3594 HadError = true; 3595 } 3596 } 3597 3598 if (OperType->getTypeQuals()) { 3599 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals); 3600 HadError = true; 3601 } 3602 3603 if (OperType->hasExceptionSpec()) { 3604 if (CheckEquivalentExceptionSpec( 3605 PDiag(diag::err_incorrect_defaulted_exception_spec) 3606 << CXXMoveAssignment, 3607 PDiag(), 3608 ExceptionType, SourceLocation(), 3609 OperType, MD->getLocation())) { 3610 HadError = true; 3611 } 3612 } else if (First) { 3613 // We set the declaration to have the computed exception spec here. 3614 // We duplicate the one parameter type. 3615 EPI.RefQualifier = OperType->getRefQualifier(); 3616 EPI.ExtInfo = OperType->getExtInfo(); 3617 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI)); 3618 } 3619 3620 if (HadError) { 3621 MD->setInvalidDecl(); 3622 return; 3623 } 3624 3625 if (ShouldDeleteMoveAssignmentOperator(MD)) { 3626 if (First) { 3627 MD->setDeletedAsWritten(); 3628 } else { 3629 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) 3630 << CXXMoveAssignment; 3631 MD->setInvalidDecl(); 3632 } 3633 } 3634} 3635 3636void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) { 3637 assert(DD->isExplicitlyDefaulted()); 3638 3639 // Whether this was the first-declared instance of the destructor. 3640 bool First = DD == DD->getCanonicalDecl(); 3641 3642 ImplicitExceptionSpecification Spec 3643 = ComputeDefaultedDtorExceptionSpec(DD->getParent()); 3644 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 3645 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(), 3646 *ExceptionType = Context.getFunctionType( 3647 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>(); 3648 3649 if (DtorType->hasExceptionSpec()) { 3650 if (CheckEquivalentExceptionSpec( 3651 PDiag(diag::err_incorrect_defaulted_exception_spec) 3652 << CXXDestructor, 3653 PDiag(), 3654 ExceptionType, SourceLocation(), 3655 DtorType, DD->getLocation())) { 3656 DD->setInvalidDecl(); 3657 return; 3658 } 3659 } else if (First) { 3660 // We set the declaration to have the computed exception spec here. 3661 // There are no parameters. 3662 EPI.ExtInfo = DtorType->getExtInfo(); 3663 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 3664 } 3665 3666 if (ShouldDeleteDestructor(DD)) { 3667 if (First) { 3668 DD->setDeletedAsWritten(); 3669 } else { 3670 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes) 3671 << CXXDestructor; 3672 DD->setInvalidDecl(); 3673 } 3674 } 3675} 3676 3677bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) { 3678 CXXRecordDecl *RD = CD->getParent(); 3679 assert(!RD->isDependentType() && "do deletion after instantiation"); 3680 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 3681 return false; 3682 3683 SourceLocation Loc = CD->getLocation(); 3684 3685 // Do access control from the constructor 3686 ContextRAII CtorContext(*this, CD); 3687 3688 bool Union = RD->isUnion(); 3689 bool AllConst = true; 3690 3691 // We do this because we should never actually use an anonymous 3692 // union's constructor. 3693 if (Union && RD->isAnonymousStructOrUnion()) 3694 return false; 3695 3696 // FIXME: We should put some diagnostic logic right into this function. 3697 3698 // C++0x [class.ctor]/5 3699 // A defaulted default constructor for class X is defined as deleted if: 3700 3701 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 3702 BE = RD->bases_end(); 3703 BI != BE; ++BI) { 3704 // We'll handle this one later 3705 if (BI->isVirtual()) 3706 continue; 3707 3708 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 3709 assert(BaseDecl && "base isn't a CXXRecordDecl"); 3710 3711 // -- any [direct base class] has a type with a destructor that is 3712 // deleted or inaccessible from the defaulted default constructor 3713 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 3714 if (BaseDtor->isDeleted()) 3715 return true; 3716 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 3717 AR_accessible) 3718 return true; 3719 3720 // -- any [direct base class either] has no default constructor or 3721 // overload resolution as applied to [its] default constructor 3722 // results in an ambiguity or in a function that is deleted or 3723 // inaccessible from the defaulted default constructor 3724 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl); 3725 if (!BaseDefault || BaseDefault->isDeleted()) 3726 return true; 3727 3728 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(), 3729 PDiag()) != AR_accessible) 3730 return true; 3731 } 3732 3733 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 3734 BE = RD->vbases_end(); 3735 BI != BE; ++BI) { 3736 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 3737 assert(BaseDecl && "base isn't a CXXRecordDecl"); 3738 3739 // -- any [virtual base class] has a type with a destructor that is 3740 // delete or inaccessible from the defaulted default constructor 3741 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 3742 if (BaseDtor->isDeleted()) 3743 return true; 3744 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 3745 AR_accessible) 3746 return true; 3747 3748 // -- any [virtual base class either] has no default constructor or 3749 // overload resolution as applied to [its] default constructor 3750 // results in an ambiguity or in a function that is deleted or 3751 // inaccessible from the defaulted default constructor 3752 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl); 3753 if (!BaseDefault || BaseDefault->isDeleted()) 3754 return true; 3755 3756 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(), 3757 PDiag()) != AR_accessible) 3758 return true; 3759 } 3760 3761 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 3762 FE = RD->field_end(); 3763 FI != FE; ++FI) { 3764 if (FI->isInvalidDecl()) 3765 continue; 3766 3767 QualType FieldType = Context.getBaseElementType(FI->getType()); 3768 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 3769 3770 // -- any non-static data member with no brace-or-equal-initializer is of 3771 // reference type 3772 if (FieldType->isReferenceType() && !FI->hasInClassInitializer()) 3773 return true; 3774 3775 // -- X is a union and all its variant members are of const-qualified type 3776 // (or array thereof) 3777 if (Union && !FieldType.isConstQualified()) 3778 AllConst = false; 3779 3780 if (FieldRecord) { 3781 // -- X is a union-like class that has a variant member with a non-trivial 3782 // default constructor 3783 if (Union && !FieldRecord->hasTrivialDefaultConstructor()) 3784 return true; 3785 3786 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord); 3787 if (FieldDtor->isDeleted()) 3788 return true; 3789 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) != 3790 AR_accessible) 3791 return true; 3792 3793 // -- any non-variant non-static data member of const-qualified type (or 3794 // array thereof) with no brace-or-equal-initializer does not have a 3795 // user-provided default constructor 3796 if (FieldType.isConstQualified() && 3797 !FI->hasInClassInitializer() && 3798 !FieldRecord->hasUserProvidedDefaultConstructor()) 3799 return true; 3800 3801 if (!Union && FieldRecord->isUnion() && 3802 FieldRecord->isAnonymousStructOrUnion()) { 3803 // We're okay to reuse AllConst here since we only care about the 3804 // value otherwise if we're in a union. 3805 AllConst = true; 3806 3807 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 3808 UE = FieldRecord->field_end(); 3809 UI != UE; ++UI) { 3810 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 3811 CXXRecordDecl *UnionFieldRecord = 3812 UnionFieldType->getAsCXXRecordDecl(); 3813 3814 if (!UnionFieldType.isConstQualified()) 3815 AllConst = false; 3816 3817 if (UnionFieldRecord && 3818 !UnionFieldRecord->hasTrivialDefaultConstructor()) 3819 return true; 3820 } 3821 3822 if (AllConst) 3823 return true; 3824 3825 // Don't try to initialize the anonymous union 3826 // This is technically non-conformant, but sanity demands it. 3827 continue; 3828 } 3829 3830 // -- any non-static data member with no brace-or-equal-initializer has 3831 // class type M (or array thereof) and either M has no default 3832 // constructor or overload resolution as applied to M's default 3833 // constructor results in an ambiguity or in a function that is deleted 3834 // or inaccessible from the defaulted default constructor. 3835 if (!FI->hasInClassInitializer()) { 3836 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord); 3837 if (!FieldDefault || FieldDefault->isDeleted()) 3838 return true; 3839 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(), 3840 PDiag()) != AR_accessible) 3841 return true; 3842 } 3843 } else if (!Union && FieldType.isConstQualified() && 3844 !FI->hasInClassInitializer()) { 3845 // -- any non-variant non-static data member of const-qualified type (or 3846 // array thereof) with no brace-or-equal-initializer does not have a 3847 // user-provided default constructor 3848 return true; 3849 } 3850 } 3851 3852 if (Union && AllConst) 3853 return true; 3854 3855 return false; 3856} 3857 3858bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) { 3859 CXXRecordDecl *RD = CD->getParent(); 3860 assert(!RD->isDependentType() && "do deletion after instantiation"); 3861 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 3862 return false; 3863 3864 SourceLocation Loc = CD->getLocation(); 3865 3866 // Do access control from the constructor 3867 ContextRAII CtorContext(*this, CD); 3868 3869 bool Union = RD->isUnion(); 3870 3871 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() && 3872 "copy assignment arg has no pointee type"); 3873 unsigned ArgQuals = 3874 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ? 3875 Qualifiers::Const : 0; 3876 3877 // We do this because we should never actually use an anonymous 3878 // union's constructor. 3879 if (Union && RD->isAnonymousStructOrUnion()) 3880 return false; 3881 3882 // FIXME: We should put some diagnostic logic right into this function. 3883 3884 // C++0x [class.copy]/11 3885 // A defaulted [copy] constructor for class X is defined as delete if X has: 3886 3887 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 3888 BE = RD->bases_end(); 3889 BI != BE; ++BI) { 3890 // We'll handle this one later 3891 if (BI->isVirtual()) 3892 continue; 3893 3894 QualType BaseType = BI->getType(); 3895 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 3896 assert(BaseDecl && "base isn't a CXXRecordDecl"); 3897 3898 // -- any [direct base class] of a type with a destructor that is deleted or 3899 // inaccessible from the defaulted constructor 3900 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 3901 if (BaseDtor->isDeleted()) 3902 return true; 3903 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 3904 AR_accessible) 3905 return true; 3906 3907 // -- a [direct base class] B that cannot be [copied] because overload 3908 // resolution, as applied to B's [copy] constructor, results in an 3909 // ambiguity or a function that is deleted or inaccessible from the 3910 // defaulted constructor 3911 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals); 3912 if (!BaseCtor || BaseCtor->isDeleted()) 3913 return true; 3914 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) != 3915 AR_accessible) 3916 return true; 3917 } 3918 3919 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 3920 BE = RD->vbases_end(); 3921 BI != BE; ++BI) { 3922 QualType BaseType = BI->getType(); 3923 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 3924 assert(BaseDecl && "base isn't a CXXRecordDecl"); 3925 3926 // -- any [virtual base class] of a type with a destructor that is deleted or 3927 // inaccessible from the defaulted constructor 3928 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 3929 if (BaseDtor->isDeleted()) 3930 return true; 3931 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 3932 AR_accessible) 3933 return true; 3934 3935 // -- a [virtual base class] B that cannot be [copied] because overload 3936 // resolution, as applied to B's [copy] constructor, results in an 3937 // ambiguity or a function that is deleted or inaccessible from the 3938 // defaulted constructor 3939 CXXConstructorDecl *BaseCtor = LookupCopyingConstructor(BaseDecl, ArgQuals); 3940 if (!BaseCtor || BaseCtor->isDeleted()) 3941 return true; 3942 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) != 3943 AR_accessible) 3944 return true; 3945 } 3946 3947 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 3948 FE = RD->field_end(); 3949 FI != FE; ++FI) { 3950 QualType FieldType = Context.getBaseElementType(FI->getType()); 3951 3952 // -- for a copy constructor, a non-static data member of rvalue reference 3953 // type 3954 if (FieldType->isRValueReferenceType()) 3955 return true; 3956 3957 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 3958 3959 if (FieldRecord) { 3960 // This is an anonymous union 3961 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 3962 // Anonymous unions inside unions do not variant members create 3963 if (!Union) { 3964 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 3965 UE = FieldRecord->field_end(); 3966 UI != UE; ++UI) { 3967 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 3968 CXXRecordDecl *UnionFieldRecord = 3969 UnionFieldType->getAsCXXRecordDecl(); 3970 3971 // -- a variant member with a non-trivial [copy] constructor and X 3972 // is a union-like class 3973 if (UnionFieldRecord && 3974 !UnionFieldRecord->hasTrivialCopyConstructor()) 3975 return true; 3976 } 3977 } 3978 3979 // Don't try to initalize an anonymous union 3980 continue; 3981 } else { 3982 // -- a variant member with a non-trivial [copy] constructor and X is a 3983 // union-like class 3984 if (Union && !FieldRecord->hasTrivialCopyConstructor()) 3985 return true; 3986 3987 // -- any [non-static data member] of a type with a destructor that is 3988 // deleted or inaccessible from the defaulted constructor 3989 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord); 3990 if (FieldDtor->isDeleted()) 3991 return true; 3992 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) != 3993 AR_accessible) 3994 return true; 3995 } 3996 3997 // -- a [non-static data member of class type (or array thereof)] B that 3998 // cannot be [copied] because overload resolution, as applied to B's 3999 // [copy] constructor, results in an ambiguity or a function that is 4000 // deleted or inaccessible from the defaulted constructor 4001 CXXConstructorDecl *FieldCtor = LookupCopyingConstructor(FieldRecord, 4002 ArgQuals); 4003 if (!FieldCtor || FieldCtor->isDeleted()) 4004 return true; 4005 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(), 4006 PDiag()) != AR_accessible) 4007 return true; 4008 } 4009 } 4010 4011 return false; 4012} 4013 4014bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) { 4015 CXXRecordDecl *RD = MD->getParent(); 4016 assert(!RD->isDependentType() && "do deletion after instantiation"); 4017 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4018 return false; 4019 4020 SourceLocation Loc = MD->getLocation(); 4021 4022 // Do access control from the constructor 4023 ContextRAII MethodContext(*this, MD); 4024 4025 bool Union = RD->isUnion(); 4026 4027 unsigned ArgQuals = 4028 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ? 4029 Qualifiers::Const : 0; 4030 4031 // We do this because we should never actually use an anonymous 4032 // union's constructor. 4033 if (Union && RD->isAnonymousStructOrUnion()) 4034 return false; 4035 4036 // FIXME: We should put some diagnostic logic right into this function. 4037 4038 // C++0x [class.copy]/20 4039 // A defaulted [copy] assignment operator for class X is defined as deleted 4040 // if X has: 4041 4042 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4043 BE = RD->bases_end(); 4044 BI != BE; ++BI) { 4045 // We'll handle this one later 4046 if (BI->isVirtual()) 4047 continue; 4048 4049 QualType BaseType = BI->getType(); 4050 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4051 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4052 4053 // -- a [direct base class] B that cannot be [copied] because overload 4054 // resolution, as applied to B's [copy] assignment operator, results in 4055 // an ambiguity or a function that is deleted or inaccessible from the 4056 // assignment operator 4057 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false, 4058 0); 4059 if (!CopyOper || CopyOper->isDeleted()) 4060 return true; 4061 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible) 4062 return true; 4063 } 4064 4065 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4066 BE = RD->vbases_end(); 4067 BI != BE; ++BI) { 4068 QualType BaseType = BI->getType(); 4069 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4070 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4071 4072 // -- a [virtual base class] B that cannot be [copied] because overload 4073 // resolution, as applied to B's [copy] assignment operator, results in 4074 // an ambiguity or a function that is deleted or inaccessible from the 4075 // assignment operator 4076 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false, 4077 0); 4078 if (!CopyOper || CopyOper->isDeleted()) 4079 return true; 4080 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible) 4081 return true; 4082 } 4083 4084 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4085 FE = RD->field_end(); 4086 FI != FE; ++FI) { 4087 QualType FieldType = Context.getBaseElementType(FI->getType()); 4088 4089 // -- a non-static data member of reference type 4090 if (FieldType->isReferenceType()) 4091 return true; 4092 4093 // -- a non-static data member of const non-class type (or array thereof) 4094 if (FieldType.isConstQualified() && !FieldType->isRecordType()) 4095 return true; 4096 4097 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4098 4099 if (FieldRecord) { 4100 // This is an anonymous union 4101 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 4102 // Anonymous unions inside unions do not variant members create 4103 if (!Union) { 4104 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4105 UE = FieldRecord->field_end(); 4106 UI != UE; ++UI) { 4107 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 4108 CXXRecordDecl *UnionFieldRecord = 4109 UnionFieldType->getAsCXXRecordDecl(); 4110 4111 // -- a variant member with a non-trivial [copy] assignment operator 4112 // and X is a union-like class 4113 if (UnionFieldRecord && 4114 !UnionFieldRecord->hasTrivialCopyAssignment()) 4115 return true; 4116 } 4117 } 4118 4119 // Don't try to initalize an anonymous union 4120 continue; 4121 // -- a variant member with a non-trivial [copy] assignment operator 4122 // and X is a union-like class 4123 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) { 4124 return true; 4125 } 4126 4127 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals, 4128 false, 0); 4129 if (!CopyOper || CopyOper->isDeleted()) 4130 return true; 4131 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible) 4132 return true; 4133 } 4134 } 4135 4136 return false; 4137} 4138 4139bool Sema::ShouldDeleteMoveConstructor(CXXConstructorDecl *CD) { 4140 CXXRecordDecl *RD = CD->getParent(); 4141 assert(!RD->isDependentType() && "do deletion after instantiation"); 4142 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4143 return false; 4144 4145 SourceLocation Loc = CD->getLocation(); 4146 4147 // Do access control from the constructor 4148 ContextRAII CtorContext(*this, CD); 4149 4150 bool Union = RD->isUnion(); 4151 4152 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() && 4153 "copy assignment arg has no pointee type"); 4154 4155 // We do this because we should never actually use an anonymous 4156 // union's constructor. 4157 if (Union && RD->isAnonymousStructOrUnion()) 4158 return false; 4159 4160 // C++0x [class.copy]/11 4161 // A defaulted [move] constructor for class X is defined as deleted 4162 // if X has: 4163 4164 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4165 BE = RD->bases_end(); 4166 BI != BE; ++BI) { 4167 // We'll handle this one later 4168 if (BI->isVirtual()) 4169 continue; 4170 4171 QualType BaseType = BI->getType(); 4172 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4173 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4174 4175 // -- any [direct base class] of a type with a destructor that is deleted or 4176 // inaccessible from the defaulted constructor 4177 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4178 if (BaseDtor->isDeleted()) 4179 return true; 4180 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4181 AR_accessible) 4182 return true; 4183 4184 // -- a [direct base class] B that cannot be [moved] because overload 4185 // resolution, as applied to B's [move] constructor, results in an 4186 // ambiguity or a function that is deleted or inaccessible from the 4187 // defaulted constructor 4188 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl); 4189 if (!BaseCtor || BaseCtor->isDeleted()) 4190 return true; 4191 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) != 4192 AR_accessible) 4193 return true; 4194 4195 // -- for a move constructor, a [direct base class] with a type that 4196 // does not have a move constructor and is not trivially copyable. 4197 // If the field isn't a record, it's always trivially copyable. 4198 // A moving constructor could be a copy constructor instead. 4199 if (!BaseCtor->isMoveConstructor() && 4200 !BaseDecl->isTriviallyCopyable()) 4201 return true; 4202 } 4203 4204 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4205 BE = RD->vbases_end(); 4206 BI != BE; ++BI) { 4207 QualType BaseType = BI->getType(); 4208 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4209 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4210 4211 // -- any [virtual base class] of a type with a destructor that is deleted 4212 // or inaccessible from the defaulted constructor 4213 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4214 if (BaseDtor->isDeleted()) 4215 return true; 4216 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4217 AR_accessible) 4218 return true; 4219 4220 // -- a [virtual base class] B that cannot be [moved] because overload 4221 // resolution, as applied to B's [move] constructor, results in an 4222 // ambiguity or a function that is deleted or inaccessible from the 4223 // defaulted constructor 4224 CXXConstructorDecl *BaseCtor = LookupMovingConstructor(BaseDecl); 4225 if (!BaseCtor || BaseCtor->isDeleted()) 4226 return true; 4227 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) != 4228 AR_accessible) 4229 return true; 4230 4231 // -- for a move constructor, a [virtual base class] with a type that 4232 // does not have a move constructor and is not trivially copyable. 4233 // If the field isn't a record, it's always trivially copyable. 4234 // A moving constructor could be a copy constructor instead. 4235 if (!BaseCtor->isMoveConstructor() && 4236 !BaseDecl->isTriviallyCopyable()) 4237 return true; 4238 } 4239 4240 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4241 FE = RD->field_end(); 4242 FI != FE; ++FI) { 4243 QualType FieldType = Context.getBaseElementType(FI->getType()); 4244 4245 if (CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl()) { 4246 // This is an anonymous union 4247 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 4248 // Anonymous unions inside unions do not variant members create 4249 if (!Union) { 4250 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4251 UE = FieldRecord->field_end(); 4252 UI != UE; ++UI) { 4253 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 4254 CXXRecordDecl *UnionFieldRecord = 4255 UnionFieldType->getAsCXXRecordDecl(); 4256 4257 // -- a variant member with a non-trivial [move] constructor and X 4258 // is a union-like class 4259 if (UnionFieldRecord && 4260 !UnionFieldRecord->hasTrivialMoveConstructor()) 4261 return true; 4262 } 4263 } 4264 4265 // Don't try to initalize an anonymous union 4266 continue; 4267 } else { 4268 // -- a variant member with a non-trivial [move] constructor and X is a 4269 // union-like class 4270 if (Union && !FieldRecord->hasTrivialMoveConstructor()) 4271 return true; 4272 4273 // -- any [non-static data member] of a type with a destructor that is 4274 // deleted or inaccessible from the defaulted constructor 4275 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord); 4276 if (FieldDtor->isDeleted()) 4277 return true; 4278 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) != 4279 AR_accessible) 4280 return true; 4281 } 4282 4283 // -- a [non-static data member of class type (or array thereof)] B that 4284 // cannot be [moved] because overload resolution, as applied to B's 4285 // [move] constructor, results in an ambiguity or a function that is 4286 // deleted or inaccessible from the defaulted constructor 4287 CXXConstructorDecl *FieldCtor = LookupMovingConstructor(FieldRecord); 4288 if (!FieldCtor || FieldCtor->isDeleted()) 4289 return true; 4290 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(), 4291 PDiag()) != AR_accessible) 4292 return true; 4293 4294 // -- for a move constructor, a [non-static data member] with a type that 4295 // does not have a move constructor and is not trivially copyable. 4296 // If the field isn't a record, it's always trivially copyable. 4297 // A moving constructor could be a copy constructor instead. 4298 if (!FieldCtor->isMoveConstructor() && 4299 !FieldRecord->isTriviallyCopyable()) 4300 return true; 4301 } 4302 } 4303 4304 return false; 4305} 4306 4307bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) { 4308 CXXRecordDecl *RD = MD->getParent(); 4309 assert(!RD->isDependentType() && "do deletion after instantiation"); 4310 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4311 return false; 4312 4313 SourceLocation Loc = MD->getLocation(); 4314 4315 // Do access control from the constructor 4316 ContextRAII MethodContext(*this, MD); 4317 4318 bool Union = RD->isUnion(); 4319 4320 // We do this because we should never actually use an anonymous 4321 // union's constructor. 4322 if (Union && RD->isAnonymousStructOrUnion()) 4323 return false; 4324 4325 // C++0x [class.copy]/20 4326 // A defaulted [move] assignment operator for class X is defined as deleted 4327 // if X has: 4328 4329 // -- for the move constructor, [...] any direct or indirect virtual base 4330 // class. 4331 if (RD->getNumVBases() != 0) 4332 return true; 4333 4334 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4335 BE = RD->bases_end(); 4336 BI != BE; ++BI) { 4337 4338 QualType BaseType = BI->getType(); 4339 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl(); 4340 assert(BaseDecl && "base isn't a CXXRecordDecl"); 4341 4342 // -- a [direct base class] B that cannot be [moved] because overload 4343 // resolution, as applied to B's [move] assignment operator, results in 4344 // an ambiguity or a function that is deleted or inaccessible from the 4345 // assignment operator 4346 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0); 4347 if (!MoveOper || MoveOper->isDeleted()) 4348 return true; 4349 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible) 4350 return true; 4351 4352 // -- for the move assignment operator, a [direct base class] with a type 4353 // that does not have a move assignment operator and is not trivially 4354 // copyable. 4355 if (!MoveOper->isMoveAssignmentOperator() && 4356 !BaseDecl->isTriviallyCopyable()) 4357 return true; 4358 } 4359 4360 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4361 FE = RD->field_end(); 4362 FI != FE; ++FI) { 4363 QualType FieldType = Context.getBaseElementType(FI->getType()); 4364 4365 // -- a non-static data member of reference type 4366 if (FieldType->isReferenceType()) 4367 return true; 4368 4369 // -- a non-static data member of const non-class type (or array thereof) 4370 if (FieldType.isConstQualified() && !FieldType->isRecordType()) 4371 return true; 4372 4373 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4374 4375 if (FieldRecord) { 4376 // This is an anonymous union 4377 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 4378 // Anonymous unions inside unions do not variant members create 4379 if (!Union) { 4380 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4381 UE = FieldRecord->field_end(); 4382 UI != UE; ++UI) { 4383 QualType UnionFieldType = Context.getBaseElementType(UI->getType()); 4384 CXXRecordDecl *UnionFieldRecord = 4385 UnionFieldType->getAsCXXRecordDecl(); 4386 4387 // -- a variant member with a non-trivial [move] assignment operator 4388 // and X is a union-like class 4389 if (UnionFieldRecord && 4390 !UnionFieldRecord->hasTrivialMoveAssignment()) 4391 return true; 4392 } 4393 } 4394 4395 // Don't try to initalize an anonymous union 4396 continue; 4397 // -- a variant member with a non-trivial [move] assignment operator 4398 // and X is a union-like class 4399 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) { 4400 return true; 4401 } 4402 4403 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0); 4404 if (!MoveOper || MoveOper->isDeleted()) 4405 return true; 4406 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible) 4407 return true; 4408 4409 // -- for the move assignment operator, a [non-static data member] with a 4410 // type that does not have a move assignment operator and is not 4411 // trivially copyable. 4412 if (!MoveOper->isMoveAssignmentOperator() && 4413 !FieldRecord->isTriviallyCopyable()) 4414 return true; 4415 } 4416 } 4417 4418 return false; 4419} 4420 4421bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) { 4422 CXXRecordDecl *RD = DD->getParent(); 4423 assert(!RD->isDependentType() && "do deletion after instantiation"); 4424 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4425 return false; 4426 4427 SourceLocation Loc = DD->getLocation(); 4428 4429 // Do access control from the destructor 4430 ContextRAII CtorContext(*this, DD); 4431 4432 bool Union = RD->isUnion(); 4433 4434 // We do this because we should never actually use an anonymous 4435 // union's destructor. 4436 if (Union && RD->isAnonymousStructOrUnion()) 4437 return false; 4438 4439 // C++0x [class.dtor]p5 4440 // A defaulted destructor for a class X is defined as deleted if: 4441 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4442 BE = RD->bases_end(); 4443 BI != BE; ++BI) { 4444 // We'll handle this one later 4445 if (BI->isVirtual()) 4446 continue; 4447 4448 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 4449 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4450 assert(BaseDtor && "base has no destructor"); 4451 4452 // -- any direct or virtual base class has a deleted destructor or 4453 // a destructor that is inaccessible from the defaulted destructor 4454 if (BaseDtor->isDeleted()) 4455 return true; 4456 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4457 AR_accessible) 4458 return true; 4459 } 4460 4461 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4462 BE = RD->vbases_end(); 4463 BI != BE; ++BI) { 4464 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl(); 4465 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl); 4466 assert(BaseDtor && "base has no destructor"); 4467 4468 // -- any direct or virtual base class has a deleted destructor or 4469 // a destructor that is inaccessible from the defaulted destructor 4470 if (BaseDtor->isDeleted()) 4471 return true; 4472 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) != 4473 AR_accessible) 4474 return true; 4475 } 4476 4477 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4478 FE = RD->field_end(); 4479 FI != FE; ++FI) { 4480 QualType FieldType = Context.getBaseElementType(FI->getType()); 4481 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4482 if (FieldRecord) { 4483 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) { 4484 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4485 UE = FieldRecord->field_end(); 4486 UI != UE; ++UI) { 4487 QualType UnionFieldType = Context.getBaseElementType(FI->getType()); 4488 CXXRecordDecl *UnionFieldRecord = 4489 UnionFieldType->getAsCXXRecordDecl(); 4490 4491 // -- X is a union-like class that has a variant member with a non- 4492 // trivial destructor. 4493 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor()) 4494 return true; 4495 } 4496 // Technically we are supposed to do this next check unconditionally. 4497 // But that makes absolutely no sense. 4498 } else { 4499 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord); 4500 4501 // -- any of the non-static data members has class type M (or array 4502 // thereof) and M has a deleted destructor or a destructor that is 4503 // inaccessible from the defaulted destructor 4504 if (FieldDtor->isDeleted()) 4505 return true; 4506 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) != 4507 AR_accessible) 4508 return true; 4509 4510 // -- X is a union-like class that has a variant member with a non- 4511 // trivial destructor. 4512 if (Union && !FieldDtor->isTrivial()) 4513 return true; 4514 } 4515 } 4516 } 4517 4518 if (DD->isVirtual()) { 4519 FunctionDecl *OperatorDelete = 0; 4520 DeclarationName Name = 4521 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 4522 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete, 4523 false)) 4524 return true; 4525 } 4526 4527 4528 return false; 4529} 4530 4531/// \brief Data used with FindHiddenVirtualMethod 4532namespace { 4533 struct FindHiddenVirtualMethodData { 4534 Sema *S; 4535 CXXMethodDecl *Method; 4536 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 4537 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 4538 }; 4539} 4540 4541/// \brief Member lookup function that determines whether a given C++ 4542/// method overloads virtual methods in a base class without overriding any, 4543/// to be used with CXXRecordDecl::lookupInBases(). 4544static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 4545 CXXBasePath &Path, 4546 void *UserData) { 4547 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 4548 4549 FindHiddenVirtualMethodData &Data 4550 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 4551 4552 DeclarationName Name = Data.Method->getDeclName(); 4553 assert(Name.getNameKind() == DeclarationName::Identifier); 4554 4555 bool foundSameNameMethod = false; 4556 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 4557 for (Path.Decls = BaseRecord->lookup(Name); 4558 Path.Decls.first != Path.Decls.second; 4559 ++Path.Decls.first) { 4560 NamedDecl *D = *Path.Decls.first; 4561 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 4562 MD = MD->getCanonicalDecl(); 4563 foundSameNameMethod = true; 4564 // Interested only in hidden virtual methods. 4565 if (!MD->isVirtual()) 4566 continue; 4567 // If the method we are checking overrides a method from its base 4568 // don't warn about the other overloaded methods. 4569 if (!Data.S->IsOverload(Data.Method, MD, false)) 4570 return true; 4571 // Collect the overload only if its hidden. 4572 if (!Data.OverridenAndUsingBaseMethods.count(MD)) 4573 overloadedMethods.push_back(MD); 4574 } 4575 } 4576 4577 if (foundSameNameMethod) 4578 Data.OverloadedMethods.append(overloadedMethods.begin(), 4579 overloadedMethods.end()); 4580 return foundSameNameMethod; 4581} 4582 4583/// \brief See if a method overloads virtual methods in a base class without 4584/// overriding any. 4585void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 4586 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 4587 MD->getLocation()) == Diagnostic::Ignored) 4588 return; 4589 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier) 4590 return; 4591 4592 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 4593 /*bool RecordPaths=*/false, 4594 /*bool DetectVirtual=*/false); 4595 FindHiddenVirtualMethodData Data; 4596 Data.Method = MD; 4597 Data.S = this; 4598 4599 // Keep the base methods that were overriden or introduced in the subclass 4600 // by 'using' in a set. A base method not in this set is hidden. 4601 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName()); 4602 res.first != res.second; ++res.first) { 4603 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first)) 4604 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 4605 E = MD->end_overridden_methods(); 4606 I != E; ++I) 4607 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl()); 4608 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first)) 4609 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl())) 4610 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl()); 4611 } 4612 4613 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 4614 !Data.OverloadedMethods.empty()) { 4615 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 4616 << MD << (Data.OverloadedMethods.size() > 1); 4617 4618 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 4619 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 4620 Diag(overloadedMD->getLocation(), 4621 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 4622 } 4623 } 4624} 4625 4626void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 4627 Decl *TagDecl, 4628 SourceLocation LBrac, 4629 SourceLocation RBrac, 4630 AttributeList *AttrList) { 4631 if (!TagDecl) 4632 return; 4633 4634 AdjustDeclIfTemplate(TagDecl); 4635 4636 ActOnFields(S, RLoc, TagDecl, 4637 // strict aliasing violation! 4638 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 4639 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList); 4640 4641 CheckCompletedCXXClass( 4642 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 4643} 4644 4645/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 4646/// special functions, such as the default constructor, copy 4647/// constructor, or destructor, to the given C++ class (C++ 4648/// [special]p1). This routine can only be executed just before the 4649/// definition of the class is complete. 4650void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 4651 if (!ClassDecl->hasUserDeclaredConstructor()) 4652 ++ASTContext::NumImplicitDefaultConstructors; 4653 4654 if (!ClassDecl->hasUserDeclaredCopyConstructor()) 4655 ++ASTContext::NumImplicitCopyConstructors; 4656 4657 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 4658 ++ASTContext::NumImplicitCopyAssignmentOperators; 4659 4660 // If we have a dynamic class, then the copy assignment operator may be 4661 // virtual, so we have to declare it immediately. This ensures that, e.g., 4662 // it shows up in the right place in the vtable and that we diagnose 4663 // problems with the implicit exception specification. 4664 if (ClassDecl->isDynamicClass()) 4665 DeclareImplicitCopyAssignment(ClassDecl); 4666 } 4667 4668 if (!ClassDecl->hasUserDeclaredDestructor()) { 4669 ++ASTContext::NumImplicitDestructors; 4670 4671 // If we have a dynamic class, then the destructor may be virtual, so we 4672 // have to declare the destructor immediately. This ensures that, e.g., it 4673 // shows up in the right place in the vtable and that we diagnose problems 4674 // with the implicit exception specification. 4675 if (ClassDecl->isDynamicClass()) 4676 DeclareImplicitDestructor(ClassDecl); 4677 } 4678} 4679 4680void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 4681 if (!D) 4682 return; 4683 4684 int NumParamList = D->getNumTemplateParameterLists(); 4685 for (int i = 0; i < NumParamList; i++) { 4686 TemplateParameterList* Params = D->getTemplateParameterList(i); 4687 for (TemplateParameterList::iterator Param = Params->begin(), 4688 ParamEnd = Params->end(); 4689 Param != ParamEnd; ++Param) { 4690 NamedDecl *Named = cast<NamedDecl>(*Param); 4691 if (Named->getDeclName()) { 4692 S->AddDecl(Named); 4693 IdResolver.AddDecl(Named); 4694 } 4695 } 4696 } 4697} 4698 4699void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 4700 if (!D) 4701 return; 4702 4703 TemplateParameterList *Params = 0; 4704 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 4705 Params = Template->getTemplateParameters(); 4706 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 4707 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 4708 Params = PartialSpec->getTemplateParameters(); 4709 else 4710 return; 4711 4712 for (TemplateParameterList::iterator Param = Params->begin(), 4713 ParamEnd = Params->end(); 4714 Param != ParamEnd; ++Param) { 4715 NamedDecl *Named = cast<NamedDecl>(*Param); 4716 if (Named->getDeclName()) { 4717 S->AddDecl(Named); 4718 IdResolver.AddDecl(Named); 4719 } 4720 } 4721} 4722 4723void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 4724 if (!RecordD) return; 4725 AdjustDeclIfTemplate(RecordD); 4726 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 4727 PushDeclContext(S, Record); 4728} 4729 4730void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 4731 if (!RecordD) return; 4732 PopDeclContext(); 4733} 4734 4735/// ActOnStartDelayedCXXMethodDeclaration - We have completed 4736/// parsing a top-level (non-nested) C++ class, and we are now 4737/// parsing those parts of the given Method declaration that could 4738/// not be parsed earlier (C++ [class.mem]p2), such as default 4739/// arguments. This action should enter the scope of the given 4740/// Method declaration as if we had just parsed the qualified method 4741/// name. However, it should not bring the parameters into scope; 4742/// that will be performed by ActOnDelayedCXXMethodParameter. 4743void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 4744} 4745 4746/// ActOnDelayedCXXMethodParameter - We've already started a delayed 4747/// C++ method declaration. We're (re-)introducing the given 4748/// function parameter into scope for use in parsing later parts of 4749/// the method declaration. For example, we could see an 4750/// ActOnParamDefaultArgument event for this parameter. 4751void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 4752 if (!ParamD) 4753 return; 4754 4755 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 4756 4757 // If this parameter has an unparsed default argument, clear it out 4758 // to make way for the parsed default argument. 4759 if (Param->hasUnparsedDefaultArg()) 4760 Param->setDefaultArg(0); 4761 4762 S->AddDecl(Param); 4763 if (Param->getDeclName()) 4764 IdResolver.AddDecl(Param); 4765} 4766 4767/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 4768/// processing the delayed method declaration for Method. The method 4769/// declaration is now considered finished. There may be a separate 4770/// ActOnStartOfFunctionDef action later (not necessarily 4771/// immediately!) for this method, if it was also defined inside the 4772/// class body. 4773void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 4774 if (!MethodD) 4775 return; 4776 4777 AdjustDeclIfTemplate(MethodD); 4778 4779 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 4780 4781 // Now that we have our default arguments, check the constructor 4782 // again. It could produce additional diagnostics or affect whether 4783 // the class has implicitly-declared destructors, among other 4784 // things. 4785 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 4786 CheckConstructor(Constructor); 4787 4788 // Check the default arguments, which we may have added. 4789 if (!Method->isInvalidDecl()) 4790 CheckCXXDefaultArguments(Method); 4791} 4792 4793/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 4794/// the well-formedness of the constructor declarator @p D with type @p 4795/// R. If there are any errors in the declarator, this routine will 4796/// emit diagnostics and set the invalid bit to true. In any case, the type 4797/// will be updated to reflect a well-formed type for the constructor and 4798/// returned. 4799QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 4800 StorageClass &SC) { 4801 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 4802 4803 // C++ [class.ctor]p3: 4804 // A constructor shall not be virtual (10.3) or static (9.4). A 4805 // constructor can be invoked for a const, volatile or const 4806 // volatile object. A constructor shall not be declared const, 4807 // volatile, or const volatile (9.3.2). 4808 if (isVirtual) { 4809 if (!D.isInvalidType()) 4810 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 4811 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 4812 << SourceRange(D.getIdentifierLoc()); 4813 D.setInvalidType(); 4814 } 4815 if (SC == SC_Static) { 4816 if (!D.isInvalidType()) 4817 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 4818 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 4819 << SourceRange(D.getIdentifierLoc()); 4820 D.setInvalidType(); 4821 SC = SC_None; 4822 } 4823 4824 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 4825 if (FTI.TypeQuals != 0) { 4826 if (FTI.TypeQuals & Qualifiers::Const) 4827 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 4828 << "const" << SourceRange(D.getIdentifierLoc()); 4829 if (FTI.TypeQuals & Qualifiers::Volatile) 4830 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 4831 << "volatile" << SourceRange(D.getIdentifierLoc()); 4832 if (FTI.TypeQuals & Qualifiers::Restrict) 4833 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 4834 << "restrict" << SourceRange(D.getIdentifierLoc()); 4835 D.setInvalidType(); 4836 } 4837 4838 // C++0x [class.ctor]p4: 4839 // A constructor shall not be declared with a ref-qualifier. 4840 if (FTI.hasRefQualifier()) { 4841 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 4842 << FTI.RefQualifierIsLValueRef 4843 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 4844 D.setInvalidType(); 4845 } 4846 4847 // Rebuild the function type "R" without any type qualifiers (in 4848 // case any of the errors above fired) and with "void" as the 4849 // return type, since constructors don't have return types. 4850 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 4851 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 4852 return R; 4853 4854 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 4855 EPI.TypeQuals = 0; 4856 EPI.RefQualifier = RQ_None; 4857 4858 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 4859 Proto->getNumArgs(), EPI); 4860} 4861 4862/// CheckConstructor - Checks a fully-formed constructor for 4863/// well-formedness, issuing any diagnostics required. Returns true if 4864/// the constructor declarator is invalid. 4865void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 4866 CXXRecordDecl *ClassDecl 4867 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 4868 if (!ClassDecl) 4869 return Constructor->setInvalidDecl(); 4870 4871 // C++ [class.copy]p3: 4872 // A declaration of a constructor for a class X is ill-formed if 4873 // its first parameter is of type (optionally cv-qualified) X and 4874 // either there are no other parameters or else all other 4875 // parameters have default arguments. 4876 if (!Constructor->isInvalidDecl() && 4877 ((Constructor->getNumParams() == 1) || 4878 (Constructor->getNumParams() > 1 && 4879 Constructor->getParamDecl(1)->hasDefaultArg())) && 4880 Constructor->getTemplateSpecializationKind() 4881 != TSK_ImplicitInstantiation) { 4882 QualType ParamType = Constructor->getParamDecl(0)->getType(); 4883 QualType ClassTy = Context.getTagDeclType(ClassDecl); 4884 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 4885 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 4886 const char *ConstRef 4887 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 4888 : " const &"; 4889 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 4890 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 4891 4892 // FIXME: Rather that making the constructor invalid, we should endeavor 4893 // to fix the type. 4894 Constructor->setInvalidDecl(); 4895 } 4896 } 4897} 4898 4899/// CheckDestructor - Checks a fully-formed destructor definition for 4900/// well-formedness, issuing any diagnostics required. Returns true 4901/// on error. 4902bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 4903 CXXRecordDecl *RD = Destructor->getParent(); 4904 4905 if (Destructor->isVirtual()) { 4906 SourceLocation Loc; 4907 4908 if (!Destructor->isImplicit()) 4909 Loc = Destructor->getLocation(); 4910 else 4911 Loc = RD->getLocation(); 4912 4913 // If we have a virtual destructor, look up the deallocation function 4914 FunctionDecl *OperatorDelete = 0; 4915 DeclarationName Name = 4916 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 4917 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 4918 return true; 4919 4920 MarkDeclarationReferenced(Loc, OperatorDelete); 4921 4922 Destructor->setOperatorDelete(OperatorDelete); 4923 } 4924 4925 return false; 4926} 4927 4928static inline bool 4929FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 4930 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 4931 FTI.ArgInfo[0].Param && 4932 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 4933} 4934 4935/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 4936/// the well-formednes of the destructor declarator @p D with type @p 4937/// R. If there are any errors in the declarator, this routine will 4938/// emit diagnostics and set the declarator to invalid. Even if this happens, 4939/// will be updated to reflect a well-formed type for the destructor and 4940/// returned. 4941QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 4942 StorageClass& SC) { 4943 // C++ [class.dtor]p1: 4944 // [...] A typedef-name that names a class is a class-name 4945 // (7.1.3); however, a typedef-name that names a class shall not 4946 // be used as the identifier in the declarator for a destructor 4947 // declaration. 4948 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 4949 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 4950 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 4951 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 4952 else if (const TemplateSpecializationType *TST = 4953 DeclaratorType->getAs<TemplateSpecializationType>()) 4954 if (TST->isTypeAlias()) 4955 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 4956 << DeclaratorType << 1; 4957 4958 // C++ [class.dtor]p2: 4959 // A destructor is used to destroy objects of its class type. A 4960 // destructor takes no parameters, and no return type can be 4961 // specified for it (not even void). The address of a destructor 4962 // shall not be taken. A destructor shall not be static. A 4963 // destructor can be invoked for a const, volatile or const 4964 // volatile object. A destructor shall not be declared const, 4965 // volatile or const volatile (9.3.2). 4966 if (SC == SC_Static) { 4967 if (!D.isInvalidType()) 4968 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 4969 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 4970 << SourceRange(D.getIdentifierLoc()) 4971 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 4972 4973 SC = SC_None; 4974 } 4975 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 4976 // Destructors don't have return types, but the parser will 4977 // happily parse something like: 4978 // 4979 // class X { 4980 // float ~X(); 4981 // }; 4982 // 4983 // The return type will be eliminated later. 4984 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 4985 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 4986 << SourceRange(D.getIdentifierLoc()); 4987 } 4988 4989 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 4990 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 4991 if (FTI.TypeQuals & Qualifiers::Const) 4992 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 4993 << "const" << SourceRange(D.getIdentifierLoc()); 4994 if (FTI.TypeQuals & Qualifiers::Volatile) 4995 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 4996 << "volatile" << SourceRange(D.getIdentifierLoc()); 4997 if (FTI.TypeQuals & Qualifiers::Restrict) 4998 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 4999 << "restrict" << SourceRange(D.getIdentifierLoc()); 5000 D.setInvalidType(); 5001 } 5002 5003 // C++0x [class.dtor]p2: 5004 // A destructor shall not be declared with a ref-qualifier. 5005 if (FTI.hasRefQualifier()) { 5006 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 5007 << FTI.RefQualifierIsLValueRef 5008 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5009 D.setInvalidType(); 5010 } 5011 5012 // Make sure we don't have any parameters. 5013 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 5014 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 5015 5016 // Delete the parameters. 5017 FTI.freeArgs(); 5018 D.setInvalidType(); 5019 } 5020 5021 // Make sure the destructor isn't variadic. 5022 if (FTI.isVariadic) { 5023 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 5024 D.setInvalidType(); 5025 } 5026 5027 // Rebuild the function type "R" without any type qualifiers or 5028 // parameters (in case any of the errors above fired) and with 5029 // "void" as the return type, since destructors don't have return 5030 // types. 5031 if (!D.isInvalidType()) 5032 return R; 5033 5034 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5035 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5036 EPI.Variadic = false; 5037 EPI.TypeQuals = 0; 5038 EPI.RefQualifier = RQ_None; 5039 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 5040} 5041 5042/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 5043/// well-formednes of the conversion function declarator @p D with 5044/// type @p R. If there are any errors in the declarator, this routine 5045/// will emit diagnostics and return true. Otherwise, it will return 5046/// false. Either way, the type @p R will be updated to reflect a 5047/// well-formed type for the conversion operator. 5048void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 5049 StorageClass& SC) { 5050 // C++ [class.conv.fct]p1: 5051 // Neither parameter types nor return type can be specified. The 5052 // type of a conversion function (8.3.5) is "function taking no 5053 // parameter returning conversion-type-id." 5054 if (SC == SC_Static) { 5055 if (!D.isInvalidType()) 5056 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 5057 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5058 << SourceRange(D.getIdentifierLoc()); 5059 D.setInvalidType(); 5060 SC = SC_None; 5061 } 5062 5063 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 5064 5065 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5066 // Conversion functions don't have return types, but the parser will 5067 // happily parse something like: 5068 // 5069 // class X { 5070 // float operator bool(); 5071 // }; 5072 // 5073 // The return type will be changed later anyway. 5074 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 5075 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5076 << SourceRange(D.getIdentifierLoc()); 5077 D.setInvalidType(); 5078 } 5079 5080 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5081 5082 // Make sure we don't have any parameters. 5083 if (Proto->getNumArgs() > 0) { 5084 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 5085 5086 // Delete the parameters. 5087 D.getFunctionTypeInfo().freeArgs(); 5088 D.setInvalidType(); 5089 } else if (Proto->isVariadic()) { 5090 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 5091 D.setInvalidType(); 5092 } 5093 5094 // Diagnose "&operator bool()" and other such nonsense. This 5095 // is actually a gcc extension which we don't support. 5096 if (Proto->getResultType() != ConvType) { 5097 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 5098 << Proto->getResultType(); 5099 D.setInvalidType(); 5100 ConvType = Proto->getResultType(); 5101 } 5102 5103 // C++ [class.conv.fct]p4: 5104 // The conversion-type-id shall not represent a function type nor 5105 // an array type. 5106 if (ConvType->isArrayType()) { 5107 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 5108 ConvType = Context.getPointerType(ConvType); 5109 D.setInvalidType(); 5110 } else if (ConvType->isFunctionType()) { 5111 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 5112 ConvType = Context.getPointerType(ConvType); 5113 D.setInvalidType(); 5114 } 5115 5116 // Rebuild the function type "R" without any parameters (in case any 5117 // of the errors above fired) and with the conversion type as the 5118 // return type. 5119 if (D.isInvalidType()) 5120 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo()); 5121 5122 // C++0x explicit conversion operators. 5123 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 5124 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5125 diag::warn_explicit_conversion_functions) 5126 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 5127} 5128 5129/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 5130/// the declaration of the given C++ conversion function. This routine 5131/// is responsible for recording the conversion function in the C++ 5132/// class, if possible. 5133Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 5134 assert(Conversion && "Expected to receive a conversion function declaration"); 5135 5136 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 5137 5138 // Make sure we aren't redeclaring the conversion function. 5139 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 5140 5141 // C++ [class.conv.fct]p1: 5142 // [...] A conversion function is never used to convert a 5143 // (possibly cv-qualified) object to the (possibly cv-qualified) 5144 // same object type (or a reference to it), to a (possibly 5145 // cv-qualified) base class of that type (or a reference to it), 5146 // or to (possibly cv-qualified) void. 5147 // FIXME: Suppress this warning if the conversion function ends up being a 5148 // virtual function that overrides a virtual function in a base class. 5149 QualType ClassType 5150 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 5151 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 5152 ConvType = ConvTypeRef->getPointeeType(); 5153 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 5154 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 5155 /* Suppress diagnostics for instantiations. */; 5156 else if (ConvType->isRecordType()) { 5157 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 5158 if (ConvType == ClassType) 5159 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 5160 << ClassType; 5161 else if (IsDerivedFrom(ClassType, ConvType)) 5162 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 5163 << ClassType << ConvType; 5164 } else if (ConvType->isVoidType()) { 5165 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 5166 << ClassType << ConvType; 5167 } 5168 5169 if (FunctionTemplateDecl *ConversionTemplate 5170 = Conversion->getDescribedFunctionTemplate()) 5171 return ConversionTemplate; 5172 5173 return Conversion; 5174} 5175 5176//===----------------------------------------------------------------------===// 5177// Namespace Handling 5178//===----------------------------------------------------------------------===// 5179 5180 5181 5182/// ActOnStartNamespaceDef - This is called at the start of a namespace 5183/// definition. 5184Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 5185 SourceLocation InlineLoc, 5186 SourceLocation NamespaceLoc, 5187 SourceLocation IdentLoc, 5188 IdentifierInfo *II, 5189 SourceLocation LBrace, 5190 AttributeList *AttrList) { 5191 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 5192 // For anonymous namespace, take the location of the left brace. 5193 SourceLocation Loc = II ? IdentLoc : LBrace; 5194 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, 5195 StartLoc, Loc, II); 5196 Namespc->setInline(InlineLoc.isValid()); 5197 5198 Scope *DeclRegionScope = NamespcScope->getParent(); 5199 5200 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 5201 5202 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 5203 PushNamespaceVisibilityAttr(Attr); 5204 5205 if (II) { 5206 // C++ [namespace.def]p2: 5207 // The identifier in an original-namespace-definition shall not 5208 // have been previously defined in the declarative region in 5209 // which the original-namespace-definition appears. The 5210 // identifier in an original-namespace-definition is the name of 5211 // the namespace. Subsequently in that declarative region, it is 5212 // treated as an original-namespace-name. 5213 // 5214 // Since namespace names are unique in their scope, and we don't 5215 // look through using directives, just look for any ordinary names. 5216 5217 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 5218 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 5219 Decl::IDNS_Namespace; 5220 NamedDecl *PrevDecl = 0; 5221 for (DeclContext::lookup_result R 5222 = CurContext->getRedeclContext()->lookup(II); 5223 R.first != R.second; ++R.first) { 5224 if ((*R.first)->getIdentifierNamespace() & IDNS) { 5225 PrevDecl = *R.first; 5226 break; 5227 } 5228 } 5229 5230 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 5231 // This is an extended namespace definition. 5232 if (Namespc->isInline() != OrigNS->isInline()) { 5233 // inline-ness must match 5234 if (OrigNS->isInline()) { 5235 // The user probably just forgot the 'inline', so suggest that it 5236 // be added back. 5237 Diag(Namespc->getLocation(), 5238 diag::warn_inline_namespace_reopened_noninline) 5239 << FixItHint::CreateInsertion(NamespaceLoc, "inline "); 5240 } else { 5241 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch) 5242 << Namespc->isInline(); 5243 } 5244 Diag(OrigNS->getLocation(), diag::note_previous_definition); 5245 5246 // Recover by ignoring the new namespace's inline status. 5247 Namespc->setInline(OrigNS->isInline()); 5248 } 5249 5250 // Attach this namespace decl to the chain of extended namespace 5251 // definitions. 5252 OrigNS->setNextNamespace(Namespc); 5253 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 5254 5255 // Remove the previous declaration from the scope. 5256 if (DeclRegionScope->isDeclScope(OrigNS)) { 5257 IdResolver.RemoveDecl(OrigNS); 5258 DeclRegionScope->RemoveDecl(OrigNS); 5259 } 5260 } else if (PrevDecl) { 5261 // This is an invalid name redefinition. 5262 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 5263 << Namespc->getDeclName(); 5264 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5265 Namespc->setInvalidDecl(); 5266 // Continue on to push Namespc as current DeclContext and return it. 5267 } else if (II->isStr("std") && 5268 CurContext->getRedeclContext()->isTranslationUnit()) { 5269 // This is the first "real" definition of the namespace "std", so update 5270 // our cache of the "std" namespace to point at this definition. 5271 if (NamespaceDecl *StdNS = getStdNamespace()) { 5272 // We had already defined a dummy namespace "std". Link this new 5273 // namespace definition to the dummy namespace "std". 5274 StdNS->setNextNamespace(Namespc); 5275 StdNS->setLocation(IdentLoc); 5276 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace()); 5277 } 5278 5279 // Make our StdNamespace cache point at the first real definition of the 5280 // "std" namespace. 5281 StdNamespace = Namespc; 5282 5283 // Add this instance of "std" to the set of known namespaces 5284 KnownNamespaces[Namespc] = false; 5285 } else if (!Namespc->isInline()) { 5286 // Since this is an "original" namespace, add it to the known set of 5287 // namespaces if it is not an inline namespace. 5288 KnownNamespaces[Namespc] = false; 5289 } 5290 5291 PushOnScopeChains(Namespc, DeclRegionScope); 5292 } else { 5293 // Anonymous namespaces. 5294 assert(Namespc->isAnonymousNamespace()); 5295 5296 // Link the anonymous namespace into its parent. 5297 NamespaceDecl *PrevDecl; 5298 DeclContext *Parent = CurContext->getRedeclContext(); 5299 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 5300 PrevDecl = TU->getAnonymousNamespace(); 5301 TU->setAnonymousNamespace(Namespc); 5302 } else { 5303 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 5304 PrevDecl = ND->getAnonymousNamespace(); 5305 ND->setAnonymousNamespace(Namespc); 5306 } 5307 5308 // Link the anonymous namespace with its previous declaration. 5309 if (PrevDecl) { 5310 assert(PrevDecl->isAnonymousNamespace()); 5311 assert(!PrevDecl->getNextNamespace()); 5312 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace()); 5313 PrevDecl->setNextNamespace(Namespc); 5314 5315 if (Namespc->isInline() != PrevDecl->isInline()) { 5316 // inline-ness must match 5317 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch) 5318 << Namespc->isInline(); 5319 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5320 Namespc->setInvalidDecl(); 5321 // Recover by ignoring the new namespace's inline status. 5322 Namespc->setInline(PrevDecl->isInline()); 5323 } 5324 } 5325 5326 CurContext->addDecl(Namespc); 5327 5328 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 5329 // behaves as if it were replaced by 5330 // namespace unique { /* empty body */ } 5331 // using namespace unique; 5332 // namespace unique { namespace-body } 5333 // where all occurrences of 'unique' in a translation unit are 5334 // replaced by the same identifier and this identifier differs 5335 // from all other identifiers in the entire program. 5336 5337 // We just create the namespace with an empty name and then add an 5338 // implicit using declaration, just like the standard suggests. 5339 // 5340 // CodeGen enforces the "universally unique" aspect by giving all 5341 // declarations semantically contained within an anonymous 5342 // namespace internal linkage. 5343 5344 if (!PrevDecl) { 5345 UsingDirectiveDecl* UD 5346 = UsingDirectiveDecl::Create(Context, CurContext, 5347 /* 'using' */ LBrace, 5348 /* 'namespace' */ SourceLocation(), 5349 /* qualifier */ NestedNameSpecifierLoc(), 5350 /* identifier */ SourceLocation(), 5351 Namespc, 5352 /* Ancestor */ CurContext); 5353 UD->setImplicit(); 5354 CurContext->addDecl(UD); 5355 } 5356 } 5357 5358 // Although we could have an invalid decl (i.e. the namespace name is a 5359 // redefinition), push it as current DeclContext and try to continue parsing. 5360 // FIXME: We should be able to push Namespc here, so that the each DeclContext 5361 // for the namespace has the declarations that showed up in that particular 5362 // namespace definition. 5363 PushDeclContext(NamespcScope, Namespc); 5364 return Namespc; 5365} 5366 5367/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 5368/// is a namespace alias, returns the namespace it points to. 5369static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 5370 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 5371 return AD->getNamespace(); 5372 return dyn_cast_or_null<NamespaceDecl>(D); 5373} 5374 5375/// ActOnFinishNamespaceDef - This callback is called after a namespace is 5376/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 5377void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 5378 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 5379 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 5380 Namespc->setRBraceLoc(RBrace); 5381 PopDeclContext(); 5382 if (Namespc->hasAttr<VisibilityAttr>()) 5383 PopPragmaVisibility(); 5384} 5385 5386CXXRecordDecl *Sema::getStdBadAlloc() const { 5387 return cast_or_null<CXXRecordDecl>( 5388 StdBadAlloc.get(Context.getExternalSource())); 5389} 5390 5391NamespaceDecl *Sema::getStdNamespace() const { 5392 return cast_or_null<NamespaceDecl>( 5393 StdNamespace.get(Context.getExternalSource())); 5394} 5395 5396/// \brief Retrieve the special "std" namespace, which may require us to 5397/// implicitly define the namespace. 5398NamespaceDecl *Sema::getOrCreateStdNamespace() { 5399 if (!StdNamespace) { 5400 // The "std" namespace has not yet been defined, so build one implicitly. 5401 StdNamespace = NamespaceDecl::Create(Context, 5402 Context.getTranslationUnitDecl(), 5403 SourceLocation(), SourceLocation(), 5404 &PP.getIdentifierTable().get("std")); 5405 getStdNamespace()->setImplicit(true); 5406 } 5407 5408 return getStdNamespace(); 5409} 5410 5411/// \brief Determine whether a using statement is in a context where it will be 5412/// apply in all contexts. 5413static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 5414 switch (CurContext->getDeclKind()) { 5415 case Decl::TranslationUnit: 5416 return true; 5417 case Decl::LinkageSpec: 5418 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 5419 default: 5420 return false; 5421 } 5422} 5423 5424static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 5425 CXXScopeSpec &SS, 5426 SourceLocation IdentLoc, 5427 IdentifierInfo *Ident) { 5428 R.clear(); 5429 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 5430 R.getLookupKind(), Sc, &SS, NULL, 5431 false, S.CTC_NoKeywords, NULL)) { 5432 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() || 5433 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) { 5434 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions())); 5435 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions())); 5436 if (DeclContext *DC = S.computeDeclContext(SS, false)) 5437 S.Diag(IdentLoc, diag::err_using_directive_member_suggest) 5438 << Ident << DC << CorrectedQuotedStr << SS.getRange() 5439 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 5440 else 5441 S.Diag(IdentLoc, diag::err_using_directive_suggest) 5442 << Ident << CorrectedQuotedStr 5443 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 5444 5445 S.Diag(Corrected.getCorrectionDecl()->getLocation(), 5446 diag::note_namespace_defined_here) << CorrectedQuotedStr; 5447 5448 Ident = Corrected.getCorrectionAsIdentifierInfo(); 5449 R.addDecl(Corrected.getCorrectionDecl()); 5450 return true; 5451 } 5452 R.setLookupName(Ident); 5453 } 5454 return false; 5455} 5456 5457Decl *Sema::ActOnUsingDirective(Scope *S, 5458 SourceLocation UsingLoc, 5459 SourceLocation NamespcLoc, 5460 CXXScopeSpec &SS, 5461 SourceLocation IdentLoc, 5462 IdentifierInfo *NamespcName, 5463 AttributeList *AttrList) { 5464 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 5465 assert(NamespcName && "Invalid NamespcName."); 5466 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 5467 5468 // This can only happen along a recovery path. 5469 while (S->getFlags() & Scope::TemplateParamScope) 5470 S = S->getParent(); 5471 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 5472 5473 UsingDirectiveDecl *UDir = 0; 5474 NestedNameSpecifier *Qualifier = 0; 5475 if (SS.isSet()) 5476 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 5477 5478 // Lookup namespace name. 5479 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 5480 LookupParsedName(R, S, &SS); 5481 if (R.isAmbiguous()) 5482 return 0; 5483 5484 if (R.empty()) { 5485 R.clear(); 5486 // Allow "using namespace std;" or "using namespace ::std;" even if 5487 // "std" hasn't been defined yet, for GCC compatibility. 5488 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 5489 NamespcName->isStr("std")) { 5490 Diag(IdentLoc, diag::ext_using_undefined_std); 5491 R.addDecl(getOrCreateStdNamespace()); 5492 R.resolveKind(); 5493 } 5494 // Otherwise, attempt typo correction. 5495 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 5496 } 5497 5498 if (!R.empty()) { 5499 NamedDecl *Named = R.getFoundDecl(); 5500 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 5501 && "expected namespace decl"); 5502 // C++ [namespace.udir]p1: 5503 // A using-directive specifies that the names in the nominated 5504 // namespace can be used in the scope in which the 5505 // using-directive appears after the using-directive. During 5506 // unqualified name lookup (3.4.1), the names appear as if they 5507 // were declared in the nearest enclosing namespace which 5508 // contains both the using-directive and the nominated 5509 // namespace. [Note: in this context, "contains" means "contains 5510 // directly or indirectly". ] 5511 5512 // Find enclosing context containing both using-directive and 5513 // nominated namespace. 5514 NamespaceDecl *NS = getNamespaceDecl(Named); 5515 DeclContext *CommonAncestor = cast<DeclContext>(NS); 5516 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 5517 CommonAncestor = CommonAncestor->getParent(); 5518 5519 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 5520 SS.getWithLocInContext(Context), 5521 IdentLoc, Named, CommonAncestor); 5522 5523 if (IsUsingDirectiveInToplevelContext(CurContext) && 5524 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 5525 Diag(IdentLoc, diag::warn_using_directive_in_header); 5526 } 5527 5528 PushUsingDirective(S, UDir); 5529 } else { 5530 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 5531 } 5532 5533 // FIXME: We ignore attributes for now. 5534 return UDir; 5535} 5536 5537void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 5538 // If scope has associated entity, then using directive is at namespace 5539 // or translation unit scope. We add UsingDirectiveDecls, into 5540 // it's lookup structure. 5541 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 5542 Ctx->addDecl(UDir); 5543 else 5544 // Otherwise it is block-sope. using-directives will affect lookup 5545 // only to the end of scope. 5546 S->PushUsingDirective(UDir); 5547} 5548 5549 5550Decl *Sema::ActOnUsingDeclaration(Scope *S, 5551 AccessSpecifier AS, 5552 bool HasUsingKeyword, 5553 SourceLocation UsingLoc, 5554 CXXScopeSpec &SS, 5555 UnqualifiedId &Name, 5556 AttributeList *AttrList, 5557 bool IsTypeName, 5558 SourceLocation TypenameLoc) { 5559 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 5560 5561 switch (Name.getKind()) { 5562 case UnqualifiedId::IK_ImplicitSelfParam: 5563 case UnqualifiedId::IK_Identifier: 5564 case UnqualifiedId::IK_OperatorFunctionId: 5565 case UnqualifiedId::IK_LiteralOperatorId: 5566 case UnqualifiedId::IK_ConversionFunctionId: 5567 break; 5568 5569 case UnqualifiedId::IK_ConstructorName: 5570 case UnqualifiedId::IK_ConstructorTemplateId: 5571 // C++0x inherited constructors. 5572 if (getLangOptions().CPlusPlus0x) break; 5573 5574 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor) 5575 << SS.getRange(); 5576 return 0; 5577 5578 case UnqualifiedId::IK_DestructorName: 5579 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor) 5580 << SS.getRange(); 5581 return 0; 5582 5583 case UnqualifiedId::IK_TemplateId: 5584 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id) 5585 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 5586 return 0; 5587 } 5588 5589 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 5590 DeclarationName TargetName = TargetNameInfo.getName(); 5591 if (!TargetName) 5592 return 0; 5593 5594 // Warn about using declarations. 5595 // TODO: store that the declaration was written without 'using' and 5596 // talk about access decls instead of using decls in the 5597 // diagnostics. 5598 if (!HasUsingKeyword) { 5599 UsingLoc = Name.getSourceRange().getBegin(); 5600 5601 Diag(UsingLoc, diag::warn_access_decl_deprecated) 5602 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 5603 } 5604 5605 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 5606 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 5607 return 0; 5608 5609 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 5610 TargetNameInfo, AttrList, 5611 /* IsInstantiation */ false, 5612 IsTypeName, TypenameLoc); 5613 if (UD) 5614 PushOnScopeChains(UD, S, /*AddToContext*/ false); 5615 5616 return UD; 5617} 5618 5619/// \brief Determine whether a using declaration considers the given 5620/// declarations as "equivalent", e.g., if they are redeclarations of 5621/// the same entity or are both typedefs of the same type. 5622static bool 5623IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 5624 bool &SuppressRedeclaration) { 5625 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 5626 SuppressRedeclaration = false; 5627 return true; 5628 } 5629 5630 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 5631 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 5632 SuppressRedeclaration = true; 5633 return Context.hasSameType(TD1->getUnderlyingType(), 5634 TD2->getUnderlyingType()); 5635 } 5636 5637 return false; 5638} 5639 5640 5641/// Determines whether to create a using shadow decl for a particular 5642/// decl, given the set of decls existing prior to this using lookup. 5643bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 5644 const LookupResult &Previous) { 5645 // Diagnose finding a decl which is not from a base class of the 5646 // current class. We do this now because there are cases where this 5647 // function will silently decide not to build a shadow decl, which 5648 // will pre-empt further diagnostics. 5649 // 5650 // We don't need to do this in C++0x because we do the check once on 5651 // the qualifier. 5652 // 5653 // FIXME: diagnose the following if we care enough: 5654 // struct A { int foo; }; 5655 // struct B : A { using A::foo; }; 5656 // template <class T> struct C : A {}; 5657 // template <class T> struct D : C<T> { using B::foo; } // <--- 5658 // This is invalid (during instantiation) in C++03 because B::foo 5659 // resolves to the using decl in B, which is not a base class of D<T>. 5660 // We can't diagnose it immediately because C<T> is an unknown 5661 // specialization. The UsingShadowDecl in D<T> then points directly 5662 // to A::foo, which will look well-formed when we instantiate. 5663 // The right solution is to not collapse the shadow-decl chain. 5664 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) { 5665 DeclContext *OrigDC = Orig->getDeclContext(); 5666 5667 // Handle enums and anonymous structs. 5668 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 5669 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 5670 while (OrigRec->isAnonymousStructOrUnion()) 5671 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 5672 5673 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 5674 if (OrigDC == CurContext) { 5675 Diag(Using->getLocation(), 5676 diag::err_using_decl_nested_name_specifier_is_current_class) 5677 << Using->getQualifierLoc().getSourceRange(); 5678 Diag(Orig->getLocation(), diag::note_using_decl_target); 5679 return true; 5680 } 5681 5682 Diag(Using->getQualifierLoc().getBeginLoc(), 5683 diag::err_using_decl_nested_name_specifier_is_not_base_class) 5684 << Using->getQualifier() 5685 << cast<CXXRecordDecl>(CurContext) 5686 << Using->getQualifierLoc().getSourceRange(); 5687 Diag(Orig->getLocation(), diag::note_using_decl_target); 5688 return true; 5689 } 5690 } 5691 5692 if (Previous.empty()) return false; 5693 5694 NamedDecl *Target = Orig; 5695 if (isa<UsingShadowDecl>(Target)) 5696 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 5697 5698 // If the target happens to be one of the previous declarations, we 5699 // don't have a conflict. 5700 // 5701 // FIXME: but we might be increasing its access, in which case we 5702 // should redeclare it. 5703 NamedDecl *NonTag = 0, *Tag = 0; 5704 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5705 I != E; ++I) { 5706 NamedDecl *D = (*I)->getUnderlyingDecl(); 5707 bool Result; 5708 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 5709 return Result; 5710 5711 (isa<TagDecl>(D) ? Tag : NonTag) = D; 5712 } 5713 5714 if (Target->isFunctionOrFunctionTemplate()) { 5715 FunctionDecl *FD; 5716 if (isa<FunctionTemplateDecl>(Target)) 5717 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 5718 else 5719 FD = cast<FunctionDecl>(Target); 5720 5721 NamedDecl *OldDecl = 0; 5722 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 5723 case Ovl_Overload: 5724 return false; 5725 5726 case Ovl_NonFunction: 5727 Diag(Using->getLocation(), diag::err_using_decl_conflict); 5728 break; 5729 5730 // We found a decl with the exact signature. 5731 case Ovl_Match: 5732 // If we're in a record, we want to hide the target, so we 5733 // return true (without a diagnostic) to tell the caller not to 5734 // build a shadow decl. 5735 if (CurContext->isRecord()) 5736 return true; 5737 5738 // If we're not in a record, this is an error. 5739 Diag(Using->getLocation(), diag::err_using_decl_conflict); 5740 break; 5741 } 5742 5743 Diag(Target->getLocation(), diag::note_using_decl_target); 5744 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 5745 return true; 5746 } 5747 5748 // Target is not a function. 5749 5750 if (isa<TagDecl>(Target)) { 5751 // No conflict between a tag and a non-tag. 5752 if (!Tag) return false; 5753 5754 Diag(Using->getLocation(), diag::err_using_decl_conflict); 5755 Diag(Target->getLocation(), diag::note_using_decl_target); 5756 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 5757 return true; 5758 } 5759 5760 // No conflict between a tag and a non-tag. 5761 if (!NonTag) return false; 5762 5763 Diag(Using->getLocation(), diag::err_using_decl_conflict); 5764 Diag(Target->getLocation(), diag::note_using_decl_target); 5765 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 5766 return true; 5767} 5768 5769/// Builds a shadow declaration corresponding to a 'using' declaration. 5770UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 5771 UsingDecl *UD, 5772 NamedDecl *Orig) { 5773 5774 // If we resolved to another shadow declaration, just coalesce them. 5775 NamedDecl *Target = Orig; 5776 if (isa<UsingShadowDecl>(Target)) { 5777 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 5778 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 5779 } 5780 5781 UsingShadowDecl *Shadow 5782 = UsingShadowDecl::Create(Context, CurContext, 5783 UD->getLocation(), UD, Target); 5784 UD->addShadowDecl(Shadow); 5785 5786 Shadow->setAccess(UD->getAccess()); 5787 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 5788 Shadow->setInvalidDecl(); 5789 5790 if (S) 5791 PushOnScopeChains(Shadow, S); 5792 else 5793 CurContext->addDecl(Shadow); 5794 5795 5796 return Shadow; 5797} 5798 5799/// Hides a using shadow declaration. This is required by the current 5800/// using-decl implementation when a resolvable using declaration in a 5801/// class is followed by a declaration which would hide or override 5802/// one or more of the using decl's targets; for example: 5803/// 5804/// struct Base { void foo(int); }; 5805/// struct Derived : Base { 5806/// using Base::foo; 5807/// void foo(int); 5808/// }; 5809/// 5810/// The governing language is C++03 [namespace.udecl]p12: 5811/// 5812/// When a using-declaration brings names from a base class into a 5813/// derived class scope, member functions in the derived class 5814/// override and/or hide member functions with the same name and 5815/// parameter types in a base class (rather than conflicting). 5816/// 5817/// There are two ways to implement this: 5818/// (1) optimistically create shadow decls when they're not hidden 5819/// by existing declarations, or 5820/// (2) don't create any shadow decls (or at least don't make them 5821/// visible) until we've fully parsed/instantiated the class. 5822/// The problem with (1) is that we might have to retroactively remove 5823/// a shadow decl, which requires several O(n) operations because the 5824/// decl structures are (very reasonably) not designed for removal. 5825/// (2) avoids this but is very fiddly and phase-dependent. 5826void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 5827 if (Shadow->getDeclName().getNameKind() == 5828 DeclarationName::CXXConversionFunctionName) 5829 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 5830 5831 // Remove it from the DeclContext... 5832 Shadow->getDeclContext()->removeDecl(Shadow); 5833 5834 // ...and the scope, if applicable... 5835 if (S) { 5836 S->RemoveDecl(Shadow); 5837 IdResolver.RemoveDecl(Shadow); 5838 } 5839 5840 // ...and the using decl. 5841 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 5842 5843 // TODO: complain somehow if Shadow was used. It shouldn't 5844 // be possible for this to happen, because...? 5845} 5846 5847/// Builds a using declaration. 5848/// 5849/// \param IsInstantiation - Whether this call arises from an 5850/// instantiation of an unresolved using declaration. We treat 5851/// the lookup differently for these declarations. 5852NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 5853 SourceLocation UsingLoc, 5854 CXXScopeSpec &SS, 5855 const DeclarationNameInfo &NameInfo, 5856 AttributeList *AttrList, 5857 bool IsInstantiation, 5858 bool IsTypeName, 5859 SourceLocation TypenameLoc) { 5860 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 5861 SourceLocation IdentLoc = NameInfo.getLoc(); 5862 assert(IdentLoc.isValid() && "Invalid TargetName location."); 5863 5864 // FIXME: We ignore attributes for now. 5865 5866 if (SS.isEmpty()) { 5867 Diag(IdentLoc, diag::err_using_requires_qualname); 5868 return 0; 5869 } 5870 5871 // Do the redeclaration lookup in the current scope. 5872 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 5873 ForRedeclaration); 5874 Previous.setHideTags(false); 5875 if (S) { 5876 LookupName(Previous, S); 5877 5878 // It is really dumb that we have to do this. 5879 LookupResult::Filter F = Previous.makeFilter(); 5880 while (F.hasNext()) { 5881 NamedDecl *D = F.next(); 5882 if (!isDeclInScope(D, CurContext, S)) 5883 F.erase(); 5884 } 5885 F.done(); 5886 } else { 5887 assert(IsInstantiation && "no scope in non-instantiation"); 5888 assert(CurContext->isRecord() && "scope not record in instantiation"); 5889 LookupQualifiedName(Previous, CurContext); 5890 } 5891 5892 // Check for invalid redeclarations. 5893 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 5894 return 0; 5895 5896 // Check for bad qualifiers. 5897 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 5898 return 0; 5899 5900 DeclContext *LookupContext = computeDeclContext(SS); 5901 NamedDecl *D; 5902 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 5903 if (!LookupContext) { 5904 if (IsTypeName) { 5905 // FIXME: not all declaration name kinds are legal here 5906 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 5907 UsingLoc, TypenameLoc, 5908 QualifierLoc, 5909 IdentLoc, NameInfo.getName()); 5910 } else { 5911 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 5912 QualifierLoc, NameInfo); 5913 } 5914 } else { 5915 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 5916 NameInfo, IsTypeName); 5917 } 5918 D->setAccess(AS); 5919 CurContext->addDecl(D); 5920 5921 if (!LookupContext) return D; 5922 UsingDecl *UD = cast<UsingDecl>(D); 5923 5924 if (RequireCompleteDeclContext(SS, LookupContext)) { 5925 UD->setInvalidDecl(); 5926 return UD; 5927 } 5928 5929 // Constructor inheriting using decls get special treatment. 5930 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 5931 if (CheckInheritedConstructorUsingDecl(UD)) 5932 UD->setInvalidDecl(); 5933 return UD; 5934 } 5935 5936 // Otherwise, look up the target name. 5937 5938 LookupResult R(*this, NameInfo, LookupOrdinaryName); 5939 R.setUsingDeclaration(true); 5940 5941 // Unlike most lookups, we don't always want to hide tag 5942 // declarations: tag names are visible through the using declaration 5943 // even if hidden by ordinary names, *except* in a dependent context 5944 // where it's important for the sanity of two-phase lookup. 5945 if (!IsInstantiation) 5946 R.setHideTags(false); 5947 5948 LookupQualifiedName(R, LookupContext); 5949 5950 if (R.empty()) { 5951 Diag(IdentLoc, diag::err_no_member) 5952 << NameInfo.getName() << LookupContext << SS.getRange(); 5953 UD->setInvalidDecl(); 5954 return UD; 5955 } 5956 5957 if (R.isAmbiguous()) { 5958 UD->setInvalidDecl(); 5959 return UD; 5960 } 5961 5962 if (IsTypeName) { 5963 // If we asked for a typename and got a non-type decl, error out. 5964 if (!R.getAsSingle<TypeDecl>()) { 5965 Diag(IdentLoc, diag::err_using_typename_non_type); 5966 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 5967 Diag((*I)->getUnderlyingDecl()->getLocation(), 5968 diag::note_using_decl_target); 5969 UD->setInvalidDecl(); 5970 return UD; 5971 } 5972 } else { 5973 // If we asked for a non-typename and we got a type, error out, 5974 // but only if this is an instantiation of an unresolved using 5975 // decl. Otherwise just silently find the type name. 5976 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 5977 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 5978 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 5979 UD->setInvalidDecl(); 5980 return UD; 5981 } 5982 } 5983 5984 // C++0x N2914 [namespace.udecl]p6: 5985 // A using-declaration shall not name a namespace. 5986 if (R.getAsSingle<NamespaceDecl>()) { 5987 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 5988 << SS.getRange(); 5989 UD->setInvalidDecl(); 5990 return UD; 5991 } 5992 5993 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 5994 if (!CheckUsingShadowDecl(UD, *I, Previous)) 5995 BuildUsingShadowDecl(S, UD, *I); 5996 } 5997 5998 return UD; 5999} 6000 6001/// Additional checks for a using declaration referring to a constructor name. 6002bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) { 6003 if (UD->isTypeName()) { 6004 // FIXME: Cannot specify typename when specifying constructor 6005 return true; 6006 } 6007 6008 const Type *SourceType = UD->getQualifier()->getAsType(); 6009 assert(SourceType && 6010 "Using decl naming constructor doesn't have type in scope spec."); 6011 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 6012 6013 // Check whether the named type is a direct base class. 6014 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 6015 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 6016 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 6017 BaseIt != BaseE; ++BaseIt) { 6018 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 6019 if (CanonicalSourceType == BaseType) 6020 break; 6021 } 6022 6023 if (BaseIt == BaseE) { 6024 // Did not find SourceType in the bases. 6025 Diag(UD->getUsingLocation(), 6026 diag::err_using_decl_constructor_not_in_direct_base) 6027 << UD->getNameInfo().getSourceRange() 6028 << QualType(SourceType, 0) << TargetClass; 6029 return true; 6030 } 6031 6032 BaseIt->setInheritConstructors(); 6033 6034 return false; 6035} 6036 6037/// Checks that the given using declaration is not an invalid 6038/// redeclaration. Note that this is checking only for the using decl 6039/// itself, not for any ill-formedness among the UsingShadowDecls. 6040bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 6041 bool isTypeName, 6042 const CXXScopeSpec &SS, 6043 SourceLocation NameLoc, 6044 const LookupResult &Prev) { 6045 // C++03 [namespace.udecl]p8: 6046 // C++0x [namespace.udecl]p10: 6047 // A using-declaration is a declaration and can therefore be used 6048 // repeatedly where (and only where) multiple declarations are 6049 // allowed. 6050 // 6051 // That's in non-member contexts. 6052 if (!CurContext->getRedeclContext()->isRecord()) 6053 return false; 6054 6055 NestedNameSpecifier *Qual 6056 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 6057 6058 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 6059 NamedDecl *D = *I; 6060 6061 bool DTypename; 6062 NestedNameSpecifier *DQual; 6063 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 6064 DTypename = UD->isTypeName(); 6065 DQual = UD->getQualifier(); 6066 } else if (UnresolvedUsingValueDecl *UD 6067 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 6068 DTypename = false; 6069 DQual = UD->getQualifier(); 6070 } else if (UnresolvedUsingTypenameDecl *UD 6071 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 6072 DTypename = true; 6073 DQual = UD->getQualifier(); 6074 } else continue; 6075 6076 // using decls differ if one says 'typename' and the other doesn't. 6077 // FIXME: non-dependent using decls? 6078 if (isTypeName != DTypename) continue; 6079 6080 // using decls differ if they name different scopes (but note that 6081 // template instantiation can cause this check to trigger when it 6082 // didn't before instantiation). 6083 if (Context.getCanonicalNestedNameSpecifier(Qual) != 6084 Context.getCanonicalNestedNameSpecifier(DQual)) 6085 continue; 6086 6087 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 6088 Diag(D->getLocation(), diag::note_using_decl) << 1; 6089 return true; 6090 } 6091 6092 return false; 6093} 6094 6095 6096/// Checks that the given nested-name qualifier used in a using decl 6097/// in the current context is appropriately related to the current 6098/// scope. If an error is found, diagnoses it and returns true. 6099bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 6100 const CXXScopeSpec &SS, 6101 SourceLocation NameLoc) { 6102 DeclContext *NamedContext = computeDeclContext(SS); 6103 6104 if (!CurContext->isRecord()) { 6105 // C++03 [namespace.udecl]p3: 6106 // C++0x [namespace.udecl]p8: 6107 // A using-declaration for a class member shall be a member-declaration. 6108 6109 // If we weren't able to compute a valid scope, it must be a 6110 // dependent class scope. 6111 if (!NamedContext || NamedContext->isRecord()) { 6112 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 6113 << SS.getRange(); 6114 return true; 6115 } 6116 6117 // Otherwise, everything is known to be fine. 6118 return false; 6119 } 6120 6121 // The current scope is a record. 6122 6123 // If the named context is dependent, we can't decide much. 6124 if (!NamedContext) { 6125 // FIXME: in C++0x, we can diagnose if we can prove that the 6126 // nested-name-specifier does not refer to a base class, which is 6127 // still possible in some cases. 6128 6129 // Otherwise we have to conservatively report that things might be 6130 // okay. 6131 return false; 6132 } 6133 6134 if (!NamedContext->isRecord()) { 6135 // Ideally this would point at the last name in the specifier, 6136 // but we don't have that level of source info. 6137 Diag(SS.getRange().getBegin(), 6138 diag::err_using_decl_nested_name_specifier_is_not_class) 6139 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 6140 return true; 6141 } 6142 6143 if (!NamedContext->isDependentContext() && 6144 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 6145 return true; 6146 6147 if (getLangOptions().CPlusPlus0x) { 6148 // C++0x [namespace.udecl]p3: 6149 // In a using-declaration used as a member-declaration, the 6150 // nested-name-specifier shall name a base class of the class 6151 // being defined. 6152 6153 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 6154 cast<CXXRecordDecl>(NamedContext))) { 6155 if (CurContext == NamedContext) { 6156 Diag(NameLoc, 6157 diag::err_using_decl_nested_name_specifier_is_current_class) 6158 << SS.getRange(); 6159 return true; 6160 } 6161 6162 Diag(SS.getRange().getBegin(), 6163 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6164 << (NestedNameSpecifier*) SS.getScopeRep() 6165 << cast<CXXRecordDecl>(CurContext) 6166 << SS.getRange(); 6167 return true; 6168 } 6169 6170 return false; 6171 } 6172 6173 // C++03 [namespace.udecl]p4: 6174 // A using-declaration used as a member-declaration shall refer 6175 // to a member of a base class of the class being defined [etc.]. 6176 6177 // Salient point: SS doesn't have to name a base class as long as 6178 // lookup only finds members from base classes. Therefore we can 6179 // diagnose here only if we can prove that that can't happen, 6180 // i.e. if the class hierarchies provably don't intersect. 6181 6182 // TODO: it would be nice if "definitely valid" results were cached 6183 // in the UsingDecl and UsingShadowDecl so that these checks didn't 6184 // need to be repeated. 6185 6186 struct UserData { 6187 llvm::DenseSet<const CXXRecordDecl*> Bases; 6188 6189 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 6190 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 6191 Data->Bases.insert(Base); 6192 return true; 6193 } 6194 6195 bool hasDependentBases(const CXXRecordDecl *Class) { 6196 return !Class->forallBases(collect, this); 6197 } 6198 6199 /// Returns true if the base is dependent or is one of the 6200 /// accumulated base classes. 6201 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 6202 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 6203 return !Data->Bases.count(Base); 6204 } 6205 6206 bool mightShareBases(const CXXRecordDecl *Class) { 6207 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 6208 } 6209 }; 6210 6211 UserData Data; 6212 6213 // Returns false if we find a dependent base. 6214 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 6215 return false; 6216 6217 // Returns false if the class has a dependent base or if it or one 6218 // of its bases is present in the base set of the current context. 6219 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 6220 return false; 6221 6222 Diag(SS.getRange().getBegin(), 6223 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6224 << (NestedNameSpecifier*) SS.getScopeRep() 6225 << cast<CXXRecordDecl>(CurContext) 6226 << SS.getRange(); 6227 6228 return true; 6229} 6230 6231Decl *Sema::ActOnAliasDeclaration(Scope *S, 6232 AccessSpecifier AS, 6233 MultiTemplateParamsArg TemplateParamLists, 6234 SourceLocation UsingLoc, 6235 UnqualifiedId &Name, 6236 TypeResult Type) { 6237 // Skip up to the relevant declaration scope. 6238 while (S->getFlags() & Scope::TemplateParamScope) 6239 S = S->getParent(); 6240 assert((S->getFlags() & Scope::DeclScope) && 6241 "got alias-declaration outside of declaration scope"); 6242 6243 if (Type.isInvalid()) 6244 return 0; 6245 6246 bool Invalid = false; 6247 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 6248 TypeSourceInfo *TInfo = 0; 6249 GetTypeFromParser(Type.get(), &TInfo); 6250 6251 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 6252 return 0; 6253 6254 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 6255 UPPC_DeclarationType)) { 6256 Invalid = true; 6257 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 6258 TInfo->getTypeLoc().getBeginLoc()); 6259 } 6260 6261 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 6262 LookupName(Previous, S); 6263 6264 // Warn about shadowing the name of a template parameter. 6265 if (Previous.isSingleResult() && 6266 Previous.getFoundDecl()->isTemplateParameter()) { 6267 if (DiagnoseTemplateParameterShadow(Name.StartLocation, 6268 Previous.getFoundDecl())) 6269 Invalid = true; 6270 Previous.clear(); 6271 } 6272 6273 assert(Name.Kind == UnqualifiedId::IK_Identifier && 6274 "name in alias declaration must be an identifier"); 6275 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 6276 Name.StartLocation, 6277 Name.Identifier, TInfo); 6278 6279 NewTD->setAccess(AS); 6280 6281 if (Invalid) 6282 NewTD->setInvalidDecl(); 6283 6284 CheckTypedefForVariablyModifiedType(S, NewTD); 6285 Invalid |= NewTD->isInvalidDecl(); 6286 6287 bool Redeclaration = false; 6288 6289 NamedDecl *NewND; 6290 if (TemplateParamLists.size()) { 6291 TypeAliasTemplateDecl *OldDecl = 0; 6292 TemplateParameterList *OldTemplateParams = 0; 6293 6294 if (TemplateParamLists.size() != 1) { 6295 Diag(UsingLoc, diag::err_alias_template_extra_headers) 6296 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(), 6297 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc()); 6298 } 6299 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0]; 6300 6301 // Only consider previous declarations in the same scope. 6302 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 6303 /*ExplicitInstantiationOrSpecialization*/false); 6304 if (!Previous.empty()) { 6305 Redeclaration = true; 6306 6307 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 6308 if (!OldDecl && !Invalid) { 6309 Diag(UsingLoc, diag::err_redefinition_different_kind) 6310 << Name.Identifier; 6311 6312 NamedDecl *OldD = Previous.getRepresentativeDecl(); 6313 if (OldD->getLocation().isValid()) 6314 Diag(OldD->getLocation(), diag::note_previous_definition); 6315 6316 Invalid = true; 6317 } 6318 6319 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 6320 if (TemplateParameterListsAreEqual(TemplateParams, 6321 OldDecl->getTemplateParameters(), 6322 /*Complain=*/true, 6323 TPL_TemplateMatch)) 6324 OldTemplateParams = OldDecl->getTemplateParameters(); 6325 else 6326 Invalid = true; 6327 6328 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 6329 if (!Invalid && 6330 !Context.hasSameType(OldTD->getUnderlyingType(), 6331 NewTD->getUnderlyingType())) { 6332 // FIXME: The C++0x standard does not clearly say this is ill-formed, 6333 // but we can't reasonably accept it. 6334 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 6335 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 6336 if (OldTD->getLocation().isValid()) 6337 Diag(OldTD->getLocation(), diag::note_previous_definition); 6338 Invalid = true; 6339 } 6340 } 6341 } 6342 6343 // Merge any previous default template arguments into our parameters, 6344 // and check the parameter list. 6345 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 6346 TPC_TypeAliasTemplate)) 6347 return 0; 6348 6349 TypeAliasTemplateDecl *NewDecl = 6350 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 6351 Name.Identifier, TemplateParams, 6352 NewTD); 6353 6354 NewDecl->setAccess(AS); 6355 6356 if (Invalid) 6357 NewDecl->setInvalidDecl(); 6358 else if (OldDecl) 6359 NewDecl->setPreviousDeclaration(OldDecl); 6360 6361 NewND = NewDecl; 6362 } else { 6363 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 6364 NewND = NewTD; 6365 } 6366 6367 if (!Redeclaration) 6368 PushOnScopeChains(NewND, S); 6369 6370 return NewND; 6371} 6372 6373Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 6374 SourceLocation NamespaceLoc, 6375 SourceLocation AliasLoc, 6376 IdentifierInfo *Alias, 6377 CXXScopeSpec &SS, 6378 SourceLocation IdentLoc, 6379 IdentifierInfo *Ident) { 6380 6381 // Lookup the namespace name. 6382 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 6383 LookupParsedName(R, S, &SS); 6384 6385 // Check if we have a previous declaration with the same name. 6386 NamedDecl *PrevDecl 6387 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 6388 ForRedeclaration); 6389 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 6390 PrevDecl = 0; 6391 6392 if (PrevDecl) { 6393 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 6394 // We already have an alias with the same name that points to the same 6395 // namespace, so don't create a new one. 6396 // FIXME: At some point, we'll want to create the (redundant) 6397 // declaration to maintain better source information. 6398 if (!R.isAmbiguous() && !R.empty() && 6399 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 6400 return 0; 6401 } 6402 6403 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 6404 diag::err_redefinition_different_kind; 6405 Diag(AliasLoc, DiagID) << Alias; 6406 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6407 return 0; 6408 } 6409 6410 if (R.isAmbiguous()) 6411 return 0; 6412 6413 if (R.empty()) { 6414 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 6415 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 6416 return 0; 6417 } 6418 } 6419 6420 NamespaceAliasDecl *AliasDecl = 6421 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 6422 Alias, SS.getWithLocInContext(Context), 6423 IdentLoc, R.getFoundDecl()); 6424 6425 PushOnScopeChains(AliasDecl, S); 6426 return AliasDecl; 6427} 6428 6429namespace { 6430 /// \brief Scoped object used to handle the state changes required in Sema 6431 /// to implicitly define the body of a C++ member function; 6432 class ImplicitlyDefinedFunctionScope { 6433 Sema &S; 6434 Sema::ContextRAII SavedContext; 6435 6436 public: 6437 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method) 6438 : S(S), SavedContext(S, Method) 6439 { 6440 S.PushFunctionScope(); 6441 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 6442 } 6443 6444 ~ImplicitlyDefinedFunctionScope() { 6445 S.PopExpressionEvaluationContext(); 6446 S.PopFunctionOrBlockScope(); 6447 } 6448 }; 6449} 6450 6451Sema::ImplicitExceptionSpecification 6452Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) { 6453 // C++ [except.spec]p14: 6454 // An implicitly declared special member function (Clause 12) shall have an 6455 // exception-specification. [...] 6456 ImplicitExceptionSpecification ExceptSpec(Context); 6457 if (ClassDecl->isInvalidDecl()) 6458 return ExceptSpec; 6459 6460 // Direct base-class constructors. 6461 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 6462 BEnd = ClassDecl->bases_end(); 6463 B != BEnd; ++B) { 6464 if (B->isVirtual()) // Handled below. 6465 continue; 6466 6467 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 6468 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6469 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 6470 // If this is a deleted function, add it anyway. This might be conformant 6471 // with the standard. This might not. I'm not sure. It might not matter. 6472 if (Constructor) 6473 ExceptSpec.CalledDecl(Constructor); 6474 } 6475 } 6476 6477 // Virtual base-class constructors. 6478 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 6479 BEnd = ClassDecl->vbases_end(); 6480 B != BEnd; ++B) { 6481 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 6482 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6483 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 6484 // If this is a deleted function, add it anyway. This might be conformant 6485 // with the standard. This might not. I'm not sure. It might not matter. 6486 if (Constructor) 6487 ExceptSpec.CalledDecl(Constructor); 6488 } 6489 } 6490 6491 // Field constructors. 6492 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 6493 FEnd = ClassDecl->field_end(); 6494 F != FEnd; ++F) { 6495 if (F->hasInClassInitializer()) { 6496 if (Expr *E = F->getInClassInitializer()) 6497 ExceptSpec.CalledExpr(E); 6498 else if (!F->isInvalidDecl()) 6499 ExceptSpec.SetDelayed(); 6500 } else if (const RecordType *RecordTy 6501 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 6502 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6503 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 6504 // If this is a deleted function, add it anyway. This might be conformant 6505 // with the standard. This might not. I'm not sure. It might not matter. 6506 // In particular, the problem is that this function never gets called. It 6507 // might just be ill-formed because this function attempts to refer to 6508 // a deleted function here. 6509 if (Constructor) 6510 ExceptSpec.CalledDecl(Constructor); 6511 } 6512 } 6513 6514 return ExceptSpec; 6515} 6516 6517CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 6518 CXXRecordDecl *ClassDecl) { 6519 // C++ [class.ctor]p5: 6520 // A default constructor for a class X is a constructor of class X 6521 // that can be called without an argument. If there is no 6522 // user-declared constructor for class X, a default constructor is 6523 // implicitly declared. An implicitly-declared default constructor 6524 // is an inline public member of its class. 6525 assert(!ClassDecl->hasUserDeclaredConstructor() && 6526 "Should not build implicit default constructor!"); 6527 6528 ImplicitExceptionSpecification Spec = 6529 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl); 6530 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 6531 6532 // Create the actual constructor declaration. 6533 CanQualType ClassType 6534 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6535 SourceLocation ClassLoc = ClassDecl->getLocation(); 6536 DeclarationName Name 6537 = Context.DeclarationNames.getCXXConstructorName(ClassType); 6538 DeclarationNameInfo NameInfo(Name, ClassLoc); 6539 CXXConstructorDecl *DefaultCon 6540 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 6541 Context.getFunctionType(Context.VoidTy, 6542 0, 0, EPI), 6543 /*TInfo=*/0, 6544 /*isExplicit=*/false, 6545 /*isInline=*/true, 6546 /*isImplicitlyDeclared=*/true, 6547 // FIXME: apply the rules for definitions here 6548 /*isConstexpr=*/false); 6549 DefaultCon->setAccess(AS_public); 6550 DefaultCon->setDefaulted(); 6551 DefaultCon->setImplicit(); 6552 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 6553 6554 // Note that we have declared this constructor. 6555 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 6556 6557 if (Scope *S = getScopeForContext(ClassDecl)) 6558 PushOnScopeChains(DefaultCon, S, false); 6559 ClassDecl->addDecl(DefaultCon); 6560 6561 if (ShouldDeleteDefaultConstructor(DefaultCon)) 6562 DefaultCon->setDeletedAsWritten(); 6563 6564 return DefaultCon; 6565} 6566 6567void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 6568 CXXConstructorDecl *Constructor) { 6569 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 6570 !Constructor->doesThisDeclarationHaveABody() && 6571 !Constructor->isDeleted()) && 6572 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 6573 6574 CXXRecordDecl *ClassDecl = Constructor->getParent(); 6575 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 6576 6577 ImplicitlyDefinedFunctionScope Scope(*this, Constructor); 6578 DiagnosticErrorTrap Trap(Diags); 6579 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) || 6580 Trap.hasErrorOccurred()) { 6581 Diag(CurrentLocation, diag::note_member_synthesized_at) 6582 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 6583 Constructor->setInvalidDecl(); 6584 return; 6585 } 6586 6587 SourceLocation Loc = Constructor->getLocation(); 6588 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 6589 6590 Constructor->setUsed(); 6591 MarkVTableUsed(CurrentLocation, ClassDecl); 6592 6593 if (ASTMutationListener *L = getASTMutationListener()) { 6594 L->CompletedImplicitDefinition(Constructor); 6595 } 6596} 6597 6598/// Get any existing defaulted default constructor for the given class. Do not 6599/// implicitly define one if it does not exist. 6600static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self, 6601 CXXRecordDecl *D) { 6602 ASTContext &Context = Self.Context; 6603 QualType ClassType = Context.getTypeDeclType(D); 6604 DeclarationName ConstructorName 6605 = Context.DeclarationNames.getCXXConstructorName( 6606 Context.getCanonicalType(ClassType.getUnqualifiedType())); 6607 6608 DeclContext::lookup_const_iterator Con, ConEnd; 6609 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName); 6610 Con != ConEnd; ++Con) { 6611 // A function template cannot be defaulted. 6612 if (isa<FunctionTemplateDecl>(*Con)) 6613 continue; 6614 6615 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 6616 if (Constructor->isDefaultConstructor()) 6617 return Constructor->isDefaulted() ? Constructor : 0; 6618 } 6619 return 0; 6620} 6621 6622void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 6623 if (!D) return; 6624 AdjustDeclIfTemplate(D); 6625 6626 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D); 6627 CXXConstructorDecl *CtorDecl 6628 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl); 6629 6630 if (!CtorDecl) return; 6631 6632 // Compute the exception specification for the default constructor. 6633 const FunctionProtoType *CtorTy = 6634 CtorDecl->getType()->castAs<FunctionProtoType>(); 6635 if (CtorTy->getExceptionSpecType() == EST_Delayed) { 6636 ImplicitExceptionSpecification Spec = 6637 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl); 6638 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 6639 assert(EPI.ExceptionSpecType != EST_Delayed); 6640 6641 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 6642 } 6643 6644 // If the default constructor is explicitly defaulted, checking the exception 6645 // specification is deferred until now. 6646 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() && 6647 !ClassDecl->isDependentType()) 6648 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl); 6649} 6650 6651void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) { 6652 // We start with an initial pass over the base classes to collect those that 6653 // inherit constructors from. If there are none, we can forgo all further 6654 // processing. 6655 typedef SmallVector<const RecordType *, 4> BasesVector; 6656 BasesVector BasesToInheritFrom; 6657 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 6658 BaseE = ClassDecl->bases_end(); 6659 BaseIt != BaseE; ++BaseIt) { 6660 if (BaseIt->getInheritConstructors()) { 6661 QualType Base = BaseIt->getType(); 6662 if (Base->isDependentType()) { 6663 // If we inherit constructors from anything that is dependent, just 6664 // abort processing altogether. We'll get another chance for the 6665 // instantiations. 6666 return; 6667 } 6668 BasesToInheritFrom.push_back(Base->castAs<RecordType>()); 6669 } 6670 } 6671 if (BasesToInheritFrom.empty()) 6672 return; 6673 6674 // Now collect the constructors that we already have in the current class. 6675 // Those take precedence over inherited constructors. 6676 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...] 6677 // unless there is a user-declared constructor with the same signature in 6678 // the class where the using-declaration appears. 6679 llvm::SmallSet<const Type *, 8> ExistingConstructors; 6680 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(), 6681 CtorE = ClassDecl->ctor_end(); 6682 CtorIt != CtorE; ++CtorIt) { 6683 ExistingConstructors.insert( 6684 Context.getCanonicalType(CtorIt->getType()).getTypePtr()); 6685 } 6686 6687 Scope *S = getScopeForContext(ClassDecl); 6688 DeclarationName CreatedCtorName = 6689 Context.DeclarationNames.getCXXConstructorName( 6690 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified()); 6691 6692 // Now comes the true work. 6693 // First, we keep a map from constructor types to the base that introduced 6694 // them. Needed for finding conflicting constructors. We also keep the 6695 // actually inserted declarations in there, for pretty diagnostics. 6696 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo; 6697 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap; 6698 ConstructorToSourceMap InheritedConstructors; 6699 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(), 6700 BaseE = BasesToInheritFrom.end(); 6701 BaseIt != BaseE; ++BaseIt) { 6702 const RecordType *Base = *BaseIt; 6703 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified(); 6704 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl()); 6705 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(), 6706 CtorE = BaseDecl->ctor_end(); 6707 CtorIt != CtorE; ++CtorIt) { 6708 // Find the using declaration for inheriting this base's constructors. 6709 DeclarationName Name = 6710 Context.DeclarationNames.getCXXConstructorName(CanonicalBase); 6711 UsingDecl *UD = dyn_cast_or_null<UsingDecl>( 6712 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName)); 6713 SourceLocation UsingLoc = UD ? UD->getLocation() : 6714 ClassDecl->getLocation(); 6715 6716 // C++0x [class.inhctor]p1: The candidate set of inherited constructors 6717 // from the class X named in the using-declaration consists of actual 6718 // constructors and notional constructors that result from the 6719 // transformation of defaulted parameters as follows: 6720 // - all non-template default constructors of X, and 6721 // - for each non-template constructor of X that has at least one 6722 // parameter with a default argument, the set of constructors that 6723 // results from omitting any ellipsis parameter specification and 6724 // successively omitting parameters with a default argument from the 6725 // end of the parameter-type-list. 6726 CXXConstructorDecl *BaseCtor = *CtorIt; 6727 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor(); 6728 const FunctionProtoType *BaseCtorType = 6729 BaseCtor->getType()->getAs<FunctionProtoType>(); 6730 6731 for (unsigned params = BaseCtor->getMinRequiredArguments(), 6732 maxParams = BaseCtor->getNumParams(); 6733 params <= maxParams; ++params) { 6734 // Skip default constructors. They're never inherited. 6735 if (params == 0) 6736 continue; 6737 // Skip copy and move constructors for the same reason. 6738 if (CanBeCopyOrMove && params == 1) 6739 continue; 6740 6741 // Build up a function type for this particular constructor. 6742 // FIXME: The working paper does not consider that the exception spec 6743 // for the inheriting constructor might be larger than that of the 6744 // source. This code doesn't yet, either. When it does, this code will 6745 // need to be delayed until after exception specifications and in-class 6746 // member initializers are attached. 6747 const Type *NewCtorType; 6748 if (params == maxParams) 6749 NewCtorType = BaseCtorType; 6750 else { 6751 SmallVector<QualType, 16> Args; 6752 for (unsigned i = 0; i < params; ++i) { 6753 Args.push_back(BaseCtorType->getArgType(i)); 6754 } 6755 FunctionProtoType::ExtProtoInfo ExtInfo = 6756 BaseCtorType->getExtProtoInfo(); 6757 ExtInfo.Variadic = false; 6758 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(), 6759 Args.data(), params, ExtInfo) 6760 .getTypePtr(); 6761 } 6762 const Type *CanonicalNewCtorType = 6763 Context.getCanonicalType(NewCtorType); 6764 6765 // Now that we have the type, first check if the class already has a 6766 // constructor with this signature. 6767 if (ExistingConstructors.count(CanonicalNewCtorType)) 6768 continue; 6769 6770 // Then we check if we have already declared an inherited constructor 6771 // with this signature. 6772 std::pair<ConstructorToSourceMap::iterator, bool> result = 6773 InheritedConstructors.insert(std::make_pair( 6774 CanonicalNewCtorType, 6775 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0))); 6776 if (!result.second) { 6777 // Already in the map. If it came from a different class, that's an 6778 // error. Not if it's from the same. 6779 CanQualType PreviousBase = result.first->second.first; 6780 if (CanonicalBase != PreviousBase) { 6781 const CXXConstructorDecl *PrevCtor = result.first->second.second; 6782 const CXXConstructorDecl *PrevBaseCtor = 6783 PrevCtor->getInheritedConstructor(); 6784 assert(PrevBaseCtor && "Conflicting constructor was not inherited"); 6785 6786 Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 6787 Diag(BaseCtor->getLocation(), 6788 diag::note_using_decl_constructor_conflict_current_ctor); 6789 Diag(PrevBaseCtor->getLocation(), 6790 diag::note_using_decl_constructor_conflict_previous_ctor); 6791 Diag(PrevCtor->getLocation(), 6792 diag::note_using_decl_constructor_conflict_previous_using); 6793 } 6794 continue; 6795 } 6796 6797 // OK, we're there, now add the constructor. 6798 // C++0x [class.inhctor]p8: [...] that would be performed by a 6799 // user-written inline constructor [...] 6800 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc); 6801 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create( 6802 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0), 6803 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true, 6804 /*ImplicitlyDeclared=*/true, 6805 // FIXME: Due to a defect in the standard, we treat inherited 6806 // constructors as constexpr even if that makes them ill-formed. 6807 /*Constexpr=*/BaseCtor->isConstexpr()); 6808 NewCtor->setAccess(BaseCtor->getAccess()); 6809 6810 // Build up the parameter decls and add them. 6811 SmallVector<ParmVarDecl *, 16> ParamDecls; 6812 for (unsigned i = 0; i < params; ++i) { 6813 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor, 6814 UsingLoc, UsingLoc, 6815 /*IdentifierInfo=*/0, 6816 BaseCtorType->getArgType(i), 6817 /*TInfo=*/0, SC_None, 6818 SC_None, /*DefaultArg=*/0)); 6819 } 6820 NewCtor->setParams(ParamDecls.data(), ParamDecls.size()); 6821 NewCtor->setInheritedConstructor(BaseCtor); 6822 6823 PushOnScopeChains(NewCtor, S, false); 6824 ClassDecl->addDecl(NewCtor); 6825 result.first->second.second = NewCtor; 6826 } 6827 } 6828 } 6829} 6830 6831Sema::ImplicitExceptionSpecification 6832Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) { 6833 // C++ [except.spec]p14: 6834 // An implicitly declared special member function (Clause 12) shall have 6835 // an exception-specification. 6836 ImplicitExceptionSpecification ExceptSpec(Context); 6837 if (ClassDecl->isInvalidDecl()) 6838 return ExceptSpec; 6839 6840 // Direct base-class destructors. 6841 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 6842 BEnd = ClassDecl->bases_end(); 6843 B != BEnd; ++B) { 6844 if (B->isVirtual()) // Handled below. 6845 continue; 6846 6847 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 6848 ExceptSpec.CalledDecl( 6849 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 6850 } 6851 6852 // Virtual base-class destructors. 6853 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 6854 BEnd = ClassDecl->vbases_end(); 6855 B != BEnd; ++B) { 6856 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 6857 ExceptSpec.CalledDecl( 6858 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 6859 } 6860 6861 // Field destructors. 6862 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 6863 FEnd = ClassDecl->field_end(); 6864 F != FEnd; ++F) { 6865 if (const RecordType *RecordTy 6866 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 6867 ExceptSpec.CalledDecl( 6868 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 6869 } 6870 6871 return ExceptSpec; 6872} 6873 6874CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 6875 // C++ [class.dtor]p2: 6876 // If a class has no user-declared destructor, a destructor is 6877 // declared implicitly. An implicitly-declared destructor is an 6878 // inline public member of its class. 6879 6880 ImplicitExceptionSpecification Spec = 6881 ComputeDefaultedDtorExceptionSpec(ClassDecl); 6882 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 6883 6884 // Create the actual destructor declaration. 6885 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 6886 6887 CanQualType ClassType 6888 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6889 SourceLocation ClassLoc = ClassDecl->getLocation(); 6890 DeclarationName Name 6891 = Context.DeclarationNames.getCXXDestructorName(ClassType); 6892 DeclarationNameInfo NameInfo(Name, ClassLoc); 6893 CXXDestructorDecl *Destructor 6894 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0, 6895 /*isInline=*/true, 6896 /*isImplicitlyDeclared=*/true); 6897 Destructor->setAccess(AS_public); 6898 Destructor->setDefaulted(); 6899 Destructor->setImplicit(); 6900 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 6901 6902 // Note that we have declared this destructor. 6903 ++ASTContext::NumImplicitDestructorsDeclared; 6904 6905 // Introduce this destructor into its scope. 6906 if (Scope *S = getScopeForContext(ClassDecl)) 6907 PushOnScopeChains(Destructor, S, false); 6908 ClassDecl->addDecl(Destructor); 6909 6910 // This could be uniqued if it ever proves significant. 6911 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty)); 6912 6913 if (ShouldDeleteDestructor(Destructor)) 6914 Destructor->setDeletedAsWritten(); 6915 6916 AddOverriddenMethods(ClassDecl, Destructor); 6917 6918 return Destructor; 6919} 6920 6921void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 6922 CXXDestructorDecl *Destructor) { 6923 assert((Destructor->isDefaulted() && 6924 !Destructor->doesThisDeclarationHaveABody()) && 6925 "DefineImplicitDestructor - call it for implicit default dtor"); 6926 CXXRecordDecl *ClassDecl = Destructor->getParent(); 6927 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 6928 6929 if (Destructor->isInvalidDecl()) 6930 return; 6931 6932 ImplicitlyDefinedFunctionScope Scope(*this, Destructor); 6933 6934 DiagnosticErrorTrap Trap(Diags); 6935 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 6936 Destructor->getParent()); 6937 6938 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 6939 Diag(CurrentLocation, diag::note_member_synthesized_at) 6940 << CXXDestructor << Context.getTagDeclType(ClassDecl); 6941 6942 Destructor->setInvalidDecl(); 6943 return; 6944 } 6945 6946 SourceLocation Loc = Destructor->getLocation(); 6947 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 6948 6949 Destructor->setUsed(); 6950 MarkVTableUsed(CurrentLocation, ClassDecl); 6951 6952 if (ASTMutationListener *L = getASTMutationListener()) { 6953 L->CompletedImplicitDefinition(Destructor); 6954 } 6955} 6956 6957void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl, 6958 CXXDestructorDecl *destructor) { 6959 // C++11 [class.dtor]p3: 6960 // A declaration of a destructor that does not have an exception- 6961 // specification is implicitly considered to have the same exception- 6962 // specification as an implicit declaration. 6963 const FunctionProtoType *dtorType = destructor->getType()-> 6964 getAs<FunctionProtoType>(); 6965 if (dtorType->hasExceptionSpec()) 6966 return; 6967 6968 ImplicitExceptionSpecification exceptSpec = 6969 ComputeDefaultedDtorExceptionSpec(classDecl); 6970 6971 // Replace the destructor's type. 6972 FunctionProtoType::ExtProtoInfo epi; 6973 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType(); 6974 epi.NumExceptions = exceptSpec.size(); 6975 epi.Exceptions = exceptSpec.data(); 6976 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi); 6977 6978 destructor->setType(ty); 6979 6980 // FIXME: If the destructor has a body that could throw, and the newly created 6981 // spec doesn't allow exceptions, we should emit a warning, because this 6982 // change in behavior can break conforming C++03 programs at runtime. 6983 // However, we don't have a body yet, so it needs to be done somewhere else. 6984} 6985 6986/// \brief Builds a statement that copies/moves the given entity from \p From to 6987/// \c To. 6988/// 6989/// This routine is used to copy/move the members of a class with an 6990/// implicitly-declared copy/move assignment operator. When the entities being 6991/// copied are arrays, this routine builds for loops to copy them. 6992/// 6993/// \param S The Sema object used for type-checking. 6994/// 6995/// \param Loc The location where the implicit copy/move is being generated. 6996/// 6997/// \param T The type of the expressions being copied/moved. Both expressions 6998/// must have this type. 6999/// 7000/// \param To The expression we are copying/moving to. 7001/// 7002/// \param From The expression we are copying/moving from. 7003/// 7004/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 7005/// Otherwise, it's a non-static member subobject. 7006/// 7007/// \param Copying Whether we're copying or moving. 7008/// 7009/// \param Depth Internal parameter recording the depth of the recursion. 7010/// 7011/// \returns A statement or a loop that copies the expressions. 7012static StmtResult 7013BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 7014 Expr *To, Expr *From, 7015 bool CopyingBaseSubobject, bool Copying, 7016 unsigned Depth = 0) { 7017 // C++0x [class.copy]p28: 7018 // Each subobject is assigned in the manner appropriate to its type: 7019 // 7020 // - if the subobject is of class type, as if by a call to operator= with 7021 // the subobject as the object expression and the corresponding 7022 // subobject of x as a single function argument (as if by explicit 7023 // qualification; that is, ignoring any possible virtual overriding 7024 // functions in more derived classes); 7025 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 7026 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7027 7028 // Look for operator=. 7029 DeclarationName Name 7030 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 7031 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 7032 S.LookupQualifiedName(OpLookup, ClassDecl, false); 7033 7034 // Filter out any result that isn't a copy/move-assignment operator. 7035 LookupResult::Filter F = OpLookup.makeFilter(); 7036 while (F.hasNext()) { 7037 NamedDecl *D = F.next(); 7038 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 7039 if (Copying ? Method->isCopyAssignmentOperator() : 7040 Method->isMoveAssignmentOperator()) 7041 continue; 7042 7043 F.erase(); 7044 } 7045 F.done(); 7046 7047 // Suppress the protected check (C++ [class.protected]) for each of the 7048 // assignment operators we found. This strange dance is required when 7049 // we're assigning via a base classes's copy-assignment operator. To 7050 // ensure that we're getting the right base class subobject (without 7051 // ambiguities), we need to cast "this" to that subobject type; to 7052 // ensure that we don't go through the virtual call mechanism, we need 7053 // to qualify the operator= name with the base class (see below). However, 7054 // this means that if the base class has a protected copy assignment 7055 // operator, the protected member access check will fail. So, we 7056 // rewrite "protected" access to "public" access in this case, since we 7057 // know by construction that we're calling from a derived class. 7058 if (CopyingBaseSubobject) { 7059 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 7060 L != LEnd; ++L) { 7061 if (L.getAccess() == AS_protected) 7062 L.setAccess(AS_public); 7063 } 7064 } 7065 7066 // Create the nested-name-specifier that will be used to qualify the 7067 // reference to operator=; this is required to suppress the virtual 7068 // call mechanism. 7069 CXXScopeSpec SS; 7070 SS.MakeTrivial(S.Context, 7071 NestedNameSpecifier::Create(S.Context, 0, false, 7072 T.getTypePtr()), 7073 Loc); 7074 7075 // Create the reference to operator=. 7076 ExprResult OpEqualRef 7077 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 7078 /*FirstQualifierInScope=*/0, OpLookup, 7079 /*TemplateArgs=*/0, 7080 /*SuppressQualifierCheck=*/true); 7081 if (OpEqualRef.isInvalid()) 7082 return StmtError(); 7083 7084 // Build the call to the assignment operator. 7085 7086 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 7087 OpEqualRef.takeAs<Expr>(), 7088 Loc, &From, 1, Loc); 7089 if (Call.isInvalid()) 7090 return StmtError(); 7091 7092 return S.Owned(Call.takeAs<Stmt>()); 7093 } 7094 7095 // - if the subobject is of scalar type, the built-in assignment 7096 // operator is used. 7097 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 7098 if (!ArrayTy) { 7099 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 7100 if (Assignment.isInvalid()) 7101 return StmtError(); 7102 7103 return S.Owned(Assignment.takeAs<Stmt>()); 7104 } 7105 7106 // - if the subobject is an array, each element is assigned, in the 7107 // manner appropriate to the element type; 7108 7109 // Construct a loop over the array bounds, e.g., 7110 // 7111 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 7112 // 7113 // that will copy each of the array elements. 7114 QualType SizeType = S.Context.getSizeType(); 7115 7116 // Create the iteration variable. 7117 IdentifierInfo *IterationVarName = 0; 7118 { 7119 llvm::SmallString<8> Str; 7120 llvm::raw_svector_ostream OS(Str); 7121 OS << "__i" << Depth; 7122 IterationVarName = &S.Context.Idents.get(OS.str()); 7123 } 7124 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 7125 IterationVarName, SizeType, 7126 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 7127 SC_None, SC_None); 7128 7129 // Initialize the iteration variable to zero. 7130 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 7131 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 7132 7133 // Create a reference to the iteration variable; we'll use this several 7134 // times throughout. 7135 Expr *IterationVarRef 7136 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take(); 7137 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 7138 7139 // Create the DeclStmt that holds the iteration variable. 7140 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 7141 7142 // Create the comparison against the array bound. 7143 llvm::APInt Upper 7144 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 7145 Expr *Comparison 7146 = new (S.Context) BinaryOperator(IterationVarRef, 7147 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 7148 BO_NE, S.Context.BoolTy, 7149 VK_RValue, OK_Ordinary, Loc); 7150 7151 // Create the pre-increment of the iteration variable. 7152 Expr *Increment 7153 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 7154 VK_LValue, OK_Ordinary, Loc); 7155 7156 // Subscript the "from" and "to" expressions with the iteration variable. 7157 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 7158 IterationVarRef, Loc)); 7159 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 7160 IterationVarRef, Loc)); 7161 if (!Copying) // Cast to rvalue 7162 From = CastForMoving(S, From); 7163 7164 // Build the copy/move for an individual element of the array. 7165 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(), 7166 To, From, CopyingBaseSubobject, 7167 Copying, Depth + 1); 7168 if (Copy.isInvalid()) 7169 return StmtError(); 7170 7171 // Construct the loop that copies all elements of this array. 7172 return S.ActOnForStmt(Loc, Loc, InitStmt, 7173 S.MakeFullExpr(Comparison), 7174 0, S.MakeFullExpr(Increment), 7175 Loc, Copy.take()); 7176} 7177 7178std::pair<Sema::ImplicitExceptionSpecification, bool> 7179Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst( 7180 CXXRecordDecl *ClassDecl) { 7181 if (ClassDecl->isInvalidDecl()) 7182 return std::make_pair(ImplicitExceptionSpecification(Context), false); 7183 7184 // C++ [class.copy]p10: 7185 // If the class definition does not explicitly declare a copy 7186 // assignment operator, one is declared implicitly. 7187 // The implicitly-defined copy assignment operator for a class X 7188 // will have the form 7189 // 7190 // X& X::operator=(const X&) 7191 // 7192 // if 7193 bool HasConstCopyAssignment = true; 7194 7195 // -- each direct base class B of X has a copy assignment operator 7196 // whose parameter is of type const B&, const volatile B& or B, 7197 // and 7198 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7199 BaseEnd = ClassDecl->bases_end(); 7200 HasConstCopyAssignment && Base != BaseEnd; ++Base) { 7201 // We'll handle this below 7202 if (LangOpts.CPlusPlus0x && Base->isVirtual()) 7203 continue; 7204 7205 assert(!Base->getType()->isDependentType() && 7206 "Cannot generate implicit members for class with dependent bases."); 7207 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl(); 7208 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0, 7209 &HasConstCopyAssignment); 7210 } 7211 7212 // In C++0x, the above citation has "or virtual added" 7213 if (LangOpts.CPlusPlus0x) { 7214 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7215 BaseEnd = ClassDecl->vbases_end(); 7216 HasConstCopyAssignment && Base != BaseEnd; ++Base) { 7217 assert(!Base->getType()->isDependentType() && 7218 "Cannot generate implicit members for class with dependent bases."); 7219 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl(); 7220 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0, 7221 &HasConstCopyAssignment); 7222 } 7223 } 7224 7225 // -- for all the nonstatic data members of X that are of a class 7226 // type M (or array thereof), each such class type has a copy 7227 // assignment operator whose parameter is of type const M&, 7228 // const volatile M& or M. 7229 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7230 FieldEnd = ClassDecl->field_end(); 7231 HasConstCopyAssignment && Field != FieldEnd; 7232 ++Field) { 7233 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 7234 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 7235 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0, 7236 &HasConstCopyAssignment); 7237 } 7238 } 7239 7240 // Otherwise, the implicitly declared copy assignment operator will 7241 // have the form 7242 // 7243 // X& X::operator=(X&) 7244 7245 // C++ [except.spec]p14: 7246 // An implicitly declared special member function (Clause 12) shall have an 7247 // exception-specification. [...] 7248 7249 // It is unspecified whether or not an implicit copy assignment operator 7250 // attempts to deduplicate calls to assignment operators of virtual bases are 7251 // made. As such, this exception specification is effectively unspecified. 7252 // Based on a similar decision made for constness in C++0x, we're erring on 7253 // the side of assuming such calls to be made regardless of whether they 7254 // actually happen. 7255 ImplicitExceptionSpecification ExceptSpec(Context); 7256 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0; 7257 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7258 BaseEnd = ClassDecl->bases_end(); 7259 Base != BaseEnd; ++Base) { 7260 if (Base->isVirtual()) 7261 continue; 7262 7263 CXXRecordDecl *BaseClassDecl 7264 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7265 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 7266 ArgQuals, false, 0)) 7267 ExceptSpec.CalledDecl(CopyAssign); 7268 } 7269 7270 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7271 BaseEnd = ClassDecl->vbases_end(); 7272 Base != BaseEnd; ++Base) { 7273 CXXRecordDecl *BaseClassDecl 7274 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7275 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 7276 ArgQuals, false, 0)) 7277 ExceptSpec.CalledDecl(CopyAssign); 7278 } 7279 7280 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7281 FieldEnd = ClassDecl->field_end(); 7282 Field != FieldEnd; 7283 ++Field) { 7284 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 7285 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 7286 if (CXXMethodDecl *CopyAssign = 7287 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0)) 7288 ExceptSpec.CalledDecl(CopyAssign); 7289 } 7290 } 7291 7292 return std::make_pair(ExceptSpec, HasConstCopyAssignment); 7293} 7294 7295CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 7296 // Note: The following rules are largely analoguous to the copy 7297 // constructor rules. Note that virtual bases are not taken into account 7298 // for determining the argument type of the operator. Note also that 7299 // operators taking an object instead of a reference are allowed. 7300 7301 ImplicitExceptionSpecification Spec(Context); 7302 bool Const; 7303 llvm::tie(Spec, Const) = 7304 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl); 7305 7306 QualType ArgType = Context.getTypeDeclType(ClassDecl); 7307 QualType RetType = Context.getLValueReferenceType(ArgType); 7308 if (Const) 7309 ArgType = ArgType.withConst(); 7310 ArgType = Context.getLValueReferenceType(ArgType); 7311 7312 // An implicitly-declared copy assignment operator is an inline public 7313 // member of its class. 7314 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 7315 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 7316 SourceLocation ClassLoc = ClassDecl->getLocation(); 7317 DeclarationNameInfo NameInfo(Name, ClassLoc); 7318 CXXMethodDecl *CopyAssignment 7319 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 7320 Context.getFunctionType(RetType, &ArgType, 1, EPI), 7321 /*TInfo=*/0, /*isStatic=*/false, 7322 /*StorageClassAsWritten=*/SC_None, 7323 /*isInline=*/true, /*isConstexpr=*/false, 7324 SourceLocation()); 7325 CopyAssignment->setAccess(AS_public); 7326 CopyAssignment->setDefaulted(); 7327 CopyAssignment->setImplicit(); 7328 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 7329 7330 // Add the parameter to the operator. 7331 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 7332 ClassLoc, ClassLoc, /*Id=*/0, 7333 ArgType, /*TInfo=*/0, 7334 SC_None, 7335 SC_None, 0); 7336 CopyAssignment->setParams(&FromParam, 1); 7337 7338 // Note that we have added this copy-assignment operator. 7339 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 7340 7341 if (Scope *S = getScopeForContext(ClassDecl)) 7342 PushOnScopeChains(CopyAssignment, S, false); 7343 ClassDecl->addDecl(CopyAssignment); 7344 7345 // C++0x [class.copy]p18: 7346 // ... If the class definition declares a move constructor or move 7347 // assignment operator, the implicitly declared copy assignment operator is 7348 // defined as deleted; ... 7349 if (ClassDecl->hasUserDeclaredMoveConstructor() || 7350 ClassDecl->hasUserDeclaredMoveAssignment() || 7351 ShouldDeleteCopyAssignmentOperator(CopyAssignment)) 7352 CopyAssignment->setDeletedAsWritten(); 7353 7354 AddOverriddenMethods(ClassDecl, CopyAssignment); 7355 return CopyAssignment; 7356} 7357 7358void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 7359 CXXMethodDecl *CopyAssignOperator) { 7360 assert((CopyAssignOperator->isDefaulted() && 7361 CopyAssignOperator->isOverloadedOperator() && 7362 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 7363 !CopyAssignOperator->doesThisDeclarationHaveABody()) && 7364 "DefineImplicitCopyAssignment called for wrong function"); 7365 7366 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 7367 7368 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 7369 CopyAssignOperator->setInvalidDecl(); 7370 return; 7371 } 7372 7373 CopyAssignOperator->setUsed(); 7374 7375 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator); 7376 DiagnosticErrorTrap Trap(Diags); 7377 7378 // C++0x [class.copy]p30: 7379 // The implicitly-defined or explicitly-defaulted copy assignment operator 7380 // for a non-union class X performs memberwise copy assignment of its 7381 // subobjects. The direct base classes of X are assigned first, in the 7382 // order of their declaration in the base-specifier-list, and then the 7383 // immediate non-static data members of X are assigned, in the order in 7384 // which they were declared in the class definition. 7385 7386 // The statements that form the synthesized function body. 7387 ASTOwningVector<Stmt*> Statements(*this); 7388 7389 // The parameter for the "other" object, which we are copying from. 7390 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 7391 Qualifiers OtherQuals = Other->getType().getQualifiers(); 7392 QualType OtherRefType = Other->getType(); 7393 if (const LValueReferenceType *OtherRef 7394 = OtherRefType->getAs<LValueReferenceType>()) { 7395 OtherRefType = OtherRef->getPointeeType(); 7396 OtherQuals = OtherRefType.getQualifiers(); 7397 } 7398 7399 // Our location for everything implicitly-generated. 7400 SourceLocation Loc = CopyAssignOperator->getLocation(); 7401 7402 // Construct a reference to the "other" object. We'll be using this 7403 // throughout the generated ASTs. 7404 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 7405 assert(OtherRef && "Reference to parameter cannot fail!"); 7406 7407 // Construct the "this" pointer. We'll be using this throughout the generated 7408 // ASTs. 7409 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 7410 assert(This && "Reference to this cannot fail!"); 7411 7412 // Assign base classes. 7413 bool Invalid = false; 7414 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7415 E = ClassDecl->bases_end(); Base != E; ++Base) { 7416 // Form the assignment: 7417 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 7418 QualType BaseType = Base->getType().getUnqualifiedType(); 7419 if (!BaseType->isRecordType()) { 7420 Invalid = true; 7421 continue; 7422 } 7423 7424 CXXCastPath BasePath; 7425 BasePath.push_back(Base); 7426 7427 // Construct the "from" expression, which is an implicit cast to the 7428 // appropriately-qualified base type. 7429 Expr *From = OtherRef; 7430 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 7431 CK_UncheckedDerivedToBase, 7432 VK_LValue, &BasePath).take(); 7433 7434 // Dereference "this". 7435 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 7436 7437 // Implicitly cast "this" to the appropriately-qualified base type. 7438 To = ImpCastExprToType(To.take(), 7439 Context.getCVRQualifiedType(BaseType, 7440 CopyAssignOperator->getTypeQualifiers()), 7441 CK_UncheckedDerivedToBase, 7442 VK_LValue, &BasePath); 7443 7444 // Build the copy. 7445 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType, 7446 To.get(), From, 7447 /*CopyingBaseSubobject=*/true, 7448 /*Copying=*/true); 7449 if (Copy.isInvalid()) { 7450 Diag(CurrentLocation, diag::note_member_synthesized_at) 7451 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7452 CopyAssignOperator->setInvalidDecl(); 7453 return; 7454 } 7455 7456 // Success! Record the copy. 7457 Statements.push_back(Copy.takeAs<Expr>()); 7458 } 7459 7460 // \brief Reference to the __builtin_memcpy function. 7461 Expr *BuiltinMemCpyRef = 0; 7462 // \brief Reference to the __builtin_objc_memmove_collectable function. 7463 Expr *CollectableMemCpyRef = 0; 7464 7465 // Assign non-static members. 7466 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7467 FieldEnd = ClassDecl->field_end(); 7468 Field != FieldEnd; ++Field) { 7469 // Check for members of reference type; we can't copy those. 7470 if (Field->getType()->isReferenceType()) { 7471 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 7472 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 7473 Diag(Field->getLocation(), diag::note_declared_at); 7474 Diag(CurrentLocation, diag::note_member_synthesized_at) 7475 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7476 Invalid = true; 7477 continue; 7478 } 7479 7480 // Check for members of const-qualified, non-class type. 7481 QualType BaseType = Context.getBaseElementType(Field->getType()); 7482 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 7483 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 7484 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 7485 Diag(Field->getLocation(), diag::note_declared_at); 7486 Diag(CurrentLocation, diag::note_member_synthesized_at) 7487 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7488 Invalid = true; 7489 continue; 7490 } 7491 7492 // Suppress assigning zero-width bitfields. 7493 if (const Expr *Width = Field->getBitWidth()) 7494 if (Width->EvaluateAsInt(Context) == 0) 7495 continue; 7496 7497 QualType FieldType = Field->getType().getNonReferenceType(); 7498 if (FieldType->isIncompleteArrayType()) { 7499 assert(ClassDecl->hasFlexibleArrayMember() && 7500 "Incomplete array type is not valid"); 7501 continue; 7502 } 7503 7504 // Build references to the field in the object we're copying from and to. 7505 CXXScopeSpec SS; // Intentionally empty 7506 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 7507 LookupMemberName); 7508 MemberLookup.addDecl(*Field); 7509 MemberLookup.resolveKind(); 7510 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 7511 Loc, /*IsArrow=*/false, 7512 SS, 0, MemberLookup, 0); 7513 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 7514 Loc, /*IsArrow=*/true, 7515 SS, 0, MemberLookup, 0); 7516 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 7517 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 7518 7519 // If the field should be copied with __builtin_memcpy rather than via 7520 // explicit assignments, do so. This optimization only applies for arrays 7521 // of scalars and arrays of class type with trivial copy-assignment 7522 // operators. 7523 if (FieldType->isArrayType() && !FieldType.isVolatileQualified() 7524 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) { 7525 // Compute the size of the memory buffer to be copied. 7526 QualType SizeType = Context.getSizeType(); 7527 llvm::APInt Size(Context.getTypeSize(SizeType), 7528 Context.getTypeSizeInChars(BaseType).getQuantity()); 7529 for (const ConstantArrayType *Array 7530 = Context.getAsConstantArrayType(FieldType); 7531 Array; 7532 Array = Context.getAsConstantArrayType(Array->getElementType())) { 7533 llvm::APInt ArraySize 7534 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 7535 Size *= ArraySize; 7536 } 7537 7538 // Take the address of the field references for "from" and "to". 7539 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get()); 7540 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get()); 7541 7542 bool NeedsCollectableMemCpy = 7543 (BaseType->isRecordType() && 7544 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 7545 7546 if (NeedsCollectableMemCpy) { 7547 if (!CollectableMemCpyRef) { 7548 // Create a reference to the __builtin_objc_memmove_collectable function. 7549 LookupResult R(*this, 7550 &Context.Idents.get("__builtin_objc_memmove_collectable"), 7551 Loc, LookupOrdinaryName); 7552 LookupName(R, TUScope, true); 7553 7554 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 7555 if (!CollectableMemCpy) { 7556 // Something went horribly wrong earlier, and we will have 7557 // complained about it. 7558 Invalid = true; 7559 continue; 7560 } 7561 7562 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 7563 CollectableMemCpy->getType(), 7564 VK_LValue, Loc, 0).take(); 7565 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 7566 } 7567 } 7568 // Create a reference to the __builtin_memcpy builtin function. 7569 else if (!BuiltinMemCpyRef) { 7570 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 7571 LookupOrdinaryName); 7572 LookupName(R, TUScope, true); 7573 7574 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 7575 if (!BuiltinMemCpy) { 7576 // Something went horribly wrong earlier, and we will have complained 7577 // about it. 7578 Invalid = true; 7579 continue; 7580 } 7581 7582 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 7583 BuiltinMemCpy->getType(), 7584 VK_LValue, Loc, 0).take(); 7585 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 7586 } 7587 7588 ASTOwningVector<Expr*> CallArgs(*this); 7589 CallArgs.push_back(To.takeAs<Expr>()); 7590 CallArgs.push_back(From.takeAs<Expr>()); 7591 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 7592 ExprResult Call = ExprError(); 7593 if (NeedsCollectableMemCpy) 7594 Call = ActOnCallExpr(/*Scope=*/0, 7595 CollectableMemCpyRef, 7596 Loc, move_arg(CallArgs), 7597 Loc); 7598 else 7599 Call = ActOnCallExpr(/*Scope=*/0, 7600 BuiltinMemCpyRef, 7601 Loc, move_arg(CallArgs), 7602 Loc); 7603 7604 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 7605 Statements.push_back(Call.takeAs<Expr>()); 7606 continue; 7607 } 7608 7609 // Build the copy of this field. 7610 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType, 7611 To.get(), From.get(), 7612 /*CopyingBaseSubobject=*/false, 7613 /*Copying=*/true); 7614 if (Copy.isInvalid()) { 7615 Diag(CurrentLocation, diag::note_member_synthesized_at) 7616 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7617 CopyAssignOperator->setInvalidDecl(); 7618 return; 7619 } 7620 7621 // Success! Record the copy. 7622 Statements.push_back(Copy.takeAs<Stmt>()); 7623 } 7624 7625 if (!Invalid) { 7626 // Add a "return *this;" 7627 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 7628 7629 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 7630 if (Return.isInvalid()) 7631 Invalid = true; 7632 else { 7633 Statements.push_back(Return.takeAs<Stmt>()); 7634 7635 if (Trap.hasErrorOccurred()) { 7636 Diag(CurrentLocation, diag::note_member_synthesized_at) 7637 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7638 Invalid = true; 7639 } 7640 } 7641 } 7642 7643 if (Invalid) { 7644 CopyAssignOperator->setInvalidDecl(); 7645 return; 7646 } 7647 7648 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 7649 /*isStmtExpr=*/false); 7650 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 7651 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 7652 7653 if (ASTMutationListener *L = getASTMutationListener()) { 7654 L->CompletedImplicitDefinition(CopyAssignOperator); 7655 } 7656} 7657 7658Sema::ImplicitExceptionSpecification 7659Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) { 7660 ImplicitExceptionSpecification ExceptSpec(Context); 7661 7662 if (ClassDecl->isInvalidDecl()) 7663 return ExceptSpec; 7664 7665 // C++0x [except.spec]p14: 7666 // An implicitly declared special member function (Clause 12) shall have an 7667 // exception-specification. [...] 7668 7669 // It is unspecified whether or not an implicit move assignment operator 7670 // attempts to deduplicate calls to assignment operators of virtual bases are 7671 // made. As such, this exception specification is effectively unspecified. 7672 // Based on a similar decision made for constness in C++0x, we're erring on 7673 // the side of assuming such calls to be made regardless of whether they 7674 // actually happen. 7675 // Note that a move constructor is not implicitly declared when there are 7676 // virtual bases, but it can still be user-declared and explicitly defaulted. 7677 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7678 BaseEnd = ClassDecl->bases_end(); 7679 Base != BaseEnd; ++Base) { 7680 if (Base->isVirtual()) 7681 continue; 7682 7683 CXXRecordDecl *BaseClassDecl 7684 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7685 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 7686 false, 0)) 7687 ExceptSpec.CalledDecl(MoveAssign); 7688 } 7689 7690 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7691 BaseEnd = ClassDecl->vbases_end(); 7692 Base != BaseEnd; ++Base) { 7693 CXXRecordDecl *BaseClassDecl 7694 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7695 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 7696 false, 0)) 7697 ExceptSpec.CalledDecl(MoveAssign); 7698 } 7699 7700 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7701 FieldEnd = ClassDecl->field_end(); 7702 Field != FieldEnd; 7703 ++Field) { 7704 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 7705 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 7706 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl, 7707 false, 0)) 7708 ExceptSpec.CalledDecl(MoveAssign); 7709 } 7710 } 7711 7712 return ExceptSpec; 7713} 7714 7715CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 7716 // Note: The following rules are largely analoguous to the move 7717 // constructor rules. 7718 7719 ImplicitExceptionSpecification Spec( 7720 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl)); 7721 7722 QualType ArgType = Context.getTypeDeclType(ClassDecl); 7723 QualType RetType = Context.getLValueReferenceType(ArgType); 7724 ArgType = Context.getRValueReferenceType(ArgType); 7725 7726 // An implicitly-declared move assignment operator is an inline public 7727 // member of its class. 7728 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 7729 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 7730 SourceLocation ClassLoc = ClassDecl->getLocation(); 7731 DeclarationNameInfo NameInfo(Name, ClassLoc); 7732 CXXMethodDecl *MoveAssignment 7733 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 7734 Context.getFunctionType(RetType, &ArgType, 1, EPI), 7735 /*TInfo=*/0, /*isStatic=*/false, 7736 /*StorageClassAsWritten=*/SC_None, 7737 /*isInline=*/true, 7738 /*isConstexpr=*/false, 7739 SourceLocation()); 7740 MoveAssignment->setAccess(AS_public); 7741 MoveAssignment->setDefaulted(); 7742 MoveAssignment->setImplicit(); 7743 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment()); 7744 7745 // Add the parameter to the operator. 7746 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 7747 ClassLoc, ClassLoc, /*Id=*/0, 7748 ArgType, /*TInfo=*/0, 7749 SC_None, 7750 SC_None, 0); 7751 MoveAssignment->setParams(&FromParam, 1); 7752 7753 // Note that we have added this copy-assignment operator. 7754 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 7755 7756 // C++0x [class.copy]p9: 7757 // If the definition of a class X does not explicitly declare a move 7758 // assignment operator, one will be implicitly declared as defaulted if and 7759 // only if: 7760 // [...] 7761 // - the move assignment operator would not be implicitly defined as 7762 // deleted. 7763 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) { 7764 // Cache this result so that we don't try to generate this over and over 7765 // on every lookup, leaking memory and wasting time. 7766 ClassDecl->setFailedImplicitMoveAssignment(); 7767 return 0; 7768 } 7769 7770 if (Scope *S = getScopeForContext(ClassDecl)) 7771 PushOnScopeChains(MoveAssignment, S, false); 7772 ClassDecl->addDecl(MoveAssignment); 7773 7774 AddOverriddenMethods(ClassDecl, MoveAssignment); 7775 return MoveAssignment; 7776} 7777 7778void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 7779 CXXMethodDecl *MoveAssignOperator) { 7780 assert((MoveAssignOperator->isDefaulted() && 7781 MoveAssignOperator->isOverloadedOperator() && 7782 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 7783 !MoveAssignOperator->doesThisDeclarationHaveABody()) && 7784 "DefineImplicitMoveAssignment called for wrong function"); 7785 7786 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 7787 7788 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 7789 MoveAssignOperator->setInvalidDecl(); 7790 return; 7791 } 7792 7793 MoveAssignOperator->setUsed(); 7794 7795 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator); 7796 DiagnosticErrorTrap Trap(Diags); 7797 7798 // C++0x [class.copy]p28: 7799 // The implicitly-defined or move assignment operator for a non-union class 7800 // X performs memberwise move assignment of its subobjects. The direct base 7801 // classes of X are assigned first, in the order of their declaration in the 7802 // base-specifier-list, and then the immediate non-static data members of X 7803 // are assigned, in the order in which they were declared in the class 7804 // definition. 7805 7806 // The statements that form the synthesized function body. 7807 ASTOwningVector<Stmt*> Statements(*this); 7808 7809 // The parameter for the "other" object, which we are move from. 7810 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 7811 QualType OtherRefType = Other->getType()-> 7812 getAs<RValueReferenceType>()->getPointeeType(); 7813 assert(OtherRefType.getQualifiers() == 0 && 7814 "Bad argument type of defaulted move assignment"); 7815 7816 // Our location for everything implicitly-generated. 7817 SourceLocation Loc = MoveAssignOperator->getLocation(); 7818 7819 // Construct a reference to the "other" object. We'll be using this 7820 // throughout the generated ASTs. 7821 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 7822 assert(OtherRef && "Reference to parameter cannot fail!"); 7823 // Cast to rvalue. 7824 OtherRef = CastForMoving(*this, OtherRef); 7825 7826 // Construct the "this" pointer. We'll be using this throughout the generated 7827 // ASTs. 7828 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 7829 assert(This && "Reference to this cannot fail!"); 7830 7831 // Assign base classes. 7832 bool Invalid = false; 7833 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7834 E = ClassDecl->bases_end(); Base != E; ++Base) { 7835 // Form the assignment: 7836 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 7837 QualType BaseType = Base->getType().getUnqualifiedType(); 7838 if (!BaseType->isRecordType()) { 7839 Invalid = true; 7840 continue; 7841 } 7842 7843 CXXCastPath BasePath; 7844 BasePath.push_back(Base); 7845 7846 // Construct the "from" expression, which is an implicit cast to the 7847 // appropriately-qualified base type. 7848 Expr *From = OtherRef; 7849 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase, 7850 VK_XValue, &BasePath).take(); 7851 7852 // Dereference "this". 7853 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 7854 7855 // Implicitly cast "this" to the appropriately-qualified base type. 7856 To = ImpCastExprToType(To.take(), 7857 Context.getCVRQualifiedType(BaseType, 7858 MoveAssignOperator->getTypeQualifiers()), 7859 CK_UncheckedDerivedToBase, 7860 VK_LValue, &BasePath); 7861 7862 // Build the move. 7863 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType, 7864 To.get(), From, 7865 /*CopyingBaseSubobject=*/true, 7866 /*Copying=*/false); 7867 if (Move.isInvalid()) { 7868 Diag(CurrentLocation, diag::note_member_synthesized_at) 7869 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 7870 MoveAssignOperator->setInvalidDecl(); 7871 return; 7872 } 7873 7874 // Success! Record the move. 7875 Statements.push_back(Move.takeAs<Expr>()); 7876 } 7877 7878 // \brief Reference to the __builtin_memcpy function. 7879 Expr *BuiltinMemCpyRef = 0; 7880 // \brief Reference to the __builtin_objc_memmove_collectable function. 7881 Expr *CollectableMemCpyRef = 0; 7882 7883 // Assign non-static members. 7884 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7885 FieldEnd = ClassDecl->field_end(); 7886 Field != FieldEnd; ++Field) { 7887 // Check for members of reference type; we can't move those. 7888 if (Field->getType()->isReferenceType()) { 7889 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 7890 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 7891 Diag(Field->getLocation(), diag::note_declared_at); 7892 Diag(CurrentLocation, diag::note_member_synthesized_at) 7893 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 7894 Invalid = true; 7895 continue; 7896 } 7897 7898 // Check for members of const-qualified, non-class type. 7899 QualType BaseType = Context.getBaseElementType(Field->getType()); 7900 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 7901 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 7902 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 7903 Diag(Field->getLocation(), diag::note_declared_at); 7904 Diag(CurrentLocation, diag::note_member_synthesized_at) 7905 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 7906 Invalid = true; 7907 continue; 7908 } 7909 7910 // Suppress assigning zero-width bitfields. 7911 if (const Expr *Width = Field->getBitWidth()) 7912 if (Width->EvaluateAsInt(Context) == 0) 7913 continue; 7914 7915 QualType FieldType = Field->getType().getNonReferenceType(); 7916 if (FieldType->isIncompleteArrayType()) { 7917 assert(ClassDecl->hasFlexibleArrayMember() && 7918 "Incomplete array type is not valid"); 7919 continue; 7920 } 7921 7922 // Build references to the field in the object we're copying from and to. 7923 CXXScopeSpec SS; // Intentionally empty 7924 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 7925 LookupMemberName); 7926 MemberLookup.addDecl(*Field); 7927 MemberLookup.resolveKind(); 7928 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 7929 Loc, /*IsArrow=*/false, 7930 SS, 0, MemberLookup, 0); 7931 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 7932 Loc, /*IsArrow=*/true, 7933 SS, 0, MemberLookup, 0); 7934 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 7935 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 7936 7937 assert(!From.get()->isLValue() && // could be xvalue or prvalue 7938 "Member reference with rvalue base must be rvalue except for reference " 7939 "members, which aren't allowed for move assignment."); 7940 7941 // If the field should be copied with __builtin_memcpy rather than via 7942 // explicit assignments, do so. This optimization only applies for arrays 7943 // of scalars and arrays of class type with trivial move-assignment 7944 // operators. 7945 if (FieldType->isArrayType() && !FieldType.isVolatileQualified() 7946 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) { 7947 // Compute the size of the memory buffer to be copied. 7948 QualType SizeType = Context.getSizeType(); 7949 llvm::APInt Size(Context.getTypeSize(SizeType), 7950 Context.getTypeSizeInChars(BaseType).getQuantity()); 7951 for (const ConstantArrayType *Array 7952 = Context.getAsConstantArrayType(FieldType); 7953 Array; 7954 Array = Context.getAsConstantArrayType(Array->getElementType())) { 7955 llvm::APInt ArraySize 7956 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 7957 Size *= ArraySize; 7958 } 7959 7960 // Take the address of the field references for "from" and "to". We 7961 // directly construct UnaryOperators here because semantic analysis 7962 // does not permit us to take the address of an xvalue. 7963 From = new (Context) UnaryOperator(From.get(), UO_AddrOf, 7964 Context.getPointerType(From.get()->getType()), 7965 VK_RValue, OK_Ordinary, Loc); 7966 To = new (Context) UnaryOperator(To.get(), UO_AddrOf, 7967 Context.getPointerType(To.get()->getType()), 7968 VK_RValue, OK_Ordinary, Loc); 7969 7970 bool NeedsCollectableMemCpy = 7971 (BaseType->isRecordType() && 7972 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 7973 7974 if (NeedsCollectableMemCpy) { 7975 if (!CollectableMemCpyRef) { 7976 // Create a reference to the __builtin_objc_memmove_collectable function. 7977 LookupResult R(*this, 7978 &Context.Idents.get("__builtin_objc_memmove_collectable"), 7979 Loc, LookupOrdinaryName); 7980 LookupName(R, TUScope, true); 7981 7982 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 7983 if (!CollectableMemCpy) { 7984 // Something went horribly wrong earlier, and we will have 7985 // complained about it. 7986 Invalid = true; 7987 continue; 7988 } 7989 7990 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 7991 CollectableMemCpy->getType(), 7992 VK_LValue, Loc, 0).take(); 7993 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 7994 } 7995 } 7996 // Create a reference to the __builtin_memcpy builtin function. 7997 else if (!BuiltinMemCpyRef) { 7998 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 7999 LookupOrdinaryName); 8000 LookupName(R, TUScope, true); 8001 8002 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 8003 if (!BuiltinMemCpy) { 8004 // Something went horribly wrong earlier, and we will have complained 8005 // about it. 8006 Invalid = true; 8007 continue; 8008 } 8009 8010 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 8011 BuiltinMemCpy->getType(), 8012 VK_LValue, Loc, 0).take(); 8013 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 8014 } 8015 8016 ASTOwningVector<Expr*> CallArgs(*this); 8017 CallArgs.push_back(To.takeAs<Expr>()); 8018 CallArgs.push_back(From.takeAs<Expr>()); 8019 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 8020 ExprResult Call = ExprError(); 8021 if (NeedsCollectableMemCpy) 8022 Call = ActOnCallExpr(/*Scope=*/0, 8023 CollectableMemCpyRef, 8024 Loc, move_arg(CallArgs), 8025 Loc); 8026 else 8027 Call = ActOnCallExpr(/*Scope=*/0, 8028 BuiltinMemCpyRef, 8029 Loc, move_arg(CallArgs), 8030 Loc); 8031 8032 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8033 Statements.push_back(Call.takeAs<Expr>()); 8034 continue; 8035 } 8036 8037 // Build the move of this field. 8038 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType, 8039 To.get(), From.get(), 8040 /*CopyingBaseSubobject=*/false, 8041 /*Copying=*/false); 8042 if (Move.isInvalid()) { 8043 Diag(CurrentLocation, diag::note_member_synthesized_at) 8044 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8045 MoveAssignOperator->setInvalidDecl(); 8046 return; 8047 } 8048 8049 // Success! Record the copy. 8050 Statements.push_back(Move.takeAs<Stmt>()); 8051 } 8052 8053 if (!Invalid) { 8054 // Add a "return *this;" 8055 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8056 8057 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 8058 if (Return.isInvalid()) 8059 Invalid = true; 8060 else { 8061 Statements.push_back(Return.takeAs<Stmt>()); 8062 8063 if (Trap.hasErrorOccurred()) { 8064 Diag(CurrentLocation, diag::note_member_synthesized_at) 8065 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8066 Invalid = true; 8067 } 8068 } 8069 } 8070 8071 if (Invalid) { 8072 MoveAssignOperator->setInvalidDecl(); 8073 return; 8074 } 8075 8076 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 8077 /*isStmtExpr=*/false); 8078 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 8079 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 8080 8081 if (ASTMutationListener *L = getASTMutationListener()) { 8082 L->CompletedImplicitDefinition(MoveAssignOperator); 8083 } 8084} 8085 8086std::pair<Sema::ImplicitExceptionSpecification, bool> 8087Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) { 8088 if (ClassDecl->isInvalidDecl()) 8089 return std::make_pair(ImplicitExceptionSpecification(Context), false); 8090 8091 // C++ [class.copy]p5: 8092 // The implicitly-declared copy constructor for a class X will 8093 // have the form 8094 // 8095 // X::X(const X&) 8096 // 8097 // if 8098 // FIXME: It ought to be possible to store this on the record. 8099 bool HasConstCopyConstructor = true; 8100 8101 // -- each direct or virtual base class B of X has a copy 8102 // constructor whose first parameter is of type const B& or 8103 // const volatile B&, and 8104 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8105 BaseEnd = ClassDecl->bases_end(); 8106 HasConstCopyConstructor && Base != BaseEnd; 8107 ++Base) { 8108 // Virtual bases are handled below. 8109 if (Base->isVirtual()) 8110 continue; 8111 8112 CXXRecordDecl *BaseClassDecl 8113 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8114 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const, 8115 &HasConstCopyConstructor); 8116 } 8117 8118 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8119 BaseEnd = ClassDecl->vbases_end(); 8120 HasConstCopyConstructor && Base != BaseEnd; 8121 ++Base) { 8122 CXXRecordDecl *BaseClassDecl 8123 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8124 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const, 8125 &HasConstCopyConstructor); 8126 } 8127 8128 // -- for all the nonstatic data members of X that are of a 8129 // class type M (or array thereof), each such class type 8130 // has a copy constructor whose first parameter is of type 8131 // const M& or const volatile M&. 8132 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8133 FieldEnd = ClassDecl->field_end(); 8134 HasConstCopyConstructor && Field != FieldEnd; 8135 ++Field) { 8136 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 8137 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8138 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const, 8139 &HasConstCopyConstructor); 8140 } 8141 } 8142 // Otherwise, the implicitly declared copy constructor will have 8143 // the form 8144 // 8145 // X::X(X&) 8146 8147 // C++ [except.spec]p14: 8148 // An implicitly declared special member function (Clause 12) shall have an 8149 // exception-specification. [...] 8150 ImplicitExceptionSpecification ExceptSpec(Context); 8151 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0; 8152 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8153 BaseEnd = ClassDecl->bases_end(); 8154 Base != BaseEnd; 8155 ++Base) { 8156 // Virtual bases are handled below. 8157 if (Base->isVirtual()) 8158 continue; 8159 8160 CXXRecordDecl *BaseClassDecl 8161 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8162 if (CXXConstructorDecl *CopyConstructor = 8163 LookupCopyingConstructor(BaseClassDecl, Quals)) 8164 ExceptSpec.CalledDecl(CopyConstructor); 8165 } 8166 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8167 BaseEnd = ClassDecl->vbases_end(); 8168 Base != BaseEnd; 8169 ++Base) { 8170 CXXRecordDecl *BaseClassDecl 8171 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8172 if (CXXConstructorDecl *CopyConstructor = 8173 LookupCopyingConstructor(BaseClassDecl, Quals)) 8174 ExceptSpec.CalledDecl(CopyConstructor); 8175 } 8176 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8177 FieldEnd = ClassDecl->field_end(); 8178 Field != FieldEnd; 8179 ++Field) { 8180 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 8181 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8182 if (CXXConstructorDecl *CopyConstructor = 8183 LookupCopyingConstructor(FieldClassDecl, Quals)) 8184 ExceptSpec.CalledDecl(CopyConstructor); 8185 } 8186 } 8187 8188 return std::make_pair(ExceptSpec, HasConstCopyConstructor); 8189} 8190 8191CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 8192 CXXRecordDecl *ClassDecl) { 8193 // C++ [class.copy]p4: 8194 // If the class definition does not explicitly declare a copy 8195 // constructor, one is declared implicitly. 8196 8197 ImplicitExceptionSpecification Spec(Context); 8198 bool Const; 8199 llvm::tie(Spec, Const) = 8200 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl); 8201 8202 QualType ClassType = Context.getTypeDeclType(ClassDecl); 8203 QualType ArgType = ClassType; 8204 if (Const) 8205 ArgType = ArgType.withConst(); 8206 ArgType = Context.getLValueReferenceType(ArgType); 8207 8208 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 8209 8210 DeclarationName Name 8211 = Context.DeclarationNames.getCXXConstructorName( 8212 Context.getCanonicalType(ClassType)); 8213 SourceLocation ClassLoc = ClassDecl->getLocation(); 8214 DeclarationNameInfo NameInfo(Name, ClassLoc); 8215 8216 // An implicitly-declared copy constructor is an inline public 8217 // member of its class. 8218 CXXConstructorDecl *CopyConstructor 8219 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8220 Context.getFunctionType(Context.VoidTy, 8221 &ArgType, 1, EPI), 8222 /*TInfo=*/0, 8223 /*isExplicit=*/false, 8224 /*isInline=*/true, 8225 /*isImplicitlyDeclared=*/true, 8226 // FIXME: apply the rules for definitions here 8227 /*isConstexpr=*/false); 8228 CopyConstructor->setAccess(AS_public); 8229 CopyConstructor->setDefaulted(); 8230 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 8231 8232 // Note that we have declared this constructor. 8233 ++ASTContext::NumImplicitCopyConstructorsDeclared; 8234 8235 // Add the parameter to the constructor. 8236 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 8237 ClassLoc, ClassLoc, 8238 /*IdentifierInfo=*/0, 8239 ArgType, /*TInfo=*/0, 8240 SC_None, 8241 SC_None, 0); 8242 CopyConstructor->setParams(&FromParam, 1); 8243 8244 if (Scope *S = getScopeForContext(ClassDecl)) 8245 PushOnScopeChains(CopyConstructor, S, false); 8246 ClassDecl->addDecl(CopyConstructor); 8247 8248 // C++0x [class.copy]p7: 8249 // ... If the class definition declares a move constructor or move 8250 // assignment operator, the implicitly declared constructor is defined as 8251 // deleted; ... 8252 if (ClassDecl->hasUserDeclaredMoveConstructor() || 8253 ClassDecl->hasUserDeclaredMoveAssignment() || 8254 ShouldDeleteCopyConstructor(CopyConstructor)) 8255 CopyConstructor->setDeletedAsWritten(); 8256 8257 return CopyConstructor; 8258} 8259 8260void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 8261 CXXConstructorDecl *CopyConstructor) { 8262 assert((CopyConstructor->isDefaulted() && 8263 CopyConstructor->isCopyConstructor() && 8264 !CopyConstructor->doesThisDeclarationHaveABody()) && 8265 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 8266 8267 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 8268 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 8269 8270 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor); 8271 DiagnosticErrorTrap Trap(Diags); 8272 8273 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) || 8274 Trap.hasErrorOccurred()) { 8275 Diag(CurrentLocation, diag::note_member_synthesized_at) 8276 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 8277 CopyConstructor->setInvalidDecl(); 8278 } else { 8279 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 8280 CopyConstructor->getLocation(), 8281 MultiStmtArg(*this, 0, 0), 8282 /*isStmtExpr=*/false) 8283 .takeAs<Stmt>()); 8284 } 8285 8286 CopyConstructor->setUsed(); 8287 8288 if (ASTMutationListener *L = getASTMutationListener()) { 8289 L->CompletedImplicitDefinition(CopyConstructor); 8290 } 8291} 8292 8293Sema::ImplicitExceptionSpecification 8294Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) { 8295 // C++ [except.spec]p14: 8296 // An implicitly declared special member function (Clause 12) shall have an 8297 // exception-specification. [...] 8298 ImplicitExceptionSpecification ExceptSpec(Context); 8299 if (ClassDecl->isInvalidDecl()) 8300 return ExceptSpec; 8301 8302 // Direct base-class constructors. 8303 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8304 BEnd = ClassDecl->bases_end(); 8305 B != BEnd; ++B) { 8306 if (B->isVirtual()) // Handled below. 8307 continue; 8308 8309 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8310 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8311 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl); 8312 // If this is a deleted function, add it anyway. This might be conformant 8313 // with the standard. This might not. I'm not sure. It might not matter. 8314 if (Constructor) 8315 ExceptSpec.CalledDecl(Constructor); 8316 } 8317 } 8318 8319 // Virtual base-class constructors. 8320 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8321 BEnd = ClassDecl->vbases_end(); 8322 B != BEnd; ++B) { 8323 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8324 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8325 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl); 8326 // If this is a deleted function, add it anyway. This might be conformant 8327 // with the standard. This might not. I'm not sure. It might not matter. 8328 if (Constructor) 8329 ExceptSpec.CalledDecl(Constructor); 8330 } 8331 } 8332 8333 // Field constructors. 8334 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8335 FEnd = ClassDecl->field_end(); 8336 F != FEnd; ++F) { 8337 if (F->hasInClassInitializer()) { 8338 if (Expr *E = F->getInClassInitializer()) 8339 ExceptSpec.CalledExpr(E); 8340 else if (!F->isInvalidDecl()) 8341 ExceptSpec.SetDelayed(); 8342 } else if (const RecordType *RecordTy 8343 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8344 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8345 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl); 8346 // If this is a deleted function, add it anyway. This might be conformant 8347 // with the standard. This might not. I'm not sure. It might not matter. 8348 // In particular, the problem is that this function never gets called. It 8349 // might just be ill-formed because this function attempts to refer to 8350 // a deleted function here. 8351 if (Constructor) 8352 ExceptSpec.CalledDecl(Constructor); 8353 } 8354 } 8355 8356 return ExceptSpec; 8357} 8358 8359CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 8360 CXXRecordDecl *ClassDecl) { 8361 ImplicitExceptionSpecification Spec( 8362 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl)); 8363 8364 QualType ClassType = Context.getTypeDeclType(ClassDecl); 8365 QualType ArgType = Context.getRValueReferenceType(ClassType); 8366 8367 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI(); 8368 8369 DeclarationName Name 8370 = Context.DeclarationNames.getCXXConstructorName( 8371 Context.getCanonicalType(ClassType)); 8372 SourceLocation ClassLoc = ClassDecl->getLocation(); 8373 DeclarationNameInfo NameInfo(Name, ClassLoc); 8374 8375 // C++0x [class.copy]p11: 8376 // An implicitly-declared copy/move constructor is an inline public 8377 // member of its class. 8378 CXXConstructorDecl *MoveConstructor 8379 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8380 Context.getFunctionType(Context.VoidTy, 8381 &ArgType, 1, EPI), 8382 /*TInfo=*/0, 8383 /*isExplicit=*/false, 8384 /*isInline=*/true, 8385 /*isImplicitlyDeclared=*/true, 8386 // FIXME: apply the rules for definitions here 8387 /*isConstexpr=*/false); 8388 MoveConstructor->setAccess(AS_public); 8389 MoveConstructor->setDefaulted(); 8390 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor()); 8391 8392 // Add the parameter to the constructor. 8393 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 8394 ClassLoc, ClassLoc, 8395 /*IdentifierInfo=*/0, 8396 ArgType, /*TInfo=*/0, 8397 SC_None, 8398 SC_None, 0); 8399 MoveConstructor->setParams(&FromParam, 1); 8400 8401 // C++0x [class.copy]p9: 8402 // If the definition of a class X does not explicitly declare a move 8403 // constructor, one will be implicitly declared as defaulted if and only if: 8404 // [...] 8405 // - the move constructor would not be implicitly defined as deleted. 8406 if (ShouldDeleteMoveConstructor(MoveConstructor)) { 8407 // Cache this result so that we don't try to generate this over and over 8408 // on every lookup, leaking memory and wasting time. 8409 ClassDecl->setFailedImplicitMoveConstructor(); 8410 return 0; 8411 } 8412 8413 // Note that we have declared this constructor. 8414 ++ASTContext::NumImplicitMoveConstructorsDeclared; 8415 8416 if (Scope *S = getScopeForContext(ClassDecl)) 8417 PushOnScopeChains(MoveConstructor, S, false); 8418 ClassDecl->addDecl(MoveConstructor); 8419 8420 return MoveConstructor; 8421} 8422 8423void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 8424 CXXConstructorDecl *MoveConstructor) { 8425 assert((MoveConstructor->isDefaulted() && 8426 MoveConstructor->isMoveConstructor() && 8427 !MoveConstructor->doesThisDeclarationHaveABody()) && 8428 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 8429 8430 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 8431 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 8432 8433 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor); 8434 DiagnosticErrorTrap Trap(Diags); 8435 8436 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) || 8437 Trap.hasErrorOccurred()) { 8438 Diag(CurrentLocation, diag::note_member_synthesized_at) 8439 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 8440 MoveConstructor->setInvalidDecl(); 8441 } else { 8442 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(), 8443 MoveConstructor->getLocation(), 8444 MultiStmtArg(*this, 0, 0), 8445 /*isStmtExpr=*/false) 8446 .takeAs<Stmt>()); 8447 } 8448 8449 MoveConstructor->setUsed(); 8450 8451 if (ASTMutationListener *L = getASTMutationListener()) { 8452 L->CompletedImplicitDefinition(MoveConstructor); 8453 } 8454} 8455 8456ExprResult 8457Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 8458 CXXConstructorDecl *Constructor, 8459 MultiExprArg ExprArgs, 8460 bool RequiresZeroInit, 8461 unsigned ConstructKind, 8462 SourceRange ParenRange) { 8463 bool Elidable = false; 8464 8465 // C++0x [class.copy]p34: 8466 // When certain criteria are met, an implementation is allowed to 8467 // omit the copy/move construction of a class object, even if the 8468 // copy/move constructor and/or destructor for the object have 8469 // side effects. [...] 8470 // - when a temporary class object that has not been bound to a 8471 // reference (12.2) would be copied/moved to a class object 8472 // with the same cv-unqualified type, the copy/move operation 8473 // can be omitted by constructing the temporary object 8474 // directly into the target of the omitted copy/move 8475 if (ConstructKind == CXXConstructExpr::CK_Complete && 8476 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) { 8477 Expr *SubExpr = ((Expr **)ExprArgs.get())[0]; 8478 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 8479 } 8480 8481 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 8482 Elidable, move(ExprArgs), RequiresZeroInit, 8483 ConstructKind, ParenRange); 8484} 8485 8486/// BuildCXXConstructExpr - Creates a complete call to a constructor, 8487/// including handling of its default argument expressions. 8488ExprResult 8489Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 8490 CXXConstructorDecl *Constructor, bool Elidable, 8491 MultiExprArg ExprArgs, 8492 bool RequiresZeroInit, 8493 unsigned ConstructKind, 8494 SourceRange ParenRange) { 8495 unsigned NumExprs = ExprArgs.size(); 8496 Expr **Exprs = (Expr **)ExprArgs.release(); 8497 8498 for (specific_attr_iterator<NonNullAttr> 8499 i = Constructor->specific_attr_begin<NonNullAttr>(), 8500 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) { 8501 const NonNullAttr *NonNull = *i; 8502 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc); 8503 } 8504 8505 MarkDeclarationReferenced(ConstructLoc, Constructor); 8506 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 8507 Constructor, Elidable, Exprs, NumExprs, 8508 RequiresZeroInit, 8509 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 8510 ParenRange)); 8511} 8512 8513bool Sema::InitializeVarWithConstructor(VarDecl *VD, 8514 CXXConstructorDecl *Constructor, 8515 MultiExprArg Exprs) { 8516 // FIXME: Provide the correct paren SourceRange when available. 8517 ExprResult TempResult = 8518 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 8519 move(Exprs), false, CXXConstructExpr::CK_Complete, 8520 SourceRange()); 8521 if (TempResult.isInvalid()) 8522 return true; 8523 8524 Expr *Temp = TempResult.takeAs<Expr>(); 8525 CheckImplicitConversions(Temp, VD->getLocation()); 8526 MarkDeclarationReferenced(VD->getLocation(), Constructor); 8527 Temp = MaybeCreateExprWithCleanups(Temp); 8528 VD->setInit(Temp); 8529 8530 return false; 8531} 8532 8533void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 8534 if (VD->isInvalidDecl()) return; 8535 8536 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 8537 if (ClassDecl->isInvalidDecl()) return; 8538 if (ClassDecl->hasTrivialDestructor()) return; 8539 if (ClassDecl->isDependentContext()) return; 8540 8541 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 8542 MarkDeclarationReferenced(VD->getLocation(), Destructor); 8543 CheckDestructorAccess(VD->getLocation(), Destructor, 8544 PDiag(diag::err_access_dtor_var) 8545 << VD->getDeclName() 8546 << VD->getType()); 8547 8548 if (!VD->hasGlobalStorage()) return; 8549 8550 // Emit warning for non-trivial dtor in global scope (a real global, 8551 // class-static, function-static). 8552 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 8553 8554 // TODO: this should be re-enabled for static locals by !CXAAtExit 8555 if (!VD->isStaticLocal()) 8556 Diag(VD->getLocation(), diag::warn_global_destructor); 8557} 8558 8559/// AddCXXDirectInitializerToDecl - This action is called immediately after 8560/// ActOnDeclarator, when a C++ direct initializer is present. 8561/// e.g: "int x(1);" 8562void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl, 8563 SourceLocation LParenLoc, 8564 MultiExprArg Exprs, 8565 SourceLocation RParenLoc, 8566 bool TypeMayContainAuto) { 8567 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions"); 8568 8569 // If there is no declaration, there was an error parsing it. Just ignore 8570 // the initializer. 8571 if (RealDecl == 0) 8572 return; 8573 8574 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8575 if (!VDecl) { 8576 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8577 RealDecl->setInvalidDecl(); 8578 return; 8579 } 8580 8581 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8582 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) { 8583 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed 8584 if (Exprs.size() > 1) { 8585 Diag(Exprs.get()[1]->getSourceRange().getBegin(), 8586 diag::err_auto_var_init_multiple_expressions) 8587 << VDecl->getDeclName() << VDecl->getType() 8588 << VDecl->getSourceRange(); 8589 RealDecl->setInvalidDecl(); 8590 return; 8591 } 8592 8593 Expr *Init = Exprs.get()[0]; 8594 TypeSourceInfo *DeducedType = 0; 8595 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType)) 8596 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure) 8597 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 8598 << Init->getSourceRange(); 8599 if (!DeducedType) { 8600 RealDecl->setInvalidDecl(); 8601 return; 8602 } 8603 VDecl->setTypeSourceInfo(DeducedType); 8604 VDecl->setType(DeducedType->getType()); 8605 8606 // In ARC, infer lifetime. 8607 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8608 VDecl->setInvalidDecl(); 8609 8610 // If this is a redeclaration, check that the type we just deduced matches 8611 // the previously declared type. 8612 if (VarDecl *Old = VDecl->getPreviousDeclaration()) 8613 MergeVarDeclTypes(VDecl, Old); 8614 } 8615 8616 // We will represent direct-initialization similarly to copy-initialization: 8617 // int x(1); -as-> int x = 1; 8618 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 8619 // 8620 // Clients that want to distinguish between the two forms, can check for 8621 // direct initializer using VarDecl::hasCXXDirectInitializer(). 8622 // A major benefit is that clients that don't particularly care about which 8623 // exactly form was it (like the CodeGen) can handle both cases without 8624 // special case code. 8625 8626 // C++ 8.5p11: 8627 // The form of initialization (using parentheses or '=') is generally 8628 // insignificant, but does matter when the entity being initialized has a 8629 // class type. 8630 8631 if (!VDecl->getType()->isDependentType() && 8632 RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 8633 diag::err_typecheck_decl_incomplete_type)) { 8634 VDecl->setInvalidDecl(); 8635 return; 8636 } 8637 8638 // The variable can not have an abstract class type. 8639 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8640 diag::err_abstract_type_in_decl, 8641 AbstractVariableType)) 8642 VDecl->setInvalidDecl(); 8643 8644 const VarDecl *Def; 8645 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8646 Diag(VDecl->getLocation(), diag::err_redefinition) 8647 << VDecl->getDeclName(); 8648 Diag(Def->getLocation(), diag::note_previous_definition); 8649 VDecl->setInvalidDecl(); 8650 return; 8651 } 8652 8653 // C++ [class.static.data]p4 8654 // If a static data member is of const integral or const 8655 // enumeration type, its declaration in the class definition can 8656 // specify a constant-initializer which shall be an integral 8657 // constant expression (5.19). In that case, the member can appear 8658 // in integral constant expressions. The member shall still be 8659 // defined in a namespace scope if it is used in the program and the 8660 // namespace scope definition shall not contain an initializer. 8661 // 8662 // We already performed a redefinition check above, but for static 8663 // data members we also need to check whether there was an in-class 8664 // declaration with an initializer. 8665 const VarDecl* PrevInit = 0; 8666 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8667 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName(); 8668 Diag(PrevInit->getLocation(), diag::note_previous_definition); 8669 return; 8670 } 8671 8672 bool IsDependent = false; 8673 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) { 8674 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) { 8675 VDecl->setInvalidDecl(); 8676 return; 8677 } 8678 8679 if (Exprs.get()[I]->isTypeDependent()) 8680 IsDependent = true; 8681 } 8682 8683 // If either the declaration has a dependent type or if any of the 8684 // expressions is type-dependent, we represent the initialization 8685 // via a ParenListExpr for later use during template instantiation. 8686 if (VDecl->getType()->isDependentType() || IsDependent) { 8687 // Let clients know that initialization was done with a direct initializer. 8688 VDecl->setCXXDirectInitializer(true); 8689 8690 // Store the initialization expressions as a ParenListExpr. 8691 unsigned NumExprs = Exprs.size(); 8692 VDecl->setInit(new (Context) ParenListExpr( 8693 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc, 8694 VDecl->getType().getNonReferenceType())); 8695 return; 8696 } 8697 8698 // Capture the variable that is being initialized and the style of 8699 // initialization. 8700 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8701 8702 // FIXME: Poor source location information. 8703 InitializationKind Kind 8704 = InitializationKind::CreateDirect(VDecl->getLocation(), 8705 LParenLoc, RParenLoc); 8706 8707 InitializationSequence InitSeq(*this, Entity, Kind, 8708 Exprs.get(), Exprs.size()); 8709 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs)); 8710 if (Result.isInvalid()) { 8711 VDecl->setInvalidDecl(); 8712 return; 8713 } 8714 8715 CheckImplicitConversions(Result.get(), LParenLoc); 8716 8717 Result = MaybeCreateExprWithCleanups(Result); 8718 VDecl->setInit(Result.takeAs<Expr>()); 8719 VDecl->setCXXDirectInitializer(true); 8720 8721 CheckCompleteVariableDeclaration(VDecl); 8722} 8723 8724/// \brief Given a constructor and the set of arguments provided for the 8725/// constructor, convert the arguments and add any required default arguments 8726/// to form a proper call to this constructor. 8727/// 8728/// \returns true if an error occurred, false otherwise. 8729bool 8730Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 8731 MultiExprArg ArgsPtr, 8732 SourceLocation Loc, 8733 ASTOwningVector<Expr*> &ConvertedArgs) { 8734 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 8735 unsigned NumArgs = ArgsPtr.size(); 8736 Expr **Args = (Expr **)ArgsPtr.get(); 8737 8738 const FunctionProtoType *Proto 8739 = Constructor->getType()->getAs<FunctionProtoType>(); 8740 assert(Proto && "Constructor without a prototype?"); 8741 unsigned NumArgsInProto = Proto->getNumArgs(); 8742 8743 // If too few arguments are available, we'll fill in the rest with defaults. 8744 if (NumArgs < NumArgsInProto) 8745 ConvertedArgs.reserve(NumArgsInProto); 8746 else 8747 ConvertedArgs.reserve(NumArgs); 8748 8749 VariadicCallType CallType = 8750 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 8751 SmallVector<Expr *, 8> AllArgs; 8752 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 8753 Proto, 0, Args, NumArgs, AllArgs, 8754 CallType); 8755 for (unsigned i =0, size = AllArgs.size(); i < size; i++) 8756 ConvertedArgs.push_back(AllArgs[i]); 8757 return Invalid; 8758} 8759 8760static inline bool 8761CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 8762 const FunctionDecl *FnDecl) { 8763 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 8764 if (isa<NamespaceDecl>(DC)) { 8765 return SemaRef.Diag(FnDecl->getLocation(), 8766 diag::err_operator_new_delete_declared_in_namespace) 8767 << FnDecl->getDeclName(); 8768 } 8769 8770 if (isa<TranslationUnitDecl>(DC) && 8771 FnDecl->getStorageClass() == SC_Static) { 8772 return SemaRef.Diag(FnDecl->getLocation(), 8773 diag::err_operator_new_delete_declared_static) 8774 << FnDecl->getDeclName(); 8775 } 8776 8777 return false; 8778} 8779 8780static inline bool 8781CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 8782 CanQualType ExpectedResultType, 8783 CanQualType ExpectedFirstParamType, 8784 unsigned DependentParamTypeDiag, 8785 unsigned InvalidParamTypeDiag) { 8786 QualType ResultType = 8787 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 8788 8789 // Check that the result type is not dependent. 8790 if (ResultType->isDependentType()) 8791 return SemaRef.Diag(FnDecl->getLocation(), 8792 diag::err_operator_new_delete_dependent_result_type) 8793 << FnDecl->getDeclName() << ExpectedResultType; 8794 8795 // Check that the result type is what we expect. 8796 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 8797 return SemaRef.Diag(FnDecl->getLocation(), 8798 diag::err_operator_new_delete_invalid_result_type) 8799 << FnDecl->getDeclName() << ExpectedResultType; 8800 8801 // A function template must have at least 2 parameters. 8802 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 8803 return SemaRef.Diag(FnDecl->getLocation(), 8804 diag::err_operator_new_delete_template_too_few_parameters) 8805 << FnDecl->getDeclName(); 8806 8807 // The function decl must have at least 1 parameter. 8808 if (FnDecl->getNumParams() == 0) 8809 return SemaRef.Diag(FnDecl->getLocation(), 8810 diag::err_operator_new_delete_too_few_parameters) 8811 << FnDecl->getDeclName(); 8812 8813 // Check the the first parameter type is not dependent. 8814 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 8815 if (FirstParamType->isDependentType()) 8816 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 8817 << FnDecl->getDeclName() << ExpectedFirstParamType; 8818 8819 // Check that the first parameter type is what we expect. 8820 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 8821 ExpectedFirstParamType) 8822 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 8823 << FnDecl->getDeclName() << ExpectedFirstParamType; 8824 8825 return false; 8826} 8827 8828static bool 8829CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 8830 // C++ [basic.stc.dynamic.allocation]p1: 8831 // A program is ill-formed if an allocation function is declared in a 8832 // namespace scope other than global scope or declared static in global 8833 // scope. 8834 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 8835 return true; 8836 8837 CanQualType SizeTy = 8838 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 8839 8840 // C++ [basic.stc.dynamic.allocation]p1: 8841 // The return type shall be void*. The first parameter shall have type 8842 // std::size_t. 8843 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 8844 SizeTy, 8845 diag::err_operator_new_dependent_param_type, 8846 diag::err_operator_new_param_type)) 8847 return true; 8848 8849 // C++ [basic.stc.dynamic.allocation]p1: 8850 // The first parameter shall not have an associated default argument. 8851 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 8852 return SemaRef.Diag(FnDecl->getLocation(), 8853 diag::err_operator_new_default_arg) 8854 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 8855 8856 return false; 8857} 8858 8859static bool 8860CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 8861 // C++ [basic.stc.dynamic.deallocation]p1: 8862 // A program is ill-formed if deallocation functions are declared in a 8863 // namespace scope other than global scope or declared static in global 8864 // scope. 8865 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 8866 return true; 8867 8868 // C++ [basic.stc.dynamic.deallocation]p2: 8869 // Each deallocation function shall return void and its first parameter 8870 // shall be void*. 8871 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 8872 SemaRef.Context.VoidPtrTy, 8873 diag::err_operator_delete_dependent_param_type, 8874 diag::err_operator_delete_param_type)) 8875 return true; 8876 8877 return false; 8878} 8879 8880/// CheckOverloadedOperatorDeclaration - Check whether the declaration 8881/// of this overloaded operator is well-formed. If so, returns false; 8882/// otherwise, emits appropriate diagnostics and returns true. 8883bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 8884 assert(FnDecl && FnDecl->isOverloadedOperator() && 8885 "Expected an overloaded operator declaration"); 8886 8887 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 8888 8889 // C++ [over.oper]p5: 8890 // The allocation and deallocation functions, operator new, 8891 // operator new[], operator delete and operator delete[], are 8892 // described completely in 3.7.3. The attributes and restrictions 8893 // found in the rest of this subclause do not apply to them unless 8894 // explicitly stated in 3.7.3. 8895 if (Op == OO_Delete || Op == OO_Array_Delete) 8896 return CheckOperatorDeleteDeclaration(*this, FnDecl); 8897 8898 if (Op == OO_New || Op == OO_Array_New) 8899 return CheckOperatorNewDeclaration(*this, FnDecl); 8900 8901 // C++ [over.oper]p6: 8902 // An operator function shall either be a non-static member 8903 // function or be a non-member function and have at least one 8904 // parameter whose type is a class, a reference to a class, an 8905 // enumeration, or a reference to an enumeration. 8906 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 8907 if (MethodDecl->isStatic()) 8908 return Diag(FnDecl->getLocation(), 8909 diag::err_operator_overload_static) << FnDecl->getDeclName(); 8910 } else { 8911 bool ClassOrEnumParam = false; 8912 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 8913 ParamEnd = FnDecl->param_end(); 8914 Param != ParamEnd; ++Param) { 8915 QualType ParamType = (*Param)->getType().getNonReferenceType(); 8916 if (ParamType->isDependentType() || ParamType->isRecordType() || 8917 ParamType->isEnumeralType()) { 8918 ClassOrEnumParam = true; 8919 break; 8920 } 8921 } 8922 8923 if (!ClassOrEnumParam) 8924 return Diag(FnDecl->getLocation(), 8925 diag::err_operator_overload_needs_class_or_enum) 8926 << FnDecl->getDeclName(); 8927 } 8928 8929 // C++ [over.oper]p8: 8930 // An operator function cannot have default arguments (8.3.6), 8931 // except where explicitly stated below. 8932 // 8933 // Only the function-call operator allows default arguments 8934 // (C++ [over.call]p1). 8935 if (Op != OO_Call) { 8936 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 8937 Param != FnDecl->param_end(); ++Param) { 8938 if ((*Param)->hasDefaultArg()) 8939 return Diag((*Param)->getLocation(), 8940 diag::err_operator_overload_default_arg) 8941 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 8942 } 8943 } 8944 8945 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 8946 { false, false, false } 8947#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 8948 , { Unary, Binary, MemberOnly } 8949#include "clang/Basic/OperatorKinds.def" 8950 }; 8951 8952 bool CanBeUnaryOperator = OperatorUses[Op][0]; 8953 bool CanBeBinaryOperator = OperatorUses[Op][1]; 8954 bool MustBeMemberOperator = OperatorUses[Op][2]; 8955 8956 // C++ [over.oper]p8: 8957 // [...] Operator functions cannot have more or fewer parameters 8958 // than the number required for the corresponding operator, as 8959 // described in the rest of this subclause. 8960 unsigned NumParams = FnDecl->getNumParams() 8961 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 8962 if (Op != OO_Call && 8963 ((NumParams == 1 && !CanBeUnaryOperator) || 8964 (NumParams == 2 && !CanBeBinaryOperator) || 8965 (NumParams < 1) || (NumParams > 2))) { 8966 // We have the wrong number of parameters. 8967 unsigned ErrorKind; 8968 if (CanBeUnaryOperator && CanBeBinaryOperator) { 8969 ErrorKind = 2; // 2 -> unary or binary. 8970 } else if (CanBeUnaryOperator) { 8971 ErrorKind = 0; // 0 -> unary 8972 } else { 8973 assert(CanBeBinaryOperator && 8974 "All non-call overloaded operators are unary or binary!"); 8975 ErrorKind = 1; // 1 -> binary 8976 } 8977 8978 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 8979 << FnDecl->getDeclName() << NumParams << ErrorKind; 8980 } 8981 8982 // Overloaded operators other than operator() cannot be variadic. 8983 if (Op != OO_Call && 8984 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 8985 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 8986 << FnDecl->getDeclName(); 8987 } 8988 8989 // Some operators must be non-static member functions. 8990 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 8991 return Diag(FnDecl->getLocation(), 8992 diag::err_operator_overload_must_be_member) 8993 << FnDecl->getDeclName(); 8994 } 8995 8996 // C++ [over.inc]p1: 8997 // The user-defined function called operator++ implements the 8998 // prefix and postfix ++ operator. If this function is a member 8999 // function with no parameters, or a non-member function with one 9000 // parameter of class or enumeration type, it defines the prefix 9001 // increment operator ++ for objects of that type. If the function 9002 // is a member function with one parameter (which shall be of type 9003 // int) or a non-member function with two parameters (the second 9004 // of which shall be of type int), it defines the postfix 9005 // increment operator ++ for objects of that type. 9006 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 9007 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 9008 bool ParamIsInt = false; 9009 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 9010 ParamIsInt = BT->getKind() == BuiltinType::Int; 9011 9012 if (!ParamIsInt) 9013 return Diag(LastParam->getLocation(), 9014 diag::err_operator_overload_post_incdec_must_be_int) 9015 << LastParam->getType() << (Op == OO_MinusMinus); 9016 } 9017 9018 return false; 9019} 9020 9021/// CheckLiteralOperatorDeclaration - Check whether the declaration 9022/// of this literal operator function is well-formed. If so, returns 9023/// false; otherwise, emits appropriate diagnostics and returns true. 9024bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 9025 DeclContext *DC = FnDecl->getDeclContext(); 9026 Decl::Kind Kind = DC->getDeclKind(); 9027 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace && 9028 Kind != Decl::LinkageSpec) { 9029 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 9030 << FnDecl->getDeclName(); 9031 return true; 9032 } 9033 9034 bool Valid = false; 9035 9036 // template <char...> type operator "" name() is the only valid template 9037 // signature, and the only valid signature with no parameters. 9038 if (FnDecl->param_size() == 0) { 9039 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) { 9040 // Must have only one template parameter 9041 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 9042 if (Params->size() == 1) { 9043 NonTypeTemplateParmDecl *PmDecl = 9044 cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 9045 9046 // The template parameter must be a char parameter pack. 9047 if (PmDecl && PmDecl->isTemplateParameterPack() && 9048 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 9049 Valid = true; 9050 } 9051 } 9052 } else { 9053 // Check the first parameter 9054 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9055 9056 QualType T = (*Param)->getType(); 9057 9058 // unsigned long long int, long double, and any character type are allowed 9059 // as the only parameters. 9060 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 9061 Context.hasSameType(T, Context.LongDoubleTy) || 9062 Context.hasSameType(T, Context.CharTy) || 9063 Context.hasSameType(T, Context.WCharTy) || 9064 Context.hasSameType(T, Context.Char16Ty) || 9065 Context.hasSameType(T, Context.Char32Ty)) { 9066 if (++Param == FnDecl->param_end()) 9067 Valid = true; 9068 goto FinishedParams; 9069 } 9070 9071 // Otherwise it must be a pointer to const; let's strip those qualifiers. 9072 const PointerType *PT = T->getAs<PointerType>(); 9073 if (!PT) 9074 goto FinishedParams; 9075 T = PT->getPointeeType(); 9076 if (!T.isConstQualified()) 9077 goto FinishedParams; 9078 T = T.getUnqualifiedType(); 9079 9080 // Move on to the second parameter; 9081 ++Param; 9082 9083 // If there is no second parameter, the first must be a const char * 9084 if (Param == FnDecl->param_end()) { 9085 if (Context.hasSameType(T, Context.CharTy)) 9086 Valid = true; 9087 goto FinishedParams; 9088 } 9089 9090 // const char *, const wchar_t*, const char16_t*, and const char32_t* 9091 // are allowed as the first parameter to a two-parameter function 9092 if (!(Context.hasSameType(T, Context.CharTy) || 9093 Context.hasSameType(T, Context.WCharTy) || 9094 Context.hasSameType(T, Context.Char16Ty) || 9095 Context.hasSameType(T, Context.Char32Ty))) 9096 goto FinishedParams; 9097 9098 // The second and final parameter must be an std::size_t 9099 T = (*Param)->getType().getUnqualifiedType(); 9100 if (Context.hasSameType(T, Context.getSizeType()) && 9101 ++Param == FnDecl->param_end()) 9102 Valid = true; 9103 } 9104 9105 // FIXME: This diagnostic is absolutely terrible. 9106FinishedParams: 9107 if (!Valid) { 9108 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 9109 << FnDecl->getDeclName(); 9110 return true; 9111 } 9112 9113 StringRef LiteralName 9114 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 9115 if (LiteralName[0] != '_') { 9116 // C++0x [usrlit.suffix]p1: 9117 // Literal suffix identifiers that do not start with an underscore are 9118 // reserved for future standardization. 9119 bool IsHexFloat = true; 9120 if (LiteralName.size() > 1 && 9121 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) { 9122 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) { 9123 if (!isdigit(LiteralName[I])) { 9124 IsHexFloat = false; 9125 break; 9126 } 9127 } 9128 } 9129 9130 if (IsHexFloat) 9131 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat) 9132 << LiteralName; 9133 else 9134 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved); 9135 } 9136 9137 return false; 9138} 9139 9140/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 9141/// linkage specification, including the language and (if present) 9142/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 9143/// the location of the language string literal, which is provided 9144/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 9145/// the '{' brace. Otherwise, this linkage specification does not 9146/// have any braces. 9147Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 9148 SourceLocation LangLoc, 9149 StringRef Lang, 9150 SourceLocation LBraceLoc) { 9151 LinkageSpecDecl::LanguageIDs Language; 9152 if (Lang == "\"C\"") 9153 Language = LinkageSpecDecl::lang_c; 9154 else if (Lang == "\"C++\"") 9155 Language = LinkageSpecDecl::lang_cxx; 9156 else { 9157 Diag(LangLoc, diag::err_bad_language); 9158 return 0; 9159 } 9160 9161 // FIXME: Add all the various semantics of linkage specifications 9162 9163 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 9164 ExternLoc, LangLoc, Language); 9165 CurContext->addDecl(D); 9166 PushDeclContext(S, D); 9167 return D; 9168} 9169 9170/// ActOnFinishLinkageSpecification - Complete the definition of 9171/// the C++ linkage specification LinkageSpec. If RBraceLoc is 9172/// valid, it's the position of the closing '}' brace in a linkage 9173/// specification that uses braces. 9174Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 9175 Decl *LinkageSpec, 9176 SourceLocation RBraceLoc) { 9177 if (LinkageSpec) { 9178 if (RBraceLoc.isValid()) { 9179 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 9180 LSDecl->setRBraceLoc(RBraceLoc); 9181 } 9182 PopDeclContext(); 9183 } 9184 return LinkageSpec; 9185} 9186 9187/// \brief Perform semantic analysis for the variable declaration that 9188/// occurs within a C++ catch clause, returning the newly-created 9189/// variable. 9190VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 9191 TypeSourceInfo *TInfo, 9192 SourceLocation StartLoc, 9193 SourceLocation Loc, 9194 IdentifierInfo *Name) { 9195 bool Invalid = false; 9196 QualType ExDeclType = TInfo->getType(); 9197 9198 // Arrays and functions decay. 9199 if (ExDeclType->isArrayType()) 9200 ExDeclType = Context.getArrayDecayedType(ExDeclType); 9201 else if (ExDeclType->isFunctionType()) 9202 ExDeclType = Context.getPointerType(ExDeclType); 9203 9204 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 9205 // The exception-declaration shall not denote a pointer or reference to an 9206 // incomplete type, other than [cv] void*. 9207 // N2844 forbids rvalue references. 9208 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 9209 Diag(Loc, diag::err_catch_rvalue_ref); 9210 Invalid = true; 9211 } 9212 9213 // GCC allows catching pointers and references to incomplete types 9214 // as an extension; so do we, but we warn by default. 9215 9216 QualType BaseType = ExDeclType; 9217 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 9218 unsigned DK = diag::err_catch_incomplete; 9219 bool IncompleteCatchIsInvalid = true; 9220 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 9221 BaseType = Ptr->getPointeeType(); 9222 Mode = 1; 9223 DK = diag::ext_catch_incomplete_ptr; 9224 IncompleteCatchIsInvalid = false; 9225 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 9226 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 9227 BaseType = Ref->getPointeeType(); 9228 Mode = 2; 9229 DK = diag::ext_catch_incomplete_ref; 9230 IncompleteCatchIsInvalid = false; 9231 } 9232 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 9233 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) && 9234 IncompleteCatchIsInvalid) 9235 Invalid = true; 9236 9237 if (!Invalid && !ExDeclType->isDependentType() && 9238 RequireNonAbstractType(Loc, ExDeclType, 9239 diag::err_abstract_type_in_decl, 9240 AbstractVariableType)) 9241 Invalid = true; 9242 9243 // Only the non-fragile NeXT runtime currently supports C++ catches 9244 // of ObjC types, and no runtime supports catching ObjC types by value. 9245 if (!Invalid && getLangOptions().ObjC1) { 9246 QualType T = ExDeclType; 9247 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 9248 T = RT->getPointeeType(); 9249 9250 if (T->isObjCObjectType()) { 9251 Diag(Loc, diag::err_objc_object_catch); 9252 Invalid = true; 9253 } else if (T->isObjCObjectPointerType()) { 9254 if (!getLangOptions().ObjCNonFragileABI) 9255 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 9256 } 9257 } 9258 9259 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 9260 ExDeclType, TInfo, SC_None, SC_None); 9261 ExDecl->setExceptionVariable(true); 9262 9263 if (!Invalid && !ExDeclType->isDependentType()) { 9264 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 9265 // C++ [except.handle]p16: 9266 // The object declared in an exception-declaration or, if the 9267 // exception-declaration does not specify a name, a temporary (12.2) is 9268 // copy-initialized (8.5) from the exception object. [...] 9269 // The object is destroyed when the handler exits, after the destruction 9270 // of any automatic objects initialized within the handler. 9271 // 9272 // We just pretend to initialize the object with itself, then make sure 9273 // it can be destroyed later. 9274 QualType initType = ExDeclType; 9275 9276 InitializedEntity entity = 9277 InitializedEntity::InitializeVariable(ExDecl); 9278 InitializationKind initKind = 9279 InitializationKind::CreateCopy(Loc, SourceLocation()); 9280 9281 Expr *opaqueValue = 9282 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 9283 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1); 9284 ExprResult result = sequence.Perform(*this, entity, initKind, 9285 MultiExprArg(&opaqueValue, 1)); 9286 if (result.isInvalid()) 9287 Invalid = true; 9288 else { 9289 // If the constructor used was non-trivial, set this as the 9290 // "initializer". 9291 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 9292 if (!construct->getConstructor()->isTrivial()) { 9293 Expr *init = MaybeCreateExprWithCleanups(construct); 9294 ExDecl->setInit(init); 9295 } 9296 9297 // And make sure it's destructable. 9298 FinalizeVarWithDestructor(ExDecl, recordType); 9299 } 9300 } 9301 } 9302 9303 if (Invalid) 9304 ExDecl->setInvalidDecl(); 9305 9306 return ExDecl; 9307} 9308 9309/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 9310/// handler. 9311Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 9312 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9313 bool Invalid = D.isInvalidType(); 9314 9315 // Check for unexpanded parameter packs. 9316 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 9317 UPPC_ExceptionType)) { 9318 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 9319 D.getIdentifierLoc()); 9320 Invalid = true; 9321 } 9322 9323 IdentifierInfo *II = D.getIdentifier(); 9324 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 9325 LookupOrdinaryName, 9326 ForRedeclaration)) { 9327 // The scope should be freshly made just for us. There is just no way 9328 // it contains any previous declaration. 9329 assert(!S->isDeclScope(PrevDecl)); 9330 if (PrevDecl->isTemplateParameter()) { 9331 // Maybe we will complain about the shadowed template parameter. 9332 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9333 } 9334 } 9335 9336 if (D.getCXXScopeSpec().isSet() && !Invalid) { 9337 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 9338 << D.getCXXScopeSpec().getRange(); 9339 Invalid = true; 9340 } 9341 9342 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 9343 D.getSourceRange().getBegin(), 9344 D.getIdentifierLoc(), 9345 D.getIdentifier()); 9346 if (Invalid) 9347 ExDecl->setInvalidDecl(); 9348 9349 // Add the exception declaration into this scope. 9350 if (II) 9351 PushOnScopeChains(ExDecl, S); 9352 else 9353 CurContext->addDecl(ExDecl); 9354 9355 ProcessDeclAttributes(S, ExDecl, D); 9356 return ExDecl; 9357} 9358 9359Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 9360 Expr *AssertExpr, 9361 Expr *AssertMessageExpr_, 9362 SourceLocation RParenLoc) { 9363 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_); 9364 9365 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 9366 llvm::APSInt Value(32); 9367 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 9368 Diag(StaticAssertLoc, 9369 diag::err_static_assert_expression_is_not_constant) << 9370 AssertExpr->getSourceRange(); 9371 return 0; 9372 } 9373 9374 if (Value == 0) { 9375 Diag(StaticAssertLoc, diag::err_static_assert_failed) 9376 << AssertMessage->getString() << AssertExpr->getSourceRange(); 9377 } 9378 } 9379 9380 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 9381 return 0; 9382 9383 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 9384 AssertExpr, AssertMessage, RParenLoc); 9385 9386 CurContext->addDecl(Decl); 9387 return Decl; 9388} 9389 9390/// \brief Perform semantic analysis of the given friend type declaration. 9391/// 9392/// \returns A friend declaration that. 9393FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc, 9394 TypeSourceInfo *TSInfo) { 9395 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 9396 9397 QualType T = TSInfo->getType(); 9398 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 9399 9400 if (!getLangOptions().CPlusPlus0x) { 9401 // C++03 [class.friend]p2: 9402 // An elaborated-type-specifier shall be used in a friend declaration 9403 // for a class.* 9404 // 9405 // * The class-key of the elaborated-type-specifier is required. 9406 if (!ActiveTemplateInstantiations.empty()) { 9407 // Do not complain about the form of friend template types during 9408 // template instantiation; we will already have complained when the 9409 // template was declared. 9410 } else if (!T->isElaboratedTypeSpecifier()) { 9411 // If we evaluated the type to a record type, suggest putting 9412 // a tag in front. 9413 if (const RecordType *RT = T->getAs<RecordType>()) { 9414 RecordDecl *RD = RT->getDecl(); 9415 9416 std::string InsertionText = std::string(" ") + RD->getKindName(); 9417 9418 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type) 9419 << (unsigned) RD->getTagKind() 9420 << T 9421 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 9422 InsertionText); 9423 } else { 9424 Diag(FriendLoc, diag::ext_nonclass_type_friend) 9425 << T 9426 << SourceRange(FriendLoc, TypeRange.getEnd()); 9427 } 9428 } else if (T->getAs<EnumType>()) { 9429 Diag(FriendLoc, diag::ext_enum_friend) 9430 << T 9431 << SourceRange(FriendLoc, TypeRange.getEnd()); 9432 } 9433 } 9434 9435 // C++0x [class.friend]p3: 9436 // If the type specifier in a friend declaration designates a (possibly 9437 // cv-qualified) class type, that class is declared as a friend; otherwise, 9438 // the friend declaration is ignored. 9439 9440 // FIXME: C++0x has some syntactic restrictions on friend type declarations 9441 // in [class.friend]p3 that we do not implement. 9442 9443 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc); 9444} 9445 9446/// Handle a friend tag declaration where the scope specifier was 9447/// templated. 9448Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 9449 unsigned TagSpec, SourceLocation TagLoc, 9450 CXXScopeSpec &SS, 9451 IdentifierInfo *Name, SourceLocation NameLoc, 9452 AttributeList *Attr, 9453 MultiTemplateParamsArg TempParamLists) { 9454 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 9455 9456 bool isExplicitSpecialization = false; 9457 bool Invalid = false; 9458 9459 if (TemplateParameterList *TemplateParams 9460 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, 9461 TempParamLists.get(), 9462 TempParamLists.size(), 9463 /*friend*/ true, 9464 isExplicitSpecialization, 9465 Invalid)) { 9466 if (TemplateParams->size() > 0) { 9467 // This is a declaration of a class template. 9468 if (Invalid) 9469 return 0; 9470 9471 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 9472 SS, Name, NameLoc, Attr, 9473 TemplateParams, AS_public, 9474 TempParamLists.size() - 1, 9475 (TemplateParameterList**) TempParamLists.release()).take(); 9476 } else { 9477 // The "template<>" header is extraneous. 9478 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 9479 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 9480 isExplicitSpecialization = true; 9481 } 9482 } 9483 9484 if (Invalid) return 0; 9485 9486 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 9487 9488 bool isAllExplicitSpecializations = true; 9489 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 9490 if (TempParamLists.get()[I]->size()) { 9491 isAllExplicitSpecializations = false; 9492 break; 9493 } 9494 } 9495 9496 // FIXME: don't ignore attributes. 9497 9498 // If it's explicit specializations all the way down, just forget 9499 // about the template header and build an appropriate non-templated 9500 // friend. TODO: for source fidelity, remember the headers. 9501 if (isAllExplicitSpecializations) { 9502 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9503 ElaboratedTypeKeyword Keyword 9504 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 9505 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 9506 *Name, NameLoc); 9507 if (T.isNull()) 9508 return 0; 9509 9510 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 9511 if (isa<DependentNameType>(T)) { 9512 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 9513 TL.setKeywordLoc(TagLoc); 9514 TL.setQualifierLoc(QualifierLoc); 9515 TL.setNameLoc(NameLoc); 9516 } else { 9517 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 9518 TL.setKeywordLoc(TagLoc); 9519 TL.setQualifierLoc(QualifierLoc); 9520 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc); 9521 } 9522 9523 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 9524 TSI, FriendLoc); 9525 Friend->setAccess(AS_public); 9526 CurContext->addDecl(Friend); 9527 return Friend; 9528 } 9529 9530 // Handle the case of a templated-scope friend class. e.g. 9531 // template <class T> class A<T>::B; 9532 // FIXME: we don't support these right now. 9533 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 9534 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 9535 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 9536 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 9537 TL.setKeywordLoc(TagLoc); 9538 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 9539 TL.setNameLoc(NameLoc); 9540 9541 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 9542 TSI, FriendLoc); 9543 Friend->setAccess(AS_public); 9544 Friend->setUnsupportedFriend(true); 9545 CurContext->addDecl(Friend); 9546 return Friend; 9547} 9548 9549 9550/// Handle a friend type declaration. This works in tandem with 9551/// ActOnTag. 9552/// 9553/// Notes on friend class templates: 9554/// 9555/// We generally treat friend class declarations as if they were 9556/// declaring a class. So, for example, the elaborated type specifier 9557/// in a friend declaration is required to obey the restrictions of a 9558/// class-head (i.e. no typedefs in the scope chain), template 9559/// parameters are required to match up with simple template-ids, &c. 9560/// However, unlike when declaring a template specialization, it's 9561/// okay to refer to a template specialization without an empty 9562/// template parameter declaration, e.g. 9563/// friend class A<T>::B<unsigned>; 9564/// We permit this as a special case; if there are any template 9565/// parameters present at all, require proper matching, i.e. 9566/// template <> template <class T> friend class A<int>::B; 9567Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 9568 MultiTemplateParamsArg TempParams) { 9569 SourceLocation Loc = DS.getSourceRange().getBegin(); 9570 9571 assert(DS.isFriendSpecified()); 9572 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 9573 9574 // Try to convert the decl specifier to a type. This works for 9575 // friend templates because ActOnTag never produces a ClassTemplateDecl 9576 // for a TUK_Friend. 9577 Declarator TheDeclarator(DS, Declarator::MemberContext); 9578 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 9579 QualType T = TSI->getType(); 9580 if (TheDeclarator.isInvalidType()) 9581 return 0; 9582 9583 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 9584 return 0; 9585 9586 // This is definitely an error in C++98. It's probably meant to 9587 // be forbidden in C++0x, too, but the specification is just 9588 // poorly written. 9589 // 9590 // The problem is with declarations like the following: 9591 // template <T> friend A<T>::foo; 9592 // where deciding whether a class C is a friend or not now hinges 9593 // on whether there exists an instantiation of A that causes 9594 // 'foo' to equal C. There are restrictions on class-heads 9595 // (which we declare (by fiat) elaborated friend declarations to 9596 // be) that makes this tractable. 9597 // 9598 // FIXME: handle "template <> friend class A<T>;", which 9599 // is possibly well-formed? Who even knows? 9600 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 9601 Diag(Loc, diag::err_tagless_friend_type_template) 9602 << DS.getSourceRange(); 9603 return 0; 9604 } 9605 9606 // C++98 [class.friend]p1: A friend of a class is a function 9607 // or class that is not a member of the class . . . 9608 // This is fixed in DR77, which just barely didn't make the C++03 9609 // deadline. It's also a very silly restriction that seriously 9610 // affects inner classes and which nobody else seems to implement; 9611 // thus we never diagnose it, not even in -pedantic. 9612 // 9613 // But note that we could warn about it: it's always useless to 9614 // friend one of your own members (it's not, however, worthless to 9615 // friend a member of an arbitrary specialization of your template). 9616 9617 Decl *D; 9618 if (unsigned NumTempParamLists = TempParams.size()) 9619 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 9620 NumTempParamLists, 9621 TempParams.release(), 9622 TSI, 9623 DS.getFriendSpecLoc()); 9624 else 9625 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI); 9626 9627 if (!D) 9628 return 0; 9629 9630 D->setAccess(AS_public); 9631 CurContext->addDecl(D); 9632 9633 return D; 9634} 9635 9636Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition, 9637 MultiTemplateParamsArg TemplateParams) { 9638 const DeclSpec &DS = D.getDeclSpec(); 9639 9640 assert(DS.isFriendSpecified()); 9641 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 9642 9643 SourceLocation Loc = D.getIdentifierLoc(); 9644 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9645 QualType T = TInfo->getType(); 9646 9647 // C++ [class.friend]p1 9648 // A friend of a class is a function or class.... 9649 // Note that this sees through typedefs, which is intended. 9650 // It *doesn't* see through dependent types, which is correct 9651 // according to [temp.arg.type]p3: 9652 // If a declaration acquires a function type through a 9653 // type dependent on a template-parameter and this causes 9654 // a declaration that does not use the syntactic form of a 9655 // function declarator to have a function type, the program 9656 // is ill-formed. 9657 if (!T->isFunctionType()) { 9658 Diag(Loc, diag::err_unexpected_friend); 9659 9660 // It might be worthwhile to try to recover by creating an 9661 // appropriate declaration. 9662 return 0; 9663 } 9664 9665 // C++ [namespace.memdef]p3 9666 // - If a friend declaration in a non-local class first declares a 9667 // class or function, the friend class or function is a member 9668 // of the innermost enclosing namespace. 9669 // - The name of the friend is not found by simple name lookup 9670 // until a matching declaration is provided in that namespace 9671 // scope (either before or after the class declaration granting 9672 // friendship). 9673 // - If a friend function is called, its name may be found by the 9674 // name lookup that considers functions from namespaces and 9675 // classes associated with the types of the function arguments. 9676 // - When looking for a prior declaration of a class or a function 9677 // declared as a friend, scopes outside the innermost enclosing 9678 // namespace scope are not considered. 9679 9680 CXXScopeSpec &SS = D.getCXXScopeSpec(); 9681 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9682 DeclarationName Name = NameInfo.getName(); 9683 assert(Name); 9684 9685 // Check for unexpanded parameter packs. 9686 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 9687 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 9688 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 9689 return 0; 9690 9691 // The context we found the declaration in, or in which we should 9692 // create the declaration. 9693 DeclContext *DC; 9694 Scope *DCScope = S; 9695 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 9696 ForRedeclaration); 9697 9698 // FIXME: there are different rules in local classes 9699 9700 // There are four cases here. 9701 // - There's no scope specifier, in which case we just go to the 9702 // appropriate scope and look for a function or function template 9703 // there as appropriate. 9704 // Recover from invalid scope qualifiers as if they just weren't there. 9705 if (SS.isInvalid() || !SS.isSet()) { 9706 // C++0x [namespace.memdef]p3: 9707 // If the name in a friend declaration is neither qualified nor 9708 // a template-id and the declaration is a function or an 9709 // elaborated-type-specifier, the lookup to determine whether 9710 // the entity has been previously declared shall not consider 9711 // any scopes outside the innermost enclosing namespace. 9712 // C++0x [class.friend]p11: 9713 // If a friend declaration appears in a local class and the name 9714 // specified is an unqualified name, a prior declaration is 9715 // looked up without considering scopes that are outside the 9716 // innermost enclosing non-class scope. For a friend function 9717 // declaration, if there is no prior declaration, the program is 9718 // ill-formed. 9719 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 9720 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 9721 9722 // Find the appropriate context according to the above. 9723 DC = CurContext; 9724 while (true) { 9725 // Skip class contexts. If someone can cite chapter and verse 9726 // for this behavior, that would be nice --- it's what GCC and 9727 // EDG do, and it seems like a reasonable intent, but the spec 9728 // really only says that checks for unqualified existing 9729 // declarations should stop at the nearest enclosing namespace, 9730 // not that they should only consider the nearest enclosing 9731 // namespace. 9732 while (DC->isRecord()) 9733 DC = DC->getParent(); 9734 9735 LookupQualifiedName(Previous, DC); 9736 9737 // TODO: decide what we think about using declarations. 9738 if (isLocal || !Previous.empty()) 9739 break; 9740 9741 if (isTemplateId) { 9742 if (isa<TranslationUnitDecl>(DC)) break; 9743 } else { 9744 if (DC->isFileContext()) break; 9745 } 9746 DC = DC->getParent(); 9747 } 9748 9749 // C++ [class.friend]p1: A friend of a class is a function or 9750 // class that is not a member of the class . . . 9751 // C++0x changes this for both friend types and functions. 9752 // Most C++ 98 compilers do seem to give an error here, so 9753 // we do, too. 9754 if (!Previous.empty() && DC->Equals(CurContext) 9755 && !getLangOptions().CPlusPlus0x) 9756 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 9757 9758 DCScope = getScopeForDeclContext(S, DC); 9759 9760 // - There's a non-dependent scope specifier, in which case we 9761 // compute it and do a previous lookup there for a function 9762 // or function template. 9763 } else if (!SS.getScopeRep()->isDependent()) { 9764 DC = computeDeclContext(SS); 9765 if (!DC) return 0; 9766 9767 if (RequireCompleteDeclContext(SS, DC)) return 0; 9768 9769 LookupQualifiedName(Previous, DC); 9770 9771 // Ignore things found implicitly in the wrong scope. 9772 // TODO: better diagnostics for this case. Suggesting the right 9773 // qualified scope would be nice... 9774 LookupResult::Filter F = Previous.makeFilter(); 9775 while (F.hasNext()) { 9776 NamedDecl *D = F.next(); 9777 if (!DC->InEnclosingNamespaceSetOf( 9778 D->getDeclContext()->getRedeclContext())) 9779 F.erase(); 9780 } 9781 F.done(); 9782 9783 if (Previous.empty()) { 9784 D.setInvalidType(); 9785 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 9786 return 0; 9787 } 9788 9789 // C++ [class.friend]p1: A friend of a class is a function or 9790 // class that is not a member of the class . . . 9791 if (DC->Equals(CurContext)) 9792 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 9793 9794 // - There's a scope specifier that does not match any template 9795 // parameter lists, in which case we use some arbitrary context, 9796 // create a method or method template, and wait for instantiation. 9797 // - There's a scope specifier that does match some template 9798 // parameter lists, which we don't handle right now. 9799 } else { 9800 DC = CurContext; 9801 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 9802 } 9803 9804 if (!DC->isRecord()) { 9805 // This implies that it has to be an operator or function. 9806 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 9807 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 9808 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 9809 Diag(Loc, diag::err_introducing_special_friend) << 9810 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 9811 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 9812 return 0; 9813 } 9814 } 9815 9816 bool Redeclaration = false; 9817 bool AddToScope = true; 9818 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous, 9819 move(TemplateParams), 9820 IsDefinition, 9821 Redeclaration, AddToScope); 9822 if (!ND) return 0; 9823 9824 assert(ND->getDeclContext() == DC); 9825 assert(ND->getLexicalDeclContext() == CurContext); 9826 9827 // Add the function declaration to the appropriate lookup tables, 9828 // adjusting the redeclarations list as necessary. We don't 9829 // want to do this yet if the friending class is dependent. 9830 // 9831 // Also update the scope-based lookup if the target context's 9832 // lookup context is in lexical scope. 9833 if (!CurContext->isDependentContext()) { 9834 DC = DC->getRedeclContext(); 9835 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 9836 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 9837 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 9838 } 9839 9840 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 9841 D.getIdentifierLoc(), ND, 9842 DS.getFriendSpecLoc()); 9843 FrD->setAccess(AS_public); 9844 CurContext->addDecl(FrD); 9845 9846 if (ND->isInvalidDecl()) 9847 FrD->setInvalidDecl(); 9848 else { 9849 FunctionDecl *FD; 9850 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 9851 FD = FTD->getTemplatedDecl(); 9852 else 9853 FD = cast<FunctionDecl>(ND); 9854 9855 // Mark templated-scope function declarations as unsupported. 9856 if (FD->getNumTemplateParameterLists()) 9857 FrD->setUnsupportedFriend(true); 9858 } 9859 9860 return ND; 9861} 9862 9863void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 9864 AdjustDeclIfTemplate(Dcl); 9865 9866 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 9867 if (!Fn) { 9868 Diag(DelLoc, diag::err_deleted_non_function); 9869 return; 9870 } 9871 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 9872 Diag(DelLoc, diag::err_deleted_decl_not_first); 9873 Diag(Prev->getLocation(), diag::note_previous_declaration); 9874 // If the declaration wasn't the first, we delete the function anyway for 9875 // recovery. 9876 } 9877 Fn->setDeletedAsWritten(); 9878} 9879 9880void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 9881 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl); 9882 9883 if (MD) { 9884 if (MD->getParent()->isDependentType()) { 9885 MD->setDefaulted(); 9886 MD->setExplicitlyDefaulted(); 9887 return; 9888 } 9889 9890 CXXSpecialMember Member = getSpecialMember(MD); 9891 if (Member == CXXInvalid) { 9892 Diag(DefaultLoc, diag::err_default_special_members); 9893 return; 9894 } 9895 9896 MD->setDefaulted(); 9897 MD->setExplicitlyDefaulted(); 9898 9899 // If this definition appears within the record, do the checking when 9900 // the record is complete. 9901 const FunctionDecl *Primary = MD; 9902 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate) 9903 // Find the uninstantiated declaration that actually had the '= default' 9904 // on it. 9905 MD->getTemplateInstantiationPattern()->isDefined(Primary); 9906 9907 if (Primary == Primary->getCanonicalDecl()) 9908 return; 9909 9910 switch (Member) { 9911 case CXXDefaultConstructor: { 9912 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 9913 CheckExplicitlyDefaultedDefaultConstructor(CD); 9914 if (!CD->isInvalidDecl()) 9915 DefineImplicitDefaultConstructor(DefaultLoc, CD); 9916 break; 9917 } 9918 9919 case CXXCopyConstructor: { 9920 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 9921 CheckExplicitlyDefaultedCopyConstructor(CD); 9922 if (!CD->isInvalidDecl()) 9923 DefineImplicitCopyConstructor(DefaultLoc, CD); 9924 break; 9925 } 9926 9927 case CXXCopyAssignment: { 9928 CheckExplicitlyDefaultedCopyAssignment(MD); 9929 if (!MD->isInvalidDecl()) 9930 DefineImplicitCopyAssignment(DefaultLoc, MD); 9931 break; 9932 } 9933 9934 case CXXDestructor: { 9935 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 9936 CheckExplicitlyDefaultedDestructor(DD); 9937 if (!DD->isInvalidDecl()) 9938 DefineImplicitDestructor(DefaultLoc, DD); 9939 break; 9940 } 9941 9942 case CXXMoveConstructor: { 9943 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 9944 CheckExplicitlyDefaultedMoveConstructor(CD); 9945 if (!CD->isInvalidDecl()) 9946 DefineImplicitMoveConstructor(DefaultLoc, CD); 9947 break; 9948 } 9949 9950 case CXXMoveAssignment: { 9951 CheckExplicitlyDefaultedMoveAssignment(MD); 9952 if (!MD->isInvalidDecl()) 9953 DefineImplicitMoveAssignment(DefaultLoc, MD); 9954 break; 9955 } 9956 9957 case CXXInvalid: 9958 assert(false && "Invalid special member."); 9959 break; 9960 } 9961 } else { 9962 Diag(DefaultLoc, diag::err_default_special_members); 9963 } 9964} 9965 9966static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 9967 for (Stmt::child_range CI = S->children(); CI; ++CI) { 9968 Stmt *SubStmt = *CI; 9969 if (!SubStmt) 9970 continue; 9971 if (isa<ReturnStmt>(SubStmt)) 9972 Self.Diag(SubStmt->getSourceRange().getBegin(), 9973 diag::err_return_in_constructor_handler); 9974 if (!isa<Expr>(SubStmt)) 9975 SearchForReturnInStmt(Self, SubStmt); 9976 } 9977} 9978 9979void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 9980 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 9981 CXXCatchStmt *Handler = TryBlock->getHandler(I); 9982 SearchForReturnInStmt(*this, Handler); 9983 } 9984} 9985 9986bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 9987 const CXXMethodDecl *Old) { 9988 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 9989 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 9990 9991 if (Context.hasSameType(NewTy, OldTy) || 9992 NewTy->isDependentType() || OldTy->isDependentType()) 9993 return false; 9994 9995 // Check if the return types are covariant 9996 QualType NewClassTy, OldClassTy; 9997 9998 /// Both types must be pointers or references to classes. 9999 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 10000 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 10001 NewClassTy = NewPT->getPointeeType(); 10002 OldClassTy = OldPT->getPointeeType(); 10003 } 10004 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 10005 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 10006 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 10007 NewClassTy = NewRT->getPointeeType(); 10008 OldClassTy = OldRT->getPointeeType(); 10009 } 10010 } 10011 } 10012 10013 // The return types aren't either both pointers or references to a class type. 10014 if (NewClassTy.isNull()) { 10015 Diag(New->getLocation(), 10016 diag::err_different_return_type_for_overriding_virtual_function) 10017 << New->getDeclName() << NewTy << OldTy; 10018 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10019 10020 return true; 10021 } 10022 10023 // C++ [class.virtual]p6: 10024 // If the return type of D::f differs from the return type of B::f, the 10025 // class type in the return type of D::f shall be complete at the point of 10026 // declaration of D::f or shall be the class type D. 10027 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 10028 if (!RT->isBeingDefined() && 10029 RequireCompleteType(New->getLocation(), NewClassTy, 10030 PDiag(diag::err_covariant_return_incomplete) 10031 << New->getDeclName())) 10032 return true; 10033 } 10034 10035 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 10036 // Check if the new class derives from the old class. 10037 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 10038 Diag(New->getLocation(), 10039 diag::err_covariant_return_not_derived) 10040 << New->getDeclName() << NewTy << OldTy; 10041 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10042 return true; 10043 } 10044 10045 // Check if we the conversion from derived to base is valid. 10046 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 10047 diag::err_covariant_return_inaccessible_base, 10048 diag::err_covariant_return_ambiguous_derived_to_base_conv, 10049 // FIXME: Should this point to the return type? 10050 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 10051 // FIXME: this note won't trigger for delayed access control 10052 // diagnostics, and it's impossible to get an undelayed error 10053 // here from access control during the original parse because 10054 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 10055 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10056 return true; 10057 } 10058 } 10059 10060 // The qualifiers of the return types must be the same. 10061 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 10062 Diag(New->getLocation(), 10063 diag::err_covariant_return_type_different_qualifications) 10064 << New->getDeclName() << NewTy << OldTy; 10065 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10066 return true; 10067 }; 10068 10069 10070 // The new class type must have the same or less qualifiers as the old type. 10071 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 10072 Diag(New->getLocation(), 10073 diag::err_covariant_return_type_class_type_more_qualified) 10074 << New->getDeclName() << NewTy << OldTy; 10075 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10076 return true; 10077 }; 10078 10079 return false; 10080} 10081 10082/// \brief Mark the given method pure. 10083/// 10084/// \param Method the method to be marked pure. 10085/// 10086/// \param InitRange the source range that covers the "0" initializer. 10087bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 10088 SourceLocation EndLoc = InitRange.getEnd(); 10089 if (EndLoc.isValid()) 10090 Method->setRangeEnd(EndLoc); 10091 10092 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 10093 Method->setPure(); 10094 return false; 10095 } 10096 10097 if (!Method->isInvalidDecl()) 10098 Diag(Method->getLocation(), diag::err_non_virtual_pure) 10099 << Method->getDeclName() << InitRange; 10100 return true; 10101} 10102 10103/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 10104/// an initializer for the out-of-line declaration 'Dcl'. The scope 10105/// is a fresh scope pushed for just this purpose. 10106/// 10107/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 10108/// static data member of class X, names should be looked up in the scope of 10109/// class X. 10110void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 10111 // If there is no declaration, there was an error parsing it. 10112 if (D == 0 || D->isInvalidDecl()) return; 10113 10114 // We should only get called for declarations with scope specifiers, like: 10115 // int foo::bar; 10116 assert(D->isOutOfLine()); 10117 EnterDeclaratorContext(S, D->getDeclContext()); 10118} 10119 10120/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 10121/// initializer for the out-of-line declaration 'D'. 10122void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 10123 // If there is no declaration, there was an error parsing it. 10124 if (D == 0 || D->isInvalidDecl()) return; 10125 10126 assert(D->isOutOfLine()); 10127 ExitDeclaratorContext(S); 10128} 10129 10130/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 10131/// C++ if/switch/while/for statement. 10132/// e.g: "if (int x = f()) {...}" 10133DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 10134 // C++ 6.4p2: 10135 // The declarator shall not specify a function or an array. 10136 // The type-specifier-seq shall not contain typedef and shall not declare a 10137 // new class or enumeration. 10138 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 10139 "Parser allowed 'typedef' as storage class of condition decl."); 10140 10141 Decl *Dcl = ActOnDeclarator(S, D); 10142 if (!Dcl) 10143 return true; 10144 10145 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 10146 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 10147 << D.getSourceRange(); 10148 return true; 10149 } 10150 10151 return Dcl; 10152} 10153 10154void Sema::LoadExternalVTableUses() { 10155 if (!ExternalSource) 10156 return; 10157 10158 SmallVector<ExternalVTableUse, 4> VTables; 10159 ExternalSource->ReadUsedVTables(VTables); 10160 SmallVector<VTableUse, 4> NewUses; 10161 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 10162 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 10163 = VTablesUsed.find(VTables[I].Record); 10164 // Even if a definition wasn't required before, it may be required now. 10165 if (Pos != VTablesUsed.end()) { 10166 if (!Pos->second && VTables[I].DefinitionRequired) 10167 Pos->second = true; 10168 continue; 10169 } 10170 10171 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 10172 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 10173 } 10174 10175 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 10176} 10177 10178void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 10179 bool DefinitionRequired) { 10180 // Ignore any vtable uses in unevaluated operands or for classes that do 10181 // not have a vtable. 10182 if (!Class->isDynamicClass() || Class->isDependentContext() || 10183 CurContext->isDependentContext() || 10184 ExprEvalContexts.back().Context == Unevaluated) 10185 return; 10186 10187 // Try to insert this class into the map. 10188 LoadExternalVTableUses(); 10189 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 10190 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 10191 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 10192 if (!Pos.second) { 10193 // If we already had an entry, check to see if we are promoting this vtable 10194 // to required a definition. If so, we need to reappend to the VTableUses 10195 // list, since we may have already processed the first entry. 10196 if (DefinitionRequired && !Pos.first->second) { 10197 Pos.first->second = true; 10198 } else { 10199 // Otherwise, we can early exit. 10200 return; 10201 } 10202 } 10203 10204 // Local classes need to have their virtual members marked 10205 // immediately. For all other classes, we mark their virtual members 10206 // at the end of the translation unit. 10207 if (Class->isLocalClass()) 10208 MarkVirtualMembersReferenced(Loc, Class); 10209 else 10210 VTableUses.push_back(std::make_pair(Class, Loc)); 10211} 10212 10213bool Sema::DefineUsedVTables() { 10214 LoadExternalVTableUses(); 10215 if (VTableUses.empty()) 10216 return false; 10217 10218 // Note: The VTableUses vector could grow as a result of marking 10219 // the members of a class as "used", so we check the size each 10220 // time through the loop and prefer indices (with are stable) to 10221 // iterators (which are not). 10222 bool DefinedAnything = false; 10223 for (unsigned I = 0; I != VTableUses.size(); ++I) { 10224 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 10225 if (!Class) 10226 continue; 10227 10228 SourceLocation Loc = VTableUses[I].second; 10229 10230 // If this class has a key function, but that key function is 10231 // defined in another translation unit, we don't need to emit the 10232 // vtable even though we're using it. 10233 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class); 10234 if (KeyFunction && !KeyFunction->hasBody()) { 10235 switch (KeyFunction->getTemplateSpecializationKind()) { 10236 case TSK_Undeclared: 10237 case TSK_ExplicitSpecialization: 10238 case TSK_ExplicitInstantiationDeclaration: 10239 // The key function is in another translation unit. 10240 continue; 10241 10242 case TSK_ExplicitInstantiationDefinition: 10243 case TSK_ImplicitInstantiation: 10244 // We will be instantiating the key function. 10245 break; 10246 } 10247 } else if (!KeyFunction) { 10248 // If we have a class with no key function that is the subject 10249 // of an explicit instantiation declaration, suppress the 10250 // vtable; it will live with the explicit instantiation 10251 // definition. 10252 bool IsExplicitInstantiationDeclaration 10253 = Class->getTemplateSpecializationKind() 10254 == TSK_ExplicitInstantiationDeclaration; 10255 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 10256 REnd = Class->redecls_end(); 10257 R != REnd; ++R) { 10258 TemplateSpecializationKind TSK 10259 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 10260 if (TSK == TSK_ExplicitInstantiationDeclaration) 10261 IsExplicitInstantiationDeclaration = true; 10262 else if (TSK == TSK_ExplicitInstantiationDefinition) { 10263 IsExplicitInstantiationDeclaration = false; 10264 break; 10265 } 10266 } 10267 10268 if (IsExplicitInstantiationDeclaration) 10269 continue; 10270 } 10271 10272 // Mark all of the virtual members of this class as referenced, so 10273 // that we can build a vtable. Then, tell the AST consumer that a 10274 // vtable for this class is required. 10275 DefinedAnything = true; 10276 MarkVirtualMembersReferenced(Loc, Class); 10277 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 10278 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 10279 10280 // Optionally warn if we're emitting a weak vtable. 10281 if (Class->getLinkage() == ExternalLinkage && 10282 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 10283 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined())) 10284 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; 10285 } 10286 } 10287 VTableUses.clear(); 10288 10289 return DefinedAnything; 10290} 10291 10292void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 10293 const CXXRecordDecl *RD) { 10294 for (CXXRecordDecl::method_iterator i = RD->method_begin(), 10295 e = RD->method_end(); i != e; ++i) { 10296 CXXMethodDecl *MD = *i; 10297 10298 // C++ [basic.def.odr]p2: 10299 // [...] A virtual member function is used if it is not pure. [...] 10300 if (MD->isVirtual() && !MD->isPure()) 10301 MarkDeclarationReferenced(Loc, MD); 10302 } 10303 10304 // Only classes that have virtual bases need a VTT. 10305 if (RD->getNumVBases() == 0) 10306 return; 10307 10308 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 10309 e = RD->bases_end(); i != e; ++i) { 10310 const CXXRecordDecl *Base = 10311 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 10312 if (Base->getNumVBases() == 0) 10313 continue; 10314 MarkVirtualMembersReferenced(Loc, Base); 10315 } 10316} 10317 10318/// SetIvarInitializers - This routine builds initialization ASTs for the 10319/// Objective-C implementation whose ivars need be initialized. 10320void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 10321 if (!getLangOptions().CPlusPlus) 10322 return; 10323 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 10324 SmallVector<ObjCIvarDecl*, 8> ivars; 10325 CollectIvarsToConstructOrDestruct(OID, ivars); 10326 if (ivars.empty()) 10327 return; 10328 SmallVector<CXXCtorInitializer*, 32> AllToInit; 10329 for (unsigned i = 0; i < ivars.size(); i++) { 10330 FieldDecl *Field = ivars[i]; 10331 if (Field->isInvalidDecl()) 10332 continue; 10333 10334 CXXCtorInitializer *Member; 10335 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 10336 InitializationKind InitKind = 10337 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 10338 10339 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 10340 ExprResult MemberInit = 10341 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 10342 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 10343 // Note, MemberInit could actually come back empty if no initialization 10344 // is required (e.g., because it would call a trivial default constructor) 10345 if (!MemberInit.get() || MemberInit.isInvalid()) 10346 continue; 10347 10348 Member = 10349 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 10350 SourceLocation(), 10351 MemberInit.takeAs<Expr>(), 10352 SourceLocation()); 10353 AllToInit.push_back(Member); 10354 10355 // Be sure that the destructor is accessible and is marked as referenced. 10356 if (const RecordType *RecordTy 10357 = Context.getBaseElementType(Field->getType()) 10358 ->getAs<RecordType>()) { 10359 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 10360 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 10361 MarkDeclarationReferenced(Field->getLocation(), Destructor); 10362 CheckDestructorAccess(Field->getLocation(), Destructor, 10363 PDiag(diag::err_access_dtor_ivar) 10364 << Context.getBaseElementType(Field->getType())); 10365 } 10366 } 10367 } 10368 ObjCImplementation->setIvarInitializers(Context, 10369 AllToInit.data(), AllToInit.size()); 10370 } 10371} 10372 10373static 10374void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 10375 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 10376 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 10377 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 10378 Sema &S) { 10379 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 10380 CE = Current.end(); 10381 if (Ctor->isInvalidDecl()) 10382 return; 10383 10384 const FunctionDecl *FNTarget = 0; 10385 CXXConstructorDecl *Target; 10386 10387 // We ignore the result here since if we don't have a body, Target will be 10388 // null below. 10389 (void)Ctor->getTargetConstructor()->hasBody(FNTarget); 10390 Target 10391= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget)); 10392 10393 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 10394 // Avoid dereferencing a null pointer here. 10395 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 10396 10397 if (!Current.insert(Canonical)) 10398 return; 10399 10400 // We know that beyond here, we aren't chaining into a cycle. 10401 if (!Target || !Target->isDelegatingConstructor() || 10402 Target->isInvalidDecl() || Valid.count(TCanonical)) { 10403 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 10404 Valid.insert(*CI); 10405 Current.clear(); 10406 // We've hit a cycle. 10407 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 10408 Current.count(TCanonical)) { 10409 // If we haven't diagnosed this cycle yet, do so now. 10410 if (!Invalid.count(TCanonical)) { 10411 S.Diag((*Ctor->init_begin())->getSourceLocation(), 10412 diag::warn_delegating_ctor_cycle) 10413 << Ctor; 10414 10415 // Don't add a note for a function delegating directo to itself. 10416 if (TCanonical != Canonical) 10417 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 10418 10419 CXXConstructorDecl *C = Target; 10420 while (C->getCanonicalDecl() != Canonical) { 10421 (void)C->getTargetConstructor()->hasBody(FNTarget); 10422 assert(FNTarget && "Ctor cycle through bodiless function"); 10423 10424 C 10425 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget)); 10426 S.Diag(C->getLocation(), diag::note_which_delegates_to); 10427 } 10428 } 10429 10430 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 10431 Invalid.insert(*CI); 10432 Current.clear(); 10433 } else { 10434 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 10435 } 10436} 10437 10438 10439void Sema::CheckDelegatingCtorCycles() { 10440 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 10441 10442 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 10443 CE = Current.end(); 10444 10445 for (DelegatingCtorDeclsType::iterator 10446 I = DelegatingCtorDecls.begin(ExternalSource), 10447 E = DelegatingCtorDecls.end(); 10448 I != E; ++I) { 10449 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 10450 } 10451 10452 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 10453 (*CI)->setInvalidDecl(); 10454} 10455