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