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