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