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