SemaDeclCXX.cpp revision 1f2e1a96bec2ba6418ae7f2d2b525a3575203b6a
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/EvaluatedExprVisitor.h" 27#include "clang/AST/ExprCXX.h" 28#include "clang/AST/RecordLayout.h" 29#include "clang/AST/RecursiveASTVisitor.h" 30#include "clang/AST/StmtVisitor.h" 31#include "clang/AST/TypeLoc.h" 32#include "clang/AST/TypeOrdering.h" 33#include "clang/Sema/DeclSpec.h" 34#include "clang/Sema/ParsedTemplate.h" 35#include "clang/Basic/PartialDiagnostic.h" 36#include "clang/Lex/Preprocessor.h" 37#include "llvm/ADT/SmallString.h" 38#include "llvm/ADT/STLExtras.h" 39#include <map> 40#include <set> 41 42using namespace clang; 43 44//===----------------------------------------------------------------------===// 45// CheckDefaultArgumentVisitor 46//===----------------------------------------------------------------------===// 47 48namespace { 49 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 50 /// the default argument of a parameter to determine whether it 51 /// contains any ill-formed subexpressions. For example, this will 52 /// diagnose the use of local variables or parameters within the 53 /// default argument expression. 54 class CheckDefaultArgumentVisitor 55 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 56 Expr *DefaultArg; 57 Sema *S; 58 59 public: 60 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 61 : DefaultArg(defarg), S(s) {} 62 63 bool VisitExpr(Expr *Node); 64 bool VisitDeclRefExpr(DeclRefExpr *DRE); 65 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 66 bool VisitLambdaExpr(LambdaExpr *Lambda); 67 }; 68 69 /// VisitExpr - Visit all of the children of this expression. 70 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 71 bool IsInvalid = false; 72 for (Stmt::child_range I = Node->children(); I; ++I) 73 IsInvalid |= Visit(*I); 74 return IsInvalid; 75 } 76 77 /// VisitDeclRefExpr - Visit a reference to a declaration, to 78 /// determine whether this declaration can be used in the default 79 /// argument expression. 80 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 81 NamedDecl *Decl = DRE->getDecl(); 82 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 83 // C++ [dcl.fct.default]p9 84 // Default arguments are evaluated each time the function is 85 // called. The order of evaluation of function arguments is 86 // unspecified. Consequently, parameters of a function shall not 87 // be used in default argument expressions, even if they are not 88 // evaluated. Parameters of a function declared before a default 89 // argument expression are in scope and can hide namespace and 90 // class member names. 91 return S->Diag(DRE->getLocStart(), 92 diag::err_param_default_argument_references_param) 93 << Param->getDeclName() << DefaultArg->getSourceRange(); 94 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 95 // C++ [dcl.fct.default]p7 96 // Local variables shall not be used in default argument 97 // expressions. 98 if (VDecl->isLocalVarDecl()) 99 return S->Diag(DRE->getLocStart(), 100 diag::err_param_default_argument_references_local) 101 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 102 } 103 104 return false; 105 } 106 107 /// VisitCXXThisExpr - Visit a C++ "this" expression. 108 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 109 // C++ [dcl.fct.default]p8: 110 // The keyword this shall not be used in a default argument of a 111 // member function. 112 return S->Diag(ThisE->getLocStart(), 113 diag::err_param_default_argument_references_this) 114 << ThisE->getSourceRange(); 115 } 116 117 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 118 // C++11 [expr.lambda.prim]p13: 119 // A lambda-expression appearing in a default argument shall not 120 // implicitly or explicitly capture any entity. 121 if (Lambda->capture_begin() == Lambda->capture_end()) 122 return false; 123 124 return S->Diag(Lambda->getLocStart(), 125 diag::err_lambda_capture_default_arg); 126 } 127} 128 129void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 130 CXXMethodDecl *Method) { 131 // If we have an MSAny spec already, don't bother. 132 if (!Method || ComputedEST == EST_MSAny) 133 return; 134 135 const FunctionProtoType *Proto 136 = Method->getType()->getAs<FunctionProtoType>(); 137 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 138 if (!Proto) 139 return; 140 141 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 142 143 // If this function can throw any exceptions, make a note of that. 144 if (EST == EST_MSAny || EST == EST_None) { 145 ClearExceptions(); 146 ComputedEST = EST; 147 return; 148 } 149 150 // FIXME: If the call to this decl is using any of its default arguments, we 151 // need to search them for potentially-throwing calls. 152 153 // If this function has a basic noexcept, it doesn't affect the outcome. 154 if (EST == EST_BasicNoexcept) 155 return; 156 157 // If we have a throw-all spec at this point, ignore the function. 158 if (ComputedEST == EST_None) 159 return; 160 161 // If we're still at noexcept(true) and there's a nothrow() callee, 162 // change to that specification. 163 if (EST == EST_DynamicNone) { 164 if (ComputedEST == EST_BasicNoexcept) 165 ComputedEST = EST_DynamicNone; 166 return; 167 } 168 169 // Check out noexcept specs. 170 if (EST == EST_ComputedNoexcept) { 171 FunctionProtoType::NoexceptResult NR = 172 Proto->getNoexceptSpec(Self->Context); 173 assert(NR != FunctionProtoType::NR_NoNoexcept && 174 "Must have noexcept result for EST_ComputedNoexcept."); 175 assert(NR != FunctionProtoType::NR_Dependent && 176 "Should not generate implicit declarations for dependent cases, " 177 "and don't know how to handle them anyway."); 178 179 // noexcept(false) -> no spec on the new function 180 if (NR == FunctionProtoType::NR_Throw) { 181 ClearExceptions(); 182 ComputedEST = EST_None; 183 } 184 // noexcept(true) won't change anything either. 185 return; 186 } 187 188 assert(EST == EST_Dynamic && "EST case not considered earlier."); 189 assert(ComputedEST != EST_None && 190 "Shouldn't collect exceptions when throw-all is guaranteed."); 191 ComputedEST = EST_Dynamic; 192 // Record the exceptions in this function's exception specification. 193 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 194 EEnd = Proto->exception_end(); 195 E != EEnd; ++E) 196 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E))) 197 Exceptions.push_back(*E); 198} 199 200void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 201 if (!E || ComputedEST == EST_MSAny) 202 return; 203 204 // FIXME: 205 // 206 // C++0x [except.spec]p14: 207 // [An] implicit exception-specification specifies the type-id T if and 208 // only if T is allowed by the exception-specification of a function directly 209 // invoked by f's implicit definition; f shall allow all exceptions if any 210 // function it directly invokes allows all exceptions, and f shall allow no 211 // exceptions if every function it directly invokes allows no exceptions. 212 // 213 // Note in particular that if an implicit exception-specification is generated 214 // for a function containing a throw-expression, that specification can still 215 // be noexcept(true). 216 // 217 // Note also that 'directly invoked' is not defined in the standard, and there 218 // is no indication that we should only consider potentially-evaluated calls. 219 // 220 // Ultimately we should implement the intent of the standard: the exception 221 // specification should be the set of exceptions which can be thrown by the 222 // implicit definition. For now, we assume that any non-nothrow expression can 223 // throw any exception. 224 225 if (Self->canThrow(E)) 226 ComputedEST = EST_None; 227} 228 229bool 230Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 231 SourceLocation EqualLoc) { 232 if (RequireCompleteType(Param->getLocation(), Param->getType(), 233 diag::err_typecheck_decl_incomplete_type)) { 234 Param->setInvalidDecl(); 235 return true; 236 } 237 238 // C++ [dcl.fct.default]p5 239 // A default argument expression is implicitly converted (clause 240 // 4) to the parameter type. The default argument expression has 241 // the same semantic constraints as the initializer expression in 242 // a declaration of a variable of the parameter type, using the 243 // copy-initialization semantics (8.5). 244 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 245 Param); 246 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 247 EqualLoc); 248 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 249 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 250 MultiExprArg(*this, &Arg, 1)); 251 if (Result.isInvalid()) 252 return true; 253 Arg = Result.takeAs<Expr>(); 254 255 CheckImplicitConversions(Arg, EqualLoc); 256 Arg = MaybeCreateExprWithCleanups(Arg); 257 258 // Okay: add the default argument to the parameter 259 Param->setDefaultArg(Arg); 260 261 // We have already instantiated this parameter; provide each of the 262 // instantiations with the uninstantiated default argument. 263 UnparsedDefaultArgInstantiationsMap::iterator InstPos 264 = UnparsedDefaultArgInstantiations.find(Param); 265 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 266 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 267 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 268 269 // We're done tracking this parameter's instantiations. 270 UnparsedDefaultArgInstantiations.erase(InstPos); 271 } 272 273 return false; 274} 275 276/// ActOnParamDefaultArgument - Check whether the default argument 277/// provided for a function parameter is well-formed. If so, attach it 278/// to the parameter declaration. 279void 280Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 281 Expr *DefaultArg) { 282 if (!param || !DefaultArg) 283 return; 284 285 ParmVarDecl *Param = cast<ParmVarDecl>(param); 286 UnparsedDefaultArgLocs.erase(Param); 287 288 // Default arguments are only permitted in C++ 289 if (!getLangOpts().CPlusPlus) { 290 Diag(EqualLoc, diag::err_param_default_argument) 291 << DefaultArg->getSourceRange(); 292 Param->setInvalidDecl(); 293 return; 294 } 295 296 // Check for unexpanded parameter packs. 297 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 298 Param->setInvalidDecl(); 299 return; 300 } 301 302 // Check that the default argument is well-formed 303 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 304 if (DefaultArgChecker.Visit(DefaultArg)) { 305 Param->setInvalidDecl(); 306 return; 307 } 308 309 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 310} 311 312/// ActOnParamUnparsedDefaultArgument - We've seen a default 313/// argument for a function parameter, but we can't parse it yet 314/// because we're inside a class definition. Note that this default 315/// argument will be parsed later. 316void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 317 SourceLocation EqualLoc, 318 SourceLocation ArgLoc) { 319 if (!param) 320 return; 321 322 ParmVarDecl *Param = cast<ParmVarDecl>(param); 323 if (Param) 324 Param->setUnparsedDefaultArg(); 325 326 UnparsedDefaultArgLocs[Param] = ArgLoc; 327} 328 329/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 330/// the default argument for the parameter param failed. 331void Sema::ActOnParamDefaultArgumentError(Decl *param) { 332 if (!param) 333 return; 334 335 ParmVarDecl *Param = cast<ParmVarDecl>(param); 336 337 Param->setInvalidDecl(); 338 339 UnparsedDefaultArgLocs.erase(Param); 340} 341 342/// CheckExtraCXXDefaultArguments - Check for any extra default 343/// arguments in the declarator, which is not a function declaration 344/// or definition and therefore is not permitted to have default 345/// arguments. This routine should be invoked for every declarator 346/// that is not a function declaration or definition. 347void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 348 // C++ [dcl.fct.default]p3 349 // A default argument expression shall be specified only in the 350 // parameter-declaration-clause of a function declaration or in a 351 // template-parameter (14.1). It shall not be specified for a 352 // parameter pack. If it is specified in a 353 // parameter-declaration-clause, it shall not occur within a 354 // declarator or abstract-declarator of a parameter-declaration. 355 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 356 DeclaratorChunk &chunk = D.getTypeObject(i); 357 if (chunk.Kind == DeclaratorChunk::Function) { 358 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 359 ParmVarDecl *Param = 360 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 361 if (Param->hasUnparsedDefaultArg()) { 362 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 363 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 364 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 365 delete Toks; 366 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 367 } else if (Param->getDefaultArg()) { 368 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 369 << Param->getDefaultArg()->getSourceRange(); 370 Param->setDefaultArg(0); 371 } 372 } 373 } 374 } 375} 376 377// MergeCXXFunctionDecl - Merge two declarations of the same C++ 378// function, once we already know that they have the same 379// type. Subroutine of MergeFunctionDecl. Returns true if there was an 380// error, false otherwise. 381bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 382 Scope *S) { 383 bool Invalid = false; 384 385 // C++ [dcl.fct.default]p4: 386 // For non-template functions, default arguments can be added in 387 // later declarations of a function in the same 388 // scope. Declarations in different scopes have completely 389 // distinct sets of default arguments. That is, declarations in 390 // inner scopes do not acquire default arguments from 391 // declarations in outer scopes, and vice versa. In a given 392 // function declaration, all parameters subsequent to a 393 // parameter with a default argument shall have default 394 // arguments supplied in this or previous declarations. A 395 // default argument shall not be redefined by a later 396 // declaration (not even to the same value). 397 // 398 // C++ [dcl.fct.default]p6: 399 // Except for member functions of class templates, the default arguments 400 // in a member function definition that appears outside of the class 401 // definition are added to the set of default arguments provided by the 402 // member function declaration in the class definition. 403 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 404 ParmVarDecl *OldParam = Old->getParamDecl(p); 405 ParmVarDecl *NewParam = New->getParamDecl(p); 406 407 bool OldParamHasDfl = OldParam->hasDefaultArg(); 408 bool NewParamHasDfl = NewParam->hasDefaultArg(); 409 410 NamedDecl *ND = Old; 411 if (S && !isDeclInScope(ND, New->getDeclContext(), S)) 412 // Ignore default parameters of old decl if they are not in 413 // the same scope. 414 OldParamHasDfl = false; 415 416 if (OldParamHasDfl && NewParamHasDfl) { 417 418 unsigned DiagDefaultParamID = 419 diag::err_param_default_argument_redefinition; 420 421 // MSVC accepts that default parameters be redefined for member functions 422 // of template class. The new default parameter's value is ignored. 423 Invalid = true; 424 if (getLangOpts().MicrosoftExt) { 425 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 426 if (MD && MD->getParent()->getDescribedClassTemplate()) { 427 // Merge the old default argument into the new parameter. 428 NewParam->setHasInheritedDefaultArg(); 429 if (OldParam->hasUninstantiatedDefaultArg()) 430 NewParam->setUninstantiatedDefaultArg( 431 OldParam->getUninstantiatedDefaultArg()); 432 else 433 NewParam->setDefaultArg(OldParam->getInit()); 434 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 435 Invalid = false; 436 } 437 } 438 439 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 440 // hint here. Alternatively, we could walk the type-source information 441 // for NewParam to find the last source location in the type... but it 442 // isn't worth the effort right now. This is the kind of test case that 443 // is hard to get right: 444 // int f(int); 445 // void g(int (*fp)(int) = f); 446 // void g(int (*fp)(int) = &f); 447 Diag(NewParam->getLocation(), DiagDefaultParamID) 448 << NewParam->getDefaultArgRange(); 449 450 // Look for the function declaration where the default argument was 451 // actually written, which may be a declaration prior to Old. 452 for (FunctionDecl *Older = Old->getPreviousDecl(); 453 Older; Older = Older->getPreviousDecl()) { 454 if (!Older->getParamDecl(p)->hasDefaultArg()) 455 break; 456 457 OldParam = Older->getParamDecl(p); 458 } 459 460 Diag(OldParam->getLocation(), diag::note_previous_definition) 461 << OldParam->getDefaultArgRange(); 462 } else if (OldParamHasDfl) { 463 // Merge the old default argument into the new parameter. 464 // It's important to use getInit() here; getDefaultArg() 465 // strips off any top-level ExprWithCleanups. 466 NewParam->setHasInheritedDefaultArg(); 467 if (OldParam->hasUninstantiatedDefaultArg()) 468 NewParam->setUninstantiatedDefaultArg( 469 OldParam->getUninstantiatedDefaultArg()); 470 else 471 NewParam->setDefaultArg(OldParam->getInit()); 472 } else if (NewParamHasDfl) { 473 if (New->getDescribedFunctionTemplate()) { 474 // Paragraph 4, quoted above, only applies to non-template functions. 475 Diag(NewParam->getLocation(), 476 diag::err_param_default_argument_template_redecl) 477 << NewParam->getDefaultArgRange(); 478 Diag(Old->getLocation(), diag::note_template_prev_declaration) 479 << false; 480 } else if (New->getTemplateSpecializationKind() 481 != TSK_ImplicitInstantiation && 482 New->getTemplateSpecializationKind() != TSK_Undeclared) { 483 // C++ [temp.expr.spec]p21: 484 // Default function arguments shall not be specified in a declaration 485 // or a definition for one of the following explicit specializations: 486 // - the explicit specialization of a function template; 487 // - the explicit specialization of a member function template; 488 // - the explicit specialization of a member function of a class 489 // template where the class template specialization to which the 490 // member function specialization belongs is implicitly 491 // instantiated. 492 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 493 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 494 << New->getDeclName() 495 << NewParam->getDefaultArgRange(); 496 } else if (New->getDeclContext()->isDependentContext()) { 497 // C++ [dcl.fct.default]p6 (DR217): 498 // Default arguments for a member function of a class template shall 499 // be specified on the initial declaration of the member function 500 // within the class template. 501 // 502 // Reading the tea leaves a bit in DR217 and its reference to DR205 503 // leads me to the conclusion that one cannot add default function 504 // arguments for an out-of-line definition of a member function of a 505 // dependent type. 506 int WhichKind = 2; 507 if (CXXRecordDecl *Record 508 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 509 if (Record->getDescribedClassTemplate()) 510 WhichKind = 0; 511 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 512 WhichKind = 1; 513 else 514 WhichKind = 2; 515 } 516 517 Diag(NewParam->getLocation(), 518 diag::err_param_default_argument_member_template_redecl) 519 << WhichKind 520 << NewParam->getDefaultArgRange(); 521 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) { 522 CXXSpecialMember NewSM = getSpecialMember(Ctor), 523 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old)); 524 if (NewSM != OldSM) { 525 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special) 526 << NewParam->getDefaultArgRange() << NewSM; 527 Diag(Old->getLocation(), diag::note_previous_declaration_special) 528 << OldSM; 529 } 530 } 531 } 532 } 533 534 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 535 // template has a constexpr specifier then all its declarations shall 536 // contain the constexpr specifier. 537 if (New->isConstexpr() != Old->isConstexpr()) { 538 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 539 << New << New->isConstexpr(); 540 Diag(Old->getLocation(), diag::note_previous_declaration); 541 Invalid = true; 542 } 543 544 if (CheckEquivalentExceptionSpec(Old, New)) 545 Invalid = true; 546 547 return Invalid; 548} 549 550/// \brief Merge the exception specifications of two variable declarations. 551/// 552/// This is called when there's a redeclaration of a VarDecl. The function 553/// checks if the redeclaration might have an exception specification and 554/// validates compatibility and merges the specs if necessary. 555void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 556 // Shortcut if exceptions are disabled. 557 if (!getLangOpts().CXXExceptions) 558 return; 559 560 assert(Context.hasSameType(New->getType(), Old->getType()) && 561 "Should only be called if types are otherwise the same."); 562 563 QualType NewType = New->getType(); 564 QualType OldType = Old->getType(); 565 566 // We're only interested in pointers and references to functions, as well 567 // as pointers to member functions. 568 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 569 NewType = R->getPointeeType(); 570 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 571 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 572 NewType = P->getPointeeType(); 573 OldType = OldType->getAs<PointerType>()->getPointeeType(); 574 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 575 NewType = M->getPointeeType(); 576 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 577 } 578 579 if (!NewType->isFunctionProtoType()) 580 return; 581 582 // There's lots of special cases for functions. For function pointers, system 583 // libraries are hopefully not as broken so that we don't need these 584 // workarounds. 585 if (CheckEquivalentExceptionSpec( 586 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 587 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 588 New->setInvalidDecl(); 589 } 590} 591 592/// CheckCXXDefaultArguments - Verify that the default arguments for a 593/// function declaration are well-formed according to C++ 594/// [dcl.fct.default]. 595void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 596 unsigned NumParams = FD->getNumParams(); 597 unsigned p; 598 599 bool IsLambda = FD->getOverloadedOperator() == OO_Call && 600 isa<CXXMethodDecl>(FD) && 601 cast<CXXMethodDecl>(FD)->getParent()->isLambda(); 602 603 // Find first parameter with a default argument 604 for (p = 0; p < NumParams; ++p) { 605 ParmVarDecl *Param = FD->getParamDecl(p); 606 if (Param->hasDefaultArg()) { 607 // C++11 [expr.prim.lambda]p5: 608 // [...] Default arguments (8.3.6) shall not be specified in the 609 // parameter-declaration-clause of a lambda-declarator. 610 // 611 // FIXME: Core issue 974 strikes this sentence, we only provide an 612 // extension warning. 613 if (IsLambda) 614 Diag(Param->getLocation(), diag::ext_lambda_default_arguments) 615 << Param->getDefaultArgRange(); 616 break; 617 } 618 } 619 620 // C++ [dcl.fct.default]p4: 621 // In a given function declaration, all parameters 622 // subsequent to a parameter with a default argument shall 623 // have default arguments supplied in this or previous 624 // declarations. A default argument shall not be redefined 625 // by a later declaration (not even to the same value). 626 unsigned LastMissingDefaultArg = 0; 627 for (; p < NumParams; ++p) { 628 ParmVarDecl *Param = FD->getParamDecl(p); 629 if (!Param->hasDefaultArg()) { 630 if (Param->isInvalidDecl()) 631 /* We already complained about this parameter. */; 632 else if (Param->getIdentifier()) 633 Diag(Param->getLocation(), 634 diag::err_param_default_argument_missing_name) 635 << Param->getIdentifier(); 636 else 637 Diag(Param->getLocation(), 638 diag::err_param_default_argument_missing); 639 640 LastMissingDefaultArg = p; 641 } 642 } 643 644 if (LastMissingDefaultArg > 0) { 645 // Some default arguments were missing. Clear out all of the 646 // default arguments up to (and including) the last missing 647 // default argument, so that we leave the function parameters 648 // in a semantically valid state. 649 for (p = 0; p <= LastMissingDefaultArg; ++p) { 650 ParmVarDecl *Param = FD->getParamDecl(p); 651 if (Param->hasDefaultArg()) { 652 Param->setDefaultArg(0); 653 } 654 } 655 } 656} 657 658// CheckConstexprParameterTypes - Check whether a function's parameter types 659// are all literal types. If so, return true. If not, produce a suitable 660// diagnostic and return false. 661static bool CheckConstexprParameterTypes(Sema &SemaRef, 662 const FunctionDecl *FD) { 663 unsigned ArgIndex = 0; 664 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 665 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 666 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 667 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 668 SourceLocation ParamLoc = PD->getLocation(); 669 if (!(*i)->isDependentType() && 670 SemaRef.RequireLiteralType(ParamLoc, *i, 671 diag::err_constexpr_non_literal_param, 672 ArgIndex+1, PD->getSourceRange(), 673 isa<CXXConstructorDecl>(FD))) 674 return false; 675 } 676 return true; 677} 678 679// CheckConstexprFunctionDecl - Check whether a function declaration satisfies 680// the requirements of a constexpr function definition or a constexpr 681// constructor definition. If so, return true. If not, produce appropriate 682// diagnostics and return false. 683// 684// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 685bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 686 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 687 if (MD && MD->isInstance()) { 688 // C++11 [dcl.constexpr]p4: 689 // The definition of a constexpr constructor shall satisfy the following 690 // constraints: 691 // - the class shall not have any virtual base classes; 692 const CXXRecordDecl *RD = MD->getParent(); 693 if (RD->getNumVBases()) { 694 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 695 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct() 696 << RD->getNumVBases(); 697 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 698 E = RD->vbases_end(); I != E; ++I) 699 Diag(I->getLocStart(), 700 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 701 return false; 702 } 703 } 704 705 if (!isa<CXXConstructorDecl>(NewFD)) { 706 // C++11 [dcl.constexpr]p3: 707 // The definition of a constexpr function shall satisfy the following 708 // constraints: 709 // - it shall not be virtual; 710 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 711 if (Method && Method->isVirtual()) { 712 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 713 714 // If it's not obvious why this function is virtual, find an overridden 715 // function which uses the 'virtual' keyword. 716 const CXXMethodDecl *WrittenVirtual = Method; 717 while (!WrittenVirtual->isVirtualAsWritten()) 718 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 719 if (WrittenVirtual != Method) 720 Diag(WrittenVirtual->getLocation(), 721 diag::note_overridden_virtual_function); 722 return false; 723 } 724 725 // - its return type shall be a literal type; 726 QualType RT = NewFD->getResultType(); 727 if (!RT->isDependentType() && 728 RequireLiteralType(NewFD->getLocation(), RT, 729 diag::err_constexpr_non_literal_return)) 730 return false; 731 } 732 733 // - each of its parameter types shall be a literal type; 734 if (!CheckConstexprParameterTypes(*this, NewFD)) 735 return false; 736 737 return true; 738} 739 740/// Check the given declaration statement is legal within a constexpr function 741/// body. C++0x [dcl.constexpr]p3,p4. 742/// 743/// \return true if the body is OK, false if we have diagnosed a problem. 744static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 745 DeclStmt *DS) { 746 // C++0x [dcl.constexpr]p3 and p4: 747 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 748 // contain only 749 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 750 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 751 switch ((*DclIt)->getKind()) { 752 case Decl::StaticAssert: 753 case Decl::Using: 754 case Decl::UsingShadow: 755 case Decl::UsingDirective: 756 case Decl::UnresolvedUsingTypename: 757 // - static_assert-declarations 758 // - using-declarations, 759 // - using-directives, 760 continue; 761 762 case Decl::Typedef: 763 case Decl::TypeAlias: { 764 // - typedef declarations and alias-declarations that do not define 765 // classes or enumerations, 766 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 767 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 768 // Don't allow variably-modified types in constexpr functions. 769 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 770 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 771 << TL.getSourceRange() << TL.getType() 772 << isa<CXXConstructorDecl>(Dcl); 773 return false; 774 } 775 continue; 776 } 777 778 case Decl::Enum: 779 case Decl::CXXRecord: 780 // As an extension, we allow the declaration (but not the definition) of 781 // classes and enumerations in all declarations, not just in typedef and 782 // alias declarations. 783 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) { 784 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition) 785 << isa<CXXConstructorDecl>(Dcl); 786 return false; 787 } 788 continue; 789 790 case Decl::Var: 791 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration) 792 << isa<CXXConstructorDecl>(Dcl); 793 return false; 794 795 default: 796 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 797 << isa<CXXConstructorDecl>(Dcl); 798 return false; 799 } 800 } 801 802 return true; 803} 804 805/// Check that the given field is initialized within a constexpr constructor. 806/// 807/// \param Dcl The constexpr constructor being checked. 808/// \param Field The field being checked. This may be a member of an anonymous 809/// struct or union nested within the class being checked. 810/// \param Inits All declarations, including anonymous struct/union members and 811/// indirect members, for which any initialization was provided. 812/// \param Diagnosed Set to true if an error is produced. 813static void CheckConstexprCtorInitializer(Sema &SemaRef, 814 const FunctionDecl *Dcl, 815 FieldDecl *Field, 816 llvm::SmallSet<Decl*, 16> &Inits, 817 bool &Diagnosed) { 818 if (Field->isUnnamedBitfield()) 819 return; 820 821 if (Field->isAnonymousStructOrUnion() && 822 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 823 return; 824 825 if (!Inits.count(Field)) { 826 if (!Diagnosed) { 827 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 828 Diagnosed = true; 829 } 830 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 831 } else if (Field->isAnonymousStructOrUnion()) { 832 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 833 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 834 I != E; ++I) 835 // If an anonymous union contains an anonymous struct of which any member 836 // is initialized, all members must be initialized. 837 if (!RD->isUnion() || Inits.count(*I)) 838 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 839 } 840} 841 842/// Check the body for the given constexpr function declaration only contains 843/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 844/// 845/// \return true if the body is OK, false if we have diagnosed a problem. 846bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 847 if (isa<CXXTryStmt>(Body)) { 848 // C++11 [dcl.constexpr]p3: 849 // The definition of a constexpr function shall satisfy the following 850 // constraints: [...] 851 // - its function-body shall be = delete, = default, or a 852 // compound-statement 853 // 854 // C++11 [dcl.constexpr]p4: 855 // In the definition of a constexpr constructor, [...] 856 // - its function-body shall not be a function-try-block; 857 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 858 << isa<CXXConstructorDecl>(Dcl); 859 return false; 860 } 861 862 // - its function-body shall be [...] a compound-statement that contains only 863 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 864 865 llvm::SmallVector<SourceLocation, 4> ReturnStmts; 866 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 867 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 868 switch ((*BodyIt)->getStmtClass()) { 869 case Stmt::NullStmtClass: 870 // - null statements, 871 continue; 872 873 case Stmt::DeclStmtClass: 874 // - static_assert-declarations 875 // - using-declarations, 876 // - using-directives, 877 // - typedef declarations and alias-declarations that do not define 878 // classes or enumerations, 879 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt))) 880 return false; 881 continue; 882 883 case Stmt::ReturnStmtClass: 884 // - and exactly one return statement; 885 if (isa<CXXConstructorDecl>(Dcl)) 886 break; 887 888 ReturnStmts.push_back((*BodyIt)->getLocStart()); 889 continue; 890 891 default: 892 break; 893 } 894 895 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt) 896 << isa<CXXConstructorDecl>(Dcl); 897 return false; 898 } 899 900 if (const CXXConstructorDecl *Constructor 901 = dyn_cast<CXXConstructorDecl>(Dcl)) { 902 const CXXRecordDecl *RD = Constructor->getParent(); 903 // DR1359: 904 // - every non-variant non-static data member and base class sub-object 905 // shall be initialized; 906 // - if the class is a non-empty union, or for each non-empty anonymous 907 // union member of a non-union class, exactly one non-static data member 908 // shall be initialized; 909 if (RD->isUnion()) { 910 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 911 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 912 return false; 913 } 914 } else if (!Constructor->isDependentContext() && 915 !Constructor->isDelegatingConstructor()) { 916 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 917 918 // Skip detailed checking if we have enough initializers, and we would 919 // allow at most one initializer per member. 920 bool AnyAnonStructUnionMembers = false; 921 unsigned Fields = 0; 922 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 923 E = RD->field_end(); I != E; ++I, ++Fields) { 924 if (I->isAnonymousStructOrUnion()) { 925 AnyAnonStructUnionMembers = true; 926 break; 927 } 928 } 929 if (AnyAnonStructUnionMembers || 930 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 931 // Check initialization of non-static data members. Base classes are 932 // always initialized so do not need to be checked. Dependent bases 933 // might not have initializers in the member initializer list. 934 llvm::SmallSet<Decl*, 16> Inits; 935 for (CXXConstructorDecl::init_const_iterator 936 I = Constructor->init_begin(), E = Constructor->init_end(); 937 I != E; ++I) { 938 if (FieldDecl *FD = (*I)->getMember()) 939 Inits.insert(FD); 940 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 941 Inits.insert(ID->chain_begin(), ID->chain_end()); 942 } 943 944 bool Diagnosed = false; 945 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 946 E = RD->field_end(); I != E; ++I) 947 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 948 if (Diagnosed) 949 return false; 950 } 951 } 952 } else { 953 if (ReturnStmts.empty()) { 954 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return); 955 return false; 956 } 957 if (ReturnStmts.size() > 1) { 958 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return); 959 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 960 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 961 return false; 962 } 963 } 964 965 // C++11 [dcl.constexpr]p5: 966 // if no function argument values exist such that the function invocation 967 // substitution would produce a constant expression, the program is 968 // ill-formed; no diagnostic required. 969 // C++11 [dcl.constexpr]p3: 970 // - every constructor call and implicit conversion used in initializing the 971 // return value shall be one of those allowed in a constant expression. 972 // C++11 [dcl.constexpr]p4: 973 // - every constructor involved in initializing non-static data members and 974 // base class sub-objects shall be a constexpr constructor. 975 llvm::SmallVector<PartialDiagnosticAt, 8> Diags; 976 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 977 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr) 978 << isa<CXXConstructorDecl>(Dcl); 979 for (size_t I = 0, N = Diags.size(); I != N; ++I) 980 Diag(Diags[I].first, Diags[I].second); 981 return false; 982 } 983 984 return true; 985} 986 987/// isCurrentClassName - Determine whether the identifier II is the 988/// name of the class type currently being defined. In the case of 989/// nested classes, this will only return true if II is the name of 990/// the innermost class. 991bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 992 const CXXScopeSpec *SS) { 993 assert(getLangOpts().CPlusPlus && "No class names in C!"); 994 995 CXXRecordDecl *CurDecl; 996 if (SS && SS->isSet() && !SS->isInvalid()) { 997 DeclContext *DC = computeDeclContext(*SS, true); 998 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 999 } else 1000 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1001 1002 if (CurDecl && CurDecl->getIdentifier()) 1003 return &II == CurDecl->getIdentifier(); 1004 else 1005 return false; 1006} 1007 1008/// \brief Check the validity of a C++ base class specifier. 1009/// 1010/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1011/// and returns NULL otherwise. 1012CXXBaseSpecifier * 1013Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1014 SourceRange SpecifierRange, 1015 bool Virtual, AccessSpecifier Access, 1016 TypeSourceInfo *TInfo, 1017 SourceLocation EllipsisLoc) { 1018 QualType BaseType = TInfo->getType(); 1019 1020 // C++ [class.union]p1: 1021 // A union shall not have base classes. 1022 if (Class->isUnion()) { 1023 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1024 << SpecifierRange; 1025 return 0; 1026 } 1027 1028 if (EllipsisLoc.isValid() && 1029 !TInfo->getType()->containsUnexpandedParameterPack()) { 1030 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1031 << TInfo->getTypeLoc().getSourceRange(); 1032 EllipsisLoc = SourceLocation(); 1033 } 1034 1035 if (BaseType->isDependentType()) 1036 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1037 Class->getTagKind() == TTK_Class, 1038 Access, TInfo, EllipsisLoc); 1039 1040 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1041 1042 // Base specifiers must be record types. 1043 if (!BaseType->isRecordType()) { 1044 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1045 return 0; 1046 } 1047 1048 // C++ [class.union]p1: 1049 // A union shall not be used as a base class. 1050 if (BaseType->isUnionType()) { 1051 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1052 return 0; 1053 } 1054 1055 // C++ [class.derived]p2: 1056 // The class-name in a base-specifier shall not be an incompletely 1057 // defined class. 1058 if (RequireCompleteType(BaseLoc, BaseType, 1059 diag::err_incomplete_base_class, SpecifierRange)) { 1060 Class->setInvalidDecl(); 1061 return 0; 1062 } 1063 1064 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1065 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1066 assert(BaseDecl && "Record type has no declaration"); 1067 BaseDecl = BaseDecl->getDefinition(); 1068 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1069 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1070 assert(CXXBaseDecl && "Base type is not a C++ type"); 1071 1072 // C++ [class]p3: 1073 // If a class is marked final and it appears as a base-type-specifier in 1074 // base-clause, the program is ill-formed. 1075 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 1076 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1077 << CXXBaseDecl->getDeclName(); 1078 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1079 << CXXBaseDecl->getDeclName(); 1080 return 0; 1081 } 1082 1083 if (BaseDecl->isInvalidDecl()) 1084 Class->setInvalidDecl(); 1085 1086 // Create the base specifier. 1087 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1088 Class->getTagKind() == TTK_Class, 1089 Access, TInfo, EllipsisLoc); 1090} 1091 1092/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1093/// one entry in the base class list of a class specifier, for 1094/// example: 1095/// class foo : public bar, virtual private baz { 1096/// 'public bar' and 'virtual private baz' are each base-specifiers. 1097BaseResult 1098Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1099 bool Virtual, AccessSpecifier Access, 1100 ParsedType basetype, SourceLocation BaseLoc, 1101 SourceLocation EllipsisLoc) { 1102 if (!classdecl) 1103 return true; 1104 1105 AdjustDeclIfTemplate(classdecl); 1106 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1107 if (!Class) 1108 return true; 1109 1110 TypeSourceInfo *TInfo = 0; 1111 GetTypeFromParser(basetype, &TInfo); 1112 1113 if (EllipsisLoc.isInvalid() && 1114 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1115 UPPC_BaseType)) 1116 return true; 1117 1118 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1119 Virtual, Access, TInfo, 1120 EllipsisLoc)) 1121 return BaseSpec; 1122 else 1123 Class->setInvalidDecl(); 1124 1125 return true; 1126} 1127 1128/// \brief Performs the actual work of attaching the given base class 1129/// specifiers to a C++ class. 1130bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1131 unsigned NumBases) { 1132 if (NumBases == 0) 1133 return false; 1134 1135 // Used to keep track of which base types we have already seen, so 1136 // that we can properly diagnose redundant direct base types. Note 1137 // that the key is always the unqualified canonical type of the base 1138 // class. 1139 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1140 1141 // Copy non-redundant base specifiers into permanent storage. 1142 unsigned NumGoodBases = 0; 1143 bool Invalid = false; 1144 for (unsigned idx = 0; idx < NumBases; ++idx) { 1145 QualType NewBaseType 1146 = Context.getCanonicalType(Bases[idx]->getType()); 1147 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1148 1149 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1150 if (KnownBase) { 1151 // C++ [class.mi]p3: 1152 // A class shall not be specified as a direct base class of a 1153 // derived class more than once. 1154 Diag(Bases[idx]->getLocStart(), 1155 diag::err_duplicate_base_class) 1156 << KnownBase->getType() 1157 << Bases[idx]->getSourceRange(); 1158 1159 // Delete the duplicate base class specifier; we're going to 1160 // overwrite its pointer later. 1161 Context.Deallocate(Bases[idx]); 1162 1163 Invalid = true; 1164 } else { 1165 // Okay, add this new base class. 1166 KnownBase = Bases[idx]; 1167 Bases[NumGoodBases++] = Bases[idx]; 1168 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) 1169 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl())) 1170 if (RD->hasAttr<WeakAttr>()) 1171 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1172 } 1173 } 1174 1175 // Attach the remaining base class specifiers to the derived class. 1176 Class->setBases(Bases, NumGoodBases); 1177 1178 // Delete the remaining (good) base class specifiers, since their 1179 // data has been copied into the CXXRecordDecl. 1180 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1181 Context.Deallocate(Bases[idx]); 1182 1183 return Invalid; 1184} 1185 1186/// ActOnBaseSpecifiers - Attach the given base specifiers to the 1187/// class, after checking whether there are any duplicate base 1188/// classes. 1189void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1190 unsigned NumBases) { 1191 if (!ClassDecl || !Bases || !NumBases) 1192 return; 1193 1194 AdjustDeclIfTemplate(ClassDecl); 1195 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 1196 (CXXBaseSpecifier**)(Bases), NumBases); 1197} 1198 1199static CXXRecordDecl *GetClassForType(QualType T) { 1200 if (const RecordType *RT = T->getAs<RecordType>()) 1201 return cast<CXXRecordDecl>(RT->getDecl()); 1202 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 1203 return ICT->getDecl(); 1204 else 1205 return 0; 1206} 1207 1208/// \brief Determine whether the type \p Derived is a C++ class that is 1209/// derived from the type \p Base. 1210bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1211 if (!getLangOpts().CPlusPlus) 1212 return false; 1213 1214 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 1215 if (!DerivedRD) 1216 return false; 1217 1218 CXXRecordDecl *BaseRD = GetClassForType(Base); 1219 if (!BaseRD) 1220 return false; 1221 1222 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1223 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1224} 1225 1226/// \brief Determine whether the type \p Derived is a C++ class that is 1227/// derived from the type \p Base. 1228bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1229 if (!getLangOpts().CPlusPlus) 1230 return false; 1231 1232 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 1233 if (!DerivedRD) 1234 return false; 1235 1236 CXXRecordDecl *BaseRD = GetClassForType(Base); 1237 if (!BaseRD) 1238 return false; 1239 1240 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1241} 1242 1243void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1244 CXXCastPath &BasePathArray) { 1245 assert(BasePathArray.empty() && "Base path array must be empty!"); 1246 assert(Paths.isRecordingPaths() && "Must record paths!"); 1247 1248 const CXXBasePath &Path = Paths.front(); 1249 1250 // We first go backward and check if we have a virtual base. 1251 // FIXME: It would be better if CXXBasePath had the base specifier for 1252 // the nearest virtual base. 1253 unsigned Start = 0; 1254 for (unsigned I = Path.size(); I != 0; --I) { 1255 if (Path[I - 1].Base->isVirtual()) { 1256 Start = I - 1; 1257 break; 1258 } 1259 } 1260 1261 // Now add all bases. 1262 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1263 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1264} 1265 1266/// \brief Determine whether the given base path includes a virtual 1267/// base class. 1268bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1269 for (CXXCastPath::const_iterator B = BasePath.begin(), 1270 BEnd = BasePath.end(); 1271 B != BEnd; ++B) 1272 if ((*B)->isVirtual()) 1273 return true; 1274 1275 return false; 1276} 1277 1278/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1279/// conversion (where Derived and Base are class types) is 1280/// well-formed, meaning that the conversion is unambiguous (and 1281/// that all of the base classes are accessible). Returns true 1282/// and emits a diagnostic if the code is ill-formed, returns false 1283/// otherwise. Loc is the location where this routine should point to 1284/// if there is an error, and Range is the source range to highlight 1285/// if there is an error. 1286bool 1287Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1288 unsigned InaccessibleBaseID, 1289 unsigned AmbigiousBaseConvID, 1290 SourceLocation Loc, SourceRange Range, 1291 DeclarationName Name, 1292 CXXCastPath *BasePath) { 1293 // First, determine whether the path from Derived to Base is 1294 // ambiguous. This is slightly more expensive than checking whether 1295 // the Derived to Base conversion exists, because here we need to 1296 // explore multiple paths to determine if there is an ambiguity. 1297 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1298 /*DetectVirtual=*/false); 1299 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1300 assert(DerivationOkay && 1301 "Can only be used with a derived-to-base conversion"); 1302 (void)DerivationOkay; 1303 1304 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1305 if (InaccessibleBaseID) { 1306 // Check that the base class can be accessed. 1307 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1308 InaccessibleBaseID)) { 1309 case AR_inaccessible: 1310 return true; 1311 case AR_accessible: 1312 case AR_dependent: 1313 case AR_delayed: 1314 break; 1315 } 1316 } 1317 1318 // Build a base path if necessary. 1319 if (BasePath) 1320 BuildBasePathArray(Paths, *BasePath); 1321 return false; 1322 } 1323 1324 // We know that the derived-to-base conversion is ambiguous, and 1325 // we're going to produce a diagnostic. Perform the derived-to-base 1326 // search just one more time to compute all of the possible paths so 1327 // that we can print them out. This is more expensive than any of 1328 // the previous derived-to-base checks we've done, but at this point 1329 // performance isn't as much of an issue. 1330 Paths.clear(); 1331 Paths.setRecordingPaths(true); 1332 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1333 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1334 (void)StillOkay; 1335 1336 // Build up a textual representation of the ambiguous paths, e.g., 1337 // D -> B -> A, that will be used to illustrate the ambiguous 1338 // conversions in the diagnostic. We only print one of the paths 1339 // to each base class subobject. 1340 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1341 1342 Diag(Loc, AmbigiousBaseConvID) 1343 << Derived << Base << PathDisplayStr << Range << Name; 1344 return true; 1345} 1346 1347bool 1348Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1349 SourceLocation Loc, SourceRange Range, 1350 CXXCastPath *BasePath, 1351 bool IgnoreAccess) { 1352 return CheckDerivedToBaseConversion(Derived, Base, 1353 IgnoreAccess ? 0 1354 : diag::err_upcast_to_inaccessible_base, 1355 diag::err_ambiguous_derived_to_base_conv, 1356 Loc, Range, DeclarationName(), 1357 BasePath); 1358} 1359 1360 1361/// @brief Builds a string representing ambiguous paths from a 1362/// specific derived class to different subobjects of the same base 1363/// class. 1364/// 1365/// This function builds a string that can be used in error messages 1366/// to show the different paths that one can take through the 1367/// inheritance hierarchy to go from the derived class to different 1368/// subobjects of a base class. The result looks something like this: 1369/// @code 1370/// struct D -> struct B -> struct A 1371/// struct D -> struct C -> struct A 1372/// @endcode 1373std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1374 std::string PathDisplayStr; 1375 std::set<unsigned> DisplayedPaths; 1376 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1377 Path != Paths.end(); ++Path) { 1378 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1379 // We haven't displayed a path to this particular base 1380 // class subobject yet. 1381 PathDisplayStr += "\n "; 1382 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1383 for (CXXBasePath::const_iterator Element = Path->begin(); 1384 Element != Path->end(); ++Element) 1385 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1386 } 1387 } 1388 1389 return PathDisplayStr; 1390} 1391 1392//===----------------------------------------------------------------------===// 1393// C++ class member Handling 1394//===----------------------------------------------------------------------===// 1395 1396/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1397bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1398 SourceLocation ASLoc, 1399 SourceLocation ColonLoc, 1400 AttributeList *Attrs) { 1401 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1402 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1403 ASLoc, ColonLoc); 1404 CurContext->addHiddenDecl(ASDecl); 1405 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1406} 1407 1408/// CheckOverrideControl - Check C++11 override control semantics. 1409void Sema::CheckOverrideControl(Decl *D) { 1410 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1411 1412 // Do we know which functions this declaration might be overriding? 1413 bool OverridesAreKnown = !MD || 1414 (!MD->getParent()->hasAnyDependentBases() && 1415 !MD->getType()->isDependentType()); 1416 1417 if (!MD || !MD->isVirtual()) { 1418 if (OverridesAreKnown) { 1419 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1420 Diag(OA->getLocation(), 1421 diag::override_keyword_only_allowed_on_virtual_member_functions) 1422 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1423 D->dropAttr<OverrideAttr>(); 1424 } 1425 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1426 Diag(FA->getLocation(), 1427 diag::override_keyword_only_allowed_on_virtual_member_functions) 1428 << "final" << FixItHint::CreateRemoval(FA->getLocation()); 1429 D->dropAttr<FinalAttr>(); 1430 } 1431 } 1432 return; 1433 } 1434 1435 if (!OverridesAreKnown) 1436 return; 1437 1438 // C++11 [class.virtual]p5: 1439 // If a virtual function is marked with the virt-specifier override and 1440 // does not override a member function of a base class, the program is 1441 // ill-formed. 1442 bool HasOverriddenMethods = 1443 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1444 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1445 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1446 << MD->getDeclName(); 1447} 1448 1449/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1450/// function overrides a virtual member function marked 'final', according to 1451/// C++11 [class.virtual]p4. 1452bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1453 const CXXMethodDecl *Old) { 1454 if (!Old->hasAttr<FinalAttr>()) 1455 return false; 1456 1457 Diag(New->getLocation(), diag::err_final_function_overridden) 1458 << New->getDeclName(); 1459 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1460 return true; 1461} 1462 1463static bool InitializationHasSideEffects(const FieldDecl &FD) { 1464 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1465 // FIXME: Destruction of ObjC lifetime types has side-effects. 1466 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1467 return !RD->isCompleteDefinition() || 1468 !RD->hasTrivialDefaultConstructor() || 1469 !RD->hasTrivialDestructor(); 1470 return false; 1471} 1472 1473/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1474/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1475/// bitfield width if there is one, 'InitExpr' specifies the initializer if 1476/// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1477/// present (but parsing it has been deferred). 1478Decl * 1479Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1480 MultiTemplateParamsArg TemplateParameterLists, 1481 Expr *BW, const VirtSpecifiers &VS, 1482 InClassInitStyle InitStyle) { 1483 const DeclSpec &DS = D.getDeclSpec(); 1484 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1485 DeclarationName Name = NameInfo.getName(); 1486 SourceLocation Loc = NameInfo.getLoc(); 1487 1488 // For anonymous bitfields, the location should point to the type. 1489 if (Loc.isInvalid()) 1490 Loc = D.getLocStart(); 1491 1492 Expr *BitWidth = static_cast<Expr*>(BW); 1493 1494 assert(isa<CXXRecordDecl>(CurContext)); 1495 assert(!DS.isFriendSpecified()); 1496 1497 bool isFunc = D.isDeclarationOfFunction(); 1498 1499 // C++ 9.2p6: A member shall not be declared to have automatic storage 1500 // duration (auto, register) or with the extern storage-class-specifier. 1501 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1502 // data members and cannot be applied to names declared const or static, 1503 // and cannot be applied to reference members. 1504 switch (DS.getStorageClassSpec()) { 1505 case DeclSpec::SCS_unspecified: 1506 case DeclSpec::SCS_typedef: 1507 case DeclSpec::SCS_static: 1508 // FALL THROUGH. 1509 break; 1510 case DeclSpec::SCS_mutable: 1511 if (isFunc) { 1512 if (DS.getStorageClassSpecLoc().isValid()) 1513 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1514 else 1515 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 1516 1517 // FIXME: It would be nicer if the keyword was ignored only for this 1518 // declarator. Otherwise we could get follow-up errors. 1519 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1520 } 1521 break; 1522 default: 1523 if (DS.getStorageClassSpecLoc().isValid()) 1524 Diag(DS.getStorageClassSpecLoc(), 1525 diag::err_storageclass_invalid_for_member); 1526 else 1527 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 1528 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1529 } 1530 1531 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1532 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1533 !isFunc); 1534 1535 Decl *Member; 1536 if (isInstField) { 1537 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1538 1539 // Data members must have identifiers for names. 1540 if (!Name.isIdentifier()) { 1541 Diag(Loc, diag::err_bad_variable_name) 1542 << Name; 1543 return 0; 1544 } 1545 1546 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1547 1548 // Member field could not be with "template" keyword. 1549 // So TemplateParameterLists should be empty in this case. 1550 if (TemplateParameterLists.size()) { 1551 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0]; 1552 if (TemplateParams->size()) { 1553 // There is no such thing as a member field template. 1554 Diag(D.getIdentifierLoc(), diag::err_template_member) 1555 << II 1556 << SourceRange(TemplateParams->getTemplateLoc(), 1557 TemplateParams->getRAngleLoc()); 1558 } else { 1559 // There is an extraneous 'template<>' for this member. 1560 Diag(TemplateParams->getTemplateLoc(), 1561 diag::err_template_member_noparams) 1562 << II 1563 << SourceRange(TemplateParams->getTemplateLoc(), 1564 TemplateParams->getRAngleLoc()); 1565 } 1566 return 0; 1567 } 1568 1569 if (SS.isSet() && !SS.isInvalid()) { 1570 // The user provided a superfluous scope specifier inside a class 1571 // definition: 1572 // 1573 // class X { 1574 // int X::member; 1575 // }; 1576 if (DeclContext *DC = computeDeclContext(SS, false)) 1577 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 1578 else 1579 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1580 << Name << SS.getRange(); 1581 1582 SS.clear(); 1583 } 1584 1585 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 1586 InitStyle, AS); 1587 assert(Member && "HandleField never returns null"); 1588 } else { 1589 assert(InitStyle == ICIS_NoInit); 1590 1591 Member = HandleDeclarator(S, D, move(TemplateParameterLists)); 1592 if (!Member) { 1593 return 0; 1594 } 1595 1596 // Non-instance-fields can't have a bitfield. 1597 if (BitWidth) { 1598 if (Member->isInvalidDecl()) { 1599 // don't emit another diagnostic. 1600 } else if (isa<VarDecl>(Member)) { 1601 // C++ 9.6p3: A bit-field shall not be a static member. 1602 // "static member 'A' cannot be a bit-field" 1603 Diag(Loc, diag::err_static_not_bitfield) 1604 << Name << BitWidth->getSourceRange(); 1605 } else if (isa<TypedefDecl>(Member)) { 1606 // "typedef member 'x' cannot be a bit-field" 1607 Diag(Loc, diag::err_typedef_not_bitfield) 1608 << Name << BitWidth->getSourceRange(); 1609 } else { 1610 // A function typedef ("typedef int f(); f a;"). 1611 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1612 Diag(Loc, diag::err_not_integral_type_bitfield) 1613 << Name << cast<ValueDecl>(Member)->getType() 1614 << BitWidth->getSourceRange(); 1615 } 1616 1617 BitWidth = 0; 1618 Member->setInvalidDecl(); 1619 } 1620 1621 Member->setAccess(AS); 1622 1623 // If we have declared a member function template, set the access of the 1624 // templated declaration as well. 1625 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 1626 FunTmpl->getTemplatedDecl()->setAccess(AS); 1627 } 1628 1629 if (VS.isOverrideSpecified()) 1630 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 1631 if (VS.isFinalSpecified()) 1632 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 1633 1634 if (VS.getLastLocation().isValid()) { 1635 // Update the end location of a method that has a virt-specifiers. 1636 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 1637 MD->setRangeEnd(VS.getLastLocation()); 1638 } 1639 1640 CheckOverrideControl(Member); 1641 1642 assert((Name || isInstField) && "No identifier for non-field ?"); 1643 1644 if (isInstField) { 1645 FieldDecl *FD = cast<FieldDecl>(Member); 1646 FieldCollector->Add(FD); 1647 1648 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 1649 FD->getLocation()) 1650 != DiagnosticsEngine::Ignored) { 1651 // Remember all explicit private FieldDecls that have a name, no side 1652 // effects and are not part of a dependent type declaration. 1653 if (!FD->isImplicit() && FD->getDeclName() && 1654 FD->getAccess() == AS_private && 1655 !FD->hasAttr<UnusedAttr>() && 1656 !FD->getParent()->isDependentContext() && 1657 !InitializationHasSideEffects(*FD)) 1658 UnusedPrivateFields.insert(FD); 1659 } 1660 } 1661 1662 return Member; 1663} 1664 1665/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 1666/// in-class initializer for a non-static C++ class member, and after 1667/// instantiating an in-class initializer in a class template. Such actions 1668/// are deferred until the class is complete. 1669void 1670Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc, 1671 Expr *InitExpr) { 1672 FieldDecl *FD = cast<FieldDecl>(D); 1673 assert(FD->getInClassInitStyle() != ICIS_NoInit && 1674 "must set init style when field is created"); 1675 1676 if (!InitExpr) { 1677 FD->setInvalidDecl(); 1678 FD->removeInClassInitializer(); 1679 return; 1680 } 1681 1682 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 1683 FD->setInvalidDecl(); 1684 FD->removeInClassInitializer(); 1685 return; 1686 } 1687 1688 ExprResult Init = InitExpr; 1689 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 1690 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) { 1691 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list) 1692 << /*at end of ctor*/1 << InitExpr->getSourceRange(); 1693 } 1694 Expr **Inits = &InitExpr; 1695 unsigned NumInits = 1; 1696 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 1697 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 1698 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 1699 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 1700 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits); 1701 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits)); 1702 if (Init.isInvalid()) { 1703 FD->setInvalidDecl(); 1704 return; 1705 } 1706 1707 CheckImplicitConversions(Init.get(), InitLoc); 1708 } 1709 1710 // C++0x [class.base.init]p7: 1711 // The initialization of each base and member constitutes a 1712 // full-expression. 1713 Init = MaybeCreateExprWithCleanups(Init); 1714 if (Init.isInvalid()) { 1715 FD->setInvalidDecl(); 1716 return; 1717 } 1718 1719 InitExpr = Init.release(); 1720 1721 FD->setInClassInitializer(InitExpr); 1722} 1723 1724/// \brief Find the direct and/or virtual base specifiers that 1725/// correspond to the given base type, for use in base initialization 1726/// within a constructor. 1727static bool FindBaseInitializer(Sema &SemaRef, 1728 CXXRecordDecl *ClassDecl, 1729 QualType BaseType, 1730 const CXXBaseSpecifier *&DirectBaseSpec, 1731 const CXXBaseSpecifier *&VirtualBaseSpec) { 1732 // First, check for a direct base class. 1733 DirectBaseSpec = 0; 1734 for (CXXRecordDecl::base_class_const_iterator Base 1735 = ClassDecl->bases_begin(); 1736 Base != ClassDecl->bases_end(); ++Base) { 1737 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 1738 // We found a direct base of this type. That's what we're 1739 // initializing. 1740 DirectBaseSpec = &*Base; 1741 break; 1742 } 1743 } 1744 1745 // Check for a virtual base class. 1746 // FIXME: We might be able to short-circuit this if we know in advance that 1747 // there are no virtual bases. 1748 VirtualBaseSpec = 0; 1749 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 1750 // We haven't found a base yet; search the class hierarchy for a 1751 // virtual base class. 1752 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1753 /*DetectVirtual=*/false); 1754 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 1755 BaseType, Paths)) { 1756 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1757 Path != Paths.end(); ++Path) { 1758 if (Path->back().Base->isVirtual()) { 1759 VirtualBaseSpec = Path->back().Base; 1760 break; 1761 } 1762 } 1763 } 1764 } 1765 1766 return DirectBaseSpec || VirtualBaseSpec; 1767} 1768 1769/// \brief Handle a C++ member initializer using braced-init-list syntax. 1770MemInitResult 1771Sema::ActOnMemInitializer(Decl *ConstructorD, 1772 Scope *S, 1773 CXXScopeSpec &SS, 1774 IdentifierInfo *MemberOrBase, 1775 ParsedType TemplateTypeTy, 1776 const DeclSpec &DS, 1777 SourceLocation IdLoc, 1778 Expr *InitList, 1779 SourceLocation EllipsisLoc) { 1780 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 1781 DS, IdLoc, InitList, 1782 EllipsisLoc); 1783} 1784 1785/// \brief Handle a C++ member initializer using parentheses syntax. 1786MemInitResult 1787Sema::ActOnMemInitializer(Decl *ConstructorD, 1788 Scope *S, 1789 CXXScopeSpec &SS, 1790 IdentifierInfo *MemberOrBase, 1791 ParsedType TemplateTypeTy, 1792 const DeclSpec &DS, 1793 SourceLocation IdLoc, 1794 SourceLocation LParenLoc, 1795 Expr **Args, unsigned NumArgs, 1796 SourceLocation RParenLoc, 1797 SourceLocation EllipsisLoc) { 1798 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1799 RParenLoc); 1800 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 1801 DS, IdLoc, List, EllipsisLoc); 1802} 1803 1804namespace { 1805 1806// Callback to only accept typo corrections that can be a valid C++ member 1807// intializer: either a non-static field member or a base class. 1808class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 1809 public: 1810 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 1811 : ClassDecl(ClassDecl) {} 1812 1813 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 1814 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 1815 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 1816 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 1817 else 1818 return isa<TypeDecl>(ND); 1819 } 1820 return false; 1821 } 1822 1823 private: 1824 CXXRecordDecl *ClassDecl; 1825}; 1826 1827} 1828 1829/// \brief Handle a C++ member initializer. 1830MemInitResult 1831Sema::BuildMemInitializer(Decl *ConstructorD, 1832 Scope *S, 1833 CXXScopeSpec &SS, 1834 IdentifierInfo *MemberOrBase, 1835 ParsedType TemplateTypeTy, 1836 const DeclSpec &DS, 1837 SourceLocation IdLoc, 1838 Expr *Init, 1839 SourceLocation EllipsisLoc) { 1840 if (!ConstructorD) 1841 return true; 1842 1843 AdjustDeclIfTemplate(ConstructorD); 1844 1845 CXXConstructorDecl *Constructor 1846 = dyn_cast<CXXConstructorDecl>(ConstructorD); 1847 if (!Constructor) { 1848 // The user wrote a constructor initializer on a function that is 1849 // not a C++ constructor. Ignore the error for now, because we may 1850 // have more member initializers coming; we'll diagnose it just 1851 // once in ActOnMemInitializers. 1852 return true; 1853 } 1854 1855 CXXRecordDecl *ClassDecl = Constructor->getParent(); 1856 1857 // C++ [class.base.init]p2: 1858 // Names in a mem-initializer-id are looked up in the scope of the 1859 // constructor's class and, if not found in that scope, are looked 1860 // up in the scope containing the constructor's definition. 1861 // [Note: if the constructor's class contains a member with the 1862 // same name as a direct or virtual base class of the class, a 1863 // mem-initializer-id naming the member or base class and composed 1864 // of a single identifier refers to the class member. A 1865 // mem-initializer-id for the hidden base class may be specified 1866 // using a qualified name. ] 1867 if (!SS.getScopeRep() && !TemplateTypeTy) { 1868 // Look for a member, first. 1869 DeclContext::lookup_result Result 1870 = ClassDecl->lookup(MemberOrBase); 1871 if (Result.first != Result.second) { 1872 ValueDecl *Member; 1873 if ((Member = dyn_cast<FieldDecl>(*Result.first)) || 1874 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) { 1875 if (EllipsisLoc.isValid()) 1876 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 1877 << MemberOrBase 1878 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 1879 1880 return BuildMemberInitializer(Member, Init, IdLoc); 1881 } 1882 } 1883 } 1884 // It didn't name a member, so see if it names a class. 1885 QualType BaseType; 1886 TypeSourceInfo *TInfo = 0; 1887 1888 if (TemplateTypeTy) { 1889 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 1890 } else if (DS.getTypeSpecType() == TST_decltype) { 1891 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 1892 } else { 1893 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 1894 LookupParsedName(R, S, &SS); 1895 1896 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 1897 if (!TyD) { 1898 if (R.isAmbiguous()) return true; 1899 1900 // We don't want access-control diagnostics here. 1901 R.suppressDiagnostics(); 1902 1903 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 1904 bool NotUnknownSpecialization = false; 1905 DeclContext *DC = computeDeclContext(SS, false); 1906 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 1907 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 1908 1909 if (!NotUnknownSpecialization) { 1910 // When the scope specifier can refer to a member of an unknown 1911 // specialization, we take it as a type name. 1912 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 1913 SS.getWithLocInContext(Context), 1914 *MemberOrBase, IdLoc); 1915 if (BaseType.isNull()) 1916 return true; 1917 1918 R.clear(); 1919 R.setLookupName(MemberOrBase); 1920 } 1921 } 1922 1923 // If no results were found, try to correct typos. 1924 TypoCorrection Corr; 1925 MemInitializerValidatorCCC Validator(ClassDecl); 1926 if (R.empty() && BaseType.isNull() && 1927 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 1928 Validator, ClassDecl))) { 1929 std::string CorrectedStr(Corr.getAsString(getLangOpts())); 1930 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts())); 1931 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 1932 // We have found a non-static data member with a similar 1933 // name to what was typed; complain and initialize that 1934 // member. 1935 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1936 << MemberOrBase << true << CorrectedQuotedStr 1937 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1938 Diag(Member->getLocation(), diag::note_previous_decl) 1939 << CorrectedQuotedStr; 1940 1941 return BuildMemberInitializer(Member, Init, IdLoc); 1942 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 1943 const CXXBaseSpecifier *DirectBaseSpec; 1944 const CXXBaseSpecifier *VirtualBaseSpec; 1945 if (FindBaseInitializer(*this, ClassDecl, 1946 Context.getTypeDeclType(Type), 1947 DirectBaseSpec, VirtualBaseSpec)) { 1948 // We have found a direct or virtual base class with a 1949 // similar name to what was typed; complain and initialize 1950 // that base class. 1951 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1952 << MemberOrBase << false << CorrectedQuotedStr 1953 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr); 1954 1955 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 1956 : VirtualBaseSpec; 1957 Diag(BaseSpec->getLocStart(), 1958 diag::note_base_class_specified_here) 1959 << BaseSpec->getType() 1960 << BaseSpec->getSourceRange(); 1961 1962 TyD = Type; 1963 } 1964 } 1965 } 1966 1967 if (!TyD && BaseType.isNull()) { 1968 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 1969 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 1970 return true; 1971 } 1972 } 1973 1974 if (BaseType.isNull()) { 1975 BaseType = Context.getTypeDeclType(TyD); 1976 if (SS.isSet()) { 1977 NestedNameSpecifier *Qualifier = 1978 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1979 1980 // FIXME: preserve source range information 1981 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 1982 } 1983 } 1984 } 1985 1986 if (!TInfo) 1987 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 1988 1989 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 1990} 1991 1992/// Checks a member initializer expression for cases where reference (or 1993/// pointer) members are bound to by-value parameters (or their addresses). 1994static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 1995 Expr *Init, 1996 SourceLocation IdLoc) { 1997 QualType MemberTy = Member->getType(); 1998 1999 // We only handle pointers and references currently. 2000 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2001 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2002 return; 2003 2004 const bool IsPointer = MemberTy->isPointerType(); 2005 if (IsPointer) { 2006 if (const UnaryOperator *Op 2007 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2008 // The only case we're worried about with pointers requires taking the 2009 // address. 2010 if (Op->getOpcode() != UO_AddrOf) 2011 return; 2012 2013 Init = Op->getSubExpr(); 2014 } else { 2015 // We only handle address-of expression initializers for pointers. 2016 return; 2017 } 2018 } 2019 2020 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) { 2021 // Taking the address of a temporary will be diagnosed as a hard error. 2022 if (IsPointer) 2023 return; 2024 2025 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary) 2026 << Member << Init->getSourceRange(); 2027 } else if (const DeclRefExpr *DRE 2028 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2029 // We only warn when referring to a non-reference parameter declaration. 2030 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2031 if (!Parameter || Parameter->getType()->isReferenceType()) 2032 return; 2033 2034 S.Diag(Init->getExprLoc(), 2035 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2036 : diag::warn_bind_ref_member_to_parameter) 2037 << Member << Parameter << Init->getSourceRange(); 2038 } else { 2039 // Other initializers are fine. 2040 return; 2041 } 2042 2043 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2044 << (unsigned)IsPointer; 2045} 2046 2047namespace { 2048 class UninitializedFieldVisitor 2049 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2050 Sema &S; 2051 ValueDecl *VD; 2052 public: 2053 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2054 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context), 2055 S(S), VD(VD) { 2056 } 2057 2058 void HandleExpr(Expr *E) { 2059 if (!E) return; 2060 2061 // Expressions like x(x) sometimes lack the surrounding expressions 2062 // but need to be checked anyways. 2063 HandleValue(E); 2064 Visit(E); 2065 } 2066 2067 void HandleValue(Expr *E) { 2068 E = E->IgnoreParens(); 2069 2070 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2071 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2072 return; 2073 Expr *Base = E; 2074 while (isa<MemberExpr>(Base)) { 2075 ME = dyn_cast<MemberExpr>(Base); 2076 if (VarDecl *VarD = dyn_cast<VarDecl>(ME->getMemberDecl())) 2077 if (VarD->hasGlobalStorage()) 2078 return; 2079 Base = ME->getBase(); 2080 } 2081 2082 if (VD == ME->getMemberDecl() && isa<CXXThisExpr>(Base)) { 2083 S.Diag(ME->getExprLoc(), diag::warn_field_is_uninit); 2084 return; 2085 } 2086 } 2087 2088 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2089 HandleValue(CO->getTrueExpr()); 2090 HandleValue(CO->getFalseExpr()); 2091 return; 2092 } 2093 2094 if (BinaryConditionalOperator *BCO = 2095 dyn_cast<BinaryConditionalOperator>(E)) { 2096 HandleValue(BCO->getCommon()); 2097 HandleValue(BCO->getFalseExpr()); 2098 return; 2099 } 2100 2101 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2102 switch (BO->getOpcode()) { 2103 default: 2104 return; 2105 case(BO_PtrMemD): 2106 case(BO_PtrMemI): 2107 HandleValue(BO->getLHS()); 2108 return; 2109 case(BO_Comma): 2110 HandleValue(BO->getRHS()); 2111 return; 2112 } 2113 } 2114 } 2115 2116 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2117 if (E->getCastKind() == CK_LValueToRValue) 2118 HandleValue(E->getSubExpr()); 2119 2120 Inherited::VisitImplicitCastExpr(E); 2121 } 2122 2123 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2124 Expr *Callee = E->getCallee(); 2125 if (isa<MemberExpr>(Callee)) 2126 HandleValue(Callee); 2127 2128 Inherited::VisitCXXMemberCallExpr(E); 2129 } 2130 }; 2131 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E, 2132 ValueDecl *VD) { 2133 UninitializedFieldVisitor(S, VD).HandleExpr(E); 2134 } 2135} // namespace 2136 2137MemInitResult 2138Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2139 SourceLocation IdLoc) { 2140 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2141 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2142 assert((DirectMember || IndirectMember) && 2143 "Member must be a FieldDecl or IndirectFieldDecl"); 2144 2145 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2146 return true; 2147 2148 if (Member->isInvalidDecl()) 2149 return true; 2150 2151 // Diagnose value-uses of fields to initialize themselves, e.g. 2152 // foo(foo) 2153 // where foo is not also a parameter to the constructor. 2154 // TODO: implement -Wuninitialized and fold this into that framework. 2155 Expr **Args; 2156 unsigned NumArgs; 2157 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2158 Args = ParenList->getExprs(); 2159 NumArgs = ParenList->getNumExprs(); 2160 } else { 2161 InitListExpr *InitList = cast<InitListExpr>(Init); 2162 Args = InitList->getInits(); 2163 NumArgs = InitList->getNumInits(); 2164 } 2165 2166 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc) 2167 != DiagnosticsEngine::Ignored) 2168 for (unsigned i = 0; i < NumArgs; ++i) 2169 // FIXME: Warn about the case when other fields are used before being 2170 // uninitialized. For example, let this field be the i'th field. When 2171 // initializing the i'th field, throw a warning if any of the >= i'th 2172 // fields are used, as they are not yet initialized. 2173 // Right now we are only handling the case where the i'th field uses 2174 // itself in its initializer. 2175 CheckInitExprContainsUninitializedFields(*this, Args[i], Member); 2176 2177 SourceRange InitRange = Init->getSourceRange(); 2178 2179 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2180 // Can't check initialization for a member of dependent type or when 2181 // any of the arguments are type-dependent expressions. 2182 DiscardCleanupsInEvaluationContext(); 2183 } else { 2184 bool InitList = false; 2185 if (isa<InitListExpr>(Init)) { 2186 InitList = true; 2187 Args = &Init; 2188 NumArgs = 1; 2189 2190 if (isStdInitializerList(Member->getType(), 0)) { 2191 Diag(IdLoc, diag::warn_dangling_std_initializer_list) 2192 << /*at end of ctor*/1 << InitRange; 2193 } 2194 } 2195 2196 // Initialize the member. 2197 InitializedEntity MemberEntity = 2198 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2199 : InitializedEntity::InitializeMember(IndirectMember, 0); 2200 InitializationKind Kind = 2201 InitList ? InitializationKind::CreateDirectList(IdLoc) 2202 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2203 InitRange.getEnd()); 2204 2205 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 2206 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, 2207 MultiExprArg(*this, Args, NumArgs), 2208 0); 2209 if (MemberInit.isInvalid()) 2210 return true; 2211 2212 CheckImplicitConversions(MemberInit.get(), 2213 InitRange.getBegin()); 2214 2215 // C++0x [class.base.init]p7: 2216 // The initialization of each base and member constitutes a 2217 // full-expression. 2218 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 2219 if (MemberInit.isInvalid()) 2220 return true; 2221 2222 // If we are in a dependent context, template instantiation will 2223 // perform this type-checking again. Just save the arguments that we 2224 // received. 2225 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2226 // of the information that we have about the member 2227 // initializer. However, deconstructing the ASTs is a dicey process, 2228 // and this approach is far more likely to get the corner cases right. 2229 if (CurContext->isDependentContext()) { 2230 // The existing Init will do fine. 2231 } else { 2232 Init = MemberInit.get(); 2233 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc); 2234 } 2235 } 2236 2237 if (DirectMember) { 2238 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2239 InitRange.getBegin(), Init, 2240 InitRange.getEnd()); 2241 } else { 2242 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2243 InitRange.getBegin(), Init, 2244 InitRange.getEnd()); 2245 } 2246} 2247 2248MemInitResult 2249Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2250 CXXRecordDecl *ClassDecl) { 2251 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2252 if (!LangOpts.CPlusPlus0x) 2253 return Diag(NameLoc, diag::err_delegating_ctor) 2254 << TInfo->getTypeLoc().getLocalSourceRange(); 2255 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2256 2257 bool InitList = true; 2258 Expr **Args = &Init; 2259 unsigned NumArgs = 1; 2260 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2261 InitList = false; 2262 Args = ParenList->getExprs(); 2263 NumArgs = ParenList->getNumExprs(); 2264 } 2265 2266 SourceRange InitRange = Init->getSourceRange(); 2267 // Initialize the object. 2268 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2269 QualType(ClassDecl->getTypeForDecl(), 0)); 2270 InitializationKind Kind = 2271 InitList ? InitializationKind::CreateDirectList(NameLoc) 2272 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2273 InitRange.getEnd()); 2274 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs); 2275 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2276 MultiExprArg(*this, Args,NumArgs), 2277 0); 2278 if (DelegationInit.isInvalid()) 2279 return true; 2280 2281 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2282 "Delegating constructor with no target?"); 2283 2284 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin()); 2285 2286 // C++0x [class.base.init]p7: 2287 // The initialization of each base and member constitutes a 2288 // full-expression. 2289 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit); 2290 if (DelegationInit.isInvalid()) 2291 return true; 2292 2293 // If we are in a dependent context, template instantiation will 2294 // perform this type-checking again. Just save the arguments that we 2295 // received in a ParenListExpr. 2296 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2297 // of the information that we have about the base 2298 // initializer. However, deconstructing the ASTs is a dicey process, 2299 // and this approach is far more likely to get the corner cases right. 2300 if (CurContext->isDependentContext()) 2301 DelegationInit = Owned(Init); 2302 2303 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2304 DelegationInit.takeAs<Expr>(), 2305 InitRange.getEnd()); 2306} 2307 2308MemInitResult 2309Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2310 Expr *Init, CXXRecordDecl *ClassDecl, 2311 SourceLocation EllipsisLoc) { 2312 SourceLocation BaseLoc 2313 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2314 2315 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2316 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2317 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2318 2319 // C++ [class.base.init]p2: 2320 // [...] Unless the mem-initializer-id names a nonstatic data 2321 // member of the constructor's class or a direct or virtual base 2322 // of that class, the mem-initializer is ill-formed. A 2323 // mem-initializer-list can initialize a base class using any 2324 // name that denotes that base class type. 2325 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2326 2327 SourceRange InitRange = Init->getSourceRange(); 2328 if (EllipsisLoc.isValid()) { 2329 // This is a pack expansion. 2330 if (!BaseType->containsUnexpandedParameterPack()) { 2331 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2332 << SourceRange(BaseLoc, InitRange.getEnd()); 2333 2334 EllipsisLoc = SourceLocation(); 2335 } 2336 } else { 2337 // Check for any unexpanded parameter packs. 2338 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2339 return true; 2340 2341 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2342 return true; 2343 } 2344 2345 // Check for direct and virtual base classes. 2346 const CXXBaseSpecifier *DirectBaseSpec = 0; 2347 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2348 if (!Dependent) { 2349 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2350 BaseType)) 2351 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2352 2353 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2354 VirtualBaseSpec); 2355 2356 // C++ [base.class.init]p2: 2357 // Unless the mem-initializer-id names a nonstatic data member of the 2358 // constructor's class or a direct or virtual base of that class, the 2359 // mem-initializer is ill-formed. 2360 if (!DirectBaseSpec && !VirtualBaseSpec) { 2361 // If the class has any dependent bases, then it's possible that 2362 // one of those types will resolve to the same type as 2363 // BaseType. Therefore, just treat this as a dependent base 2364 // class initialization. FIXME: Should we try to check the 2365 // initialization anyway? It seems odd. 2366 if (ClassDecl->hasAnyDependentBases()) 2367 Dependent = true; 2368 else 2369 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2370 << BaseType << Context.getTypeDeclType(ClassDecl) 2371 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2372 } 2373 } 2374 2375 if (Dependent) { 2376 DiscardCleanupsInEvaluationContext(); 2377 2378 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2379 /*IsVirtual=*/false, 2380 InitRange.getBegin(), Init, 2381 InitRange.getEnd(), EllipsisLoc); 2382 } 2383 2384 // C++ [base.class.init]p2: 2385 // If a mem-initializer-id is ambiguous because it designates both 2386 // a direct non-virtual base class and an inherited virtual base 2387 // class, the mem-initializer is ill-formed. 2388 if (DirectBaseSpec && VirtualBaseSpec) 2389 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2390 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2391 2392 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 2393 if (!BaseSpec) 2394 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 2395 2396 // Initialize the base. 2397 bool InitList = true; 2398 Expr **Args = &Init; 2399 unsigned NumArgs = 1; 2400 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2401 InitList = false; 2402 Args = ParenList->getExprs(); 2403 NumArgs = ParenList->getNumExprs(); 2404 } 2405 2406 InitializedEntity BaseEntity = 2407 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2408 InitializationKind Kind = 2409 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2410 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2411 InitRange.getEnd()); 2412 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 2413 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, 2414 MultiExprArg(*this, Args, NumArgs), 2415 0); 2416 if (BaseInit.isInvalid()) 2417 return true; 2418 2419 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin()); 2420 2421 // C++0x [class.base.init]p7: 2422 // The initialization of each base and member constitutes a 2423 // full-expression. 2424 BaseInit = MaybeCreateExprWithCleanups(BaseInit); 2425 if (BaseInit.isInvalid()) 2426 return true; 2427 2428 // If we are in a dependent context, template instantiation will 2429 // perform this type-checking again. Just save the arguments that we 2430 // received in a ParenListExpr. 2431 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2432 // of the information that we have about the base 2433 // initializer. However, deconstructing the ASTs is a dicey process, 2434 // and this approach is far more likely to get the corner cases right. 2435 if (CurContext->isDependentContext()) 2436 BaseInit = Owned(Init); 2437 2438 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2439 BaseSpec->isVirtual(), 2440 InitRange.getBegin(), 2441 BaseInit.takeAs<Expr>(), 2442 InitRange.getEnd(), EllipsisLoc); 2443} 2444 2445// Create a static_cast\<T&&>(expr). 2446static Expr *CastForMoving(Sema &SemaRef, Expr *E) { 2447 QualType ExprType = E->getType(); 2448 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType); 2449 SourceLocation ExprLoc = E->getLocStart(); 2450 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2451 TargetType, ExprLoc); 2452 2453 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2454 SourceRange(ExprLoc, ExprLoc), 2455 E->getSourceRange()).take(); 2456} 2457 2458/// ImplicitInitializerKind - How an implicit base or member initializer should 2459/// initialize its base or member. 2460enum ImplicitInitializerKind { 2461 IIK_Default, 2462 IIK_Copy, 2463 IIK_Move 2464}; 2465 2466static bool 2467BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2468 ImplicitInitializerKind ImplicitInitKind, 2469 CXXBaseSpecifier *BaseSpec, 2470 bool IsInheritedVirtualBase, 2471 CXXCtorInitializer *&CXXBaseInit) { 2472 InitializedEntity InitEntity 2473 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2474 IsInheritedVirtualBase); 2475 2476 ExprResult BaseInit; 2477 2478 switch (ImplicitInitKind) { 2479 case IIK_Default: { 2480 InitializationKind InitKind 2481 = InitializationKind::CreateDefault(Constructor->getLocation()); 2482 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2483 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 2484 MultiExprArg(SemaRef, 0, 0)); 2485 break; 2486 } 2487 2488 case IIK_Move: 2489 case IIK_Copy: { 2490 bool Moving = ImplicitInitKind == IIK_Move; 2491 ParmVarDecl *Param = Constructor->getParamDecl(0); 2492 QualType ParamType = Param->getType().getNonReferenceType(); 2493 2494 Expr *CopyCtorArg = 2495 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2496 SourceLocation(), Param, false, 2497 Constructor->getLocation(), ParamType, 2498 VK_LValue, 0); 2499 2500 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2501 2502 // Cast to the base class to avoid ambiguities. 2503 QualType ArgTy = 2504 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 2505 ParamType.getQualifiers()); 2506 2507 if (Moving) { 2508 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 2509 } 2510 2511 CXXCastPath BasePath; 2512 BasePath.push_back(BaseSpec); 2513 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 2514 CK_UncheckedDerivedToBase, 2515 Moving ? VK_XValue : VK_LValue, 2516 &BasePath).take(); 2517 2518 InitializationKind InitKind 2519 = InitializationKind::CreateDirect(Constructor->getLocation(), 2520 SourceLocation(), SourceLocation()); 2521 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 2522 &CopyCtorArg, 1); 2523 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 2524 MultiExprArg(&CopyCtorArg, 1)); 2525 break; 2526 } 2527 } 2528 2529 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 2530 if (BaseInit.isInvalid()) 2531 return true; 2532 2533 CXXBaseInit = 2534 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2535 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 2536 SourceLocation()), 2537 BaseSpec->isVirtual(), 2538 SourceLocation(), 2539 BaseInit.takeAs<Expr>(), 2540 SourceLocation(), 2541 SourceLocation()); 2542 2543 return false; 2544} 2545 2546static bool RefersToRValueRef(Expr *MemRef) { 2547 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 2548 return Referenced->getType()->isRValueReferenceType(); 2549} 2550 2551static bool 2552BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2553 ImplicitInitializerKind ImplicitInitKind, 2554 FieldDecl *Field, IndirectFieldDecl *Indirect, 2555 CXXCtorInitializer *&CXXMemberInit) { 2556 if (Field->isInvalidDecl()) 2557 return true; 2558 2559 SourceLocation Loc = Constructor->getLocation(); 2560 2561 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 2562 bool Moving = ImplicitInitKind == IIK_Move; 2563 ParmVarDecl *Param = Constructor->getParamDecl(0); 2564 QualType ParamType = Param->getType().getNonReferenceType(); 2565 2566 // Suppress copying zero-width bitfields. 2567 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 2568 return false; 2569 2570 Expr *MemberExprBase = 2571 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2572 SourceLocation(), Param, false, 2573 Loc, ParamType, VK_LValue, 0); 2574 2575 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 2576 2577 if (Moving) { 2578 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 2579 } 2580 2581 // Build a reference to this field within the parameter. 2582 CXXScopeSpec SS; 2583 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 2584 Sema::LookupMemberName); 2585 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 2586 : cast<ValueDecl>(Field), AS_public); 2587 MemberLookup.resolveKind(); 2588 ExprResult CtorArg 2589 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 2590 ParamType, Loc, 2591 /*IsArrow=*/false, 2592 SS, 2593 /*TemplateKWLoc=*/SourceLocation(), 2594 /*FirstQualifierInScope=*/0, 2595 MemberLookup, 2596 /*TemplateArgs=*/0); 2597 if (CtorArg.isInvalid()) 2598 return true; 2599 2600 // C++11 [class.copy]p15: 2601 // - if a member m has rvalue reference type T&&, it is direct-initialized 2602 // with static_cast<T&&>(x.m); 2603 if (RefersToRValueRef(CtorArg.get())) { 2604 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2605 } 2606 2607 // When the field we are copying is an array, create index variables for 2608 // each dimension of the array. We use these index variables to subscript 2609 // the source array, and other clients (e.g., CodeGen) will perform the 2610 // necessary iteration with these index variables. 2611 SmallVector<VarDecl *, 4> IndexVariables; 2612 QualType BaseType = Field->getType(); 2613 QualType SizeType = SemaRef.Context.getSizeType(); 2614 bool InitializingArray = false; 2615 while (const ConstantArrayType *Array 2616 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 2617 InitializingArray = true; 2618 // Create the iteration variable for this array index. 2619 IdentifierInfo *IterationVarName = 0; 2620 { 2621 SmallString<8> Str; 2622 llvm::raw_svector_ostream OS(Str); 2623 OS << "__i" << IndexVariables.size(); 2624 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 2625 } 2626 VarDecl *IterationVar 2627 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 2628 IterationVarName, SizeType, 2629 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 2630 SC_None, SC_None); 2631 IndexVariables.push_back(IterationVar); 2632 2633 // Create a reference to the iteration variable. 2634 ExprResult IterationVarRef 2635 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 2636 assert(!IterationVarRef.isInvalid() && 2637 "Reference to invented variable cannot fail!"); 2638 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 2639 assert(!IterationVarRef.isInvalid() && 2640 "Conversion of invented variable cannot fail!"); 2641 2642 // Subscript the array with this iteration variable. 2643 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 2644 IterationVarRef.take(), 2645 Loc); 2646 if (CtorArg.isInvalid()) 2647 return true; 2648 2649 BaseType = Array->getElementType(); 2650 } 2651 2652 // The array subscript expression is an lvalue, which is wrong for moving. 2653 if (Moving && InitializingArray) 2654 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 2655 2656 // Construct the entity that we will be initializing. For an array, this 2657 // will be first element in the array, which may require several levels 2658 // of array-subscript entities. 2659 SmallVector<InitializedEntity, 4> Entities; 2660 Entities.reserve(1 + IndexVariables.size()); 2661 if (Indirect) 2662 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 2663 else 2664 Entities.push_back(InitializedEntity::InitializeMember(Field)); 2665 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 2666 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 2667 0, 2668 Entities.back())); 2669 2670 // Direct-initialize to use the copy constructor. 2671 InitializationKind InitKind = 2672 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 2673 2674 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 2675 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 2676 &CtorArgE, 1); 2677 2678 ExprResult MemberInit 2679 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 2680 MultiExprArg(&CtorArgE, 1)); 2681 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2682 if (MemberInit.isInvalid()) 2683 return true; 2684 2685 if (Indirect) { 2686 assert(IndexVariables.size() == 0 && 2687 "Indirect field improperly initialized"); 2688 CXXMemberInit 2689 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2690 Loc, Loc, 2691 MemberInit.takeAs<Expr>(), 2692 Loc); 2693 } else 2694 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 2695 Loc, MemberInit.takeAs<Expr>(), 2696 Loc, 2697 IndexVariables.data(), 2698 IndexVariables.size()); 2699 return false; 2700 } 2701 2702 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!"); 2703 2704 QualType FieldBaseElementType = 2705 SemaRef.Context.getBaseElementType(Field->getType()); 2706 2707 if (FieldBaseElementType->isRecordType()) { 2708 InitializedEntity InitEntity 2709 = Indirect? InitializedEntity::InitializeMember(Indirect) 2710 : InitializedEntity::InitializeMember(Field); 2711 InitializationKind InitKind = 2712 InitializationKind::CreateDefault(Loc); 2713 2714 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 2715 ExprResult MemberInit = 2716 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 2717 2718 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 2719 if (MemberInit.isInvalid()) 2720 return true; 2721 2722 if (Indirect) 2723 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2724 Indirect, Loc, 2725 Loc, 2726 MemberInit.get(), 2727 Loc); 2728 else 2729 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2730 Field, Loc, Loc, 2731 MemberInit.get(), 2732 Loc); 2733 return false; 2734 } 2735 2736 if (!Field->getParent()->isUnion()) { 2737 if (FieldBaseElementType->isReferenceType()) { 2738 SemaRef.Diag(Constructor->getLocation(), 2739 diag::err_uninitialized_member_in_ctor) 2740 << (int)Constructor->isImplicit() 2741 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2742 << 0 << Field->getDeclName(); 2743 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2744 return true; 2745 } 2746 2747 if (FieldBaseElementType.isConstQualified()) { 2748 SemaRef.Diag(Constructor->getLocation(), 2749 diag::err_uninitialized_member_in_ctor) 2750 << (int)Constructor->isImplicit() 2751 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 2752 << 1 << Field->getDeclName(); 2753 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 2754 return true; 2755 } 2756 } 2757 2758 if (SemaRef.getLangOpts().ObjCAutoRefCount && 2759 FieldBaseElementType->isObjCRetainableType() && 2760 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 2761 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 2762 // ARC: 2763 // Default-initialize Objective-C pointers to NULL. 2764 CXXMemberInit 2765 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 2766 Loc, Loc, 2767 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 2768 Loc); 2769 return false; 2770 } 2771 2772 // Nothing to initialize. 2773 CXXMemberInit = 0; 2774 return false; 2775} 2776 2777namespace { 2778struct BaseAndFieldInfo { 2779 Sema &S; 2780 CXXConstructorDecl *Ctor; 2781 bool AnyErrorsInInits; 2782 ImplicitInitializerKind IIK; 2783 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 2784 SmallVector<CXXCtorInitializer*, 8> AllToInit; 2785 2786 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 2787 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 2788 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 2789 if (Generated && Ctor->isCopyConstructor()) 2790 IIK = IIK_Copy; 2791 else if (Generated && Ctor->isMoveConstructor()) 2792 IIK = IIK_Move; 2793 else 2794 IIK = IIK_Default; 2795 } 2796 2797 bool isImplicitCopyOrMove() const { 2798 switch (IIK) { 2799 case IIK_Copy: 2800 case IIK_Move: 2801 return true; 2802 2803 case IIK_Default: 2804 return false; 2805 } 2806 2807 llvm_unreachable("Invalid ImplicitInitializerKind!"); 2808 } 2809 2810 bool addFieldInitializer(CXXCtorInitializer *Init) { 2811 AllToInit.push_back(Init); 2812 2813 // Check whether this initializer makes the field "used". 2814 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context)) 2815 S.UnusedPrivateFields.remove(Init->getAnyMember()); 2816 2817 return false; 2818 } 2819}; 2820} 2821 2822/// \brief Determine whether the given indirect field declaration is somewhere 2823/// within an anonymous union. 2824static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 2825 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 2826 CEnd = F->chain_end(); 2827 C != CEnd; ++C) 2828 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 2829 if (Record->isUnion()) 2830 return true; 2831 2832 return false; 2833} 2834 2835/// \brief Determine whether the given type is an incomplete or zero-lenfgth 2836/// array type. 2837static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 2838 if (T->isIncompleteArrayType()) 2839 return true; 2840 2841 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 2842 if (!ArrayT->getSize()) 2843 return true; 2844 2845 T = ArrayT->getElementType(); 2846 } 2847 2848 return false; 2849} 2850 2851static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 2852 FieldDecl *Field, 2853 IndirectFieldDecl *Indirect = 0) { 2854 2855 // Overwhelmingly common case: we have a direct initializer for this field. 2856 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 2857 return Info.addFieldInitializer(Init); 2858 2859 // C++11 [class.base.init]p8: if the entity is a non-static data member that 2860 // has a brace-or-equal-initializer, the entity is initialized as specified 2861 // in [dcl.init]. 2862 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 2863 CXXCtorInitializer *Init; 2864 if (Indirect) 2865 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 2866 SourceLocation(), 2867 SourceLocation(), 0, 2868 SourceLocation()); 2869 else 2870 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 2871 SourceLocation(), 2872 SourceLocation(), 0, 2873 SourceLocation()); 2874 return Info.addFieldInitializer(Init); 2875 } 2876 2877 // Don't build an implicit initializer for union members if none was 2878 // explicitly specified. 2879 if (Field->getParent()->isUnion() || 2880 (Indirect && isWithinAnonymousUnion(Indirect))) 2881 return false; 2882 2883 // Don't initialize incomplete or zero-length arrays. 2884 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 2885 return false; 2886 2887 // Don't try to build an implicit initializer if there were semantic 2888 // errors in any of the initializers (and therefore we might be 2889 // missing some that the user actually wrote). 2890 if (Info.AnyErrorsInInits || Field->isInvalidDecl()) 2891 return false; 2892 2893 CXXCtorInitializer *Init = 0; 2894 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 2895 Indirect, Init)) 2896 return true; 2897 2898 if (!Init) 2899 return false; 2900 2901 return Info.addFieldInitializer(Init); 2902} 2903 2904bool 2905Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 2906 CXXCtorInitializer *Initializer) { 2907 assert(Initializer->isDelegatingInitializer()); 2908 Constructor->setNumCtorInitializers(1); 2909 CXXCtorInitializer **initializer = 2910 new (Context) CXXCtorInitializer*[1]; 2911 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 2912 Constructor->setCtorInitializers(initializer); 2913 2914 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 2915 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 2916 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 2917 } 2918 2919 DelegatingCtorDecls.push_back(Constructor); 2920 2921 return false; 2922} 2923 2924bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, 2925 CXXCtorInitializer **Initializers, 2926 unsigned NumInitializers, 2927 bool AnyErrors) { 2928 if (Constructor->isDependentContext()) { 2929 // Just store the initializers as written, they will be checked during 2930 // instantiation. 2931 if (NumInitializers > 0) { 2932 Constructor->setNumCtorInitializers(NumInitializers); 2933 CXXCtorInitializer **baseOrMemberInitializers = 2934 new (Context) CXXCtorInitializer*[NumInitializers]; 2935 memcpy(baseOrMemberInitializers, Initializers, 2936 NumInitializers * sizeof(CXXCtorInitializer*)); 2937 Constructor->setCtorInitializers(baseOrMemberInitializers); 2938 } 2939 2940 return false; 2941 } 2942 2943 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 2944 2945 // We need to build the initializer AST according to order of construction 2946 // and not what user specified in the Initializers list. 2947 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 2948 if (!ClassDecl) 2949 return true; 2950 2951 bool HadError = false; 2952 2953 for (unsigned i = 0; i < NumInitializers; i++) { 2954 CXXCtorInitializer *Member = Initializers[i]; 2955 2956 if (Member->isBaseInitializer()) 2957 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 2958 else 2959 Info.AllBaseFields[Member->getAnyMember()] = Member; 2960 } 2961 2962 // Keep track of the direct virtual bases. 2963 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 2964 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 2965 E = ClassDecl->bases_end(); I != E; ++I) { 2966 if (I->isVirtual()) 2967 DirectVBases.insert(I); 2968 } 2969 2970 // Push virtual bases before others. 2971 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2972 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2973 2974 if (CXXCtorInitializer *Value 2975 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 2976 Info.AllToInit.push_back(Value); 2977 } else if (!AnyErrors) { 2978 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 2979 CXXCtorInitializer *CXXBaseInit; 2980 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 2981 VBase, IsInheritedVirtualBase, 2982 CXXBaseInit)) { 2983 HadError = true; 2984 continue; 2985 } 2986 2987 Info.AllToInit.push_back(CXXBaseInit); 2988 } 2989 } 2990 2991 // Non-virtual bases. 2992 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2993 E = ClassDecl->bases_end(); Base != E; ++Base) { 2994 // Virtuals are in the virtual base list and already constructed. 2995 if (Base->isVirtual()) 2996 continue; 2997 2998 if (CXXCtorInitializer *Value 2999 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 3000 Info.AllToInit.push_back(Value); 3001 } else if (!AnyErrors) { 3002 CXXCtorInitializer *CXXBaseInit; 3003 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3004 Base, /*IsInheritedVirtualBase=*/false, 3005 CXXBaseInit)) { 3006 HadError = true; 3007 continue; 3008 } 3009 3010 Info.AllToInit.push_back(CXXBaseInit); 3011 } 3012 } 3013 3014 // Fields. 3015 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 3016 MemEnd = ClassDecl->decls_end(); 3017 Mem != MemEnd; ++Mem) { 3018 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 3019 // C++ [class.bit]p2: 3020 // A declaration for a bit-field that omits the identifier declares an 3021 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3022 // initialized. 3023 if (F->isUnnamedBitfield()) 3024 continue; 3025 3026 // If we're not generating the implicit copy/move constructor, then we'll 3027 // handle anonymous struct/union fields based on their individual 3028 // indirect fields. 3029 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default) 3030 continue; 3031 3032 if (CollectFieldInitializer(*this, Info, F)) 3033 HadError = true; 3034 continue; 3035 } 3036 3037 // Beyond this point, we only consider default initialization. 3038 if (Info.IIK != IIK_Default) 3039 continue; 3040 3041 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 3042 if (F->getType()->isIncompleteArrayType()) { 3043 assert(ClassDecl->hasFlexibleArrayMember() && 3044 "Incomplete array type is not valid"); 3045 continue; 3046 } 3047 3048 // Initialize each field of an anonymous struct individually. 3049 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3050 HadError = true; 3051 3052 continue; 3053 } 3054 } 3055 3056 NumInitializers = Info.AllToInit.size(); 3057 if (NumInitializers > 0) { 3058 Constructor->setNumCtorInitializers(NumInitializers); 3059 CXXCtorInitializer **baseOrMemberInitializers = 3060 new (Context) CXXCtorInitializer*[NumInitializers]; 3061 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3062 NumInitializers * sizeof(CXXCtorInitializer*)); 3063 Constructor->setCtorInitializers(baseOrMemberInitializers); 3064 3065 // Constructors implicitly reference the base and member 3066 // destructors. 3067 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3068 Constructor->getParent()); 3069 } 3070 3071 return HadError; 3072} 3073 3074static void *GetKeyForTopLevelField(FieldDecl *Field) { 3075 // For anonymous unions, use the class declaration as the key. 3076 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3077 if (RT->getDecl()->isAnonymousStructOrUnion()) 3078 return static_cast<void *>(RT->getDecl()); 3079 } 3080 return static_cast<void *>(Field); 3081} 3082 3083static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3084 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 3085} 3086 3087static void *GetKeyForMember(ASTContext &Context, 3088 CXXCtorInitializer *Member) { 3089 if (!Member->isAnyMemberInitializer()) 3090 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3091 3092 // For fields injected into the class via declaration of an anonymous union, 3093 // use its anonymous union class declaration as the unique key. 3094 FieldDecl *Field = Member->getAnyMember(); 3095 3096 // If the field is a member of an anonymous struct or union, our key 3097 // is the anonymous record decl that's a direct child of the class. 3098 RecordDecl *RD = Field->getParent(); 3099 if (RD->isAnonymousStructOrUnion()) { 3100 while (true) { 3101 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext()); 3102 if (Parent->isAnonymousStructOrUnion()) 3103 RD = Parent; 3104 else 3105 break; 3106 } 3107 3108 return static_cast<void *>(RD); 3109 } 3110 3111 return static_cast<void *>(Field); 3112} 3113 3114static void 3115DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, 3116 const CXXConstructorDecl *Constructor, 3117 CXXCtorInitializer **Inits, 3118 unsigned NumInits) { 3119 if (Constructor->getDeclContext()->isDependentContext()) 3120 return; 3121 3122 // Don't check initializers order unless the warning is enabled at the 3123 // location of at least one initializer. 3124 bool ShouldCheckOrder = false; 3125 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 3126 CXXCtorInitializer *Init = Inits[InitIndex]; 3127 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3128 Init->getSourceLocation()) 3129 != DiagnosticsEngine::Ignored) { 3130 ShouldCheckOrder = true; 3131 break; 3132 } 3133 } 3134 if (!ShouldCheckOrder) 3135 return; 3136 3137 // Build the list of bases and members in the order that they'll 3138 // actually be initialized. The explicit initializers should be in 3139 // this same order but may be missing things. 3140 SmallVector<const void*, 32> IdealInitKeys; 3141 3142 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3143 3144 // 1. Virtual bases. 3145 for (CXXRecordDecl::base_class_const_iterator VBase = 3146 ClassDecl->vbases_begin(), 3147 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3148 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3149 3150 // 2. Non-virtual bases. 3151 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3152 E = ClassDecl->bases_end(); Base != E; ++Base) { 3153 if (Base->isVirtual()) 3154 continue; 3155 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3156 } 3157 3158 // 3. Direct fields. 3159 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3160 E = ClassDecl->field_end(); Field != E; ++Field) { 3161 if (Field->isUnnamedBitfield()) 3162 continue; 3163 3164 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field)); 3165 } 3166 3167 unsigned NumIdealInits = IdealInitKeys.size(); 3168 unsigned IdealIndex = 0; 3169 3170 CXXCtorInitializer *PrevInit = 0; 3171 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 3172 CXXCtorInitializer *Init = Inits[InitIndex]; 3173 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3174 3175 // Scan forward to try to find this initializer in the idealized 3176 // initializers list. 3177 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3178 if (InitKey == IdealInitKeys[IdealIndex]) 3179 break; 3180 3181 // If we didn't find this initializer, it must be because we 3182 // scanned past it on a previous iteration. That can only 3183 // happen if we're out of order; emit a warning. 3184 if (IdealIndex == NumIdealInits && PrevInit) { 3185 Sema::SemaDiagnosticBuilder D = 3186 SemaRef.Diag(PrevInit->getSourceLocation(), 3187 diag::warn_initializer_out_of_order); 3188 3189 if (PrevInit->isAnyMemberInitializer()) 3190 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3191 else 3192 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3193 3194 if (Init->isAnyMemberInitializer()) 3195 D << 0 << Init->getAnyMember()->getDeclName(); 3196 else 3197 D << 1 << Init->getTypeSourceInfo()->getType(); 3198 3199 // Move back to the initializer's location in the ideal list. 3200 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3201 if (InitKey == IdealInitKeys[IdealIndex]) 3202 break; 3203 3204 assert(IdealIndex != NumIdealInits && 3205 "initializer not found in initializer list"); 3206 } 3207 3208 PrevInit = Init; 3209 } 3210} 3211 3212namespace { 3213bool CheckRedundantInit(Sema &S, 3214 CXXCtorInitializer *Init, 3215 CXXCtorInitializer *&PrevInit) { 3216 if (!PrevInit) { 3217 PrevInit = Init; 3218 return false; 3219 } 3220 3221 if (FieldDecl *Field = Init->getMember()) 3222 S.Diag(Init->getSourceLocation(), 3223 diag::err_multiple_mem_initialization) 3224 << Field->getDeclName() 3225 << Init->getSourceRange(); 3226 else { 3227 const Type *BaseClass = Init->getBaseClass(); 3228 assert(BaseClass && "neither field nor base"); 3229 S.Diag(Init->getSourceLocation(), 3230 diag::err_multiple_base_initialization) 3231 << QualType(BaseClass, 0) 3232 << Init->getSourceRange(); 3233 } 3234 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3235 << 0 << PrevInit->getSourceRange(); 3236 3237 return true; 3238} 3239 3240typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3241typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3242 3243bool CheckRedundantUnionInit(Sema &S, 3244 CXXCtorInitializer *Init, 3245 RedundantUnionMap &Unions) { 3246 FieldDecl *Field = Init->getAnyMember(); 3247 RecordDecl *Parent = Field->getParent(); 3248 NamedDecl *Child = Field; 3249 3250 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3251 if (Parent->isUnion()) { 3252 UnionEntry &En = Unions[Parent]; 3253 if (En.first && En.first != Child) { 3254 S.Diag(Init->getSourceLocation(), 3255 diag::err_multiple_mem_union_initialization) 3256 << Field->getDeclName() 3257 << Init->getSourceRange(); 3258 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3259 << 0 << En.second->getSourceRange(); 3260 return true; 3261 } 3262 if (!En.first) { 3263 En.first = Child; 3264 En.second = Init; 3265 } 3266 if (!Parent->isAnonymousStructOrUnion()) 3267 return false; 3268 } 3269 3270 Child = Parent; 3271 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3272 } 3273 3274 return false; 3275} 3276} 3277 3278/// ActOnMemInitializers - Handle the member initializers for a constructor. 3279void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3280 SourceLocation ColonLoc, 3281 CXXCtorInitializer **meminits, 3282 unsigned NumMemInits, 3283 bool AnyErrors) { 3284 if (!ConstructorDecl) 3285 return; 3286 3287 AdjustDeclIfTemplate(ConstructorDecl); 3288 3289 CXXConstructorDecl *Constructor 3290 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3291 3292 if (!Constructor) { 3293 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3294 return; 3295 } 3296 3297 CXXCtorInitializer **MemInits = 3298 reinterpret_cast<CXXCtorInitializer **>(meminits); 3299 3300 // Mapping for the duplicate initializers check. 3301 // For member initializers, this is keyed with a FieldDecl*. 3302 // For base initializers, this is keyed with a Type*. 3303 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 3304 3305 // Mapping for the inconsistent anonymous-union initializers check. 3306 RedundantUnionMap MemberUnions; 3307 3308 bool HadError = false; 3309 for (unsigned i = 0; i < NumMemInits; i++) { 3310 CXXCtorInitializer *Init = MemInits[i]; 3311 3312 // Set the source order index. 3313 Init->setSourceOrder(i); 3314 3315 if (Init->isAnyMemberInitializer()) { 3316 FieldDecl *Field = Init->getAnyMember(); 3317 if (CheckRedundantInit(*this, Init, Members[Field]) || 3318 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3319 HadError = true; 3320 } else if (Init->isBaseInitializer()) { 3321 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3322 if (CheckRedundantInit(*this, Init, Members[Key])) 3323 HadError = true; 3324 } else { 3325 assert(Init->isDelegatingInitializer()); 3326 // This must be the only initializer 3327 if (i != 0 || NumMemInits > 1) { 3328 Diag(MemInits[0]->getSourceLocation(), 3329 diag::err_delegating_initializer_alone) 3330 << MemInits[0]->getSourceRange(); 3331 HadError = true; 3332 // We will treat this as being the only initializer. 3333 } 3334 SetDelegatingInitializer(Constructor, MemInits[i]); 3335 // Return immediately as the initializer is set. 3336 return; 3337 } 3338 } 3339 3340 if (HadError) 3341 return; 3342 3343 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits); 3344 3345 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors); 3346} 3347 3348void 3349Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3350 CXXRecordDecl *ClassDecl) { 3351 // Ignore dependent contexts. Also ignore unions, since their members never 3352 // have destructors implicitly called. 3353 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3354 return; 3355 3356 // FIXME: all the access-control diagnostics are positioned on the 3357 // field/base declaration. That's probably good; that said, the 3358 // user might reasonably want to know why the destructor is being 3359 // emitted, and we currently don't say. 3360 3361 // Non-static data members. 3362 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3363 E = ClassDecl->field_end(); I != E; ++I) { 3364 FieldDecl *Field = *I; 3365 if (Field->isInvalidDecl()) 3366 continue; 3367 3368 // Don't destroy incomplete or zero-length arrays. 3369 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3370 continue; 3371 3372 QualType FieldType = Context.getBaseElementType(Field->getType()); 3373 3374 const RecordType* RT = FieldType->getAs<RecordType>(); 3375 if (!RT) 3376 continue; 3377 3378 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3379 if (FieldClassDecl->isInvalidDecl()) 3380 continue; 3381 if (FieldClassDecl->hasIrrelevantDestructor()) 3382 continue; 3383 // The destructor for an implicit anonymous union member is never invoked. 3384 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3385 continue; 3386 3387 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3388 assert(Dtor && "No dtor found for FieldClassDecl!"); 3389 CheckDestructorAccess(Field->getLocation(), Dtor, 3390 PDiag(diag::err_access_dtor_field) 3391 << Field->getDeclName() 3392 << FieldType); 3393 3394 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3395 DiagnoseUseOfDecl(Dtor, Location); 3396 } 3397 3398 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3399 3400 // Bases. 3401 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3402 E = ClassDecl->bases_end(); Base != E; ++Base) { 3403 // Bases are always records in a well-formed non-dependent class. 3404 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3405 3406 // Remember direct virtual bases. 3407 if (Base->isVirtual()) 3408 DirectVirtualBases.insert(RT); 3409 3410 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3411 // If our base class is invalid, we probably can't get its dtor anyway. 3412 if (BaseClassDecl->isInvalidDecl()) 3413 continue; 3414 if (BaseClassDecl->hasIrrelevantDestructor()) 3415 continue; 3416 3417 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3418 assert(Dtor && "No dtor found for BaseClassDecl!"); 3419 3420 // FIXME: caret should be on the start of the class name 3421 CheckDestructorAccess(Base->getLocStart(), Dtor, 3422 PDiag(diag::err_access_dtor_base) 3423 << Base->getType() 3424 << Base->getSourceRange(), 3425 Context.getTypeDeclType(ClassDecl)); 3426 3427 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3428 DiagnoseUseOfDecl(Dtor, Location); 3429 } 3430 3431 // Virtual bases. 3432 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3433 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3434 3435 // Bases are always records in a well-formed non-dependent class. 3436 const RecordType *RT = VBase->getType()->castAs<RecordType>(); 3437 3438 // Ignore direct virtual bases. 3439 if (DirectVirtualBases.count(RT)) 3440 continue; 3441 3442 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3443 // If our base class is invalid, we probably can't get its dtor anyway. 3444 if (BaseClassDecl->isInvalidDecl()) 3445 continue; 3446 if (BaseClassDecl->hasIrrelevantDestructor()) 3447 continue; 3448 3449 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3450 assert(Dtor && "No dtor found for BaseClassDecl!"); 3451 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 3452 PDiag(diag::err_access_dtor_vbase) 3453 << VBase->getType(), 3454 Context.getTypeDeclType(ClassDecl)); 3455 3456 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 3457 DiagnoseUseOfDecl(Dtor, Location); 3458 } 3459} 3460 3461void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 3462 if (!CDtorDecl) 3463 return; 3464 3465 if (CXXConstructorDecl *Constructor 3466 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 3467 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 3468} 3469 3470bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3471 unsigned DiagID, AbstractDiagSelID SelID) { 3472 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 3473 unsigned DiagID; 3474 AbstractDiagSelID SelID; 3475 3476 public: 3477 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 3478 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 3479 3480 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 3481 if (SelID == -1) 3482 S.Diag(Loc, DiagID) << T; 3483 else 3484 S.Diag(Loc, DiagID) << SelID << T; 3485 } 3486 } Diagnoser(DiagID, SelID); 3487 3488 return RequireNonAbstractType(Loc, T, Diagnoser); 3489} 3490 3491bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 3492 TypeDiagnoser &Diagnoser) { 3493 if (!getLangOpts().CPlusPlus) 3494 return false; 3495 3496 if (const ArrayType *AT = Context.getAsArrayType(T)) 3497 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3498 3499 if (const PointerType *PT = T->getAs<PointerType>()) { 3500 // Find the innermost pointer type. 3501 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 3502 PT = T; 3503 3504 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 3505 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 3506 } 3507 3508 const RecordType *RT = T->getAs<RecordType>(); 3509 if (!RT) 3510 return false; 3511 3512 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3513 3514 // We can't answer whether something is abstract until it has a 3515 // definition. If it's currently being defined, we'll walk back 3516 // over all the declarations when we have a full definition. 3517 const CXXRecordDecl *Def = RD->getDefinition(); 3518 if (!Def || Def->isBeingDefined()) 3519 return false; 3520 3521 if (!RD->isAbstract()) 3522 return false; 3523 3524 Diagnoser.diagnose(*this, Loc, T); 3525 DiagnoseAbstractType(RD); 3526 3527 return true; 3528} 3529 3530void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 3531 // Check if we've already emitted the list of pure virtual functions 3532 // for this class. 3533 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 3534 return; 3535 3536 CXXFinalOverriderMap FinalOverriders; 3537 RD->getFinalOverriders(FinalOverriders); 3538 3539 // Keep a set of seen pure methods so we won't diagnose the same method 3540 // more than once. 3541 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 3542 3543 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 3544 MEnd = FinalOverriders.end(); 3545 M != MEnd; 3546 ++M) { 3547 for (OverridingMethods::iterator SO = M->second.begin(), 3548 SOEnd = M->second.end(); 3549 SO != SOEnd; ++SO) { 3550 // C++ [class.abstract]p4: 3551 // A class is abstract if it contains or inherits at least one 3552 // pure virtual function for which the final overrider is pure 3553 // virtual. 3554 3555 // 3556 if (SO->second.size() != 1) 3557 continue; 3558 3559 if (!SO->second.front().Method->isPure()) 3560 continue; 3561 3562 if (!SeenPureMethods.insert(SO->second.front().Method)) 3563 continue; 3564 3565 Diag(SO->second.front().Method->getLocation(), 3566 diag::note_pure_virtual_function) 3567 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 3568 } 3569 } 3570 3571 if (!PureVirtualClassDiagSet) 3572 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 3573 PureVirtualClassDiagSet->insert(RD); 3574} 3575 3576namespace { 3577struct AbstractUsageInfo { 3578 Sema &S; 3579 CXXRecordDecl *Record; 3580 CanQualType AbstractType; 3581 bool Invalid; 3582 3583 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 3584 : S(S), Record(Record), 3585 AbstractType(S.Context.getCanonicalType( 3586 S.Context.getTypeDeclType(Record))), 3587 Invalid(false) {} 3588 3589 void DiagnoseAbstractType() { 3590 if (Invalid) return; 3591 S.DiagnoseAbstractType(Record); 3592 Invalid = true; 3593 } 3594 3595 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 3596}; 3597 3598struct CheckAbstractUsage { 3599 AbstractUsageInfo &Info; 3600 const NamedDecl *Ctx; 3601 3602 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 3603 : Info(Info), Ctx(Ctx) {} 3604 3605 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3606 switch (TL.getTypeLocClass()) { 3607#define ABSTRACT_TYPELOC(CLASS, PARENT) 3608#define TYPELOC(CLASS, PARENT) \ 3609 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break; 3610#include "clang/AST/TypeLocNodes.def" 3611 } 3612 } 3613 3614 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3615 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 3616 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3617 if (!TL.getArg(I)) 3618 continue; 3619 3620 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 3621 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 3622 } 3623 } 3624 3625 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3626 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 3627 } 3628 3629 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 3630 // Visit the type parameters from a permissive context. 3631 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 3632 TemplateArgumentLoc TAL = TL.getArgLoc(I); 3633 if (TAL.getArgument().getKind() == TemplateArgument::Type) 3634 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 3635 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 3636 // TODO: other template argument types? 3637 } 3638 } 3639 3640 // Visit pointee types from a permissive context. 3641#define CheckPolymorphic(Type) \ 3642 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 3643 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 3644 } 3645 CheckPolymorphic(PointerTypeLoc) 3646 CheckPolymorphic(ReferenceTypeLoc) 3647 CheckPolymorphic(MemberPointerTypeLoc) 3648 CheckPolymorphic(BlockPointerTypeLoc) 3649 CheckPolymorphic(AtomicTypeLoc) 3650 3651 /// Handle all the types we haven't given a more specific 3652 /// implementation for above. 3653 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 3654 // Every other kind of type that we haven't called out already 3655 // that has an inner type is either (1) sugar or (2) contains that 3656 // inner type in some way as a subobject. 3657 if (TypeLoc Next = TL.getNextTypeLoc()) 3658 return Visit(Next, Sel); 3659 3660 // If there's no inner type and we're in a permissive context, 3661 // don't diagnose. 3662 if (Sel == Sema::AbstractNone) return; 3663 3664 // Check whether the type matches the abstract type. 3665 QualType T = TL.getType(); 3666 if (T->isArrayType()) { 3667 Sel = Sema::AbstractArrayType; 3668 T = Info.S.Context.getBaseElementType(T); 3669 } 3670 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 3671 if (CT != Info.AbstractType) return; 3672 3673 // It matched; do some magic. 3674 if (Sel == Sema::AbstractArrayType) { 3675 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 3676 << T << TL.getSourceRange(); 3677 } else { 3678 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 3679 << Sel << T << TL.getSourceRange(); 3680 } 3681 Info.DiagnoseAbstractType(); 3682 } 3683}; 3684 3685void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 3686 Sema::AbstractDiagSelID Sel) { 3687 CheckAbstractUsage(*this, D).Visit(TL, Sel); 3688} 3689 3690} 3691 3692/// Check for invalid uses of an abstract type in a method declaration. 3693static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3694 CXXMethodDecl *MD) { 3695 // No need to do the check on definitions, which require that 3696 // the return/param types be complete. 3697 if (MD->doesThisDeclarationHaveABody()) 3698 return; 3699 3700 // For safety's sake, just ignore it if we don't have type source 3701 // information. This should never happen for non-implicit methods, 3702 // but... 3703 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 3704 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 3705} 3706 3707/// Check for invalid uses of an abstract type within a class definition. 3708static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 3709 CXXRecordDecl *RD) { 3710 for (CXXRecordDecl::decl_iterator 3711 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 3712 Decl *D = *I; 3713 if (D->isImplicit()) continue; 3714 3715 // Methods and method templates. 3716 if (isa<CXXMethodDecl>(D)) { 3717 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 3718 } else if (isa<FunctionTemplateDecl>(D)) { 3719 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 3720 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 3721 3722 // Fields and static variables. 3723 } else if (isa<FieldDecl>(D)) { 3724 FieldDecl *FD = cast<FieldDecl>(D); 3725 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 3726 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 3727 } else if (isa<VarDecl>(D)) { 3728 VarDecl *VD = cast<VarDecl>(D); 3729 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 3730 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 3731 3732 // Nested classes and class templates. 3733 } else if (isa<CXXRecordDecl>(D)) { 3734 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 3735 } else if (isa<ClassTemplateDecl>(D)) { 3736 CheckAbstractClassUsage(Info, 3737 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 3738 } 3739 } 3740} 3741 3742/// \brief Perform semantic checks on a class definition that has been 3743/// completing, introducing implicitly-declared members, checking for 3744/// abstract types, etc. 3745void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 3746 if (!Record) 3747 return; 3748 3749 if (Record->isAbstract() && !Record->isInvalidDecl()) { 3750 AbstractUsageInfo Info(*this, Record); 3751 CheckAbstractClassUsage(Info, Record); 3752 } 3753 3754 // If this is not an aggregate type and has no user-declared constructor, 3755 // complain about any non-static data members of reference or const scalar 3756 // type, since they will never get initializers. 3757 if (!Record->isInvalidDecl() && !Record->isDependentType() && 3758 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 3759 !Record->isLambda()) { 3760 bool Complained = false; 3761 for (RecordDecl::field_iterator F = Record->field_begin(), 3762 FEnd = Record->field_end(); 3763 F != FEnd; ++F) { 3764 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 3765 continue; 3766 3767 if (F->getType()->isReferenceType() || 3768 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 3769 if (!Complained) { 3770 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 3771 << Record->getTagKind() << Record; 3772 Complained = true; 3773 } 3774 3775 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 3776 << F->getType()->isReferenceType() 3777 << F->getDeclName(); 3778 } 3779 } 3780 } 3781 3782 if (Record->isDynamicClass() && !Record->isDependentType()) 3783 DynamicClasses.push_back(Record); 3784 3785 if (Record->getIdentifier()) { 3786 // C++ [class.mem]p13: 3787 // If T is the name of a class, then each of the following shall have a 3788 // name different from T: 3789 // - every member of every anonymous union that is a member of class T. 3790 // 3791 // C++ [class.mem]p14: 3792 // In addition, if class T has a user-declared constructor (12.1), every 3793 // non-static data member of class T shall have a name different from T. 3794 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 3795 R.first != R.second; ++R.first) { 3796 NamedDecl *D = *R.first; 3797 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 3798 isa<IndirectFieldDecl>(D)) { 3799 Diag(D->getLocation(), diag::err_member_name_of_class) 3800 << D->getDeclName(); 3801 break; 3802 } 3803 } 3804 } 3805 3806 // Warn if the class has virtual methods but non-virtual public destructor. 3807 if (Record->isPolymorphic() && !Record->isDependentType()) { 3808 CXXDestructorDecl *dtor = Record->getDestructor(); 3809 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 3810 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 3811 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 3812 } 3813 3814 // See if a method overloads virtual methods in a base 3815 /// class without overriding any. 3816 if (!Record->isDependentType()) { 3817 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 3818 MEnd = Record->method_end(); 3819 M != MEnd; ++M) { 3820 if (!M->isStatic()) 3821 DiagnoseHiddenVirtualMethods(Record, *M); 3822 } 3823 } 3824 3825 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member 3826 // function that is not a constructor declares that member function to be 3827 // const. [...] The class of which that function is a member shall be 3828 // a literal type. 3829 // 3830 // If the class has virtual bases, any constexpr members will already have 3831 // been diagnosed by the checks performed on the member declaration, so 3832 // suppress this (less useful) diagnostic. 3833 if (LangOpts.CPlusPlus0x && !Record->isDependentType() && 3834 !Record->isLiteral() && !Record->getNumVBases()) { 3835 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 3836 MEnd = Record->method_end(); 3837 M != MEnd; ++M) { 3838 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 3839 switch (Record->getTemplateSpecializationKind()) { 3840 case TSK_ImplicitInstantiation: 3841 case TSK_ExplicitInstantiationDeclaration: 3842 case TSK_ExplicitInstantiationDefinition: 3843 // If a template instantiates to a non-literal type, but its members 3844 // instantiate to constexpr functions, the template is technically 3845 // ill-formed, but we allow it for sanity. 3846 continue; 3847 3848 case TSK_Undeclared: 3849 case TSK_ExplicitSpecialization: 3850 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 3851 diag::err_constexpr_method_non_literal); 3852 break; 3853 } 3854 3855 // Only produce one error per class. 3856 break; 3857 } 3858 } 3859 } 3860 3861 // Declare inherited constructors. We do this eagerly here because: 3862 // - The standard requires an eager diagnostic for conflicting inherited 3863 // constructors from different classes. 3864 // - The lazy declaration of the other implicit constructors is so as to not 3865 // waste space and performance on classes that are not meant to be 3866 // instantiated (e.g. meta-functions). This doesn't apply to classes that 3867 // have inherited constructors. 3868 DeclareInheritedConstructors(Record); 3869} 3870 3871void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) { 3872 for (CXXRecordDecl::method_iterator MI = Record->method_begin(), 3873 ME = Record->method_end(); 3874 MI != ME; ++MI) 3875 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) 3876 CheckExplicitlyDefaultedSpecialMember(*MI); 3877} 3878 3879/// Is the special member function which would be selected to perform the 3880/// specified operation on the specified class type a constexpr constructor? 3881static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 3882 Sema::CXXSpecialMember CSM, 3883 bool ConstArg) { 3884 Sema::SpecialMemberOverloadResult *SMOR = 3885 S.LookupSpecialMember(ClassDecl, CSM, ConstArg, 3886 false, false, false, false); 3887 if (!SMOR || !SMOR->getMethod()) 3888 // A constructor we wouldn't select can't be "involved in initializing" 3889 // anything. 3890 return true; 3891 return SMOR->getMethod()->isConstexpr(); 3892} 3893 3894/// Determine whether the specified special member function would be constexpr 3895/// if it were implicitly defined. 3896static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 3897 Sema::CXXSpecialMember CSM, 3898 bool ConstArg) { 3899 if (!S.getLangOpts().CPlusPlus0x) 3900 return false; 3901 3902 // C++11 [dcl.constexpr]p4: 3903 // In the definition of a constexpr constructor [...] 3904 switch (CSM) { 3905 case Sema::CXXDefaultConstructor: 3906 // Since default constructor lookup is essentially trivial (and cannot 3907 // involve, for instance, template instantiation), we compute whether a 3908 // defaulted default constructor is constexpr directly within CXXRecordDecl. 3909 // 3910 // This is important for performance; we need to know whether the default 3911 // constructor is constexpr to determine whether the type is a literal type. 3912 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 3913 3914 case Sema::CXXCopyConstructor: 3915 case Sema::CXXMoveConstructor: 3916 // For copy or move constructors, we need to perform overload resolution. 3917 break; 3918 3919 case Sema::CXXCopyAssignment: 3920 case Sema::CXXMoveAssignment: 3921 case Sema::CXXDestructor: 3922 case Sema::CXXInvalid: 3923 return false; 3924 } 3925 3926 // -- if the class is a non-empty union, or for each non-empty anonymous 3927 // union member of a non-union class, exactly one non-static data member 3928 // shall be initialized; [DR1359] 3929 // 3930 // If we squint, this is guaranteed, since exactly one non-static data member 3931 // will be initialized (if the constructor isn't deleted), we just don't know 3932 // which one. 3933 if (ClassDecl->isUnion()) 3934 return true; 3935 3936 // -- the class shall not have any virtual base classes; 3937 if (ClassDecl->getNumVBases()) 3938 return false; 3939 3940 // -- every constructor involved in initializing [...] base class 3941 // sub-objects shall be a constexpr constructor; 3942 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 3943 BEnd = ClassDecl->bases_end(); 3944 B != BEnd; ++B) { 3945 const RecordType *BaseType = B->getType()->getAs<RecordType>(); 3946 if (!BaseType) continue; 3947 3948 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 3949 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg)) 3950 return false; 3951 } 3952 3953 // -- every constructor involved in initializing non-static data members 3954 // [...] shall be a constexpr constructor; 3955 // -- every non-static data member and base class sub-object shall be 3956 // initialized 3957 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 3958 FEnd = ClassDecl->field_end(); 3959 F != FEnd; ++F) { 3960 if (F->isInvalidDecl()) 3961 continue; 3962 if (const RecordType *RecordTy = 3963 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 3964 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 3965 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg)) 3966 return false; 3967 } 3968 } 3969 3970 // All OK, it's constexpr! 3971 return true; 3972} 3973 3974static Sema::ImplicitExceptionSpecification 3975computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 3976 switch (S.getSpecialMember(MD)) { 3977 case Sema::CXXDefaultConstructor: 3978 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 3979 case Sema::CXXCopyConstructor: 3980 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 3981 case Sema::CXXCopyAssignment: 3982 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 3983 case Sema::CXXMoveConstructor: 3984 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 3985 case Sema::CXXMoveAssignment: 3986 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 3987 case Sema::CXXDestructor: 3988 return S.ComputeDefaultedDtorExceptionSpec(MD); 3989 case Sema::CXXInvalid: 3990 break; 3991 } 3992 llvm_unreachable("only special members have implicit exception specs"); 3993} 3994 3995static void 3996updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT, 3997 const Sema::ImplicitExceptionSpecification &ExceptSpec) { 3998 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 3999 ExceptSpec.getEPI(EPI); 4000 const FunctionProtoType *NewFPT = cast<FunctionProtoType>( 4001 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(), 4002 FPT->getNumArgs(), EPI)); 4003 FD->setType(QualType(NewFPT, 0)); 4004} 4005 4006void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4007 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4008 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4009 return; 4010 4011 // Evaluate the exception specification. 4012 ImplicitExceptionSpecification ExceptSpec = 4013 computeImplicitExceptionSpec(*this, Loc, MD); 4014 4015 // Update the type of the special member to use it. 4016 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4017 4018 // A user-provided destructor can be defined outside the class. When that 4019 // happens, be sure to update the exception specification on both 4020 // declarations. 4021 const FunctionProtoType *CanonicalFPT = 4022 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4023 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4024 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4025 CanonicalFPT, ExceptSpec); 4026} 4027 4028static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl); 4029static bool isImplicitCopyAssignmentArgConst(Sema &S, CXXRecordDecl *ClassDecl); 4030 4031void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4032 CXXRecordDecl *RD = MD->getParent(); 4033 CXXSpecialMember CSM = getSpecialMember(MD); 4034 4035 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4036 "not an explicitly-defaulted special member"); 4037 4038 // Whether this was the first-declared instance of the constructor. 4039 // This affects whether we implicitly add an exception spec and constexpr. 4040 bool First = MD == MD->getCanonicalDecl(); 4041 4042 bool HadError = false; 4043 4044 // C++11 [dcl.fct.def.default]p1: 4045 // A function that is explicitly defaulted shall 4046 // -- be a special member function (checked elsewhere), 4047 // -- have the same type (except for ref-qualifiers, and except that a 4048 // copy operation can take a non-const reference) as an implicit 4049 // declaration, and 4050 // -- not have default arguments. 4051 unsigned ExpectedParams = 1; 4052 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4053 ExpectedParams = 0; 4054 if (MD->getNumParams() != ExpectedParams) { 4055 // This also checks for default arguments: a copy or move constructor with a 4056 // default argument is classified as a default constructor, and assignment 4057 // operations and destructors can't have default arguments. 4058 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4059 << CSM << MD->getSourceRange(); 4060 HadError = true; 4061 } 4062 4063 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4064 4065 // Compute argument constness, constexpr, and triviality. 4066 bool CanHaveConstParam = false; 4067 bool Trivial; 4068 switch (CSM) { 4069 case CXXDefaultConstructor: 4070 Trivial = RD->hasTrivialDefaultConstructor(); 4071 break; 4072 case CXXCopyConstructor: 4073 CanHaveConstParam = isImplicitCopyCtorArgConst(*this, RD); 4074 Trivial = RD->hasTrivialCopyConstructor(); 4075 break; 4076 case CXXCopyAssignment: 4077 CanHaveConstParam = isImplicitCopyAssignmentArgConst(*this, RD); 4078 Trivial = RD->hasTrivialCopyAssignment(); 4079 break; 4080 case CXXMoveConstructor: 4081 Trivial = RD->hasTrivialMoveConstructor(); 4082 break; 4083 case CXXMoveAssignment: 4084 Trivial = RD->hasTrivialMoveAssignment(); 4085 break; 4086 case CXXDestructor: 4087 Trivial = RD->hasTrivialDestructor(); 4088 break; 4089 case CXXInvalid: 4090 llvm_unreachable("non-special member explicitly defaulted!"); 4091 } 4092 4093 QualType ReturnType = Context.VoidTy; 4094 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4095 // Check for return type matching. 4096 ReturnType = Type->getResultType(); 4097 QualType ExpectedReturnType = 4098 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4099 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4100 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4101 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4102 HadError = true; 4103 } 4104 4105 // A defaulted special member cannot have cv-qualifiers. 4106 if (Type->getTypeQuals()) { 4107 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4108 << (CSM == CXXMoveAssignment); 4109 HadError = true; 4110 } 4111 } 4112 4113 // Check for parameter type matching. 4114 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType(); 4115 bool HasConstParam = false; 4116 if (ExpectedParams && ArgType->isReferenceType()) { 4117 // Argument must be reference to possibly-const T. 4118 QualType ReferentType = ArgType->getPointeeType(); 4119 HasConstParam = ReferentType.isConstQualified(); 4120 4121 if (ReferentType.isVolatileQualified()) { 4122 Diag(MD->getLocation(), 4123 diag::err_defaulted_special_member_volatile_param) << CSM; 4124 HadError = true; 4125 } 4126 4127 if (HasConstParam && !CanHaveConstParam) { 4128 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4129 Diag(MD->getLocation(), 4130 diag::err_defaulted_special_member_copy_const_param) 4131 << (CSM == CXXCopyAssignment); 4132 // FIXME: Explain why this special member can't be const. 4133 } else { 4134 Diag(MD->getLocation(), 4135 diag::err_defaulted_special_member_move_const_param) 4136 << (CSM == CXXMoveAssignment); 4137 } 4138 HadError = true; 4139 } 4140 4141 // If a function is explicitly defaulted on its first declaration, it shall 4142 // have the same parameter type as if it had been implicitly declared. 4143 // (Presumably this is to prevent it from being trivial?) 4144 if (!HasConstParam && CanHaveConstParam && First) 4145 Diag(MD->getLocation(), 4146 diag::err_defaulted_special_member_copy_non_const_param) 4147 << (CSM == CXXCopyAssignment); 4148 } else if (ExpectedParams) { 4149 // A copy assignment operator can take its argument by value, but a 4150 // defaulted one cannot. 4151 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4152 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4153 HadError = true; 4154 } 4155 4156 // Rebuild the type with the implicit exception specification added, if we 4157 // are going to need it. 4158 const FunctionProtoType *ImplicitType = 0; 4159 if (First || Type->hasExceptionSpec()) { 4160 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4161 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4162 ImplicitType = cast<FunctionProtoType>( 4163 Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI)); 4164 } 4165 4166 // C++11 [dcl.fct.def.default]p2: 4167 // An explicitly-defaulted function may be declared constexpr only if it 4168 // would have been implicitly declared as constexpr, 4169 // Do not apply this rule to members of class templates, since core issue 1358 4170 // makes such functions always instantiate to constexpr functions. For 4171 // non-constructors, this is checked elsewhere. 4172 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4173 HasConstParam); 4174 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr && 4175 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4176 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4177 // FIXME: Explain why the constructor can't be constexpr. 4178 HadError = true; 4179 } 4180 // and may have an explicit exception-specification only if it is compatible 4181 // with the exception-specification on the implicit declaration. 4182 if (Type->hasExceptionSpec() && 4183 CheckEquivalentExceptionSpec( 4184 PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM, 4185 PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation())) 4186 HadError = true; 4187 4188 // If a function is explicitly defaulted on its first declaration, 4189 if (First) { 4190 // -- it is implicitly considered to be constexpr if the implicit 4191 // definition would be, 4192 MD->setConstexpr(Constexpr); 4193 4194 // -- it is implicitly considered to have the same exception-specification 4195 // as if it had been implicitly declared, 4196 MD->setType(QualType(ImplicitType, 0)); 4197 4198 // Such a function is also trivial if the implicitly-declared function 4199 // would have been. 4200 MD->setTrivial(Trivial); 4201 } 4202 4203 if (ShouldDeleteSpecialMember(MD, CSM)) { 4204 if (First) { 4205 MD->setDeletedAsWritten(); 4206 } else { 4207 // C++11 [dcl.fct.def.default]p4: 4208 // [For a] user-provided explicitly-defaulted function [...] if such a 4209 // function is implicitly defined as deleted, the program is ill-formed. 4210 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4211 HadError = true; 4212 } 4213 } 4214 4215 if (HadError) 4216 MD->setInvalidDecl(); 4217} 4218 4219namespace { 4220struct SpecialMemberDeletionInfo { 4221 Sema &S; 4222 CXXMethodDecl *MD; 4223 Sema::CXXSpecialMember CSM; 4224 bool Diagnose; 4225 4226 // Properties of the special member, computed for convenience. 4227 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg; 4228 SourceLocation Loc; 4229 4230 bool AllFieldsAreConst; 4231 4232 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4233 Sema::CXXSpecialMember CSM, bool Diagnose) 4234 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4235 IsConstructor(false), IsAssignment(false), IsMove(false), 4236 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()), 4237 AllFieldsAreConst(true) { 4238 switch (CSM) { 4239 case Sema::CXXDefaultConstructor: 4240 case Sema::CXXCopyConstructor: 4241 IsConstructor = true; 4242 break; 4243 case Sema::CXXMoveConstructor: 4244 IsConstructor = true; 4245 IsMove = true; 4246 break; 4247 case Sema::CXXCopyAssignment: 4248 IsAssignment = true; 4249 break; 4250 case Sema::CXXMoveAssignment: 4251 IsAssignment = true; 4252 IsMove = true; 4253 break; 4254 case Sema::CXXDestructor: 4255 break; 4256 case Sema::CXXInvalid: 4257 llvm_unreachable("invalid special member kind"); 4258 } 4259 4260 if (MD->getNumParams()) { 4261 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4262 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified(); 4263 } 4264 } 4265 4266 bool inUnion() const { return MD->getParent()->isUnion(); } 4267 4268 /// Look up the corresponding special member in the given class. 4269 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4270 unsigned Quals) { 4271 unsigned TQ = MD->getTypeQualifiers(); 4272 // cv-qualifiers on class members don't affect default ctor / dtor calls. 4273 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4274 Quals = 0; 4275 return S.LookupSpecialMember(Class, CSM, 4276 ConstArg || (Quals & Qualifiers::Const), 4277 VolatileArg || (Quals & Qualifiers::Volatile), 4278 MD->getRefQualifier() == RQ_RValue, 4279 TQ & Qualifiers::Const, 4280 TQ & Qualifiers::Volatile); 4281 } 4282 4283 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4284 4285 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4286 bool shouldDeleteForField(FieldDecl *FD); 4287 bool shouldDeleteForAllConstMembers(); 4288 4289 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4290 unsigned Quals); 4291 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4292 Sema::SpecialMemberOverloadResult *SMOR, 4293 bool IsDtorCallInCtor); 4294 4295 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4296}; 4297} 4298 4299/// Is the given special member inaccessible when used on the given 4300/// sub-object. 4301bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4302 CXXMethodDecl *target) { 4303 /// If we're operating on a base class, the object type is the 4304 /// type of this special member. 4305 QualType objectTy; 4306 AccessSpecifier access = target->getAccess();; 4307 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 4308 objectTy = S.Context.getTypeDeclType(MD->getParent()); 4309 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 4310 4311 // If we're operating on a field, the object type is the type of the field. 4312 } else { 4313 objectTy = S.Context.getTypeDeclType(target->getParent()); 4314 } 4315 4316 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 4317} 4318 4319/// Check whether we should delete a special member due to the implicit 4320/// definition containing a call to a special member of a subobject. 4321bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 4322 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 4323 bool IsDtorCallInCtor) { 4324 CXXMethodDecl *Decl = SMOR->getMethod(); 4325 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4326 4327 int DiagKind = -1; 4328 4329 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 4330 DiagKind = !Decl ? 0 : 1; 4331 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4332 DiagKind = 2; 4333 else if (!isAccessible(Subobj, Decl)) 4334 DiagKind = 3; 4335 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 4336 !Decl->isTrivial()) { 4337 // A member of a union must have a trivial corresponding special member. 4338 // As a weird special case, a destructor call from a union's constructor 4339 // must be accessible and non-deleted, but need not be trivial. Such a 4340 // destructor is never actually called, but is semantically checked as 4341 // if it were. 4342 DiagKind = 4; 4343 } 4344 4345 if (DiagKind == -1) 4346 return false; 4347 4348 if (Diagnose) { 4349 if (Field) { 4350 S.Diag(Field->getLocation(), 4351 diag::note_deleted_special_member_class_subobject) 4352 << CSM << MD->getParent() << /*IsField*/true 4353 << Field << DiagKind << IsDtorCallInCtor; 4354 } else { 4355 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 4356 S.Diag(Base->getLocStart(), 4357 diag::note_deleted_special_member_class_subobject) 4358 << CSM << MD->getParent() << /*IsField*/false 4359 << Base->getType() << DiagKind << IsDtorCallInCtor; 4360 } 4361 4362 if (DiagKind == 1) 4363 S.NoteDeletedFunction(Decl); 4364 // FIXME: Explain inaccessibility if DiagKind == 3. 4365 } 4366 4367 return true; 4368} 4369 4370/// Check whether we should delete a special member function due to having a 4371/// direct or virtual base class or non-static data member of class type M. 4372bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 4373 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 4374 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4375 4376 // C++11 [class.ctor]p5: 4377 // -- any direct or virtual base class, or non-static data member with no 4378 // brace-or-equal-initializer, has class type M (or array thereof) and 4379 // either M has no default constructor or overload resolution as applied 4380 // to M's default constructor results in an ambiguity or in a function 4381 // that is deleted or inaccessible 4382 // C++11 [class.copy]p11, C++11 [class.copy]p23: 4383 // -- a direct or virtual base class B that cannot be copied/moved because 4384 // overload resolution, as applied to B's corresponding special member, 4385 // results in an ambiguity or a function that is deleted or inaccessible 4386 // from the defaulted special member 4387 // C++11 [class.dtor]p5: 4388 // -- any direct or virtual base class [...] has a type with a destructor 4389 // that is deleted or inaccessible 4390 if (!(CSM == Sema::CXXDefaultConstructor && 4391 Field && Field->hasInClassInitializer()) && 4392 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false)) 4393 return true; 4394 4395 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 4396 // -- any direct or virtual base class or non-static data member has a 4397 // type with a destructor that is deleted or inaccessible 4398 if (IsConstructor) { 4399 Sema::SpecialMemberOverloadResult *SMOR = 4400 S.LookupSpecialMember(Class, Sema::CXXDestructor, 4401 false, false, false, false, false); 4402 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 4403 return true; 4404 } 4405 4406 return false; 4407} 4408 4409/// Check whether we should delete a special member function due to the class 4410/// having a particular direct or virtual base class. 4411bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 4412 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 4413 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 4414} 4415 4416/// Check whether we should delete a special member function due to the class 4417/// having a particular non-static data member. 4418bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 4419 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 4420 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 4421 4422 if (CSM == Sema::CXXDefaultConstructor) { 4423 // For a default constructor, all references must be initialized in-class 4424 // and, if a union, it must have a non-const member. 4425 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 4426 if (Diagnose) 4427 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4428 << MD->getParent() << FD << FieldType << /*Reference*/0; 4429 return true; 4430 } 4431 // C++11 [class.ctor]p5: any non-variant non-static data member of 4432 // const-qualified type (or array thereof) with no 4433 // brace-or-equal-initializer does not have a user-provided default 4434 // constructor. 4435 if (!inUnion() && FieldType.isConstQualified() && 4436 !FD->hasInClassInitializer() && 4437 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 4438 if (Diagnose) 4439 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 4440 << MD->getParent() << FD << FD->getType() << /*Const*/1; 4441 return true; 4442 } 4443 4444 if (inUnion() && !FieldType.isConstQualified()) 4445 AllFieldsAreConst = false; 4446 } else if (CSM == Sema::CXXCopyConstructor) { 4447 // For a copy constructor, data members must not be of rvalue reference 4448 // type. 4449 if (FieldType->isRValueReferenceType()) { 4450 if (Diagnose) 4451 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 4452 << MD->getParent() << FD << FieldType; 4453 return true; 4454 } 4455 } else if (IsAssignment) { 4456 // For an assignment operator, data members must not be of reference type. 4457 if (FieldType->isReferenceType()) { 4458 if (Diagnose) 4459 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4460 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 4461 return true; 4462 } 4463 if (!FieldRecord && FieldType.isConstQualified()) { 4464 // C++11 [class.copy]p23: 4465 // -- a non-static data member of const non-class type (or array thereof) 4466 if (Diagnose) 4467 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 4468 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 4469 return true; 4470 } 4471 } 4472 4473 if (FieldRecord) { 4474 // Some additional restrictions exist on the variant members. 4475 if (!inUnion() && FieldRecord->isUnion() && 4476 FieldRecord->isAnonymousStructOrUnion()) { 4477 bool AllVariantFieldsAreConst = true; 4478 4479 // FIXME: Handle anonymous unions declared within anonymous unions. 4480 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 4481 UE = FieldRecord->field_end(); 4482 UI != UE; ++UI) { 4483 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 4484 4485 if (!UnionFieldType.isConstQualified()) 4486 AllVariantFieldsAreConst = false; 4487 4488 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 4489 if (UnionFieldRecord && 4490 shouldDeleteForClassSubobject(UnionFieldRecord, *UI, 4491 UnionFieldType.getCVRQualifiers())) 4492 return true; 4493 } 4494 4495 // At least one member in each anonymous union must be non-const 4496 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 4497 FieldRecord->field_begin() != FieldRecord->field_end()) { 4498 if (Diagnose) 4499 S.Diag(FieldRecord->getLocation(), 4500 diag::note_deleted_default_ctor_all_const) 4501 << MD->getParent() << /*anonymous union*/1; 4502 return true; 4503 } 4504 4505 // Don't check the implicit member of the anonymous union type. 4506 // This is technically non-conformant, but sanity demands it. 4507 return false; 4508 } 4509 4510 if (shouldDeleteForClassSubobject(FieldRecord, FD, 4511 FieldType.getCVRQualifiers())) 4512 return true; 4513 } 4514 4515 return false; 4516} 4517 4518/// C++11 [class.ctor] p5: 4519/// A defaulted default constructor for a class X is defined as deleted if 4520/// X is a union and all of its variant members are of const-qualified type. 4521bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 4522 // This is a silly definition, because it gives an empty union a deleted 4523 // default constructor. Don't do that. 4524 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 4525 (MD->getParent()->field_begin() != MD->getParent()->field_end())) { 4526 if (Diagnose) 4527 S.Diag(MD->getParent()->getLocation(), 4528 diag::note_deleted_default_ctor_all_const) 4529 << MD->getParent() << /*not anonymous union*/0; 4530 return true; 4531 } 4532 return false; 4533} 4534 4535/// Determine whether a defaulted special member function should be defined as 4536/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 4537/// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 4538bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 4539 bool Diagnose) { 4540 if (MD->isInvalidDecl()) 4541 return false; 4542 CXXRecordDecl *RD = MD->getParent(); 4543 assert(!RD->isDependentType() && "do deletion after instantiation"); 4544 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl()) 4545 return false; 4546 4547 // C++11 [expr.lambda.prim]p19: 4548 // The closure type associated with a lambda-expression has a 4549 // deleted (8.4.3) default constructor and a deleted copy 4550 // assignment operator. 4551 if (RD->isLambda() && 4552 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 4553 if (Diagnose) 4554 Diag(RD->getLocation(), diag::note_lambda_decl); 4555 return true; 4556 } 4557 4558 // For an anonymous struct or union, the copy and assignment special members 4559 // will never be used, so skip the check. For an anonymous union declared at 4560 // namespace scope, the constructor and destructor are used. 4561 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 4562 RD->isAnonymousStructOrUnion()) 4563 return false; 4564 4565 // C++11 [class.copy]p7, p18: 4566 // If the class definition declares a move constructor or move assignment 4567 // operator, an implicitly declared copy constructor or copy assignment 4568 // operator is defined as deleted. 4569 if (MD->isImplicit() && 4570 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 4571 CXXMethodDecl *UserDeclaredMove = 0; 4572 4573 // In Microsoft mode, a user-declared move only causes the deletion of the 4574 // corresponding copy operation, not both copy operations. 4575 if (RD->hasUserDeclaredMoveConstructor() && 4576 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) { 4577 if (!Diagnose) return true; 4578 UserDeclaredMove = RD->getMoveConstructor(); 4579 assert(UserDeclaredMove); 4580 } else if (RD->hasUserDeclaredMoveAssignment() && 4581 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) { 4582 if (!Diagnose) return true; 4583 UserDeclaredMove = RD->getMoveAssignmentOperator(); 4584 assert(UserDeclaredMove); 4585 } 4586 4587 if (UserDeclaredMove) { 4588 Diag(UserDeclaredMove->getLocation(), 4589 diag::note_deleted_copy_user_declared_move) 4590 << (CSM == CXXCopyAssignment) << RD 4591 << UserDeclaredMove->isMoveAssignmentOperator(); 4592 return true; 4593 } 4594 } 4595 4596 // Do access control from the special member function 4597 ContextRAII MethodContext(*this, MD); 4598 4599 // C++11 [class.dtor]p5: 4600 // -- for a virtual destructor, lookup of the non-array deallocation function 4601 // results in an ambiguity or in a function that is deleted or inaccessible 4602 if (CSM == CXXDestructor && MD->isVirtual()) { 4603 FunctionDecl *OperatorDelete = 0; 4604 DeclarationName Name = 4605 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 4606 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 4607 OperatorDelete, false)) { 4608 if (Diagnose) 4609 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 4610 return true; 4611 } 4612 } 4613 4614 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 4615 4616 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 4617 BE = RD->bases_end(); BI != BE; ++BI) 4618 if (!BI->isVirtual() && 4619 SMI.shouldDeleteForBase(BI)) 4620 return true; 4621 4622 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 4623 BE = RD->vbases_end(); BI != BE; ++BI) 4624 if (SMI.shouldDeleteForBase(BI)) 4625 return true; 4626 4627 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 4628 FE = RD->field_end(); FI != FE; ++FI) 4629 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 4630 SMI.shouldDeleteForField(*FI)) 4631 return true; 4632 4633 if (SMI.shouldDeleteForAllConstMembers()) 4634 return true; 4635 4636 return false; 4637} 4638 4639/// \brief Data used with FindHiddenVirtualMethod 4640namespace { 4641 struct FindHiddenVirtualMethodData { 4642 Sema *S; 4643 CXXMethodDecl *Method; 4644 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 4645 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 4646 }; 4647} 4648 4649/// \brief Member lookup function that determines whether a given C++ 4650/// method overloads virtual methods in a base class without overriding any, 4651/// to be used with CXXRecordDecl::lookupInBases(). 4652static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 4653 CXXBasePath &Path, 4654 void *UserData) { 4655 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 4656 4657 FindHiddenVirtualMethodData &Data 4658 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 4659 4660 DeclarationName Name = Data.Method->getDeclName(); 4661 assert(Name.getNameKind() == DeclarationName::Identifier); 4662 4663 bool foundSameNameMethod = false; 4664 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 4665 for (Path.Decls = BaseRecord->lookup(Name); 4666 Path.Decls.first != Path.Decls.second; 4667 ++Path.Decls.first) { 4668 NamedDecl *D = *Path.Decls.first; 4669 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 4670 MD = MD->getCanonicalDecl(); 4671 foundSameNameMethod = true; 4672 // Interested only in hidden virtual methods. 4673 if (!MD->isVirtual()) 4674 continue; 4675 // If the method we are checking overrides a method from its base 4676 // don't warn about the other overloaded methods. 4677 if (!Data.S->IsOverload(Data.Method, MD, false)) 4678 return true; 4679 // Collect the overload only if its hidden. 4680 if (!Data.OverridenAndUsingBaseMethods.count(MD)) 4681 overloadedMethods.push_back(MD); 4682 } 4683 } 4684 4685 if (foundSameNameMethod) 4686 Data.OverloadedMethods.append(overloadedMethods.begin(), 4687 overloadedMethods.end()); 4688 return foundSameNameMethod; 4689} 4690 4691/// \brief See if a method overloads virtual methods in a base class without 4692/// overriding any. 4693void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 4694 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 4695 MD->getLocation()) == DiagnosticsEngine::Ignored) 4696 return; 4697 if (!MD->getDeclName().isIdentifier()) 4698 return; 4699 4700 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 4701 /*bool RecordPaths=*/false, 4702 /*bool DetectVirtual=*/false); 4703 FindHiddenVirtualMethodData Data; 4704 Data.Method = MD; 4705 Data.S = this; 4706 4707 // Keep the base methods that were overriden or introduced in the subclass 4708 // by 'using' in a set. A base method not in this set is hidden. 4709 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName()); 4710 res.first != res.second; ++res.first) { 4711 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first)) 4712 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 4713 E = MD->end_overridden_methods(); 4714 I != E; ++I) 4715 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl()); 4716 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first)) 4717 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl())) 4718 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl()); 4719 } 4720 4721 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 4722 !Data.OverloadedMethods.empty()) { 4723 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 4724 << MD << (Data.OverloadedMethods.size() > 1); 4725 4726 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 4727 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 4728 Diag(overloadedMD->getLocation(), 4729 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 4730 } 4731 } 4732} 4733 4734void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 4735 Decl *TagDecl, 4736 SourceLocation LBrac, 4737 SourceLocation RBrac, 4738 AttributeList *AttrList) { 4739 if (!TagDecl) 4740 return; 4741 4742 AdjustDeclIfTemplate(TagDecl); 4743 4744 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 4745 if (l->getKind() != AttributeList::AT_Visibility) 4746 continue; 4747 l->setInvalid(); 4748 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 4749 l->getName(); 4750 } 4751 4752 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 4753 // strict aliasing violation! 4754 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 4755 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 4756 4757 CheckCompletedCXXClass( 4758 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 4759} 4760 4761/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 4762/// special functions, such as the default constructor, copy 4763/// constructor, or destructor, to the given C++ class (C++ 4764/// [special]p1). This routine can only be executed just before the 4765/// definition of the class is complete. 4766void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 4767 if (!ClassDecl->hasUserDeclaredConstructor()) 4768 ++ASTContext::NumImplicitDefaultConstructors; 4769 4770 if (!ClassDecl->hasUserDeclaredCopyConstructor()) 4771 ++ASTContext::NumImplicitCopyConstructors; 4772 4773 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor()) 4774 ++ASTContext::NumImplicitMoveConstructors; 4775 4776 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 4777 ++ASTContext::NumImplicitCopyAssignmentOperators; 4778 4779 // If we have a dynamic class, then the copy assignment operator may be 4780 // virtual, so we have to declare it immediately. This ensures that, e.g., 4781 // it shows up in the right place in the vtable and that we diagnose 4782 // problems with the implicit exception specification. 4783 if (ClassDecl->isDynamicClass()) 4784 DeclareImplicitCopyAssignment(ClassDecl); 4785 } 4786 4787 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) { 4788 ++ASTContext::NumImplicitMoveAssignmentOperators; 4789 4790 // Likewise for the move assignment operator. 4791 if (ClassDecl->isDynamicClass()) 4792 DeclareImplicitMoveAssignment(ClassDecl); 4793 } 4794 4795 if (!ClassDecl->hasUserDeclaredDestructor()) { 4796 ++ASTContext::NumImplicitDestructors; 4797 4798 // If we have a dynamic class, then the destructor may be virtual, so we 4799 // have to declare the destructor immediately. This ensures that, e.g., it 4800 // shows up in the right place in the vtable and that we diagnose problems 4801 // with the implicit exception specification. 4802 if (ClassDecl->isDynamicClass()) 4803 DeclareImplicitDestructor(ClassDecl); 4804 } 4805} 4806 4807void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 4808 if (!D) 4809 return; 4810 4811 int NumParamList = D->getNumTemplateParameterLists(); 4812 for (int i = 0; i < NumParamList; i++) { 4813 TemplateParameterList* Params = D->getTemplateParameterList(i); 4814 for (TemplateParameterList::iterator Param = Params->begin(), 4815 ParamEnd = Params->end(); 4816 Param != ParamEnd; ++Param) { 4817 NamedDecl *Named = cast<NamedDecl>(*Param); 4818 if (Named->getDeclName()) { 4819 S->AddDecl(Named); 4820 IdResolver.AddDecl(Named); 4821 } 4822 } 4823 } 4824} 4825 4826void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 4827 if (!D) 4828 return; 4829 4830 TemplateParameterList *Params = 0; 4831 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 4832 Params = Template->getTemplateParameters(); 4833 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 4834 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 4835 Params = PartialSpec->getTemplateParameters(); 4836 else 4837 return; 4838 4839 for (TemplateParameterList::iterator Param = Params->begin(), 4840 ParamEnd = Params->end(); 4841 Param != ParamEnd; ++Param) { 4842 NamedDecl *Named = cast<NamedDecl>(*Param); 4843 if (Named->getDeclName()) { 4844 S->AddDecl(Named); 4845 IdResolver.AddDecl(Named); 4846 } 4847 } 4848} 4849 4850void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 4851 if (!RecordD) return; 4852 AdjustDeclIfTemplate(RecordD); 4853 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 4854 PushDeclContext(S, Record); 4855} 4856 4857void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 4858 if (!RecordD) return; 4859 PopDeclContext(); 4860} 4861 4862/// ActOnStartDelayedCXXMethodDeclaration - We have completed 4863/// parsing a top-level (non-nested) C++ class, and we are now 4864/// parsing those parts of the given Method declaration that could 4865/// not be parsed earlier (C++ [class.mem]p2), such as default 4866/// arguments. This action should enter the scope of the given 4867/// Method declaration as if we had just parsed the qualified method 4868/// name. However, it should not bring the parameters into scope; 4869/// that will be performed by ActOnDelayedCXXMethodParameter. 4870void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 4871} 4872 4873/// ActOnDelayedCXXMethodParameter - We've already started a delayed 4874/// C++ method declaration. We're (re-)introducing the given 4875/// function parameter into scope for use in parsing later parts of 4876/// the method declaration. For example, we could see an 4877/// ActOnParamDefaultArgument event for this parameter. 4878void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 4879 if (!ParamD) 4880 return; 4881 4882 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 4883 4884 // If this parameter has an unparsed default argument, clear it out 4885 // to make way for the parsed default argument. 4886 if (Param->hasUnparsedDefaultArg()) 4887 Param->setDefaultArg(0); 4888 4889 S->AddDecl(Param); 4890 if (Param->getDeclName()) 4891 IdResolver.AddDecl(Param); 4892} 4893 4894/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 4895/// processing the delayed method declaration for Method. The method 4896/// declaration is now considered finished. There may be a separate 4897/// ActOnStartOfFunctionDef action later (not necessarily 4898/// immediately!) for this method, if it was also defined inside the 4899/// class body. 4900void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 4901 if (!MethodD) 4902 return; 4903 4904 AdjustDeclIfTemplate(MethodD); 4905 4906 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 4907 4908 // Now that we have our default arguments, check the constructor 4909 // again. It could produce additional diagnostics or affect whether 4910 // the class has implicitly-declared destructors, among other 4911 // things. 4912 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 4913 CheckConstructor(Constructor); 4914 4915 // Check the default arguments, which we may have added. 4916 if (!Method->isInvalidDecl()) 4917 CheckCXXDefaultArguments(Method); 4918} 4919 4920/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 4921/// the well-formedness of the constructor declarator @p D with type @p 4922/// R. If there are any errors in the declarator, this routine will 4923/// emit diagnostics and set the invalid bit to true. In any case, the type 4924/// will be updated to reflect a well-formed type for the constructor and 4925/// returned. 4926QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 4927 StorageClass &SC) { 4928 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 4929 4930 // C++ [class.ctor]p3: 4931 // A constructor shall not be virtual (10.3) or static (9.4). A 4932 // constructor can be invoked for a const, volatile or const 4933 // volatile object. A constructor shall not be declared const, 4934 // volatile, or const volatile (9.3.2). 4935 if (isVirtual) { 4936 if (!D.isInvalidType()) 4937 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 4938 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 4939 << SourceRange(D.getIdentifierLoc()); 4940 D.setInvalidType(); 4941 } 4942 if (SC == SC_Static) { 4943 if (!D.isInvalidType()) 4944 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 4945 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 4946 << SourceRange(D.getIdentifierLoc()); 4947 D.setInvalidType(); 4948 SC = SC_None; 4949 } 4950 4951 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 4952 if (FTI.TypeQuals != 0) { 4953 if (FTI.TypeQuals & Qualifiers::Const) 4954 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 4955 << "const" << SourceRange(D.getIdentifierLoc()); 4956 if (FTI.TypeQuals & Qualifiers::Volatile) 4957 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 4958 << "volatile" << SourceRange(D.getIdentifierLoc()); 4959 if (FTI.TypeQuals & Qualifiers::Restrict) 4960 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 4961 << "restrict" << SourceRange(D.getIdentifierLoc()); 4962 D.setInvalidType(); 4963 } 4964 4965 // C++0x [class.ctor]p4: 4966 // A constructor shall not be declared with a ref-qualifier. 4967 if (FTI.hasRefQualifier()) { 4968 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 4969 << FTI.RefQualifierIsLValueRef 4970 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 4971 D.setInvalidType(); 4972 } 4973 4974 // Rebuild the function type "R" without any type qualifiers (in 4975 // case any of the errors above fired) and with "void" as the 4976 // return type, since constructors don't have return types. 4977 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 4978 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 4979 return R; 4980 4981 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 4982 EPI.TypeQuals = 0; 4983 EPI.RefQualifier = RQ_None; 4984 4985 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 4986 Proto->getNumArgs(), EPI); 4987} 4988 4989/// CheckConstructor - Checks a fully-formed constructor for 4990/// well-formedness, issuing any diagnostics required. Returns true if 4991/// the constructor declarator is invalid. 4992void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 4993 CXXRecordDecl *ClassDecl 4994 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 4995 if (!ClassDecl) 4996 return Constructor->setInvalidDecl(); 4997 4998 // C++ [class.copy]p3: 4999 // A declaration of a constructor for a class X is ill-formed if 5000 // its first parameter is of type (optionally cv-qualified) X and 5001 // either there are no other parameters or else all other 5002 // parameters have default arguments. 5003 if (!Constructor->isInvalidDecl() && 5004 ((Constructor->getNumParams() == 1) || 5005 (Constructor->getNumParams() > 1 && 5006 Constructor->getParamDecl(1)->hasDefaultArg())) && 5007 Constructor->getTemplateSpecializationKind() 5008 != TSK_ImplicitInstantiation) { 5009 QualType ParamType = Constructor->getParamDecl(0)->getType(); 5010 QualType ClassTy = Context.getTagDeclType(ClassDecl); 5011 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 5012 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 5013 const char *ConstRef 5014 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 5015 : " const &"; 5016 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 5017 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 5018 5019 // FIXME: Rather that making the constructor invalid, we should endeavor 5020 // to fix the type. 5021 Constructor->setInvalidDecl(); 5022 } 5023 } 5024} 5025 5026/// CheckDestructor - Checks a fully-formed destructor definition for 5027/// well-formedness, issuing any diagnostics required. Returns true 5028/// on error. 5029bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 5030 CXXRecordDecl *RD = Destructor->getParent(); 5031 5032 if (Destructor->isVirtual()) { 5033 SourceLocation Loc; 5034 5035 if (!Destructor->isImplicit()) 5036 Loc = Destructor->getLocation(); 5037 else 5038 Loc = RD->getLocation(); 5039 5040 // If we have a virtual destructor, look up the deallocation function 5041 FunctionDecl *OperatorDelete = 0; 5042 DeclarationName Name = 5043 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5044 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 5045 return true; 5046 5047 MarkFunctionReferenced(Loc, OperatorDelete); 5048 5049 Destructor->setOperatorDelete(OperatorDelete); 5050 } 5051 5052 return false; 5053} 5054 5055static inline bool 5056FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 5057 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 5058 FTI.ArgInfo[0].Param && 5059 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 5060} 5061 5062/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 5063/// the well-formednes of the destructor declarator @p D with type @p 5064/// R. If there are any errors in the declarator, this routine will 5065/// emit diagnostics and set the declarator to invalid. Even if this happens, 5066/// will be updated to reflect a well-formed type for the destructor and 5067/// returned. 5068QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 5069 StorageClass& SC) { 5070 // C++ [class.dtor]p1: 5071 // [...] A typedef-name that names a class is a class-name 5072 // (7.1.3); however, a typedef-name that names a class shall not 5073 // be used as the identifier in the declarator for a destructor 5074 // declaration. 5075 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 5076 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 5077 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5078 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 5079 else if (const TemplateSpecializationType *TST = 5080 DeclaratorType->getAs<TemplateSpecializationType>()) 5081 if (TST->isTypeAlias()) 5082 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 5083 << DeclaratorType << 1; 5084 5085 // C++ [class.dtor]p2: 5086 // A destructor is used to destroy objects of its class type. A 5087 // destructor takes no parameters, and no return type can be 5088 // specified for it (not even void). The address of a destructor 5089 // shall not be taken. A destructor shall not be static. A 5090 // destructor can be invoked for a const, volatile or const 5091 // volatile object. A destructor shall not be declared const, 5092 // volatile or const volatile (9.3.2). 5093 if (SC == SC_Static) { 5094 if (!D.isInvalidType()) 5095 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 5096 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5097 << SourceRange(D.getIdentifierLoc()) 5098 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5099 5100 SC = SC_None; 5101 } 5102 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5103 // Destructors don't have return types, but the parser will 5104 // happily parse something like: 5105 // 5106 // class X { 5107 // float ~X(); 5108 // }; 5109 // 5110 // The return type will be eliminated later. 5111 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 5112 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5113 << SourceRange(D.getIdentifierLoc()); 5114 } 5115 5116 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5117 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 5118 if (FTI.TypeQuals & Qualifiers::Const) 5119 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5120 << "const" << SourceRange(D.getIdentifierLoc()); 5121 if (FTI.TypeQuals & Qualifiers::Volatile) 5122 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5123 << "volatile" << SourceRange(D.getIdentifierLoc()); 5124 if (FTI.TypeQuals & Qualifiers::Restrict) 5125 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 5126 << "restrict" << SourceRange(D.getIdentifierLoc()); 5127 D.setInvalidType(); 5128 } 5129 5130 // C++0x [class.dtor]p2: 5131 // A destructor shall not be declared with a ref-qualifier. 5132 if (FTI.hasRefQualifier()) { 5133 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 5134 << FTI.RefQualifierIsLValueRef 5135 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 5136 D.setInvalidType(); 5137 } 5138 5139 // Make sure we don't have any parameters. 5140 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 5141 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 5142 5143 // Delete the parameters. 5144 FTI.freeArgs(); 5145 D.setInvalidType(); 5146 } 5147 5148 // Make sure the destructor isn't variadic. 5149 if (FTI.isVariadic) { 5150 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 5151 D.setInvalidType(); 5152 } 5153 5154 // Rebuild the function type "R" without any type qualifiers or 5155 // parameters (in case any of the errors above fired) and with 5156 // "void" as the return type, since destructors don't have return 5157 // types. 5158 if (!D.isInvalidType()) 5159 return R; 5160 5161 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5162 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 5163 EPI.Variadic = false; 5164 EPI.TypeQuals = 0; 5165 EPI.RefQualifier = RQ_None; 5166 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 5167} 5168 5169/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 5170/// well-formednes of the conversion function declarator @p D with 5171/// type @p R. If there are any errors in the declarator, this routine 5172/// will emit diagnostics and return true. Otherwise, it will return 5173/// false. Either way, the type @p R will be updated to reflect a 5174/// well-formed type for the conversion operator. 5175void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 5176 StorageClass& SC) { 5177 // C++ [class.conv.fct]p1: 5178 // Neither parameter types nor return type can be specified. The 5179 // type of a conversion function (8.3.5) is "function taking no 5180 // parameter returning conversion-type-id." 5181 if (SC == SC_Static) { 5182 if (!D.isInvalidType()) 5183 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 5184 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 5185 << SourceRange(D.getIdentifierLoc()); 5186 D.setInvalidType(); 5187 SC = SC_None; 5188 } 5189 5190 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 5191 5192 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 5193 // Conversion functions don't have return types, but the parser will 5194 // happily parse something like: 5195 // 5196 // class X { 5197 // float operator bool(); 5198 // }; 5199 // 5200 // The return type will be changed later anyway. 5201 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 5202 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 5203 << SourceRange(D.getIdentifierLoc()); 5204 D.setInvalidType(); 5205 } 5206 5207 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 5208 5209 // Make sure we don't have any parameters. 5210 if (Proto->getNumArgs() > 0) { 5211 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 5212 5213 // Delete the parameters. 5214 D.getFunctionTypeInfo().freeArgs(); 5215 D.setInvalidType(); 5216 } else if (Proto->isVariadic()) { 5217 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 5218 D.setInvalidType(); 5219 } 5220 5221 // Diagnose "&operator bool()" and other such nonsense. This 5222 // is actually a gcc extension which we don't support. 5223 if (Proto->getResultType() != ConvType) { 5224 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 5225 << Proto->getResultType(); 5226 D.setInvalidType(); 5227 ConvType = Proto->getResultType(); 5228 } 5229 5230 // C++ [class.conv.fct]p4: 5231 // The conversion-type-id shall not represent a function type nor 5232 // an array type. 5233 if (ConvType->isArrayType()) { 5234 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 5235 ConvType = Context.getPointerType(ConvType); 5236 D.setInvalidType(); 5237 } else if (ConvType->isFunctionType()) { 5238 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 5239 ConvType = Context.getPointerType(ConvType); 5240 D.setInvalidType(); 5241 } 5242 5243 // Rebuild the function type "R" without any parameters (in case any 5244 // of the errors above fired) and with the conversion type as the 5245 // return type. 5246 if (D.isInvalidType()) 5247 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo()); 5248 5249 // C++0x explicit conversion operators. 5250 if (D.getDeclSpec().isExplicitSpecified()) 5251 Diag(D.getDeclSpec().getExplicitSpecLoc(), 5252 getLangOpts().CPlusPlus0x ? 5253 diag::warn_cxx98_compat_explicit_conversion_functions : 5254 diag::ext_explicit_conversion_functions) 5255 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 5256} 5257 5258/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 5259/// the declaration of the given C++ conversion function. This routine 5260/// is responsible for recording the conversion function in the C++ 5261/// class, if possible. 5262Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 5263 assert(Conversion && "Expected to receive a conversion function declaration"); 5264 5265 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 5266 5267 // Make sure we aren't redeclaring the conversion function. 5268 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 5269 5270 // C++ [class.conv.fct]p1: 5271 // [...] A conversion function is never used to convert a 5272 // (possibly cv-qualified) object to the (possibly cv-qualified) 5273 // same object type (or a reference to it), to a (possibly 5274 // cv-qualified) base class of that type (or a reference to it), 5275 // or to (possibly cv-qualified) void. 5276 // FIXME: Suppress this warning if the conversion function ends up being a 5277 // virtual function that overrides a virtual function in a base class. 5278 QualType ClassType 5279 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 5280 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 5281 ConvType = ConvTypeRef->getPointeeType(); 5282 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 5283 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 5284 /* Suppress diagnostics for instantiations. */; 5285 else if (ConvType->isRecordType()) { 5286 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 5287 if (ConvType == ClassType) 5288 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 5289 << ClassType; 5290 else if (IsDerivedFrom(ClassType, ConvType)) 5291 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 5292 << ClassType << ConvType; 5293 } else if (ConvType->isVoidType()) { 5294 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 5295 << ClassType << ConvType; 5296 } 5297 5298 if (FunctionTemplateDecl *ConversionTemplate 5299 = Conversion->getDescribedFunctionTemplate()) 5300 return ConversionTemplate; 5301 5302 return Conversion; 5303} 5304 5305//===----------------------------------------------------------------------===// 5306// Namespace Handling 5307//===----------------------------------------------------------------------===// 5308 5309 5310 5311/// ActOnStartNamespaceDef - This is called at the start of a namespace 5312/// definition. 5313Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 5314 SourceLocation InlineLoc, 5315 SourceLocation NamespaceLoc, 5316 SourceLocation IdentLoc, 5317 IdentifierInfo *II, 5318 SourceLocation LBrace, 5319 AttributeList *AttrList) { 5320 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 5321 // For anonymous namespace, take the location of the left brace. 5322 SourceLocation Loc = II ? IdentLoc : LBrace; 5323 bool IsInline = InlineLoc.isValid(); 5324 bool IsInvalid = false; 5325 bool IsStd = false; 5326 bool AddToKnown = false; 5327 Scope *DeclRegionScope = NamespcScope->getParent(); 5328 5329 NamespaceDecl *PrevNS = 0; 5330 if (II) { 5331 // C++ [namespace.def]p2: 5332 // The identifier in an original-namespace-definition shall not 5333 // have been previously defined in the declarative region in 5334 // which the original-namespace-definition appears. The 5335 // identifier in an original-namespace-definition is the name of 5336 // the namespace. Subsequently in that declarative region, it is 5337 // treated as an original-namespace-name. 5338 // 5339 // Since namespace names are unique in their scope, and we don't 5340 // look through using directives, just look for any ordinary names. 5341 5342 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 5343 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 5344 Decl::IDNS_Namespace; 5345 NamedDecl *PrevDecl = 0; 5346 for (DeclContext::lookup_result R 5347 = CurContext->getRedeclContext()->lookup(II); 5348 R.first != R.second; ++R.first) { 5349 if ((*R.first)->getIdentifierNamespace() & IDNS) { 5350 PrevDecl = *R.first; 5351 break; 5352 } 5353 } 5354 5355 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 5356 5357 if (PrevNS) { 5358 // This is an extended namespace definition. 5359 if (IsInline != PrevNS->isInline()) { 5360 // inline-ness must match 5361 if (PrevNS->isInline()) { 5362 // The user probably just forgot the 'inline', so suggest that it 5363 // be added back. 5364 Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 5365 << FixItHint::CreateInsertion(NamespaceLoc, "inline "); 5366 } else { 5367 Diag(Loc, diag::err_inline_namespace_mismatch) 5368 << IsInline; 5369 } 5370 Diag(PrevNS->getLocation(), diag::note_previous_definition); 5371 5372 IsInline = PrevNS->isInline(); 5373 } 5374 } else if (PrevDecl) { 5375 // This is an invalid name redefinition. 5376 Diag(Loc, diag::err_redefinition_different_kind) 5377 << II; 5378 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 5379 IsInvalid = true; 5380 // Continue on to push Namespc as current DeclContext and return it. 5381 } else if (II->isStr("std") && 5382 CurContext->getRedeclContext()->isTranslationUnit()) { 5383 // This is the first "real" definition of the namespace "std", so update 5384 // our cache of the "std" namespace to point at this definition. 5385 PrevNS = getStdNamespace(); 5386 IsStd = true; 5387 AddToKnown = !IsInline; 5388 } else { 5389 // We've seen this namespace for the first time. 5390 AddToKnown = !IsInline; 5391 } 5392 } else { 5393 // Anonymous namespaces. 5394 5395 // Determine whether the parent already has an anonymous namespace. 5396 DeclContext *Parent = CurContext->getRedeclContext(); 5397 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 5398 PrevNS = TU->getAnonymousNamespace(); 5399 } else { 5400 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 5401 PrevNS = ND->getAnonymousNamespace(); 5402 } 5403 5404 if (PrevNS && IsInline != PrevNS->isInline()) { 5405 // inline-ness must match 5406 Diag(Loc, diag::err_inline_namespace_mismatch) 5407 << IsInline; 5408 Diag(PrevNS->getLocation(), diag::note_previous_definition); 5409 5410 // Recover by ignoring the new namespace's inline status. 5411 IsInline = PrevNS->isInline(); 5412 } 5413 } 5414 5415 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 5416 StartLoc, Loc, II, PrevNS); 5417 if (IsInvalid) 5418 Namespc->setInvalidDecl(); 5419 5420 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 5421 5422 // FIXME: Should we be merging attributes? 5423 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 5424 PushNamespaceVisibilityAttr(Attr, Loc); 5425 5426 if (IsStd) 5427 StdNamespace = Namespc; 5428 if (AddToKnown) 5429 KnownNamespaces[Namespc] = false; 5430 5431 if (II) { 5432 PushOnScopeChains(Namespc, DeclRegionScope); 5433 } else { 5434 // Link the anonymous namespace into its parent. 5435 DeclContext *Parent = CurContext->getRedeclContext(); 5436 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 5437 TU->setAnonymousNamespace(Namespc); 5438 } else { 5439 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 5440 } 5441 5442 CurContext->addDecl(Namespc); 5443 5444 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 5445 // behaves as if it were replaced by 5446 // namespace unique { /* empty body */ } 5447 // using namespace unique; 5448 // namespace unique { namespace-body } 5449 // where all occurrences of 'unique' in a translation unit are 5450 // replaced by the same identifier and this identifier differs 5451 // from all other identifiers in the entire program. 5452 5453 // We just create the namespace with an empty name and then add an 5454 // implicit using declaration, just like the standard suggests. 5455 // 5456 // CodeGen enforces the "universally unique" aspect by giving all 5457 // declarations semantically contained within an anonymous 5458 // namespace internal linkage. 5459 5460 if (!PrevNS) { 5461 UsingDirectiveDecl* UD 5462 = UsingDirectiveDecl::Create(Context, CurContext, 5463 /* 'using' */ LBrace, 5464 /* 'namespace' */ SourceLocation(), 5465 /* qualifier */ NestedNameSpecifierLoc(), 5466 /* identifier */ SourceLocation(), 5467 Namespc, 5468 /* Ancestor */ CurContext); 5469 UD->setImplicit(); 5470 CurContext->addDecl(UD); 5471 } 5472 } 5473 5474 ActOnDocumentableDecl(Namespc); 5475 5476 // Although we could have an invalid decl (i.e. the namespace name is a 5477 // redefinition), push it as current DeclContext and try to continue parsing. 5478 // FIXME: We should be able to push Namespc here, so that the each DeclContext 5479 // for the namespace has the declarations that showed up in that particular 5480 // namespace definition. 5481 PushDeclContext(NamespcScope, Namespc); 5482 return Namespc; 5483} 5484 5485/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 5486/// is a namespace alias, returns the namespace it points to. 5487static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 5488 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 5489 return AD->getNamespace(); 5490 return dyn_cast_or_null<NamespaceDecl>(D); 5491} 5492 5493/// ActOnFinishNamespaceDef - This callback is called after a namespace is 5494/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 5495void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 5496 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 5497 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 5498 Namespc->setRBraceLoc(RBrace); 5499 PopDeclContext(); 5500 if (Namespc->hasAttr<VisibilityAttr>()) 5501 PopPragmaVisibility(true, RBrace); 5502} 5503 5504CXXRecordDecl *Sema::getStdBadAlloc() const { 5505 return cast_or_null<CXXRecordDecl>( 5506 StdBadAlloc.get(Context.getExternalSource())); 5507} 5508 5509NamespaceDecl *Sema::getStdNamespace() const { 5510 return cast_or_null<NamespaceDecl>( 5511 StdNamespace.get(Context.getExternalSource())); 5512} 5513 5514/// \brief Retrieve the special "std" namespace, which may require us to 5515/// implicitly define the namespace. 5516NamespaceDecl *Sema::getOrCreateStdNamespace() { 5517 if (!StdNamespace) { 5518 // The "std" namespace has not yet been defined, so build one implicitly. 5519 StdNamespace = NamespaceDecl::Create(Context, 5520 Context.getTranslationUnitDecl(), 5521 /*Inline=*/false, 5522 SourceLocation(), SourceLocation(), 5523 &PP.getIdentifierTable().get("std"), 5524 /*PrevDecl=*/0); 5525 getStdNamespace()->setImplicit(true); 5526 } 5527 5528 return getStdNamespace(); 5529} 5530 5531bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 5532 assert(getLangOpts().CPlusPlus && 5533 "Looking for std::initializer_list outside of C++."); 5534 5535 // We're looking for implicit instantiations of 5536 // template <typename E> class std::initializer_list. 5537 5538 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 5539 return false; 5540 5541 ClassTemplateDecl *Template = 0; 5542 const TemplateArgument *Arguments = 0; 5543 5544 if (const RecordType *RT = Ty->getAs<RecordType>()) { 5545 5546 ClassTemplateSpecializationDecl *Specialization = 5547 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 5548 if (!Specialization) 5549 return false; 5550 5551 Template = Specialization->getSpecializedTemplate(); 5552 Arguments = Specialization->getTemplateArgs().data(); 5553 } else if (const TemplateSpecializationType *TST = 5554 Ty->getAs<TemplateSpecializationType>()) { 5555 Template = dyn_cast_or_null<ClassTemplateDecl>( 5556 TST->getTemplateName().getAsTemplateDecl()); 5557 Arguments = TST->getArgs(); 5558 } 5559 if (!Template) 5560 return false; 5561 5562 if (!StdInitializerList) { 5563 // Haven't recognized std::initializer_list yet, maybe this is it. 5564 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 5565 if (TemplateClass->getIdentifier() != 5566 &PP.getIdentifierTable().get("initializer_list") || 5567 !getStdNamespace()->InEnclosingNamespaceSetOf( 5568 TemplateClass->getDeclContext())) 5569 return false; 5570 // This is a template called std::initializer_list, but is it the right 5571 // template? 5572 TemplateParameterList *Params = Template->getTemplateParameters(); 5573 if (Params->getMinRequiredArguments() != 1) 5574 return false; 5575 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 5576 return false; 5577 5578 // It's the right template. 5579 StdInitializerList = Template; 5580 } 5581 5582 if (Template != StdInitializerList) 5583 return false; 5584 5585 // This is an instance of std::initializer_list. Find the argument type. 5586 if (Element) 5587 *Element = Arguments[0].getAsType(); 5588 return true; 5589} 5590 5591static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 5592 NamespaceDecl *Std = S.getStdNamespace(); 5593 if (!Std) { 5594 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 5595 return 0; 5596 } 5597 5598 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 5599 Loc, Sema::LookupOrdinaryName); 5600 if (!S.LookupQualifiedName(Result, Std)) { 5601 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 5602 return 0; 5603 } 5604 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 5605 if (!Template) { 5606 Result.suppressDiagnostics(); 5607 // We found something weird. Complain about the first thing we found. 5608 NamedDecl *Found = *Result.begin(); 5609 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 5610 return 0; 5611 } 5612 5613 // We found some template called std::initializer_list. Now verify that it's 5614 // correct. 5615 TemplateParameterList *Params = Template->getTemplateParameters(); 5616 if (Params->getMinRequiredArguments() != 1 || 5617 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 5618 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 5619 return 0; 5620 } 5621 5622 return Template; 5623} 5624 5625QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 5626 if (!StdInitializerList) { 5627 StdInitializerList = LookupStdInitializerList(*this, Loc); 5628 if (!StdInitializerList) 5629 return QualType(); 5630 } 5631 5632 TemplateArgumentListInfo Args(Loc, Loc); 5633 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 5634 Context.getTrivialTypeSourceInfo(Element, 5635 Loc))); 5636 return Context.getCanonicalType( 5637 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 5638} 5639 5640bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 5641 // C++ [dcl.init.list]p2: 5642 // A constructor is an initializer-list constructor if its first parameter 5643 // is of type std::initializer_list<E> or reference to possibly cv-qualified 5644 // std::initializer_list<E> for some type E, and either there are no other 5645 // parameters or else all other parameters have default arguments. 5646 if (Ctor->getNumParams() < 1 || 5647 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 5648 return false; 5649 5650 QualType ArgType = Ctor->getParamDecl(0)->getType(); 5651 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 5652 ArgType = RT->getPointeeType().getUnqualifiedType(); 5653 5654 return isStdInitializerList(ArgType, 0); 5655} 5656 5657/// \brief Determine whether a using statement is in a context where it will be 5658/// apply in all contexts. 5659static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 5660 switch (CurContext->getDeclKind()) { 5661 case Decl::TranslationUnit: 5662 return true; 5663 case Decl::LinkageSpec: 5664 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 5665 default: 5666 return false; 5667 } 5668} 5669 5670namespace { 5671 5672// Callback to only accept typo corrections that are namespaces. 5673class NamespaceValidatorCCC : public CorrectionCandidateCallback { 5674 public: 5675 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 5676 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 5677 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 5678 } 5679 return false; 5680 } 5681}; 5682 5683} 5684 5685static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 5686 CXXScopeSpec &SS, 5687 SourceLocation IdentLoc, 5688 IdentifierInfo *Ident) { 5689 NamespaceValidatorCCC Validator; 5690 R.clear(); 5691 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 5692 R.getLookupKind(), Sc, &SS, 5693 Validator)) { 5694 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 5695 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts())); 5696 if (DeclContext *DC = S.computeDeclContext(SS, false)) 5697 S.Diag(IdentLoc, diag::err_using_directive_member_suggest) 5698 << Ident << DC << CorrectedQuotedStr << SS.getRange() 5699 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 5700 else 5701 S.Diag(IdentLoc, diag::err_using_directive_suggest) 5702 << Ident << CorrectedQuotedStr 5703 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr); 5704 5705 S.Diag(Corrected.getCorrectionDecl()->getLocation(), 5706 diag::note_namespace_defined_here) << CorrectedQuotedStr; 5707 5708 R.addDecl(Corrected.getCorrectionDecl()); 5709 return true; 5710 } 5711 return false; 5712} 5713 5714Decl *Sema::ActOnUsingDirective(Scope *S, 5715 SourceLocation UsingLoc, 5716 SourceLocation NamespcLoc, 5717 CXXScopeSpec &SS, 5718 SourceLocation IdentLoc, 5719 IdentifierInfo *NamespcName, 5720 AttributeList *AttrList) { 5721 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 5722 assert(NamespcName && "Invalid NamespcName."); 5723 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 5724 5725 // This can only happen along a recovery path. 5726 while (S->getFlags() & Scope::TemplateParamScope) 5727 S = S->getParent(); 5728 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 5729 5730 UsingDirectiveDecl *UDir = 0; 5731 NestedNameSpecifier *Qualifier = 0; 5732 if (SS.isSet()) 5733 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 5734 5735 // Lookup namespace name. 5736 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 5737 LookupParsedName(R, S, &SS); 5738 if (R.isAmbiguous()) 5739 return 0; 5740 5741 if (R.empty()) { 5742 R.clear(); 5743 // Allow "using namespace std;" or "using namespace ::std;" even if 5744 // "std" hasn't been defined yet, for GCC compatibility. 5745 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 5746 NamespcName->isStr("std")) { 5747 Diag(IdentLoc, diag::ext_using_undefined_std); 5748 R.addDecl(getOrCreateStdNamespace()); 5749 R.resolveKind(); 5750 } 5751 // Otherwise, attempt typo correction. 5752 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 5753 } 5754 5755 if (!R.empty()) { 5756 NamedDecl *Named = R.getFoundDecl(); 5757 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 5758 && "expected namespace decl"); 5759 // C++ [namespace.udir]p1: 5760 // A using-directive specifies that the names in the nominated 5761 // namespace can be used in the scope in which the 5762 // using-directive appears after the using-directive. During 5763 // unqualified name lookup (3.4.1), the names appear as if they 5764 // were declared in the nearest enclosing namespace which 5765 // contains both the using-directive and the nominated 5766 // namespace. [Note: in this context, "contains" means "contains 5767 // directly or indirectly". ] 5768 5769 // Find enclosing context containing both using-directive and 5770 // nominated namespace. 5771 NamespaceDecl *NS = getNamespaceDecl(Named); 5772 DeclContext *CommonAncestor = cast<DeclContext>(NS); 5773 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 5774 CommonAncestor = CommonAncestor->getParent(); 5775 5776 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 5777 SS.getWithLocInContext(Context), 5778 IdentLoc, Named, CommonAncestor); 5779 5780 if (IsUsingDirectiveInToplevelContext(CurContext) && 5781 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 5782 Diag(IdentLoc, diag::warn_using_directive_in_header); 5783 } 5784 5785 PushUsingDirective(S, UDir); 5786 } else { 5787 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 5788 } 5789 5790 // FIXME: We ignore attributes for now. 5791 return UDir; 5792} 5793 5794void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 5795 // If the scope has an associated entity and the using directive is at 5796 // namespace or translation unit scope, add the UsingDirectiveDecl into 5797 // its lookup structure so qualified name lookup can find it. 5798 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 5799 if (Ctx && !Ctx->isFunctionOrMethod()) 5800 Ctx->addDecl(UDir); 5801 else 5802 // Otherwise, it is at block sope. The using-directives will affect lookup 5803 // only to the end of the scope. 5804 S->PushUsingDirective(UDir); 5805} 5806 5807 5808Decl *Sema::ActOnUsingDeclaration(Scope *S, 5809 AccessSpecifier AS, 5810 bool HasUsingKeyword, 5811 SourceLocation UsingLoc, 5812 CXXScopeSpec &SS, 5813 UnqualifiedId &Name, 5814 AttributeList *AttrList, 5815 bool IsTypeName, 5816 SourceLocation TypenameLoc) { 5817 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 5818 5819 switch (Name.getKind()) { 5820 case UnqualifiedId::IK_ImplicitSelfParam: 5821 case UnqualifiedId::IK_Identifier: 5822 case UnqualifiedId::IK_OperatorFunctionId: 5823 case UnqualifiedId::IK_LiteralOperatorId: 5824 case UnqualifiedId::IK_ConversionFunctionId: 5825 break; 5826 5827 case UnqualifiedId::IK_ConstructorName: 5828 case UnqualifiedId::IK_ConstructorTemplateId: 5829 // C++11 inheriting constructors. 5830 Diag(Name.getLocStart(), 5831 getLangOpts().CPlusPlus0x ? 5832 // FIXME: Produce warn_cxx98_compat_using_decl_constructor 5833 // instead once inheriting constructors work. 5834 diag::err_using_decl_constructor_unsupported : 5835 diag::err_using_decl_constructor) 5836 << SS.getRange(); 5837 5838 if (getLangOpts().CPlusPlus0x) break; 5839 5840 return 0; 5841 5842 case UnqualifiedId::IK_DestructorName: 5843 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 5844 << SS.getRange(); 5845 return 0; 5846 5847 case UnqualifiedId::IK_TemplateId: 5848 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 5849 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 5850 return 0; 5851 } 5852 5853 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 5854 DeclarationName TargetName = TargetNameInfo.getName(); 5855 if (!TargetName) 5856 return 0; 5857 5858 // Warn about using declarations. 5859 // TODO: store that the declaration was written without 'using' and 5860 // talk about access decls instead of using decls in the 5861 // diagnostics. 5862 if (!HasUsingKeyword) { 5863 UsingLoc = Name.getLocStart(); 5864 5865 Diag(UsingLoc, diag::warn_access_decl_deprecated) 5866 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 5867 } 5868 5869 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 5870 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 5871 return 0; 5872 5873 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 5874 TargetNameInfo, AttrList, 5875 /* IsInstantiation */ false, 5876 IsTypeName, TypenameLoc); 5877 if (UD) 5878 PushOnScopeChains(UD, S, /*AddToContext*/ false); 5879 5880 return UD; 5881} 5882 5883/// \brief Determine whether a using declaration considers the given 5884/// declarations as "equivalent", e.g., if they are redeclarations of 5885/// the same entity or are both typedefs of the same type. 5886static bool 5887IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 5888 bool &SuppressRedeclaration) { 5889 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 5890 SuppressRedeclaration = false; 5891 return true; 5892 } 5893 5894 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 5895 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 5896 SuppressRedeclaration = true; 5897 return Context.hasSameType(TD1->getUnderlyingType(), 5898 TD2->getUnderlyingType()); 5899 } 5900 5901 return false; 5902} 5903 5904 5905/// Determines whether to create a using shadow decl for a particular 5906/// decl, given the set of decls existing prior to this using lookup. 5907bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 5908 const LookupResult &Previous) { 5909 // Diagnose finding a decl which is not from a base class of the 5910 // current class. We do this now because there are cases where this 5911 // function will silently decide not to build a shadow decl, which 5912 // will pre-empt further diagnostics. 5913 // 5914 // We don't need to do this in C++0x because we do the check once on 5915 // the qualifier. 5916 // 5917 // FIXME: diagnose the following if we care enough: 5918 // struct A { int foo; }; 5919 // struct B : A { using A::foo; }; 5920 // template <class T> struct C : A {}; 5921 // template <class T> struct D : C<T> { using B::foo; } // <--- 5922 // This is invalid (during instantiation) in C++03 because B::foo 5923 // resolves to the using decl in B, which is not a base class of D<T>. 5924 // We can't diagnose it immediately because C<T> is an unknown 5925 // specialization. The UsingShadowDecl in D<T> then points directly 5926 // to A::foo, which will look well-formed when we instantiate. 5927 // The right solution is to not collapse the shadow-decl chain. 5928 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) { 5929 DeclContext *OrigDC = Orig->getDeclContext(); 5930 5931 // Handle enums and anonymous structs. 5932 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 5933 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 5934 while (OrigRec->isAnonymousStructOrUnion()) 5935 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 5936 5937 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 5938 if (OrigDC == CurContext) { 5939 Diag(Using->getLocation(), 5940 diag::err_using_decl_nested_name_specifier_is_current_class) 5941 << Using->getQualifierLoc().getSourceRange(); 5942 Diag(Orig->getLocation(), diag::note_using_decl_target); 5943 return true; 5944 } 5945 5946 Diag(Using->getQualifierLoc().getBeginLoc(), 5947 diag::err_using_decl_nested_name_specifier_is_not_base_class) 5948 << Using->getQualifier() 5949 << cast<CXXRecordDecl>(CurContext) 5950 << Using->getQualifierLoc().getSourceRange(); 5951 Diag(Orig->getLocation(), diag::note_using_decl_target); 5952 return true; 5953 } 5954 } 5955 5956 if (Previous.empty()) return false; 5957 5958 NamedDecl *Target = Orig; 5959 if (isa<UsingShadowDecl>(Target)) 5960 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 5961 5962 // If the target happens to be one of the previous declarations, we 5963 // don't have a conflict. 5964 // 5965 // FIXME: but we might be increasing its access, in which case we 5966 // should redeclare it. 5967 NamedDecl *NonTag = 0, *Tag = 0; 5968 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5969 I != E; ++I) { 5970 NamedDecl *D = (*I)->getUnderlyingDecl(); 5971 bool Result; 5972 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 5973 return Result; 5974 5975 (isa<TagDecl>(D) ? Tag : NonTag) = D; 5976 } 5977 5978 if (Target->isFunctionOrFunctionTemplate()) { 5979 FunctionDecl *FD; 5980 if (isa<FunctionTemplateDecl>(Target)) 5981 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 5982 else 5983 FD = cast<FunctionDecl>(Target); 5984 5985 NamedDecl *OldDecl = 0; 5986 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 5987 case Ovl_Overload: 5988 return false; 5989 5990 case Ovl_NonFunction: 5991 Diag(Using->getLocation(), diag::err_using_decl_conflict); 5992 break; 5993 5994 // We found a decl with the exact signature. 5995 case Ovl_Match: 5996 // If we're in a record, we want to hide the target, so we 5997 // return true (without a diagnostic) to tell the caller not to 5998 // build a shadow decl. 5999 if (CurContext->isRecord()) 6000 return true; 6001 6002 // If we're not in a record, this is an error. 6003 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6004 break; 6005 } 6006 6007 Diag(Target->getLocation(), diag::note_using_decl_target); 6008 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 6009 return true; 6010 } 6011 6012 // Target is not a function. 6013 6014 if (isa<TagDecl>(Target)) { 6015 // No conflict between a tag and a non-tag. 6016 if (!Tag) return false; 6017 6018 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6019 Diag(Target->getLocation(), diag::note_using_decl_target); 6020 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 6021 return true; 6022 } 6023 6024 // No conflict between a tag and a non-tag. 6025 if (!NonTag) return false; 6026 6027 Diag(Using->getLocation(), diag::err_using_decl_conflict); 6028 Diag(Target->getLocation(), diag::note_using_decl_target); 6029 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 6030 return true; 6031} 6032 6033/// Builds a shadow declaration corresponding to a 'using' declaration. 6034UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 6035 UsingDecl *UD, 6036 NamedDecl *Orig) { 6037 6038 // If we resolved to another shadow declaration, just coalesce them. 6039 NamedDecl *Target = Orig; 6040 if (isa<UsingShadowDecl>(Target)) { 6041 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 6042 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 6043 } 6044 6045 UsingShadowDecl *Shadow 6046 = UsingShadowDecl::Create(Context, CurContext, 6047 UD->getLocation(), UD, Target); 6048 UD->addShadowDecl(Shadow); 6049 6050 Shadow->setAccess(UD->getAccess()); 6051 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 6052 Shadow->setInvalidDecl(); 6053 6054 if (S) 6055 PushOnScopeChains(Shadow, S); 6056 else 6057 CurContext->addDecl(Shadow); 6058 6059 6060 return Shadow; 6061} 6062 6063/// Hides a using shadow declaration. This is required by the current 6064/// using-decl implementation when a resolvable using declaration in a 6065/// class is followed by a declaration which would hide or override 6066/// one or more of the using decl's targets; for example: 6067/// 6068/// struct Base { void foo(int); }; 6069/// struct Derived : Base { 6070/// using Base::foo; 6071/// void foo(int); 6072/// }; 6073/// 6074/// The governing language is C++03 [namespace.udecl]p12: 6075/// 6076/// When a using-declaration brings names from a base class into a 6077/// derived class scope, member functions in the derived class 6078/// override and/or hide member functions with the same name and 6079/// parameter types in a base class (rather than conflicting). 6080/// 6081/// There are two ways to implement this: 6082/// (1) optimistically create shadow decls when they're not hidden 6083/// by existing declarations, or 6084/// (2) don't create any shadow decls (or at least don't make them 6085/// visible) until we've fully parsed/instantiated the class. 6086/// The problem with (1) is that we might have to retroactively remove 6087/// a shadow decl, which requires several O(n) operations because the 6088/// decl structures are (very reasonably) not designed for removal. 6089/// (2) avoids this but is very fiddly and phase-dependent. 6090void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 6091 if (Shadow->getDeclName().getNameKind() == 6092 DeclarationName::CXXConversionFunctionName) 6093 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 6094 6095 // Remove it from the DeclContext... 6096 Shadow->getDeclContext()->removeDecl(Shadow); 6097 6098 // ...and the scope, if applicable... 6099 if (S) { 6100 S->RemoveDecl(Shadow); 6101 IdResolver.RemoveDecl(Shadow); 6102 } 6103 6104 // ...and the using decl. 6105 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 6106 6107 // TODO: complain somehow if Shadow was used. It shouldn't 6108 // be possible for this to happen, because...? 6109} 6110 6111/// Builds a using declaration. 6112/// 6113/// \param IsInstantiation - Whether this call arises from an 6114/// instantiation of an unresolved using declaration. We treat 6115/// the lookup differently for these declarations. 6116NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 6117 SourceLocation UsingLoc, 6118 CXXScopeSpec &SS, 6119 const DeclarationNameInfo &NameInfo, 6120 AttributeList *AttrList, 6121 bool IsInstantiation, 6122 bool IsTypeName, 6123 SourceLocation TypenameLoc) { 6124 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6125 SourceLocation IdentLoc = NameInfo.getLoc(); 6126 assert(IdentLoc.isValid() && "Invalid TargetName location."); 6127 6128 // FIXME: We ignore attributes for now. 6129 6130 if (SS.isEmpty()) { 6131 Diag(IdentLoc, diag::err_using_requires_qualname); 6132 return 0; 6133 } 6134 6135 // Do the redeclaration lookup in the current scope. 6136 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 6137 ForRedeclaration); 6138 Previous.setHideTags(false); 6139 if (S) { 6140 LookupName(Previous, S); 6141 6142 // It is really dumb that we have to do this. 6143 LookupResult::Filter F = Previous.makeFilter(); 6144 while (F.hasNext()) { 6145 NamedDecl *D = F.next(); 6146 if (!isDeclInScope(D, CurContext, S)) 6147 F.erase(); 6148 } 6149 F.done(); 6150 } else { 6151 assert(IsInstantiation && "no scope in non-instantiation"); 6152 assert(CurContext->isRecord() && "scope not record in instantiation"); 6153 LookupQualifiedName(Previous, CurContext); 6154 } 6155 6156 // Check for invalid redeclarations. 6157 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 6158 return 0; 6159 6160 // Check for bad qualifiers. 6161 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 6162 return 0; 6163 6164 DeclContext *LookupContext = computeDeclContext(SS); 6165 NamedDecl *D; 6166 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 6167 if (!LookupContext) { 6168 if (IsTypeName) { 6169 // FIXME: not all declaration name kinds are legal here 6170 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 6171 UsingLoc, TypenameLoc, 6172 QualifierLoc, 6173 IdentLoc, NameInfo.getName()); 6174 } else { 6175 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 6176 QualifierLoc, NameInfo); 6177 } 6178 } else { 6179 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 6180 NameInfo, IsTypeName); 6181 } 6182 D->setAccess(AS); 6183 CurContext->addDecl(D); 6184 6185 if (!LookupContext) return D; 6186 UsingDecl *UD = cast<UsingDecl>(D); 6187 6188 if (RequireCompleteDeclContext(SS, LookupContext)) { 6189 UD->setInvalidDecl(); 6190 return UD; 6191 } 6192 6193 // The normal rules do not apply to inheriting constructor declarations. 6194 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 6195 if (CheckInheritingConstructorUsingDecl(UD)) 6196 UD->setInvalidDecl(); 6197 return UD; 6198 } 6199 6200 // Otherwise, look up the target name. 6201 6202 LookupResult R(*this, NameInfo, LookupOrdinaryName); 6203 6204 // Unlike most lookups, we don't always want to hide tag 6205 // declarations: tag names are visible through the using declaration 6206 // even if hidden by ordinary names, *except* in a dependent context 6207 // where it's important for the sanity of two-phase lookup. 6208 if (!IsInstantiation) 6209 R.setHideTags(false); 6210 6211 // For the purposes of this lookup, we have a base object type 6212 // equal to that of the current context. 6213 if (CurContext->isRecord()) { 6214 R.setBaseObjectType( 6215 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 6216 } 6217 6218 LookupQualifiedName(R, LookupContext); 6219 6220 if (R.empty()) { 6221 Diag(IdentLoc, diag::err_no_member) 6222 << NameInfo.getName() << LookupContext << SS.getRange(); 6223 UD->setInvalidDecl(); 6224 return UD; 6225 } 6226 6227 if (R.isAmbiguous()) { 6228 UD->setInvalidDecl(); 6229 return UD; 6230 } 6231 6232 if (IsTypeName) { 6233 // If we asked for a typename and got a non-type decl, error out. 6234 if (!R.getAsSingle<TypeDecl>()) { 6235 Diag(IdentLoc, diag::err_using_typename_non_type); 6236 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 6237 Diag((*I)->getUnderlyingDecl()->getLocation(), 6238 diag::note_using_decl_target); 6239 UD->setInvalidDecl(); 6240 return UD; 6241 } 6242 } else { 6243 // If we asked for a non-typename and we got a type, error out, 6244 // but only if this is an instantiation of an unresolved using 6245 // decl. Otherwise just silently find the type name. 6246 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 6247 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 6248 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 6249 UD->setInvalidDecl(); 6250 return UD; 6251 } 6252 } 6253 6254 // C++0x N2914 [namespace.udecl]p6: 6255 // A using-declaration shall not name a namespace. 6256 if (R.getAsSingle<NamespaceDecl>()) { 6257 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 6258 << SS.getRange(); 6259 UD->setInvalidDecl(); 6260 return UD; 6261 } 6262 6263 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 6264 if (!CheckUsingShadowDecl(UD, *I, Previous)) 6265 BuildUsingShadowDecl(S, UD, *I); 6266 } 6267 6268 return UD; 6269} 6270 6271/// Additional checks for a using declaration referring to a constructor name. 6272bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 6273 assert(!UD->isTypeName() && "expecting a constructor name"); 6274 6275 const Type *SourceType = UD->getQualifier()->getAsType(); 6276 assert(SourceType && 6277 "Using decl naming constructor doesn't have type in scope spec."); 6278 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 6279 6280 // Check whether the named type is a direct base class. 6281 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 6282 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 6283 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 6284 BaseIt != BaseE; ++BaseIt) { 6285 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 6286 if (CanonicalSourceType == BaseType) 6287 break; 6288 if (BaseIt->getType()->isDependentType()) 6289 break; 6290 } 6291 6292 if (BaseIt == BaseE) { 6293 // Did not find SourceType in the bases. 6294 Diag(UD->getUsingLocation(), 6295 diag::err_using_decl_constructor_not_in_direct_base) 6296 << UD->getNameInfo().getSourceRange() 6297 << QualType(SourceType, 0) << TargetClass; 6298 return true; 6299 } 6300 6301 if (!CurContext->isDependentContext()) 6302 BaseIt->setInheritConstructors(); 6303 6304 return false; 6305} 6306 6307/// Checks that the given using declaration is not an invalid 6308/// redeclaration. Note that this is checking only for the using decl 6309/// itself, not for any ill-formedness among the UsingShadowDecls. 6310bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 6311 bool isTypeName, 6312 const CXXScopeSpec &SS, 6313 SourceLocation NameLoc, 6314 const LookupResult &Prev) { 6315 // C++03 [namespace.udecl]p8: 6316 // C++0x [namespace.udecl]p10: 6317 // A using-declaration is a declaration and can therefore be used 6318 // repeatedly where (and only where) multiple declarations are 6319 // allowed. 6320 // 6321 // That's in non-member contexts. 6322 if (!CurContext->getRedeclContext()->isRecord()) 6323 return false; 6324 6325 NestedNameSpecifier *Qual 6326 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 6327 6328 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 6329 NamedDecl *D = *I; 6330 6331 bool DTypename; 6332 NestedNameSpecifier *DQual; 6333 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 6334 DTypename = UD->isTypeName(); 6335 DQual = UD->getQualifier(); 6336 } else if (UnresolvedUsingValueDecl *UD 6337 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 6338 DTypename = false; 6339 DQual = UD->getQualifier(); 6340 } else if (UnresolvedUsingTypenameDecl *UD 6341 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 6342 DTypename = true; 6343 DQual = UD->getQualifier(); 6344 } else continue; 6345 6346 // using decls differ if one says 'typename' and the other doesn't. 6347 // FIXME: non-dependent using decls? 6348 if (isTypeName != DTypename) continue; 6349 6350 // using decls differ if they name different scopes (but note that 6351 // template instantiation can cause this check to trigger when it 6352 // didn't before instantiation). 6353 if (Context.getCanonicalNestedNameSpecifier(Qual) != 6354 Context.getCanonicalNestedNameSpecifier(DQual)) 6355 continue; 6356 6357 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 6358 Diag(D->getLocation(), diag::note_using_decl) << 1; 6359 return true; 6360 } 6361 6362 return false; 6363} 6364 6365 6366/// Checks that the given nested-name qualifier used in a using decl 6367/// in the current context is appropriately related to the current 6368/// scope. If an error is found, diagnoses it and returns true. 6369bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 6370 const CXXScopeSpec &SS, 6371 SourceLocation NameLoc) { 6372 DeclContext *NamedContext = computeDeclContext(SS); 6373 6374 if (!CurContext->isRecord()) { 6375 // C++03 [namespace.udecl]p3: 6376 // C++0x [namespace.udecl]p8: 6377 // A using-declaration for a class member shall be a member-declaration. 6378 6379 // If we weren't able to compute a valid scope, it must be a 6380 // dependent class scope. 6381 if (!NamedContext || NamedContext->isRecord()) { 6382 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 6383 << SS.getRange(); 6384 return true; 6385 } 6386 6387 // Otherwise, everything is known to be fine. 6388 return false; 6389 } 6390 6391 // The current scope is a record. 6392 6393 // If the named context is dependent, we can't decide much. 6394 if (!NamedContext) { 6395 // FIXME: in C++0x, we can diagnose if we can prove that the 6396 // nested-name-specifier does not refer to a base class, which is 6397 // still possible in some cases. 6398 6399 // Otherwise we have to conservatively report that things might be 6400 // okay. 6401 return false; 6402 } 6403 6404 if (!NamedContext->isRecord()) { 6405 // Ideally this would point at the last name in the specifier, 6406 // but we don't have that level of source info. 6407 Diag(SS.getRange().getBegin(), 6408 diag::err_using_decl_nested_name_specifier_is_not_class) 6409 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 6410 return true; 6411 } 6412 6413 if (!NamedContext->isDependentContext() && 6414 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 6415 return true; 6416 6417 if (getLangOpts().CPlusPlus0x) { 6418 // C++0x [namespace.udecl]p3: 6419 // In a using-declaration used as a member-declaration, the 6420 // nested-name-specifier shall name a base class of the class 6421 // being defined. 6422 6423 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 6424 cast<CXXRecordDecl>(NamedContext))) { 6425 if (CurContext == NamedContext) { 6426 Diag(NameLoc, 6427 diag::err_using_decl_nested_name_specifier_is_current_class) 6428 << SS.getRange(); 6429 return true; 6430 } 6431 6432 Diag(SS.getRange().getBegin(), 6433 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6434 << (NestedNameSpecifier*) SS.getScopeRep() 6435 << cast<CXXRecordDecl>(CurContext) 6436 << SS.getRange(); 6437 return true; 6438 } 6439 6440 return false; 6441 } 6442 6443 // C++03 [namespace.udecl]p4: 6444 // A using-declaration used as a member-declaration shall refer 6445 // to a member of a base class of the class being defined [etc.]. 6446 6447 // Salient point: SS doesn't have to name a base class as long as 6448 // lookup only finds members from base classes. Therefore we can 6449 // diagnose here only if we can prove that that can't happen, 6450 // i.e. if the class hierarchies provably don't intersect. 6451 6452 // TODO: it would be nice if "definitely valid" results were cached 6453 // in the UsingDecl and UsingShadowDecl so that these checks didn't 6454 // need to be repeated. 6455 6456 struct UserData { 6457 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 6458 6459 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 6460 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 6461 Data->Bases.insert(Base); 6462 return true; 6463 } 6464 6465 bool hasDependentBases(const CXXRecordDecl *Class) { 6466 return !Class->forallBases(collect, this); 6467 } 6468 6469 /// Returns true if the base is dependent or is one of the 6470 /// accumulated base classes. 6471 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 6472 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 6473 return !Data->Bases.count(Base); 6474 } 6475 6476 bool mightShareBases(const CXXRecordDecl *Class) { 6477 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 6478 } 6479 }; 6480 6481 UserData Data; 6482 6483 // Returns false if we find a dependent base. 6484 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 6485 return false; 6486 6487 // Returns false if the class has a dependent base or if it or one 6488 // of its bases is present in the base set of the current context. 6489 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 6490 return false; 6491 6492 Diag(SS.getRange().getBegin(), 6493 diag::err_using_decl_nested_name_specifier_is_not_base_class) 6494 << (NestedNameSpecifier*) SS.getScopeRep() 6495 << cast<CXXRecordDecl>(CurContext) 6496 << SS.getRange(); 6497 6498 return true; 6499} 6500 6501Decl *Sema::ActOnAliasDeclaration(Scope *S, 6502 AccessSpecifier AS, 6503 MultiTemplateParamsArg TemplateParamLists, 6504 SourceLocation UsingLoc, 6505 UnqualifiedId &Name, 6506 TypeResult Type) { 6507 // Skip up to the relevant declaration scope. 6508 while (S->getFlags() & Scope::TemplateParamScope) 6509 S = S->getParent(); 6510 assert((S->getFlags() & Scope::DeclScope) && 6511 "got alias-declaration outside of declaration scope"); 6512 6513 if (Type.isInvalid()) 6514 return 0; 6515 6516 bool Invalid = false; 6517 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 6518 TypeSourceInfo *TInfo = 0; 6519 GetTypeFromParser(Type.get(), &TInfo); 6520 6521 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 6522 return 0; 6523 6524 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 6525 UPPC_DeclarationType)) { 6526 Invalid = true; 6527 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 6528 TInfo->getTypeLoc().getBeginLoc()); 6529 } 6530 6531 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 6532 LookupName(Previous, S); 6533 6534 // Warn about shadowing the name of a template parameter. 6535 if (Previous.isSingleResult() && 6536 Previous.getFoundDecl()->isTemplateParameter()) { 6537 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 6538 Previous.clear(); 6539 } 6540 6541 assert(Name.Kind == UnqualifiedId::IK_Identifier && 6542 "name in alias declaration must be an identifier"); 6543 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 6544 Name.StartLocation, 6545 Name.Identifier, TInfo); 6546 6547 NewTD->setAccess(AS); 6548 6549 if (Invalid) 6550 NewTD->setInvalidDecl(); 6551 6552 CheckTypedefForVariablyModifiedType(S, NewTD); 6553 Invalid |= NewTD->isInvalidDecl(); 6554 6555 bool Redeclaration = false; 6556 6557 NamedDecl *NewND; 6558 if (TemplateParamLists.size()) { 6559 TypeAliasTemplateDecl *OldDecl = 0; 6560 TemplateParameterList *OldTemplateParams = 0; 6561 6562 if (TemplateParamLists.size() != 1) { 6563 Diag(UsingLoc, diag::err_alias_template_extra_headers) 6564 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(), 6565 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc()); 6566 } 6567 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0]; 6568 6569 // Only consider previous declarations in the same scope. 6570 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 6571 /*ExplicitInstantiationOrSpecialization*/false); 6572 if (!Previous.empty()) { 6573 Redeclaration = true; 6574 6575 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 6576 if (!OldDecl && !Invalid) { 6577 Diag(UsingLoc, diag::err_redefinition_different_kind) 6578 << Name.Identifier; 6579 6580 NamedDecl *OldD = Previous.getRepresentativeDecl(); 6581 if (OldD->getLocation().isValid()) 6582 Diag(OldD->getLocation(), diag::note_previous_definition); 6583 6584 Invalid = true; 6585 } 6586 6587 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 6588 if (TemplateParameterListsAreEqual(TemplateParams, 6589 OldDecl->getTemplateParameters(), 6590 /*Complain=*/true, 6591 TPL_TemplateMatch)) 6592 OldTemplateParams = OldDecl->getTemplateParameters(); 6593 else 6594 Invalid = true; 6595 6596 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 6597 if (!Invalid && 6598 !Context.hasSameType(OldTD->getUnderlyingType(), 6599 NewTD->getUnderlyingType())) { 6600 // FIXME: The C++0x standard does not clearly say this is ill-formed, 6601 // but we can't reasonably accept it. 6602 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 6603 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 6604 if (OldTD->getLocation().isValid()) 6605 Diag(OldTD->getLocation(), diag::note_previous_definition); 6606 Invalid = true; 6607 } 6608 } 6609 } 6610 6611 // Merge any previous default template arguments into our parameters, 6612 // and check the parameter list. 6613 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 6614 TPC_TypeAliasTemplate)) 6615 return 0; 6616 6617 TypeAliasTemplateDecl *NewDecl = 6618 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 6619 Name.Identifier, TemplateParams, 6620 NewTD); 6621 6622 NewDecl->setAccess(AS); 6623 6624 if (Invalid) 6625 NewDecl->setInvalidDecl(); 6626 else if (OldDecl) 6627 NewDecl->setPreviousDeclaration(OldDecl); 6628 6629 NewND = NewDecl; 6630 } else { 6631 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 6632 NewND = NewTD; 6633 } 6634 6635 if (!Redeclaration) 6636 PushOnScopeChains(NewND, S); 6637 6638 ActOnDocumentableDecl(NewND); 6639 return NewND; 6640} 6641 6642Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 6643 SourceLocation NamespaceLoc, 6644 SourceLocation AliasLoc, 6645 IdentifierInfo *Alias, 6646 CXXScopeSpec &SS, 6647 SourceLocation IdentLoc, 6648 IdentifierInfo *Ident) { 6649 6650 // Lookup the namespace name. 6651 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 6652 LookupParsedName(R, S, &SS); 6653 6654 // Check if we have a previous declaration with the same name. 6655 NamedDecl *PrevDecl 6656 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 6657 ForRedeclaration); 6658 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 6659 PrevDecl = 0; 6660 6661 if (PrevDecl) { 6662 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 6663 // We already have an alias with the same name that points to the same 6664 // namespace, so don't create a new one. 6665 // FIXME: At some point, we'll want to create the (redundant) 6666 // declaration to maintain better source information. 6667 if (!R.isAmbiguous() && !R.empty() && 6668 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 6669 return 0; 6670 } 6671 6672 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 6673 diag::err_redefinition_different_kind; 6674 Diag(AliasLoc, DiagID) << Alias; 6675 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6676 return 0; 6677 } 6678 6679 if (R.isAmbiguous()) 6680 return 0; 6681 6682 if (R.empty()) { 6683 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 6684 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6685 return 0; 6686 } 6687 } 6688 6689 NamespaceAliasDecl *AliasDecl = 6690 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 6691 Alias, SS.getWithLocInContext(Context), 6692 IdentLoc, R.getFoundDecl()); 6693 6694 PushOnScopeChains(AliasDecl, S); 6695 return AliasDecl; 6696} 6697 6698namespace { 6699 /// \brief Scoped object used to handle the state changes required in Sema 6700 /// to implicitly define the body of a C++ member function; 6701 class ImplicitlyDefinedFunctionScope { 6702 Sema &S; 6703 Sema::ContextRAII SavedContext; 6704 6705 public: 6706 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method) 6707 : S(S), SavedContext(S, Method) 6708 { 6709 S.PushFunctionScope(); 6710 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 6711 } 6712 6713 ~ImplicitlyDefinedFunctionScope() { 6714 S.PopExpressionEvaluationContext(); 6715 S.PopFunctionScopeInfo(); 6716 } 6717 }; 6718} 6719 6720Sema::ImplicitExceptionSpecification 6721Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 6722 CXXMethodDecl *MD) { 6723 CXXRecordDecl *ClassDecl = MD->getParent(); 6724 6725 // C++ [except.spec]p14: 6726 // An implicitly declared special member function (Clause 12) shall have an 6727 // exception-specification. [...] 6728 ImplicitExceptionSpecification ExceptSpec(*this); 6729 if (ClassDecl->isInvalidDecl()) 6730 return ExceptSpec; 6731 6732 // Direct base-class constructors. 6733 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 6734 BEnd = ClassDecl->bases_end(); 6735 B != BEnd; ++B) { 6736 if (B->isVirtual()) // Handled below. 6737 continue; 6738 6739 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 6740 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6741 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 6742 // If this is a deleted function, add it anyway. This might be conformant 6743 // with the standard. This might not. I'm not sure. It might not matter. 6744 if (Constructor) 6745 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 6746 } 6747 } 6748 6749 // Virtual base-class constructors. 6750 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 6751 BEnd = ClassDecl->vbases_end(); 6752 B != BEnd; ++B) { 6753 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 6754 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6755 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 6756 // If this is a deleted function, add it anyway. This might be conformant 6757 // with the standard. This might not. I'm not sure. It might not matter. 6758 if (Constructor) 6759 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 6760 } 6761 } 6762 6763 // Field constructors. 6764 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 6765 FEnd = ClassDecl->field_end(); 6766 F != FEnd; ++F) { 6767 if (F->hasInClassInitializer()) { 6768 if (Expr *E = F->getInClassInitializer()) 6769 ExceptSpec.CalledExpr(E); 6770 else if (!F->isInvalidDecl()) 6771 // DR1351: 6772 // If the brace-or-equal-initializer of a non-static data member 6773 // invokes a defaulted default constructor of its class or of an 6774 // enclosing class in a potentially evaluated subexpression, the 6775 // program is ill-formed. 6776 // 6777 // This resolution is unworkable: the exception specification of the 6778 // default constructor can be needed in an unevaluated context, in 6779 // particular, in the operand of a noexcept-expression, and we can be 6780 // unable to compute an exception specification for an enclosed class. 6781 // 6782 // We do not allow an in-class initializer to require the evaluation 6783 // of the exception specification for any in-class initializer whose 6784 // definition is not lexically complete. 6785 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 6786 } else if (const RecordType *RecordTy 6787 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 6788 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6789 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 6790 // If this is a deleted function, add it anyway. This might be conformant 6791 // with the standard. This might not. I'm not sure. It might not matter. 6792 // In particular, the problem is that this function never gets called. It 6793 // might just be ill-formed because this function attempts to refer to 6794 // a deleted function here. 6795 if (Constructor) 6796 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 6797 } 6798 } 6799 6800 return ExceptSpec; 6801} 6802 6803CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 6804 CXXRecordDecl *ClassDecl) { 6805 // C++ [class.ctor]p5: 6806 // A default constructor for a class X is a constructor of class X 6807 // that can be called without an argument. If there is no 6808 // user-declared constructor for class X, a default constructor is 6809 // implicitly declared. An implicitly-declared default constructor 6810 // is an inline public member of its class. 6811 assert(!ClassDecl->hasUserDeclaredConstructor() && 6812 "Should not build implicit default constructor!"); 6813 6814 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 6815 CXXDefaultConstructor, 6816 false); 6817 6818 // Create the actual constructor declaration. 6819 CanQualType ClassType 6820 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6821 SourceLocation ClassLoc = ClassDecl->getLocation(); 6822 DeclarationName Name 6823 = Context.DeclarationNames.getCXXConstructorName(ClassType); 6824 DeclarationNameInfo NameInfo(Name, ClassLoc); 6825 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 6826 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 6827 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 6828 Constexpr); 6829 DefaultCon->setAccess(AS_public); 6830 DefaultCon->setDefaulted(); 6831 DefaultCon->setImplicit(); 6832 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 6833 6834 // Build an exception specification pointing back at this constructor. 6835 FunctionProtoType::ExtProtoInfo EPI; 6836 EPI.ExceptionSpecType = EST_Unevaluated; 6837 EPI.ExceptionSpecDecl = DefaultCon; 6838 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 6839 6840 // Note that we have declared this constructor. 6841 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 6842 6843 if (Scope *S = getScopeForContext(ClassDecl)) 6844 PushOnScopeChains(DefaultCon, S, false); 6845 ClassDecl->addDecl(DefaultCon); 6846 6847 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 6848 DefaultCon->setDeletedAsWritten(); 6849 6850 return DefaultCon; 6851} 6852 6853void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 6854 CXXConstructorDecl *Constructor) { 6855 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 6856 !Constructor->doesThisDeclarationHaveABody() && 6857 !Constructor->isDeleted()) && 6858 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 6859 6860 CXXRecordDecl *ClassDecl = Constructor->getParent(); 6861 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 6862 6863 ImplicitlyDefinedFunctionScope Scope(*this, Constructor); 6864 DiagnosticErrorTrap Trap(Diags); 6865 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) || 6866 Trap.hasErrorOccurred()) { 6867 Diag(CurrentLocation, diag::note_member_synthesized_at) 6868 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 6869 Constructor->setInvalidDecl(); 6870 return; 6871 } 6872 6873 SourceLocation Loc = Constructor->getLocation(); 6874 Constructor->setBody(new (Context) CompoundStmt(Loc)); 6875 6876 Constructor->setUsed(); 6877 MarkVTableUsed(CurrentLocation, ClassDecl); 6878 6879 if (ASTMutationListener *L = getASTMutationListener()) { 6880 L->CompletedImplicitDefinition(Constructor); 6881 } 6882} 6883 6884void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 6885 if (!D) return; 6886 AdjustDeclIfTemplate(D); 6887 6888 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D); 6889 6890 if (!ClassDecl->isDependentType()) 6891 CheckExplicitlyDefaultedMethods(ClassDecl); 6892} 6893 6894void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) { 6895 // We start with an initial pass over the base classes to collect those that 6896 // inherit constructors from. If there are none, we can forgo all further 6897 // processing. 6898 typedef SmallVector<const RecordType *, 4> BasesVector; 6899 BasesVector BasesToInheritFrom; 6900 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 6901 BaseE = ClassDecl->bases_end(); 6902 BaseIt != BaseE; ++BaseIt) { 6903 if (BaseIt->getInheritConstructors()) { 6904 QualType Base = BaseIt->getType(); 6905 if (Base->isDependentType()) { 6906 // If we inherit constructors from anything that is dependent, just 6907 // abort processing altogether. We'll get another chance for the 6908 // instantiations. 6909 return; 6910 } 6911 BasesToInheritFrom.push_back(Base->castAs<RecordType>()); 6912 } 6913 } 6914 if (BasesToInheritFrom.empty()) 6915 return; 6916 6917 // Now collect the constructors that we already have in the current class. 6918 // Those take precedence over inherited constructors. 6919 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...] 6920 // unless there is a user-declared constructor with the same signature in 6921 // the class where the using-declaration appears. 6922 llvm::SmallSet<const Type *, 8> ExistingConstructors; 6923 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(), 6924 CtorE = ClassDecl->ctor_end(); 6925 CtorIt != CtorE; ++CtorIt) { 6926 ExistingConstructors.insert( 6927 Context.getCanonicalType(CtorIt->getType()).getTypePtr()); 6928 } 6929 6930 DeclarationName CreatedCtorName = 6931 Context.DeclarationNames.getCXXConstructorName( 6932 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified()); 6933 6934 // Now comes the true work. 6935 // First, we keep a map from constructor types to the base that introduced 6936 // them. Needed for finding conflicting constructors. We also keep the 6937 // actually inserted declarations in there, for pretty diagnostics. 6938 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo; 6939 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap; 6940 ConstructorToSourceMap InheritedConstructors; 6941 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(), 6942 BaseE = BasesToInheritFrom.end(); 6943 BaseIt != BaseE; ++BaseIt) { 6944 const RecordType *Base = *BaseIt; 6945 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified(); 6946 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl()); 6947 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(), 6948 CtorE = BaseDecl->ctor_end(); 6949 CtorIt != CtorE; ++CtorIt) { 6950 // Find the using declaration for inheriting this base's constructors. 6951 // FIXME: Don't perform name lookup just to obtain a source location! 6952 DeclarationName Name = 6953 Context.DeclarationNames.getCXXConstructorName(CanonicalBase); 6954 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName); 6955 LookupQualifiedName(Result, CurContext); 6956 UsingDecl *UD = Result.getAsSingle<UsingDecl>(); 6957 SourceLocation UsingLoc = UD ? UD->getLocation() : 6958 ClassDecl->getLocation(); 6959 6960 // C++0x [class.inhctor]p1: The candidate set of inherited constructors 6961 // from the class X named in the using-declaration consists of actual 6962 // constructors and notional constructors that result from the 6963 // transformation of defaulted parameters as follows: 6964 // - all non-template default constructors of X, and 6965 // - for each non-template constructor of X that has at least one 6966 // parameter with a default argument, the set of constructors that 6967 // results from omitting any ellipsis parameter specification and 6968 // successively omitting parameters with a default argument from the 6969 // end of the parameter-type-list. 6970 CXXConstructorDecl *BaseCtor = *CtorIt; 6971 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor(); 6972 const FunctionProtoType *BaseCtorType = 6973 BaseCtor->getType()->getAs<FunctionProtoType>(); 6974 6975 for (unsigned params = BaseCtor->getMinRequiredArguments(), 6976 maxParams = BaseCtor->getNumParams(); 6977 params <= maxParams; ++params) { 6978 // Skip default constructors. They're never inherited. 6979 if (params == 0) 6980 continue; 6981 // Skip copy and move constructors for the same reason. 6982 if (CanBeCopyOrMove && params == 1) 6983 continue; 6984 6985 // Build up a function type for this particular constructor. 6986 // FIXME: The working paper does not consider that the exception spec 6987 // for the inheriting constructor might be larger than that of the 6988 // source. This code doesn't yet, either. When it does, this code will 6989 // need to be delayed until after exception specifications and in-class 6990 // member initializers are attached. 6991 const Type *NewCtorType; 6992 if (params == maxParams) 6993 NewCtorType = BaseCtorType; 6994 else { 6995 SmallVector<QualType, 16> Args; 6996 for (unsigned i = 0; i < params; ++i) { 6997 Args.push_back(BaseCtorType->getArgType(i)); 6998 } 6999 FunctionProtoType::ExtProtoInfo ExtInfo = 7000 BaseCtorType->getExtProtoInfo(); 7001 ExtInfo.Variadic = false; 7002 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(), 7003 Args.data(), params, ExtInfo) 7004 .getTypePtr(); 7005 } 7006 const Type *CanonicalNewCtorType = 7007 Context.getCanonicalType(NewCtorType); 7008 7009 // Now that we have the type, first check if the class already has a 7010 // constructor with this signature. 7011 if (ExistingConstructors.count(CanonicalNewCtorType)) 7012 continue; 7013 7014 // Then we check if we have already declared an inherited constructor 7015 // with this signature. 7016 std::pair<ConstructorToSourceMap::iterator, bool> result = 7017 InheritedConstructors.insert(std::make_pair( 7018 CanonicalNewCtorType, 7019 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0))); 7020 if (!result.second) { 7021 // Already in the map. If it came from a different class, that's an 7022 // error. Not if it's from the same. 7023 CanQualType PreviousBase = result.first->second.first; 7024 if (CanonicalBase != PreviousBase) { 7025 const CXXConstructorDecl *PrevCtor = result.first->second.second; 7026 const CXXConstructorDecl *PrevBaseCtor = 7027 PrevCtor->getInheritedConstructor(); 7028 assert(PrevBaseCtor && "Conflicting constructor was not inherited"); 7029 7030 Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 7031 Diag(BaseCtor->getLocation(), 7032 diag::note_using_decl_constructor_conflict_current_ctor); 7033 Diag(PrevBaseCtor->getLocation(), 7034 diag::note_using_decl_constructor_conflict_previous_ctor); 7035 Diag(PrevCtor->getLocation(), 7036 diag::note_using_decl_constructor_conflict_previous_using); 7037 } 7038 continue; 7039 } 7040 7041 // OK, we're there, now add the constructor. 7042 // C++0x [class.inhctor]p8: [...] that would be performed by a 7043 // user-written inline constructor [...] 7044 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc); 7045 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create( 7046 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0), 7047 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true, 7048 /*ImplicitlyDeclared=*/true, 7049 // FIXME: Due to a defect in the standard, we treat inherited 7050 // constructors as constexpr even if that makes them ill-formed. 7051 /*Constexpr=*/BaseCtor->isConstexpr()); 7052 NewCtor->setAccess(BaseCtor->getAccess()); 7053 7054 // Build up the parameter decls and add them. 7055 SmallVector<ParmVarDecl *, 16> ParamDecls; 7056 for (unsigned i = 0; i < params; ++i) { 7057 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor, 7058 UsingLoc, UsingLoc, 7059 /*IdentifierInfo=*/0, 7060 BaseCtorType->getArgType(i), 7061 /*TInfo=*/0, SC_None, 7062 SC_None, /*DefaultArg=*/0)); 7063 } 7064 NewCtor->setParams(ParamDecls); 7065 NewCtor->setInheritedConstructor(BaseCtor); 7066 7067 ClassDecl->addDecl(NewCtor); 7068 result.first->second.second = NewCtor; 7069 } 7070 } 7071 } 7072} 7073 7074Sema::ImplicitExceptionSpecification 7075Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 7076 CXXRecordDecl *ClassDecl = MD->getParent(); 7077 7078 // C++ [except.spec]p14: 7079 // An implicitly declared special member function (Clause 12) shall have 7080 // an exception-specification. 7081 ImplicitExceptionSpecification ExceptSpec(*this); 7082 if (ClassDecl->isInvalidDecl()) 7083 return ExceptSpec; 7084 7085 // Direct base-class destructors. 7086 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7087 BEnd = ClassDecl->bases_end(); 7088 B != BEnd; ++B) { 7089 if (B->isVirtual()) // Handled below. 7090 continue; 7091 7092 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7093 ExceptSpec.CalledDecl(B->getLocStart(), 7094 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7095 } 7096 7097 // Virtual base-class destructors. 7098 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7099 BEnd = ClassDecl->vbases_end(); 7100 B != BEnd; ++B) { 7101 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 7102 ExceptSpec.CalledDecl(B->getLocStart(), 7103 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 7104 } 7105 7106 // Field destructors. 7107 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7108 FEnd = ClassDecl->field_end(); 7109 F != FEnd; ++F) { 7110 if (const RecordType *RecordTy 7111 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 7112 ExceptSpec.CalledDecl(F->getLocation(), 7113 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 7114 } 7115 7116 return ExceptSpec; 7117} 7118 7119CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 7120 // C++ [class.dtor]p2: 7121 // If a class has no user-declared destructor, a destructor is 7122 // declared implicitly. An implicitly-declared destructor is an 7123 // inline public member of its class. 7124 7125 // Create the actual destructor declaration. 7126 CanQualType ClassType 7127 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 7128 SourceLocation ClassLoc = ClassDecl->getLocation(); 7129 DeclarationName Name 7130 = Context.DeclarationNames.getCXXDestructorName(ClassType); 7131 DeclarationNameInfo NameInfo(Name, ClassLoc); 7132 CXXDestructorDecl *Destructor 7133 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 7134 QualType(), 0, /*isInline=*/true, 7135 /*isImplicitlyDeclared=*/true); 7136 Destructor->setAccess(AS_public); 7137 Destructor->setDefaulted(); 7138 Destructor->setImplicit(); 7139 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 7140 7141 // Build an exception specification pointing back at this destructor. 7142 FunctionProtoType::ExtProtoInfo EPI; 7143 EPI.ExceptionSpecType = EST_Unevaluated; 7144 EPI.ExceptionSpecDecl = Destructor; 7145 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 7146 7147 // Note that we have declared this destructor. 7148 ++ASTContext::NumImplicitDestructorsDeclared; 7149 7150 // Introduce this destructor into its scope. 7151 if (Scope *S = getScopeForContext(ClassDecl)) 7152 PushOnScopeChains(Destructor, S, false); 7153 ClassDecl->addDecl(Destructor); 7154 7155 AddOverriddenMethods(ClassDecl, Destructor); 7156 7157 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 7158 Destructor->setDeletedAsWritten(); 7159 7160 return Destructor; 7161} 7162 7163void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 7164 CXXDestructorDecl *Destructor) { 7165 assert((Destructor->isDefaulted() && 7166 !Destructor->doesThisDeclarationHaveABody() && 7167 !Destructor->isDeleted()) && 7168 "DefineImplicitDestructor - call it for implicit default dtor"); 7169 CXXRecordDecl *ClassDecl = Destructor->getParent(); 7170 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 7171 7172 if (Destructor->isInvalidDecl()) 7173 return; 7174 7175 ImplicitlyDefinedFunctionScope Scope(*this, Destructor); 7176 7177 DiagnosticErrorTrap Trap(Diags); 7178 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 7179 Destructor->getParent()); 7180 7181 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 7182 Diag(CurrentLocation, diag::note_member_synthesized_at) 7183 << CXXDestructor << Context.getTagDeclType(ClassDecl); 7184 7185 Destructor->setInvalidDecl(); 7186 return; 7187 } 7188 7189 SourceLocation Loc = Destructor->getLocation(); 7190 Destructor->setBody(new (Context) CompoundStmt(Loc)); 7191 Destructor->setImplicitlyDefined(true); 7192 Destructor->setUsed(); 7193 MarkVTableUsed(CurrentLocation, ClassDecl); 7194 7195 if (ASTMutationListener *L = getASTMutationListener()) { 7196 L->CompletedImplicitDefinition(Destructor); 7197 } 7198} 7199 7200/// \brief Perform any semantic analysis which needs to be delayed until all 7201/// pending class member declarations have been parsed. 7202void Sema::ActOnFinishCXXMemberDecls() { 7203 // Perform any deferred checking of exception specifications for virtual 7204 // destructors. 7205 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size(); 7206 i != e; ++i) { 7207 const CXXDestructorDecl *Dtor = 7208 DelayedDestructorExceptionSpecChecks[i].first; 7209 assert(!Dtor->getParent()->isDependentType() && 7210 "Should not ever add destructors of templates into the list."); 7211 CheckOverridingFunctionExceptionSpec(Dtor, 7212 DelayedDestructorExceptionSpecChecks[i].second); 7213 } 7214 DelayedDestructorExceptionSpecChecks.clear(); 7215} 7216 7217void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 7218 CXXDestructorDecl *Destructor) { 7219 assert(getLangOpts().CPlusPlus0x && 7220 "adjusting dtor exception specs was introduced in c++11"); 7221 7222 // C++11 [class.dtor]p3: 7223 // A declaration of a destructor that does not have an exception- 7224 // specification is implicitly considered to have the same exception- 7225 // specification as an implicit declaration. 7226 const FunctionProtoType *DtorType = Destructor->getType()-> 7227 getAs<FunctionProtoType>(); 7228 if (DtorType->hasExceptionSpec()) 7229 return; 7230 7231 // Replace the destructor's type, building off the existing one. Fortunately, 7232 // the only thing of interest in the destructor type is its extended info. 7233 // The return and arguments are fixed. 7234 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 7235 EPI.ExceptionSpecType = EST_Unevaluated; 7236 EPI.ExceptionSpecDecl = Destructor; 7237 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI)); 7238 7239 // FIXME: If the destructor has a body that could throw, and the newly created 7240 // spec doesn't allow exceptions, we should emit a warning, because this 7241 // change in behavior can break conforming C++03 programs at runtime. 7242 // However, we don't have a body or an exception specification yet, so it 7243 // needs to be done somewhere else. 7244} 7245 7246/// \brief Builds a statement that copies/moves the given entity from \p From to 7247/// \c To. 7248/// 7249/// This routine is used to copy/move the members of a class with an 7250/// implicitly-declared copy/move assignment operator. When the entities being 7251/// copied are arrays, this routine builds for loops to copy them. 7252/// 7253/// \param S The Sema object used for type-checking. 7254/// 7255/// \param Loc The location where the implicit copy/move is being generated. 7256/// 7257/// \param T The type of the expressions being copied/moved. Both expressions 7258/// must have this type. 7259/// 7260/// \param To The expression we are copying/moving to. 7261/// 7262/// \param From The expression we are copying/moving from. 7263/// 7264/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 7265/// Otherwise, it's a non-static member subobject. 7266/// 7267/// \param Copying Whether we're copying or moving. 7268/// 7269/// \param Depth Internal parameter recording the depth of the recursion. 7270/// 7271/// \returns A statement or a loop that copies the expressions. 7272static StmtResult 7273BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 7274 Expr *To, Expr *From, 7275 bool CopyingBaseSubobject, bool Copying, 7276 unsigned Depth = 0) { 7277 // C++0x [class.copy]p28: 7278 // Each subobject is assigned in the manner appropriate to its type: 7279 // 7280 // - if the subobject is of class type, as if by a call to operator= with 7281 // the subobject as the object expression and the corresponding 7282 // subobject of x as a single function argument (as if by explicit 7283 // qualification; that is, ignoring any possible virtual overriding 7284 // functions in more derived classes); 7285 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 7286 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7287 7288 // Look for operator=. 7289 DeclarationName Name 7290 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 7291 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 7292 S.LookupQualifiedName(OpLookup, ClassDecl, false); 7293 7294 // Filter out any result that isn't a copy/move-assignment operator. 7295 LookupResult::Filter F = OpLookup.makeFilter(); 7296 while (F.hasNext()) { 7297 NamedDecl *D = F.next(); 7298 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 7299 if (Method->isCopyAssignmentOperator() || 7300 (!Copying && Method->isMoveAssignmentOperator())) 7301 continue; 7302 7303 F.erase(); 7304 } 7305 F.done(); 7306 7307 // Suppress the protected check (C++ [class.protected]) for each of the 7308 // assignment operators we found. This strange dance is required when 7309 // we're assigning via a base classes's copy-assignment operator. To 7310 // ensure that we're getting the right base class subobject (without 7311 // ambiguities), we need to cast "this" to that subobject type; to 7312 // ensure that we don't go through the virtual call mechanism, we need 7313 // to qualify the operator= name with the base class (see below). However, 7314 // this means that if the base class has a protected copy assignment 7315 // operator, the protected member access check will fail. So, we 7316 // rewrite "protected" access to "public" access in this case, since we 7317 // know by construction that we're calling from a derived class. 7318 if (CopyingBaseSubobject) { 7319 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 7320 L != LEnd; ++L) { 7321 if (L.getAccess() == AS_protected) 7322 L.setAccess(AS_public); 7323 } 7324 } 7325 7326 // Create the nested-name-specifier that will be used to qualify the 7327 // reference to operator=; this is required to suppress the virtual 7328 // call mechanism. 7329 CXXScopeSpec SS; 7330 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 7331 SS.MakeTrivial(S.Context, 7332 NestedNameSpecifier::Create(S.Context, 0, false, 7333 CanonicalT), 7334 Loc); 7335 7336 // Create the reference to operator=. 7337 ExprResult OpEqualRef 7338 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 7339 /*TemplateKWLoc=*/SourceLocation(), 7340 /*FirstQualifierInScope=*/0, 7341 OpLookup, 7342 /*TemplateArgs=*/0, 7343 /*SuppressQualifierCheck=*/true); 7344 if (OpEqualRef.isInvalid()) 7345 return StmtError(); 7346 7347 // Build the call to the assignment operator. 7348 7349 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 7350 OpEqualRef.takeAs<Expr>(), 7351 Loc, &From, 1, Loc); 7352 if (Call.isInvalid()) 7353 return StmtError(); 7354 7355 return S.Owned(Call.takeAs<Stmt>()); 7356 } 7357 7358 // - if the subobject is of scalar type, the built-in assignment 7359 // operator is used. 7360 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 7361 if (!ArrayTy) { 7362 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 7363 if (Assignment.isInvalid()) 7364 return StmtError(); 7365 7366 return S.Owned(Assignment.takeAs<Stmt>()); 7367 } 7368 7369 // - if the subobject is an array, each element is assigned, in the 7370 // manner appropriate to the element type; 7371 7372 // Construct a loop over the array bounds, e.g., 7373 // 7374 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 7375 // 7376 // that will copy each of the array elements. 7377 QualType SizeType = S.Context.getSizeType(); 7378 7379 // Create the iteration variable. 7380 IdentifierInfo *IterationVarName = 0; 7381 { 7382 SmallString<8> Str; 7383 llvm::raw_svector_ostream OS(Str); 7384 OS << "__i" << Depth; 7385 IterationVarName = &S.Context.Idents.get(OS.str()); 7386 } 7387 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 7388 IterationVarName, SizeType, 7389 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 7390 SC_None, SC_None); 7391 7392 // Initialize the iteration variable to zero. 7393 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 7394 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 7395 7396 // Create a reference to the iteration variable; we'll use this several 7397 // times throughout. 7398 Expr *IterationVarRef 7399 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take(); 7400 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 7401 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take(); 7402 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!"); 7403 7404 // Create the DeclStmt that holds the iteration variable. 7405 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 7406 7407 // Create the comparison against the array bound. 7408 llvm::APInt Upper 7409 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 7410 Expr *Comparison 7411 = new (S.Context) BinaryOperator(IterationVarRefRVal, 7412 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 7413 BO_NE, S.Context.BoolTy, 7414 VK_RValue, OK_Ordinary, Loc); 7415 7416 // Create the pre-increment of the iteration variable. 7417 Expr *Increment 7418 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 7419 VK_LValue, OK_Ordinary, Loc); 7420 7421 // Subscript the "from" and "to" expressions with the iteration variable. 7422 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 7423 IterationVarRefRVal, 7424 Loc)); 7425 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 7426 IterationVarRefRVal, 7427 Loc)); 7428 if (!Copying) // Cast to rvalue 7429 From = CastForMoving(S, From); 7430 7431 // Build the copy/move for an individual element of the array. 7432 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(), 7433 To, From, CopyingBaseSubobject, 7434 Copying, Depth + 1); 7435 if (Copy.isInvalid()) 7436 return StmtError(); 7437 7438 // Construct the loop that copies all elements of this array. 7439 return S.ActOnForStmt(Loc, Loc, InitStmt, 7440 S.MakeFullExpr(Comparison), 7441 0, S.MakeFullExpr(Increment), 7442 Loc, Copy.take()); 7443} 7444 7445/// Determine whether an implicit copy assignment operator for ClassDecl has a 7446/// const argument. 7447/// FIXME: It ought to be possible to store this on the record. 7448static bool isImplicitCopyAssignmentArgConst(Sema &S, 7449 CXXRecordDecl *ClassDecl) { 7450 if (ClassDecl->isInvalidDecl()) 7451 return true; 7452 7453 // C++ [class.copy]p10: 7454 // If the class definition does not explicitly declare a copy 7455 // assignment operator, one is declared implicitly. 7456 // The implicitly-defined copy assignment operator for a class X 7457 // will have the form 7458 // 7459 // X& X::operator=(const X&) 7460 // 7461 // if 7462 // -- each direct base class B of X has a copy assignment operator 7463 // whose parameter is of type const B&, const volatile B& or B, 7464 // and 7465 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7466 BaseEnd = ClassDecl->bases_end(); 7467 Base != BaseEnd; ++Base) { 7468 // We'll handle this below 7469 if (S.getLangOpts().CPlusPlus0x && Base->isVirtual()) 7470 continue; 7471 7472 assert(!Base->getType()->isDependentType() && 7473 "Cannot generate implicit members for class with dependent bases."); 7474 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl(); 7475 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0)) 7476 return false; 7477 } 7478 7479 // In C++11, the above citation has "or virtual" added 7480 if (S.getLangOpts().CPlusPlus0x) { 7481 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7482 BaseEnd = ClassDecl->vbases_end(); 7483 Base != BaseEnd; ++Base) { 7484 assert(!Base->getType()->isDependentType() && 7485 "Cannot generate implicit members for class with dependent bases."); 7486 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl(); 7487 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, 7488 false, 0)) 7489 return false; 7490 } 7491 } 7492 7493 // -- for all the nonstatic data members of X that are of a class 7494 // type M (or array thereof), each such class type has a copy 7495 // assignment operator whose parameter is of type const M&, 7496 // const volatile M& or M. 7497 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7498 FieldEnd = ClassDecl->field_end(); 7499 Field != FieldEnd; ++Field) { 7500 QualType FieldType = S.Context.getBaseElementType(Field->getType()); 7501 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) 7502 if (!S.LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, 7503 false, 0)) 7504 return false; 7505 } 7506 7507 // Otherwise, the implicitly declared copy assignment operator will 7508 // have the form 7509 // 7510 // X& X::operator=(X&) 7511 7512 return true; 7513} 7514 7515Sema::ImplicitExceptionSpecification 7516Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 7517 CXXRecordDecl *ClassDecl = MD->getParent(); 7518 7519 ImplicitExceptionSpecification ExceptSpec(*this); 7520 if (ClassDecl->isInvalidDecl()) 7521 return ExceptSpec; 7522 7523 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 7524 assert(T->getNumArgs() == 1 && "not a copy assignment op"); 7525 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 7526 7527 // C++ [except.spec]p14: 7528 // An implicitly declared special member function (Clause 12) shall have an 7529 // exception-specification. [...] 7530 7531 // It is unspecified whether or not an implicit copy assignment operator 7532 // attempts to deduplicate calls to assignment operators of virtual bases are 7533 // made. As such, this exception specification is effectively unspecified. 7534 // Based on a similar decision made for constness in C++0x, we're erring on 7535 // the side of assuming such calls to be made regardless of whether they 7536 // actually happen. 7537 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7538 BaseEnd = ClassDecl->bases_end(); 7539 Base != BaseEnd; ++Base) { 7540 if (Base->isVirtual()) 7541 continue; 7542 7543 CXXRecordDecl *BaseClassDecl 7544 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7545 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 7546 ArgQuals, false, 0)) 7547 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 7548 } 7549 7550 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7551 BaseEnd = ClassDecl->vbases_end(); 7552 Base != BaseEnd; ++Base) { 7553 CXXRecordDecl *BaseClassDecl 7554 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7555 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 7556 ArgQuals, false, 0)) 7557 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 7558 } 7559 7560 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7561 FieldEnd = ClassDecl->field_end(); 7562 Field != FieldEnd; 7563 ++Field) { 7564 QualType FieldType = Context.getBaseElementType(Field->getType()); 7565 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 7566 if (CXXMethodDecl *CopyAssign = 7567 LookupCopyingAssignment(FieldClassDecl, 7568 ArgQuals | FieldType.getCVRQualifiers(), 7569 false, 0)) 7570 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 7571 } 7572 } 7573 7574 return ExceptSpec; 7575} 7576 7577CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 7578 // Note: The following rules are largely analoguous to the copy 7579 // constructor rules. Note that virtual bases are not taken into account 7580 // for determining the argument type of the operator. Note also that 7581 // operators taking an object instead of a reference are allowed. 7582 7583 QualType ArgType = Context.getTypeDeclType(ClassDecl); 7584 QualType RetType = Context.getLValueReferenceType(ArgType); 7585 if (isImplicitCopyAssignmentArgConst(*this, ClassDecl)) 7586 ArgType = ArgType.withConst(); 7587 ArgType = Context.getLValueReferenceType(ArgType); 7588 7589 // An implicitly-declared copy assignment operator is an inline public 7590 // member of its class. 7591 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 7592 SourceLocation ClassLoc = ClassDecl->getLocation(); 7593 DeclarationNameInfo NameInfo(Name, ClassLoc); 7594 CXXMethodDecl *CopyAssignment 7595 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 7596 /*TInfo=*/0, /*isStatic=*/false, 7597 /*StorageClassAsWritten=*/SC_None, 7598 /*isInline=*/true, /*isConstexpr=*/false, 7599 SourceLocation()); 7600 CopyAssignment->setAccess(AS_public); 7601 CopyAssignment->setDefaulted(); 7602 CopyAssignment->setImplicit(); 7603 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 7604 7605 // Build an exception specification pointing back at this member. 7606 FunctionProtoType::ExtProtoInfo EPI; 7607 EPI.ExceptionSpecType = EST_Unevaluated; 7608 EPI.ExceptionSpecDecl = CopyAssignment; 7609 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI)); 7610 7611 // Add the parameter to the operator. 7612 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 7613 ClassLoc, ClassLoc, /*Id=*/0, 7614 ArgType, /*TInfo=*/0, 7615 SC_None, 7616 SC_None, 0); 7617 CopyAssignment->setParams(FromParam); 7618 7619 // Note that we have added this copy-assignment operator. 7620 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 7621 7622 if (Scope *S = getScopeForContext(ClassDecl)) 7623 PushOnScopeChains(CopyAssignment, S, false); 7624 ClassDecl->addDecl(CopyAssignment); 7625 7626 // C++0x [class.copy]p19: 7627 // .... If the class definition does not explicitly declare a copy 7628 // assignment operator, there is no user-declared move constructor, and 7629 // there is no user-declared move assignment operator, a copy assignment 7630 // operator is implicitly declared as defaulted. 7631 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 7632 CopyAssignment->setDeletedAsWritten(); 7633 7634 AddOverriddenMethods(ClassDecl, CopyAssignment); 7635 return CopyAssignment; 7636} 7637 7638void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 7639 CXXMethodDecl *CopyAssignOperator) { 7640 assert((CopyAssignOperator->isDefaulted() && 7641 CopyAssignOperator->isOverloadedOperator() && 7642 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 7643 !CopyAssignOperator->doesThisDeclarationHaveABody() && 7644 !CopyAssignOperator->isDeleted()) && 7645 "DefineImplicitCopyAssignment called for wrong function"); 7646 7647 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 7648 7649 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 7650 CopyAssignOperator->setInvalidDecl(); 7651 return; 7652 } 7653 7654 CopyAssignOperator->setUsed(); 7655 7656 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator); 7657 DiagnosticErrorTrap Trap(Diags); 7658 7659 // C++0x [class.copy]p30: 7660 // The implicitly-defined or explicitly-defaulted copy assignment operator 7661 // for a non-union class X performs memberwise copy assignment of its 7662 // subobjects. The direct base classes of X are assigned first, in the 7663 // order of their declaration in the base-specifier-list, and then the 7664 // immediate non-static data members of X are assigned, in the order in 7665 // which they were declared in the class definition. 7666 7667 // The statements that form the synthesized function body. 7668 ASTOwningVector<Stmt*> Statements(*this); 7669 7670 // The parameter for the "other" object, which we are copying from. 7671 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 7672 Qualifiers OtherQuals = Other->getType().getQualifiers(); 7673 QualType OtherRefType = Other->getType(); 7674 if (const LValueReferenceType *OtherRef 7675 = OtherRefType->getAs<LValueReferenceType>()) { 7676 OtherRefType = OtherRef->getPointeeType(); 7677 OtherQuals = OtherRefType.getQualifiers(); 7678 } 7679 7680 // Our location for everything implicitly-generated. 7681 SourceLocation Loc = CopyAssignOperator->getLocation(); 7682 7683 // Construct a reference to the "other" object. We'll be using this 7684 // throughout the generated ASTs. 7685 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 7686 assert(OtherRef && "Reference to parameter cannot fail!"); 7687 7688 // Construct the "this" pointer. We'll be using this throughout the generated 7689 // ASTs. 7690 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 7691 assert(This && "Reference to this cannot fail!"); 7692 7693 // Assign base classes. 7694 bool Invalid = false; 7695 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7696 E = ClassDecl->bases_end(); Base != E; ++Base) { 7697 // Form the assignment: 7698 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 7699 QualType BaseType = Base->getType().getUnqualifiedType(); 7700 if (!BaseType->isRecordType()) { 7701 Invalid = true; 7702 continue; 7703 } 7704 7705 CXXCastPath BasePath; 7706 BasePath.push_back(Base); 7707 7708 // Construct the "from" expression, which is an implicit cast to the 7709 // appropriately-qualified base type. 7710 Expr *From = OtherRef; 7711 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 7712 CK_UncheckedDerivedToBase, 7713 VK_LValue, &BasePath).take(); 7714 7715 // Dereference "this". 7716 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 7717 7718 // Implicitly cast "this" to the appropriately-qualified base type. 7719 To = ImpCastExprToType(To.take(), 7720 Context.getCVRQualifiedType(BaseType, 7721 CopyAssignOperator->getTypeQualifiers()), 7722 CK_UncheckedDerivedToBase, 7723 VK_LValue, &BasePath); 7724 7725 // Build the copy. 7726 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType, 7727 To.get(), From, 7728 /*CopyingBaseSubobject=*/true, 7729 /*Copying=*/true); 7730 if (Copy.isInvalid()) { 7731 Diag(CurrentLocation, diag::note_member_synthesized_at) 7732 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7733 CopyAssignOperator->setInvalidDecl(); 7734 return; 7735 } 7736 7737 // Success! Record the copy. 7738 Statements.push_back(Copy.takeAs<Expr>()); 7739 } 7740 7741 // \brief Reference to the __builtin_memcpy function. 7742 Expr *BuiltinMemCpyRef = 0; 7743 // \brief Reference to the __builtin_objc_memmove_collectable function. 7744 Expr *CollectableMemCpyRef = 0; 7745 7746 // Assign non-static members. 7747 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7748 FieldEnd = ClassDecl->field_end(); 7749 Field != FieldEnd; ++Field) { 7750 if (Field->isUnnamedBitfield()) 7751 continue; 7752 7753 // Check for members of reference type; we can't copy those. 7754 if (Field->getType()->isReferenceType()) { 7755 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 7756 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 7757 Diag(Field->getLocation(), diag::note_declared_at); 7758 Diag(CurrentLocation, diag::note_member_synthesized_at) 7759 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7760 Invalid = true; 7761 continue; 7762 } 7763 7764 // Check for members of const-qualified, non-class type. 7765 QualType BaseType = Context.getBaseElementType(Field->getType()); 7766 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 7767 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 7768 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 7769 Diag(Field->getLocation(), diag::note_declared_at); 7770 Diag(CurrentLocation, diag::note_member_synthesized_at) 7771 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7772 Invalid = true; 7773 continue; 7774 } 7775 7776 // Suppress assigning zero-width bitfields. 7777 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 7778 continue; 7779 7780 QualType FieldType = Field->getType().getNonReferenceType(); 7781 if (FieldType->isIncompleteArrayType()) { 7782 assert(ClassDecl->hasFlexibleArrayMember() && 7783 "Incomplete array type is not valid"); 7784 continue; 7785 } 7786 7787 // Build references to the field in the object we're copying from and to. 7788 CXXScopeSpec SS; // Intentionally empty 7789 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 7790 LookupMemberName); 7791 MemberLookup.addDecl(*Field); 7792 MemberLookup.resolveKind(); 7793 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 7794 Loc, /*IsArrow=*/false, 7795 SS, SourceLocation(), 0, 7796 MemberLookup, 0); 7797 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 7798 Loc, /*IsArrow=*/true, 7799 SS, SourceLocation(), 0, 7800 MemberLookup, 0); 7801 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 7802 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 7803 7804 // If the field should be copied with __builtin_memcpy rather than via 7805 // explicit assignments, do so. This optimization only applies for arrays 7806 // of scalars and arrays of class type with trivial copy-assignment 7807 // operators. 7808 if (FieldType->isArrayType() && !FieldType.isVolatileQualified() 7809 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) { 7810 // Compute the size of the memory buffer to be copied. 7811 QualType SizeType = Context.getSizeType(); 7812 llvm::APInt Size(Context.getTypeSize(SizeType), 7813 Context.getTypeSizeInChars(BaseType).getQuantity()); 7814 for (const ConstantArrayType *Array 7815 = Context.getAsConstantArrayType(FieldType); 7816 Array; 7817 Array = Context.getAsConstantArrayType(Array->getElementType())) { 7818 llvm::APInt ArraySize 7819 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 7820 Size *= ArraySize; 7821 } 7822 7823 // Take the address of the field references for "from" and "to". 7824 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get()); 7825 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get()); 7826 7827 bool NeedsCollectableMemCpy = 7828 (BaseType->isRecordType() && 7829 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 7830 7831 if (NeedsCollectableMemCpy) { 7832 if (!CollectableMemCpyRef) { 7833 // Create a reference to the __builtin_objc_memmove_collectable function. 7834 LookupResult R(*this, 7835 &Context.Idents.get("__builtin_objc_memmove_collectable"), 7836 Loc, LookupOrdinaryName); 7837 LookupName(R, TUScope, true); 7838 7839 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 7840 if (!CollectableMemCpy) { 7841 // Something went horribly wrong earlier, and we will have 7842 // complained about it. 7843 Invalid = true; 7844 continue; 7845 } 7846 7847 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 7848 CollectableMemCpy->getType(), 7849 VK_LValue, Loc, 0).take(); 7850 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 7851 } 7852 } 7853 // Create a reference to the __builtin_memcpy builtin function. 7854 else if (!BuiltinMemCpyRef) { 7855 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 7856 LookupOrdinaryName); 7857 LookupName(R, TUScope, true); 7858 7859 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 7860 if (!BuiltinMemCpy) { 7861 // Something went horribly wrong earlier, and we will have complained 7862 // about it. 7863 Invalid = true; 7864 continue; 7865 } 7866 7867 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 7868 BuiltinMemCpy->getType(), 7869 VK_LValue, Loc, 0).take(); 7870 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 7871 } 7872 7873 ASTOwningVector<Expr*> CallArgs(*this); 7874 CallArgs.push_back(To.takeAs<Expr>()); 7875 CallArgs.push_back(From.takeAs<Expr>()); 7876 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 7877 ExprResult Call = ExprError(); 7878 if (NeedsCollectableMemCpy) 7879 Call = ActOnCallExpr(/*Scope=*/0, 7880 CollectableMemCpyRef, 7881 Loc, move_arg(CallArgs), 7882 Loc); 7883 else 7884 Call = ActOnCallExpr(/*Scope=*/0, 7885 BuiltinMemCpyRef, 7886 Loc, move_arg(CallArgs), 7887 Loc); 7888 7889 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 7890 Statements.push_back(Call.takeAs<Expr>()); 7891 continue; 7892 } 7893 7894 // Build the copy of this field. 7895 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType, 7896 To.get(), From.get(), 7897 /*CopyingBaseSubobject=*/false, 7898 /*Copying=*/true); 7899 if (Copy.isInvalid()) { 7900 Diag(CurrentLocation, diag::note_member_synthesized_at) 7901 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7902 CopyAssignOperator->setInvalidDecl(); 7903 return; 7904 } 7905 7906 // Success! Record the copy. 7907 Statements.push_back(Copy.takeAs<Stmt>()); 7908 } 7909 7910 if (!Invalid) { 7911 // Add a "return *this;" 7912 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 7913 7914 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 7915 if (Return.isInvalid()) 7916 Invalid = true; 7917 else { 7918 Statements.push_back(Return.takeAs<Stmt>()); 7919 7920 if (Trap.hasErrorOccurred()) { 7921 Diag(CurrentLocation, diag::note_member_synthesized_at) 7922 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 7923 Invalid = true; 7924 } 7925 } 7926 } 7927 7928 if (Invalid) { 7929 CopyAssignOperator->setInvalidDecl(); 7930 return; 7931 } 7932 7933 StmtResult Body; 7934 { 7935 CompoundScopeRAII CompoundScope(*this); 7936 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 7937 /*isStmtExpr=*/false); 7938 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 7939 } 7940 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 7941 7942 if (ASTMutationListener *L = getASTMutationListener()) { 7943 L->CompletedImplicitDefinition(CopyAssignOperator); 7944 } 7945} 7946 7947Sema::ImplicitExceptionSpecification 7948Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 7949 CXXRecordDecl *ClassDecl = MD->getParent(); 7950 7951 ImplicitExceptionSpecification ExceptSpec(*this); 7952 if (ClassDecl->isInvalidDecl()) 7953 return ExceptSpec; 7954 7955 // C++0x [except.spec]p14: 7956 // An implicitly declared special member function (Clause 12) shall have an 7957 // exception-specification. [...] 7958 7959 // It is unspecified whether or not an implicit move assignment operator 7960 // attempts to deduplicate calls to assignment operators of virtual bases are 7961 // made. As such, this exception specification is effectively unspecified. 7962 // Based on a similar decision made for constness in C++0x, we're erring on 7963 // the side of assuming such calls to be made regardless of whether they 7964 // actually happen. 7965 // Note that a move constructor is not implicitly declared when there are 7966 // virtual bases, but it can still be user-declared and explicitly defaulted. 7967 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 7968 BaseEnd = ClassDecl->bases_end(); 7969 Base != BaseEnd; ++Base) { 7970 if (Base->isVirtual()) 7971 continue; 7972 7973 CXXRecordDecl *BaseClassDecl 7974 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7975 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 7976 0, false, 0)) 7977 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 7978 } 7979 7980 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 7981 BaseEnd = ClassDecl->vbases_end(); 7982 Base != BaseEnd; ++Base) { 7983 CXXRecordDecl *BaseClassDecl 7984 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 7985 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 7986 0, false, 0)) 7987 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 7988 } 7989 7990 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 7991 FieldEnd = ClassDecl->field_end(); 7992 Field != FieldEnd; 7993 ++Field) { 7994 QualType FieldType = Context.getBaseElementType(Field->getType()); 7995 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 7996 if (CXXMethodDecl *MoveAssign = 7997 LookupMovingAssignment(FieldClassDecl, 7998 FieldType.getCVRQualifiers(), 7999 false, 0)) 8000 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 8001 } 8002 } 8003 8004 return ExceptSpec; 8005} 8006 8007/// Determine whether the class type has any direct or indirect virtual base 8008/// classes which have a non-trivial move assignment operator. 8009static bool 8010hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) { 8011 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8012 BaseEnd = ClassDecl->vbases_end(); 8013 Base != BaseEnd; ++Base) { 8014 CXXRecordDecl *BaseClass = 8015 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8016 8017 // Try to declare the move assignment. If it would be deleted, then the 8018 // class does not have a non-trivial move assignment. 8019 if (BaseClass->needsImplicitMoveAssignment()) 8020 S.DeclareImplicitMoveAssignment(BaseClass); 8021 8022 // If the class has both a trivial move assignment and a non-trivial move 8023 // assignment, hasTrivialMoveAssignment() is false. 8024 if (BaseClass->hasDeclaredMoveAssignment() && 8025 !BaseClass->hasTrivialMoveAssignment()) 8026 return true; 8027 } 8028 8029 return false; 8030} 8031 8032/// Determine whether the given type either has a move constructor or is 8033/// trivially copyable. 8034static bool 8035hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) { 8036 Type = S.Context.getBaseElementType(Type); 8037 8038 // FIXME: Technically, non-trivially-copyable non-class types, such as 8039 // reference types, are supposed to return false here, but that appears 8040 // to be a standard defect. 8041 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl(); 8042 if (!ClassDecl || !ClassDecl->getDefinition()) 8043 return true; 8044 8045 if (Type.isTriviallyCopyableType(S.Context)) 8046 return true; 8047 8048 if (IsConstructor) { 8049 if (ClassDecl->needsImplicitMoveConstructor()) 8050 S.DeclareImplicitMoveConstructor(ClassDecl); 8051 return ClassDecl->hasDeclaredMoveConstructor(); 8052 } 8053 8054 if (ClassDecl->needsImplicitMoveAssignment()) 8055 S.DeclareImplicitMoveAssignment(ClassDecl); 8056 return ClassDecl->hasDeclaredMoveAssignment(); 8057} 8058 8059/// Determine whether all non-static data members and direct or virtual bases 8060/// of class \p ClassDecl have either a move operation, or are trivially 8061/// copyable. 8062static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl, 8063 bool IsConstructor) { 8064 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8065 BaseEnd = ClassDecl->bases_end(); 8066 Base != BaseEnd; ++Base) { 8067 if (Base->isVirtual()) 8068 continue; 8069 8070 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 8071 return false; 8072 } 8073 8074 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8075 BaseEnd = ClassDecl->vbases_end(); 8076 Base != BaseEnd; ++Base) { 8077 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 8078 return false; 8079 } 8080 8081 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8082 FieldEnd = ClassDecl->field_end(); 8083 Field != FieldEnd; ++Field) { 8084 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor)) 8085 return false; 8086 } 8087 8088 return true; 8089} 8090 8091CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 8092 // C++11 [class.copy]p20: 8093 // If the definition of a class X does not explicitly declare a move 8094 // assignment operator, one will be implicitly declared as defaulted 8095 // if and only if: 8096 // 8097 // - [first 4 bullets] 8098 assert(ClassDecl->needsImplicitMoveAssignment()); 8099 8100 // [Checked after we build the declaration] 8101 // - the move assignment operator would not be implicitly defined as 8102 // deleted, 8103 8104 // [DR1402]: 8105 // - X has no direct or indirect virtual base class with a non-trivial 8106 // move assignment operator, and 8107 // - each of X's non-static data members and direct or virtual base classes 8108 // has a type that either has a move assignment operator or is trivially 8109 // copyable. 8110 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) || 8111 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) { 8112 ClassDecl->setFailedImplicitMoveAssignment(); 8113 return 0; 8114 } 8115 8116 // Note: The following rules are largely analoguous to the move 8117 // constructor rules. 8118 8119 QualType ArgType = Context.getTypeDeclType(ClassDecl); 8120 QualType RetType = Context.getLValueReferenceType(ArgType); 8121 ArgType = Context.getRValueReferenceType(ArgType); 8122 8123 // An implicitly-declared move assignment operator is an inline public 8124 // member of its class. 8125 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8126 SourceLocation ClassLoc = ClassDecl->getLocation(); 8127 DeclarationNameInfo NameInfo(Name, ClassLoc); 8128 CXXMethodDecl *MoveAssignment 8129 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 8130 /*TInfo=*/0, /*isStatic=*/false, 8131 /*StorageClassAsWritten=*/SC_None, 8132 /*isInline=*/true, 8133 /*isConstexpr=*/false, 8134 SourceLocation()); 8135 MoveAssignment->setAccess(AS_public); 8136 MoveAssignment->setDefaulted(); 8137 MoveAssignment->setImplicit(); 8138 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment()); 8139 8140 // Build an exception specification pointing back at this member. 8141 FunctionProtoType::ExtProtoInfo EPI; 8142 EPI.ExceptionSpecType = EST_Unevaluated; 8143 EPI.ExceptionSpecDecl = MoveAssignment; 8144 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI)); 8145 8146 // Add the parameter to the operator. 8147 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 8148 ClassLoc, ClassLoc, /*Id=*/0, 8149 ArgType, /*TInfo=*/0, 8150 SC_None, 8151 SC_None, 0); 8152 MoveAssignment->setParams(FromParam); 8153 8154 // Note that we have added this copy-assignment operator. 8155 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 8156 8157 // C++0x [class.copy]p9: 8158 // If the definition of a class X does not explicitly declare a move 8159 // assignment operator, one will be implicitly declared as defaulted if and 8160 // only if: 8161 // [...] 8162 // - the move assignment operator would not be implicitly defined as 8163 // deleted. 8164 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 8165 // Cache this result so that we don't try to generate this over and over 8166 // on every lookup, leaking memory and wasting time. 8167 ClassDecl->setFailedImplicitMoveAssignment(); 8168 return 0; 8169 } 8170 8171 if (Scope *S = getScopeForContext(ClassDecl)) 8172 PushOnScopeChains(MoveAssignment, S, false); 8173 ClassDecl->addDecl(MoveAssignment); 8174 8175 AddOverriddenMethods(ClassDecl, MoveAssignment); 8176 return MoveAssignment; 8177} 8178 8179void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 8180 CXXMethodDecl *MoveAssignOperator) { 8181 assert((MoveAssignOperator->isDefaulted() && 8182 MoveAssignOperator->isOverloadedOperator() && 8183 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 8184 !MoveAssignOperator->doesThisDeclarationHaveABody() && 8185 !MoveAssignOperator->isDeleted()) && 8186 "DefineImplicitMoveAssignment called for wrong function"); 8187 8188 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 8189 8190 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 8191 MoveAssignOperator->setInvalidDecl(); 8192 return; 8193 } 8194 8195 MoveAssignOperator->setUsed(); 8196 8197 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator); 8198 DiagnosticErrorTrap Trap(Diags); 8199 8200 // C++0x [class.copy]p28: 8201 // The implicitly-defined or move assignment operator for a non-union class 8202 // X performs memberwise move assignment of its subobjects. The direct base 8203 // classes of X are assigned first, in the order of their declaration in the 8204 // base-specifier-list, and then the immediate non-static data members of X 8205 // are assigned, in the order in which they were declared in the class 8206 // definition. 8207 8208 // The statements that form the synthesized function body. 8209 ASTOwningVector<Stmt*> Statements(*this); 8210 8211 // The parameter for the "other" object, which we are move from. 8212 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 8213 QualType OtherRefType = Other->getType()-> 8214 getAs<RValueReferenceType>()->getPointeeType(); 8215 assert(OtherRefType.getQualifiers() == 0 && 8216 "Bad argument type of defaulted move assignment"); 8217 8218 // Our location for everything implicitly-generated. 8219 SourceLocation Loc = MoveAssignOperator->getLocation(); 8220 8221 // Construct a reference to the "other" object. We'll be using this 8222 // throughout the generated ASTs. 8223 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 8224 assert(OtherRef && "Reference to parameter cannot fail!"); 8225 // Cast to rvalue. 8226 OtherRef = CastForMoving(*this, OtherRef); 8227 8228 // Construct the "this" pointer. We'll be using this throughout the generated 8229 // ASTs. 8230 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 8231 assert(This && "Reference to this cannot fail!"); 8232 8233 // Assign base classes. 8234 bool Invalid = false; 8235 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8236 E = ClassDecl->bases_end(); Base != E; ++Base) { 8237 // Form the assignment: 8238 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 8239 QualType BaseType = Base->getType().getUnqualifiedType(); 8240 if (!BaseType->isRecordType()) { 8241 Invalid = true; 8242 continue; 8243 } 8244 8245 CXXCastPath BasePath; 8246 BasePath.push_back(Base); 8247 8248 // Construct the "from" expression, which is an implicit cast to the 8249 // appropriately-qualified base type. 8250 Expr *From = OtherRef; 8251 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase, 8252 VK_XValue, &BasePath).take(); 8253 8254 // Dereference "this". 8255 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8256 8257 // Implicitly cast "this" to the appropriately-qualified base type. 8258 To = ImpCastExprToType(To.take(), 8259 Context.getCVRQualifiedType(BaseType, 8260 MoveAssignOperator->getTypeQualifiers()), 8261 CK_UncheckedDerivedToBase, 8262 VK_LValue, &BasePath); 8263 8264 // Build the move. 8265 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType, 8266 To.get(), From, 8267 /*CopyingBaseSubobject=*/true, 8268 /*Copying=*/false); 8269 if (Move.isInvalid()) { 8270 Diag(CurrentLocation, diag::note_member_synthesized_at) 8271 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8272 MoveAssignOperator->setInvalidDecl(); 8273 return; 8274 } 8275 8276 // Success! Record the move. 8277 Statements.push_back(Move.takeAs<Expr>()); 8278 } 8279 8280 // \brief Reference to the __builtin_memcpy function. 8281 Expr *BuiltinMemCpyRef = 0; 8282 // \brief Reference to the __builtin_objc_memmove_collectable function. 8283 Expr *CollectableMemCpyRef = 0; 8284 8285 // Assign non-static members. 8286 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8287 FieldEnd = ClassDecl->field_end(); 8288 Field != FieldEnd; ++Field) { 8289 if (Field->isUnnamedBitfield()) 8290 continue; 8291 8292 // Check for members of reference type; we can't move those. 8293 if (Field->getType()->isReferenceType()) { 8294 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8295 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 8296 Diag(Field->getLocation(), diag::note_declared_at); 8297 Diag(CurrentLocation, diag::note_member_synthesized_at) 8298 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8299 Invalid = true; 8300 continue; 8301 } 8302 8303 // Check for members of const-qualified, non-class type. 8304 QualType BaseType = Context.getBaseElementType(Field->getType()); 8305 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 8306 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 8307 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 8308 Diag(Field->getLocation(), diag::note_declared_at); 8309 Diag(CurrentLocation, diag::note_member_synthesized_at) 8310 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8311 Invalid = true; 8312 continue; 8313 } 8314 8315 // Suppress assigning zero-width bitfields. 8316 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 8317 continue; 8318 8319 QualType FieldType = Field->getType().getNonReferenceType(); 8320 if (FieldType->isIncompleteArrayType()) { 8321 assert(ClassDecl->hasFlexibleArrayMember() && 8322 "Incomplete array type is not valid"); 8323 continue; 8324 } 8325 8326 // Build references to the field in the object we're copying from and to. 8327 CXXScopeSpec SS; // Intentionally empty 8328 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 8329 LookupMemberName); 8330 MemberLookup.addDecl(*Field); 8331 MemberLookup.resolveKind(); 8332 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 8333 Loc, /*IsArrow=*/false, 8334 SS, SourceLocation(), 0, 8335 MemberLookup, 0); 8336 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 8337 Loc, /*IsArrow=*/true, 8338 SS, SourceLocation(), 0, 8339 MemberLookup, 0); 8340 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 8341 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 8342 8343 assert(!From.get()->isLValue() && // could be xvalue or prvalue 8344 "Member reference with rvalue base must be rvalue except for reference " 8345 "members, which aren't allowed for move assignment."); 8346 8347 // If the field should be copied with __builtin_memcpy rather than via 8348 // explicit assignments, do so. This optimization only applies for arrays 8349 // of scalars and arrays of class type with trivial move-assignment 8350 // operators. 8351 if (FieldType->isArrayType() && !FieldType.isVolatileQualified() 8352 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) { 8353 // Compute the size of the memory buffer to be copied. 8354 QualType SizeType = Context.getSizeType(); 8355 llvm::APInt Size(Context.getTypeSize(SizeType), 8356 Context.getTypeSizeInChars(BaseType).getQuantity()); 8357 for (const ConstantArrayType *Array 8358 = Context.getAsConstantArrayType(FieldType); 8359 Array; 8360 Array = Context.getAsConstantArrayType(Array->getElementType())) { 8361 llvm::APInt ArraySize 8362 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 8363 Size *= ArraySize; 8364 } 8365 8366 // Take the address of the field references for "from" and "to". We 8367 // directly construct UnaryOperators here because semantic analysis 8368 // does not permit us to take the address of an xvalue. 8369 From = new (Context) UnaryOperator(From.get(), UO_AddrOf, 8370 Context.getPointerType(From.get()->getType()), 8371 VK_RValue, OK_Ordinary, Loc); 8372 To = new (Context) UnaryOperator(To.get(), UO_AddrOf, 8373 Context.getPointerType(To.get()->getType()), 8374 VK_RValue, OK_Ordinary, Loc); 8375 8376 bool NeedsCollectableMemCpy = 8377 (BaseType->isRecordType() && 8378 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 8379 8380 if (NeedsCollectableMemCpy) { 8381 if (!CollectableMemCpyRef) { 8382 // Create a reference to the __builtin_objc_memmove_collectable function. 8383 LookupResult R(*this, 8384 &Context.Idents.get("__builtin_objc_memmove_collectable"), 8385 Loc, LookupOrdinaryName); 8386 LookupName(R, TUScope, true); 8387 8388 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 8389 if (!CollectableMemCpy) { 8390 // Something went horribly wrong earlier, and we will have 8391 // complained about it. 8392 Invalid = true; 8393 continue; 8394 } 8395 8396 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 8397 CollectableMemCpy->getType(), 8398 VK_LValue, Loc, 0).take(); 8399 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 8400 } 8401 } 8402 // Create a reference to the __builtin_memcpy builtin function. 8403 else if (!BuiltinMemCpyRef) { 8404 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 8405 LookupOrdinaryName); 8406 LookupName(R, TUScope, true); 8407 8408 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 8409 if (!BuiltinMemCpy) { 8410 // Something went horribly wrong earlier, and we will have complained 8411 // about it. 8412 Invalid = true; 8413 continue; 8414 } 8415 8416 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 8417 BuiltinMemCpy->getType(), 8418 VK_LValue, Loc, 0).take(); 8419 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 8420 } 8421 8422 ASTOwningVector<Expr*> CallArgs(*this); 8423 CallArgs.push_back(To.takeAs<Expr>()); 8424 CallArgs.push_back(From.takeAs<Expr>()); 8425 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 8426 ExprResult Call = ExprError(); 8427 if (NeedsCollectableMemCpy) 8428 Call = ActOnCallExpr(/*Scope=*/0, 8429 CollectableMemCpyRef, 8430 Loc, move_arg(CallArgs), 8431 Loc); 8432 else 8433 Call = ActOnCallExpr(/*Scope=*/0, 8434 BuiltinMemCpyRef, 8435 Loc, move_arg(CallArgs), 8436 Loc); 8437 8438 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8439 Statements.push_back(Call.takeAs<Expr>()); 8440 continue; 8441 } 8442 8443 // Build the move of this field. 8444 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType, 8445 To.get(), From.get(), 8446 /*CopyingBaseSubobject=*/false, 8447 /*Copying=*/false); 8448 if (Move.isInvalid()) { 8449 Diag(CurrentLocation, diag::note_member_synthesized_at) 8450 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8451 MoveAssignOperator->setInvalidDecl(); 8452 return; 8453 } 8454 8455 // Success! Record the copy. 8456 Statements.push_back(Move.takeAs<Stmt>()); 8457 } 8458 8459 if (!Invalid) { 8460 // Add a "return *this;" 8461 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 8462 8463 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 8464 if (Return.isInvalid()) 8465 Invalid = true; 8466 else { 8467 Statements.push_back(Return.takeAs<Stmt>()); 8468 8469 if (Trap.hasErrorOccurred()) { 8470 Diag(CurrentLocation, diag::note_member_synthesized_at) 8471 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 8472 Invalid = true; 8473 } 8474 } 8475 } 8476 8477 if (Invalid) { 8478 MoveAssignOperator->setInvalidDecl(); 8479 return; 8480 } 8481 8482 StmtResult Body; 8483 { 8484 CompoundScopeRAII CompoundScope(*this); 8485 Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 8486 /*isStmtExpr=*/false); 8487 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 8488 } 8489 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 8490 8491 if (ASTMutationListener *L = getASTMutationListener()) { 8492 L->CompletedImplicitDefinition(MoveAssignOperator); 8493 } 8494} 8495 8496/// Determine whether an implicit copy constructor for ClassDecl has a const 8497/// argument. 8498/// FIXME: It ought to be possible to store this on the record. 8499static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl) { 8500 if (ClassDecl->isInvalidDecl()) 8501 return true; 8502 8503 // C++ [class.copy]p5: 8504 // The implicitly-declared copy constructor for a class X will 8505 // have the form 8506 // 8507 // X::X(const X&) 8508 // 8509 // if 8510 // -- each direct or virtual base class B of X has a copy 8511 // constructor whose first parameter is of type const B& or 8512 // const volatile B&, and 8513 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8514 BaseEnd = ClassDecl->bases_end(); 8515 Base != BaseEnd; ++Base) { 8516 // Virtual bases are handled below. 8517 if (Base->isVirtual()) 8518 continue; 8519 8520 CXXRecordDecl *BaseClassDecl 8521 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8522 // FIXME: This lookup is wrong. If the copy ctor for a member or base is 8523 // ambiguous, we should still produce a constructor with a const-qualified 8524 // parameter. 8525 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const)) 8526 return false; 8527 } 8528 8529 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8530 BaseEnd = ClassDecl->vbases_end(); 8531 Base != BaseEnd; ++Base) { 8532 CXXRecordDecl *BaseClassDecl 8533 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8534 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const)) 8535 return false; 8536 } 8537 8538 // -- for all the nonstatic data members of X that are of a 8539 // class type M (or array thereof), each such class type 8540 // has a copy constructor whose first parameter is of type 8541 // const M& or const volatile M&. 8542 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8543 FieldEnd = ClassDecl->field_end(); 8544 Field != FieldEnd; ++Field) { 8545 QualType FieldType = S.Context.getBaseElementType(Field->getType()); 8546 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8547 if (!S.LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const)) 8548 return false; 8549 } 8550 } 8551 8552 // Otherwise, the implicitly declared copy constructor will have 8553 // the form 8554 // 8555 // X::X(X&) 8556 8557 return true; 8558} 8559 8560Sema::ImplicitExceptionSpecification 8561Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 8562 CXXRecordDecl *ClassDecl = MD->getParent(); 8563 8564 ImplicitExceptionSpecification ExceptSpec(*this); 8565 if (ClassDecl->isInvalidDecl()) 8566 return ExceptSpec; 8567 8568 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 8569 assert(T->getNumArgs() >= 1 && "not a copy ctor"); 8570 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 8571 8572 // C++ [except.spec]p14: 8573 // An implicitly declared special member function (Clause 12) shall have an 8574 // exception-specification. [...] 8575 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 8576 BaseEnd = ClassDecl->bases_end(); 8577 Base != BaseEnd; 8578 ++Base) { 8579 // Virtual bases are handled below. 8580 if (Base->isVirtual()) 8581 continue; 8582 8583 CXXRecordDecl *BaseClassDecl 8584 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8585 if (CXXConstructorDecl *CopyConstructor = 8586 LookupCopyingConstructor(BaseClassDecl, Quals)) 8587 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 8588 } 8589 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 8590 BaseEnd = ClassDecl->vbases_end(); 8591 Base != BaseEnd; 8592 ++Base) { 8593 CXXRecordDecl *BaseClassDecl 8594 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 8595 if (CXXConstructorDecl *CopyConstructor = 8596 LookupCopyingConstructor(BaseClassDecl, Quals)) 8597 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 8598 } 8599 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 8600 FieldEnd = ClassDecl->field_end(); 8601 Field != FieldEnd; 8602 ++Field) { 8603 QualType FieldType = Context.getBaseElementType(Field->getType()); 8604 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 8605 if (CXXConstructorDecl *CopyConstructor = 8606 LookupCopyingConstructor(FieldClassDecl, 8607 Quals | FieldType.getCVRQualifiers())) 8608 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 8609 } 8610 } 8611 8612 return ExceptSpec; 8613} 8614 8615CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 8616 CXXRecordDecl *ClassDecl) { 8617 // C++ [class.copy]p4: 8618 // If the class definition does not explicitly declare a copy 8619 // constructor, one is declared implicitly. 8620 8621 QualType ClassType = Context.getTypeDeclType(ClassDecl); 8622 QualType ArgType = ClassType; 8623 bool Const = isImplicitCopyCtorArgConst(*this, ClassDecl); 8624 if (Const) 8625 ArgType = ArgType.withConst(); 8626 ArgType = Context.getLValueReferenceType(ArgType); 8627 8628 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8629 CXXCopyConstructor, 8630 Const); 8631 8632 DeclarationName Name 8633 = Context.DeclarationNames.getCXXConstructorName( 8634 Context.getCanonicalType(ClassType)); 8635 SourceLocation ClassLoc = ClassDecl->getLocation(); 8636 DeclarationNameInfo NameInfo(Name, ClassLoc); 8637 8638 // An implicitly-declared copy constructor is an inline public 8639 // member of its class. 8640 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 8641 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 8642 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8643 Constexpr); 8644 CopyConstructor->setAccess(AS_public); 8645 CopyConstructor->setDefaulted(); 8646 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 8647 8648 // Build an exception specification pointing back at this member. 8649 FunctionProtoType::ExtProtoInfo EPI; 8650 EPI.ExceptionSpecType = EST_Unevaluated; 8651 EPI.ExceptionSpecDecl = CopyConstructor; 8652 CopyConstructor->setType( 8653 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 8654 8655 // Note that we have declared this constructor. 8656 ++ASTContext::NumImplicitCopyConstructorsDeclared; 8657 8658 // Add the parameter to the constructor. 8659 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 8660 ClassLoc, ClassLoc, 8661 /*IdentifierInfo=*/0, 8662 ArgType, /*TInfo=*/0, 8663 SC_None, 8664 SC_None, 0); 8665 CopyConstructor->setParams(FromParam); 8666 8667 if (Scope *S = getScopeForContext(ClassDecl)) 8668 PushOnScopeChains(CopyConstructor, S, false); 8669 ClassDecl->addDecl(CopyConstructor); 8670 8671 // C++11 [class.copy]p8: 8672 // ... If the class definition does not explicitly declare a copy 8673 // constructor, there is no user-declared move constructor, and there is no 8674 // user-declared move assignment operator, a copy constructor is implicitly 8675 // declared as defaulted. 8676 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 8677 CopyConstructor->setDeletedAsWritten(); 8678 8679 return CopyConstructor; 8680} 8681 8682void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 8683 CXXConstructorDecl *CopyConstructor) { 8684 assert((CopyConstructor->isDefaulted() && 8685 CopyConstructor->isCopyConstructor() && 8686 !CopyConstructor->doesThisDeclarationHaveABody() && 8687 !CopyConstructor->isDeleted()) && 8688 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 8689 8690 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 8691 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 8692 8693 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor); 8694 DiagnosticErrorTrap Trap(Diags); 8695 8696 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) || 8697 Trap.hasErrorOccurred()) { 8698 Diag(CurrentLocation, diag::note_member_synthesized_at) 8699 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 8700 CopyConstructor->setInvalidDecl(); 8701 } else { 8702 Sema::CompoundScopeRAII CompoundScope(*this); 8703 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 8704 CopyConstructor->getLocation(), 8705 MultiStmtArg(*this, 0, 0), 8706 /*isStmtExpr=*/false) 8707 .takeAs<Stmt>()); 8708 CopyConstructor->setImplicitlyDefined(true); 8709 } 8710 8711 CopyConstructor->setUsed(); 8712 if (ASTMutationListener *L = getASTMutationListener()) { 8713 L->CompletedImplicitDefinition(CopyConstructor); 8714 } 8715} 8716 8717Sema::ImplicitExceptionSpecification 8718Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 8719 CXXRecordDecl *ClassDecl = MD->getParent(); 8720 8721 // C++ [except.spec]p14: 8722 // An implicitly declared special member function (Clause 12) shall have an 8723 // exception-specification. [...] 8724 ImplicitExceptionSpecification ExceptSpec(*this); 8725 if (ClassDecl->isInvalidDecl()) 8726 return ExceptSpec; 8727 8728 // Direct base-class constructors. 8729 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8730 BEnd = ClassDecl->bases_end(); 8731 B != BEnd; ++B) { 8732 if (B->isVirtual()) // Handled below. 8733 continue; 8734 8735 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8736 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8737 CXXConstructorDecl *Constructor = 8738 LookupMovingConstructor(BaseClassDecl, 0); 8739 // If this is a deleted function, add it anyway. This might be conformant 8740 // with the standard. This might not. I'm not sure. It might not matter. 8741 if (Constructor) 8742 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 8743 } 8744 } 8745 8746 // Virtual base-class constructors. 8747 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8748 BEnd = ClassDecl->vbases_end(); 8749 B != BEnd; ++B) { 8750 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8751 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8752 CXXConstructorDecl *Constructor = 8753 LookupMovingConstructor(BaseClassDecl, 0); 8754 // If this is a deleted function, add it anyway. This might be conformant 8755 // with the standard. This might not. I'm not sure. It might not matter. 8756 if (Constructor) 8757 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 8758 } 8759 } 8760 8761 // Field constructors. 8762 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8763 FEnd = ClassDecl->field_end(); 8764 F != FEnd; ++F) { 8765 QualType FieldType = Context.getBaseElementType(F->getType()); 8766 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 8767 CXXConstructorDecl *Constructor = 8768 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 8769 // If this is a deleted function, add it anyway. This might be conformant 8770 // with the standard. This might not. I'm not sure. It might not matter. 8771 // In particular, the problem is that this function never gets called. It 8772 // might just be ill-formed because this function attempts to refer to 8773 // a deleted function here. 8774 if (Constructor) 8775 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8776 } 8777 } 8778 8779 return ExceptSpec; 8780} 8781 8782CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 8783 CXXRecordDecl *ClassDecl) { 8784 // C++11 [class.copy]p9: 8785 // If the definition of a class X does not explicitly declare a move 8786 // constructor, one will be implicitly declared as defaulted if and only if: 8787 // 8788 // - [first 4 bullets] 8789 assert(ClassDecl->needsImplicitMoveConstructor()); 8790 8791 // [Checked after we build the declaration] 8792 // - the move assignment operator would not be implicitly defined as 8793 // deleted, 8794 8795 // [DR1402]: 8796 // - each of X's non-static data members and direct or virtual base classes 8797 // has a type that either has a move constructor or is trivially copyable. 8798 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) { 8799 ClassDecl->setFailedImplicitMoveConstructor(); 8800 return 0; 8801 } 8802 8803 QualType ClassType = Context.getTypeDeclType(ClassDecl); 8804 QualType ArgType = Context.getRValueReferenceType(ClassType); 8805 8806 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8807 CXXMoveConstructor, 8808 false); 8809 8810 DeclarationName Name 8811 = Context.DeclarationNames.getCXXConstructorName( 8812 Context.getCanonicalType(ClassType)); 8813 SourceLocation ClassLoc = ClassDecl->getLocation(); 8814 DeclarationNameInfo NameInfo(Name, ClassLoc); 8815 8816 // C++0x [class.copy]p11: 8817 // An implicitly-declared copy/move constructor is an inline public 8818 // member of its class. 8819 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 8820 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 8821 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8822 Constexpr); 8823 MoveConstructor->setAccess(AS_public); 8824 MoveConstructor->setDefaulted(); 8825 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor()); 8826 8827 // Build an exception specification pointing back at this member. 8828 FunctionProtoType::ExtProtoInfo EPI; 8829 EPI.ExceptionSpecType = EST_Unevaluated; 8830 EPI.ExceptionSpecDecl = MoveConstructor; 8831 MoveConstructor->setType( 8832 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI)); 8833 8834 // Add the parameter to the constructor. 8835 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 8836 ClassLoc, ClassLoc, 8837 /*IdentifierInfo=*/0, 8838 ArgType, /*TInfo=*/0, 8839 SC_None, 8840 SC_None, 0); 8841 MoveConstructor->setParams(FromParam); 8842 8843 // C++0x [class.copy]p9: 8844 // If the definition of a class X does not explicitly declare a move 8845 // constructor, one will be implicitly declared as defaulted if and only if: 8846 // [...] 8847 // - the move constructor would not be implicitly defined as deleted. 8848 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 8849 // Cache this result so that we don't try to generate this over and over 8850 // on every lookup, leaking memory and wasting time. 8851 ClassDecl->setFailedImplicitMoveConstructor(); 8852 return 0; 8853 } 8854 8855 // Note that we have declared this constructor. 8856 ++ASTContext::NumImplicitMoveConstructorsDeclared; 8857 8858 if (Scope *S = getScopeForContext(ClassDecl)) 8859 PushOnScopeChains(MoveConstructor, S, false); 8860 ClassDecl->addDecl(MoveConstructor); 8861 8862 return MoveConstructor; 8863} 8864 8865void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 8866 CXXConstructorDecl *MoveConstructor) { 8867 assert((MoveConstructor->isDefaulted() && 8868 MoveConstructor->isMoveConstructor() && 8869 !MoveConstructor->doesThisDeclarationHaveABody() && 8870 !MoveConstructor->isDeleted()) && 8871 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 8872 8873 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 8874 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 8875 8876 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor); 8877 DiagnosticErrorTrap Trap(Diags); 8878 8879 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) || 8880 Trap.hasErrorOccurred()) { 8881 Diag(CurrentLocation, diag::note_member_synthesized_at) 8882 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 8883 MoveConstructor->setInvalidDecl(); 8884 } else { 8885 Sema::CompoundScopeRAII CompoundScope(*this); 8886 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(), 8887 MoveConstructor->getLocation(), 8888 MultiStmtArg(*this, 0, 0), 8889 /*isStmtExpr=*/false) 8890 .takeAs<Stmt>()); 8891 MoveConstructor->setImplicitlyDefined(true); 8892 } 8893 8894 MoveConstructor->setUsed(); 8895 8896 if (ASTMutationListener *L = getASTMutationListener()) { 8897 L->CompletedImplicitDefinition(MoveConstructor); 8898 } 8899} 8900 8901bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 8902 return FD->isDeleted() && 8903 (FD->isDefaulted() || FD->isImplicit()) && 8904 isa<CXXMethodDecl>(FD); 8905} 8906 8907/// \brief Mark the call operator of the given lambda closure type as "used". 8908static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) { 8909 CXXMethodDecl *CallOperator 8910 = cast<CXXMethodDecl>( 8911 *Lambda->lookup( 8912 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first); 8913 CallOperator->setReferenced(); 8914 CallOperator->setUsed(); 8915} 8916 8917void Sema::DefineImplicitLambdaToFunctionPointerConversion( 8918 SourceLocation CurrentLocation, 8919 CXXConversionDecl *Conv) 8920{ 8921 CXXRecordDecl *Lambda = Conv->getParent(); 8922 8923 // Make sure that the lambda call operator is marked used. 8924 markLambdaCallOperatorUsed(*this, Lambda); 8925 8926 Conv->setUsed(); 8927 8928 ImplicitlyDefinedFunctionScope Scope(*this, Conv); 8929 DiagnosticErrorTrap Trap(Diags); 8930 8931 // Return the address of the __invoke function. 8932 DeclarationName InvokeName = &Context.Idents.get("__invoke"); 8933 CXXMethodDecl *Invoke 8934 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first); 8935 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(), 8936 VK_LValue, Conv->getLocation()).take(); 8937 assert(FunctionRef && "Can't refer to __invoke function?"); 8938 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 8939 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1, 8940 Conv->getLocation(), 8941 Conv->getLocation())); 8942 8943 // Fill in the __invoke function with a dummy implementation. IR generation 8944 // will fill in the actual details. 8945 Invoke->setUsed(); 8946 Invoke->setReferenced(); 8947 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation())); 8948 8949 if (ASTMutationListener *L = getASTMutationListener()) { 8950 L->CompletedImplicitDefinition(Conv); 8951 L->CompletedImplicitDefinition(Invoke); 8952 } 8953} 8954 8955void Sema::DefineImplicitLambdaToBlockPointerConversion( 8956 SourceLocation CurrentLocation, 8957 CXXConversionDecl *Conv) 8958{ 8959 Conv->setUsed(); 8960 8961 ImplicitlyDefinedFunctionScope Scope(*this, Conv); 8962 DiagnosticErrorTrap Trap(Diags); 8963 8964 // Copy-initialize the lambda object as needed to capture it. 8965 Expr *This = ActOnCXXThis(CurrentLocation).take(); 8966 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 8967 8968 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 8969 Conv->getLocation(), 8970 Conv, DerefThis); 8971 8972 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 8973 // behavior. Note that only the general conversion function does this 8974 // (since it's unusable otherwise); in the case where we inline the 8975 // block literal, it has block literal lifetime semantics. 8976 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 8977 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 8978 CK_CopyAndAutoreleaseBlockObject, 8979 BuildBlock.get(), 0, VK_RValue); 8980 8981 if (BuildBlock.isInvalid()) { 8982 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 8983 Conv->setInvalidDecl(); 8984 return; 8985 } 8986 8987 // Create the return statement that returns the block from the conversion 8988 // function. 8989 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 8990 if (Return.isInvalid()) { 8991 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 8992 Conv->setInvalidDecl(); 8993 return; 8994 } 8995 8996 // Set the body of the conversion function. 8997 Stmt *ReturnS = Return.take(); 8998 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1, 8999 Conv->getLocation(), 9000 Conv->getLocation())); 9001 9002 // We're done; notify the mutation listener, if any. 9003 if (ASTMutationListener *L = getASTMutationListener()) { 9004 L->CompletedImplicitDefinition(Conv); 9005 } 9006} 9007 9008/// \brief Determine whether the given list arguments contains exactly one 9009/// "real" (non-default) argument. 9010static bool hasOneRealArgument(MultiExprArg Args) { 9011 switch (Args.size()) { 9012 case 0: 9013 return false; 9014 9015 default: 9016 if (!Args.get()[1]->isDefaultArgument()) 9017 return false; 9018 9019 // fall through 9020 case 1: 9021 return !Args.get()[0]->isDefaultArgument(); 9022 } 9023 9024 return false; 9025} 9026 9027ExprResult 9028Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9029 CXXConstructorDecl *Constructor, 9030 MultiExprArg ExprArgs, 9031 bool HadMultipleCandidates, 9032 bool RequiresZeroInit, 9033 unsigned ConstructKind, 9034 SourceRange ParenRange) { 9035 bool Elidable = false; 9036 9037 // C++0x [class.copy]p34: 9038 // When certain criteria are met, an implementation is allowed to 9039 // omit the copy/move construction of a class object, even if the 9040 // copy/move constructor and/or destructor for the object have 9041 // side effects. [...] 9042 // - when a temporary class object that has not been bound to a 9043 // reference (12.2) would be copied/moved to a class object 9044 // with the same cv-unqualified type, the copy/move operation 9045 // can be omitted by constructing the temporary object 9046 // directly into the target of the omitted copy/move 9047 if (ConstructKind == CXXConstructExpr::CK_Complete && 9048 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 9049 Expr *SubExpr = ((Expr **)ExprArgs.get())[0]; 9050 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 9051 } 9052 9053 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 9054 Elidable, move(ExprArgs), HadMultipleCandidates, 9055 RequiresZeroInit, ConstructKind, ParenRange); 9056} 9057 9058/// BuildCXXConstructExpr - Creates a complete call to a constructor, 9059/// including handling of its default argument expressions. 9060ExprResult 9061Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 9062 CXXConstructorDecl *Constructor, bool Elidable, 9063 MultiExprArg ExprArgs, 9064 bool HadMultipleCandidates, 9065 bool RequiresZeroInit, 9066 unsigned ConstructKind, 9067 SourceRange ParenRange) { 9068 unsigned NumExprs = ExprArgs.size(); 9069 Expr **Exprs = (Expr **)ExprArgs.release(); 9070 9071 MarkFunctionReferenced(ConstructLoc, Constructor); 9072 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 9073 Constructor, Elidable, Exprs, NumExprs, 9074 HadMultipleCandidates, /*FIXME*/false, 9075 RequiresZeroInit, 9076 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 9077 ParenRange)); 9078} 9079 9080bool Sema::InitializeVarWithConstructor(VarDecl *VD, 9081 CXXConstructorDecl *Constructor, 9082 MultiExprArg Exprs, 9083 bool HadMultipleCandidates) { 9084 // FIXME: Provide the correct paren SourceRange when available. 9085 ExprResult TempResult = 9086 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 9087 move(Exprs), HadMultipleCandidates, false, 9088 CXXConstructExpr::CK_Complete, SourceRange()); 9089 if (TempResult.isInvalid()) 9090 return true; 9091 9092 Expr *Temp = TempResult.takeAs<Expr>(); 9093 CheckImplicitConversions(Temp, VD->getLocation()); 9094 MarkFunctionReferenced(VD->getLocation(), Constructor); 9095 Temp = MaybeCreateExprWithCleanups(Temp); 9096 VD->setInit(Temp); 9097 9098 return false; 9099} 9100 9101void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 9102 if (VD->isInvalidDecl()) return; 9103 9104 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 9105 if (ClassDecl->isInvalidDecl()) return; 9106 if (ClassDecl->hasIrrelevantDestructor()) return; 9107 if (ClassDecl->isDependentContext()) return; 9108 9109 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 9110 MarkFunctionReferenced(VD->getLocation(), Destructor); 9111 CheckDestructorAccess(VD->getLocation(), Destructor, 9112 PDiag(diag::err_access_dtor_var) 9113 << VD->getDeclName() 9114 << VD->getType()); 9115 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 9116 9117 if (!VD->hasGlobalStorage()) return; 9118 9119 // Emit warning for non-trivial dtor in global scope (a real global, 9120 // class-static, function-static). 9121 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 9122 9123 // TODO: this should be re-enabled for static locals by !CXAAtExit 9124 if (!VD->isStaticLocal()) 9125 Diag(VD->getLocation(), diag::warn_global_destructor); 9126} 9127 9128/// \brief Given a constructor and the set of arguments provided for the 9129/// constructor, convert the arguments and add any required default arguments 9130/// to form a proper call to this constructor. 9131/// 9132/// \returns true if an error occurred, false otherwise. 9133bool 9134Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 9135 MultiExprArg ArgsPtr, 9136 SourceLocation Loc, 9137 ASTOwningVector<Expr*> &ConvertedArgs, 9138 bool AllowExplicit) { 9139 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 9140 unsigned NumArgs = ArgsPtr.size(); 9141 Expr **Args = (Expr **)ArgsPtr.get(); 9142 9143 const FunctionProtoType *Proto 9144 = Constructor->getType()->getAs<FunctionProtoType>(); 9145 assert(Proto && "Constructor without a prototype?"); 9146 unsigned NumArgsInProto = Proto->getNumArgs(); 9147 9148 // If too few arguments are available, we'll fill in the rest with defaults. 9149 if (NumArgs < NumArgsInProto) 9150 ConvertedArgs.reserve(NumArgsInProto); 9151 else 9152 ConvertedArgs.reserve(NumArgs); 9153 9154 VariadicCallType CallType = 9155 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 9156 SmallVector<Expr *, 8> AllArgs; 9157 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 9158 Proto, 0, Args, NumArgs, AllArgs, 9159 CallType, AllowExplicit); 9160 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 9161 9162 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size()); 9163 9164 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(), 9165 Proto, Loc); 9166 9167 return Invalid; 9168} 9169 9170static inline bool 9171CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 9172 const FunctionDecl *FnDecl) { 9173 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 9174 if (isa<NamespaceDecl>(DC)) { 9175 return SemaRef.Diag(FnDecl->getLocation(), 9176 diag::err_operator_new_delete_declared_in_namespace) 9177 << FnDecl->getDeclName(); 9178 } 9179 9180 if (isa<TranslationUnitDecl>(DC) && 9181 FnDecl->getStorageClass() == SC_Static) { 9182 return SemaRef.Diag(FnDecl->getLocation(), 9183 diag::err_operator_new_delete_declared_static) 9184 << FnDecl->getDeclName(); 9185 } 9186 9187 return false; 9188} 9189 9190static inline bool 9191CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 9192 CanQualType ExpectedResultType, 9193 CanQualType ExpectedFirstParamType, 9194 unsigned DependentParamTypeDiag, 9195 unsigned InvalidParamTypeDiag) { 9196 QualType ResultType = 9197 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 9198 9199 // Check that the result type is not dependent. 9200 if (ResultType->isDependentType()) 9201 return SemaRef.Diag(FnDecl->getLocation(), 9202 diag::err_operator_new_delete_dependent_result_type) 9203 << FnDecl->getDeclName() << ExpectedResultType; 9204 9205 // Check that the result type is what we expect. 9206 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 9207 return SemaRef.Diag(FnDecl->getLocation(), 9208 diag::err_operator_new_delete_invalid_result_type) 9209 << FnDecl->getDeclName() << ExpectedResultType; 9210 9211 // A function template must have at least 2 parameters. 9212 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 9213 return SemaRef.Diag(FnDecl->getLocation(), 9214 diag::err_operator_new_delete_template_too_few_parameters) 9215 << FnDecl->getDeclName(); 9216 9217 // The function decl must have at least 1 parameter. 9218 if (FnDecl->getNumParams() == 0) 9219 return SemaRef.Diag(FnDecl->getLocation(), 9220 diag::err_operator_new_delete_too_few_parameters) 9221 << FnDecl->getDeclName(); 9222 9223 // Check the first parameter type is not dependent. 9224 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 9225 if (FirstParamType->isDependentType()) 9226 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 9227 << FnDecl->getDeclName() << ExpectedFirstParamType; 9228 9229 // Check that the first parameter type is what we expect. 9230 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 9231 ExpectedFirstParamType) 9232 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 9233 << FnDecl->getDeclName() << ExpectedFirstParamType; 9234 9235 return false; 9236} 9237 9238static bool 9239CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 9240 // C++ [basic.stc.dynamic.allocation]p1: 9241 // A program is ill-formed if an allocation function is declared in a 9242 // namespace scope other than global scope or declared static in global 9243 // scope. 9244 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9245 return true; 9246 9247 CanQualType SizeTy = 9248 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 9249 9250 // C++ [basic.stc.dynamic.allocation]p1: 9251 // The return type shall be void*. The first parameter shall have type 9252 // std::size_t. 9253 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 9254 SizeTy, 9255 diag::err_operator_new_dependent_param_type, 9256 diag::err_operator_new_param_type)) 9257 return true; 9258 9259 // C++ [basic.stc.dynamic.allocation]p1: 9260 // The first parameter shall not have an associated default argument. 9261 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 9262 return SemaRef.Diag(FnDecl->getLocation(), 9263 diag::err_operator_new_default_arg) 9264 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 9265 9266 return false; 9267} 9268 9269static bool 9270CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 9271 // C++ [basic.stc.dynamic.deallocation]p1: 9272 // A program is ill-formed if deallocation functions are declared in a 9273 // namespace scope other than global scope or declared static in global 9274 // scope. 9275 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 9276 return true; 9277 9278 // C++ [basic.stc.dynamic.deallocation]p2: 9279 // Each deallocation function shall return void and its first parameter 9280 // shall be void*. 9281 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 9282 SemaRef.Context.VoidPtrTy, 9283 diag::err_operator_delete_dependent_param_type, 9284 diag::err_operator_delete_param_type)) 9285 return true; 9286 9287 return false; 9288} 9289 9290/// CheckOverloadedOperatorDeclaration - Check whether the declaration 9291/// of this overloaded operator is well-formed. If so, returns false; 9292/// otherwise, emits appropriate diagnostics and returns true. 9293bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 9294 assert(FnDecl && FnDecl->isOverloadedOperator() && 9295 "Expected an overloaded operator declaration"); 9296 9297 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 9298 9299 // C++ [over.oper]p5: 9300 // The allocation and deallocation functions, operator new, 9301 // operator new[], operator delete and operator delete[], are 9302 // described completely in 3.7.3. The attributes and restrictions 9303 // found in the rest of this subclause do not apply to them unless 9304 // explicitly stated in 3.7.3. 9305 if (Op == OO_Delete || Op == OO_Array_Delete) 9306 return CheckOperatorDeleteDeclaration(*this, FnDecl); 9307 9308 if (Op == OO_New || Op == OO_Array_New) 9309 return CheckOperatorNewDeclaration(*this, FnDecl); 9310 9311 // C++ [over.oper]p6: 9312 // An operator function shall either be a non-static member 9313 // function or be a non-member function and have at least one 9314 // parameter whose type is a class, a reference to a class, an 9315 // enumeration, or a reference to an enumeration. 9316 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 9317 if (MethodDecl->isStatic()) 9318 return Diag(FnDecl->getLocation(), 9319 diag::err_operator_overload_static) << FnDecl->getDeclName(); 9320 } else { 9321 bool ClassOrEnumParam = false; 9322 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 9323 ParamEnd = FnDecl->param_end(); 9324 Param != ParamEnd; ++Param) { 9325 QualType ParamType = (*Param)->getType().getNonReferenceType(); 9326 if (ParamType->isDependentType() || ParamType->isRecordType() || 9327 ParamType->isEnumeralType()) { 9328 ClassOrEnumParam = true; 9329 break; 9330 } 9331 } 9332 9333 if (!ClassOrEnumParam) 9334 return Diag(FnDecl->getLocation(), 9335 diag::err_operator_overload_needs_class_or_enum) 9336 << FnDecl->getDeclName(); 9337 } 9338 9339 // C++ [over.oper]p8: 9340 // An operator function cannot have default arguments (8.3.6), 9341 // except where explicitly stated below. 9342 // 9343 // Only the function-call operator allows default arguments 9344 // (C++ [over.call]p1). 9345 if (Op != OO_Call) { 9346 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9347 Param != FnDecl->param_end(); ++Param) { 9348 if ((*Param)->hasDefaultArg()) 9349 return Diag((*Param)->getLocation(), 9350 diag::err_operator_overload_default_arg) 9351 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 9352 } 9353 } 9354 9355 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 9356 { false, false, false } 9357#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 9358 , { Unary, Binary, MemberOnly } 9359#include "clang/Basic/OperatorKinds.def" 9360 }; 9361 9362 bool CanBeUnaryOperator = OperatorUses[Op][0]; 9363 bool CanBeBinaryOperator = OperatorUses[Op][1]; 9364 bool MustBeMemberOperator = OperatorUses[Op][2]; 9365 9366 // C++ [over.oper]p8: 9367 // [...] Operator functions cannot have more or fewer parameters 9368 // than the number required for the corresponding operator, as 9369 // described in the rest of this subclause. 9370 unsigned NumParams = FnDecl->getNumParams() 9371 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 9372 if (Op != OO_Call && 9373 ((NumParams == 1 && !CanBeUnaryOperator) || 9374 (NumParams == 2 && !CanBeBinaryOperator) || 9375 (NumParams < 1) || (NumParams > 2))) { 9376 // We have the wrong number of parameters. 9377 unsigned ErrorKind; 9378 if (CanBeUnaryOperator && CanBeBinaryOperator) { 9379 ErrorKind = 2; // 2 -> unary or binary. 9380 } else if (CanBeUnaryOperator) { 9381 ErrorKind = 0; // 0 -> unary 9382 } else { 9383 assert(CanBeBinaryOperator && 9384 "All non-call overloaded operators are unary or binary!"); 9385 ErrorKind = 1; // 1 -> binary 9386 } 9387 9388 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 9389 << FnDecl->getDeclName() << NumParams << ErrorKind; 9390 } 9391 9392 // Overloaded operators other than operator() cannot be variadic. 9393 if (Op != OO_Call && 9394 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 9395 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 9396 << FnDecl->getDeclName(); 9397 } 9398 9399 // Some operators must be non-static member functions. 9400 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 9401 return Diag(FnDecl->getLocation(), 9402 diag::err_operator_overload_must_be_member) 9403 << FnDecl->getDeclName(); 9404 } 9405 9406 // C++ [over.inc]p1: 9407 // The user-defined function called operator++ implements the 9408 // prefix and postfix ++ operator. If this function is a member 9409 // function with no parameters, or a non-member function with one 9410 // parameter of class or enumeration type, it defines the prefix 9411 // increment operator ++ for objects of that type. If the function 9412 // is a member function with one parameter (which shall be of type 9413 // int) or a non-member function with two parameters (the second 9414 // of which shall be of type int), it defines the postfix 9415 // increment operator ++ for objects of that type. 9416 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 9417 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 9418 bool ParamIsInt = false; 9419 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 9420 ParamIsInt = BT->getKind() == BuiltinType::Int; 9421 9422 if (!ParamIsInt) 9423 return Diag(LastParam->getLocation(), 9424 diag::err_operator_overload_post_incdec_must_be_int) 9425 << LastParam->getType() << (Op == OO_MinusMinus); 9426 } 9427 9428 return false; 9429} 9430 9431/// CheckLiteralOperatorDeclaration - Check whether the declaration 9432/// of this literal operator function is well-formed. If so, returns 9433/// false; otherwise, emits appropriate diagnostics and returns true. 9434bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 9435 if (isa<CXXMethodDecl>(FnDecl)) { 9436 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 9437 << FnDecl->getDeclName(); 9438 return true; 9439 } 9440 9441 if (FnDecl->isExternC()) { 9442 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 9443 return true; 9444 } 9445 9446 bool Valid = false; 9447 9448 // This might be the definition of a literal operator template. 9449 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 9450 // This might be a specialization of a literal operator template. 9451 if (!TpDecl) 9452 TpDecl = FnDecl->getPrimaryTemplate(); 9453 9454 // template <char...> type operator "" name() is the only valid template 9455 // signature, and the only valid signature with no parameters. 9456 if (TpDecl) { 9457 if (FnDecl->param_size() == 0) { 9458 // Must have only one template parameter 9459 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 9460 if (Params->size() == 1) { 9461 NonTypeTemplateParmDecl *PmDecl = 9462 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 9463 9464 // The template parameter must be a char parameter pack. 9465 if (PmDecl && PmDecl->isTemplateParameterPack() && 9466 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 9467 Valid = true; 9468 } 9469 } 9470 } else if (FnDecl->param_size()) { 9471 // Check the first parameter 9472 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 9473 9474 QualType T = (*Param)->getType().getUnqualifiedType(); 9475 9476 // unsigned long long int, long double, and any character type are allowed 9477 // as the only parameters. 9478 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 9479 Context.hasSameType(T, Context.LongDoubleTy) || 9480 Context.hasSameType(T, Context.CharTy) || 9481 Context.hasSameType(T, Context.WCharTy) || 9482 Context.hasSameType(T, Context.Char16Ty) || 9483 Context.hasSameType(T, Context.Char32Ty)) { 9484 if (++Param == FnDecl->param_end()) 9485 Valid = true; 9486 goto FinishedParams; 9487 } 9488 9489 // Otherwise it must be a pointer to const; let's strip those qualifiers. 9490 const PointerType *PT = T->getAs<PointerType>(); 9491 if (!PT) 9492 goto FinishedParams; 9493 T = PT->getPointeeType(); 9494 if (!T.isConstQualified() || T.isVolatileQualified()) 9495 goto FinishedParams; 9496 T = T.getUnqualifiedType(); 9497 9498 // Move on to the second parameter; 9499 ++Param; 9500 9501 // If there is no second parameter, the first must be a const char * 9502 if (Param == FnDecl->param_end()) { 9503 if (Context.hasSameType(T, Context.CharTy)) 9504 Valid = true; 9505 goto FinishedParams; 9506 } 9507 9508 // const char *, const wchar_t*, const char16_t*, and const char32_t* 9509 // are allowed as the first parameter to a two-parameter function 9510 if (!(Context.hasSameType(T, Context.CharTy) || 9511 Context.hasSameType(T, Context.WCharTy) || 9512 Context.hasSameType(T, Context.Char16Ty) || 9513 Context.hasSameType(T, Context.Char32Ty))) 9514 goto FinishedParams; 9515 9516 // The second and final parameter must be an std::size_t 9517 T = (*Param)->getType().getUnqualifiedType(); 9518 if (Context.hasSameType(T, Context.getSizeType()) && 9519 ++Param == FnDecl->param_end()) 9520 Valid = true; 9521 } 9522 9523 // FIXME: This diagnostic is absolutely terrible. 9524FinishedParams: 9525 if (!Valid) { 9526 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 9527 << FnDecl->getDeclName(); 9528 return true; 9529 } 9530 9531 // A parameter-declaration-clause containing a default argument is not 9532 // equivalent to any of the permitted forms. 9533 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 9534 ParamEnd = FnDecl->param_end(); 9535 Param != ParamEnd; ++Param) { 9536 if ((*Param)->hasDefaultArg()) { 9537 Diag((*Param)->getDefaultArgRange().getBegin(), 9538 diag::err_literal_operator_default_argument) 9539 << (*Param)->getDefaultArgRange(); 9540 break; 9541 } 9542 } 9543 9544 StringRef LiteralName 9545 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 9546 if (LiteralName[0] != '_') { 9547 // C++11 [usrlit.suffix]p1: 9548 // Literal suffix identifiers that do not start with an underscore 9549 // are reserved for future standardization. 9550 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved); 9551 } 9552 9553 return false; 9554} 9555 9556/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 9557/// linkage specification, including the language and (if present) 9558/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 9559/// the location of the language string literal, which is provided 9560/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 9561/// the '{' brace. Otherwise, this linkage specification does not 9562/// have any braces. 9563Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 9564 SourceLocation LangLoc, 9565 StringRef Lang, 9566 SourceLocation LBraceLoc) { 9567 LinkageSpecDecl::LanguageIDs Language; 9568 if (Lang == "\"C\"") 9569 Language = LinkageSpecDecl::lang_c; 9570 else if (Lang == "\"C++\"") 9571 Language = LinkageSpecDecl::lang_cxx; 9572 else { 9573 Diag(LangLoc, diag::err_bad_language); 9574 return 0; 9575 } 9576 9577 // FIXME: Add all the various semantics of linkage specifications 9578 9579 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 9580 ExternLoc, LangLoc, Language); 9581 CurContext->addDecl(D); 9582 PushDeclContext(S, D); 9583 return D; 9584} 9585 9586/// ActOnFinishLinkageSpecification - Complete the definition of 9587/// the C++ linkage specification LinkageSpec. If RBraceLoc is 9588/// valid, it's the position of the closing '}' brace in a linkage 9589/// specification that uses braces. 9590Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 9591 Decl *LinkageSpec, 9592 SourceLocation RBraceLoc) { 9593 if (LinkageSpec) { 9594 if (RBraceLoc.isValid()) { 9595 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 9596 LSDecl->setRBraceLoc(RBraceLoc); 9597 } 9598 PopDeclContext(); 9599 } 9600 return LinkageSpec; 9601} 9602 9603/// \brief Perform semantic analysis for the variable declaration that 9604/// occurs within a C++ catch clause, returning the newly-created 9605/// variable. 9606VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 9607 TypeSourceInfo *TInfo, 9608 SourceLocation StartLoc, 9609 SourceLocation Loc, 9610 IdentifierInfo *Name) { 9611 bool Invalid = false; 9612 QualType ExDeclType = TInfo->getType(); 9613 9614 // Arrays and functions decay. 9615 if (ExDeclType->isArrayType()) 9616 ExDeclType = Context.getArrayDecayedType(ExDeclType); 9617 else if (ExDeclType->isFunctionType()) 9618 ExDeclType = Context.getPointerType(ExDeclType); 9619 9620 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 9621 // The exception-declaration shall not denote a pointer or reference to an 9622 // incomplete type, other than [cv] void*. 9623 // N2844 forbids rvalue references. 9624 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 9625 Diag(Loc, diag::err_catch_rvalue_ref); 9626 Invalid = true; 9627 } 9628 9629 QualType BaseType = ExDeclType; 9630 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 9631 unsigned DK = diag::err_catch_incomplete; 9632 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 9633 BaseType = Ptr->getPointeeType(); 9634 Mode = 1; 9635 DK = diag::err_catch_incomplete_ptr; 9636 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 9637 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 9638 BaseType = Ref->getPointeeType(); 9639 Mode = 2; 9640 DK = diag::err_catch_incomplete_ref; 9641 } 9642 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 9643 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 9644 Invalid = true; 9645 9646 if (!Invalid && !ExDeclType->isDependentType() && 9647 RequireNonAbstractType(Loc, ExDeclType, 9648 diag::err_abstract_type_in_decl, 9649 AbstractVariableType)) 9650 Invalid = true; 9651 9652 // Only the non-fragile NeXT runtime currently supports C++ catches 9653 // of ObjC types, and no runtime supports catching ObjC types by value. 9654 if (!Invalid && getLangOpts().ObjC1) { 9655 QualType T = ExDeclType; 9656 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 9657 T = RT->getPointeeType(); 9658 9659 if (T->isObjCObjectType()) { 9660 Diag(Loc, diag::err_objc_object_catch); 9661 Invalid = true; 9662 } else if (T->isObjCObjectPointerType()) { 9663 // FIXME: should this be a test for macosx-fragile specifically? 9664 if (getLangOpts().ObjCRuntime.isFragile()) 9665 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 9666 } 9667 } 9668 9669 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 9670 ExDeclType, TInfo, SC_None, SC_None); 9671 ExDecl->setExceptionVariable(true); 9672 9673 // In ARC, infer 'retaining' for variables of retainable type. 9674 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 9675 Invalid = true; 9676 9677 if (!Invalid && !ExDeclType->isDependentType()) { 9678 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 9679 // C++ [except.handle]p16: 9680 // The object declared in an exception-declaration or, if the 9681 // exception-declaration does not specify a name, a temporary (12.2) is 9682 // copy-initialized (8.5) from the exception object. [...] 9683 // The object is destroyed when the handler exits, after the destruction 9684 // of any automatic objects initialized within the handler. 9685 // 9686 // We just pretend to initialize the object with itself, then make sure 9687 // it can be destroyed later. 9688 QualType initType = ExDeclType; 9689 9690 InitializedEntity entity = 9691 InitializedEntity::InitializeVariable(ExDecl); 9692 InitializationKind initKind = 9693 InitializationKind::CreateCopy(Loc, SourceLocation()); 9694 9695 Expr *opaqueValue = 9696 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 9697 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1); 9698 ExprResult result = sequence.Perform(*this, entity, initKind, 9699 MultiExprArg(&opaqueValue, 1)); 9700 if (result.isInvalid()) 9701 Invalid = true; 9702 else { 9703 // If the constructor used was non-trivial, set this as the 9704 // "initializer". 9705 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 9706 if (!construct->getConstructor()->isTrivial()) { 9707 Expr *init = MaybeCreateExprWithCleanups(construct); 9708 ExDecl->setInit(init); 9709 } 9710 9711 // And make sure it's destructable. 9712 FinalizeVarWithDestructor(ExDecl, recordType); 9713 } 9714 } 9715 } 9716 9717 if (Invalid) 9718 ExDecl->setInvalidDecl(); 9719 9720 return ExDecl; 9721} 9722 9723/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 9724/// handler. 9725Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 9726 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9727 bool Invalid = D.isInvalidType(); 9728 9729 // Check for unexpanded parameter packs. 9730 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 9731 UPPC_ExceptionType)) { 9732 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 9733 D.getIdentifierLoc()); 9734 Invalid = true; 9735 } 9736 9737 IdentifierInfo *II = D.getIdentifier(); 9738 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 9739 LookupOrdinaryName, 9740 ForRedeclaration)) { 9741 // The scope should be freshly made just for us. There is just no way 9742 // it contains any previous declaration. 9743 assert(!S->isDeclScope(PrevDecl)); 9744 if (PrevDecl->isTemplateParameter()) { 9745 // Maybe we will complain about the shadowed template parameter. 9746 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9747 PrevDecl = 0; 9748 } 9749 } 9750 9751 if (D.getCXXScopeSpec().isSet() && !Invalid) { 9752 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 9753 << D.getCXXScopeSpec().getRange(); 9754 Invalid = true; 9755 } 9756 9757 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 9758 D.getLocStart(), 9759 D.getIdentifierLoc(), 9760 D.getIdentifier()); 9761 if (Invalid) 9762 ExDecl->setInvalidDecl(); 9763 9764 // Add the exception declaration into this scope. 9765 if (II) 9766 PushOnScopeChains(ExDecl, S); 9767 else 9768 CurContext->addDecl(ExDecl); 9769 9770 ProcessDeclAttributes(S, ExDecl, D); 9771 return ExDecl; 9772} 9773 9774Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 9775 Expr *AssertExpr, 9776 Expr *AssertMessageExpr, 9777 SourceLocation RParenLoc) { 9778 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 9779 9780 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 9781 return 0; 9782 9783 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 9784 AssertMessage, RParenLoc, false); 9785} 9786 9787Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 9788 Expr *AssertExpr, 9789 StringLiteral *AssertMessage, 9790 SourceLocation RParenLoc, 9791 bool Failed) { 9792 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 9793 !Failed) { 9794 // In a static_assert-declaration, the constant-expression shall be a 9795 // constant expression that can be contextually converted to bool. 9796 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 9797 if (Converted.isInvalid()) 9798 Failed = true; 9799 9800 llvm::APSInt Cond; 9801 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 9802 diag::err_static_assert_expression_is_not_constant, 9803 /*AllowFold=*/false).isInvalid()) 9804 Failed = true; 9805 9806 if (!Failed && !Cond) { 9807 llvm::SmallString<256> MsgBuffer; 9808 llvm::raw_svector_ostream Msg(MsgBuffer); 9809 AssertMessage->printPretty(Msg, Context, 0, getPrintingPolicy()); 9810 Diag(StaticAssertLoc, diag::err_static_assert_failed) 9811 << Msg.str() << AssertExpr->getSourceRange(); 9812 Failed = true; 9813 } 9814 } 9815 9816 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 9817 AssertExpr, AssertMessage, RParenLoc, 9818 Failed); 9819 9820 CurContext->addDecl(Decl); 9821 return Decl; 9822} 9823 9824/// \brief Perform semantic analysis of the given friend type declaration. 9825/// 9826/// \returns A friend declaration that. 9827FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc, 9828 SourceLocation FriendLoc, 9829 TypeSourceInfo *TSInfo) { 9830 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 9831 9832 QualType T = TSInfo->getType(); 9833 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 9834 9835 // C++03 [class.friend]p2: 9836 // An elaborated-type-specifier shall be used in a friend declaration 9837 // for a class.* 9838 // 9839 // * The class-key of the elaborated-type-specifier is required. 9840 if (!ActiveTemplateInstantiations.empty()) { 9841 // Do not complain about the form of friend template types during 9842 // template instantiation; we will already have complained when the 9843 // template was declared. 9844 } else if (!T->isElaboratedTypeSpecifier()) { 9845 // If we evaluated the type to a record type, suggest putting 9846 // a tag in front. 9847 if (const RecordType *RT = T->getAs<RecordType>()) { 9848 RecordDecl *RD = RT->getDecl(); 9849 9850 std::string InsertionText = std::string(" ") + RD->getKindName(); 9851 9852 Diag(TypeRange.getBegin(), 9853 getLangOpts().CPlusPlus0x ? 9854 diag::warn_cxx98_compat_unelaborated_friend_type : 9855 diag::ext_unelaborated_friend_type) 9856 << (unsigned) RD->getTagKind() 9857 << T 9858 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 9859 InsertionText); 9860 } else { 9861 Diag(FriendLoc, 9862 getLangOpts().CPlusPlus0x ? 9863 diag::warn_cxx98_compat_nonclass_type_friend : 9864 diag::ext_nonclass_type_friend) 9865 << T 9866 << SourceRange(FriendLoc, TypeRange.getEnd()); 9867 } 9868 } else if (T->getAs<EnumType>()) { 9869 Diag(FriendLoc, 9870 getLangOpts().CPlusPlus0x ? 9871 diag::warn_cxx98_compat_enum_friend : 9872 diag::ext_enum_friend) 9873 << T 9874 << SourceRange(FriendLoc, TypeRange.getEnd()); 9875 } 9876 9877 // C++0x [class.friend]p3: 9878 // If the type specifier in a friend declaration designates a (possibly 9879 // cv-qualified) class type, that class is declared as a friend; otherwise, 9880 // the friend declaration is ignored. 9881 9882 // FIXME: C++0x has some syntactic restrictions on friend type declarations 9883 // in [class.friend]p3 that we do not implement. 9884 9885 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc); 9886} 9887 9888/// Handle a friend tag declaration where the scope specifier was 9889/// templated. 9890Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 9891 unsigned TagSpec, SourceLocation TagLoc, 9892 CXXScopeSpec &SS, 9893 IdentifierInfo *Name, SourceLocation NameLoc, 9894 AttributeList *Attr, 9895 MultiTemplateParamsArg TempParamLists) { 9896 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 9897 9898 bool isExplicitSpecialization = false; 9899 bool Invalid = false; 9900 9901 if (TemplateParameterList *TemplateParams 9902 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS, 9903 TempParamLists.get(), 9904 TempParamLists.size(), 9905 /*friend*/ true, 9906 isExplicitSpecialization, 9907 Invalid)) { 9908 if (TemplateParams->size() > 0) { 9909 // This is a declaration of a class template. 9910 if (Invalid) 9911 return 0; 9912 9913 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 9914 SS, Name, NameLoc, Attr, 9915 TemplateParams, AS_public, 9916 /*ModulePrivateLoc=*/SourceLocation(), 9917 TempParamLists.size() - 1, 9918 (TemplateParameterList**) TempParamLists.release()).take(); 9919 } else { 9920 // The "template<>" header is extraneous. 9921 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 9922 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 9923 isExplicitSpecialization = true; 9924 } 9925 } 9926 9927 if (Invalid) return 0; 9928 9929 bool isAllExplicitSpecializations = true; 9930 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 9931 if (TempParamLists.get()[I]->size()) { 9932 isAllExplicitSpecializations = false; 9933 break; 9934 } 9935 } 9936 9937 // FIXME: don't ignore attributes. 9938 9939 // If it's explicit specializations all the way down, just forget 9940 // about the template header and build an appropriate non-templated 9941 // friend. TODO: for source fidelity, remember the headers. 9942 if (isAllExplicitSpecializations) { 9943 if (SS.isEmpty()) { 9944 bool Owned = false; 9945 bool IsDependent = false; 9946 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 9947 Attr, AS_public, 9948 /*ModulePrivateLoc=*/SourceLocation(), 9949 MultiTemplateParamsArg(), Owned, IsDependent, 9950 /*ScopedEnumKWLoc=*/SourceLocation(), 9951 /*ScopedEnumUsesClassTag=*/false, 9952 /*UnderlyingType=*/TypeResult()); 9953 } 9954 9955 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9956 ElaboratedTypeKeyword Keyword 9957 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 9958 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 9959 *Name, NameLoc); 9960 if (T.isNull()) 9961 return 0; 9962 9963 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 9964 if (isa<DependentNameType>(T)) { 9965 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 9966 TL.setElaboratedKeywordLoc(TagLoc); 9967 TL.setQualifierLoc(QualifierLoc); 9968 TL.setNameLoc(NameLoc); 9969 } else { 9970 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 9971 TL.setElaboratedKeywordLoc(TagLoc); 9972 TL.setQualifierLoc(QualifierLoc); 9973 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc); 9974 } 9975 9976 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 9977 TSI, FriendLoc); 9978 Friend->setAccess(AS_public); 9979 CurContext->addDecl(Friend); 9980 return Friend; 9981 } 9982 9983 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 9984 9985 9986 9987 // Handle the case of a templated-scope friend class. e.g. 9988 // template <class T> class A<T>::B; 9989 // FIXME: we don't support these right now. 9990 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 9991 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 9992 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 9993 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 9994 TL.setElaboratedKeywordLoc(TagLoc); 9995 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 9996 TL.setNameLoc(NameLoc); 9997 9998 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 9999 TSI, FriendLoc); 10000 Friend->setAccess(AS_public); 10001 Friend->setUnsupportedFriend(true); 10002 CurContext->addDecl(Friend); 10003 return Friend; 10004} 10005 10006 10007/// Handle a friend type declaration. This works in tandem with 10008/// ActOnTag. 10009/// 10010/// Notes on friend class templates: 10011/// 10012/// We generally treat friend class declarations as if they were 10013/// declaring a class. So, for example, the elaborated type specifier 10014/// in a friend declaration is required to obey the restrictions of a 10015/// class-head (i.e. no typedefs in the scope chain), template 10016/// parameters are required to match up with simple template-ids, &c. 10017/// However, unlike when declaring a template specialization, it's 10018/// okay to refer to a template specialization without an empty 10019/// template parameter declaration, e.g. 10020/// friend class A<T>::B<unsigned>; 10021/// We permit this as a special case; if there are any template 10022/// parameters present at all, require proper matching, i.e. 10023/// template <> template \<class T> friend class A<int>::B; 10024Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 10025 MultiTemplateParamsArg TempParams) { 10026 SourceLocation Loc = DS.getLocStart(); 10027 10028 assert(DS.isFriendSpecified()); 10029 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10030 10031 // Try to convert the decl specifier to a type. This works for 10032 // friend templates because ActOnTag never produces a ClassTemplateDecl 10033 // for a TUK_Friend. 10034 Declarator TheDeclarator(DS, Declarator::MemberContext); 10035 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 10036 QualType T = TSI->getType(); 10037 if (TheDeclarator.isInvalidType()) 10038 return 0; 10039 10040 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 10041 return 0; 10042 10043 // This is definitely an error in C++98. It's probably meant to 10044 // be forbidden in C++0x, too, but the specification is just 10045 // poorly written. 10046 // 10047 // The problem is with declarations like the following: 10048 // template <T> friend A<T>::foo; 10049 // where deciding whether a class C is a friend or not now hinges 10050 // on whether there exists an instantiation of A that causes 10051 // 'foo' to equal C. There are restrictions on class-heads 10052 // (which we declare (by fiat) elaborated friend declarations to 10053 // be) that makes this tractable. 10054 // 10055 // FIXME: handle "template <> friend class A<T>;", which 10056 // is possibly well-formed? Who even knows? 10057 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 10058 Diag(Loc, diag::err_tagless_friend_type_template) 10059 << DS.getSourceRange(); 10060 return 0; 10061 } 10062 10063 // C++98 [class.friend]p1: A friend of a class is a function 10064 // or class that is not a member of the class . . . 10065 // This is fixed in DR77, which just barely didn't make the C++03 10066 // deadline. It's also a very silly restriction that seriously 10067 // affects inner classes and which nobody else seems to implement; 10068 // thus we never diagnose it, not even in -pedantic. 10069 // 10070 // But note that we could warn about it: it's always useless to 10071 // friend one of your own members (it's not, however, worthless to 10072 // friend a member of an arbitrary specialization of your template). 10073 10074 Decl *D; 10075 if (unsigned NumTempParamLists = TempParams.size()) 10076 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 10077 NumTempParamLists, 10078 TempParams.release(), 10079 TSI, 10080 DS.getFriendSpecLoc()); 10081 else 10082 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 10083 10084 if (!D) 10085 return 0; 10086 10087 D->setAccess(AS_public); 10088 CurContext->addDecl(D); 10089 10090 return D; 10091} 10092 10093Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 10094 MultiTemplateParamsArg TemplateParams) { 10095 const DeclSpec &DS = D.getDeclSpec(); 10096 10097 assert(DS.isFriendSpecified()); 10098 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 10099 10100 SourceLocation Loc = D.getIdentifierLoc(); 10101 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10102 10103 // C++ [class.friend]p1 10104 // A friend of a class is a function or class.... 10105 // Note that this sees through typedefs, which is intended. 10106 // It *doesn't* see through dependent types, which is correct 10107 // according to [temp.arg.type]p3: 10108 // If a declaration acquires a function type through a 10109 // type dependent on a template-parameter and this causes 10110 // a declaration that does not use the syntactic form of a 10111 // function declarator to have a function type, the program 10112 // is ill-formed. 10113 if (!TInfo->getType()->isFunctionType()) { 10114 Diag(Loc, diag::err_unexpected_friend); 10115 10116 // It might be worthwhile to try to recover by creating an 10117 // appropriate declaration. 10118 return 0; 10119 } 10120 10121 // C++ [namespace.memdef]p3 10122 // - If a friend declaration in a non-local class first declares a 10123 // class or function, the friend class or function is a member 10124 // of the innermost enclosing namespace. 10125 // - The name of the friend is not found by simple name lookup 10126 // until a matching declaration is provided in that namespace 10127 // scope (either before or after the class declaration granting 10128 // friendship). 10129 // - If a friend function is called, its name may be found by the 10130 // name lookup that considers functions from namespaces and 10131 // classes associated with the types of the function arguments. 10132 // - When looking for a prior declaration of a class or a function 10133 // declared as a friend, scopes outside the innermost enclosing 10134 // namespace scope are not considered. 10135 10136 CXXScopeSpec &SS = D.getCXXScopeSpec(); 10137 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 10138 DeclarationName Name = NameInfo.getName(); 10139 assert(Name); 10140 10141 // Check for unexpanded parameter packs. 10142 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 10143 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 10144 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 10145 return 0; 10146 10147 // The context we found the declaration in, or in which we should 10148 // create the declaration. 10149 DeclContext *DC; 10150 Scope *DCScope = S; 10151 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10152 ForRedeclaration); 10153 10154 // FIXME: there are different rules in local classes 10155 10156 // There are four cases here. 10157 // - There's no scope specifier, in which case we just go to the 10158 // appropriate scope and look for a function or function template 10159 // there as appropriate. 10160 // Recover from invalid scope qualifiers as if they just weren't there. 10161 if (SS.isInvalid() || !SS.isSet()) { 10162 // C++0x [namespace.memdef]p3: 10163 // If the name in a friend declaration is neither qualified nor 10164 // a template-id and the declaration is a function or an 10165 // elaborated-type-specifier, the lookup to determine whether 10166 // the entity has been previously declared shall not consider 10167 // any scopes outside the innermost enclosing namespace. 10168 // C++0x [class.friend]p11: 10169 // If a friend declaration appears in a local class and the name 10170 // specified is an unqualified name, a prior declaration is 10171 // looked up without considering scopes that are outside the 10172 // innermost enclosing non-class scope. For a friend function 10173 // declaration, if there is no prior declaration, the program is 10174 // ill-formed. 10175 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 10176 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 10177 10178 // Find the appropriate context according to the above. 10179 DC = CurContext; 10180 while (true) { 10181 // Skip class contexts. If someone can cite chapter and verse 10182 // for this behavior, that would be nice --- it's what GCC and 10183 // EDG do, and it seems like a reasonable intent, but the spec 10184 // really only says that checks for unqualified existing 10185 // declarations should stop at the nearest enclosing namespace, 10186 // not that they should only consider the nearest enclosing 10187 // namespace. 10188 while (DC->isRecord() || DC->isTransparentContext()) 10189 DC = DC->getParent(); 10190 10191 LookupQualifiedName(Previous, DC); 10192 10193 // TODO: decide what we think about using declarations. 10194 if (isLocal || !Previous.empty()) 10195 break; 10196 10197 if (isTemplateId) { 10198 if (isa<TranslationUnitDecl>(DC)) break; 10199 } else { 10200 if (DC->isFileContext()) break; 10201 } 10202 DC = DC->getParent(); 10203 } 10204 10205 // C++ [class.friend]p1: A friend of a class is a function or 10206 // class that is not a member of the class . . . 10207 // C++11 changes this for both friend types and functions. 10208 // Most C++ 98 compilers do seem to give an error here, so 10209 // we do, too. 10210 if (!Previous.empty() && DC->Equals(CurContext)) 10211 Diag(DS.getFriendSpecLoc(), 10212 getLangOpts().CPlusPlus0x ? 10213 diag::warn_cxx98_compat_friend_is_member : 10214 diag::err_friend_is_member); 10215 10216 DCScope = getScopeForDeclContext(S, DC); 10217 10218 // C++ [class.friend]p6: 10219 // A function can be defined in a friend declaration of a class if and 10220 // only if the class is a non-local class (9.8), the function name is 10221 // unqualified, and the function has namespace scope. 10222 if (isLocal && D.isFunctionDefinition()) { 10223 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 10224 } 10225 10226 // - There's a non-dependent scope specifier, in which case we 10227 // compute it and do a previous lookup there for a function 10228 // or function template. 10229 } else if (!SS.getScopeRep()->isDependent()) { 10230 DC = computeDeclContext(SS); 10231 if (!DC) return 0; 10232 10233 if (RequireCompleteDeclContext(SS, DC)) return 0; 10234 10235 LookupQualifiedName(Previous, DC); 10236 10237 // Ignore things found implicitly in the wrong scope. 10238 // TODO: better diagnostics for this case. Suggesting the right 10239 // qualified scope would be nice... 10240 LookupResult::Filter F = Previous.makeFilter(); 10241 while (F.hasNext()) { 10242 NamedDecl *D = F.next(); 10243 if (!DC->InEnclosingNamespaceSetOf( 10244 D->getDeclContext()->getRedeclContext())) 10245 F.erase(); 10246 } 10247 F.done(); 10248 10249 if (Previous.empty()) { 10250 D.setInvalidType(); 10251 Diag(Loc, diag::err_qualified_friend_not_found) 10252 << Name << TInfo->getType(); 10253 return 0; 10254 } 10255 10256 // C++ [class.friend]p1: A friend of a class is a function or 10257 // class that is not a member of the class . . . 10258 if (DC->Equals(CurContext)) 10259 Diag(DS.getFriendSpecLoc(), 10260 getLangOpts().CPlusPlus0x ? 10261 diag::warn_cxx98_compat_friend_is_member : 10262 diag::err_friend_is_member); 10263 10264 if (D.isFunctionDefinition()) { 10265 // C++ [class.friend]p6: 10266 // A function can be defined in a friend declaration of a class if and 10267 // only if the class is a non-local class (9.8), the function name is 10268 // unqualified, and the function has namespace scope. 10269 SemaDiagnosticBuilder DB 10270 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 10271 10272 DB << SS.getScopeRep(); 10273 if (DC->isFileContext()) 10274 DB << FixItHint::CreateRemoval(SS.getRange()); 10275 SS.clear(); 10276 } 10277 10278 // - There's a scope specifier that does not match any template 10279 // parameter lists, in which case we use some arbitrary context, 10280 // create a method or method template, and wait for instantiation. 10281 // - There's a scope specifier that does match some template 10282 // parameter lists, which we don't handle right now. 10283 } else { 10284 if (D.isFunctionDefinition()) { 10285 // C++ [class.friend]p6: 10286 // A function can be defined in a friend declaration of a class if and 10287 // only if the class is a non-local class (9.8), the function name is 10288 // unqualified, and the function has namespace scope. 10289 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 10290 << SS.getScopeRep(); 10291 } 10292 10293 DC = CurContext; 10294 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 10295 } 10296 10297 if (!DC->isRecord()) { 10298 // This implies that it has to be an operator or function. 10299 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 10300 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 10301 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 10302 Diag(Loc, diag::err_introducing_special_friend) << 10303 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 10304 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 10305 return 0; 10306 } 10307 } 10308 10309 // FIXME: This is an egregious hack to cope with cases where the scope stack 10310 // does not contain the declaration context, i.e., in an out-of-line 10311 // definition of a class. 10312 Scope FakeDCScope(S, Scope::DeclScope, Diags); 10313 if (!DCScope) { 10314 FakeDCScope.setEntity(DC); 10315 DCScope = &FakeDCScope; 10316 } 10317 10318 bool AddToScope = true; 10319 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 10320 move(TemplateParams), AddToScope); 10321 if (!ND) return 0; 10322 10323 assert(ND->getDeclContext() == DC); 10324 assert(ND->getLexicalDeclContext() == CurContext); 10325 10326 // Add the function declaration to the appropriate lookup tables, 10327 // adjusting the redeclarations list as necessary. We don't 10328 // want to do this yet if the friending class is dependent. 10329 // 10330 // Also update the scope-based lookup if the target context's 10331 // lookup context is in lexical scope. 10332 if (!CurContext->isDependentContext()) { 10333 DC = DC->getRedeclContext(); 10334 DC->makeDeclVisibleInContext(ND); 10335 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 10336 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 10337 } 10338 10339 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 10340 D.getIdentifierLoc(), ND, 10341 DS.getFriendSpecLoc()); 10342 FrD->setAccess(AS_public); 10343 CurContext->addDecl(FrD); 10344 10345 if (ND->isInvalidDecl()) { 10346 FrD->setInvalidDecl(); 10347 } else { 10348 if (DC->isRecord()) CheckFriendAccess(ND); 10349 10350 FunctionDecl *FD; 10351 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 10352 FD = FTD->getTemplatedDecl(); 10353 else 10354 FD = cast<FunctionDecl>(ND); 10355 10356 // Mark templated-scope function declarations as unsupported. 10357 if (FD->getNumTemplateParameterLists()) 10358 FrD->setUnsupportedFriend(true); 10359 } 10360 10361 return ND; 10362} 10363 10364void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 10365 AdjustDeclIfTemplate(Dcl); 10366 10367 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 10368 if (!Fn) { 10369 Diag(DelLoc, diag::err_deleted_non_function); 10370 return; 10371 } 10372 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 10373 // Don't consider the implicit declaration we generate for explicit 10374 // specializations. FIXME: Do not generate these implicit declarations. 10375 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization 10376 || Prev->getPreviousDecl()) && !Prev->isDefined()) { 10377 Diag(DelLoc, diag::err_deleted_decl_not_first); 10378 Diag(Prev->getLocation(), diag::note_previous_declaration); 10379 } 10380 // If the declaration wasn't the first, we delete the function anyway for 10381 // recovery. 10382 } 10383 Fn->setDeletedAsWritten(); 10384 10385 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl); 10386 if (!MD) 10387 return; 10388 10389 // A deleted special member function is trivial if the corresponding 10390 // implicitly-declared function would have been. 10391 switch (getSpecialMember(MD)) { 10392 case CXXInvalid: 10393 break; 10394 case CXXDefaultConstructor: 10395 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor()); 10396 break; 10397 case CXXCopyConstructor: 10398 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor()); 10399 break; 10400 case CXXMoveConstructor: 10401 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor()); 10402 break; 10403 case CXXCopyAssignment: 10404 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment()); 10405 break; 10406 case CXXMoveAssignment: 10407 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment()); 10408 break; 10409 case CXXDestructor: 10410 MD->setTrivial(MD->getParent()->hasTrivialDestructor()); 10411 break; 10412 } 10413} 10414 10415void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 10416 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl); 10417 10418 if (MD) { 10419 if (MD->getParent()->isDependentType()) { 10420 MD->setDefaulted(); 10421 MD->setExplicitlyDefaulted(); 10422 return; 10423 } 10424 10425 CXXSpecialMember Member = getSpecialMember(MD); 10426 if (Member == CXXInvalid) { 10427 Diag(DefaultLoc, diag::err_default_special_members); 10428 return; 10429 } 10430 10431 MD->setDefaulted(); 10432 MD->setExplicitlyDefaulted(); 10433 10434 // If this definition appears within the record, do the checking when 10435 // the record is complete. 10436 const FunctionDecl *Primary = MD; 10437 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate) 10438 // Find the uninstantiated declaration that actually had the '= default' 10439 // on it. 10440 MD->getTemplateInstantiationPattern()->isDefined(Primary); 10441 10442 if (Primary == Primary->getCanonicalDecl()) 10443 return; 10444 10445 CheckExplicitlyDefaultedSpecialMember(MD); 10446 10447 switch (Member) { 10448 case CXXDefaultConstructor: { 10449 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10450 if (!CD->isInvalidDecl()) 10451 DefineImplicitDefaultConstructor(DefaultLoc, CD); 10452 break; 10453 } 10454 10455 case CXXCopyConstructor: { 10456 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10457 if (!CD->isInvalidDecl()) 10458 DefineImplicitCopyConstructor(DefaultLoc, CD); 10459 break; 10460 } 10461 10462 case CXXCopyAssignment: { 10463 if (!MD->isInvalidDecl()) 10464 DefineImplicitCopyAssignment(DefaultLoc, MD); 10465 break; 10466 } 10467 10468 case CXXDestructor: { 10469 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD); 10470 if (!DD->isInvalidDecl()) 10471 DefineImplicitDestructor(DefaultLoc, DD); 10472 break; 10473 } 10474 10475 case CXXMoveConstructor: { 10476 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD); 10477 if (!CD->isInvalidDecl()) 10478 DefineImplicitMoveConstructor(DefaultLoc, CD); 10479 break; 10480 } 10481 10482 case CXXMoveAssignment: { 10483 if (!MD->isInvalidDecl()) 10484 DefineImplicitMoveAssignment(DefaultLoc, MD); 10485 break; 10486 } 10487 10488 case CXXInvalid: 10489 llvm_unreachable("Invalid special member."); 10490 } 10491 } else { 10492 Diag(DefaultLoc, diag::err_default_special_members); 10493 } 10494} 10495 10496static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 10497 for (Stmt::child_range CI = S->children(); CI; ++CI) { 10498 Stmt *SubStmt = *CI; 10499 if (!SubStmt) 10500 continue; 10501 if (isa<ReturnStmt>(SubStmt)) 10502 Self.Diag(SubStmt->getLocStart(), 10503 diag::err_return_in_constructor_handler); 10504 if (!isa<Expr>(SubStmt)) 10505 SearchForReturnInStmt(Self, SubStmt); 10506 } 10507} 10508 10509void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 10510 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 10511 CXXCatchStmt *Handler = TryBlock->getHandler(I); 10512 SearchForReturnInStmt(*this, Handler); 10513 } 10514} 10515 10516bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 10517 const CXXMethodDecl *Old) { 10518 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 10519 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 10520 10521 if (Context.hasSameType(NewTy, OldTy) || 10522 NewTy->isDependentType() || OldTy->isDependentType()) 10523 return false; 10524 10525 // Check if the return types are covariant 10526 QualType NewClassTy, OldClassTy; 10527 10528 /// Both types must be pointers or references to classes. 10529 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 10530 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 10531 NewClassTy = NewPT->getPointeeType(); 10532 OldClassTy = OldPT->getPointeeType(); 10533 } 10534 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 10535 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 10536 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 10537 NewClassTy = NewRT->getPointeeType(); 10538 OldClassTy = OldRT->getPointeeType(); 10539 } 10540 } 10541 } 10542 10543 // The return types aren't either both pointers or references to a class type. 10544 if (NewClassTy.isNull()) { 10545 Diag(New->getLocation(), 10546 diag::err_different_return_type_for_overriding_virtual_function) 10547 << New->getDeclName() << NewTy << OldTy; 10548 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10549 10550 return true; 10551 } 10552 10553 // C++ [class.virtual]p6: 10554 // If the return type of D::f differs from the return type of B::f, the 10555 // class type in the return type of D::f shall be complete at the point of 10556 // declaration of D::f or shall be the class type D. 10557 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 10558 if (!RT->isBeingDefined() && 10559 RequireCompleteType(New->getLocation(), NewClassTy, 10560 diag::err_covariant_return_incomplete, 10561 New->getDeclName())) 10562 return true; 10563 } 10564 10565 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 10566 // Check if the new class derives from the old class. 10567 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 10568 Diag(New->getLocation(), 10569 diag::err_covariant_return_not_derived) 10570 << New->getDeclName() << NewTy << OldTy; 10571 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10572 return true; 10573 } 10574 10575 // Check if we the conversion from derived to base is valid. 10576 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 10577 diag::err_covariant_return_inaccessible_base, 10578 diag::err_covariant_return_ambiguous_derived_to_base_conv, 10579 // FIXME: Should this point to the return type? 10580 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 10581 // FIXME: this note won't trigger for delayed access control 10582 // diagnostics, and it's impossible to get an undelayed error 10583 // here from access control during the original parse because 10584 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 10585 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10586 return true; 10587 } 10588 } 10589 10590 // The qualifiers of the return types must be the same. 10591 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 10592 Diag(New->getLocation(), 10593 diag::err_covariant_return_type_different_qualifications) 10594 << New->getDeclName() << NewTy << OldTy; 10595 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10596 return true; 10597 }; 10598 10599 10600 // The new class type must have the same or less qualifiers as the old type. 10601 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 10602 Diag(New->getLocation(), 10603 diag::err_covariant_return_type_class_type_more_qualified) 10604 << New->getDeclName() << NewTy << OldTy; 10605 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 10606 return true; 10607 }; 10608 10609 return false; 10610} 10611 10612/// \brief Mark the given method pure. 10613/// 10614/// \param Method the method to be marked pure. 10615/// 10616/// \param InitRange the source range that covers the "0" initializer. 10617bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 10618 SourceLocation EndLoc = InitRange.getEnd(); 10619 if (EndLoc.isValid()) 10620 Method->setRangeEnd(EndLoc); 10621 10622 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 10623 Method->setPure(); 10624 return false; 10625 } 10626 10627 if (!Method->isInvalidDecl()) 10628 Diag(Method->getLocation(), diag::err_non_virtual_pure) 10629 << Method->getDeclName() << InitRange; 10630 return true; 10631} 10632 10633/// \brief Determine whether the given declaration is a static data member. 10634static bool isStaticDataMember(Decl *D) { 10635 VarDecl *Var = dyn_cast_or_null<VarDecl>(D); 10636 if (!Var) 10637 return false; 10638 10639 return Var->isStaticDataMember(); 10640} 10641/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 10642/// an initializer for the out-of-line declaration 'Dcl'. The scope 10643/// is a fresh scope pushed for just this purpose. 10644/// 10645/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 10646/// static data member of class X, names should be looked up in the scope of 10647/// class X. 10648void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 10649 // If there is no declaration, there was an error parsing it. 10650 if (D == 0 || D->isInvalidDecl()) return; 10651 10652 // We should only get called for declarations with scope specifiers, like: 10653 // int foo::bar; 10654 assert(D->isOutOfLine()); 10655 EnterDeclaratorContext(S, D->getDeclContext()); 10656 10657 // If we are parsing the initializer for a static data member, push a 10658 // new expression evaluation context that is associated with this static 10659 // data member. 10660 if (isStaticDataMember(D)) 10661 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 10662} 10663 10664/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 10665/// initializer for the out-of-line declaration 'D'. 10666void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 10667 // If there is no declaration, there was an error parsing it. 10668 if (D == 0 || D->isInvalidDecl()) return; 10669 10670 if (isStaticDataMember(D)) 10671 PopExpressionEvaluationContext(); 10672 10673 assert(D->isOutOfLine()); 10674 ExitDeclaratorContext(S); 10675} 10676 10677/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 10678/// C++ if/switch/while/for statement. 10679/// e.g: "if (int x = f()) {...}" 10680DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 10681 // C++ 6.4p2: 10682 // The declarator shall not specify a function or an array. 10683 // The type-specifier-seq shall not contain typedef and shall not declare a 10684 // new class or enumeration. 10685 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 10686 "Parser allowed 'typedef' as storage class of condition decl."); 10687 10688 Decl *Dcl = ActOnDeclarator(S, D); 10689 if (!Dcl) 10690 return true; 10691 10692 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 10693 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 10694 << D.getSourceRange(); 10695 return true; 10696 } 10697 10698 return Dcl; 10699} 10700 10701void Sema::LoadExternalVTableUses() { 10702 if (!ExternalSource) 10703 return; 10704 10705 SmallVector<ExternalVTableUse, 4> VTables; 10706 ExternalSource->ReadUsedVTables(VTables); 10707 SmallVector<VTableUse, 4> NewUses; 10708 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 10709 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 10710 = VTablesUsed.find(VTables[I].Record); 10711 // Even if a definition wasn't required before, it may be required now. 10712 if (Pos != VTablesUsed.end()) { 10713 if (!Pos->second && VTables[I].DefinitionRequired) 10714 Pos->second = true; 10715 continue; 10716 } 10717 10718 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 10719 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 10720 } 10721 10722 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 10723} 10724 10725void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 10726 bool DefinitionRequired) { 10727 // Ignore any vtable uses in unevaluated operands or for classes that do 10728 // not have a vtable. 10729 if (!Class->isDynamicClass() || Class->isDependentContext() || 10730 CurContext->isDependentContext() || 10731 ExprEvalContexts.back().Context == Unevaluated) 10732 return; 10733 10734 // Try to insert this class into the map. 10735 LoadExternalVTableUses(); 10736 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 10737 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 10738 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 10739 if (!Pos.second) { 10740 // If we already had an entry, check to see if we are promoting this vtable 10741 // to required a definition. If so, we need to reappend to the VTableUses 10742 // list, since we may have already processed the first entry. 10743 if (DefinitionRequired && !Pos.first->second) { 10744 Pos.first->second = true; 10745 } else { 10746 // Otherwise, we can early exit. 10747 return; 10748 } 10749 } 10750 10751 // Local classes need to have their virtual members marked 10752 // immediately. For all other classes, we mark their virtual members 10753 // at the end of the translation unit. 10754 if (Class->isLocalClass()) 10755 MarkVirtualMembersReferenced(Loc, Class); 10756 else 10757 VTableUses.push_back(std::make_pair(Class, Loc)); 10758} 10759 10760bool Sema::DefineUsedVTables() { 10761 LoadExternalVTableUses(); 10762 if (VTableUses.empty()) 10763 return false; 10764 10765 // Note: The VTableUses vector could grow as a result of marking 10766 // the members of a class as "used", so we check the size each 10767 // time through the loop and prefer indices (which are stable) to 10768 // iterators (which are not). 10769 bool DefinedAnything = false; 10770 for (unsigned I = 0; I != VTableUses.size(); ++I) { 10771 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 10772 if (!Class) 10773 continue; 10774 10775 SourceLocation Loc = VTableUses[I].second; 10776 10777 bool DefineVTable = true; 10778 10779 // If this class has a key function, but that key function is 10780 // defined in another translation unit, we don't need to emit the 10781 // vtable even though we're using it. 10782 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class); 10783 if (KeyFunction && !KeyFunction->hasBody()) { 10784 switch (KeyFunction->getTemplateSpecializationKind()) { 10785 case TSK_Undeclared: 10786 case TSK_ExplicitSpecialization: 10787 case TSK_ExplicitInstantiationDeclaration: 10788 // The key function is in another translation unit. 10789 DefineVTable = false; 10790 break; 10791 10792 case TSK_ExplicitInstantiationDefinition: 10793 case TSK_ImplicitInstantiation: 10794 // We will be instantiating the key function. 10795 break; 10796 } 10797 } else if (!KeyFunction) { 10798 // If we have a class with no key function that is the subject 10799 // of an explicit instantiation declaration, suppress the 10800 // vtable; it will live with the explicit instantiation 10801 // definition. 10802 bool IsExplicitInstantiationDeclaration 10803 = Class->getTemplateSpecializationKind() 10804 == TSK_ExplicitInstantiationDeclaration; 10805 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 10806 REnd = Class->redecls_end(); 10807 R != REnd; ++R) { 10808 TemplateSpecializationKind TSK 10809 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 10810 if (TSK == TSK_ExplicitInstantiationDeclaration) 10811 IsExplicitInstantiationDeclaration = true; 10812 else if (TSK == TSK_ExplicitInstantiationDefinition) { 10813 IsExplicitInstantiationDeclaration = false; 10814 break; 10815 } 10816 } 10817 10818 if (IsExplicitInstantiationDeclaration) 10819 DefineVTable = false; 10820 } 10821 10822 // The exception specifications for all virtual members may be needed even 10823 // if we are not providing an authoritative form of the vtable in this TU. 10824 // We may choose to emit it available_externally anyway. 10825 if (!DefineVTable) { 10826 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 10827 continue; 10828 } 10829 10830 // Mark all of the virtual members of this class as referenced, so 10831 // that we can build a vtable. Then, tell the AST consumer that a 10832 // vtable for this class is required. 10833 DefinedAnything = true; 10834 MarkVirtualMembersReferenced(Loc, Class); 10835 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 10836 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 10837 10838 // Optionally warn if we're emitting a weak vtable. 10839 if (Class->getLinkage() == ExternalLinkage && 10840 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 10841 const FunctionDecl *KeyFunctionDef = 0; 10842 if (!KeyFunction || 10843 (KeyFunction->hasBody(KeyFunctionDef) && 10844 KeyFunctionDef->isInlined())) 10845 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 10846 TSK_ExplicitInstantiationDefinition 10847 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 10848 << Class; 10849 } 10850 } 10851 VTableUses.clear(); 10852 10853 return DefinedAnything; 10854} 10855 10856void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 10857 const CXXRecordDecl *RD) { 10858 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 10859 E = RD->method_end(); I != E; ++I) 10860 if ((*I)->isVirtual() && !(*I)->isPure()) 10861 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 10862} 10863 10864void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 10865 const CXXRecordDecl *RD) { 10866 // Mark all functions which will appear in RD's vtable as used. 10867 CXXFinalOverriderMap FinalOverriders; 10868 RD->getFinalOverriders(FinalOverriders); 10869 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 10870 E = FinalOverriders.end(); 10871 I != E; ++I) { 10872 for (OverridingMethods::const_iterator OI = I->second.begin(), 10873 OE = I->second.end(); 10874 OI != OE; ++OI) { 10875 assert(OI->second.size() > 0 && "no final overrider"); 10876 CXXMethodDecl *Overrider = OI->second.front().Method; 10877 10878 // C++ [basic.def.odr]p2: 10879 // [...] A virtual member function is used if it is not pure. [...] 10880 if (!Overrider->isPure()) 10881 MarkFunctionReferenced(Loc, Overrider); 10882 } 10883 } 10884 10885 // Only classes that have virtual bases need a VTT. 10886 if (RD->getNumVBases() == 0) 10887 return; 10888 10889 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 10890 e = RD->bases_end(); i != e; ++i) { 10891 const CXXRecordDecl *Base = 10892 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 10893 if (Base->getNumVBases() == 0) 10894 continue; 10895 MarkVirtualMembersReferenced(Loc, Base); 10896 } 10897} 10898 10899/// SetIvarInitializers - This routine builds initialization ASTs for the 10900/// Objective-C implementation whose ivars need be initialized. 10901void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 10902 if (!getLangOpts().CPlusPlus) 10903 return; 10904 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 10905 SmallVector<ObjCIvarDecl*, 8> ivars; 10906 CollectIvarsToConstructOrDestruct(OID, ivars); 10907 if (ivars.empty()) 10908 return; 10909 SmallVector<CXXCtorInitializer*, 32> AllToInit; 10910 for (unsigned i = 0; i < ivars.size(); i++) { 10911 FieldDecl *Field = ivars[i]; 10912 if (Field->isInvalidDecl()) 10913 continue; 10914 10915 CXXCtorInitializer *Member; 10916 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 10917 InitializationKind InitKind = 10918 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 10919 10920 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 10921 ExprResult MemberInit = 10922 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 10923 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 10924 // Note, MemberInit could actually come back empty if no initialization 10925 // is required (e.g., because it would call a trivial default constructor) 10926 if (!MemberInit.get() || MemberInit.isInvalid()) 10927 continue; 10928 10929 Member = 10930 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 10931 SourceLocation(), 10932 MemberInit.takeAs<Expr>(), 10933 SourceLocation()); 10934 AllToInit.push_back(Member); 10935 10936 // Be sure that the destructor is accessible and is marked as referenced. 10937 if (const RecordType *RecordTy 10938 = Context.getBaseElementType(Field->getType()) 10939 ->getAs<RecordType>()) { 10940 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 10941 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 10942 MarkFunctionReferenced(Field->getLocation(), Destructor); 10943 CheckDestructorAccess(Field->getLocation(), Destructor, 10944 PDiag(diag::err_access_dtor_ivar) 10945 << Context.getBaseElementType(Field->getType())); 10946 } 10947 } 10948 } 10949 ObjCImplementation->setIvarInitializers(Context, 10950 AllToInit.data(), AllToInit.size()); 10951 } 10952} 10953 10954static 10955void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 10956 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 10957 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 10958 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 10959 Sema &S) { 10960 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 10961 CE = Current.end(); 10962 if (Ctor->isInvalidDecl()) 10963 return; 10964 10965 const FunctionDecl *FNTarget = 0; 10966 CXXConstructorDecl *Target; 10967 10968 // We ignore the result here since if we don't have a body, Target will be 10969 // null below. 10970 (void)Ctor->getTargetConstructor()->hasBody(FNTarget); 10971 Target 10972= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget)); 10973 10974 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 10975 // Avoid dereferencing a null pointer here. 10976 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 10977 10978 if (!Current.insert(Canonical)) 10979 return; 10980 10981 // We know that beyond here, we aren't chaining into a cycle. 10982 if (!Target || !Target->isDelegatingConstructor() || 10983 Target->isInvalidDecl() || Valid.count(TCanonical)) { 10984 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 10985 Valid.insert(*CI); 10986 Current.clear(); 10987 // We've hit a cycle. 10988 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 10989 Current.count(TCanonical)) { 10990 // If we haven't diagnosed this cycle yet, do so now. 10991 if (!Invalid.count(TCanonical)) { 10992 S.Diag((*Ctor->init_begin())->getSourceLocation(), 10993 diag::warn_delegating_ctor_cycle) 10994 << Ctor; 10995 10996 // Don't add a note for a function delegating directo to itself. 10997 if (TCanonical != Canonical) 10998 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 10999 11000 CXXConstructorDecl *C = Target; 11001 while (C->getCanonicalDecl() != Canonical) { 11002 (void)C->getTargetConstructor()->hasBody(FNTarget); 11003 assert(FNTarget && "Ctor cycle through bodiless function"); 11004 11005 C 11006 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget)); 11007 S.Diag(C->getLocation(), diag::note_which_delegates_to); 11008 } 11009 } 11010 11011 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI) 11012 Invalid.insert(*CI); 11013 Current.clear(); 11014 } else { 11015 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 11016 } 11017} 11018 11019 11020void Sema::CheckDelegatingCtorCycles() { 11021 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 11022 11023 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(), 11024 CE = Current.end(); 11025 11026 for (DelegatingCtorDeclsType::iterator 11027 I = DelegatingCtorDecls.begin(ExternalSource), 11028 E = DelegatingCtorDecls.end(); 11029 I != E; ++I) { 11030 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 11031 } 11032 11033 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 11034 (*CI)->setInvalidDecl(); 11035} 11036 11037namespace { 11038 /// \brief AST visitor that finds references to the 'this' expression. 11039 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 11040 Sema &S; 11041 11042 public: 11043 explicit FindCXXThisExpr(Sema &S) : S(S) { } 11044 11045 bool VisitCXXThisExpr(CXXThisExpr *E) { 11046 S.Diag(E->getLocation(), diag::err_this_static_member_func) 11047 << E->isImplicit(); 11048 return false; 11049 } 11050 }; 11051} 11052 11053bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 11054 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 11055 if (!TSInfo) 11056 return false; 11057 11058 TypeLoc TL = TSInfo->getTypeLoc(); 11059 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL); 11060 if (!ProtoTL) 11061 return false; 11062 11063 // C++11 [expr.prim.general]p3: 11064 // [The expression this] shall not appear before the optional 11065 // cv-qualifier-seq and it shall not appear within the declaration of a 11066 // static member function (although its type and value category are defined 11067 // within a static member function as they are within a non-static member 11068 // function). [ Note: this is because declaration matching does not occur 11069 // until the complete declarator is known. - end note ] 11070 const FunctionProtoType *Proto = ProtoTL->getTypePtr(); 11071 FindCXXThisExpr Finder(*this); 11072 11073 // If the return type came after the cv-qualifier-seq, check it now. 11074 if (Proto->hasTrailingReturn() && 11075 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc())) 11076 return true; 11077 11078 // Check the exception specification. 11079 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 11080 return true; 11081 11082 return checkThisInStaticMemberFunctionAttributes(Method); 11083} 11084 11085bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 11086 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 11087 if (!TSInfo) 11088 return false; 11089 11090 TypeLoc TL = TSInfo->getTypeLoc(); 11091 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL); 11092 if (!ProtoTL) 11093 return false; 11094 11095 const FunctionProtoType *Proto = ProtoTL->getTypePtr(); 11096 FindCXXThisExpr Finder(*this); 11097 11098 switch (Proto->getExceptionSpecType()) { 11099 case EST_Uninstantiated: 11100 case EST_Unevaluated: 11101 case EST_BasicNoexcept: 11102 case EST_DynamicNone: 11103 case EST_MSAny: 11104 case EST_None: 11105 break; 11106 11107 case EST_ComputedNoexcept: 11108 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 11109 return true; 11110 11111 case EST_Dynamic: 11112 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 11113 EEnd = Proto->exception_end(); 11114 E != EEnd; ++E) { 11115 if (!Finder.TraverseType(*E)) 11116 return true; 11117 } 11118 break; 11119 } 11120 11121 return false; 11122} 11123 11124bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 11125 FindCXXThisExpr Finder(*this); 11126 11127 // Check attributes. 11128 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end(); 11129 A != AEnd; ++A) { 11130 // FIXME: This should be emitted by tblgen. 11131 Expr *Arg = 0; 11132 ArrayRef<Expr *> Args; 11133 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A)) 11134 Arg = G->getArg(); 11135 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A)) 11136 Arg = G->getArg(); 11137 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A)) 11138 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 11139 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A)) 11140 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 11141 else if (ExclusiveLockFunctionAttr *ELF 11142 = dyn_cast<ExclusiveLockFunctionAttr>(*A)) 11143 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 11144 else if (SharedLockFunctionAttr *SLF 11145 = dyn_cast<SharedLockFunctionAttr>(*A)) 11146 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 11147 else if (ExclusiveTrylockFunctionAttr *ETLF 11148 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) { 11149 Arg = ETLF->getSuccessValue(); 11150 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 11151 } else if (SharedTrylockFunctionAttr *STLF 11152 = dyn_cast<SharedTrylockFunctionAttr>(*A)) { 11153 Arg = STLF->getSuccessValue(); 11154 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 11155 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A)) 11156 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 11157 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A)) 11158 Arg = LR->getArg(); 11159 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A)) 11160 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 11161 else if (ExclusiveLocksRequiredAttr *ELR 11162 = dyn_cast<ExclusiveLocksRequiredAttr>(*A)) 11163 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size()); 11164 else if (SharedLocksRequiredAttr *SLR 11165 = dyn_cast<SharedLocksRequiredAttr>(*A)) 11166 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size()); 11167 11168 if (Arg && !Finder.TraverseStmt(Arg)) 11169 return true; 11170 11171 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 11172 if (!Finder.TraverseStmt(Args[I])) 11173 return true; 11174 } 11175 } 11176 11177 return false; 11178} 11179 11180void 11181Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 11182 ArrayRef<ParsedType> DynamicExceptions, 11183 ArrayRef<SourceRange> DynamicExceptionRanges, 11184 Expr *NoexceptExpr, 11185 llvm::SmallVectorImpl<QualType> &Exceptions, 11186 FunctionProtoType::ExtProtoInfo &EPI) { 11187 Exceptions.clear(); 11188 EPI.ExceptionSpecType = EST; 11189 if (EST == EST_Dynamic) { 11190 Exceptions.reserve(DynamicExceptions.size()); 11191 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 11192 // FIXME: Preserve type source info. 11193 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 11194 11195 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 11196 collectUnexpandedParameterPacks(ET, Unexpanded); 11197 if (!Unexpanded.empty()) { 11198 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 11199 UPPC_ExceptionType, 11200 Unexpanded); 11201 continue; 11202 } 11203 11204 // Check that the type is valid for an exception spec, and 11205 // drop it if not. 11206 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 11207 Exceptions.push_back(ET); 11208 } 11209 EPI.NumExceptions = Exceptions.size(); 11210 EPI.Exceptions = Exceptions.data(); 11211 return; 11212 } 11213 11214 if (EST == EST_ComputedNoexcept) { 11215 // If an error occurred, there's no expression here. 11216 if (NoexceptExpr) { 11217 assert((NoexceptExpr->isTypeDependent() || 11218 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 11219 Context.BoolTy) && 11220 "Parser should have made sure that the expression is boolean"); 11221 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 11222 EPI.ExceptionSpecType = EST_BasicNoexcept; 11223 return; 11224 } 11225 11226 if (!NoexceptExpr->isValueDependent()) 11227 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 11228 diag::err_noexcept_needs_constant_expression, 11229 /*AllowFold*/ false).take(); 11230 EPI.NoexceptExpr = NoexceptExpr; 11231 } 11232 return; 11233 } 11234} 11235 11236/// IdentifyCUDATarget - Determine the CUDA compilation target for this function 11237Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 11238 // Implicitly declared functions (e.g. copy constructors) are 11239 // __host__ __device__ 11240 if (D->isImplicit()) 11241 return CFT_HostDevice; 11242 11243 if (D->hasAttr<CUDAGlobalAttr>()) 11244 return CFT_Global; 11245 11246 if (D->hasAttr<CUDADeviceAttr>()) { 11247 if (D->hasAttr<CUDAHostAttr>()) 11248 return CFT_HostDevice; 11249 else 11250 return CFT_Device; 11251 } 11252 11253 return CFT_Host; 11254} 11255 11256bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 11257 CUDAFunctionTarget CalleeTarget) { 11258 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 11259 // Callable from the device only." 11260 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 11261 return true; 11262 11263 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 11264 // Callable from the host only." 11265 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 11266 // Callable from the host only." 11267 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 11268 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 11269 return true; 11270 11271 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 11272 return true; 11273 11274 return false; 11275} 11276