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