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