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