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