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