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/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/DeclVisitor.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/RecordLayout.h" 25 #include "clang/AST/RecursiveASTVisitor.h" 26 #include "clang/AST/StmtVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/AST/TypeOrdering.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/LiteralSupport.h" 32 #include "clang/Lex/Preprocessor.h" 33 #include "clang/Sema/CXXFieldCollector.h" 34 #include "clang/Sema/DeclSpec.h" 35 #include "clang/Sema/Initialization.h" 36 #include "clang/Sema/Lookup.h" 37 #include "clang/Sema/ParsedTemplate.h" 38 #include "clang/Sema/Scope.h" 39 #include "clang/Sema/ScopeInfo.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/SmallString.h" 42 #include <map> 43 #include <set> 44 45 using namespace clang; 46 47 //===----------------------------------------------------------------------===// 48 // CheckDefaultArgumentVisitor 49 //===----------------------------------------------------------------------===// 50 51 namespace { 52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 53 /// the default argument of a parameter to determine whether it 54 /// contains any ill-formed subexpressions. For example, this will 55 /// diagnose the use of local variables or parameters within the 56 /// default argument expression. 57 class CheckDefaultArgumentVisitor 58 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 59 Expr *DefaultArg; 60 Sema *S; 61 62 public: 63 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 64 : DefaultArg(defarg), S(s) {} 65 66 bool VisitExpr(Expr *Node); 67 bool VisitDeclRefExpr(DeclRefExpr *DRE); 68 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 69 bool VisitLambdaExpr(LambdaExpr *Lambda); 70 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 71 }; 72 73 /// VisitExpr - Visit all of the children of this expression. 74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 75 bool IsInvalid = false; 76 for (Stmt::child_range I = Node->children(); I; ++I) 77 IsInvalid |= Visit(*I); 78 return IsInvalid; 79 } 80 81 /// VisitDeclRefExpr - Visit a reference to a declaration, to 82 /// determine whether this declaration can be used in the default 83 /// argument expression. 84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 85 NamedDecl *Decl = DRE->getDecl(); 86 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 87 // C++ [dcl.fct.default]p9 88 // Default arguments are evaluated each time the function is 89 // called. The order of evaluation of function arguments is 90 // unspecified. Consequently, parameters of a function shall not 91 // be used in default argument expressions, even if they are not 92 // evaluated. Parameters of a function declared before a default 93 // argument expression are in scope and can hide namespace and 94 // class member names. 95 return S->Diag(DRE->getLocStart(), 96 diag::err_param_default_argument_references_param) 97 << Param->getDeclName() << DefaultArg->getSourceRange(); 98 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 99 // C++ [dcl.fct.default]p7 100 // Local variables shall not be used in default argument 101 // expressions. 102 if (VDecl->isLocalVarDecl()) 103 return S->Diag(DRE->getLocStart(), 104 diag::err_param_default_argument_references_local) 105 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 106 } 107 108 return false; 109 } 110 111 /// VisitCXXThisExpr - Visit a C++ "this" expression. 112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 113 // C++ [dcl.fct.default]p8: 114 // The keyword this shall not be used in a default argument of a 115 // member function. 116 return S->Diag(ThisE->getLocStart(), 117 diag::err_param_default_argument_references_this) 118 << ThisE->getSourceRange(); 119 } 120 121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 122 bool Invalid = false; 123 for (PseudoObjectExpr::semantics_iterator 124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 125 Expr *E = *i; 126 127 // Look through bindings. 128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 129 E = OVE->getSourceExpr(); 130 assert(E && "pseudo-object binding without source expression?"); 131 } 132 133 Invalid |= Visit(E); 134 } 135 return Invalid; 136 } 137 138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 139 // C++11 [expr.lambda.prim]p13: 140 // A lambda-expression appearing in a default argument shall not 141 // implicitly or explicitly capture any entity. 142 if (Lambda->capture_begin() == Lambda->capture_end()) 143 return false; 144 145 return S->Diag(Lambda->getLocStart(), 146 diag::err_lambda_capture_default_arg); 147 } 148 } 149 150 void 151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 152 const CXXMethodDecl *Method) { 153 // If we have an MSAny spec already, don't bother. 154 if (!Method || ComputedEST == EST_MSAny) 155 return; 156 157 const FunctionProtoType *Proto 158 = Method->getType()->getAs<FunctionProtoType>(); 159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 160 if (!Proto) 161 return; 162 163 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 164 165 // If this function can throw any exceptions, make a note of that. 166 if (EST == EST_MSAny || EST == EST_None) { 167 ClearExceptions(); 168 ComputedEST = EST; 169 return; 170 } 171 172 // FIXME: If the call to this decl is using any of its default arguments, we 173 // need to search them for potentially-throwing calls. 174 175 // If this function has a basic noexcept, it doesn't affect the outcome. 176 if (EST == EST_BasicNoexcept) 177 return; 178 179 // If we have a throw-all spec at this point, ignore the function. 180 if (ComputedEST == EST_None) 181 return; 182 183 // If we're still at noexcept(true) and there's a nothrow() callee, 184 // change to that specification. 185 if (EST == EST_DynamicNone) { 186 if (ComputedEST == EST_BasicNoexcept) 187 ComputedEST = EST_DynamicNone; 188 return; 189 } 190 191 // Check out noexcept specs. 192 if (EST == EST_ComputedNoexcept) { 193 FunctionProtoType::NoexceptResult NR = 194 Proto->getNoexceptSpec(Self->Context); 195 assert(NR != FunctionProtoType::NR_NoNoexcept && 196 "Must have noexcept result for EST_ComputedNoexcept."); 197 assert(NR != FunctionProtoType::NR_Dependent && 198 "Should not generate implicit declarations for dependent cases, " 199 "and don't know how to handle them anyway."); 200 201 // noexcept(false) -> no spec on the new function 202 if (NR == FunctionProtoType::NR_Throw) { 203 ClearExceptions(); 204 ComputedEST = EST_None; 205 } 206 // noexcept(true) won't change anything either. 207 return; 208 } 209 210 assert(EST == EST_Dynamic && "EST case not considered earlier."); 211 assert(ComputedEST != EST_None && 212 "Shouldn't collect exceptions when throw-all is guaranteed."); 213 ComputedEST = EST_Dynamic; 214 // Record the exceptions in this function's exception specification. 215 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 216 EEnd = Proto->exception_end(); 217 E != EEnd; ++E) 218 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E))) 219 Exceptions.push_back(*E); 220 } 221 222 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 223 if (!E || ComputedEST == EST_MSAny) 224 return; 225 226 // FIXME: 227 // 228 // C++0x [except.spec]p14: 229 // [An] implicit exception-specification specifies the type-id T if and 230 // only if T is allowed by the exception-specification of a function directly 231 // invoked by f's implicit definition; f shall allow all exceptions if any 232 // function it directly invokes allows all exceptions, and f shall allow no 233 // exceptions if every function it directly invokes allows no exceptions. 234 // 235 // Note in particular that if an implicit exception-specification is generated 236 // for a function containing a throw-expression, that specification can still 237 // be noexcept(true). 238 // 239 // Note also that 'directly invoked' is not defined in the standard, and there 240 // is no indication that we should only consider potentially-evaluated calls. 241 // 242 // Ultimately we should implement the intent of the standard: the exception 243 // specification should be the set of exceptions which can be thrown by the 244 // implicit definition. For now, we assume that any non-nothrow expression can 245 // throw any exception. 246 247 if (Self->canThrow(E)) 248 ComputedEST = EST_None; 249 } 250 251 bool 252 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 253 SourceLocation EqualLoc) { 254 if (RequireCompleteType(Param->getLocation(), Param->getType(), 255 diag::err_typecheck_decl_incomplete_type)) { 256 Param->setInvalidDecl(); 257 return true; 258 } 259 260 // C++ [dcl.fct.default]p5 261 // A default argument expression is implicitly converted (clause 262 // 4) to the parameter type. The default argument expression has 263 // the same semantic constraints as the initializer expression in 264 // a declaration of a variable of the parameter type, using the 265 // copy-initialization semantics (8.5). 266 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 267 Param); 268 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 269 EqualLoc); 270 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 271 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 272 if (Result.isInvalid()) 273 return true; 274 Arg = Result.takeAs<Expr>(); 275 276 CheckCompletedExpr(Arg, EqualLoc); 277 Arg = MaybeCreateExprWithCleanups(Arg); 278 279 // Okay: add the default argument to the parameter 280 Param->setDefaultArg(Arg); 281 282 // We have already instantiated this parameter; provide each of the 283 // instantiations with the uninstantiated default argument. 284 UnparsedDefaultArgInstantiationsMap::iterator InstPos 285 = UnparsedDefaultArgInstantiations.find(Param); 286 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 287 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 288 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 289 290 // We're done tracking this parameter's instantiations. 291 UnparsedDefaultArgInstantiations.erase(InstPos); 292 } 293 294 return false; 295 } 296 297 /// ActOnParamDefaultArgument - Check whether the default argument 298 /// provided for a function parameter is well-formed. If so, attach it 299 /// to the parameter declaration. 300 void 301 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 302 Expr *DefaultArg) { 303 if (!param || !DefaultArg) 304 return; 305 306 ParmVarDecl *Param = cast<ParmVarDecl>(param); 307 UnparsedDefaultArgLocs.erase(Param); 308 309 // Default arguments are only permitted in C++ 310 if (!getLangOpts().CPlusPlus) { 311 Diag(EqualLoc, diag::err_param_default_argument) 312 << DefaultArg->getSourceRange(); 313 Param->setInvalidDecl(); 314 return; 315 } 316 317 // Check for unexpanded parameter packs. 318 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 319 Param->setInvalidDecl(); 320 return; 321 } 322 323 // Check that the default argument is well-formed 324 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 325 if (DefaultArgChecker.Visit(DefaultArg)) { 326 Param->setInvalidDecl(); 327 return; 328 } 329 330 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 331 } 332 333 /// ActOnParamUnparsedDefaultArgument - We've seen a default 334 /// argument for a function parameter, but we can't parse it yet 335 /// because we're inside a class definition. Note that this default 336 /// argument will be parsed later. 337 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 338 SourceLocation EqualLoc, 339 SourceLocation ArgLoc) { 340 if (!param) 341 return; 342 343 ParmVarDecl *Param = cast<ParmVarDecl>(param); 344 Param->setUnparsedDefaultArg(); 345 UnparsedDefaultArgLocs[Param] = ArgLoc; 346 } 347 348 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 349 /// the default argument for the parameter param failed. 350 void Sema::ActOnParamDefaultArgumentError(Decl *param) { 351 if (!param) 352 return; 353 354 ParmVarDecl *Param = cast<ParmVarDecl>(param); 355 Param->setInvalidDecl(); 356 UnparsedDefaultArgLocs.erase(Param); 357 } 358 359 /// CheckExtraCXXDefaultArguments - Check for any extra default 360 /// arguments in the declarator, which is not a function declaration 361 /// or definition and therefore is not permitted to have default 362 /// arguments. This routine should be invoked for every declarator 363 /// that is not a function declaration or definition. 364 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 365 // C++ [dcl.fct.default]p3 366 // A default argument expression shall be specified only in the 367 // parameter-declaration-clause of a function declaration or in a 368 // template-parameter (14.1). It shall not be specified for a 369 // parameter pack. If it is specified in a 370 // parameter-declaration-clause, it shall not occur within a 371 // declarator or abstract-declarator of a parameter-declaration. 372 bool MightBeFunction = D.isFunctionDeclarationContext(); 373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 374 DeclaratorChunk &chunk = D.getTypeObject(i); 375 if (chunk.Kind == DeclaratorChunk::Function) { 376 if (MightBeFunction) { 377 // This is a function declaration. It can have default arguments, but 378 // keep looking in case its return type is a function type with default 379 // arguments. 380 MightBeFunction = false; 381 continue; 382 } 383 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 384 ParmVarDecl *Param = 385 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 386 if (Param->hasUnparsedDefaultArg()) { 387 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 388 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 389 << SourceRange((*Toks)[1].getLocation(), 390 Toks->back().getLocation()); 391 delete Toks; 392 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 393 } else if (Param->getDefaultArg()) { 394 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 395 << Param->getDefaultArg()->getSourceRange(); 396 Param->setDefaultArg(0); 397 } 398 } 399 } else if (chunk.Kind != DeclaratorChunk::Paren) { 400 MightBeFunction = false; 401 } 402 } 403 } 404 405 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 406 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 407 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 408 if (!PVD->hasDefaultArg()) 409 return false; 410 if (!PVD->hasInheritedDefaultArg()) 411 return true; 412 } 413 return false; 414 } 415 416 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 417 /// function, once we already know that they have the same 418 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 419 /// error, false otherwise. 420 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 421 Scope *S) { 422 bool Invalid = false; 423 424 // C++ [dcl.fct.default]p4: 425 // For non-template functions, default arguments can be added in 426 // later declarations of a function in the same 427 // scope. Declarations in different scopes have completely 428 // distinct sets of default arguments. That is, declarations in 429 // inner scopes do not acquire default arguments from 430 // declarations in outer scopes, and vice versa. In a given 431 // function declaration, all parameters subsequent to a 432 // parameter with a default argument shall have default 433 // arguments supplied in this or previous declarations. A 434 // default argument shall not be redefined by a later 435 // declaration (not even to the same value). 436 // 437 // C++ [dcl.fct.default]p6: 438 // Except for member functions of class templates, the default arguments 439 // in a member function definition that appears outside of the class 440 // definition are added to the set of default arguments provided by the 441 // member function declaration in the class definition. 442 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 443 ParmVarDecl *OldParam = Old->getParamDecl(p); 444 ParmVarDecl *NewParam = New->getParamDecl(p); 445 446 bool OldParamHasDfl = OldParam->hasDefaultArg(); 447 bool NewParamHasDfl = NewParam->hasDefaultArg(); 448 449 NamedDecl *ND = Old; 450 451 // The declaration context corresponding to the scope is the semantic 452 // parent, unless this is a local function declaration, in which case 453 // it is that surrounding function. 454 DeclContext *ScopeDC = New->getLexicalDeclContext(); 455 if (!ScopeDC->isFunctionOrMethod()) 456 ScopeDC = New->getDeclContext(); 457 if (S && !isDeclInScope(ND, ScopeDC, S) && 458 !New->getDeclContext()->isRecord()) 459 // Ignore default parameters of old decl if they are not in 460 // the same scope and this is not an out-of-line definition of 461 // a member function. 462 OldParamHasDfl = false; 463 464 if (OldParamHasDfl && NewParamHasDfl) { 465 466 unsigned DiagDefaultParamID = 467 diag::err_param_default_argument_redefinition; 468 469 // MSVC accepts that default parameters be redefined for member functions 470 // of template class. The new default parameter's value is ignored. 471 Invalid = true; 472 if (getLangOpts().MicrosoftExt) { 473 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 474 if (MD && MD->getParent()->getDescribedClassTemplate()) { 475 // Merge the old default argument into the new parameter. 476 NewParam->setHasInheritedDefaultArg(); 477 if (OldParam->hasUninstantiatedDefaultArg()) 478 NewParam->setUninstantiatedDefaultArg( 479 OldParam->getUninstantiatedDefaultArg()); 480 else 481 NewParam->setDefaultArg(OldParam->getInit()); 482 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 483 Invalid = false; 484 } 485 } 486 487 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 488 // hint here. Alternatively, we could walk the type-source information 489 // for NewParam to find the last source location in the type... but it 490 // isn't worth the effort right now. This is the kind of test case that 491 // is hard to get right: 492 // int f(int); 493 // void g(int (*fp)(int) = f); 494 // void g(int (*fp)(int) = &f); 495 Diag(NewParam->getLocation(), DiagDefaultParamID) 496 << NewParam->getDefaultArgRange(); 497 498 // Look for the function declaration where the default argument was 499 // actually written, which may be a declaration prior to Old. 500 for (FunctionDecl *Older = Old->getPreviousDecl(); 501 Older; Older = Older->getPreviousDecl()) { 502 if (!Older->getParamDecl(p)->hasDefaultArg()) 503 break; 504 505 OldParam = Older->getParamDecl(p); 506 } 507 508 Diag(OldParam->getLocation(), diag::note_previous_definition) 509 << OldParam->getDefaultArgRange(); 510 } else if (OldParamHasDfl) { 511 // Merge the old default argument into the new parameter. 512 // It's important to use getInit() here; getDefaultArg() 513 // strips off any top-level ExprWithCleanups. 514 NewParam->setHasInheritedDefaultArg(); 515 if (OldParam->hasUninstantiatedDefaultArg()) 516 NewParam->setUninstantiatedDefaultArg( 517 OldParam->getUninstantiatedDefaultArg()); 518 else 519 NewParam->setDefaultArg(OldParam->getInit()); 520 } else if (NewParamHasDfl) { 521 if (New->getDescribedFunctionTemplate()) { 522 // Paragraph 4, quoted above, only applies to non-template functions. 523 Diag(NewParam->getLocation(), 524 diag::err_param_default_argument_template_redecl) 525 << NewParam->getDefaultArgRange(); 526 Diag(Old->getLocation(), diag::note_template_prev_declaration) 527 << false; 528 } else if (New->getTemplateSpecializationKind() 529 != TSK_ImplicitInstantiation && 530 New->getTemplateSpecializationKind() != TSK_Undeclared) { 531 // C++ [temp.expr.spec]p21: 532 // Default function arguments shall not be specified in a declaration 533 // or a definition for one of the following explicit specializations: 534 // - the explicit specialization of a function template; 535 // - the explicit specialization of a member function template; 536 // - the explicit specialization of a member function of a class 537 // template where the class template specialization to which the 538 // member function specialization belongs is implicitly 539 // instantiated. 540 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 541 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 542 << New->getDeclName() 543 << NewParam->getDefaultArgRange(); 544 } else if (New->getDeclContext()->isDependentContext()) { 545 // C++ [dcl.fct.default]p6 (DR217): 546 // Default arguments for a member function of a class template shall 547 // be specified on the initial declaration of the member function 548 // within the class template. 549 // 550 // Reading the tea leaves a bit in DR217 and its reference to DR205 551 // leads me to the conclusion that one cannot add default function 552 // arguments for an out-of-line definition of a member function of a 553 // dependent type. 554 int WhichKind = 2; 555 if (CXXRecordDecl *Record 556 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 557 if (Record->getDescribedClassTemplate()) 558 WhichKind = 0; 559 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 560 WhichKind = 1; 561 else 562 WhichKind = 2; 563 } 564 565 Diag(NewParam->getLocation(), 566 diag::err_param_default_argument_member_template_redecl) 567 << WhichKind 568 << NewParam->getDefaultArgRange(); 569 } 570 } 571 } 572 573 // DR1344: If a default argument is added outside a class definition and that 574 // default argument makes the function a special member function, the program 575 // is ill-formed. This can only happen for constructors. 576 if (isa<CXXConstructorDecl>(New) && 577 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 578 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 579 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 580 if (NewSM != OldSM) { 581 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 582 assert(NewParam->hasDefaultArg()); 583 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 584 << NewParam->getDefaultArgRange() << NewSM; 585 Diag(Old->getLocation(), diag::note_previous_declaration); 586 } 587 } 588 589 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 590 // template has a constexpr specifier then all its declarations shall 591 // contain the constexpr specifier. 592 if (New->isConstexpr() != Old->isConstexpr()) { 593 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 594 << New << New->isConstexpr(); 595 Diag(Old->getLocation(), diag::note_previous_declaration); 596 Invalid = true; 597 } 598 599 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 600 // argument expression, that declaration shall be a definition and shall be 601 // the only declaration of the function or function template in the 602 // translation unit. 603 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 604 functionDeclHasDefaultArgument(Old)) { 605 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 606 Diag(Old->getLocation(), diag::note_previous_declaration); 607 Invalid = true; 608 } 609 610 if (CheckEquivalentExceptionSpec(Old, New)) 611 Invalid = true; 612 613 return Invalid; 614 } 615 616 /// \brief Merge the exception specifications of two variable declarations. 617 /// 618 /// This is called when there's a redeclaration of a VarDecl. The function 619 /// checks if the redeclaration might have an exception specification and 620 /// validates compatibility and merges the specs if necessary. 621 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 622 // Shortcut if exceptions are disabled. 623 if (!getLangOpts().CXXExceptions) 624 return; 625 626 assert(Context.hasSameType(New->getType(), Old->getType()) && 627 "Should only be called if types are otherwise the same."); 628 629 QualType NewType = New->getType(); 630 QualType OldType = Old->getType(); 631 632 // We're only interested in pointers and references to functions, as well 633 // as pointers to member functions. 634 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 635 NewType = R->getPointeeType(); 636 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 637 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 638 NewType = P->getPointeeType(); 639 OldType = OldType->getAs<PointerType>()->getPointeeType(); 640 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 641 NewType = M->getPointeeType(); 642 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 643 } 644 645 if (!NewType->isFunctionProtoType()) 646 return; 647 648 // There's lots of special cases for functions. For function pointers, system 649 // libraries are hopefully not as broken so that we don't need these 650 // workarounds. 651 if (CheckEquivalentExceptionSpec( 652 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 653 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 654 New->setInvalidDecl(); 655 } 656 } 657 658 /// CheckCXXDefaultArguments - Verify that the default arguments for a 659 /// function declaration are well-formed according to C++ 660 /// [dcl.fct.default]. 661 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 662 unsigned NumParams = FD->getNumParams(); 663 unsigned p; 664 665 // Find first parameter with a default argument 666 for (p = 0; p < NumParams; ++p) { 667 ParmVarDecl *Param = FD->getParamDecl(p); 668 if (Param->hasDefaultArg()) 669 break; 670 } 671 672 // C++ [dcl.fct.default]p4: 673 // In a given function declaration, all parameters 674 // subsequent to a parameter with a default argument shall 675 // have default arguments supplied in this or previous 676 // declarations. A default argument shall not be redefined 677 // by a later declaration (not even to the same value). 678 unsigned LastMissingDefaultArg = 0; 679 for (; p < NumParams; ++p) { 680 ParmVarDecl *Param = FD->getParamDecl(p); 681 if (!Param->hasDefaultArg()) { 682 if (Param->isInvalidDecl()) 683 /* We already complained about this parameter. */; 684 else if (Param->getIdentifier()) 685 Diag(Param->getLocation(), 686 diag::err_param_default_argument_missing_name) 687 << Param->getIdentifier(); 688 else 689 Diag(Param->getLocation(), 690 diag::err_param_default_argument_missing); 691 692 LastMissingDefaultArg = p; 693 } 694 } 695 696 if (LastMissingDefaultArg > 0) { 697 // Some default arguments were missing. Clear out all of the 698 // default arguments up to (and including) the last missing 699 // default argument, so that we leave the function parameters 700 // in a semantically valid state. 701 for (p = 0; p <= LastMissingDefaultArg; ++p) { 702 ParmVarDecl *Param = FD->getParamDecl(p); 703 if (Param->hasDefaultArg()) { 704 Param->setDefaultArg(0); 705 } 706 } 707 } 708 } 709 710 // CheckConstexprParameterTypes - Check whether a function's parameter types 711 // are all literal types. If so, return true. If not, produce a suitable 712 // diagnostic and return false. 713 static bool CheckConstexprParameterTypes(Sema &SemaRef, 714 const FunctionDecl *FD) { 715 unsigned ArgIndex = 0; 716 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 717 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 718 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 719 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 720 SourceLocation ParamLoc = PD->getLocation(); 721 if (!(*i)->isDependentType() && 722 SemaRef.RequireLiteralType(ParamLoc, *i, 723 diag::err_constexpr_non_literal_param, 724 ArgIndex+1, PD->getSourceRange(), 725 isa<CXXConstructorDecl>(FD))) 726 return false; 727 } 728 return true; 729 } 730 731 /// \brief Get diagnostic %select index for tag kind for 732 /// record diagnostic message. 733 /// WARNING: Indexes apply to particular diagnostics only! 734 /// 735 /// \returns diagnostic %select index. 736 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 737 switch (Tag) { 738 case TTK_Struct: return 0; 739 case TTK_Interface: return 1; 740 case TTK_Class: return 2; 741 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 742 } 743 } 744 745 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 746 // the requirements of a constexpr function definition or a constexpr 747 // constructor definition. If so, return true. If not, produce appropriate 748 // diagnostics and return false. 749 // 750 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 751 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 752 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 753 if (MD && MD->isInstance()) { 754 // C++11 [dcl.constexpr]p4: 755 // The definition of a constexpr constructor shall satisfy the following 756 // constraints: 757 // - the class shall not have any virtual base classes; 758 const CXXRecordDecl *RD = MD->getParent(); 759 if (RD->getNumVBases()) { 760 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 761 << isa<CXXConstructorDecl>(NewFD) 762 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 763 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 764 E = RD->vbases_end(); I != E; ++I) 765 Diag(I->getLocStart(), 766 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 767 return false; 768 } 769 } 770 771 if (!isa<CXXConstructorDecl>(NewFD)) { 772 // C++11 [dcl.constexpr]p3: 773 // The definition of a constexpr function shall satisfy the following 774 // constraints: 775 // - it shall not be virtual; 776 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 777 if (Method && Method->isVirtual()) { 778 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 779 780 // If it's not obvious why this function is virtual, find an overridden 781 // function which uses the 'virtual' keyword. 782 const CXXMethodDecl *WrittenVirtual = Method; 783 while (!WrittenVirtual->isVirtualAsWritten()) 784 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 785 if (WrittenVirtual != Method) 786 Diag(WrittenVirtual->getLocation(), 787 diag::note_overridden_virtual_function); 788 return false; 789 } 790 791 // - its return type shall be a literal type; 792 QualType RT = NewFD->getResultType(); 793 if (!RT->isDependentType() && 794 RequireLiteralType(NewFD->getLocation(), RT, 795 diag::err_constexpr_non_literal_return)) 796 return false; 797 } 798 799 // - each of its parameter types shall be a literal type; 800 if (!CheckConstexprParameterTypes(*this, NewFD)) 801 return false; 802 803 return true; 804 } 805 806 /// Check the given declaration statement is legal within a constexpr function 807 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 808 /// 809 /// \return true if the body is OK (maybe only as an extension), false if we 810 /// have diagnosed a problem. 811 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 812 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 813 // C++11 [dcl.constexpr]p3 and p4: 814 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 815 // contain only 816 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 817 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 818 switch ((*DclIt)->getKind()) { 819 case Decl::StaticAssert: 820 case Decl::Using: 821 case Decl::UsingShadow: 822 case Decl::UsingDirective: 823 case Decl::UnresolvedUsingTypename: 824 case Decl::UnresolvedUsingValue: 825 // - static_assert-declarations 826 // - using-declarations, 827 // - using-directives, 828 continue; 829 830 case Decl::Typedef: 831 case Decl::TypeAlias: { 832 // - typedef declarations and alias-declarations that do not define 833 // classes or enumerations, 834 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 835 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 836 // Don't allow variably-modified types in constexpr functions. 837 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 838 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 839 << TL.getSourceRange() << TL.getType() 840 << isa<CXXConstructorDecl>(Dcl); 841 return false; 842 } 843 continue; 844 } 845 846 case Decl::Enum: 847 case Decl::CXXRecord: 848 // C++1y allows types to be defined, not just declared. 849 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) 850 SemaRef.Diag(DS->getLocStart(), 851 SemaRef.getLangOpts().CPlusPlus1y 852 ? diag::warn_cxx11_compat_constexpr_type_definition 853 : diag::ext_constexpr_type_definition) 854 << isa<CXXConstructorDecl>(Dcl); 855 continue; 856 857 case Decl::EnumConstant: 858 case Decl::IndirectField: 859 case Decl::ParmVar: 860 // These can only appear with other declarations which are banned in 861 // C++11 and permitted in C++1y, so ignore them. 862 continue; 863 864 case Decl::Var: { 865 // C++1y [dcl.constexpr]p3 allows anything except: 866 // a definition of a variable of non-literal type or of static or 867 // thread storage duration or for which no initialization is performed. 868 VarDecl *VD = cast<VarDecl>(*DclIt); 869 if (VD->isThisDeclarationADefinition()) { 870 if (VD->isStaticLocal()) { 871 SemaRef.Diag(VD->getLocation(), 872 diag::err_constexpr_local_var_static) 873 << isa<CXXConstructorDecl>(Dcl) 874 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 875 return false; 876 } 877 if (!VD->getType()->isDependentType() && 878 SemaRef.RequireLiteralType( 879 VD->getLocation(), VD->getType(), 880 diag::err_constexpr_local_var_non_literal_type, 881 isa<CXXConstructorDecl>(Dcl))) 882 return false; 883 if (!VD->hasInit()) { 884 SemaRef.Diag(VD->getLocation(), 885 diag::err_constexpr_local_var_no_init) 886 << isa<CXXConstructorDecl>(Dcl); 887 return false; 888 } 889 } 890 SemaRef.Diag(VD->getLocation(), 891 SemaRef.getLangOpts().CPlusPlus1y 892 ? diag::warn_cxx11_compat_constexpr_local_var 893 : diag::ext_constexpr_local_var) 894 << isa<CXXConstructorDecl>(Dcl); 895 continue; 896 } 897 898 case Decl::NamespaceAlias: 899 case Decl::Function: 900 // These are disallowed in C++11 and permitted in C++1y. Allow them 901 // everywhere as an extension. 902 if (!Cxx1yLoc.isValid()) 903 Cxx1yLoc = DS->getLocStart(); 904 continue; 905 906 default: 907 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 908 << isa<CXXConstructorDecl>(Dcl); 909 return false; 910 } 911 } 912 913 return true; 914 } 915 916 /// Check that the given field is initialized within a constexpr constructor. 917 /// 918 /// \param Dcl The constexpr constructor being checked. 919 /// \param Field The field being checked. This may be a member of an anonymous 920 /// struct or union nested within the class being checked. 921 /// \param Inits All declarations, including anonymous struct/union members and 922 /// indirect members, for which any initialization was provided. 923 /// \param Diagnosed Set to true if an error is produced. 924 static void CheckConstexprCtorInitializer(Sema &SemaRef, 925 const FunctionDecl *Dcl, 926 FieldDecl *Field, 927 llvm::SmallSet<Decl*, 16> &Inits, 928 bool &Diagnosed) { 929 if (Field->isInvalidDecl()) 930 return; 931 932 if (Field->isUnnamedBitfield()) 933 return; 934 935 if (Field->isAnonymousStructOrUnion() && 936 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 937 return; 938 939 if (!Inits.count(Field)) { 940 if (!Diagnosed) { 941 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 942 Diagnosed = true; 943 } 944 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 945 } else if (Field->isAnonymousStructOrUnion()) { 946 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 947 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 948 I != E; ++I) 949 // If an anonymous union contains an anonymous struct of which any member 950 // is initialized, all members must be initialized. 951 if (!RD->isUnion() || Inits.count(*I)) 952 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 953 } 954 } 955 956 /// Check the provided statement is allowed in a constexpr function 957 /// definition. 958 static bool 959 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 960 SmallVectorImpl<SourceLocation> &ReturnStmts, 961 SourceLocation &Cxx1yLoc) { 962 // - its function-body shall be [...] a compound-statement that contains only 963 switch (S->getStmtClass()) { 964 case Stmt::NullStmtClass: 965 // - null statements, 966 return true; 967 968 case Stmt::DeclStmtClass: 969 // - static_assert-declarations 970 // - using-declarations, 971 // - using-directives, 972 // - typedef declarations and alias-declarations that do not define 973 // classes or enumerations, 974 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 975 return false; 976 return true; 977 978 case Stmt::ReturnStmtClass: 979 // - and exactly one return statement; 980 if (isa<CXXConstructorDecl>(Dcl)) { 981 // C++1y allows return statements in constexpr constructors. 982 if (!Cxx1yLoc.isValid()) 983 Cxx1yLoc = S->getLocStart(); 984 return true; 985 } 986 987 ReturnStmts.push_back(S->getLocStart()); 988 return true; 989 990 case Stmt::CompoundStmtClass: { 991 // C++1y allows compound-statements. 992 if (!Cxx1yLoc.isValid()) 993 Cxx1yLoc = S->getLocStart(); 994 995 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 996 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(), 997 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) { 998 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts, 999 Cxx1yLoc)) 1000 return false; 1001 } 1002 return true; 1003 } 1004 1005 case Stmt::AttributedStmtClass: 1006 if (!Cxx1yLoc.isValid()) 1007 Cxx1yLoc = S->getLocStart(); 1008 return true; 1009 1010 case Stmt::IfStmtClass: { 1011 // C++1y allows if-statements. 1012 if (!Cxx1yLoc.isValid()) 1013 Cxx1yLoc = S->getLocStart(); 1014 1015 IfStmt *If = cast<IfStmt>(S); 1016 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1017 Cxx1yLoc)) 1018 return false; 1019 if (If->getElse() && 1020 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1021 Cxx1yLoc)) 1022 return false; 1023 return true; 1024 } 1025 1026 case Stmt::WhileStmtClass: 1027 case Stmt::DoStmtClass: 1028 case Stmt::ForStmtClass: 1029 case Stmt::CXXForRangeStmtClass: 1030 case Stmt::ContinueStmtClass: 1031 // C++1y allows all of these. We don't allow them as extensions in C++11, 1032 // because they don't make sense without variable mutation. 1033 if (!SemaRef.getLangOpts().CPlusPlus1y) 1034 break; 1035 if (!Cxx1yLoc.isValid()) 1036 Cxx1yLoc = S->getLocStart(); 1037 for (Stmt::child_range Children = S->children(); Children; ++Children) 1038 if (*Children && 1039 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1040 Cxx1yLoc)) 1041 return false; 1042 return true; 1043 1044 case Stmt::SwitchStmtClass: 1045 case Stmt::CaseStmtClass: 1046 case Stmt::DefaultStmtClass: 1047 case Stmt::BreakStmtClass: 1048 // C++1y allows switch-statements, and since they don't need variable 1049 // mutation, we can reasonably allow them in C++11 as an extension. 1050 if (!Cxx1yLoc.isValid()) 1051 Cxx1yLoc = S->getLocStart(); 1052 for (Stmt::child_range Children = S->children(); Children; ++Children) 1053 if (*Children && 1054 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1055 Cxx1yLoc)) 1056 return false; 1057 return true; 1058 1059 default: 1060 if (!isa<Expr>(S)) 1061 break; 1062 1063 // C++1y allows expression-statements. 1064 if (!Cxx1yLoc.isValid()) 1065 Cxx1yLoc = S->getLocStart(); 1066 return true; 1067 } 1068 1069 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1070 << isa<CXXConstructorDecl>(Dcl); 1071 return false; 1072 } 1073 1074 /// Check the body for the given constexpr function declaration only contains 1075 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1076 /// 1077 /// \return true if the body is OK, false if we have diagnosed a problem. 1078 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1079 if (isa<CXXTryStmt>(Body)) { 1080 // C++11 [dcl.constexpr]p3: 1081 // The definition of a constexpr function shall satisfy the following 1082 // constraints: [...] 1083 // - its function-body shall be = delete, = default, or a 1084 // compound-statement 1085 // 1086 // C++11 [dcl.constexpr]p4: 1087 // In the definition of a constexpr constructor, [...] 1088 // - its function-body shall not be a function-try-block; 1089 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1090 << isa<CXXConstructorDecl>(Dcl); 1091 return false; 1092 } 1093 1094 SmallVector<SourceLocation, 4> ReturnStmts; 1095 1096 // - its function-body shall be [...] a compound-statement that contains only 1097 // [... list of cases ...] 1098 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1099 SourceLocation Cxx1yLoc; 1100 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 1101 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 1102 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc)) 1103 return false; 1104 } 1105 1106 if (Cxx1yLoc.isValid()) 1107 Diag(Cxx1yLoc, 1108 getLangOpts().CPlusPlus1y 1109 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1110 : diag::ext_constexpr_body_invalid_stmt) 1111 << isa<CXXConstructorDecl>(Dcl); 1112 1113 if (const CXXConstructorDecl *Constructor 1114 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1115 const CXXRecordDecl *RD = Constructor->getParent(); 1116 // DR1359: 1117 // - every non-variant non-static data member and base class sub-object 1118 // shall be initialized; 1119 // - if the class is a non-empty union, or for each non-empty anonymous 1120 // union member of a non-union class, exactly one non-static data member 1121 // shall be initialized; 1122 if (RD->isUnion()) { 1123 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 1124 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1125 return false; 1126 } 1127 } else if (!Constructor->isDependentContext() && 1128 !Constructor->isDelegatingConstructor()) { 1129 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1130 1131 // Skip detailed checking if we have enough initializers, and we would 1132 // allow at most one initializer per member. 1133 bool AnyAnonStructUnionMembers = false; 1134 unsigned Fields = 0; 1135 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1136 E = RD->field_end(); I != E; ++I, ++Fields) { 1137 if (I->isAnonymousStructOrUnion()) { 1138 AnyAnonStructUnionMembers = true; 1139 break; 1140 } 1141 } 1142 if (AnyAnonStructUnionMembers || 1143 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1144 // Check initialization of non-static data members. Base classes are 1145 // always initialized so do not need to be checked. Dependent bases 1146 // might not have initializers in the member initializer list. 1147 llvm::SmallSet<Decl*, 16> Inits; 1148 for (CXXConstructorDecl::init_const_iterator 1149 I = Constructor->init_begin(), E = Constructor->init_end(); 1150 I != E; ++I) { 1151 if (FieldDecl *FD = (*I)->getMember()) 1152 Inits.insert(FD); 1153 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 1154 Inits.insert(ID->chain_begin(), ID->chain_end()); 1155 } 1156 1157 bool Diagnosed = false; 1158 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1159 E = RD->field_end(); I != E; ++I) 1160 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 1161 if (Diagnosed) 1162 return false; 1163 } 1164 } 1165 } else { 1166 if (ReturnStmts.empty()) { 1167 // C++1y doesn't require constexpr functions to contain a 'return' 1168 // statement. We still do, unless the return type is void, because 1169 // otherwise if there's no return statement, the function cannot 1170 // be used in a core constant expression. 1171 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType(); 1172 Diag(Dcl->getLocation(), 1173 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1174 : diag::err_constexpr_body_no_return); 1175 return OK; 1176 } 1177 if (ReturnStmts.size() > 1) { 1178 Diag(ReturnStmts.back(), 1179 getLangOpts().CPlusPlus1y 1180 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1181 : diag::ext_constexpr_body_multiple_return); 1182 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1183 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1184 } 1185 } 1186 1187 // C++11 [dcl.constexpr]p5: 1188 // if no function argument values exist such that the function invocation 1189 // substitution would produce a constant expression, the program is 1190 // ill-formed; no diagnostic required. 1191 // C++11 [dcl.constexpr]p3: 1192 // - every constructor call and implicit conversion used in initializing the 1193 // return value shall be one of those allowed in a constant expression. 1194 // C++11 [dcl.constexpr]p4: 1195 // - every constructor involved in initializing non-static data members and 1196 // base class sub-objects shall be a constexpr constructor. 1197 SmallVector<PartialDiagnosticAt, 8> Diags; 1198 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1199 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1200 << isa<CXXConstructorDecl>(Dcl); 1201 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1202 Diag(Diags[I].first, Diags[I].second); 1203 // Don't return false here: we allow this for compatibility in 1204 // system headers. 1205 } 1206 1207 return true; 1208 } 1209 1210 /// isCurrentClassName - Determine whether the identifier II is the 1211 /// name of the class type currently being defined. In the case of 1212 /// nested classes, this will only return true if II is the name of 1213 /// the innermost class. 1214 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1215 const CXXScopeSpec *SS) { 1216 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1217 1218 CXXRecordDecl *CurDecl; 1219 if (SS && SS->isSet() && !SS->isInvalid()) { 1220 DeclContext *DC = computeDeclContext(*SS, true); 1221 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1222 } else 1223 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1224 1225 if (CurDecl && CurDecl->getIdentifier()) 1226 return &II == CurDecl->getIdentifier(); 1227 return false; 1228 } 1229 1230 /// \brief Determine whether the identifier II is a typo for the name of 1231 /// the class type currently being defined. If so, update it to the identifier 1232 /// that should have been used. 1233 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1234 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1235 1236 if (!getLangOpts().SpellChecking) 1237 return false; 1238 1239 CXXRecordDecl *CurDecl; 1240 if (SS && SS->isSet() && !SS->isInvalid()) { 1241 DeclContext *DC = computeDeclContext(*SS, true); 1242 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1243 } else 1244 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1245 1246 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1247 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1248 < II->getLength()) { 1249 II = CurDecl->getIdentifier(); 1250 return true; 1251 } 1252 1253 return false; 1254 } 1255 1256 /// \brief Determine whether the given class is a base class of the given 1257 /// class, including looking at dependent bases. 1258 static bool findCircularInheritance(const CXXRecordDecl *Class, 1259 const CXXRecordDecl *Current) { 1260 SmallVector<const CXXRecordDecl*, 8> Queue; 1261 1262 Class = Class->getCanonicalDecl(); 1263 while (true) { 1264 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(), 1265 E = Current->bases_end(); 1266 I != E; ++I) { 1267 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 1268 if (!Base) 1269 continue; 1270 1271 Base = Base->getDefinition(); 1272 if (!Base) 1273 continue; 1274 1275 if (Base->getCanonicalDecl() == Class) 1276 return true; 1277 1278 Queue.push_back(Base); 1279 } 1280 1281 if (Queue.empty()) 1282 return false; 1283 1284 Current = Queue.pop_back_val(); 1285 } 1286 1287 return false; 1288 } 1289 1290 /// \brief Check the validity of a C++ base class specifier. 1291 /// 1292 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1293 /// and returns NULL otherwise. 1294 CXXBaseSpecifier * 1295 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1296 SourceRange SpecifierRange, 1297 bool Virtual, AccessSpecifier Access, 1298 TypeSourceInfo *TInfo, 1299 SourceLocation EllipsisLoc) { 1300 QualType BaseType = TInfo->getType(); 1301 1302 // C++ [class.union]p1: 1303 // A union shall not have base classes. 1304 if (Class->isUnion()) { 1305 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1306 << SpecifierRange; 1307 return 0; 1308 } 1309 1310 if (EllipsisLoc.isValid() && 1311 !TInfo->getType()->containsUnexpandedParameterPack()) { 1312 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1313 << TInfo->getTypeLoc().getSourceRange(); 1314 EllipsisLoc = SourceLocation(); 1315 } 1316 1317 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1318 1319 if (BaseType->isDependentType()) { 1320 // Make sure that we don't have circular inheritance among our dependent 1321 // bases. For non-dependent bases, the check for completeness below handles 1322 // this. 1323 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1324 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1325 ((BaseDecl = BaseDecl->getDefinition()) && 1326 findCircularInheritance(Class, BaseDecl))) { 1327 Diag(BaseLoc, diag::err_circular_inheritance) 1328 << BaseType << Context.getTypeDeclType(Class); 1329 1330 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1331 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1332 << BaseType; 1333 1334 return 0; 1335 } 1336 } 1337 1338 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1339 Class->getTagKind() == TTK_Class, 1340 Access, TInfo, EllipsisLoc); 1341 } 1342 1343 // Base specifiers must be record types. 1344 if (!BaseType->isRecordType()) { 1345 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1346 return 0; 1347 } 1348 1349 // C++ [class.union]p1: 1350 // A union shall not be used as a base class. 1351 if (BaseType->isUnionType()) { 1352 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1353 return 0; 1354 } 1355 1356 // C++ [class.derived]p2: 1357 // The class-name in a base-specifier shall not be an incompletely 1358 // defined class. 1359 if (RequireCompleteType(BaseLoc, BaseType, 1360 diag::err_incomplete_base_class, SpecifierRange)) { 1361 Class->setInvalidDecl(); 1362 return 0; 1363 } 1364 1365 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1366 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1367 assert(BaseDecl && "Record type has no declaration"); 1368 BaseDecl = BaseDecl->getDefinition(); 1369 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1370 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1371 assert(CXXBaseDecl && "Base type is not a C++ type"); 1372 1373 // C++ [class]p3: 1374 // If a class is marked final and it appears as a base-type-specifier in 1375 // base-clause, the program is ill-formed. 1376 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1377 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1378 << CXXBaseDecl->getDeclName() 1379 << FA->isSpelledAsSealed(); 1380 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1381 << CXXBaseDecl->getDeclName(); 1382 return 0; 1383 } 1384 1385 if (BaseDecl->isInvalidDecl()) 1386 Class->setInvalidDecl(); 1387 1388 // Create the base specifier. 1389 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1390 Class->getTagKind() == TTK_Class, 1391 Access, TInfo, EllipsisLoc); 1392 } 1393 1394 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1395 /// one entry in the base class list of a class specifier, for 1396 /// example: 1397 /// class foo : public bar, virtual private baz { 1398 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1399 BaseResult 1400 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1401 ParsedAttributes &Attributes, 1402 bool Virtual, AccessSpecifier Access, 1403 ParsedType basetype, SourceLocation BaseLoc, 1404 SourceLocation EllipsisLoc) { 1405 if (!classdecl) 1406 return true; 1407 1408 AdjustDeclIfTemplate(classdecl); 1409 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1410 if (!Class) 1411 return true; 1412 1413 // We do not support any C++11 attributes on base-specifiers yet. 1414 // Diagnose any attributes we see. 1415 if (!Attributes.empty()) { 1416 for (AttributeList *Attr = Attributes.getList(); Attr; 1417 Attr = Attr->getNext()) { 1418 if (Attr->isInvalid() || 1419 Attr->getKind() == AttributeList::IgnoredAttribute) 1420 continue; 1421 Diag(Attr->getLoc(), 1422 Attr->getKind() == AttributeList::UnknownAttribute 1423 ? diag::warn_unknown_attribute_ignored 1424 : diag::err_base_specifier_attribute) 1425 << Attr->getName(); 1426 } 1427 } 1428 1429 TypeSourceInfo *TInfo = 0; 1430 GetTypeFromParser(basetype, &TInfo); 1431 1432 if (EllipsisLoc.isInvalid() && 1433 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1434 UPPC_BaseType)) 1435 return true; 1436 1437 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1438 Virtual, Access, TInfo, 1439 EllipsisLoc)) 1440 return BaseSpec; 1441 else 1442 Class->setInvalidDecl(); 1443 1444 return true; 1445 } 1446 1447 /// \brief Performs the actual work of attaching the given base class 1448 /// specifiers to a C++ class. 1449 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1450 unsigned NumBases) { 1451 if (NumBases == 0) 1452 return false; 1453 1454 // Used to keep track of which base types we have already seen, so 1455 // that we can properly diagnose redundant direct base types. Note 1456 // that the key is always the unqualified canonical type of the base 1457 // class. 1458 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1459 1460 // Copy non-redundant base specifiers into permanent storage. 1461 unsigned NumGoodBases = 0; 1462 bool Invalid = false; 1463 for (unsigned idx = 0; idx < NumBases; ++idx) { 1464 QualType NewBaseType 1465 = Context.getCanonicalType(Bases[idx]->getType()); 1466 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1467 1468 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1469 if (KnownBase) { 1470 // C++ [class.mi]p3: 1471 // A class shall not be specified as a direct base class of a 1472 // derived class more than once. 1473 Diag(Bases[idx]->getLocStart(), 1474 diag::err_duplicate_base_class) 1475 << KnownBase->getType() 1476 << Bases[idx]->getSourceRange(); 1477 1478 // Delete the duplicate base class specifier; we're going to 1479 // overwrite its pointer later. 1480 Context.Deallocate(Bases[idx]); 1481 1482 Invalid = true; 1483 } else { 1484 // Okay, add this new base class. 1485 KnownBase = Bases[idx]; 1486 Bases[NumGoodBases++] = Bases[idx]; 1487 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1488 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1489 if (Class->isInterface() && 1490 (!RD->isInterface() || 1491 KnownBase->getAccessSpecifier() != AS_public)) { 1492 // The Microsoft extension __interface does not permit bases that 1493 // are not themselves public interfaces. 1494 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1495 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1496 << RD->getSourceRange(); 1497 Invalid = true; 1498 } 1499 if (RD->hasAttr<WeakAttr>()) 1500 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1501 } 1502 } 1503 } 1504 1505 // Attach the remaining base class specifiers to the derived class. 1506 Class->setBases(Bases, NumGoodBases); 1507 1508 // Delete the remaining (good) base class specifiers, since their 1509 // data has been copied into the CXXRecordDecl. 1510 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1511 Context.Deallocate(Bases[idx]); 1512 1513 return Invalid; 1514 } 1515 1516 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1517 /// class, after checking whether there are any duplicate base 1518 /// classes. 1519 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1520 unsigned NumBases) { 1521 if (!ClassDecl || !Bases || !NumBases) 1522 return; 1523 1524 AdjustDeclIfTemplate(ClassDecl); 1525 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1526 } 1527 1528 /// \brief Determine whether the type \p Derived is a C++ class that is 1529 /// derived from the type \p Base. 1530 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1531 if (!getLangOpts().CPlusPlus) 1532 return false; 1533 1534 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1535 if (!DerivedRD) 1536 return false; 1537 1538 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1539 if (!BaseRD) 1540 return false; 1541 1542 // If either the base or the derived type is invalid, don't try to 1543 // check whether one is derived from the other. 1544 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1545 return false; 1546 1547 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1548 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1549 } 1550 1551 /// \brief Determine whether the type \p Derived is a C++ class that is 1552 /// derived from the type \p Base. 1553 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1554 if (!getLangOpts().CPlusPlus) 1555 return false; 1556 1557 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1558 if (!DerivedRD) 1559 return false; 1560 1561 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1562 if (!BaseRD) 1563 return false; 1564 1565 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1566 } 1567 1568 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1569 CXXCastPath &BasePathArray) { 1570 assert(BasePathArray.empty() && "Base path array must be empty!"); 1571 assert(Paths.isRecordingPaths() && "Must record paths!"); 1572 1573 const CXXBasePath &Path = Paths.front(); 1574 1575 // We first go backward and check if we have a virtual base. 1576 // FIXME: It would be better if CXXBasePath had the base specifier for 1577 // the nearest virtual base. 1578 unsigned Start = 0; 1579 for (unsigned I = Path.size(); I != 0; --I) { 1580 if (Path[I - 1].Base->isVirtual()) { 1581 Start = I - 1; 1582 break; 1583 } 1584 } 1585 1586 // Now add all bases. 1587 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1588 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1589 } 1590 1591 /// \brief Determine whether the given base path includes a virtual 1592 /// base class. 1593 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1594 for (CXXCastPath::const_iterator B = BasePath.begin(), 1595 BEnd = BasePath.end(); 1596 B != BEnd; ++B) 1597 if ((*B)->isVirtual()) 1598 return true; 1599 1600 return false; 1601 } 1602 1603 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1604 /// conversion (where Derived and Base are class types) is 1605 /// well-formed, meaning that the conversion is unambiguous (and 1606 /// that all of the base classes are accessible). Returns true 1607 /// and emits a diagnostic if the code is ill-formed, returns false 1608 /// otherwise. Loc is the location where this routine should point to 1609 /// if there is an error, and Range is the source range to highlight 1610 /// if there is an error. 1611 bool 1612 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1613 unsigned InaccessibleBaseID, 1614 unsigned AmbigiousBaseConvID, 1615 SourceLocation Loc, SourceRange Range, 1616 DeclarationName Name, 1617 CXXCastPath *BasePath) { 1618 // First, determine whether the path from Derived to Base is 1619 // ambiguous. This is slightly more expensive than checking whether 1620 // the Derived to Base conversion exists, because here we need to 1621 // explore multiple paths to determine if there is an ambiguity. 1622 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1623 /*DetectVirtual=*/false); 1624 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1625 assert(DerivationOkay && 1626 "Can only be used with a derived-to-base conversion"); 1627 (void)DerivationOkay; 1628 1629 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1630 if (InaccessibleBaseID) { 1631 // Check that the base class can be accessed. 1632 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1633 InaccessibleBaseID)) { 1634 case AR_inaccessible: 1635 return true; 1636 case AR_accessible: 1637 case AR_dependent: 1638 case AR_delayed: 1639 break; 1640 } 1641 } 1642 1643 // Build a base path if necessary. 1644 if (BasePath) 1645 BuildBasePathArray(Paths, *BasePath); 1646 return false; 1647 } 1648 1649 if (AmbigiousBaseConvID) { 1650 // We know that the derived-to-base conversion is ambiguous, and 1651 // we're going to produce a diagnostic. Perform the derived-to-base 1652 // search just one more time to compute all of the possible paths so 1653 // that we can print them out. This is more expensive than any of 1654 // the previous derived-to-base checks we've done, but at this point 1655 // performance isn't as much of an issue. 1656 Paths.clear(); 1657 Paths.setRecordingPaths(true); 1658 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1659 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1660 (void)StillOkay; 1661 1662 // Build up a textual representation of the ambiguous paths, e.g., 1663 // D -> B -> A, that will be used to illustrate the ambiguous 1664 // conversions in the diagnostic. We only print one of the paths 1665 // to each base class subobject. 1666 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1667 1668 Diag(Loc, AmbigiousBaseConvID) 1669 << Derived << Base << PathDisplayStr << Range << Name; 1670 } 1671 return true; 1672 } 1673 1674 bool 1675 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1676 SourceLocation Loc, SourceRange Range, 1677 CXXCastPath *BasePath, 1678 bool IgnoreAccess) { 1679 return CheckDerivedToBaseConversion(Derived, Base, 1680 IgnoreAccess ? 0 1681 : diag::err_upcast_to_inaccessible_base, 1682 diag::err_ambiguous_derived_to_base_conv, 1683 Loc, Range, DeclarationName(), 1684 BasePath); 1685 } 1686 1687 1688 /// @brief Builds a string representing ambiguous paths from a 1689 /// specific derived class to different subobjects of the same base 1690 /// class. 1691 /// 1692 /// This function builds a string that can be used in error messages 1693 /// to show the different paths that one can take through the 1694 /// inheritance hierarchy to go from the derived class to different 1695 /// subobjects of a base class. The result looks something like this: 1696 /// @code 1697 /// struct D -> struct B -> struct A 1698 /// struct D -> struct C -> struct A 1699 /// @endcode 1700 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1701 std::string PathDisplayStr; 1702 std::set<unsigned> DisplayedPaths; 1703 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1704 Path != Paths.end(); ++Path) { 1705 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1706 // We haven't displayed a path to this particular base 1707 // class subobject yet. 1708 PathDisplayStr += "\n "; 1709 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1710 for (CXXBasePath::const_iterator Element = Path->begin(); 1711 Element != Path->end(); ++Element) 1712 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1713 } 1714 } 1715 1716 return PathDisplayStr; 1717 } 1718 1719 //===----------------------------------------------------------------------===// 1720 // C++ class member Handling 1721 //===----------------------------------------------------------------------===// 1722 1723 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1724 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1725 SourceLocation ASLoc, 1726 SourceLocation ColonLoc, 1727 AttributeList *Attrs) { 1728 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1729 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1730 ASLoc, ColonLoc); 1731 CurContext->addHiddenDecl(ASDecl); 1732 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1733 } 1734 1735 /// CheckOverrideControl - Check C++11 override control semantics. 1736 void Sema::CheckOverrideControl(NamedDecl *D) { 1737 if (D->isInvalidDecl()) 1738 return; 1739 1740 // We only care about "override" and "final" declarations. 1741 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1742 return; 1743 1744 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1745 1746 // We can't check dependent instance methods. 1747 if (MD && MD->isInstance() && 1748 (MD->getParent()->hasAnyDependentBases() || 1749 MD->getType()->isDependentType())) 1750 return; 1751 1752 if (MD && !MD->isVirtual()) { 1753 // If we have a non-virtual method, check if if hides a virtual method. 1754 // (In that case, it's most likely the method has the wrong type.) 1755 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1756 FindHiddenVirtualMethods(MD, OverloadedMethods); 1757 1758 if (!OverloadedMethods.empty()) { 1759 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1760 Diag(OA->getLocation(), 1761 diag::override_keyword_hides_virtual_member_function) 1762 << "override" << (OverloadedMethods.size() > 1); 1763 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1764 Diag(FA->getLocation(), 1765 diag::override_keyword_hides_virtual_member_function) 1766 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1767 << (OverloadedMethods.size() > 1); 1768 } 1769 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1770 MD->setInvalidDecl(); 1771 return; 1772 } 1773 // Fall through into the general case diagnostic. 1774 // FIXME: We might want to attempt typo correction here. 1775 } 1776 1777 if (!MD || !MD->isVirtual()) { 1778 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1779 Diag(OA->getLocation(), 1780 diag::override_keyword_only_allowed_on_virtual_member_functions) 1781 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1782 D->dropAttr<OverrideAttr>(); 1783 } 1784 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1785 Diag(FA->getLocation(), 1786 diag::override_keyword_only_allowed_on_virtual_member_functions) 1787 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1788 << FixItHint::CreateRemoval(FA->getLocation()); 1789 D->dropAttr<FinalAttr>(); 1790 } 1791 return; 1792 } 1793 1794 // C++11 [class.virtual]p5: 1795 // If a virtual function is marked with the virt-specifier override and 1796 // does not override a member function of a base class, the program is 1797 // ill-formed. 1798 bool HasOverriddenMethods = 1799 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1800 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1801 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1802 << MD->getDeclName(); 1803 } 1804 1805 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1806 /// function overrides a virtual member function marked 'final', according to 1807 /// C++11 [class.virtual]p4. 1808 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1809 const CXXMethodDecl *Old) { 1810 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1811 if (!FA) 1812 return false; 1813 1814 Diag(New->getLocation(), diag::err_final_function_overridden) 1815 << New->getDeclName() 1816 << FA->isSpelledAsSealed(); 1817 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1818 return true; 1819 } 1820 1821 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1822 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1823 // FIXME: Destruction of ObjC lifetime types has side-effects. 1824 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1825 return !RD->isCompleteDefinition() || 1826 !RD->hasTrivialDefaultConstructor() || 1827 !RD->hasTrivialDestructor(); 1828 return false; 1829 } 1830 1831 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1832 for (AttributeList* it = list; it != 0; it = it->getNext()) 1833 if (it->isDeclspecPropertyAttribute()) 1834 return it; 1835 return 0; 1836 } 1837 1838 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1839 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1840 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1841 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1842 /// present (but parsing it has been deferred). 1843 NamedDecl * 1844 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1845 MultiTemplateParamsArg TemplateParameterLists, 1846 Expr *BW, const VirtSpecifiers &VS, 1847 InClassInitStyle InitStyle) { 1848 const DeclSpec &DS = D.getDeclSpec(); 1849 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1850 DeclarationName Name = NameInfo.getName(); 1851 SourceLocation Loc = NameInfo.getLoc(); 1852 1853 // For anonymous bitfields, the location should point to the type. 1854 if (Loc.isInvalid()) 1855 Loc = D.getLocStart(); 1856 1857 Expr *BitWidth = static_cast<Expr*>(BW); 1858 1859 assert(isa<CXXRecordDecl>(CurContext)); 1860 assert(!DS.isFriendSpecified()); 1861 1862 bool isFunc = D.isDeclarationOfFunction(); 1863 1864 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1865 // The Microsoft extension __interface only permits public member functions 1866 // and prohibits constructors, destructors, operators, non-public member 1867 // functions, static methods and data members. 1868 unsigned InvalidDecl; 1869 bool ShowDeclName = true; 1870 if (!isFunc) 1871 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1872 else if (AS != AS_public) 1873 InvalidDecl = 2; 1874 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1875 InvalidDecl = 3; 1876 else switch (Name.getNameKind()) { 1877 case DeclarationName::CXXConstructorName: 1878 InvalidDecl = 4; 1879 ShowDeclName = false; 1880 break; 1881 1882 case DeclarationName::CXXDestructorName: 1883 InvalidDecl = 5; 1884 ShowDeclName = false; 1885 break; 1886 1887 case DeclarationName::CXXOperatorName: 1888 case DeclarationName::CXXConversionFunctionName: 1889 InvalidDecl = 6; 1890 break; 1891 1892 default: 1893 InvalidDecl = 0; 1894 break; 1895 } 1896 1897 if (InvalidDecl) { 1898 if (ShowDeclName) 1899 Diag(Loc, diag::err_invalid_member_in_interface) 1900 << (InvalidDecl-1) << Name; 1901 else 1902 Diag(Loc, diag::err_invalid_member_in_interface) 1903 << (InvalidDecl-1) << ""; 1904 return 0; 1905 } 1906 } 1907 1908 // C++ 9.2p6: A member shall not be declared to have automatic storage 1909 // duration (auto, register) or with the extern storage-class-specifier. 1910 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1911 // data members and cannot be applied to names declared const or static, 1912 // and cannot be applied to reference members. 1913 switch (DS.getStorageClassSpec()) { 1914 case DeclSpec::SCS_unspecified: 1915 case DeclSpec::SCS_typedef: 1916 case DeclSpec::SCS_static: 1917 break; 1918 case DeclSpec::SCS_mutable: 1919 if (isFunc) { 1920 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1921 1922 // FIXME: It would be nicer if the keyword was ignored only for this 1923 // declarator. Otherwise we could get follow-up errors. 1924 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1925 } 1926 break; 1927 default: 1928 Diag(DS.getStorageClassSpecLoc(), 1929 diag::err_storageclass_invalid_for_member); 1930 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1931 break; 1932 } 1933 1934 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1935 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1936 !isFunc); 1937 1938 if (DS.isConstexprSpecified() && isInstField) { 1939 SemaDiagnosticBuilder B = 1940 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 1941 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 1942 if (InitStyle == ICIS_NoInit) { 1943 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const"); 1944 D.getMutableDeclSpec().ClearConstexprSpec(); 1945 const char *PrevSpec; 1946 unsigned DiagID; 1947 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc, 1948 PrevSpec, DiagID, getLangOpts()); 1949 (void)Failed; 1950 assert(!Failed && "Making a constexpr member const shouldn't fail"); 1951 } else { 1952 B << 1; 1953 const char *PrevSpec; 1954 unsigned DiagID; 1955 if (D.getMutableDeclSpec().SetStorageClassSpec( 1956 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) { 1957 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 1958 "This is the only DeclSpec that should fail to be applied"); 1959 B << 1; 1960 } else { 1961 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 1962 isInstField = false; 1963 } 1964 } 1965 } 1966 1967 NamedDecl *Member; 1968 if (isInstField) { 1969 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1970 1971 // Data members must have identifiers for names. 1972 if (!Name.isIdentifier()) { 1973 Diag(Loc, diag::err_bad_variable_name) 1974 << Name; 1975 return 0; 1976 } 1977 1978 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1979 1980 // Member field could not be with "template" keyword. 1981 // So TemplateParameterLists should be empty in this case. 1982 if (TemplateParameterLists.size()) { 1983 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 1984 if (TemplateParams->size()) { 1985 // There is no such thing as a member field template. 1986 Diag(D.getIdentifierLoc(), diag::err_template_member) 1987 << II 1988 << SourceRange(TemplateParams->getTemplateLoc(), 1989 TemplateParams->getRAngleLoc()); 1990 } else { 1991 // There is an extraneous 'template<>' for this member. 1992 Diag(TemplateParams->getTemplateLoc(), 1993 diag::err_template_member_noparams) 1994 << II 1995 << SourceRange(TemplateParams->getTemplateLoc(), 1996 TemplateParams->getRAngleLoc()); 1997 } 1998 return 0; 1999 } 2000 2001 if (SS.isSet() && !SS.isInvalid()) { 2002 // The user provided a superfluous scope specifier inside a class 2003 // definition: 2004 // 2005 // class X { 2006 // int X::member; 2007 // }; 2008 if (DeclContext *DC = computeDeclContext(SS, false)) 2009 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2010 else 2011 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2012 << Name << SS.getRange(); 2013 2014 SS.clear(); 2015 } 2016 2017 AttributeList *MSPropertyAttr = 2018 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2019 if (MSPropertyAttr) { 2020 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2021 BitWidth, InitStyle, AS, MSPropertyAttr); 2022 if (!Member) 2023 return 0; 2024 isInstField = false; 2025 } else { 2026 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2027 BitWidth, InitStyle, AS); 2028 assert(Member && "HandleField never returns null"); 2029 } 2030 } else { 2031 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2032 2033 Member = HandleDeclarator(S, D, TemplateParameterLists); 2034 if (!Member) 2035 return 0; 2036 2037 // Non-instance-fields can't have a bitfield. 2038 if (BitWidth) { 2039 if (Member->isInvalidDecl()) { 2040 // don't emit another diagnostic. 2041 } else if (isa<VarDecl>(Member)) { 2042 // C++ 9.6p3: A bit-field shall not be a static member. 2043 // "static member 'A' cannot be a bit-field" 2044 Diag(Loc, diag::err_static_not_bitfield) 2045 << Name << BitWidth->getSourceRange(); 2046 } else if (isa<TypedefDecl>(Member)) { 2047 // "typedef member 'x' cannot be a bit-field" 2048 Diag(Loc, diag::err_typedef_not_bitfield) 2049 << Name << BitWidth->getSourceRange(); 2050 } else { 2051 // A function typedef ("typedef int f(); f a;"). 2052 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2053 Diag(Loc, diag::err_not_integral_type_bitfield) 2054 << Name << cast<ValueDecl>(Member)->getType() 2055 << BitWidth->getSourceRange(); 2056 } 2057 2058 BitWidth = 0; 2059 Member->setInvalidDecl(); 2060 } 2061 2062 Member->setAccess(AS); 2063 2064 // If we have declared a member function template or static data member 2065 // template, set the access of the templated declaration as well. 2066 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2067 FunTmpl->getTemplatedDecl()->setAccess(AS); 2068 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2069 VarTmpl->getTemplatedDecl()->setAccess(AS); 2070 } 2071 2072 if (VS.isOverrideSpecified()) 2073 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 2074 if (VS.isFinalSpecified()) 2075 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2076 VS.isFinalSpelledSealed())); 2077 2078 if (VS.getLastLocation().isValid()) { 2079 // Update the end location of a method that has a virt-specifiers. 2080 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2081 MD->setRangeEnd(VS.getLastLocation()); 2082 } 2083 2084 CheckOverrideControl(Member); 2085 2086 assert((Name || isInstField) && "No identifier for non-field ?"); 2087 2088 if (isInstField) { 2089 FieldDecl *FD = cast<FieldDecl>(Member); 2090 FieldCollector->Add(FD); 2091 2092 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 2093 FD->getLocation()) 2094 != DiagnosticsEngine::Ignored) { 2095 // Remember all explicit private FieldDecls that have a name, no side 2096 // effects and are not part of a dependent type declaration. 2097 if (!FD->isImplicit() && FD->getDeclName() && 2098 FD->getAccess() == AS_private && 2099 !FD->hasAttr<UnusedAttr>() && 2100 !FD->getParent()->isDependentContext() && 2101 !InitializationHasSideEffects(*FD)) 2102 UnusedPrivateFields.insert(FD); 2103 } 2104 } 2105 2106 return Member; 2107 } 2108 2109 namespace { 2110 class UninitializedFieldVisitor 2111 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2112 Sema &S; 2113 // If VD is null, this visitor will only update the Decls set. 2114 ValueDecl *VD; 2115 bool isReferenceType; 2116 // List of Decls to generate a warning on. 2117 llvm::SmallPtrSet<ValueDecl*, 4> &Decls; 2118 bool WarnOnSelfReference; 2119 // If non-null, add a note to the warning pointing back to the constructor. 2120 const CXXConstructorDecl *Constructor; 2121 public: 2122 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2123 UninitializedFieldVisitor(Sema &S, ValueDecl *VD, 2124 llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2125 bool WarnOnSelfReference, 2126 const CXXConstructorDecl *Constructor) 2127 : Inherited(S.Context), S(S), VD(VD), isReferenceType(false), Decls(Decls), 2128 WarnOnSelfReference(WarnOnSelfReference), Constructor(Constructor) { 2129 // When VD is null, this visitor is used to detect initialization of other 2130 // fields. 2131 if (VD) { 2132 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD)) 2133 this->VD = IFD->getAnonField(); 2134 else 2135 this->VD = VD; 2136 isReferenceType = this->VD->getType()->isReferenceType(); 2137 } 2138 } 2139 2140 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) { 2141 if (!VD) 2142 return; 2143 2144 if (CheckReferenceOnly && !isReferenceType) 2145 return; 2146 2147 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2148 return; 2149 2150 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2151 // or union. 2152 MemberExpr *FieldME = ME; 2153 2154 Expr *Base = ME; 2155 while (isa<MemberExpr>(Base)) { 2156 ME = cast<MemberExpr>(Base); 2157 2158 if (isa<VarDecl>(ME->getMemberDecl())) 2159 return; 2160 2161 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2162 if (!FD->isAnonymousStructOrUnion()) 2163 FieldME = ME; 2164 2165 Base = ME->getBase(); 2166 } 2167 2168 if (!isa<CXXThisExpr>(Base)) 2169 return; 2170 2171 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2172 2173 if (VD == FoundVD) { 2174 if (!WarnOnSelfReference) 2175 return; 2176 2177 unsigned diag = isReferenceType 2178 ? diag::warn_reference_field_is_uninit 2179 : diag::warn_field_is_uninit; 2180 S.Diag(FieldME->getExprLoc(), diag) << VD; 2181 if (Constructor) 2182 S.Diag(Constructor->getLocation(), 2183 diag::note_uninit_in_this_constructor); 2184 return; 2185 } 2186 2187 if (CheckReferenceOnly) 2188 return; 2189 2190 if (Decls.count(FoundVD)) { 2191 S.Diag(FieldME->getExprLoc(), diag::warn_field_is_uninit) << FoundVD; 2192 if (Constructor) 2193 S.Diag(Constructor->getLocation(), 2194 diag::note_uninit_in_this_constructor); 2195 2196 } 2197 } 2198 2199 void HandleValue(Expr *E) { 2200 if (!VD) 2201 return; 2202 2203 E = E->IgnoreParens(); 2204 2205 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2206 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2207 return; 2208 } 2209 2210 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2211 HandleValue(CO->getTrueExpr()); 2212 HandleValue(CO->getFalseExpr()); 2213 return; 2214 } 2215 2216 if (BinaryConditionalOperator *BCO = 2217 dyn_cast<BinaryConditionalOperator>(E)) { 2218 HandleValue(BCO->getCommon()); 2219 HandleValue(BCO->getFalseExpr()); 2220 return; 2221 } 2222 2223 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2224 switch (BO->getOpcode()) { 2225 default: 2226 return; 2227 case(BO_PtrMemD): 2228 case(BO_PtrMemI): 2229 HandleValue(BO->getLHS()); 2230 return; 2231 case(BO_Comma): 2232 HandleValue(BO->getRHS()); 2233 return; 2234 } 2235 } 2236 } 2237 2238 void VisitMemberExpr(MemberExpr *ME) { 2239 HandleMemberExpr(ME, true /*CheckReferenceOnly*/); 2240 2241 Inherited::VisitMemberExpr(ME); 2242 } 2243 2244 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2245 if (E->getCastKind() == CK_LValueToRValue) 2246 HandleValue(E->getSubExpr()); 2247 2248 Inherited::VisitImplicitCastExpr(E); 2249 } 2250 2251 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2252 if (E->getConstructor()->isCopyConstructor()) 2253 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0))) 2254 if (ICE->getCastKind() == CK_NoOp) 2255 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr())) 2256 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2257 2258 Inherited::VisitCXXConstructExpr(E); 2259 } 2260 2261 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2262 Expr *Callee = E->getCallee(); 2263 if (isa<MemberExpr>(Callee)) 2264 HandleValue(Callee); 2265 2266 Inherited::VisitCXXMemberCallExpr(E); 2267 } 2268 2269 void VisitBinaryOperator(BinaryOperator *E) { 2270 // If a field assignment is detected, remove the field from the 2271 // uninitiailized field set. 2272 if (E->getOpcode() == BO_Assign) 2273 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2274 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2275 Decls.erase(FD); 2276 2277 Inherited::VisitBinaryOperator(E); 2278 } 2279 }; 2280 static void CheckInitExprContainsUninitializedFields( 2281 Sema &S, Expr *E, ValueDecl *VD, llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2282 bool WarnOnSelfReference, const CXXConstructorDecl *Constructor = 0) { 2283 if (Decls.size() == 0 && !WarnOnSelfReference) 2284 return; 2285 2286 if (E) 2287 UninitializedFieldVisitor(S, VD, Decls, WarnOnSelfReference, Constructor) 2288 .Visit(E); 2289 } 2290 } // namespace 2291 2292 /// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 2293 /// in-class initializer for a non-static C++ class member, and after 2294 /// instantiating an in-class initializer in a class template. Such actions 2295 /// are deferred until the class is complete. 2296 void 2297 Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc, 2298 Expr *InitExpr) { 2299 FieldDecl *FD = cast<FieldDecl>(D); 2300 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2301 "must set init style when field is created"); 2302 2303 if (!InitExpr) { 2304 FD->setInvalidDecl(); 2305 FD->removeInClassInitializer(); 2306 return; 2307 } 2308 2309 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2310 FD->setInvalidDecl(); 2311 FD->removeInClassInitializer(); 2312 return; 2313 } 2314 2315 ExprResult Init = InitExpr; 2316 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2317 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2318 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2319 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2320 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2321 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2322 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2323 if (Init.isInvalid()) { 2324 FD->setInvalidDecl(); 2325 return; 2326 } 2327 } 2328 2329 // C++11 [class.base.init]p7: 2330 // The initialization of each base and member constitutes a 2331 // full-expression. 2332 Init = ActOnFinishFullExpr(Init.take(), InitLoc); 2333 if (Init.isInvalid()) { 2334 FD->setInvalidDecl(); 2335 return; 2336 } 2337 2338 InitExpr = Init.release(); 2339 2340 FD->setInClassInitializer(InitExpr); 2341 } 2342 2343 /// \brief Find the direct and/or virtual base specifiers that 2344 /// correspond to the given base type, for use in base initialization 2345 /// within a constructor. 2346 static bool FindBaseInitializer(Sema &SemaRef, 2347 CXXRecordDecl *ClassDecl, 2348 QualType BaseType, 2349 const CXXBaseSpecifier *&DirectBaseSpec, 2350 const CXXBaseSpecifier *&VirtualBaseSpec) { 2351 // First, check for a direct base class. 2352 DirectBaseSpec = 0; 2353 for (CXXRecordDecl::base_class_const_iterator Base 2354 = ClassDecl->bases_begin(); 2355 Base != ClassDecl->bases_end(); ++Base) { 2356 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 2357 // We found a direct base of this type. That's what we're 2358 // initializing. 2359 DirectBaseSpec = &*Base; 2360 break; 2361 } 2362 } 2363 2364 // Check for a virtual base class. 2365 // FIXME: We might be able to short-circuit this if we know in advance that 2366 // there are no virtual bases. 2367 VirtualBaseSpec = 0; 2368 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2369 // We haven't found a base yet; search the class hierarchy for a 2370 // virtual base class. 2371 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2372 /*DetectVirtual=*/false); 2373 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2374 BaseType, Paths)) { 2375 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2376 Path != Paths.end(); ++Path) { 2377 if (Path->back().Base->isVirtual()) { 2378 VirtualBaseSpec = Path->back().Base; 2379 break; 2380 } 2381 } 2382 } 2383 } 2384 2385 return DirectBaseSpec || VirtualBaseSpec; 2386 } 2387 2388 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2389 MemInitResult 2390 Sema::ActOnMemInitializer(Decl *ConstructorD, 2391 Scope *S, 2392 CXXScopeSpec &SS, 2393 IdentifierInfo *MemberOrBase, 2394 ParsedType TemplateTypeTy, 2395 const DeclSpec &DS, 2396 SourceLocation IdLoc, 2397 Expr *InitList, 2398 SourceLocation EllipsisLoc) { 2399 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2400 DS, IdLoc, InitList, 2401 EllipsisLoc); 2402 } 2403 2404 /// \brief Handle a C++ member initializer using parentheses syntax. 2405 MemInitResult 2406 Sema::ActOnMemInitializer(Decl *ConstructorD, 2407 Scope *S, 2408 CXXScopeSpec &SS, 2409 IdentifierInfo *MemberOrBase, 2410 ParsedType TemplateTypeTy, 2411 const DeclSpec &DS, 2412 SourceLocation IdLoc, 2413 SourceLocation LParenLoc, 2414 ArrayRef<Expr *> Args, 2415 SourceLocation RParenLoc, 2416 SourceLocation EllipsisLoc) { 2417 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2418 Args, RParenLoc); 2419 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2420 DS, IdLoc, List, EllipsisLoc); 2421 } 2422 2423 namespace { 2424 2425 // Callback to only accept typo corrections that can be a valid C++ member 2426 // intializer: either a non-static field member or a base class. 2427 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2428 public: 2429 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2430 : ClassDecl(ClassDecl) {} 2431 2432 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE { 2433 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2434 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2435 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2436 return isa<TypeDecl>(ND); 2437 } 2438 return false; 2439 } 2440 2441 private: 2442 CXXRecordDecl *ClassDecl; 2443 }; 2444 2445 } 2446 2447 /// \brief Handle a C++ member initializer. 2448 MemInitResult 2449 Sema::BuildMemInitializer(Decl *ConstructorD, 2450 Scope *S, 2451 CXXScopeSpec &SS, 2452 IdentifierInfo *MemberOrBase, 2453 ParsedType TemplateTypeTy, 2454 const DeclSpec &DS, 2455 SourceLocation IdLoc, 2456 Expr *Init, 2457 SourceLocation EllipsisLoc) { 2458 if (!ConstructorD) 2459 return true; 2460 2461 AdjustDeclIfTemplate(ConstructorD); 2462 2463 CXXConstructorDecl *Constructor 2464 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2465 if (!Constructor) { 2466 // The user wrote a constructor initializer on a function that is 2467 // not a C++ constructor. Ignore the error for now, because we may 2468 // have more member initializers coming; we'll diagnose it just 2469 // once in ActOnMemInitializers. 2470 return true; 2471 } 2472 2473 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2474 2475 // C++ [class.base.init]p2: 2476 // Names in a mem-initializer-id are looked up in the scope of the 2477 // constructor's class and, if not found in that scope, are looked 2478 // up in the scope containing the constructor's definition. 2479 // [Note: if the constructor's class contains a member with the 2480 // same name as a direct or virtual base class of the class, a 2481 // mem-initializer-id naming the member or base class and composed 2482 // of a single identifier refers to the class member. A 2483 // mem-initializer-id for the hidden base class may be specified 2484 // using a qualified name. ] 2485 if (!SS.getScopeRep() && !TemplateTypeTy) { 2486 // Look for a member, first. 2487 DeclContext::lookup_result Result 2488 = ClassDecl->lookup(MemberOrBase); 2489 if (!Result.empty()) { 2490 ValueDecl *Member; 2491 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2492 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2493 if (EllipsisLoc.isValid()) 2494 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2495 << MemberOrBase 2496 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2497 2498 return BuildMemberInitializer(Member, Init, IdLoc); 2499 } 2500 } 2501 } 2502 // It didn't name a member, so see if it names a class. 2503 QualType BaseType; 2504 TypeSourceInfo *TInfo = 0; 2505 2506 if (TemplateTypeTy) { 2507 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2508 } else if (DS.getTypeSpecType() == TST_decltype) { 2509 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2510 } else { 2511 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2512 LookupParsedName(R, S, &SS); 2513 2514 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2515 if (!TyD) { 2516 if (R.isAmbiguous()) return true; 2517 2518 // We don't want access-control diagnostics here. 2519 R.suppressDiagnostics(); 2520 2521 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2522 bool NotUnknownSpecialization = false; 2523 DeclContext *DC = computeDeclContext(SS, false); 2524 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2525 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2526 2527 if (!NotUnknownSpecialization) { 2528 // When the scope specifier can refer to a member of an unknown 2529 // specialization, we take it as a type name. 2530 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2531 SS.getWithLocInContext(Context), 2532 *MemberOrBase, IdLoc); 2533 if (BaseType.isNull()) 2534 return true; 2535 2536 R.clear(); 2537 R.setLookupName(MemberOrBase); 2538 } 2539 } 2540 2541 // If no results were found, try to correct typos. 2542 TypoCorrection Corr; 2543 MemInitializerValidatorCCC Validator(ClassDecl); 2544 if (R.empty() && BaseType.isNull() && 2545 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2546 Validator, ClassDecl))) { 2547 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2548 // We have found a non-static data member with a similar 2549 // name to what was typed; complain and initialize that 2550 // member. 2551 diagnoseTypo(Corr, 2552 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2553 << MemberOrBase << true); 2554 return BuildMemberInitializer(Member, Init, IdLoc); 2555 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2556 const CXXBaseSpecifier *DirectBaseSpec; 2557 const CXXBaseSpecifier *VirtualBaseSpec; 2558 if (FindBaseInitializer(*this, ClassDecl, 2559 Context.getTypeDeclType(Type), 2560 DirectBaseSpec, VirtualBaseSpec)) { 2561 // We have found a direct or virtual base class with a 2562 // similar name to what was typed; complain and initialize 2563 // that base class. 2564 diagnoseTypo(Corr, 2565 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2566 << MemberOrBase << false, 2567 PDiag() /*Suppress note, we provide our own.*/); 2568 2569 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2570 : VirtualBaseSpec; 2571 Diag(BaseSpec->getLocStart(), 2572 diag::note_base_class_specified_here) 2573 << BaseSpec->getType() 2574 << BaseSpec->getSourceRange(); 2575 2576 TyD = Type; 2577 } 2578 } 2579 } 2580 2581 if (!TyD && BaseType.isNull()) { 2582 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2583 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2584 return true; 2585 } 2586 } 2587 2588 if (BaseType.isNull()) { 2589 BaseType = Context.getTypeDeclType(TyD); 2590 if (SS.isSet()) { 2591 NestedNameSpecifier *Qualifier = 2592 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2593 2594 // FIXME: preserve source range information 2595 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 2596 } 2597 } 2598 } 2599 2600 if (!TInfo) 2601 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2602 2603 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2604 } 2605 2606 /// Checks a member initializer expression for cases where reference (or 2607 /// pointer) members are bound to by-value parameters (or their addresses). 2608 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2609 Expr *Init, 2610 SourceLocation IdLoc) { 2611 QualType MemberTy = Member->getType(); 2612 2613 // We only handle pointers and references currently. 2614 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2615 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2616 return; 2617 2618 const bool IsPointer = MemberTy->isPointerType(); 2619 if (IsPointer) { 2620 if (const UnaryOperator *Op 2621 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2622 // The only case we're worried about with pointers requires taking the 2623 // address. 2624 if (Op->getOpcode() != UO_AddrOf) 2625 return; 2626 2627 Init = Op->getSubExpr(); 2628 } else { 2629 // We only handle address-of expression initializers for pointers. 2630 return; 2631 } 2632 } 2633 2634 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2635 // We only warn when referring to a non-reference parameter declaration. 2636 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2637 if (!Parameter || Parameter->getType()->isReferenceType()) 2638 return; 2639 2640 S.Diag(Init->getExprLoc(), 2641 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2642 : diag::warn_bind_ref_member_to_parameter) 2643 << Member << Parameter << Init->getSourceRange(); 2644 } else { 2645 // Other initializers are fine. 2646 return; 2647 } 2648 2649 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2650 << (unsigned)IsPointer; 2651 } 2652 2653 MemInitResult 2654 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2655 SourceLocation IdLoc) { 2656 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2657 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2658 assert((DirectMember || IndirectMember) && 2659 "Member must be a FieldDecl or IndirectFieldDecl"); 2660 2661 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2662 return true; 2663 2664 if (Member->isInvalidDecl()) 2665 return true; 2666 2667 MultiExprArg Args; 2668 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2669 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2670 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2671 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2672 } else { 2673 // Template instantiation doesn't reconstruct ParenListExprs for us. 2674 Args = Init; 2675 } 2676 2677 SourceRange InitRange = Init->getSourceRange(); 2678 2679 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2680 // Can't check initialization for a member of dependent type or when 2681 // any of the arguments are type-dependent expressions. 2682 DiscardCleanupsInEvaluationContext(); 2683 } else { 2684 bool InitList = false; 2685 if (isa<InitListExpr>(Init)) { 2686 InitList = true; 2687 Args = Init; 2688 } 2689 2690 // Initialize the member. 2691 InitializedEntity MemberEntity = 2692 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2693 : InitializedEntity::InitializeMember(IndirectMember, 0); 2694 InitializationKind Kind = 2695 InitList ? InitializationKind::CreateDirectList(IdLoc) 2696 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2697 InitRange.getEnd()); 2698 2699 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 2700 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0); 2701 if (MemberInit.isInvalid()) 2702 return true; 2703 2704 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 2705 2706 // C++11 [class.base.init]p7: 2707 // The initialization of each base and member constitutes a 2708 // full-expression. 2709 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2710 if (MemberInit.isInvalid()) 2711 return true; 2712 2713 Init = MemberInit.get(); 2714 } 2715 2716 if (DirectMember) { 2717 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2718 InitRange.getBegin(), Init, 2719 InitRange.getEnd()); 2720 } else { 2721 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2722 InitRange.getBegin(), Init, 2723 InitRange.getEnd()); 2724 } 2725 } 2726 2727 MemInitResult 2728 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2729 CXXRecordDecl *ClassDecl) { 2730 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2731 if (!LangOpts.CPlusPlus11) 2732 return Diag(NameLoc, diag::err_delegating_ctor) 2733 << TInfo->getTypeLoc().getLocalSourceRange(); 2734 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2735 2736 bool InitList = true; 2737 MultiExprArg Args = Init; 2738 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2739 InitList = false; 2740 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2741 } 2742 2743 SourceRange InitRange = Init->getSourceRange(); 2744 // Initialize the object. 2745 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2746 QualType(ClassDecl->getTypeForDecl(), 0)); 2747 InitializationKind Kind = 2748 InitList ? InitializationKind::CreateDirectList(NameLoc) 2749 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2750 InitRange.getEnd()); 2751 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 2752 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2753 Args, 0); 2754 if (DelegationInit.isInvalid()) 2755 return true; 2756 2757 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2758 "Delegating constructor with no target?"); 2759 2760 // C++11 [class.base.init]p7: 2761 // The initialization of each base and member constitutes a 2762 // full-expression. 2763 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2764 InitRange.getBegin()); 2765 if (DelegationInit.isInvalid()) 2766 return true; 2767 2768 // If we are in a dependent context, template instantiation will 2769 // perform this type-checking again. Just save the arguments that we 2770 // received in a ParenListExpr. 2771 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2772 // of the information that we have about the base 2773 // initializer. However, deconstructing the ASTs is a dicey process, 2774 // and this approach is far more likely to get the corner cases right. 2775 if (CurContext->isDependentContext()) 2776 DelegationInit = Owned(Init); 2777 2778 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2779 DelegationInit.takeAs<Expr>(), 2780 InitRange.getEnd()); 2781 } 2782 2783 MemInitResult 2784 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2785 Expr *Init, CXXRecordDecl *ClassDecl, 2786 SourceLocation EllipsisLoc) { 2787 SourceLocation BaseLoc 2788 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2789 2790 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2791 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2792 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2793 2794 // C++ [class.base.init]p2: 2795 // [...] Unless the mem-initializer-id names a nonstatic data 2796 // member of the constructor's class or a direct or virtual base 2797 // of that class, the mem-initializer is ill-formed. A 2798 // mem-initializer-list can initialize a base class using any 2799 // name that denotes that base class type. 2800 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2801 2802 SourceRange InitRange = Init->getSourceRange(); 2803 if (EllipsisLoc.isValid()) { 2804 // This is a pack expansion. 2805 if (!BaseType->containsUnexpandedParameterPack()) { 2806 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2807 << SourceRange(BaseLoc, InitRange.getEnd()); 2808 2809 EllipsisLoc = SourceLocation(); 2810 } 2811 } else { 2812 // Check for any unexpanded parameter packs. 2813 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2814 return true; 2815 2816 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2817 return true; 2818 } 2819 2820 // Check for direct and virtual base classes. 2821 const CXXBaseSpecifier *DirectBaseSpec = 0; 2822 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2823 if (!Dependent) { 2824 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2825 BaseType)) 2826 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2827 2828 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2829 VirtualBaseSpec); 2830 2831 // C++ [base.class.init]p2: 2832 // Unless the mem-initializer-id names a nonstatic data member of the 2833 // constructor's class or a direct or virtual base of that class, the 2834 // mem-initializer is ill-formed. 2835 if (!DirectBaseSpec && !VirtualBaseSpec) { 2836 // If the class has any dependent bases, then it's possible that 2837 // one of those types will resolve to the same type as 2838 // BaseType. Therefore, just treat this as a dependent base 2839 // class initialization. FIXME: Should we try to check the 2840 // initialization anyway? It seems odd. 2841 if (ClassDecl->hasAnyDependentBases()) 2842 Dependent = true; 2843 else 2844 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2845 << BaseType << Context.getTypeDeclType(ClassDecl) 2846 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2847 } 2848 } 2849 2850 if (Dependent) { 2851 DiscardCleanupsInEvaluationContext(); 2852 2853 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2854 /*IsVirtual=*/false, 2855 InitRange.getBegin(), Init, 2856 InitRange.getEnd(), EllipsisLoc); 2857 } 2858 2859 // C++ [base.class.init]p2: 2860 // If a mem-initializer-id is ambiguous because it designates both 2861 // a direct non-virtual base class and an inherited virtual base 2862 // class, the mem-initializer is ill-formed. 2863 if (DirectBaseSpec && VirtualBaseSpec) 2864 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2865 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2866 2867 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 2868 if (!BaseSpec) 2869 BaseSpec = VirtualBaseSpec; 2870 2871 // Initialize the base. 2872 bool InitList = true; 2873 MultiExprArg Args = Init; 2874 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2875 InitList = false; 2876 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2877 } 2878 2879 InitializedEntity BaseEntity = 2880 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2881 InitializationKind Kind = 2882 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2883 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2884 InitRange.getEnd()); 2885 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 2886 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0); 2887 if (BaseInit.isInvalid()) 2888 return true; 2889 2890 // C++11 [class.base.init]p7: 2891 // The initialization of each base and member constitutes a 2892 // full-expression. 2893 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 2894 if (BaseInit.isInvalid()) 2895 return true; 2896 2897 // If we are in a dependent context, template instantiation will 2898 // perform this type-checking again. Just save the arguments that we 2899 // received in a ParenListExpr. 2900 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2901 // of the information that we have about the base 2902 // initializer. However, deconstructing the ASTs is a dicey process, 2903 // and this approach is far more likely to get the corner cases right. 2904 if (CurContext->isDependentContext()) 2905 BaseInit = Owned(Init); 2906 2907 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2908 BaseSpec->isVirtual(), 2909 InitRange.getBegin(), 2910 BaseInit.takeAs<Expr>(), 2911 InitRange.getEnd(), EllipsisLoc); 2912 } 2913 2914 // Create a static_cast\<T&&>(expr). 2915 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 2916 if (T.isNull()) T = E->getType(); 2917 QualType TargetType = SemaRef.BuildReferenceType( 2918 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 2919 SourceLocation ExprLoc = E->getLocStart(); 2920 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2921 TargetType, ExprLoc); 2922 2923 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2924 SourceRange(ExprLoc, ExprLoc), 2925 E->getSourceRange()).take(); 2926 } 2927 2928 /// ImplicitInitializerKind - How an implicit base or member initializer should 2929 /// initialize its base or member. 2930 enum ImplicitInitializerKind { 2931 IIK_Default, 2932 IIK_Copy, 2933 IIK_Move, 2934 IIK_Inherit 2935 }; 2936 2937 static bool 2938 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2939 ImplicitInitializerKind ImplicitInitKind, 2940 CXXBaseSpecifier *BaseSpec, 2941 bool IsInheritedVirtualBase, 2942 CXXCtorInitializer *&CXXBaseInit) { 2943 InitializedEntity InitEntity 2944 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2945 IsInheritedVirtualBase); 2946 2947 ExprResult BaseInit; 2948 2949 switch (ImplicitInitKind) { 2950 case IIK_Inherit: { 2951 const CXXRecordDecl *Inherited = 2952 Constructor->getInheritedConstructor()->getParent(); 2953 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 2954 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 2955 // C++11 [class.inhctor]p8: 2956 // Each expression in the expression-list is of the form 2957 // static_cast<T&&>(p), where p is the name of the corresponding 2958 // constructor parameter and T is the declared type of p. 2959 SmallVector<Expr*, 16> Args; 2960 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 2961 ParmVarDecl *PD = Constructor->getParamDecl(I); 2962 ExprResult ArgExpr = 2963 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 2964 VK_LValue, SourceLocation()); 2965 if (ArgExpr.isInvalid()) 2966 return true; 2967 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType())); 2968 } 2969 2970 InitializationKind InitKind = InitializationKind::CreateDirect( 2971 Constructor->getLocation(), SourceLocation(), SourceLocation()); 2972 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 2973 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 2974 break; 2975 } 2976 } 2977 // Fall through. 2978 case IIK_Default: { 2979 InitializationKind InitKind 2980 = InitializationKind::CreateDefault(Constructor->getLocation()); 2981 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 2982 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 2983 break; 2984 } 2985 2986 case IIK_Move: 2987 case IIK_Copy: { 2988 bool Moving = ImplicitInitKind == IIK_Move; 2989 ParmVarDecl *Param = Constructor->getParamDecl(0); 2990 QualType ParamType = Param->getType().getNonReferenceType(); 2991 2992 Expr *CopyCtorArg = 2993 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2994 SourceLocation(), Param, false, 2995 Constructor->getLocation(), ParamType, 2996 VK_LValue, 0); 2997 2998 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2999 3000 // Cast to the base class to avoid ambiguities. 3001 QualType ArgTy = 3002 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3003 ParamType.getQualifiers()); 3004 3005 if (Moving) { 3006 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3007 } 3008 3009 CXXCastPath BasePath; 3010 BasePath.push_back(BaseSpec); 3011 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3012 CK_UncheckedDerivedToBase, 3013 Moving ? VK_XValue : VK_LValue, 3014 &BasePath).take(); 3015 3016 InitializationKind InitKind 3017 = InitializationKind::CreateDirect(Constructor->getLocation(), 3018 SourceLocation(), SourceLocation()); 3019 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3020 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3021 break; 3022 } 3023 } 3024 3025 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3026 if (BaseInit.isInvalid()) 3027 return true; 3028 3029 CXXBaseInit = 3030 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3031 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3032 SourceLocation()), 3033 BaseSpec->isVirtual(), 3034 SourceLocation(), 3035 BaseInit.takeAs<Expr>(), 3036 SourceLocation(), 3037 SourceLocation()); 3038 3039 return false; 3040 } 3041 3042 static bool RefersToRValueRef(Expr *MemRef) { 3043 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3044 return Referenced->getType()->isRValueReferenceType(); 3045 } 3046 3047 static bool 3048 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3049 ImplicitInitializerKind ImplicitInitKind, 3050 FieldDecl *Field, IndirectFieldDecl *Indirect, 3051 CXXCtorInitializer *&CXXMemberInit) { 3052 if (Field->isInvalidDecl()) 3053 return true; 3054 3055 SourceLocation Loc = Constructor->getLocation(); 3056 3057 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3058 bool Moving = ImplicitInitKind == IIK_Move; 3059 ParmVarDecl *Param = Constructor->getParamDecl(0); 3060 QualType ParamType = Param->getType().getNonReferenceType(); 3061 3062 // Suppress copying zero-width bitfields. 3063 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3064 return false; 3065 3066 Expr *MemberExprBase = 3067 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3068 SourceLocation(), Param, false, 3069 Loc, ParamType, VK_LValue, 0); 3070 3071 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3072 3073 if (Moving) { 3074 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3075 } 3076 3077 // Build a reference to this field within the parameter. 3078 CXXScopeSpec SS; 3079 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3080 Sema::LookupMemberName); 3081 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3082 : cast<ValueDecl>(Field), AS_public); 3083 MemberLookup.resolveKind(); 3084 ExprResult CtorArg 3085 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3086 ParamType, Loc, 3087 /*IsArrow=*/false, 3088 SS, 3089 /*TemplateKWLoc=*/SourceLocation(), 3090 /*FirstQualifierInScope=*/0, 3091 MemberLookup, 3092 /*TemplateArgs=*/0); 3093 if (CtorArg.isInvalid()) 3094 return true; 3095 3096 // C++11 [class.copy]p15: 3097 // - if a member m has rvalue reference type T&&, it is direct-initialized 3098 // with static_cast<T&&>(x.m); 3099 if (RefersToRValueRef(CtorArg.get())) { 3100 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3101 } 3102 3103 // When the field we are copying is an array, create index variables for 3104 // each dimension of the array. We use these index variables to subscript 3105 // the source array, and other clients (e.g., CodeGen) will perform the 3106 // necessary iteration with these index variables. 3107 SmallVector<VarDecl *, 4> IndexVariables; 3108 QualType BaseType = Field->getType(); 3109 QualType SizeType = SemaRef.Context.getSizeType(); 3110 bool InitializingArray = false; 3111 while (const ConstantArrayType *Array 3112 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3113 InitializingArray = true; 3114 // Create the iteration variable for this array index. 3115 IdentifierInfo *IterationVarName = 0; 3116 { 3117 SmallString<8> Str; 3118 llvm::raw_svector_ostream OS(Str); 3119 OS << "__i" << IndexVariables.size(); 3120 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3121 } 3122 VarDecl *IterationVar 3123 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3124 IterationVarName, SizeType, 3125 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3126 SC_None); 3127 IndexVariables.push_back(IterationVar); 3128 3129 // Create a reference to the iteration variable. 3130 ExprResult IterationVarRef 3131 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3132 assert(!IterationVarRef.isInvalid() && 3133 "Reference to invented variable cannot fail!"); 3134 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 3135 assert(!IterationVarRef.isInvalid() && 3136 "Conversion of invented variable cannot fail!"); 3137 3138 // Subscript the array with this iteration variable. 3139 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 3140 IterationVarRef.take(), 3141 Loc); 3142 if (CtorArg.isInvalid()) 3143 return true; 3144 3145 BaseType = Array->getElementType(); 3146 } 3147 3148 // The array subscript expression is an lvalue, which is wrong for moving. 3149 if (Moving && InitializingArray) 3150 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3151 3152 // Construct the entity that we will be initializing. For an array, this 3153 // will be first element in the array, which may require several levels 3154 // of array-subscript entities. 3155 SmallVector<InitializedEntity, 4> Entities; 3156 Entities.reserve(1 + IndexVariables.size()); 3157 if (Indirect) 3158 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3159 else 3160 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3161 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3162 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3163 0, 3164 Entities.back())); 3165 3166 // Direct-initialize to use the copy constructor. 3167 InitializationKind InitKind = 3168 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3169 3170 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 3171 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3172 3173 ExprResult MemberInit 3174 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3175 MultiExprArg(&CtorArgE, 1)); 3176 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3177 if (MemberInit.isInvalid()) 3178 return true; 3179 3180 if (Indirect) { 3181 assert(IndexVariables.size() == 0 && 3182 "Indirect field improperly initialized"); 3183 CXXMemberInit 3184 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3185 Loc, Loc, 3186 MemberInit.takeAs<Expr>(), 3187 Loc); 3188 } else 3189 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3190 Loc, MemberInit.takeAs<Expr>(), 3191 Loc, 3192 IndexVariables.data(), 3193 IndexVariables.size()); 3194 return false; 3195 } 3196 3197 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3198 "Unhandled implicit init kind!"); 3199 3200 QualType FieldBaseElementType = 3201 SemaRef.Context.getBaseElementType(Field->getType()); 3202 3203 if (FieldBaseElementType->isRecordType()) { 3204 InitializedEntity InitEntity 3205 = Indirect? InitializedEntity::InitializeMember(Indirect) 3206 : InitializedEntity::InitializeMember(Field); 3207 InitializationKind InitKind = 3208 InitializationKind::CreateDefault(Loc); 3209 3210 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3211 ExprResult MemberInit = 3212 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3213 3214 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3215 if (MemberInit.isInvalid()) 3216 return true; 3217 3218 if (Indirect) 3219 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3220 Indirect, Loc, 3221 Loc, 3222 MemberInit.get(), 3223 Loc); 3224 else 3225 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3226 Field, Loc, Loc, 3227 MemberInit.get(), 3228 Loc); 3229 return false; 3230 } 3231 3232 if (!Field->getParent()->isUnion()) { 3233 if (FieldBaseElementType->isReferenceType()) { 3234 SemaRef.Diag(Constructor->getLocation(), 3235 diag::err_uninitialized_member_in_ctor) 3236 << (int)Constructor->isImplicit() 3237 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3238 << 0 << Field->getDeclName(); 3239 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3240 return true; 3241 } 3242 3243 if (FieldBaseElementType.isConstQualified()) { 3244 SemaRef.Diag(Constructor->getLocation(), 3245 diag::err_uninitialized_member_in_ctor) 3246 << (int)Constructor->isImplicit() 3247 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3248 << 1 << Field->getDeclName(); 3249 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3250 return true; 3251 } 3252 } 3253 3254 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3255 FieldBaseElementType->isObjCRetainableType() && 3256 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3257 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3258 // ARC: 3259 // Default-initialize Objective-C pointers to NULL. 3260 CXXMemberInit 3261 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3262 Loc, Loc, 3263 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3264 Loc); 3265 return false; 3266 } 3267 3268 // Nothing to initialize. 3269 CXXMemberInit = 0; 3270 return false; 3271 } 3272 3273 namespace { 3274 struct BaseAndFieldInfo { 3275 Sema &S; 3276 CXXConstructorDecl *Ctor; 3277 bool AnyErrorsInInits; 3278 ImplicitInitializerKind IIK; 3279 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3280 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3281 3282 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3283 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3284 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3285 if (Generated && Ctor->isCopyConstructor()) 3286 IIK = IIK_Copy; 3287 else if (Generated && Ctor->isMoveConstructor()) 3288 IIK = IIK_Move; 3289 else if (Ctor->getInheritedConstructor()) 3290 IIK = IIK_Inherit; 3291 else 3292 IIK = IIK_Default; 3293 } 3294 3295 bool isImplicitCopyOrMove() const { 3296 switch (IIK) { 3297 case IIK_Copy: 3298 case IIK_Move: 3299 return true; 3300 3301 case IIK_Default: 3302 case IIK_Inherit: 3303 return false; 3304 } 3305 3306 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3307 } 3308 3309 bool addFieldInitializer(CXXCtorInitializer *Init) { 3310 AllToInit.push_back(Init); 3311 3312 // Check whether this initializer makes the field "used". 3313 if (Init->getInit()->HasSideEffects(S.Context)) 3314 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3315 3316 return false; 3317 } 3318 }; 3319 } 3320 3321 /// \brief Determine whether the given indirect field declaration is somewhere 3322 /// within an anonymous union. 3323 static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 3324 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 3325 CEnd = F->chain_end(); 3326 C != CEnd; ++C) 3327 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 3328 if (Record->isUnion()) 3329 return true; 3330 3331 return false; 3332 } 3333 3334 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3335 /// array type. 3336 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3337 if (T->isIncompleteArrayType()) 3338 return true; 3339 3340 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3341 if (!ArrayT->getSize()) 3342 return true; 3343 3344 T = ArrayT->getElementType(); 3345 } 3346 3347 return false; 3348 } 3349 3350 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3351 FieldDecl *Field, 3352 IndirectFieldDecl *Indirect = 0) { 3353 if (Field->isInvalidDecl()) 3354 return false; 3355 3356 // Overwhelmingly common case: we have a direct initializer for this field. 3357 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 3358 return Info.addFieldInitializer(Init); 3359 3360 // C++11 [class.base.init]p8: if the entity is a non-static data member that 3361 // has a brace-or-equal-initializer, the entity is initialized as specified 3362 // in [dcl.init]. 3363 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3364 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3365 Info.Ctor->getLocation(), Field); 3366 CXXCtorInitializer *Init; 3367 if (Indirect) 3368 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3369 SourceLocation(), 3370 SourceLocation(), DIE, 3371 SourceLocation()); 3372 else 3373 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3374 SourceLocation(), 3375 SourceLocation(), DIE, 3376 SourceLocation()); 3377 return Info.addFieldInitializer(Init); 3378 } 3379 3380 // Don't build an implicit initializer for union members if none was 3381 // explicitly specified. 3382 if (Field->getParent()->isUnion() || 3383 (Indirect && isWithinAnonymousUnion(Indirect))) 3384 return false; 3385 3386 // Don't initialize incomplete or zero-length arrays. 3387 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3388 return false; 3389 3390 // Don't try to build an implicit initializer if there were semantic 3391 // errors in any of the initializers (and therefore we might be 3392 // missing some that the user actually wrote). 3393 if (Info.AnyErrorsInInits) 3394 return false; 3395 3396 CXXCtorInitializer *Init = 0; 3397 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3398 Indirect, Init)) 3399 return true; 3400 3401 if (!Init) 3402 return false; 3403 3404 return Info.addFieldInitializer(Init); 3405 } 3406 3407 bool 3408 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3409 CXXCtorInitializer *Initializer) { 3410 assert(Initializer->isDelegatingInitializer()); 3411 Constructor->setNumCtorInitializers(1); 3412 CXXCtorInitializer **initializer = 3413 new (Context) CXXCtorInitializer*[1]; 3414 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3415 Constructor->setCtorInitializers(initializer); 3416 3417 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3418 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3419 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3420 } 3421 3422 DelegatingCtorDecls.push_back(Constructor); 3423 3424 return false; 3425 } 3426 3427 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3428 ArrayRef<CXXCtorInitializer *> Initializers) { 3429 if (Constructor->isDependentContext()) { 3430 // Just store the initializers as written, they will be checked during 3431 // instantiation. 3432 if (!Initializers.empty()) { 3433 Constructor->setNumCtorInitializers(Initializers.size()); 3434 CXXCtorInitializer **baseOrMemberInitializers = 3435 new (Context) CXXCtorInitializer*[Initializers.size()]; 3436 memcpy(baseOrMemberInitializers, Initializers.data(), 3437 Initializers.size() * sizeof(CXXCtorInitializer*)); 3438 Constructor->setCtorInitializers(baseOrMemberInitializers); 3439 } 3440 3441 // Let template instantiation know whether we had errors. 3442 if (AnyErrors) 3443 Constructor->setInvalidDecl(); 3444 3445 return false; 3446 } 3447 3448 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3449 3450 // We need to build the initializer AST according to order of construction 3451 // and not what user specified in the Initializers list. 3452 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3453 if (!ClassDecl) 3454 return true; 3455 3456 bool HadError = false; 3457 3458 for (unsigned i = 0; i < Initializers.size(); i++) { 3459 CXXCtorInitializer *Member = Initializers[i]; 3460 3461 if (Member->isBaseInitializer()) 3462 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3463 else 3464 Info.AllBaseFields[Member->getAnyMember()] = Member; 3465 } 3466 3467 // Keep track of the direct virtual bases. 3468 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3469 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 3470 E = ClassDecl->bases_end(); I != E; ++I) { 3471 if (I->isVirtual()) 3472 DirectVBases.insert(I); 3473 } 3474 3475 // Push virtual bases before others. 3476 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3477 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3478 3479 if (CXXCtorInitializer *Value 3480 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 3481 // [class.base.init]p7, per DR257: 3482 // A mem-initializer where the mem-initializer-id names a virtual base 3483 // class is ignored during execution of a constructor of any class that 3484 // is not the most derived class. 3485 if (ClassDecl->isAbstract()) { 3486 // FIXME: Provide a fixit to remove the base specifier. This requires 3487 // tracking the location of the associated comma for a base specifier. 3488 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3489 << VBase->getType() << ClassDecl; 3490 DiagnoseAbstractType(ClassDecl); 3491 } 3492 3493 Info.AllToInit.push_back(Value); 3494 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3495 // [class.base.init]p8, per DR257: 3496 // If a given [...] base class is not named by a mem-initializer-id 3497 // [...] and the entity is not a virtual base class of an abstract 3498 // class, then [...] the entity is default-initialized. 3499 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 3500 CXXCtorInitializer *CXXBaseInit; 3501 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3502 VBase, IsInheritedVirtualBase, 3503 CXXBaseInit)) { 3504 HadError = true; 3505 continue; 3506 } 3507 3508 Info.AllToInit.push_back(CXXBaseInit); 3509 } 3510 } 3511 3512 // Non-virtual bases. 3513 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3514 E = ClassDecl->bases_end(); Base != E; ++Base) { 3515 // Virtuals are in the virtual base list and already constructed. 3516 if (Base->isVirtual()) 3517 continue; 3518 3519 if (CXXCtorInitializer *Value 3520 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 3521 Info.AllToInit.push_back(Value); 3522 } else if (!AnyErrors) { 3523 CXXCtorInitializer *CXXBaseInit; 3524 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3525 Base, /*IsInheritedVirtualBase=*/false, 3526 CXXBaseInit)) { 3527 HadError = true; 3528 continue; 3529 } 3530 3531 Info.AllToInit.push_back(CXXBaseInit); 3532 } 3533 } 3534 3535 // Fields. 3536 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 3537 MemEnd = ClassDecl->decls_end(); 3538 Mem != MemEnd; ++Mem) { 3539 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 3540 // C++ [class.bit]p2: 3541 // A declaration for a bit-field that omits the identifier declares an 3542 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3543 // initialized. 3544 if (F->isUnnamedBitfield()) 3545 continue; 3546 3547 // If we're not generating the implicit copy/move constructor, then we'll 3548 // handle anonymous struct/union fields based on their individual 3549 // indirect fields. 3550 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3551 continue; 3552 3553 if (CollectFieldInitializer(*this, Info, F)) 3554 HadError = true; 3555 continue; 3556 } 3557 3558 // Beyond this point, we only consider default initialization. 3559 if (Info.isImplicitCopyOrMove()) 3560 continue; 3561 3562 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 3563 if (F->getType()->isIncompleteArrayType()) { 3564 assert(ClassDecl->hasFlexibleArrayMember() && 3565 "Incomplete array type is not valid"); 3566 continue; 3567 } 3568 3569 // Initialize each field of an anonymous struct individually. 3570 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3571 HadError = true; 3572 3573 continue; 3574 } 3575 } 3576 3577 unsigned NumInitializers = Info.AllToInit.size(); 3578 if (NumInitializers > 0) { 3579 Constructor->setNumCtorInitializers(NumInitializers); 3580 CXXCtorInitializer **baseOrMemberInitializers = 3581 new (Context) CXXCtorInitializer*[NumInitializers]; 3582 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3583 NumInitializers * sizeof(CXXCtorInitializer*)); 3584 Constructor->setCtorInitializers(baseOrMemberInitializers); 3585 3586 // Constructors implicitly reference the base and member 3587 // destructors. 3588 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3589 Constructor->getParent()); 3590 } 3591 3592 return HadError; 3593 } 3594 3595 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3596 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3597 const RecordDecl *RD = RT->getDecl(); 3598 if (RD->isAnonymousStructOrUnion()) { 3599 for (RecordDecl::field_iterator Field = RD->field_begin(), 3600 E = RD->field_end(); Field != E; ++Field) 3601 PopulateKeysForFields(*Field, IdealInits); 3602 return; 3603 } 3604 } 3605 IdealInits.push_back(Field); 3606 } 3607 3608 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3609 return Context.getCanonicalType(BaseType).getTypePtr(); 3610 } 3611 3612 static const void *GetKeyForMember(ASTContext &Context, 3613 CXXCtorInitializer *Member) { 3614 if (!Member->isAnyMemberInitializer()) 3615 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3616 3617 return Member->getAnyMember(); 3618 } 3619 3620 static void DiagnoseBaseOrMemInitializerOrder( 3621 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3622 ArrayRef<CXXCtorInitializer *> Inits) { 3623 if (Constructor->getDeclContext()->isDependentContext()) 3624 return; 3625 3626 // Don't check initializers order unless the warning is enabled at the 3627 // location of at least one initializer. 3628 bool ShouldCheckOrder = false; 3629 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3630 CXXCtorInitializer *Init = Inits[InitIndex]; 3631 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3632 Init->getSourceLocation()) 3633 != DiagnosticsEngine::Ignored) { 3634 ShouldCheckOrder = true; 3635 break; 3636 } 3637 } 3638 if (!ShouldCheckOrder) 3639 return; 3640 3641 // Build the list of bases and members in the order that they'll 3642 // actually be initialized. The explicit initializers should be in 3643 // this same order but may be missing things. 3644 SmallVector<const void*, 32> IdealInitKeys; 3645 3646 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3647 3648 // 1. Virtual bases. 3649 for (CXXRecordDecl::base_class_const_iterator VBase = 3650 ClassDecl->vbases_begin(), 3651 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3652 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3653 3654 // 2. Non-virtual bases. 3655 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3656 E = ClassDecl->bases_end(); Base != E; ++Base) { 3657 if (Base->isVirtual()) 3658 continue; 3659 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3660 } 3661 3662 // 3. Direct fields. 3663 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3664 E = ClassDecl->field_end(); Field != E; ++Field) { 3665 if (Field->isUnnamedBitfield()) 3666 continue; 3667 3668 PopulateKeysForFields(*Field, IdealInitKeys); 3669 } 3670 3671 unsigned NumIdealInits = IdealInitKeys.size(); 3672 unsigned IdealIndex = 0; 3673 3674 CXXCtorInitializer *PrevInit = 0; 3675 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3676 CXXCtorInitializer *Init = Inits[InitIndex]; 3677 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3678 3679 // Scan forward to try to find this initializer in the idealized 3680 // initializers list. 3681 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3682 if (InitKey == IdealInitKeys[IdealIndex]) 3683 break; 3684 3685 // If we didn't find this initializer, it must be because we 3686 // scanned past it on a previous iteration. That can only 3687 // happen if we're out of order; emit a warning. 3688 if (IdealIndex == NumIdealInits && PrevInit) { 3689 Sema::SemaDiagnosticBuilder D = 3690 SemaRef.Diag(PrevInit->getSourceLocation(), 3691 diag::warn_initializer_out_of_order); 3692 3693 if (PrevInit->isAnyMemberInitializer()) 3694 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3695 else 3696 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3697 3698 if (Init->isAnyMemberInitializer()) 3699 D << 0 << Init->getAnyMember()->getDeclName(); 3700 else 3701 D << 1 << Init->getTypeSourceInfo()->getType(); 3702 3703 // Move back to the initializer's location in the ideal list. 3704 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3705 if (InitKey == IdealInitKeys[IdealIndex]) 3706 break; 3707 3708 assert(IdealIndex != NumIdealInits && 3709 "initializer not found in initializer list"); 3710 } 3711 3712 PrevInit = Init; 3713 } 3714 } 3715 3716 namespace { 3717 bool CheckRedundantInit(Sema &S, 3718 CXXCtorInitializer *Init, 3719 CXXCtorInitializer *&PrevInit) { 3720 if (!PrevInit) { 3721 PrevInit = Init; 3722 return false; 3723 } 3724 3725 if (FieldDecl *Field = Init->getAnyMember()) 3726 S.Diag(Init->getSourceLocation(), 3727 diag::err_multiple_mem_initialization) 3728 << Field->getDeclName() 3729 << Init->getSourceRange(); 3730 else { 3731 const Type *BaseClass = Init->getBaseClass(); 3732 assert(BaseClass && "neither field nor base"); 3733 S.Diag(Init->getSourceLocation(), 3734 diag::err_multiple_base_initialization) 3735 << QualType(BaseClass, 0) 3736 << Init->getSourceRange(); 3737 } 3738 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3739 << 0 << PrevInit->getSourceRange(); 3740 3741 return true; 3742 } 3743 3744 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3745 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3746 3747 bool CheckRedundantUnionInit(Sema &S, 3748 CXXCtorInitializer *Init, 3749 RedundantUnionMap &Unions) { 3750 FieldDecl *Field = Init->getAnyMember(); 3751 RecordDecl *Parent = Field->getParent(); 3752 NamedDecl *Child = Field; 3753 3754 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3755 if (Parent->isUnion()) { 3756 UnionEntry &En = Unions[Parent]; 3757 if (En.first && En.first != Child) { 3758 S.Diag(Init->getSourceLocation(), 3759 diag::err_multiple_mem_union_initialization) 3760 << Field->getDeclName() 3761 << Init->getSourceRange(); 3762 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3763 << 0 << En.second->getSourceRange(); 3764 return true; 3765 } 3766 if (!En.first) { 3767 En.first = Child; 3768 En.second = Init; 3769 } 3770 if (!Parent->isAnonymousStructOrUnion()) 3771 return false; 3772 } 3773 3774 Child = Parent; 3775 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3776 } 3777 3778 return false; 3779 } 3780 } 3781 3782 // Diagnose value-uses of fields to initialize themselves, e.g. 3783 // foo(foo) 3784 // where foo is not also a parameter to the constructor. 3785 // Also diagnose across field uninitialized use such as 3786 // x(y), y(x) 3787 // TODO: implement -Wuninitialized and fold this into that framework. 3788 static void DiagnoseUnitializedFields( 3789 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3790 3791 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, 3792 Constructor->getLocation()) 3793 == DiagnosticsEngine::Ignored) { 3794 return; 3795 } 3796 3797 const CXXRecordDecl *RD = Constructor->getParent(); 3798 3799 // Holds fields that are uninitialized. 3800 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3801 3802 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end(); 3803 I != E; ++I) { 3804 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) { 3805 UninitializedFields.insert(FD); 3806 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) { 3807 UninitializedFields.insert(IFD->getAnonField()); 3808 } 3809 } 3810 3811 // Fields already checked when processing the in class initializers. 3812 llvm::SmallPtrSet<ValueDecl*, 4> 3813 InClassUninitializedFields = UninitializedFields; 3814 3815 for (CXXConstructorDecl::init_const_iterator FieldInit = 3816 Constructor->init_begin(), 3817 FieldInitEnd = Constructor->init_end(); 3818 FieldInit != FieldInitEnd; ++FieldInit) { 3819 3820 FieldDecl *Field = (*FieldInit)->getAnyMember(); 3821 Expr *InitExpr = (*FieldInit)->getInit(); 3822 3823 if (!Field) { 3824 CheckInitExprContainsUninitializedFields( 3825 SemaRef, InitExpr, 0, UninitializedFields, 3826 false/*WarnOnSelfReference*/); 3827 continue; 3828 } 3829 3830 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3831 // This field is initialized with an in-class initailzer. Remove the 3832 // fields already checked to prevent duplicate warnings. 3833 llvm::SmallPtrSet<ValueDecl*, 4> DiffSet = UninitializedFields; 3834 for (llvm::SmallPtrSet<ValueDecl*, 4>::iterator 3835 I = InClassUninitializedFields.begin(), 3836 E = InClassUninitializedFields.end(); 3837 I != E; ++I) { 3838 DiffSet.erase(*I); 3839 } 3840 CheckInitExprContainsUninitializedFields( 3841 SemaRef, Default->getExpr(), Field, DiffSet, 3842 DiffSet.count(Field), Constructor); 3843 3844 // Update the unitialized field sets. 3845 CheckInitExprContainsUninitializedFields( 3846 SemaRef, Default->getExpr(), 0, UninitializedFields, 3847 false); 3848 CheckInitExprContainsUninitializedFields( 3849 SemaRef, Default->getExpr(), 0, InClassUninitializedFields, 3850 false); 3851 } else { 3852 CheckInitExprContainsUninitializedFields( 3853 SemaRef, InitExpr, Field, UninitializedFields, 3854 UninitializedFields.count(Field)); 3855 if (Expr* InClassInit = Field->getInClassInitializer()) { 3856 CheckInitExprContainsUninitializedFields( 3857 SemaRef, InClassInit, 0, InClassUninitializedFields, 3858 false); 3859 } 3860 } 3861 UninitializedFields.erase(Field); 3862 InClassUninitializedFields.erase(Field); 3863 } 3864 } 3865 3866 /// ActOnMemInitializers - Handle the member initializers for a constructor. 3867 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3868 SourceLocation ColonLoc, 3869 ArrayRef<CXXCtorInitializer*> MemInits, 3870 bool AnyErrors) { 3871 if (!ConstructorDecl) 3872 return; 3873 3874 AdjustDeclIfTemplate(ConstructorDecl); 3875 3876 CXXConstructorDecl *Constructor 3877 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3878 3879 if (!Constructor) { 3880 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3881 return; 3882 } 3883 3884 // Mapping for the duplicate initializers check. 3885 // For member initializers, this is keyed with a FieldDecl*. 3886 // For base initializers, this is keyed with a Type*. 3887 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 3888 3889 // Mapping for the inconsistent anonymous-union initializers check. 3890 RedundantUnionMap MemberUnions; 3891 3892 bool HadError = false; 3893 for (unsigned i = 0; i < MemInits.size(); i++) { 3894 CXXCtorInitializer *Init = MemInits[i]; 3895 3896 // Set the source order index. 3897 Init->setSourceOrder(i); 3898 3899 if (Init->isAnyMemberInitializer()) { 3900 FieldDecl *Field = Init->getAnyMember(); 3901 if (CheckRedundantInit(*this, Init, Members[Field]) || 3902 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3903 HadError = true; 3904 } else if (Init->isBaseInitializer()) { 3905 const void *Key = 3906 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3907 if (CheckRedundantInit(*this, Init, Members[Key])) 3908 HadError = true; 3909 } else { 3910 assert(Init->isDelegatingInitializer()); 3911 // This must be the only initializer 3912 if (MemInits.size() != 1) { 3913 Diag(Init->getSourceLocation(), 3914 diag::err_delegating_initializer_alone) 3915 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3916 // We will treat this as being the only initializer. 3917 } 3918 SetDelegatingInitializer(Constructor, MemInits[i]); 3919 // Return immediately as the initializer is set. 3920 return; 3921 } 3922 } 3923 3924 if (HadError) 3925 return; 3926 3927 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 3928 3929 SetCtorInitializers(Constructor, AnyErrors, MemInits); 3930 3931 DiagnoseUnitializedFields(*this, Constructor); 3932 } 3933 3934 void 3935 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3936 CXXRecordDecl *ClassDecl) { 3937 // Ignore dependent contexts. Also ignore unions, since their members never 3938 // have destructors implicitly called. 3939 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3940 return; 3941 3942 // FIXME: all the access-control diagnostics are positioned on the 3943 // field/base declaration. That's probably good; that said, the 3944 // user might reasonably want to know why the destructor is being 3945 // emitted, and we currently don't say. 3946 3947 // Non-static data members. 3948 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3949 E = ClassDecl->field_end(); I != E; ++I) { 3950 FieldDecl *Field = *I; 3951 if (Field->isInvalidDecl()) 3952 continue; 3953 3954 // Don't destroy incomplete or zero-length arrays. 3955 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3956 continue; 3957 3958 QualType FieldType = Context.getBaseElementType(Field->getType()); 3959 3960 const RecordType* RT = FieldType->getAs<RecordType>(); 3961 if (!RT) 3962 continue; 3963 3964 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3965 if (FieldClassDecl->isInvalidDecl()) 3966 continue; 3967 if (FieldClassDecl->hasIrrelevantDestructor()) 3968 continue; 3969 // The destructor for an implicit anonymous union member is never invoked. 3970 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3971 continue; 3972 3973 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3974 assert(Dtor && "No dtor found for FieldClassDecl!"); 3975 CheckDestructorAccess(Field->getLocation(), Dtor, 3976 PDiag(diag::err_access_dtor_field) 3977 << Field->getDeclName() 3978 << FieldType); 3979 3980 MarkFunctionReferenced(Location, Dtor); 3981 DiagnoseUseOfDecl(Dtor, Location); 3982 } 3983 3984 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3985 3986 // Bases. 3987 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3988 E = ClassDecl->bases_end(); Base != E; ++Base) { 3989 // Bases are always records in a well-formed non-dependent class. 3990 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3991 3992 // Remember direct virtual bases. 3993 if (Base->isVirtual()) 3994 DirectVirtualBases.insert(RT); 3995 3996 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3997 // If our base class is invalid, we probably can't get its dtor anyway. 3998 if (BaseClassDecl->isInvalidDecl()) 3999 continue; 4000 if (BaseClassDecl->hasIrrelevantDestructor()) 4001 continue; 4002 4003 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4004 assert(Dtor && "No dtor found for BaseClassDecl!"); 4005 4006 // FIXME: caret should be on the start of the class name 4007 CheckDestructorAccess(Base->getLocStart(), Dtor, 4008 PDiag(diag::err_access_dtor_base) 4009 << Base->getType() 4010 << Base->getSourceRange(), 4011 Context.getTypeDeclType(ClassDecl)); 4012 4013 MarkFunctionReferenced(Location, Dtor); 4014 DiagnoseUseOfDecl(Dtor, Location); 4015 } 4016 4017 // Virtual bases. 4018 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 4019 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 4020 4021 // Bases are always records in a well-formed non-dependent class. 4022 const RecordType *RT = VBase->getType()->castAs<RecordType>(); 4023 4024 // Ignore direct virtual bases. 4025 if (DirectVirtualBases.count(RT)) 4026 continue; 4027 4028 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4029 // If our base class is invalid, we probably can't get its dtor anyway. 4030 if (BaseClassDecl->isInvalidDecl()) 4031 continue; 4032 if (BaseClassDecl->hasIrrelevantDestructor()) 4033 continue; 4034 4035 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4036 assert(Dtor && "No dtor found for BaseClassDecl!"); 4037 if (CheckDestructorAccess( 4038 ClassDecl->getLocation(), Dtor, 4039 PDiag(diag::err_access_dtor_vbase) 4040 << Context.getTypeDeclType(ClassDecl) << VBase->getType(), 4041 Context.getTypeDeclType(ClassDecl)) == 4042 AR_accessible) { 4043 CheckDerivedToBaseConversion( 4044 Context.getTypeDeclType(ClassDecl), VBase->getType(), 4045 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4046 SourceRange(), DeclarationName(), 0); 4047 } 4048 4049 MarkFunctionReferenced(Location, Dtor); 4050 DiagnoseUseOfDecl(Dtor, Location); 4051 } 4052 } 4053 4054 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4055 if (!CDtorDecl) 4056 return; 4057 4058 if (CXXConstructorDecl *Constructor 4059 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 4060 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4061 } 4062 4063 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4064 unsigned DiagID, AbstractDiagSelID SelID) { 4065 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4066 unsigned DiagID; 4067 AbstractDiagSelID SelID; 4068 4069 public: 4070 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4071 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4072 4073 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE { 4074 if (Suppressed) return; 4075 if (SelID == -1) 4076 S.Diag(Loc, DiagID) << T; 4077 else 4078 S.Diag(Loc, DiagID) << SelID << T; 4079 } 4080 } Diagnoser(DiagID, SelID); 4081 4082 return RequireNonAbstractType(Loc, T, Diagnoser); 4083 } 4084 4085 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4086 TypeDiagnoser &Diagnoser) { 4087 if (!getLangOpts().CPlusPlus) 4088 return false; 4089 4090 if (const ArrayType *AT = Context.getAsArrayType(T)) 4091 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4092 4093 if (const PointerType *PT = T->getAs<PointerType>()) { 4094 // Find the innermost pointer type. 4095 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4096 PT = T; 4097 4098 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4099 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4100 } 4101 4102 const RecordType *RT = T->getAs<RecordType>(); 4103 if (!RT) 4104 return false; 4105 4106 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4107 4108 // We can't answer whether something is abstract until it has a 4109 // definition. If it's currently being defined, we'll walk back 4110 // over all the declarations when we have a full definition. 4111 const CXXRecordDecl *Def = RD->getDefinition(); 4112 if (!Def || Def->isBeingDefined()) 4113 return false; 4114 4115 if (!RD->isAbstract()) 4116 return false; 4117 4118 Diagnoser.diagnose(*this, Loc, T); 4119 DiagnoseAbstractType(RD); 4120 4121 return true; 4122 } 4123 4124 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4125 // Check if we've already emitted the list of pure virtual functions 4126 // for this class. 4127 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4128 return; 4129 4130 // If the diagnostic is suppressed, don't emit the notes. We're only 4131 // going to emit them once, so try to attach them to a diagnostic we're 4132 // actually going to show. 4133 if (Diags.isLastDiagnosticIgnored()) 4134 return; 4135 4136 CXXFinalOverriderMap FinalOverriders; 4137 RD->getFinalOverriders(FinalOverriders); 4138 4139 // Keep a set of seen pure methods so we won't diagnose the same method 4140 // more than once. 4141 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4142 4143 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4144 MEnd = FinalOverriders.end(); 4145 M != MEnd; 4146 ++M) { 4147 for (OverridingMethods::iterator SO = M->second.begin(), 4148 SOEnd = M->second.end(); 4149 SO != SOEnd; ++SO) { 4150 // C++ [class.abstract]p4: 4151 // A class is abstract if it contains or inherits at least one 4152 // pure virtual function for which the final overrider is pure 4153 // virtual. 4154 4155 // 4156 if (SO->second.size() != 1) 4157 continue; 4158 4159 if (!SO->second.front().Method->isPure()) 4160 continue; 4161 4162 if (!SeenPureMethods.insert(SO->second.front().Method)) 4163 continue; 4164 4165 Diag(SO->second.front().Method->getLocation(), 4166 diag::note_pure_virtual_function) 4167 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4168 } 4169 } 4170 4171 if (!PureVirtualClassDiagSet) 4172 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4173 PureVirtualClassDiagSet->insert(RD); 4174 } 4175 4176 namespace { 4177 struct AbstractUsageInfo { 4178 Sema &S; 4179 CXXRecordDecl *Record; 4180 CanQualType AbstractType; 4181 bool Invalid; 4182 4183 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4184 : S(S), Record(Record), 4185 AbstractType(S.Context.getCanonicalType( 4186 S.Context.getTypeDeclType(Record))), 4187 Invalid(false) {} 4188 4189 void DiagnoseAbstractType() { 4190 if (Invalid) return; 4191 S.DiagnoseAbstractType(Record); 4192 Invalid = true; 4193 } 4194 4195 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4196 }; 4197 4198 struct CheckAbstractUsage { 4199 AbstractUsageInfo &Info; 4200 const NamedDecl *Ctx; 4201 4202 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4203 : Info(Info), Ctx(Ctx) {} 4204 4205 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4206 switch (TL.getTypeLocClass()) { 4207 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4208 #define TYPELOC(CLASS, PARENT) \ 4209 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4210 #include "clang/AST/TypeLocNodes.def" 4211 } 4212 } 4213 4214 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4215 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 4216 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4217 if (!TL.getArg(I)) 4218 continue; 4219 4220 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 4221 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4222 } 4223 } 4224 4225 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4226 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4227 } 4228 4229 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4230 // Visit the type parameters from a permissive context. 4231 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4232 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4233 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4234 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4235 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4236 // TODO: other template argument types? 4237 } 4238 } 4239 4240 // Visit pointee types from a permissive context. 4241 #define CheckPolymorphic(Type) \ 4242 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4243 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4244 } 4245 CheckPolymorphic(PointerTypeLoc) 4246 CheckPolymorphic(ReferenceTypeLoc) 4247 CheckPolymorphic(MemberPointerTypeLoc) 4248 CheckPolymorphic(BlockPointerTypeLoc) 4249 CheckPolymorphic(AtomicTypeLoc) 4250 4251 /// Handle all the types we haven't given a more specific 4252 /// implementation for above. 4253 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4254 // Every other kind of type that we haven't called out already 4255 // that has an inner type is either (1) sugar or (2) contains that 4256 // inner type in some way as a subobject. 4257 if (TypeLoc Next = TL.getNextTypeLoc()) 4258 return Visit(Next, Sel); 4259 4260 // If there's no inner type and we're in a permissive context, 4261 // don't diagnose. 4262 if (Sel == Sema::AbstractNone) return; 4263 4264 // Check whether the type matches the abstract type. 4265 QualType T = TL.getType(); 4266 if (T->isArrayType()) { 4267 Sel = Sema::AbstractArrayType; 4268 T = Info.S.Context.getBaseElementType(T); 4269 } 4270 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4271 if (CT != Info.AbstractType) return; 4272 4273 // It matched; do some magic. 4274 if (Sel == Sema::AbstractArrayType) { 4275 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4276 << T << TL.getSourceRange(); 4277 } else { 4278 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4279 << Sel << T << TL.getSourceRange(); 4280 } 4281 Info.DiagnoseAbstractType(); 4282 } 4283 }; 4284 4285 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4286 Sema::AbstractDiagSelID Sel) { 4287 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4288 } 4289 4290 } 4291 4292 /// Check for invalid uses of an abstract type in a method declaration. 4293 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4294 CXXMethodDecl *MD) { 4295 // No need to do the check on definitions, which require that 4296 // the return/param types be complete. 4297 if (MD->doesThisDeclarationHaveABody()) 4298 return; 4299 4300 // For safety's sake, just ignore it if we don't have type source 4301 // information. This should never happen for non-implicit methods, 4302 // but... 4303 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4304 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4305 } 4306 4307 /// Check for invalid uses of an abstract type within a class definition. 4308 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4309 CXXRecordDecl *RD) { 4310 for (CXXRecordDecl::decl_iterator 4311 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 4312 Decl *D = *I; 4313 if (D->isImplicit()) continue; 4314 4315 // Methods and method templates. 4316 if (isa<CXXMethodDecl>(D)) { 4317 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4318 } else if (isa<FunctionTemplateDecl>(D)) { 4319 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4320 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4321 4322 // Fields and static variables. 4323 } else if (isa<FieldDecl>(D)) { 4324 FieldDecl *FD = cast<FieldDecl>(D); 4325 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4326 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4327 } else if (isa<VarDecl>(D)) { 4328 VarDecl *VD = cast<VarDecl>(D); 4329 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4330 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4331 4332 // Nested classes and class templates. 4333 } else if (isa<CXXRecordDecl>(D)) { 4334 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4335 } else if (isa<ClassTemplateDecl>(D)) { 4336 CheckAbstractClassUsage(Info, 4337 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4338 } 4339 } 4340 } 4341 4342 /// \brief Perform semantic checks on a class definition that has been 4343 /// completing, introducing implicitly-declared members, checking for 4344 /// abstract types, etc. 4345 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4346 if (!Record) 4347 return; 4348 4349 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4350 AbstractUsageInfo Info(*this, Record); 4351 CheckAbstractClassUsage(Info, Record); 4352 } 4353 4354 // If this is not an aggregate type and has no user-declared constructor, 4355 // complain about any non-static data members of reference or const scalar 4356 // type, since they will never get initializers. 4357 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4358 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4359 !Record->isLambda()) { 4360 bool Complained = false; 4361 for (RecordDecl::field_iterator F = Record->field_begin(), 4362 FEnd = Record->field_end(); 4363 F != FEnd; ++F) { 4364 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4365 continue; 4366 4367 if (F->getType()->isReferenceType() || 4368 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4369 if (!Complained) { 4370 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4371 << Record->getTagKind() << Record; 4372 Complained = true; 4373 } 4374 4375 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4376 << F->getType()->isReferenceType() 4377 << F->getDeclName(); 4378 } 4379 } 4380 } 4381 4382 if (Record->isDynamicClass() && !Record->isDependentType()) 4383 DynamicClasses.push_back(Record); 4384 4385 if (Record->getIdentifier()) { 4386 // C++ [class.mem]p13: 4387 // If T is the name of a class, then each of the following shall have a 4388 // name different from T: 4389 // - every member of every anonymous union that is a member of class T. 4390 // 4391 // C++ [class.mem]p14: 4392 // In addition, if class T has a user-declared constructor (12.1), every 4393 // non-static data member of class T shall have a name different from T. 4394 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4395 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4396 ++I) { 4397 NamedDecl *D = *I; 4398 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4399 isa<IndirectFieldDecl>(D)) { 4400 Diag(D->getLocation(), diag::err_member_name_of_class) 4401 << D->getDeclName(); 4402 break; 4403 } 4404 } 4405 } 4406 4407 // Warn if the class has virtual methods but non-virtual public destructor. 4408 if (Record->isPolymorphic() && !Record->isDependentType()) { 4409 CXXDestructorDecl *dtor = Record->getDestructor(); 4410 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 4411 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4412 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4413 } 4414 4415 if (Record->isAbstract()) { 4416 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4417 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4418 << FA->isSpelledAsSealed(); 4419 DiagnoseAbstractType(Record); 4420 } 4421 } 4422 4423 if (!Record->isDependentType()) { 4424 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4425 MEnd = Record->method_end(); 4426 M != MEnd; ++M) { 4427 // See if a method overloads virtual methods in a base 4428 // class without overriding any. 4429 if (!M->isStatic()) 4430 DiagnoseHiddenVirtualMethods(*M); 4431 4432 // Check whether the explicitly-defaulted special members are valid. 4433 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4434 CheckExplicitlyDefaultedSpecialMember(*M); 4435 4436 // For an explicitly defaulted or deleted special member, we defer 4437 // determining triviality until the class is complete. That time is now! 4438 if (!M->isImplicit() && !M->isUserProvided()) { 4439 CXXSpecialMember CSM = getSpecialMember(*M); 4440 if (CSM != CXXInvalid) { 4441 M->setTrivial(SpecialMemberIsTrivial(*M, CSM)); 4442 4443 // Inform the class that we've finished declaring this member. 4444 Record->finishedDefaultedOrDeletedMember(*M); 4445 } 4446 } 4447 } 4448 } 4449 4450 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4451 // function that is not a constructor declares that member function to be 4452 // const. [...] The class of which that function is a member shall be 4453 // a literal type. 4454 // 4455 // If the class has virtual bases, any constexpr members will already have 4456 // been diagnosed by the checks performed on the member declaration, so 4457 // suppress this (less useful) diagnostic. 4458 // 4459 // We delay this until we know whether an explicitly-defaulted (or deleted) 4460 // destructor for the class is trivial. 4461 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4462 !Record->isLiteral() && !Record->getNumVBases()) { 4463 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4464 MEnd = Record->method_end(); 4465 M != MEnd; ++M) { 4466 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 4467 switch (Record->getTemplateSpecializationKind()) { 4468 case TSK_ImplicitInstantiation: 4469 case TSK_ExplicitInstantiationDeclaration: 4470 case TSK_ExplicitInstantiationDefinition: 4471 // If a template instantiates to a non-literal type, but its members 4472 // instantiate to constexpr functions, the template is technically 4473 // ill-formed, but we allow it for sanity. 4474 continue; 4475 4476 case TSK_Undeclared: 4477 case TSK_ExplicitSpecialization: 4478 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4479 diag::err_constexpr_method_non_literal); 4480 break; 4481 } 4482 4483 // Only produce one error per class. 4484 break; 4485 } 4486 } 4487 } 4488 4489 // Check to see if we're trying to lay out a struct using the ms_struct 4490 // attribute that is dynamic. 4491 if (Record->isMsStruct(Context) && Record->isDynamicClass()) { 4492 Diag(Record->getLocation(), diag::warn_pragma_ms_struct_failed); 4493 Record->dropAttr<MsStructAttr>(); 4494 } 4495 4496 // Declare inheriting constructors. We do this eagerly here because: 4497 // - The standard requires an eager diagnostic for conflicting inheriting 4498 // constructors from different classes. 4499 // - The lazy declaration of the other implicit constructors is so as to not 4500 // waste space and performance on classes that are not meant to be 4501 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4502 // have inheriting constructors. 4503 DeclareInheritingConstructors(Record); 4504 } 4505 4506 /// Is the special member function which would be selected to perform the 4507 /// specified operation on the specified class type a constexpr constructor? 4508 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4509 Sema::CXXSpecialMember CSM, 4510 bool ConstArg) { 4511 Sema::SpecialMemberOverloadResult *SMOR = 4512 S.LookupSpecialMember(ClassDecl, CSM, ConstArg, 4513 false, false, false, false); 4514 if (!SMOR || !SMOR->getMethod()) 4515 // A constructor we wouldn't select can't be "involved in initializing" 4516 // anything. 4517 return true; 4518 return SMOR->getMethod()->isConstexpr(); 4519 } 4520 4521 /// Determine whether the specified special member function would be constexpr 4522 /// if it were implicitly defined. 4523 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4524 Sema::CXXSpecialMember CSM, 4525 bool ConstArg) { 4526 if (!S.getLangOpts().CPlusPlus11) 4527 return false; 4528 4529 // C++11 [dcl.constexpr]p4: 4530 // In the definition of a constexpr constructor [...] 4531 bool Ctor = true; 4532 switch (CSM) { 4533 case Sema::CXXDefaultConstructor: 4534 // Since default constructor lookup is essentially trivial (and cannot 4535 // involve, for instance, template instantiation), we compute whether a 4536 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4537 // 4538 // This is important for performance; we need to know whether the default 4539 // constructor is constexpr to determine whether the type is a literal type. 4540 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4541 4542 case Sema::CXXCopyConstructor: 4543 case Sema::CXXMoveConstructor: 4544 // For copy or move constructors, we need to perform overload resolution. 4545 break; 4546 4547 case Sema::CXXCopyAssignment: 4548 case Sema::CXXMoveAssignment: 4549 if (!S.getLangOpts().CPlusPlus1y) 4550 return false; 4551 // In C++1y, we need to perform overload resolution. 4552 Ctor = false; 4553 break; 4554 4555 case Sema::CXXDestructor: 4556 case Sema::CXXInvalid: 4557 return false; 4558 } 4559 4560 // -- if the class is a non-empty union, or for each non-empty anonymous 4561 // union member of a non-union class, exactly one non-static data member 4562 // shall be initialized; [DR1359] 4563 // 4564 // If we squint, this is guaranteed, since exactly one non-static data member 4565 // will be initialized (if the constructor isn't deleted), we just don't know 4566 // which one. 4567 if (Ctor && ClassDecl->isUnion()) 4568 return true; 4569 4570 // -- the class shall not have any virtual base classes; 4571 if (Ctor && ClassDecl->getNumVBases()) 4572 return false; 4573 4574 // C++1y [class.copy]p26: 4575 // -- [the class] is a literal type, and 4576 if (!Ctor && !ClassDecl->isLiteral()) 4577 return false; 4578 4579 // -- every constructor involved in initializing [...] base class 4580 // sub-objects shall be a constexpr constructor; 4581 // -- the assignment operator selected to copy/move each direct base 4582 // class is a constexpr function, and 4583 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4584 BEnd = ClassDecl->bases_end(); 4585 B != BEnd; ++B) { 4586 const RecordType *BaseType = B->getType()->getAs<RecordType>(); 4587 if (!BaseType) continue; 4588 4589 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4590 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg)) 4591 return false; 4592 } 4593 4594 // -- every constructor involved in initializing non-static data members 4595 // [...] shall be a constexpr constructor; 4596 // -- every non-static data member and base class sub-object shall be 4597 // initialized 4598 // -- for each non-stastic data member of X that is of class type (or array 4599 // thereof), the assignment operator selected to copy/move that member is 4600 // a constexpr function 4601 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4602 FEnd = ClassDecl->field_end(); 4603 F != FEnd; ++F) { 4604 if (F->isInvalidDecl()) 4605 continue; 4606 if (const RecordType *RecordTy = 4607 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4608 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4609 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg)) 4610 return false; 4611 } 4612 } 4613 4614 // All OK, it's constexpr! 4615 return true; 4616 } 4617 4618 static Sema::ImplicitExceptionSpecification 4619 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4620 switch (S.getSpecialMember(MD)) { 4621 case Sema::CXXDefaultConstructor: 4622 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4623 case Sema::CXXCopyConstructor: 4624 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4625 case Sema::CXXCopyAssignment: 4626 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4627 case Sema::CXXMoveConstructor: 4628 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4629 case Sema::CXXMoveAssignment: 4630 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4631 case Sema::CXXDestructor: 4632 return S.ComputeDefaultedDtorExceptionSpec(MD); 4633 case Sema::CXXInvalid: 4634 break; 4635 } 4636 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4637 "only special members have implicit exception specs"); 4638 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4639 } 4640 4641 static void 4642 updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT, 4643 const Sema::ImplicitExceptionSpecification &ExceptSpec) { 4644 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4645 ExceptSpec.getEPI(EPI); 4646 FD->setType(S.Context.getFunctionType(FPT->getResultType(), 4647 FPT->getArgTypes(), EPI)); 4648 } 4649 4650 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 4651 CXXMethodDecl *MD) { 4652 FunctionProtoType::ExtProtoInfo EPI; 4653 4654 // Build an exception specification pointing back at this member. 4655 EPI.ExceptionSpecType = EST_Unevaluated; 4656 EPI.ExceptionSpecDecl = MD; 4657 4658 // Set the calling convention to the default for C++ instance methods. 4659 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 4660 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4661 /*IsCXXMethod=*/true)); 4662 return EPI; 4663 } 4664 4665 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4666 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4667 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4668 return; 4669 4670 // Evaluate the exception specification. 4671 ImplicitExceptionSpecification ExceptSpec = 4672 computeImplicitExceptionSpec(*this, Loc, MD); 4673 4674 // Update the type of the special member to use it. 4675 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4676 4677 // A user-provided destructor can be defined outside the class. When that 4678 // happens, be sure to update the exception specification on both 4679 // declarations. 4680 const FunctionProtoType *CanonicalFPT = 4681 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4682 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4683 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4684 CanonicalFPT, ExceptSpec); 4685 } 4686 4687 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4688 CXXRecordDecl *RD = MD->getParent(); 4689 CXXSpecialMember CSM = getSpecialMember(MD); 4690 4691 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4692 "not an explicitly-defaulted special member"); 4693 4694 // Whether this was the first-declared instance of the constructor. 4695 // This affects whether we implicitly add an exception spec and constexpr. 4696 bool First = MD == MD->getCanonicalDecl(); 4697 4698 bool HadError = false; 4699 4700 // C++11 [dcl.fct.def.default]p1: 4701 // A function that is explicitly defaulted shall 4702 // -- be a special member function (checked elsewhere), 4703 // -- have the same type (except for ref-qualifiers, and except that a 4704 // copy operation can take a non-const reference) as an implicit 4705 // declaration, and 4706 // -- not have default arguments. 4707 unsigned ExpectedParams = 1; 4708 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4709 ExpectedParams = 0; 4710 if (MD->getNumParams() != ExpectedParams) { 4711 // This also checks for default arguments: a copy or move constructor with a 4712 // default argument is classified as a default constructor, and assignment 4713 // operations and destructors can't have default arguments. 4714 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4715 << CSM << MD->getSourceRange(); 4716 HadError = true; 4717 } else if (MD->isVariadic()) { 4718 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4719 << CSM << MD->getSourceRange(); 4720 HadError = true; 4721 } 4722 4723 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4724 4725 bool CanHaveConstParam = false; 4726 if (CSM == CXXCopyConstructor) 4727 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4728 else if (CSM == CXXCopyAssignment) 4729 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4730 4731 QualType ReturnType = Context.VoidTy; 4732 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4733 // Check for return type matching. 4734 ReturnType = Type->getResultType(); 4735 QualType ExpectedReturnType = 4736 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4737 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4738 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4739 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4740 HadError = true; 4741 } 4742 4743 // A defaulted special member cannot have cv-qualifiers. 4744 if (Type->getTypeQuals()) { 4745 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4746 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y; 4747 HadError = true; 4748 } 4749 } 4750 4751 // Check for parameter type matching. 4752 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType(); 4753 bool HasConstParam = false; 4754 if (ExpectedParams && ArgType->isReferenceType()) { 4755 // Argument must be reference to possibly-const T. 4756 QualType ReferentType = ArgType->getPointeeType(); 4757 HasConstParam = ReferentType.isConstQualified(); 4758 4759 if (ReferentType.isVolatileQualified()) { 4760 Diag(MD->getLocation(), 4761 diag::err_defaulted_special_member_volatile_param) << CSM; 4762 HadError = true; 4763 } 4764 4765 if (HasConstParam && !CanHaveConstParam) { 4766 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4767 Diag(MD->getLocation(), 4768 diag::err_defaulted_special_member_copy_const_param) 4769 << (CSM == CXXCopyAssignment); 4770 // FIXME: Explain why this special member can't be const. 4771 } else { 4772 Diag(MD->getLocation(), 4773 diag::err_defaulted_special_member_move_const_param) 4774 << (CSM == CXXMoveAssignment); 4775 } 4776 HadError = true; 4777 } 4778 } else if (ExpectedParams) { 4779 // A copy assignment operator can take its argument by value, but a 4780 // defaulted one cannot. 4781 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4782 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4783 HadError = true; 4784 } 4785 4786 // C++11 [dcl.fct.def.default]p2: 4787 // An explicitly-defaulted function may be declared constexpr only if it 4788 // would have been implicitly declared as constexpr, 4789 // Do not apply this rule to members of class templates, since core issue 1358 4790 // makes such functions always instantiate to constexpr functions. For 4791 // functions which cannot be constexpr (for non-constructors in C++11 and for 4792 // destructors in C++1y), this is checked elsewhere. 4793 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4794 HasConstParam); 4795 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD) 4796 : isa<CXXConstructorDecl>(MD)) && 4797 MD->isConstexpr() && !Constexpr && 4798 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4799 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4800 // FIXME: Explain why the special member can't be constexpr. 4801 HadError = true; 4802 } 4803 4804 // and may have an explicit exception-specification only if it is compatible 4805 // with the exception-specification on the implicit declaration. 4806 if (Type->hasExceptionSpec()) { 4807 // Delay the check if this is the first declaration of the special member, 4808 // since we may not have parsed some necessary in-class initializers yet. 4809 if (First) { 4810 // If the exception specification needs to be instantiated, do so now, 4811 // before we clobber it with an EST_Unevaluated specification below. 4812 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4813 InstantiateExceptionSpec(MD->getLocStart(), MD); 4814 Type = MD->getType()->getAs<FunctionProtoType>(); 4815 } 4816 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4817 } else 4818 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4819 } 4820 4821 // If a function is explicitly defaulted on its first declaration, 4822 if (First) { 4823 // -- it is implicitly considered to be constexpr if the implicit 4824 // definition would be, 4825 MD->setConstexpr(Constexpr); 4826 4827 // -- it is implicitly considered to have the same exception-specification 4828 // as if it had been implicitly declared, 4829 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4830 EPI.ExceptionSpecType = EST_Unevaluated; 4831 EPI.ExceptionSpecDecl = MD; 4832 MD->setType(Context.getFunctionType(ReturnType, 4833 ArrayRef<QualType>(&ArgType, 4834 ExpectedParams), 4835 EPI)); 4836 } 4837 4838 if (ShouldDeleteSpecialMember(MD, CSM)) { 4839 if (First) { 4840 SetDeclDeleted(MD, MD->getLocation()); 4841 } else { 4842 // C++11 [dcl.fct.def.default]p4: 4843 // [For a] user-provided explicitly-defaulted function [...] if such a 4844 // function is implicitly defined as deleted, the program is ill-formed. 4845 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4846 HadError = true; 4847 } 4848 } 4849 4850 if (HadError) 4851 MD->setInvalidDecl(); 4852 } 4853 4854 /// Check whether the exception specification provided for an 4855 /// explicitly-defaulted special member matches the exception specification 4856 /// that would have been generated for an implicit special member, per 4857 /// C++11 [dcl.fct.def.default]p2. 4858 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 4859 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 4860 // Compute the implicit exception specification. 4861 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4862 /*IsCXXMethod=*/true); 4863 FunctionProtoType::ExtProtoInfo EPI(CC); 4864 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4865 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 4866 Context.getFunctionType(Context.VoidTy, None, EPI)); 4867 4868 // Ensure that it matches. 4869 CheckEquivalentExceptionSpec( 4870 PDiag(diag::err_incorrect_defaulted_exception_spec) 4871 << getSpecialMember(MD), PDiag(), 4872 ImplicitType, SourceLocation(), 4873 SpecifiedType, MD->getLocation()); 4874 } 4875 4876 void Sema::CheckDelayedMemberExceptionSpecs() { 4877 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>, 4878 2> Checks; 4879 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs; 4880 4881 std::swap(Checks, DelayedDestructorExceptionSpecChecks); 4882 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 4883 4884 // Perform any deferred checking of exception specifications for virtual 4885 // destructors. 4886 for (unsigned i = 0, e = Checks.size(); i != e; ++i) { 4887 const CXXDestructorDecl *Dtor = Checks[i].first; 4888 assert(!Dtor->getParent()->isDependentType() && 4889 "Should not ever add destructors of templates into the list."); 4890 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second); 4891 } 4892 4893 // Check that any explicitly-defaulted methods have exception specifications 4894 // compatible with their implicit exception specifications. 4895 for (unsigned I = 0, N = Specs.size(); I != N; ++I) 4896 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first, 4897 Specs[I].second); 4898 } 4899 4900 namespace { 4901 struct SpecialMemberDeletionInfo { 4902 Sema &S; 4903 CXXMethodDecl *MD; 4904 Sema::CXXSpecialMember CSM; 4905 bool Diagnose; 4906 4907 // Properties of the special member, computed for convenience. 4908 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg; 4909 SourceLocation Loc; 4910 4911 bool AllFieldsAreConst; 4912 4913 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4914 Sema::CXXSpecialMember CSM, bool Diagnose) 4915 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4916 IsConstructor(false), IsAssignment(false), IsMove(false), 4917 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()), 4918 AllFieldsAreConst(true) { 4919 switch (CSM) { 4920 case Sema::CXXDefaultConstructor: 4921 case Sema::CXXCopyConstructor: 4922 IsConstructor = true; 4923 break; 4924 case Sema::CXXMoveConstructor: 4925 IsConstructor = true; 4926 IsMove = true; 4927 break; 4928 case Sema::CXXCopyAssignment: 4929 IsAssignment = true; 4930 break; 4931 case Sema::CXXMoveAssignment: 4932 IsAssignment = true; 4933 IsMove = true; 4934 break; 4935 case Sema::CXXDestructor: 4936 break; 4937 case Sema::CXXInvalid: 4938 llvm_unreachable("invalid special member kind"); 4939 } 4940 4941 if (MD->getNumParams()) { 4942 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4943 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified(); 4944 } 4945 } 4946 4947 bool inUnion() const { return MD->getParent()->isUnion(); } 4948 4949 /// Look up the corresponding special member in the given class. 4950 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4951 unsigned Quals) { 4952 unsigned TQ = MD->getTypeQualifiers(); 4953 // cv-qualifiers on class members don't affect default ctor / dtor calls. 4954 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4955 Quals = 0; 4956 return S.LookupSpecialMember(Class, CSM, 4957 ConstArg || (Quals & Qualifiers::Const), 4958 VolatileArg || (Quals & Qualifiers::Volatile), 4959 MD->getRefQualifier() == RQ_RValue, 4960 TQ & Qualifiers::Const, 4961 TQ & Qualifiers::Volatile); 4962 } 4963 4964 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4965 4966 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4967 bool shouldDeleteForField(FieldDecl *FD); 4968 bool shouldDeleteForAllConstMembers(); 4969 4970 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4971 unsigned Quals); 4972 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4973 Sema::SpecialMemberOverloadResult *SMOR, 4974 bool IsDtorCallInCtor); 4975 4976 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4977 }; 4978 } 4979 4980 /// Is the given special member inaccessible when used on the given 4981 /// sub-object. 4982 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4983 CXXMethodDecl *target) { 4984 /// If we're operating on a base class, the object type is the 4985 /// type of this special member. 4986 QualType objectTy; 4987 AccessSpecifier access = target->getAccess(); 4988 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 4989 objectTy = S.Context.getTypeDeclType(MD->getParent()); 4990 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 4991 4992 // If we're operating on a field, the object type is the type of the field. 4993 } else { 4994 objectTy = S.Context.getTypeDeclType(target->getParent()); 4995 } 4996 4997 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 4998 } 4999 5000 /// Check whether we should delete a special member due to the implicit 5001 /// definition containing a call to a special member of a subobject. 5002 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5003 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5004 bool IsDtorCallInCtor) { 5005 CXXMethodDecl *Decl = SMOR->getMethod(); 5006 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5007 5008 int DiagKind = -1; 5009 5010 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5011 DiagKind = !Decl ? 0 : 1; 5012 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5013 DiagKind = 2; 5014 else if (!isAccessible(Subobj, Decl)) 5015 DiagKind = 3; 5016 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5017 !Decl->isTrivial()) { 5018 // A member of a union must have a trivial corresponding special member. 5019 // As a weird special case, a destructor call from a union's constructor 5020 // must be accessible and non-deleted, but need not be trivial. Such a 5021 // destructor is never actually called, but is semantically checked as 5022 // if it were. 5023 DiagKind = 4; 5024 } 5025 5026 if (DiagKind == -1) 5027 return false; 5028 5029 if (Diagnose) { 5030 if (Field) { 5031 S.Diag(Field->getLocation(), 5032 diag::note_deleted_special_member_class_subobject) 5033 << CSM << MD->getParent() << /*IsField*/true 5034 << Field << DiagKind << IsDtorCallInCtor; 5035 } else { 5036 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5037 S.Diag(Base->getLocStart(), 5038 diag::note_deleted_special_member_class_subobject) 5039 << CSM << MD->getParent() << /*IsField*/false 5040 << Base->getType() << DiagKind << IsDtorCallInCtor; 5041 } 5042 5043 if (DiagKind == 1) 5044 S.NoteDeletedFunction(Decl); 5045 // FIXME: Explain inaccessibility if DiagKind == 3. 5046 } 5047 5048 return true; 5049 } 5050 5051 /// Check whether we should delete a special member function due to having a 5052 /// direct or virtual base class or non-static data member of class type M. 5053 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5054 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5055 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5056 5057 // C++11 [class.ctor]p5: 5058 // -- any direct or virtual base class, or non-static data member with no 5059 // brace-or-equal-initializer, has class type M (or array thereof) and 5060 // either M has no default constructor or overload resolution as applied 5061 // to M's default constructor results in an ambiguity or in a function 5062 // that is deleted or inaccessible 5063 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5064 // -- a direct or virtual base class B that cannot be copied/moved because 5065 // overload resolution, as applied to B's corresponding special member, 5066 // results in an ambiguity or a function that is deleted or inaccessible 5067 // from the defaulted special member 5068 // C++11 [class.dtor]p5: 5069 // -- any direct or virtual base class [...] has a type with a destructor 5070 // that is deleted or inaccessible 5071 if (!(CSM == Sema::CXXDefaultConstructor && 5072 Field && Field->hasInClassInitializer()) && 5073 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false)) 5074 return true; 5075 5076 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5077 // -- any direct or virtual base class or non-static data member has a 5078 // type with a destructor that is deleted or inaccessible 5079 if (IsConstructor) { 5080 Sema::SpecialMemberOverloadResult *SMOR = 5081 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5082 false, false, false, false, false); 5083 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5084 return true; 5085 } 5086 5087 return false; 5088 } 5089 5090 /// Check whether we should delete a special member function due to the class 5091 /// having a particular direct or virtual base class. 5092 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5093 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5094 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5095 } 5096 5097 /// Check whether we should delete a special member function due to the class 5098 /// having a particular non-static data member. 5099 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5100 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5101 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5102 5103 if (CSM == Sema::CXXDefaultConstructor) { 5104 // For a default constructor, all references must be initialized in-class 5105 // and, if a union, it must have a non-const member. 5106 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5107 if (Diagnose) 5108 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5109 << MD->getParent() << FD << FieldType << /*Reference*/0; 5110 return true; 5111 } 5112 // C++11 [class.ctor]p5: any non-variant non-static data member of 5113 // const-qualified type (or array thereof) with no 5114 // brace-or-equal-initializer does not have a user-provided default 5115 // constructor. 5116 if (!inUnion() && FieldType.isConstQualified() && 5117 !FD->hasInClassInitializer() && 5118 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5119 if (Diagnose) 5120 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5121 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5122 return true; 5123 } 5124 5125 if (inUnion() && !FieldType.isConstQualified()) 5126 AllFieldsAreConst = false; 5127 } else if (CSM == Sema::CXXCopyConstructor) { 5128 // For a copy constructor, data members must not be of rvalue reference 5129 // type. 5130 if (FieldType->isRValueReferenceType()) { 5131 if (Diagnose) 5132 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5133 << MD->getParent() << FD << FieldType; 5134 return true; 5135 } 5136 } else if (IsAssignment) { 5137 // For an assignment operator, data members must not be of reference type. 5138 if (FieldType->isReferenceType()) { 5139 if (Diagnose) 5140 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5141 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5142 return true; 5143 } 5144 if (!FieldRecord && FieldType.isConstQualified()) { 5145 // C++11 [class.copy]p23: 5146 // -- a non-static data member of const non-class type (or array thereof) 5147 if (Diagnose) 5148 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5149 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5150 return true; 5151 } 5152 } 5153 5154 if (FieldRecord) { 5155 // Some additional restrictions exist on the variant members. 5156 if (!inUnion() && FieldRecord->isUnion() && 5157 FieldRecord->isAnonymousStructOrUnion()) { 5158 bool AllVariantFieldsAreConst = true; 5159 5160 // FIXME: Handle anonymous unions declared within anonymous unions. 5161 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 5162 UE = FieldRecord->field_end(); 5163 UI != UE; ++UI) { 5164 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5165 5166 if (!UnionFieldType.isConstQualified()) 5167 AllVariantFieldsAreConst = false; 5168 5169 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5170 if (UnionFieldRecord && 5171 shouldDeleteForClassSubobject(UnionFieldRecord, *UI, 5172 UnionFieldType.getCVRQualifiers())) 5173 return true; 5174 } 5175 5176 // At least one member in each anonymous union must be non-const 5177 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5178 FieldRecord->field_begin() != FieldRecord->field_end()) { 5179 if (Diagnose) 5180 S.Diag(FieldRecord->getLocation(), 5181 diag::note_deleted_default_ctor_all_const) 5182 << MD->getParent() << /*anonymous union*/1; 5183 return true; 5184 } 5185 5186 // Don't check the implicit member of the anonymous union type. 5187 // This is technically non-conformant, but sanity demands it. 5188 return false; 5189 } 5190 5191 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5192 FieldType.getCVRQualifiers())) 5193 return true; 5194 } 5195 5196 return false; 5197 } 5198 5199 /// C++11 [class.ctor] p5: 5200 /// A defaulted default constructor for a class X is defined as deleted if 5201 /// X is a union and all of its variant members are of const-qualified type. 5202 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5203 // This is a silly definition, because it gives an empty union a deleted 5204 // default constructor. Don't do that. 5205 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5206 (MD->getParent()->field_begin() != MD->getParent()->field_end())) { 5207 if (Diagnose) 5208 S.Diag(MD->getParent()->getLocation(), 5209 diag::note_deleted_default_ctor_all_const) 5210 << MD->getParent() << /*not anonymous union*/0; 5211 return true; 5212 } 5213 return false; 5214 } 5215 5216 /// Determine whether a defaulted special member function should be defined as 5217 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5218 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5219 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5220 bool Diagnose) { 5221 if (MD->isInvalidDecl()) 5222 return false; 5223 CXXRecordDecl *RD = MD->getParent(); 5224 assert(!RD->isDependentType() && "do deletion after instantiation"); 5225 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5226 return false; 5227 5228 // C++11 [expr.lambda.prim]p19: 5229 // The closure type associated with a lambda-expression has a 5230 // deleted (8.4.3) default constructor and a deleted copy 5231 // assignment operator. 5232 if (RD->isLambda() && 5233 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5234 if (Diagnose) 5235 Diag(RD->getLocation(), diag::note_lambda_decl); 5236 return true; 5237 } 5238 5239 // For an anonymous struct or union, the copy and assignment special members 5240 // will never be used, so skip the check. For an anonymous union declared at 5241 // namespace scope, the constructor and destructor are used. 5242 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5243 RD->isAnonymousStructOrUnion()) 5244 return false; 5245 5246 // C++11 [class.copy]p7, p18: 5247 // If the class definition declares a move constructor or move assignment 5248 // operator, an implicitly declared copy constructor or copy assignment 5249 // operator is defined as deleted. 5250 if (MD->isImplicit() && 5251 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5252 CXXMethodDecl *UserDeclaredMove = 0; 5253 5254 // In Microsoft mode, a user-declared move only causes the deletion of the 5255 // corresponding copy operation, not both copy operations. 5256 if (RD->hasUserDeclaredMoveConstructor() && 5257 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) { 5258 if (!Diagnose) return true; 5259 5260 // Find any user-declared move constructor. 5261 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 5262 E = RD->ctor_end(); I != E; ++I) { 5263 if (I->isMoveConstructor()) { 5264 UserDeclaredMove = *I; 5265 break; 5266 } 5267 } 5268 assert(UserDeclaredMove); 5269 } else if (RD->hasUserDeclaredMoveAssignment() && 5270 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) { 5271 if (!Diagnose) return true; 5272 5273 // Find any user-declared move assignment operator. 5274 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 5275 E = RD->method_end(); I != E; ++I) { 5276 if (I->isMoveAssignmentOperator()) { 5277 UserDeclaredMove = *I; 5278 break; 5279 } 5280 } 5281 assert(UserDeclaredMove); 5282 } 5283 5284 if (UserDeclaredMove) { 5285 Diag(UserDeclaredMove->getLocation(), 5286 diag::note_deleted_copy_user_declared_move) 5287 << (CSM == CXXCopyAssignment) << RD 5288 << UserDeclaredMove->isMoveAssignmentOperator(); 5289 return true; 5290 } 5291 } 5292 5293 // Do access control from the special member function 5294 ContextRAII MethodContext(*this, MD); 5295 5296 // C++11 [class.dtor]p5: 5297 // -- for a virtual destructor, lookup of the non-array deallocation function 5298 // results in an ambiguity or in a function that is deleted or inaccessible 5299 if (CSM == CXXDestructor && MD->isVirtual()) { 5300 FunctionDecl *OperatorDelete = 0; 5301 DeclarationName Name = 5302 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5303 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5304 OperatorDelete, false)) { 5305 if (Diagnose) 5306 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5307 return true; 5308 } 5309 } 5310 5311 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5312 5313 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5314 BE = RD->bases_end(); BI != BE; ++BI) 5315 if (!BI->isVirtual() && 5316 SMI.shouldDeleteForBase(BI)) 5317 return true; 5318 5319 // Per DR1611, do not consider virtual bases of constructors of abstract 5320 // classes, since we are not going to construct them. 5321 if (!RD->isAbstract() || !SMI.IsConstructor) { 5322 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 5323 BE = RD->vbases_end(); 5324 BI != BE; ++BI) 5325 if (SMI.shouldDeleteForBase(BI)) 5326 return true; 5327 } 5328 5329 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5330 FE = RD->field_end(); FI != FE; ++FI) 5331 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5332 SMI.shouldDeleteForField(*FI)) 5333 return true; 5334 5335 if (SMI.shouldDeleteForAllConstMembers()) 5336 return true; 5337 5338 return false; 5339 } 5340 5341 /// Perform lookup for a special member of the specified kind, and determine 5342 /// whether it is trivial. If the triviality can be determined without the 5343 /// lookup, skip it. This is intended for use when determining whether a 5344 /// special member of a containing object is trivial, and thus does not ever 5345 /// perform overload resolution for default constructors. 5346 /// 5347 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5348 /// member that was most likely to be intended to be trivial, if any. 5349 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5350 Sema::CXXSpecialMember CSM, unsigned Quals, 5351 CXXMethodDecl **Selected) { 5352 if (Selected) 5353 *Selected = 0; 5354 5355 switch (CSM) { 5356 case Sema::CXXInvalid: 5357 llvm_unreachable("not a special member"); 5358 5359 case Sema::CXXDefaultConstructor: 5360 // C++11 [class.ctor]p5: 5361 // A default constructor is trivial if: 5362 // - all the [direct subobjects] have trivial default constructors 5363 // 5364 // Note, no overload resolution is performed in this case. 5365 if (RD->hasTrivialDefaultConstructor()) 5366 return true; 5367 5368 if (Selected) { 5369 // If there's a default constructor which could have been trivial, dig it 5370 // out. Otherwise, if there's any user-provided default constructor, point 5371 // to that as an example of why there's not a trivial one. 5372 CXXConstructorDecl *DefCtor = 0; 5373 if (RD->needsImplicitDefaultConstructor()) 5374 S.DeclareImplicitDefaultConstructor(RD); 5375 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), 5376 CE = RD->ctor_end(); CI != CE; ++CI) { 5377 if (!CI->isDefaultConstructor()) 5378 continue; 5379 DefCtor = *CI; 5380 if (!DefCtor->isUserProvided()) 5381 break; 5382 } 5383 5384 *Selected = DefCtor; 5385 } 5386 5387 return false; 5388 5389 case Sema::CXXDestructor: 5390 // C++11 [class.dtor]p5: 5391 // A destructor is trivial if: 5392 // - all the direct [subobjects] have trivial destructors 5393 if (RD->hasTrivialDestructor()) 5394 return true; 5395 5396 if (Selected) { 5397 if (RD->needsImplicitDestructor()) 5398 S.DeclareImplicitDestructor(RD); 5399 *Selected = RD->getDestructor(); 5400 } 5401 5402 return false; 5403 5404 case Sema::CXXCopyConstructor: 5405 // C++11 [class.copy]p12: 5406 // A copy constructor is trivial if: 5407 // - the constructor selected to copy each direct [subobject] is trivial 5408 if (RD->hasTrivialCopyConstructor()) { 5409 if (Quals == Qualifiers::Const) 5410 // We must either select the trivial copy constructor or reach an 5411 // ambiguity; no need to actually perform overload resolution. 5412 return true; 5413 } else if (!Selected) { 5414 return false; 5415 } 5416 // In C++98, we are not supposed to perform overload resolution here, but we 5417 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5418 // cases like B as having a non-trivial copy constructor: 5419 // struct A { template<typename T> A(T&); }; 5420 // struct B { mutable A a; }; 5421 goto NeedOverloadResolution; 5422 5423 case Sema::CXXCopyAssignment: 5424 // C++11 [class.copy]p25: 5425 // A copy assignment operator is trivial if: 5426 // - the assignment operator selected to copy each direct [subobject] is 5427 // trivial 5428 if (RD->hasTrivialCopyAssignment()) { 5429 if (Quals == Qualifiers::Const) 5430 return true; 5431 } else if (!Selected) { 5432 return false; 5433 } 5434 // In C++98, we are not supposed to perform overload resolution here, but we 5435 // treat that as a language defect. 5436 goto NeedOverloadResolution; 5437 5438 case Sema::CXXMoveConstructor: 5439 case Sema::CXXMoveAssignment: 5440 NeedOverloadResolution: 5441 Sema::SpecialMemberOverloadResult *SMOR = 5442 S.LookupSpecialMember(RD, CSM, 5443 Quals & Qualifiers::Const, 5444 Quals & Qualifiers::Volatile, 5445 /*RValueThis*/false, /*ConstThis*/false, 5446 /*VolatileThis*/false); 5447 5448 // The standard doesn't describe how to behave if the lookup is ambiguous. 5449 // We treat it as not making the member non-trivial, just like the standard 5450 // mandates for the default constructor. This should rarely matter, because 5451 // the member will also be deleted. 5452 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5453 return true; 5454 5455 if (!SMOR->getMethod()) { 5456 assert(SMOR->getKind() == 5457 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5458 return false; 5459 } 5460 5461 // We deliberately don't check if we found a deleted special member. We're 5462 // not supposed to! 5463 if (Selected) 5464 *Selected = SMOR->getMethod(); 5465 return SMOR->getMethod()->isTrivial(); 5466 } 5467 5468 llvm_unreachable("unknown special method kind"); 5469 } 5470 5471 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5472 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end(); 5473 CI != CE; ++CI) 5474 if (!CI->isImplicit()) 5475 return *CI; 5476 5477 // Look for constructor templates. 5478 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5479 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5480 if (CXXConstructorDecl *CD = 5481 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5482 return CD; 5483 } 5484 5485 return 0; 5486 } 5487 5488 /// The kind of subobject we are checking for triviality. The values of this 5489 /// enumeration are used in diagnostics. 5490 enum TrivialSubobjectKind { 5491 /// The subobject is a base class. 5492 TSK_BaseClass, 5493 /// The subobject is a non-static data member. 5494 TSK_Field, 5495 /// The object is actually the complete object. 5496 TSK_CompleteObject 5497 }; 5498 5499 /// Check whether the special member selected for a given type would be trivial. 5500 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5501 QualType SubType, 5502 Sema::CXXSpecialMember CSM, 5503 TrivialSubobjectKind Kind, 5504 bool Diagnose) { 5505 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5506 if (!SubRD) 5507 return true; 5508 5509 CXXMethodDecl *Selected; 5510 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5511 Diagnose ? &Selected : 0)) 5512 return true; 5513 5514 if (Diagnose) { 5515 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5516 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5517 << Kind << SubType.getUnqualifiedType(); 5518 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5519 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5520 } else if (!Selected) 5521 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5522 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5523 else if (Selected->isUserProvided()) { 5524 if (Kind == TSK_CompleteObject) 5525 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5526 << Kind << SubType.getUnqualifiedType() << CSM; 5527 else { 5528 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5529 << Kind << SubType.getUnqualifiedType() << CSM; 5530 S.Diag(Selected->getLocation(), diag::note_declared_at); 5531 } 5532 } else { 5533 if (Kind != TSK_CompleteObject) 5534 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5535 << Kind << SubType.getUnqualifiedType() << CSM; 5536 5537 // Explain why the defaulted or deleted special member isn't trivial. 5538 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5539 } 5540 } 5541 5542 return false; 5543 } 5544 5545 /// Check whether the members of a class type allow a special member to be 5546 /// trivial. 5547 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5548 Sema::CXXSpecialMember CSM, 5549 bool ConstArg, bool Diagnose) { 5550 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5551 FE = RD->field_end(); FI != FE; ++FI) { 5552 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5553 continue; 5554 5555 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5556 5557 // Pretend anonymous struct or union members are members of this class. 5558 if (FI->isAnonymousStructOrUnion()) { 5559 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5560 CSM, ConstArg, Diagnose)) 5561 return false; 5562 continue; 5563 } 5564 5565 // C++11 [class.ctor]p5: 5566 // A default constructor is trivial if [...] 5567 // -- no non-static data member of its class has a 5568 // brace-or-equal-initializer 5569 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5570 if (Diagnose) 5571 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI; 5572 return false; 5573 } 5574 5575 // Objective C ARC 4.3.5: 5576 // [...] nontrivally ownership-qualified types are [...] not trivially 5577 // default constructible, copy constructible, move constructible, copy 5578 // assignable, move assignable, or destructible [...] 5579 if (S.getLangOpts().ObjCAutoRefCount && 5580 FieldType.hasNonTrivialObjCLifetime()) { 5581 if (Diagnose) 5582 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5583 << RD << FieldType.getObjCLifetime(); 5584 return false; 5585 } 5586 5587 if (ConstArg && !FI->isMutable()) 5588 FieldType.addConst(); 5589 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM, 5590 TSK_Field, Diagnose)) 5591 return false; 5592 } 5593 5594 return true; 5595 } 5596 5597 /// Diagnose why the specified class does not have a trivial special member of 5598 /// the given kind. 5599 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5600 QualType Ty = Context.getRecordType(RD); 5601 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) 5602 Ty.addConst(); 5603 5604 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM, 5605 TSK_CompleteObject, /*Diagnose*/true); 5606 } 5607 5608 /// Determine whether a defaulted or deleted special member function is trivial, 5609 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5610 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5611 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5612 bool Diagnose) { 5613 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5614 5615 CXXRecordDecl *RD = MD->getParent(); 5616 5617 bool ConstArg = false; 5618 5619 // C++11 [class.copy]p12, p25: 5620 // A [special member] is trivial if its declared parameter type is the same 5621 // as if it had been implicitly declared [...] 5622 switch (CSM) { 5623 case CXXDefaultConstructor: 5624 case CXXDestructor: 5625 // Trivial default constructors and destructors cannot have parameters. 5626 break; 5627 5628 case CXXCopyConstructor: 5629 case CXXCopyAssignment: { 5630 // Trivial copy operations always have const, non-volatile parameter types. 5631 ConstArg = true; 5632 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5633 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5634 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5635 if (Diagnose) 5636 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5637 << Param0->getSourceRange() << Param0->getType() 5638 << Context.getLValueReferenceType( 5639 Context.getRecordType(RD).withConst()); 5640 return false; 5641 } 5642 break; 5643 } 5644 5645 case CXXMoveConstructor: 5646 case CXXMoveAssignment: { 5647 // Trivial move operations always have non-cv-qualified parameters. 5648 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5649 const RValueReferenceType *RT = 5650 Param0->getType()->getAs<RValueReferenceType>(); 5651 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5652 if (Diagnose) 5653 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5654 << Param0->getSourceRange() << Param0->getType() 5655 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5656 return false; 5657 } 5658 break; 5659 } 5660 5661 case CXXInvalid: 5662 llvm_unreachable("not a special member"); 5663 } 5664 5665 // FIXME: We require that the parameter-declaration-clause is equivalent to 5666 // that of an implicit declaration, not just that the declared parameter type 5667 // matches, in order to prevent absuridities like a function simultaneously 5668 // being a trivial copy constructor and a non-trivial default constructor. 5669 // This issue has not yet been assigned a core issue number. 5670 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5671 if (Diagnose) 5672 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5673 diag::note_nontrivial_default_arg) 5674 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5675 return false; 5676 } 5677 if (MD->isVariadic()) { 5678 if (Diagnose) 5679 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5680 return false; 5681 } 5682 5683 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5684 // A copy/move [constructor or assignment operator] is trivial if 5685 // -- the [member] selected to copy/move each direct base class subobject 5686 // is trivial 5687 // 5688 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5689 // A [default constructor or destructor] is trivial if 5690 // -- all the direct base classes have trivial [default constructors or 5691 // destructors] 5692 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5693 BE = RD->bases_end(); BI != BE; ++BI) 5694 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), 5695 ConstArg ? BI->getType().withConst() 5696 : BI->getType(), 5697 CSM, TSK_BaseClass, Diagnose)) 5698 return false; 5699 5700 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5701 // A copy/move [constructor or assignment operator] for a class X is 5702 // trivial if 5703 // -- for each non-static data member of X that is of class type (or array 5704 // thereof), the constructor selected to copy/move that member is 5705 // trivial 5706 // 5707 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5708 // A [default constructor or destructor] is trivial if 5709 // -- for all of the non-static data members of its class that are of class 5710 // type (or array thereof), each such class has a trivial [default 5711 // constructor or destructor] 5712 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5713 return false; 5714 5715 // C++11 [class.dtor]p5: 5716 // A destructor is trivial if [...] 5717 // -- the destructor is not virtual 5718 if (CSM == CXXDestructor && MD->isVirtual()) { 5719 if (Diagnose) 5720 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5721 return false; 5722 } 5723 5724 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5725 // A [special member] for class X is trivial if [...] 5726 // -- class X has no virtual functions and no virtual base classes 5727 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5728 if (!Diagnose) 5729 return false; 5730 5731 if (RD->getNumVBases()) { 5732 // Check for virtual bases. We already know that the corresponding 5733 // member in all bases is trivial, so vbases must all be direct. 5734 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5735 assert(BS.isVirtual()); 5736 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5737 return false; 5738 } 5739 5740 // Must have a virtual method. 5741 for (CXXRecordDecl::method_iterator MI = RD->method_begin(), 5742 ME = RD->method_end(); MI != ME; ++MI) { 5743 if (MI->isVirtual()) { 5744 SourceLocation MLoc = MI->getLocStart(); 5745 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5746 return false; 5747 } 5748 } 5749 5750 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5751 } 5752 5753 // Looks like it's trivial! 5754 return true; 5755 } 5756 5757 /// \brief Data used with FindHiddenVirtualMethod 5758 namespace { 5759 struct FindHiddenVirtualMethodData { 5760 Sema *S; 5761 CXXMethodDecl *Method; 5762 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5763 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5764 }; 5765 } 5766 5767 /// \brief Check whether any most overriden method from MD in Methods 5768 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5769 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5770 if (MD->size_overridden_methods() == 0) 5771 return Methods.count(MD->getCanonicalDecl()); 5772 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5773 E = MD->end_overridden_methods(); 5774 I != E; ++I) 5775 if (CheckMostOverridenMethods(*I, Methods)) 5776 return true; 5777 return false; 5778 } 5779 5780 /// \brief Member lookup function that determines whether a given C++ 5781 /// method overloads virtual methods in a base class without overriding any, 5782 /// to be used with CXXRecordDecl::lookupInBases(). 5783 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5784 CXXBasePath &Path, 5785 void *UserData) { 5786 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5787 5788 FindHiddenVirtualMethodData &Data 5789 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5790 5791 DeclarationName Name = Data.Method->getDeclName(); 5792 assert(Name.getNameKind() == DeclarationName::Identifier); 5793 5794 bool foundSameNameMethod = false; 5795 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5796 for (Path.Decls = BaseRecord->lookup(Name); 5797 !Path.Decls.empty(); 5798 Path.Decls = Path.Decls.slice(1)) { 5799 NamedDecl *D = Path.Decls.front(); 5800 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5801 MD = MD->getCanonicalDecl(); 5802 foundSameNameMethod = true; 5803 // Interested only in hidden virtual methods. 5804 if (!MD->isVirtual()) 5805 continue; 5806 // If the method we are checking overrides a method from its base 5807 // don't warn about the other overloaded methods. 5808 if (!Data.S->IsOverload(Data.Method, MD, false)) 5809 return true; 5810 // Collect the overload only if its hidden. 5811 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5812 overloadedMethods.push_back(MD); 5813 } 5814 } 5815 5816 if (foundSameNameMethod) 5817 Data.OverloadedMethods.append(overloadedMethods.begin(), 5818 overloadedMethods.end()); 5819 return foundSameNameMethod; 5820 } 5821 5822 /// \brief Add the most overriden methods from MD to Methods 5823 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5824 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5825 if (MD->size_overridden_methods() == 0) 5826 Methods.insert(MD->getCanonicalDecl()); 5827 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5828 E = MD->end_overridden_methods(); 5829 I != E; ++I) 5830 AddMostOverridenMethods(*I, Methods); 5831 } 5832 5833 /// \brief Check if a method overloads virtual methods in a base class without 5834 /// overriding any. 5835 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 5836 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5837 if (!MD->getDeclName().isIdentifier()) 5838 return; 5839 5840 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5841 /*bool RecordPaths=*/false, 5842 /*bool DetectVirtual=*/false); 5843 FindHiddenVirtualMethodData Data; 5844 Data.Method = MD; 5845 Data.S = this; 5846 5847 // Keep the base methods that were overriden or introduced in the subclass 5848 // by 'using' in a set. A base method not in this set is hidden. 5849 CXXRecordDecl *DC = MD->getParent(); 5850 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5851 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5852 NamedDecl *ND = *I; 5853 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5854 ND = shad->getTargetDecl(); 5855 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5856 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5857 } 5858 5859 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 5860 OverloadedMethods = Data.OverloadedMethods; 5861 } 5862 5863 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 5864 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5865 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 5866 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 5867 PartialDiagnostic PD = PDiag( 5868 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5869 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 5870 Diag(overloadedMD->getLocation(), PD); 5871 } 5872 } 5873 5874 /// \brief Diagnose methods which overload virtual methods in a base class 5875 /// without overriding any. 5876 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 5877 if (MD->isInvalidDecl()) 5878 return; 5879 5880 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5881 MD->getLocation()) == DiagnosticsEngine::Ignored) 5882 return; 5883 5884 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5885 FindHiddenVirtualMethods(MD, OverloadedMethods); 5886 if (!OverloadedMethods.empty()) { 5887 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5888 << MD << (OverloadedMethods.size() > 1); 5889 5890 NoteHiddenVirtualMethods(MD, OverloadedMethods); 5891 } 5892 } 5893 5894 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5895 Decl *TagDecl, 5896 SourceLocation LBrac, 5897 SourceLocation RBrac, 5898 AttributeList *AttrList) { 5899 if (!TagDecl) 5900 return; 5901 5902 AdjustDeclIfTemplate(TagDecl); 5903 5904 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5905 if (l->getKind() != AttributeList::AT_Visibility) 5906 continue; 5907 l->setInvalid(); 5908 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5909 l->getName(); 5910 } 5911 5912 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5913 // strict aliasing violation! 5914 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5915 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5916 5917 CheckCompletedCXXClass( 5918 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5919 } 5920 5921 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5922 /// special functions, such as the default constructor, copy 5923 /// constructor, or destructor, to the given C++ class (C++ 5924 /// [special]p1). This routine can only be executed just before the 5925 /// definition of the class is complete. 5926 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5927 if (!ClassDecl->hasUserDeclaredConstructor()) 5928 ++ASTContext::NumImplicitDefaultConstructors; 5929 5930 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 5931 ++ASTContext::NumImplicitCopyConstructors; 5932 5933 // If the properties or semantics of the copy constructor couldn't be 5934 // determined while the class was being declared, force a declaration 5935 // of it now. 5936 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 5937 DeclareImplicitCopyConstructor(ClassDecl); 5938 } 5939 5940 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 5941 ++ASTContext::NumImplicitMoveConstructors; 5942 5943 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 5944 DeclareImplicitMoveConstructor(ClassDecl); 5945 } 5946 5947 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5948 ++ASTContext::NumImplicitCopyAssignmentOperators; 5949 5950 // If we have a dynamic class, then the copy assignment operator may be 5951 // virtual, so we have to declare it immediately. This ensures that, e.g., 5952 // it shows up in the right place in the vtable and that we diagnose 5953 // problems with the implicit exception specification. 5954 if (ClassDecl->isDynamicClass() || 5955 ClassDecl->needsOverloadResolutionForCopyAssignment()) 5956 DeclareImplicitCopyAssignment(ClassDecl); 5957 } 5958 5959 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 5960 ++ASTContext::NumImplicitMoveAssignmentOperators; 5961 5962 // Likewise for the move assignment operator. 5963 if (ClassDecl->isDynamicClass() || 5964 ClassDecl->needsOverloadResolutionForMoveAssignment()) 5965 DeclareImplicitMoveAssignment(ClassDecl); 5966 } 5967 5968 if (!ClassDecl->hasUserDeclaredDestructor()) { 5969 ++ASTContext::NumImplicitDestructors; 5970 5971 // If we have a dynamic class, then the destructor may be virtual, so we 5972 // have to declare the destructor immediately. This ensures that, e.g., it 5973 // shows up in the right place in the vtable and that we diagnose problems 5974 // with the implicit exception specification. 5975 if (ClassDecl->isDynamicClass() || 5976 ClassDecl->needsOverloadResolutionForDestructor()) 5977 DeclareImplicitDestructor(ClassDecl); 5978 } 5979 } 5980 5981 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5982 if (!D) 5983 return; 5984 5985 int NumParamList = D->getNumTemplateParameterLists(); 5986 for (int i = 0; i < NumParamList; i++) { 5987 TemplateParameterList* Params = D->getTemplateParameterList(i); 5988 for (TemplateParameterList::iterator Param = Params->begin(), 5989 ParamEnd = Params->end(); 5990 Param != ParamEnd; ++Param) { 5991 NamedDecl *Named = cast<NamedDecl>(*Param); 5992 if (Named->getDeclName()) { 5993 S->AddDecl(Named); 5994 IdResolver.AddDecl(Named); 5995 } 5996 } 5997 } 5998 } 5999 6000 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 6001 if (!D) 6002 return; 6003 6004 TemplateParameterList *Params = 0; 6005 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 6006 Params = Template->getTemplateParameters(); 6007 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 6008 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6009 Params = PartialSpec->getTemplateParameters(); 6010 else 6011 return; 6012 6013 for (TemplateParameterList::iterator Param = Params->begin(), 6014 ParamEnd = Params->end(); 6015 Param != ParamEnd; ++Param) { 6016 NamedDecl *Named = cast<NamedDecl>(*Param); 6017 if (Named->getDeclName()) { 6018 S->AddDecl(Named); 6019 IdResolver.AddDecl(Named); 6020 } 6021 } 6022 } 6023 6024 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6025 if (!RecordD) return; 6026 AdjustDeclIfTemplate(RecordD); 6027 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6028 PushDeclContext(S, Record); 6029 } 6030 6031 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6032 if (!RecordD) return; 6033 PopDeclContext(); 6034 } 6035 6036 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6037 /// parsing a top-level (non-nested) C++ class, and we are now 6038 /// parsing those parts of the given Method declaration that could 6039 /// not be parsed earlier (C++ [class.mem]p2), such as default 6040 /// arguments. This action should enter the scope of the given 6041 /// Method declaration as if we had just parsed the qualified method 6042 /// name. However, it should not bring the parameters into scope; 6043 /// that will be performed by ActOnDelayedCXXMethodParameter. 6044 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6045 } 6046 6047 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6048 /// C++ method declaration. We're (re-)introducing the given 6049 /// function parameter into scope for use in parsing later parts of 6050 /// the method declaration. For example, we could see an 6051 /// ActOnParamDefaultArgument event for this parameter. 6052 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6053 if (!ParamD) 6054 return; 6055 6056 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6057 6058 // If this parameter has an unparsed default argument, clear it out 6059 // to make way for the parsed default argument. 6060 if (Param->hasUnparsedDefaultArg()) 6061 Param->setDefaultArg(0); 6062 6063 S->AddDecl(Param); 6064 if (Param->getDeclName()) 6065 IdResolver.AddDecl(Param); 6066 } 6067 6068 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6069 /// processing the delayed method declaration for Method. The method 6070 /// declaration is now considered finished. There may be a separate 6071 /// ActOnStartOfFunctionDef action later (not necessarily 6072 /// immediately!) for this method, if it was also defined inside the 6073 /// class body. 6074 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6075 if (!MethodD) 6076 return; 6077 6078 AdjustDeclIfTemplate(MethodD); 6079 6080 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6081 6082 // Now that we have our default arguments, check the constructor 6083 // again. It could produce additional diagnostics or affect whether 6084 // the class has implicitly-declared destructors, among other 6085 // things. 6086 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6087 CheckConstructor(Constructor); 6088 6089 // Check the default arguments, which we may have added. 6090 if (!Method->isInvalidDecl()) 6091 CheckCXXDefaultArguments(Method); 6092 } 6093 6094 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6095 /// the well-formedness of the constructor declarator @p D with type @p 6096 /// R. If there are any errors in the declarator, this routine will 6097 /// emit diagnostics and set the invalid bit to true. In any case, the type 6098 /// will be updated to reflect a well-formed type for the constructor and 6099 /// returned. 6100 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6101 StorageClass &SC) { 6102 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6103 6104 // C++ [class.ctor]p3: 6105 // A constructor shall not be virtual (10.3) or static (9.4). A 6106 // constructor can be invoked for a const, volatile or const 6107 // volatile object. A constructor shall not be declared const, 6108 // volatile, or const volatile (9.3.2). 6109 if (isVirtual) { 6110 if (!D.isInvalidType()) 6111 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6112 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6113 << SourceRange(D.getIdentifierLoc()); 6114 D.setInvalidType(); 6115 } 6116 if (SC == SC_Static) { 6117 if (!D.isInvalidType()) 6118 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6119 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6120 << SourceRange(D.getIdentifierLoc()); 6121 D.setInvalidType(); 6122 SC = SC_None; 6123 } 6124 6125 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6126 if (FTI.TypeQuals != 0) { 6127 if (FTI.TypeQuals & Qualifiers::Const) 6128 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6129 << "const" << SourceRange(D.getIdentifierLoc()); 6130 if (FTI.TypeQuals & Qualifiers::Volatile) 6131 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6132 << "volatile" << SourceRange(D.getIdentifierLoc()); 6133 if (FTI.TypeQuals & Qualifiers::Restrict) 6134 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6135 << "restrict" << SourceRange(D.getIdentifierLoc()); 6136 D.setInvalidType(); 6137 } 6138 6139 // C++0x [class.ctor]p4: 6140 // A constructor shall not be declared with a ref-qualifier. 6141 if (FTI.hasRefQualifier()) { 6142 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6143 << FTI.RefQualifierIsLValueRef 6144 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6145 D.setInvalidType(); 6146 } 6147 6148 // Rebuild the function type "R" without any type qualifiers (in 6149 // case any of the errors above fired) and with "void" as the 6150 // return type, since constructors don't have return types. 6151 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6152 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 6153 return R; 6154 6155 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6156 EPI.TypeQuals = 0; 6157 EPI.RefQualifier = RQ_None; 6158 6159 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI); 6160 } 6161 6162 /// CheckConstructor - Checks a fully-formed constructor for 6163 /// well-formedness, issuing any diagnostics required. Returns true if 6164 /// the constructor declarator is invalid. 6165 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6166 CXXRecordDecl *ClassDecl 6167 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6168 if (!ClassDecl) 6169 return Constructor->setInvalidDecl(); 6170 6171 // C++ [class.copy]p3: 6172 // A declaration of a constructor for a class X is ill-formed if 6173 // its first parameter is of type (optionally cv-qualified) X and 6174 // either there are no other parameters or else all other 6175 // parameters have default arguments. 6176 if (!Constructor->isInvalidDecl() && 6177 ((Constructor->getNumParams() == 1) || 6178 (Constructor->getNumParams() > 1 && 6179 Constructor->getParamDecl(1)->hasDefaultArg())) && 6180 Constructor->getTemplateSpecializationKind() 6181 != TSK_ImplicitInstantiation) { 6182 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6183 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6184 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6185 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6186 const char *ConstRef 6187 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6188 : " const &"; 6189 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6190 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6191 6192 // FIXME: Rather that making the constructor invalid, we should endeavor 6193 // to fix the type. 6194 Constructor->setInvalidDecl(); 6195 } 6196 } 6197 } 6198 6199 /// CheckDestructor - Checks a fully-formed destructor definition for 6200 /// well-formedness, issuing any diagnostics required. Returns true 6201 /// on error. 6202 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6203 CXXRecordDecl *RD = Destructor->getParent(); 6204 6205 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6206 SourceLocation Loc; 6207 6208 if (!Destructor->isImplicit()) 6209 Loc = Destructor->getLocation(); 6210 else 6211 Loc = RD->getLocation(); 6212 6213 // If we have a virtual destructor, look up the deallocation function 6214 FunctionDecl *OperatorDelete = 0; 6215 DeclarationName Name = 6216 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6217 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6218 return true; 6219 6220 MarkFunctionReferenced(Loc, OperatorDelete); 6221 6222 Destructor->setOperatorDelete(OperatorDelete); 6223 } 6224 6225 return false; 6226 } 6227 6228 static inline bool 6229 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 6230 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 6231 FTI.ArgInfo[0].Param && 6232 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 6233 } 6234 6235 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6236 /// the well-formednes of the destructor declarator @p D with type @p 6237 /// R. If there are any errors in the declarator, this routine will 6238 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6239 /// will be updated to reflect a well-formed type for the destructor and 6240 /// returned. 6241 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6242 StorageClass& SC) { 6243 // C++ [class.dtor]p1: 6244 // [...] A typedef-name that names a class is a class-name 6245 // (7.1.3); however, a typedef-name that names a class shall not 6246 // be used as the identifier in the declarator for a destructor 6247 // declaration. 6248 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6249 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6250 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6251 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6252 else if (const TemplateSpecializationType *TST = 6253 DeclaratorType->getAs<TemplateSpecializationType>()) 6254 if (TST->isTypeAlias()) 6255 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6256 << DeclaratorType << 1; 6257 6258 // C++ [class.dtor]p2: 6259 // A destructor is used to destroy objects of its class type. A 6260 // destructor takes no parameters, and no return type can be 6261 // specified for it (not even void). The address of a destructor 6262 // shall not be taken. A destructor shall not be static. A 6263 // destructor can be invoked for a const, volatile or const 6264 // volatile object. A destructor shall not be declared const, 6265 // volatile or const volatile (9.3.2). 6266 if (SC == SC_Static) { 6267 if (!D.isInvalidType()) 6268 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6269 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6270 << SourceRange(D.getIdentifierLoc()) 6271 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6272 6273 SC = SC_None; 6274 } 6275 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6276 // Destructors don't have return types, but the parser will 6277 // happily parse something like: 6278 // 6279 // class X { 6280 // float ~X(); 6281 // }; 6282 // 6283 // The return type will be eliminated later. 6284 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6285 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6286 << SourceRange(D.getIdentifierLoc()); 6287 } 6288 6289 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6290 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6291 if (FTI.TypeQuals & Qualifiers::Const) 6292 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6293 << "const" << SourceRange(D.getIdentifierLoc()); 6294 if (FTI.TypeQuals & Qualifiers::Volatile) 6295 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6296 << "volatile" << SourceRange(D.getIdentifierLoc()); 6297 if (FTI.TypeQuals & Qualifiers::Restrict) 6298 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6299 << "restrict" << SourceRange(D.getIdentifierLoc()); 6300 D.setInvalidType(); 6301 } 6302 6303 // C++0x [class.dtor]p2: 6304 // A destructor shall not be declared with a ref-qualifier. 6305 if (FTI.hasRefQualifier()) { 6306 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6307 << FTI.RefQualifierIsLValueRef 6308 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6309 D.setInvalidType(); 6310 } 6311 6312 // Make sure we don't have any parameters. 6313 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 6314 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6315 6316 // Delete the parameters. 6317 FTI.freeArgs(); 6318 D.setInvalidType(); 6319 } 6320 6321 // Make sure the destructor isn't variadic. 6322 if (FTI.isVariadic) { 6323 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6324 D.setInvalidType(); 6325 } 6326 6327 // Rebuild the function type "R" without any type qualifiers or 6328 // parameters (in case any of the errors above fired) and with 6329 // "void" as the return type, since destructors don't have return 6330 // types. 6331 if (!D.isInvalidType()) 6332 return R; 6333 6334 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6335 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6336 EPI.Variadic = false; 6337 EPI.TypeQuals = 0; 6338 EPI.RefQualifier = RQ_None; 6339 return Context.getFunctionType(Context.VoidTy, None, EPI); 6340 } 6341 6342 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6343 /// well-formednes of the conversion function declarator @p D with 6344 /// type @p R. If there are any errors in the declarator, this routine 6345 /// will emit diagnostics and return true. Otherwise, it will return 6346 /// false. Either way, the type @p R will be updated to reflect a 6347 /// well-formed type for the conversion operator. 6348 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6349 StorageClass& SC) { 6350 // C++ [class.conv.fct]p1: 6351 // Neither parameter types nor return type can be specified. The 6352 // type of a conversion function (8.3.5) is "function taking no 6353 // parameter returning conversion-type-id." 6354 if (SC == SC_Static) { 6355 if (!D.isInvalidType()) 6356 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6357 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6358 << D.getName().getSourceRange(); 6359 D.setInvalidType(); 6360 SC = SC_None; 6361 } 6362 6363 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6364 6365 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6366 // Conversion functions don't have return types, but the parser will 6367 // happily parse something like: 6368 // 6369 // class X { 6370 // float operator bool(); 6371 // }; 6372 // 6373 // The return type will be changed later anyway. 6374 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6375 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6376 << SourceRange(D.getIdentifierLoc()); 6377 D.setInvalidType(); 6378 } 6379 6380 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6381 6382 // Make sure we don't have any parameters. 6383 if (Proto->getNumArgs() > 0) { 6384 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6385 6386 // Delete the parameters. 6387 D.getFunctionTypeInfo().freeArgs(); 6388 D.setInvalidType(); 6389 } else if (Proto->isVariadic()) { 6390 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6391 D.setInvalidType(); 6392 } 6393 6394 // Diagnose "&operator bool()" and other such nonsense. This 6395 // is actually a gcc extension which we don't support. 6396 if (Proto->getResultType() != ConvType) { 6397 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6398 << Proto->getResultType(); 6399 D.setInvalidType(); 6400 ConvType = Proto->getResultType(); 6401 } 6402 6403 // C++ [class.conv.fct]p4: 6404 // The conversion-type-id shall not represent a function type nor 6405 // an array type. 6406 if (ConvType->isArrayType()) { 6407 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6408 ConvType = Context.getPointerType(ConvType); 6409 D.setInvalidType(); 6410 } else if (ConvType->isFunctionType()) { 6411 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6412 ConvType = Context.getPointerType(ConvType); 6413 D.setInvalidType(); 6414 } 6415 6416 // Rebuild the function type "R" without any parameters (in case any 6417 // of the errors above fired) and with the conversion type as the 6418 // return type. 6419 if (D.isInvalidType()) 6420 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6421 6422 // C++0x explicit conversion operators. 6423 if (D.getDeclSpec().isExplicitSpecified()) 6424 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6425 getLangOpts().CPlusPlus11 ? 6426 diag::warn_cxx98_compat_explicit_conversion_functions : 6427 diag::ext_explicit_conversion_functions) 6428 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6429 } 6430 6431 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6432 /// the declaration of the given C++ conversion function. This routine 6433 /// is responsible for recording the conversion function in the C++ 6434 /// class, if possible. 6435 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6436 assert(Conversion && "Expected to receive a conversion function declaration"); 6437 6438 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6439 6440 // Make sure we aren't redeclaring the conversion function. 6441 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6442 6443 // C++ [class.conv.fct]p1: 6444 // [...] A conversion function is never used to convert a 6445 // (possibly cv-qualified) object to the (possibly cv-qualified) 6446 // same object type (or a reference to it), to a (possibly 6447 // cv-qualified) base class of that type (or a reference to it), 6448 // or to (possibly cv-qualified) void. 6449 // FIXME: Suppress this warning if the conversion function ends up being a 6450 // virtual function that overrides a virtual function in a base class. 6451 QualType ClassType 6452 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6453 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6454 ConvType = ConvTypeRef->getPointeeType(); 6455 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6456 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6457 /* Suppress diagnostics for instantiations. */; 6458 else if (ConvType->isRecordType()) { 6459 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6460 if (ConvType == ClassType) 6461 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6462 << ClassType; 6463 else if (IsDerivedFrom(ClassType, ConvType)) 6464 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6465 << ClassType << ConvType; 6466 } else if (ConvType->isVoidType()) { 6467 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6468 << ClassType << ConvType; 6469 } 6470 6471 if (FunctionTemplateDecl *ConversionTemplate 6472 = Conversion->getDescribedFunctionTemplate()) 6473 return ConversionTemplate; 6474 6475 return Conversion; 6476 } 6477 6478 //===----------------------------------------------------------------------===// 6479 // Namespace Handling 6480 //===----------------------------------------------------------------------===// 6481 6482 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6483 /// reopened. 6484 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6485 SourceLocation Loc, 6486 IdentifierInfo *II, bool *IsInline, 6487 NamespaceDecl *PrevNS) { 6488 assert(*IsInline != PrevNS->isInline()); 6489 6490 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6491 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6492 // inline namespaces, with the intention of bringing names into namespace std. 6493 // 6494 // We support this just well enough to get that case working; this is not 6495 // sufficient to support reopening namespaces as inline in general. 6496 if (*IsInline && II && II->getName().startswith("__atomic") && 6497 S.getSourceManager().isInSystemHeader(Loc)) { 6498 // Mark all prior declarations of the namespace as inline. 6499 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6500 NS = NS->getPreviousDecl()) 6501 NS->setInline(*IsInline); 6502 // Patch up the lookup table for the containing namespace. This isn't really 6503 // correct, but it's good enough for this particular case. 6504 for (DeclContext::decl_iterator I = PrevNS->decls_begin(), 6505 E = PrevNS->decls_end(); I != E; ++I) 6506 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) 6507 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6508 return; 6509 } 6510 6511 if (PrevNS->isInline()) 6512 // The user probably just forgot the 'inline', so suggest that it 6513 // be added back. 6514 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6515 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6516 else 6517 S.Diag(Loc, diag::err_inline_namespace_mismatch) 6518 << IsInline; 6519 6520 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6521 *IsInline = PrevNS->isInline(); 6522 } 6523 6524 /// ActOnStartNamespaceDef - This is called at the start of a namespace 6525 /// definition. 6526 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6527 SourceLocation InlineLoc, 6528 SourceLocation NamespaceLoc, 6529 SourceLocation IdentLoc, 6530 IdentifierInfo *II, 6531 SourceLocation LBrace, 6532 AttributeList *AttrList) { 6533 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6534 // For anonymous namespace, take the location of the left brace. 6535 SourceLocation Loc = II ? IdentLoc : LBrace; 6536 bool IsInline = InlineLoc.isValid(); 6537 bool IsInvalid = false; 6538 bool IsStd = false; 6539 bool AddToKnown = false; 6540 Scope *DeclRegionScope = NamespcScope->getParent(); 6541 6542 NamespaceDecl *PrevNS = 0; 6543 if (II) { 6544 // C++ [namespace.def]p2: 6545 // The identifier in an original-namespace-definition shall not 6546 // have been previously defined in the declarative region in 6547 // which the original-namespace-definition appears. The 6548 // identifier in an original-namespace-definition is the name of 6549 // the namespace. Subsequently in that declarative region, it is 6550 // treated as an original-namespace-name. 6551 // 6552 // Since namespace names are unique in their scope, and we don't 6553 // look through using directives, just look for any ordinary names. 6554 6555 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6556 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6557 Decl::IDNS_Namespace; 6558 NamedDecl *PrevDecl = 0; 6559 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6560 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6561 ++I) { 6562 if ((*I)->getIdentifierNamespace() & IDNS) { 6563 PrevDecl = *I; 6564 break; 6565 } 6566 } 6567 6568 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6569 6570 if (PrevNS) { 6571 // This is an extended namespace definition. 6572 if (IsInline != PrevNS->isInline()) 6573 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6574 &IsInline, PrevNS); 6575 } else if (PrevDecl) { 6576 // This is an invalid name redefinition. 6577 Diag(Loc, diag::err_redefinition_different_kind) 6578 << II; 6579 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6580 IsInvalid = true; 6581 // Continue on to push Namespc as current DeclContext and return it. 6582 } else if (II->isStr("std") && 6583 CurContext->getRedeclContext()->isTranslationUnit()) { 6584 // This is the first "real" definition of the namespace "std", so update 6585 // our cache of the "std" namespace to point at this definition. 6586 PrevNS = getStdNamespace(); 6587 IsStd = true; 6588 AddToKnown = !IsInline; 6589 } else { 6590 // We've seen this namespace for the first time. 6591 AddToKnown = !IsInline; 6592 } 6593 } else { 6594 // Anonymous namespaces. 6595 6596 // Determine whether the parent already has an anonymous namespace. 6597 DeclContext *Parent = CurContext->getRedeclContext(); 6598 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6599 PrevNS = TU->getAnonymousNamespace(); 6600 } else { 6601 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6602 PrevNS = ND->getAnonymousNamespace(); 6603 } 6604 6605 if (PrevNS && IsInline != PrevNS->isInline()) 6606 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6607 &IsInline, PrevNS); 6608 } 6609 6610 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6611 StartLoc, Loc, II, PrevNS); 6612 if (IsInvalid) 6613 Namespc->setInvalidDecl(); 6614 6615 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6616 6617 // FIXME: Should we be merging attributes? 6618 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6619 PushNamespaceVisibilityAttr(Attr, Loc); 6620 6621 if (IsStd) 6622 StdNamespace = Namespc; 6623 if (AddToKnown) 6624 KnownNamespaces[Namespc] = false; 6625 6626 if (II) { 6627 PushOnScopeChains(Namespc, DeclRegionScope); 6628 } else { 6629 // Link the anonymous namespace into its parent. 6630 DeclContext *Parent = CurContext->getRedeclContext(); 6631 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6632 TU->setAnonymousNamespace(Namespc); 6633 } else { 6634 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6635 } 6636 6637 CurContext->addDecl(Namespc); 6638 6639 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6640 // behaves as if it were replaced by 6641 // namespace unique { /* empty body */ } 6642 // using namespace unique; 6643 // namespace unique { namespace-body } 6644 // where all occurrences of 'unique' in a translation unit are 6645 // replaced by the same identifier and this identifier differs 6646 // from all other identifiers in the entire program. 6647 6648 // We just create the namespace with an empty name and then add an 6649 // implicit using declaration, just like the standard suggests. 6650 // 6651 // CodeGen enforces the "universally unique" aspect by giving all 6652 // declarations semantically contained within an anonymous 6653 // namespace internal linkage. 6654 6655 if (!PrevNS) { 6656 UsingDirectiveDecl* UD 6657 = UsingDirectiveDecl::Create(Context, Parent, 6658 /* 'using' */ LBrace, 6659 /* 'namespace' */ SourceLocation(), 6660 /* qualifier */ NestedNameSpecifierLoc(), 6661 /* identifier */ SourceLocation(), 6662 Namespc, 6663 /* Ancestor */ Parent); 6664 UD->setImplicit(); 6665 Parent->addDecl(UD); 6666 } 6667 } 6668 6669 ActOnDocumentableDecl(Namespc); 6670 6671 // Although we could have an invalid decl (i.e. the namespace name is a 6672 // redefinition), push it as current DeclContext and try to continue parsing. 6673 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6674 // for the namespace has the declarations that showed up in that particular 6675 // namespace definition. 6676 PushDeclContext(NamespcScope, Namespc); 6677 return Namespc; 6678 } 6679 6680 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6681 /// is a namespace alias, returns the namespace it points to. 6682 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6683 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6684 return AD->getNamespace(); 6685 return dyn_cast_or_null<NamespaceDecl>(D); 6686 } 6687 6688 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 6689 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6690 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6691 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6692 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6693 Namespc->setRBraceLoc(RBrace); 6694 PopDeclContext(); 6695 if (Namespc->hasAttr<VisibilityAttr>()) 6696 PopPragmaVisibility(true, RBrace); 6697 } 6698 6699 CXXRecordDecl *Sema::getStdBadAlloc() const { 6700 return cast_or_null<CXXRecordDecl>( 6701 StdBadAlloc.get(Context.getExternalSource())); 6702 } 6703 6704 NamespaceDecl *Sema::getStdNamespace() const { 6705 return cast_or_null<NamespaceDecl>( 6706 StdNamespace.get(Context.getExternalSource())); 6707 } 6708 6709 /// \brief Retrieve the special "std" namespace, which may require us to 6710 /// implicitly define the namespace. 6711 NamespaceDecl *Sema::getOrCreateStdNamespace() { 6712 if (!StdNamespace) { 6713 // The "std" namespace has not yet been defined, so build one implicitly. 6714 StdNamespace = NamespaceDecl::Create(Context, 6715 Context.getTranslationUnitDecl(), 6716 /*Inline=*/false, 6717 SourceLocation(), SourceLocation(), 6718 &PP.getIdentifierTable().get("std"), 6719 /*PrevDecl=*/0); 6720 getStdNamespace()->setImplicit(true); 6721 } 6722 6723 return getStdNamespace(); 6724 } 6725 6726 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6727 assert(getLangOpts().CPlusPlus && 6728 "Looking for std::initializer_list outside of C++."); 6729 6730 // We're looking for implicit instantiations of 6731 // template <typename E> class std::initializer_list. 6732 6733 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6734 return false; 6735 6736 ClassTemplateDecl *Template = 0; 6737 const TemplateArgument *Arguments = 0; 6738 6739 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6740 6741 ClassTemplateSpecializationDecl *Specialization = 6742 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6743 if (!Specialization) 6744 return false; 6745 6746 Template = Specialization->getSpecializedTemplate(); 6747 Arguments = Specialization->getTemplateArgs().data(); 6748 } else if (const TemplateSpecializationType *TST = 6749 Ty->getAs<TemplateSpecializationType>()) { 6750 Template = dyn_cast_or_null<ClassTemplateDecl>( 6751 TST->getTemplateName().getAsTemplateDecl()); 6752 Arguments = TST->getArgs(); 6753 } 6754 if (!Template) 6755 return false; 6756 6757 if (!StdInitializerList) { 6758 // Haven't recognized std::initializer_list yet, maybe this is it. 6759 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6760 if (TemplateClass->getIdentifier() != 6761 &PP.getIdentifierTable().get("initializer_list") || 6762 !getStdNamespace()->InEnclosingNamespaceSetOf( 6763 TemplateClass->getDeclContext())) 6764 return false; 6765 // This is a template called std::initializer_list, but is it the right 6766 // template? 6767 TemplateParameterList *Params = Template->getTemplateParameters(); 6768 if (Params->getMinRequiredArguments() != 1) 6769 return false; 6770 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6771 return false; 6772 6773 // It's the right template. 6774 StdInitializerList = Template; 6775 } 6776 6777 if (Template != StdInitializerList) 6778 return false; 6779 6780 // This is an instance of std::initializer_list. Find the argument type. 6781 if (Element) 6782 *Element = Arguments[0].getAsType(); 6783 return true; 6784 } 6785 6786 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6787 NamespaceDecl *Std = S.getStdNamespace(); 6788 if (!Std) { 6789 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6790 return 0; 6791 } 6792 6793 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6794 Loc, Sema::LookupOrdinaryName); 6795 if (!S.LookupQualifiedName(Result, Std)) { 6796 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6797 return 0; 6798 } 6799 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6800 if (!Template) { 6801 Result.suppressDiagnostics(); 6802 // We found something weird. Complain about the first thing we found. 6803 NamedDecl *Found = *Result.begin(); 6804 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6805 return 0; 6806 } 6807 6808 // We found some template called std::initializer_list. Now verify that it's 6809 // correct. 6810 TemplateParameterList *Params = Template->getTemplateParameters(); 6811 if (Params->getMinRequiredArguments() != 1 || 6812 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6813 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6814 return 0; 6815 } 6816 6817 return Template; 6818 } 6819 6820 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6821 if (!StdInitializerList) { 6822 StdInitializerList = LookupStdInitializerList(*this, Loc); 6823 if (!StdInitializerList) 6824 return QualType(); 6825 } 6826 6827 TemplateArgumentListInfo Args(Loc, Loc); 6828 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6829 Context.getTrivialTypeSourceInfo(Element, 6830 Loc))); 6831 return Context.getCanonicalType( 6832 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6833 } 6834 6835 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6836 // C++ [dcl.init.list]p2: 6837 // A constructor is an initializer-list constructor if its first parameter 6838 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6839 // std::initializer_list<E> for some type E, and either there are no other 6840 // parameters or else all other parameters have default arguments. 6841 if (Ctor->getNumParams() < 1 || 6842 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6843 return false; 6844 6845 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6846 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6847 ArgType = RT->getPointeeType().getUnqualifiedType(); 6848 6849 return isStdInitializerList(ArgType, 0); 6850 } 6851 6852 /// \brief Determine whether a using statement is in a context where it will be 6853 /// apply in all contexts. 6854 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6855 switch (CurContext->getDeclKind()) { 6856 case Decl::TranslationUnit: 6857 return true; 6858 case Decl::LinkageSpec: 6859 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6860 default: 6861 return false; 6862 } 6863 } 6864 6865 namespace { 6866 6867 // Callback to only accept typo corrections that are namespaces. 6868 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6869 public: 6870 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE { 6871 if (NamedDecl *ND = candidate.getCorrectionDecl()) 6872 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6873 return false; 6874 } 6875 }; 6876 6877 } 6878 6879 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6880 CXXScopeSpec &SS, 6881 SourceLocation IdentLoc, 6882 IdentifierInfo *Ident) { 6883 NamespaceValidatorCCC Validator; 6884 R.clear(); 6885 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6886 R.getLookupKind(), Sc, &SS, 6887 Validator)) { 6888 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 6889 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6890 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 6891 Ident->getName().equals(CorrectedStr); 6892 S.diagnoseTypo(Corrected, 6893 S.PDiag(diag::err_using_directive_member_suggest) 6894 << Ident << DC << DroppedSpecifier << SS.getRange(), 6895 S.PDiag(diag::note_namespace_defined_here)); 6896 } else { 6897 S.diagnoseTypo(Corrected, 6898 S.PDiag(diag::err_using_directive_suggest) << Ident, 6899 S.PDiag(diag::note_namespace_defined_here)); 6900 } 6901 R.addDecl(Corrected.getCorrectionDecl()); 6902 return true; 6903 } 6904 return false; 6905 } 6906 6907 Decl *Sema::ActOnUsingDirective(Scope *S, 6908 SourceLocation UsingLoc, 6909 SourceLocation NamespcLoc, 6910 CXXScopeSpec &SS, 6911 SourceLocation IdentLoc, 6912 IdentifierInfo *NamespcName, 6913 AttributeList *AttrList) { 6914 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6915 assert(NamespcName && "Invalid NamespcName."); 6916 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6917 6918 // This can only happen along a recovery path. 6919 while (S->getFlags() & Scope::TemplateParamScope) 6920 S = S->getParent(); 6921 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6922 6923 UsingDirectiveDecl *UDir = 0; 6924 NestedNameSpecifier *Qualifier = 0; 6925 if (SS.isSet()) 6926 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6927 6928 // Lookup namespace name. 6929 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6930 LookupParsedName(R, S, &SS); 6931 if (R.isAmbiguous()) 6932 return 0; 6933 6934 if (R.empty()) { 6935 R.clear(); 6936 // Allow "using namespace std;" or "using namespace ::std;" even if 6937 // "std" hasn't been defined yet, for GCC compatibility. 6938 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6939 NamespcName->isStr("std")) { 6940 Diag(IdentLoc, diag::ext_using_undefined_std); 6941 R.addDecl(getOrCreateStdNamespace()); 6942 R.resolveKind(); 6943 } 6944 // Otherwise, attempt typo correction. 6945 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6946 } 6947 6948 if (!R.empty()) { 6949 NamedDecl *Named = R.getFoundDecl(); 6950 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6951 && "expected namespace decl"); 6952 // C++ [namespace.udir]p1: 6953 // A using-directive specifies that the names in the nominated 6954 // namespace can be used in the scope in which the 6955 // using-directive appears after the using-directive. During 6956 // unqualified name lookup (3.4.1), the names appear as if they 6957 // were declared in the nearest enclosing namespace which 6958 // contains both the using-directive and the nominated 6959 // namespace. [Note: in this context, "contains" means "contains 6960 // directly or indirectly". ] 6961 6962 // Find enclosing context containing both using-directive and 6963 // nominated namespace. 6964 NamespaceDecl *NS = getNamespaceDecl(Named); 6965 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6966 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6967 CommonAncestor = CommonAncestor->getParent(); 6968 6969 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6970 SS.getWithLocInContext(Context), 6971 IdentLoc, Named, CommonAncestor); 6972 6973 if (IsUsingDirectiveInToplevelContext(CurContext) && 6974 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6975 Diag(IdentLoc, diag::warn_using_directive_in_header); 6976 } 6977 6978 PushUsingDirective(S, UDir); 6979 } else { 6980 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6981 } 6982 6983 if (UDir) 6984 ProcessDeclAttributeList(S, UDir, AttrList); 6985 6986 return UDir; 6987 } 6988 6989 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 6990 // If the scope has an associated entity and the using directive is at 6991 // namespace or translation unit scope, add the UsingDirectiveDecl into 6992 // its lookup structure so qualified name lookup can find it. 6993 DeclContext *Ctx = S->getEntity(); 6994 if (Ctx && !Ctx->isFunctionOrMethod()) 6995 Ctx->addDecl(UDir); 6996 else 6997 // Otherwise, it is at block sope. The using-directives will affect lookup 6998 // only to the end of the scope. 6999 S->PushUsingDirective(UDir); 7000 } 7001 7002 7003 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7004 AccessSpecifier AS, 7005 bool HasUsingKeyword, 7006 SourceLocation UsingLoc, 7007 CXXScopeSpec &SS, 7008 UnqualifiedId &Name, 7009 AttributeList *AttrList, 7010 bool HasTypenameKeyword, 7011 SourceLocation TypenameLoc) { 7012 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7013 7014 switch (Name.getKind()) { 7015 case UnqualifiedId::IK_ImplicitSelfParam: 7016 case UnqualifiedId::IK_Identifier: 7017 case UnqualifiedId::IK_OperatorFunctionId: 7018 case UnqualifiedId::IK_LiteralOperatorId: 7019 case UnqualifiedId::IK_ConversionFunctionId: 7020 break; 7021 7022 case UnqualifiedId::IK_ConstructorName: 7023 case UnqualifiedId::IK_ConstructorTemplateId: 7024 // C++11 inheriting constructors. 7025 Diag(Name.getLocStart(), 7026 getLangOpts().CPlusPlus11 ? 7027 diag::warn_cxx98_compat_using_decl_constructor : 7028 diag::err_using_decl_constructor) 7029 << SS.getRange(); 7030 7031 if (getLangOpts().CPlusPlus11) break; 7032 7033 return 0; 7034 7035 case UnqualifiedId::IK_DestructorName: 7036 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7037 << SS.getRange(); 7038 return 0; 7039 7040 case UnqualifiedId::IK_TemplateId: 7041 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7042 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7043 return 0; 7044 } 7045 7046 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7047 DeclarationName TargetName = TargetNameInfo.getName(); 7048 if (!TargetName) 7049 return 0; 7050 7051 // Warn about access declarations. 7052 if (!HasUsingKeyword) { 7053 Diag(Name.getLocStart(), 7054 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7055 : diag::warn_access_decl_deprecated) 7056 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7057 } 7058 7059 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7060 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7061 return 0; 7062 7063 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7064 TargetNameInfo, AttrList, 7065 /* IsInstantiation */ false, 7066 HasTypenameKeyword, TypenameLoc); 7067 if (UD) 7068 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7069 7070 return UD; 7071 } 7072 7073 /// \brief Determine whether a using declaration considers the given 7074 /// declarations as "equivalent", e.g., if they are redeclarations of 7075 /// the same entity or are both typedefs of the same type. 7076 static bool 7077 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7078 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7079 return true; 7080 7081 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7082 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7083 return Context.hasSameType(TD1->getUnderlyingType(), 7084 TD2->getUnderlyingType()); 7085 7086 return false; 7087 } 7088 7089 7090 /// Determines whether to create a using shadow decl for a particular 7091 /// decl, given the set of decls existing prior to this using lookup. 7092 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7093 const LookupResult &Previous, 7094 UsingShadowDecl *&PrevShadow) { 7095 // Diagnose finding a decl which is not from a base class of the 7096 // current class. We do this now because there are cases where this 7097 // function will silently decide not to build a shadow decl, which 7098 // will pre-empt further diagnostics. 7099 // 7100 // We don't need to do this in C++0x because we do the check once on 7101 // the qualifier. 7102 // 7103 // FIXME: diagnose the following if we care enough: 7104 // struct A { int foo; }; 7105 // struct B : A { using A::foo; }; 7106 // template <class T> struct C : A {}; 7107 // template <class T> struct D : C<T> { using B::foo; } // <--- 7108 // This is invalid (during instantiation) in C++03 because B::foo 7109 // resolves to the using decl in B, which is not a base class of D<T>. 7110 // We can't diagnose it immediately because C<T> is an unknown 7111 // specialization. The UsingShadowDecl in D<T> then points directly 7112 // to A::foo, which will look well-formed when we instantiate. 7113 // The right solution is to not collapse the shadow-decl chain. 7114 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7115 DeclContext *OrigDC = Orig->getDeclContext(); 7116 7117 // Handle enums and anonymous structs. 7118 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7119 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7120 while (OrigRec->isAnonymousStructOrUnion()) 7121 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7122 7123 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7124 if (OrigDC == CurContext) { 7125 Diag(Using->getLocation(), 7126 diag::err_using_decl_nested_name_specifier_is_current_class) 7127 << Using->getQualifierLoc().getSourceRange(); 7128 Diag(Orig->getLocation(), diag::note_using_decl_target); 7129 return true; 7130 } 7131 7132 Diag(Using->getQualifierLoc().getBeginLoc(), 7133 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7134 << Using->getQualifier() 7135 << cast<CXXRecordDecl>(CurContext) 7136 << Using->getQualifierLoc().getSourceRange(); 7137 Diag(Orig->getLocation(), diag::note_using_decl_target); 7138 return true; 7139 } 7140 } 7141 7142 if (Previous.empty()) return false; 7143 7144 NamedDecl *Target = Orig; 7145 if (isa<UsingShadowDecl>(Target)) 7146 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7147 7148 // If the target happens to be one of the previous declarations, we 7149 // don't have a conflict. 7150 // 7151 // FIXME: but we might be increasing its access, in which case we 7152 // should redeclare it. 7153 NamedDecl *NonTag = 0, *Tag = 0; 7154 bool FoundEquivalentDecl = false; 7155 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7156 I != E; ++I) { 7157 NamedDecl *D = (*I)->getUnderlyingDecl(); 7158 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7159 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7160 PrevShadow = Shadow; 7161 FoundEquivalentDecl = true; 7162 } 7163 7164 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7165 } 7166 7167 if (FoundEquivalentDecl) 7168 return false; 7169 7170 if (Target->isFunctionOrFunctionTemplate()) { 7171 FunctionDecl *FD; 7172 if (isa<FunctionTemplateDecl>(Target)) 7173 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 7174 else 7175 FD = cast<FunctionDecl>(Target); 7176 7177 NamedDecl *OldDecl = 0; 7178 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 7179 case Ovl_Overload: 7180 return false; 7181 7182 case Ovl_NonFunction: 7183 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7184 break; 7185 7186 // We found a decl with the exact signature. 7187 case Ovl_Match: 7188 // If we're in a record, we want to hide the target, so we 7189 // return true (without a diagnostic) to tell the caller not to 7190 // build a shadow decl. 7191 if (CurContext->isRecord()) 7192 return true; 7193 7194 // If we're not in a record, this is an error. 7195 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7196 break; 7197 } 7198 7199 Diag(Target->getLocation(), diag::note_using_decl_target); 7200 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7201 return true; 7202 } 7203 7204 // Target is not a function. 7205 7206 if (isa<TagDecl>(Target)) { 7207 // No conflict between a tag and a non-tag. 7208 if (!Tag) return false; 7209 7210 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7211 Diag(Target->getLocation(), diag::note_using_decl_target); 7212 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7213 return true; 7214 } 7215 7216 // No conflict between a tag and a non-tag. 7217 if (!NonTag) return false; 7218 7219 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7220 Diag(Target->getLocation(), diag::note_using_decl_target); 7221 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7222 return true; 7223 } 7224 7225 /// Builds a shadow declaration corresponding to a 'using' declaration. 7226 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7227 UsingDecl *UD, 7228 NamedDecl *Orig, 7229 UsingShadowDecl *PrevDecl) { 7230 7231 // If we resolved to another shadow declaration, just coalesce them. 7232 NamedDecl *Target = Orig; 7233 if (isa<UsingShadowDecl>(Target)) { 7234 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7235 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7236 } 7237 7238 UsingShadowDecl *Shadow 7239 = UsingShadowDecl::Create(Context, CurContext, 7240 UD->getLocation(), UD, Target); 7241 UD->addShadowDecl(Shadow); 7242 7243 Shadow->setAccess(UD->getAccess()); 7244 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7245 Shadow->setInvalidDecl(); 7246 7247 Shadow->setPreviousDecl(PrevDecl); 7248 7249 if (S) 7250 PushOnScopeChains(Shadow, S); 7251 else 7252 CurContext->addDecl(Shadow); 7253 7254 7255 return Shadow; 7256 } 7257 7258 /// Hides a using shadow declaration. This is required by the current 7259 /// using-decl implementation when a resolvable using declaration in a 7260 /// class is followed by a declaration which would hide or override 7261 /// one or more of the using decl's targets; for example: 7262 /// 7263 /// struct Base { void foo(int); }; 7264 /// struct Derived : Base { 7265 /// using Base::foo; 7266 /// void foo(int); 7267 /// }; 7268 /// 7269 /// The governing language is C++03 [namespace.udecl]p12: 7270 /// 7271 /// When a using-declaration brings names from a base class into a 7272 /// derived class scope, member functions in the derived class 7273 /// override and/or hide member functions with the same name and 7274 /// parameter types in a base class (rather than conflicting). 7275 /// 7276 /// There are two ways to implement this: 7277 /// (1) optimistically create shadow decls when they're not hidden 7278 /// by existing declarations, or 7279 /// (2) don't create any shadow decls (or at least don't make them 7280 /// visible) until we've fully parsed/instantiated the class. 7281 /// The problem with (1) is that we might have to retroactively remove 7282 /// a shadow decl, which requires several O(n) operations because the 7283 /// decl structures are (very reasonably) not designed for removal. 7284 /// (2) avoids this but is very fiddly and phase-dependent. 7285 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7286 if (Shadow->getDeclName().getNameKind() == 7287 DeclarationName::CXXConversionFunctionName) 7288 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7289 7290 // Remove it from the DeclContext... 7291 Shadow->getDeclContext()->removeDecl(Shadow); 7292 7293 // ...and the scope, if applicable... 7294 if (S) { 7295 S->RemoveDecl(Shadow); 7296 IdResolver.RemoveDecl(Shadow); 7297 } 7298 7299 // ...and the using decl. 7300 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7301 7302 // TODO: complain somehow if Shadow was used. It shouldn't 7303 // be possible for this to happen, because...? 7304 } 7305 7306 namespace { 7307 class UsingValidatorCCC : public CorrectionCandidateCallback { 7308 public: 7309 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7310 bool RequireMember) 7311 : HasTypenameKeyword(HasTypenameKeyword), 7312 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {} 7313 7314 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE { 7315 NamedDecl *ND = Candidate.getCorrectionDecl(); 7316 7317 // Keywords are not valid here. 7318 if (!ND || isa<NamespaceDecl>(ND)) 7319 return false; 7320 7321 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) && 7322 !isa<TypeDecl>(ND)) 7323 return false; 7324 7325 // Completely unqualified names are invalid for a 'using' declaration. 7326 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7327 return false; 7328 7329 if (isa<TypeDecl>(ND)) 7330 return HasTypenameKeyword || !IsInstantiation; 7331 7332 return !HasTypenameKeyword; 7333 } 7334 7335 private: 7336 bool HasTypenameKeyword; 7337 bool IsInstantiation; 7338 bool RequireMember; 7339 }; 7340 } // end anonymous namespace 7341 7342 /// Builds a using declaration. 7343 /// 7344 /// \param IsInstantiation - Whether this call arises from an 7345 /// instantiation of an unresolved using declaration. We treat 7346 /// the lookup differently for these declarations. 7347 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7348 SourceLocation UsingLoc, 7349 CXXScopeSpec &SS, 7350 const DeclarationNameInfo &NameInfo, 7351 AttributeList *AttrList, 7352 bool IsInstantiation, 7353 bool HasTypenameKeyword, 7354 SourceLocation TypenameLoc) { 7355 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7356 SourceLocation IdentLoc = NameInfo.getLoc(); 7357 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7358 7359 // FIXME: We ignore attributes for now. 7360 7361 if (SS.isEmpty()) { 7362 Diag(IdentLoc, diag::err_using_requires_qualname); 7363 return 0; 7364 } 7365 7366 // Do the redeclaration lookup in the current scope. 7367 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7368 ForRedeclaration); 7369 Previous.setHideTags(false); 7370 if (S) { 7371 LookupName(Previous, S); 7372 7373 // It is really dumb that we have to do this. 7374 LookupResult::Filter F = Previous.makeFilter(); 7375 while (F.hasNext()) { 7376 NamedDecl *D = F.next(); 7377 if (!isDeclInScope(D, CurContext, S)) 7378 F.erase(); 7379 } 7380 F.done(); 7381 } else { 7382 assert(IsInstantiation && "no scope in non-instantiation"); 7383 assert(CurContext->isRecord() && "scope not record in instantiation"); 7384 LookupQualifiedName(Previous, CurContext); 7385 } 7386 7387 // Check for invalid redeclarations. 7388 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7389 SS, IdentLoc, Previous)) 7390 return 0; 7391 7392 // Check for bad qualifiers. 7393 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 7394 return 0; 7395 7396 DeclContext *LookupContext = computeDeclContext(SS); 7397 NamedDecl *D; 7398 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7399 if (!LookupContext) { 7400 if (HasTypenameKeyword) { 7401 // FIXME: not all declaration name kinds are legal here 7402 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7403 UsingLoc, TypenameLoc, 7404 QualifierLoc, 7405 IdentLoc, NameInfo.getName()); 7406 } else { 7407 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7408 QualifierLoc, NameInfo); 7409 } 7410 } else { 7411 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 7412 NameInfo, HasTypenameKeyword); 7413 } 7414 D->setAccess(AS); 7415 CurContext->addDecl(D); 7416 7417 if (!LookupContext) return D; 7418 UsingDecl *UD = cast<UsingDecl>(D); 7419 7420 if (RequireCompleteDeclContext(SS, LookupContext)) { 7421 UD->setInvalidDecl(); 7422 return UD; 7423 } 7424 7425 // The normal rules do not apply to inheriting constructor declarations. 7426 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7427 if (CheckInheritingConstructorUsingDecl(UD)) 7428 UD->setInvalidDecl(); 7429 return UD; 7430 } 7431 7432 // Otherwise, look up the target name. 7433 7434 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7435 7436 // Unlike most lookups, we don't always want to hide tag 7437 // declarations: tag names are visible through the using declaration 7438 // even if hidden by ordinary names, *except* in a dependent context 7439 // where it's important for the sanity of two-phase lookup. 7440 if (!IsInstantiation) 7441 R.setHideTags(false); 7442 7443 // For the purposes of this lookup, we have a base object type 7444 // equal to that of the current context. 7445 if (CurContext->isRecord()) { 7446 R.setBaseObjectType( 7447 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7448 } 7449 7450 LookupQualifiedName(R, LookupContext); 7451 7452 // Try to correct typos if possible. 7453 if (R.empty()) { 7454 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, 7455 CurContext->isRecord()); 7456 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(), 7457 R.getLookupKind(), S, &SS, CCC)){ 7458 // We reject any correction for which ND would be NULL. 7459 NamedDecl *ND = Corrected.getCorrectionDecl(); 7460 R.setLookupName(Corrected.getCorrection()); 7461 R.addDecl(ND); 7462 // We reject candidates where DroppedSpecifier == true, hence the 7463 // literal '0' below. 7464 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 7465 << NameInfo.getName() << LookupContext << 0 7466 << SS.getRange()); 7467 } else { 7468 Diag(IdentLoc, diag::err_no_member) 7469 << NameInfo.getName() << LookupContext << SS.getRange(); 7470 UD->setInvalidDecl(); 7471 return UD; 7472 } 7473 } 7474 7475 if (R.isAmbiguous()) { 7476 UD->setInvalidDecl(); 7477 return UD; 7478 } 7479 7480 if (HasTypenameKeyword) { 7481 // If we asked for a typename and got a non-type decl, error out. 7482 if (!R.getAsSingle<TypeDecl>()) { 7483 Diag(IdentLoc, diag::err_using_typename_non_type); 7484 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7485 Diag((*I)->getUnderlyingDecl()->getLocation(), 7486 diag::note_using_decl_target); 7487 UD->setInvalidDecl(); 7488 return UD; 7489 } 7490 } else { 7491 // If we asked for a non-typename and we got a type, error out, 7492 // but only if this is an instantiation of an unresolved using 7493 // decl. Otherwise just silently find the type name. 7494 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7495 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7496 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7497 UD->setInvalidDecl(); 7498 return UD; 7499 } 7500 } 7501 7502 // C++0x N2914 [namespace.udecl]p6: 7503 // A using-declaration shall not name a namespace. 7504 if (R.getAsSingle<NamespaceDecl>()) { 7505 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7506 << SS.getRange(); 7507 UD->setInvalidDecl(); 7508 return UD; 7509 } 7510 7511 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7512 UsingShadowDecl *PrevDecl = 0; 7513 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 7514 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 7515 } 7516 7517 return UD; 7518 } 7519 7520 /// Additional checks for a using declaration referring to a constructor name. 7521 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7522 assert(!UD->hasTypename() && "expecting a constructor name"); 7523 7524 const Type *SourceType = UD->getQualifier()->getAsType(); 7525 assert(SourceType && 7526 "Using decl naming constructor doesn't have type in scope spec."); 7527 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7528 7529 // Check whether the named type is a direct base class. 7530 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 7531 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 7532 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 7533 BaseIt != BaseE; ++BaseIt) { 7534 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 7535 if (CanonicalSourceType == BaseType) 7536 break; 7537 if (BaseIt->getType()->isDependentType()) 7538 break; 7539 } 7540 7541 if (BaseIt == BaseE) { 7542 // Did not find SourceType in the bases. 7543 Diag(UD->getUsingLoc(), 7544 diag::err_using_decl_constructor_not_in_direct_base) 7545 << UD->getNameInfo().getSourceRange() 7546 << QualType(SourceType, 0) << TargetClass; 7547 return true; 7548 } 7549 7550 if (!CurContext->isDependentContext()) 7551 BaseIt->setInheritConstructors(); 7552 7553 return false; 7554 } 7555 7556 /// Checks that the given using declaration is not an invalid 7557 /// redeclaration. Note that this is checking only for the using decl 7558 /// itself, not for any ill-formedness among the UsingShadowDecls. 7559 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7560 bool HasTypenameKeyword, 7561 const CXXScopeSpec &SS, 7562 SourceLocation NameLoc, 7563 const LookupResult &Prev) { 7564 // C++03 [namespace.udecl]p8: 7565 // C++0x [namespace.udecl]p10: 7566 // A using-declaration is a declaration and can therefore be used 7567 // repeatedly where (and only where) multiple declarations are 7568 // allowed. 7569 // 7570 // That's in non-member contexts. 7571 if (!CurContext->getRedeclContext()->isRecord()) 7572 return false; 7573 7574 NestedNameSpecifier *Qual 7575 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 7576 7577 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7578 NamedDecl *D = *I; 7579 7580 bool DTypename; 7581 NestedNameSpecifier *DQual; 7582 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7583 DTypename = UD->hasTypename(); 7584 DQual = UD->getQualifier(); 7585 } else if (UnresolvedUsingValueDecl *UD 7586 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7587 DTypename = false; 7588 DQual = UD->getQualifier(); 7589 } else if (UnresolvedUsingTypenameDecl *UD 7590 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7591 DTypename = true; 7592 DQual = UD->getQualifier(); 7593 } else continue; 7594 7595 // using decls differ if one says 'typename' and the other doesn't. 7596 // FIXME: non-dependent using decls? 7597 if (HasTypenameKeyword != DTypename) continue; 7598 7599 // using decls differ if they name different scopes (but note that 7600 // template instantiation can cause this check to trigger when it 7601 // didn't before instantiation). 7602 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7603 Context.getCanonicalNestedNameSpecifier(DQual)) 7604 continue; 7605 7606 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7607 Diag(D->getLocation(), diag::note_using_decl) << 1; 7608 return true; 7609 } 7610 7611 return false; 7612 } 7613 7614 7615 /// Checks that the given nested-name qualifier used in a using decl 7616 /// in the current context is appropriately related to the current 7617 /// scope. If an error is found, diagnoses it and returns true. 7618 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7619 const CXXScopeSpec &SS, 7620 SourceLocation NameLoc) { 7621 DeclContext *NamedContext = computeDeclContext(SS); 7622 7623 if (!CurContext->isRecord()) { 7624 // C++03 [namespace.udecl]p3: 7625 // C++0x [namespace.udecl]p8: 7626 // A using-declaration for a class member shall be a member-declaration. 7627 7628 // If we weren't able to compute a valid scope, it must be a 7629 // dependent class scope. 7630 if (!NamedContext || NamedContext->isRecord()) { 7631 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7632 << SS.getRange(); 7633 return true; 7634 } 7635 7636 // Otherwise, everything is known to be fine. 7637 return false; 7638 } 7639 7640 // The current scope is a record. 7641 7642 // If the named context is dependent, we can't decide much. 7643 if (!NamedContext) { 7644 // FIXME: in C++0x, we can diagnose if we can prove that the 7645 // nested-name-specifier does not refer to a base class, which is 7646 // still possible in some cases. 7647 7648 // Otherwise we have to conservatively report that things might be 7649 // okay. 7650 return false; 7651 } 7652 7653 if (!NamedContext->isRecord()) { 7654 // Ideally this would point at the last name in the specifier, 7655 // but we don't have that level of source info. 7656 Diag(SS.getRange().getBegin(), 7657 diag::err_using_decl_nested_name_specifier_is_not_class) 7658 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 7659 return true; 7660 } 7661 7662 if (!NamedContext->isDependentContext() && 7663 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7664 return true; 7665 7666 if (getLangOpts().CPlusPlus11) { 7667 // C++0x [namespace.udecl]p3: 7668 // In a using-declaration used as a member-declaration, the 7669 // nested-name-specifier shall name a base class of the class 7670 // being defined. 7671 7672 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7673 cast<CXXRecordDecl>(NamedContext))) { 7674 if (CurContext == NamedContext) { 7675 Diag(NameLoc, 7676 diag::err_using_decl_nested_name_specifier_is_current_class) 7677 << SS.getRange(); 7678 return true; 7679 } 7680 7681 Diag(SS.getRange().getBegin(), 7682 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7683 << (NestedNameSpecifier*) SS.getScopeRep() 7684 << cast<CXXRecordDecl>(CurContext) 7685 << SS.getRange(); 7686 return true; 7687 } 7688 7689 return false; 7690 } 7691 7692 // C++03 [namespace.udecl]p4: 7693 // A using-declaration used as a member-declaration shall refer 7694 // to a member of a base class of the class being defined [etc.]. 7695 7696 // Salient point: SS doesn't have to name a base class as long as 7697 // lookup only finds members from base classes. Therefore we can 7698 // diagnose here only if we can prove that that can't happen, 7699 // i.e. if the class hierarchies provably don't intersect. 7700 7701 // TODO: it would be nice if "definitely valid" results were cached 7702 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7703 // need to be repeated. 7704 7705 struct UserData { 7706 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7707 7708 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7709 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7710 Data->Bases.insert(Base); 7711 return true; 7712 } 7713 7714 bool hasDependentBases(const CXXRecordDecl *Class) { 7715 return !Class->forallBases(collect, this); 7716 } 7717 7718 /// Returns true if the base is dependent or is one of the 7719 /// accumulated base classes. 7720 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7721 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7722 return !Data->Bases.count(Base); 7723 } 7724 7725 bool mightShareBases(const CXXRecordDecl *Class) { 7726 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7727 } 7728 }; 7729 7730 UserData Data; 7731 7732 // Returns false if we find a dependent base. 7733 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7734 return false; 7735 7736 // Returns false if the class has a dependent base or if it or one 7737 // of its bases is present in the base set of the current context. 7738 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7739 return false; 7740 7741 Diag(SS.getRange().getBegin(), 7742 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7743 << (NestedNameSpecifier*) SS.getScopeRep() 7744 << cast<CXXRecordDecl>(CurContext) 7745 << SS.getRange(); 7746 7747 return true; 7748 } 7749 7750 Decl *Sema::ActOnAliasDeclaration(Scope *S, 7751 AccessSpecifier AS, 7752 MultiTemplateParamsArg TemplateParamLists, 7753 SourceLocation UsingLoc, 7754 UnqualifiedId &Name, 7755 AttributeList *AttrList, 7756 TypeResult Type) { 7757 // Skip up to the relevant declaration scope. 7758 while (S->getFlags() & Scope::TemplateParamScope) 7759 S = S->getParent(); 7760 assert((S->getFlags() & Scope::DeclScope) && 7761 "got alias-declaration outside of declaration scope"); 7762 7763 if (Type.isInvalid()) 7764 return 0; 7765 7766 bool Invalid = false; 7767 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7768 TypeSourceInfo *TInfo = 0; 7769 GetTypeFromParser(Type.get(), &TInfo); 7770 7771 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7772 return 0; 7773 7774 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7775 UPPC_DeclarationType)) { 7776 Invalid = true; 7777 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7778 TInfo->getTypeLoc().getBeginLoc()); 7779 } 7780 7781 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7782 LookupName(Previous, S); 7783 7784 // Warn about shadowing the name of a template parameter. 7785 if (Previous.isSingleResult() && 7786 Previous.getFoundDecl()->isTemplateParameter()) { 7787 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7788 Previous.clear(); 7789 } 7790 7791 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7792 "name in alias declaration must be an identifier"); 7793 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7794 Name.StartLocation, 7795 Name.Identifier, TInfo); 7796 7797 NewTD->setAccess(AS); 7798 7799 if (Invalid) 7800 NewTD->setInvalidDecl(); 7801 7802 ProcessDeclAttributeList(S, NewTD, AttrList); 7803 7804 CheckTypedefForVariablyModifiedType(S, NewTD); 7805 Invalid |= NewTD->isInvalidDecl(); 7806 7807 bool Redeclaration = false; 7808 7809 NamedDecl *NewND; 7810 if (TemplateParamLists.size()) { 7811 TypeAliasTemplateDecl *OldDecl = 0; 7812 TemplateParameterList *OldTemplateParams = 0; 7813 7814 if (TemplateParamLists.size() != 1) { 7815 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7816 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7817 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7818 } 7819 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7820 7821 // Only consider previous declarations in the same scope. 7822 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7823 /*ExplicitInstantiationOrSpecialization*/false); 7824 if (!Previous.empty()) { 7825 Redeclaration = true; 7826 7827 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7828 if (!OldDecl && !Invalid) { 7829 Diag(UsingLoc, diag::err_redefinition_different_kind) 7830 << Name.Identifier; 7831 7832 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7833 if (OldD->getLocation().isValid()) 7834 Diag(OldD->getLocation(), diag::note_previous_definition); 7835 7836 Invalid = true; 7837 } 7838 7839 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7840 if (TemplateParameterListsAreEqual(TemplateParams, 7841 OldDecl->getTemplateParameters(), 7842 /*Complain=*/true, 7843 TPL_TemplateMatch)) 7844 OldTemplateParams = OldDecl->getTemplateParameters(); 7845 else 7846 Invalid = true; 7847 7848 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7849 if (!Invalid && 7850 !Context.hasSameType(OldTD->getUnderlyingType(), 7851 NewTD->getUnderlyingType())) { 7852 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7853 // but we can't reasonably accept it. 7854 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7855 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7856 if (OldTD->getLocation().isValid()) 7857 Diag(OldTD->getLocation(), diag::note_previous_definition); 7858 Invalid = true; 7859 } 7860 } 7861 } 7862 7863 // Merge any previous default template arguments into our parameters, 7864 // and check the parameter list. 7865 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7866 TPC_TypeAliasTemplate)) 7867 return 0; 7868 7869 TypeAliasTemplateDecl *NewDecl = 7870 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7871 Name.Identifier, TemplateParams, 7872 NewTD); 7873 7874 NewDecl->setAccess(AS); 7875 7876 if (Invalid) 7877 NewDecl->setInvalidDecl(); 7878 else if (OldDecl) 7879 NewDecl->setPreviousDecl(OldDecl); 7880 7881 NewND = NewDecl; 7882 } else { 7883 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7884 NewND = NewTD; 7885 } 7886 7887 if (!Redeclaration) 7888 PushOnScopeChains(NewND, S); 7889 7890 ActOnDocumentableDecl(NewND); 7891 return NewND; 7892 } 7893 7894 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7895 SourceLocation NamespaceLoc, 7896 SourceLocation AliasLoc, 7897 IdentifierInfo *Alias, 7898 CXXScopeSpec &SS, 7899 SourceLocation IdentLoc, 7900 IdentifierInfo *Ident) { 7901 7902 // Lookup the namespace name. 7903 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7904 LookupParsedName(R, S, &SS); 7905 7906 // Check if we have a previous declaration with the same name. 7907 NamedDecl *PrevDecl 7908 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7909 ForRedeclaration); 7910 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7911 PrevDecl = 0; 7912 7913 if (PrevDecl) { 7914 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7915 // We already have an alias with the same name that points to the same 7916 // namespace, so don't create a new one. 7917 // FIXME: At some point, we'll want to create the (redundant) 7918 // declaration to maintain better source information. 7919 if (!R.isAmbiguous() && !R.empty() && 7920 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7921 return 0; 7922 } 7923 7924 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7925 diag::err_redefinition_different_kind; 7926 Diag(AliasLoc, DiagID) << Alias; 7927 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7928 return 0; 7929 } 7930 7931 if (R.isAmbiguous()) 7932 return 0; 7933 7934 if (R.empty()) { 7935 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 7936 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7937 return 0; 7938 } 7939 } 7940 7941 NamespaceAliasDecl *AliasDecl = 7942 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 7943 Alias, SS.getWithLocInContext(Context), 7944 IdentLoc, R.getFoundDecl()); 7945 7946 PushOnScopeChains(AliasDecl, S); 7947 return AliasDecl; 7948 } 7949 7950 Sema::ImplicitExceptionSpecification 7951 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 7952 CXXMethodDecl *MD) { 7953 CXXRecordDecl *ClassDecl = MD->getParent(); 7954 7955 // C++ [except.spec]p14: 7956 // An implicitly declared special member function (Clause 12) shall have an 7957 // exception-specification. [...] 7958 ImplicitExceptionSpecification ExceptSpec(*this); 7959 if (ClassDecl->isInvalidDecl()) 7960 return ExceptSpec; 7961 7962 // Direct base-class constructors. 7963 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7964 BEnd = ClassDecl->bases_end(); 7965 B != BEnd; ++B) { 7966 if (B->isVirtual()) // Handled below. 7967 continue; 7968 7969 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7970 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7971 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7972 // If this is a deleted function, add it anyway. This might be conformant 7973 // with the standard. This might not. I'm not sure. It might not matter. 7974 if (Constructor) 7975 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7976 } 7977 } 7978 7979 // Virtual base-class constructors. 7980 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7981 BEnd = ClassDecl->vbases_end(); 7982 B != BEnd; ++B) { 7983 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7984 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7985 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7986 // If this is a deleted function, add it anyway. This might be conformant 7987 // with the standard. This might not. I'm not sure. It might not matter. 7988 if (Constructor) 7989 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7990 } 7991 } 7992 7993 // Field constructors. 7994 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7995 FEnd = ClassDecl->field_end(); 7996 F != FEnd; ++F) { 7997 if (F->hasInClassInitializer()) { 7998 if (Expr *E = F->getInClassInitializer()) 7999 ExceptSpec.CalledExpr(E); 8000 else if (!F->isInvalidDecl()) 8001 // DR1351: 8002 // If the brace-or-equal-initializer of a non-static data member 8003 // invokes a defaulted default constructor of its class or of an 8004 // enclosing class in a potentially evaluated subexpression, the 8005 // program is ill-formed. 8006 // 8007 // This resolution is unworkable: the exception specification of the 8008 // default constructor can be needed in an unevaluated context, in 8009 // particular, in the operand of a noexcept-expression, and we can be 8010 // unable to compute an exception specification for an enclosed class. 8011 // 8012 // We do not allow an in-class initializer to require the evaluation 8013 // of the exception specification for any in-class initializer whose 8014 // definition is not lexically complete. 8015 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 8016 } else if (const RecordType *RecordTy 8017 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8018 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8019 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8020 // If this is a deleted function, add it anyway. This might be conformant 8021 // with the standard. This might not. I'm not sure. It might not matter. 8022 // In particular, the problem is that this function never gets called. It 8023 // might just be ill-formed because this function attempts to refer to 8024 // a deleted function here. 8025 if (Constructor) 8026 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8027 } 8028 } 8029 8030 return ExceptSpec; 8031 } 8032 8033 Sema::ImplicitExceptionSpecification 8034 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8035 CXXRecordDecl *ClassDecl = CD->getParent(); 8036 8037 // C++ [except.spec]p14: 8038 // An inheriting constructor [...] shall have an exception-specification. [...] 8039 ImplicitExceptionSpecification ExceptSpec(*this); 8040 if (ClassDecl->isInvalidDecl()) 8041 return ExceptSpec; 8042 8043 // Inherited constructor. 8044 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8045 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8046 // FIXME: Copying or moving the parameters could add extra exceptions to the 8047 // set, as could the default arguments for the inherited constructor. This 8048 // will be addressed when we implement the resolution of core issue 1351. 8049 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8050 8051 // Direct base-class constructors. 8052 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8053 BEnd = ClassDecl->bases_end(); 8054 B != BEnd; ++B) { 8055 if (B->isVirtual()) // Handled below. 8056 continue; 8057 8058 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8059 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8060 if (BaseClassDecl == InheritedDecl) 8061 continue; 8062 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8063 if (Constructor) 8064 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 8065 } 8066 } 8067 8068 // Virtual base-class constructors. 8069 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8070 BEnd = ClassDecl->vbases_end(); 8071 B != BEnd; ++B) { 8072 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8073 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8074 if (BaseClassDecl == InheritedDecl) 8075 continue; 8076 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8077 if (Constructor) 8078 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 8079 } 8080 } 8081 8082 // Field constructors. 8083 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8084 FEnd = ClassDecl->field_end(); 8085 F != FEnd; ++F) { 8086 if (F->hasInClassInitializer()) { 8087 if (Expr *E = F->getInClassInitializer()) 8088 ExceptSpec.CalledExpr(E); 8089 else if (!F->isInvalidDecl()) 8090 Diag(CD->getLocation(), 8091 diag::err_in_class_initializer_references_def_ctor) << CD; 8092 } else if (const RecordType *RecordTy 8093 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8094 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8095 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8096 if (Constructor) 8097 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8098 } 8099 } 8100 8101 return ExceptSpec; 8102 } 8103 8104 namespace { 8105 /// RAII object to register a special member as being currently declared. 8106 struct DeclaringSpecialMember { 8107 Sema &S; 8108 Sema::SpecialMemberDecl D; 8109 bool WasAlreadyBeingDeclared; 8110 8111 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8112 : S(S), D(RD, CSM) { 8113 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 8114 if (WasAlreadyBeingDeclared) 8115 // This almost never happens, but if it does, ensure that our cache 8116 // doesn't contain a stale result. 8117 S.SpecialMemberCache.clear(); 8118 8119 // FIXME: Register a note to be produced if we encounter an error while 8120 // declaring the special member. 8121 } 8122 ~DeclaringSpecialMember() { 8123 if (!WasAlreadyBeingDeclared) 8124 S.SpecialMembersBeingDeclared.erase(D); 8125 } 8126 8127 /// \brief Are we already trying to declare this special member? 8128 bool isAlreadyBeingDeclared() const { 8129 return WasAlreadyBeingDeclared; 8130 } 8131 }; 8132 } 8133 8134 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8135 CXXRecordDecl *ClassDecl) { 8136 // C++ [class.ctor]p5: 8137 // A default constructor for a class X is a constructor of class X 8138 // that can be called without an argument. If there is no 8139 // user-declared constructor for class X, a default constructor is 8140 // implicitly declared. An implicitly-declared default constructor 8141 // is an inline public member of its class. 8142 assert(ClassDecl->needsImplicitDefaultConstructor() && 8143 "Should not build implicit default constructor!"); 8144 8145 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8146 if (DSM.isAlreadyBeingDeclared()) 8147 return 0; 8148 8149 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8150 CXXDefaultConstructor, 8151 false); 8152 8153 // Create the actual constructor declaration. 8154 CanQualType ClassType 8155 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8156 SourceLocation ClassLoc = ClassDecl->getLocation(); 8157 DeclarationName Name 8158 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8159 DeclarationNameInfo NameInfo(Name, ClassLoc); 8160 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8161 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 8162 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8163 Constexpr); 8164 DefaultCon->setAccess(AS_public); 8165 DefaultCon->setDefaulted(); 8166 DefaultCon->setImplicit(); 8167 8168 // Build an exception specification pointing back at this constructor. 8169 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8170 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8171 8172 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8173 // constructors is easy to compute. 8174 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8175 8176 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8177 SetDeclDeleted(DefaultCon, ClassLoc); 8178 8179 // Note that we have declared this constructor. 8180 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8181 8182 if (Scope *S = getScopeForContext(ClassDecl)) 8183 PushOnScopeChains(DefaultCon, S, false); 8184 ClassDecl->addDecl(DefaultCon); 8185 8186 return DefaultCon; 8187 } 8188 8189 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8190 CXXConstructorDecl *Constructor) { 8191 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8192 !Constructor->doesThisDeclarationHaveABody() && 8193 !Constructor->isDeleted()) && 8194 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8195 8196 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8197 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8198 8199 SynthesizedFunctionScope Scope(*this, Constructor); 8200 DiagnosticErrorTrap Trap(Diags); 8201 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8202 Trap.hasErrorOccurred()) { 8203 Diag(CurrentLocation, diag::note_member_synthesized_at) 8204 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8205 Constructor->setInvalidDecl(); 8206 return; 8207 } 8208 8209 SourceLocation Loc = Constructor->getLocation(); 8210 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8211 8212 Constructor->markUsed(Context); 8213 MarkVTableUsed(CurrentLocation, ClassDecl); 8214 8215 if (ASTMutationListener *L = getASTMutationListener()) { 8216 L->CompletedImplicitDefinition(Constructor); 8217 } 8218 } 8219 8220 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8221 // Perform any delayed checks on exception specifications. 8222 CheckDelayedMemberExceptionSpecs(); 8223 8224 // Once all the member initializers are processed, perform checks to see if 8225 // any unintialized use is happeneing. 8226 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, 8227 D->getLocation()) 8228 == DiagnosticsEngine::Ignored) 8229 return; 8230 8231 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D); 8232 if (!RD) return; 8233 8234 // Holds fields that are uninitialized. 8235 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 8236 8237 // In the beginning, every field is uninitialized. 8238 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end(); 8239 I != E; ++I) { 8240 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) { 8241 UninitializedFields.insert(FD); 8242 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) { 8243 UninitializedFields.insert(IFD->getAnonField()); 8244 } 8245 } 8246 8247 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end(); 8248 I != E; ++I) { 8249 FieldDecl *FD = dyn_cast<FieldDecl>(*I); 8250 if (!FD) 8251 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) 8252 FD = IFD->getAnonField(); 8253 8254 if (!FD) 8255 continue; 8256 8257 Expr *InitExpr = FD->getInClassInitializer(); 8258 if (!InitExpr) { 8259 // Uninitialized reference types will give an error. 8260 // Record types with an initializer are default initialized. 8261 QualType FieldType = FD->getType(); 8262 if (FieldType->isReferenceType() || FieldType->isRecordType()) 8263 UninitializedFields.erase(FD); 8264 continue; 8265 } 8266 8267 CheckInitExprContainsUninitializedFields( 8268 *this, InitExpr, FD, UninitializedFields, 8269 UninitializedFields.count(FD)/*WarnOnSelfReference*/); 8270 8271 UninitializedFields.erase(FD); 8272 } 8273 } 8274 8275 namespace { 8276 /// Information on inheriting constructors to declare. 8277 class InheritingConstructorInfo { 8278 public: 8279 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8280 : SemaRef(SemaRef), Derived(Derived) { 8281 // Mark the constructors that we already have in the derived class. 8282 // 8283 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8284 // unless there is a user-declared constructor with the same signature in 8285 // the class where the using-declaration appears. 8286 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8287 } 8288 8289 void inheritAll(CXXRecordDecl *RD) { 8290 visitAll(RD, &InheritingConstructorInfo::inherit); 8291 } 8292 8293 private: 8294 /// Information about an inheriting constructor. 8295 struct InheritingConstructor { 8296 InheritingConstructor() 8297 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {} 8298 8299 /// If \c true, a constructor with this signature is already declared 8300 /// in the derived class. 8301 bool DeclaredInDerived; 8302 8303 /// The constructor which is inherited. 8304 const CXXConstructorDecl *BaseCtor; 8305 8306 /// The derived constructor we declared. 8307 CXXConstructorDecl *DerivedCtor; 8308 }; 8309 8310 /// Inheriting constructors with a given canonical type. There can be at 8311 /// most one such non-template constructor, and any number of templated 8312 /// constructors. 8313 struct InheritingConstructorsForType { 8314 InheritingConstructor NonTemplate; 8315 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8316 Templates; 8317 8318 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8319 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8320 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8321 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8322 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8323 false, S.TPL_TemplateMatch)) 8324 return Templates[I].second; 8325 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8326 return Templates.back().second; 8327 } 8328 8329 return NonTemplate; 8330 } 8331 }; 8332 8333 /// Get or create the inheriting constructor record for a constructor. 8334 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8335 QualType CtorType) { 8336 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8337 .getEntry(SemaRef, Ctor); 8338 } 8339 8340 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8341 8342 /// Process all constructors for a class. 8343 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8344 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(), 8345 CtorE = RD->ctor_end(); 8346 CtorIt != CtorE; ++CtorIt) 8347 (this->*Callback)(*CtorIt); 8348 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8349 I(RD->decls_begin()), E(RD->decls_end()); 8350 I != E; ++I) { 8351 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8352 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8353 (this->*Callback)(CD); 8354 } 8355 } 8356 8357 /// Note that a constructor (or constructor template) was declared in Derived. 8358 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8359 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8360 } 8361 8362 /// Inherit a single constructor. 8363 void inherit(const CXXConstructorDecl *Ctor) { 8364 const FunctionProtoType *CtorType = 8365 Ctor->getType()->castAs<FunctionProtoType>(); 8366 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes()); 8367 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8368 8369 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8370 8371 // Core issue (no number yet): the ellipsis is always discarded. 8372 if (EPI.Variadic) { 8373 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8374 SemaRef.Diag(Ctor->getLocation(), 8375 diag::note_using_decl_constructor_ellipsis); 8376 EPI.Variadic = false; 8377 } 8378 8379 // Declare a constructor for each number of parameters. 8380 // 8381 // C++11 [class.inhctor]p1: 8382 // The candidate set of inherited constructors from the class X named in 8383 // the using-declaration consists of [... modulo defects ...] for each 8384 // constructor or constructor template of X, the set of constructors or 8385 // constructor templates that results from omitting any ellipsis parameter 8386 // specification and successively omitting parameters with a default 8387 // argument from the end of the parameter-type-list 8388 unsigned MinParams = minParamsToInherit(Ctor); 8389 unsigned Params = Ctor->getNumParams(); 8390 if (Params >= MinParams) { 8391 do 8392 declareCtor(UsingLoc, Ctor, 8393 SemaRef.Context.getFunctionType( 8394 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI)); 8395 while (Params > MinParams && 8396 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8397 } 8398 } 8399 8400 /// Find the using-declaration which specified that we should inherit the 8401 /// constructors of \p Base. 8402 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8403 // No fancy lookup required; just look for the base constructor name 8404 // directly within the derived class. 8405 ASTContext &Context = SemaRef.Context; 8406 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8407 Context.getCanonicalType(Context.getRecordType(Base))); 8408 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8409 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8410 } 8411 8412 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8413 // C++11 [class.inhctor]p3: 8414 // [F]or each constructor template in the candidate set of inherited 8415 // constructors, a constructor template is implicitly declared 8416 if (Ctor->getDescribedFunctionTemplate()) 8417 return 0; 8418 8419 // For each non-template constructor in the candidate set of inherited 8420 // constructors other than a constructor having no parameters or a 8421 // copy/move constructor having a single parameter, a constructor is 8422 // implicitly declared [...] 8423 if (Ctor->getNumParams() == 0) 8424 return 1; 8425 if (Ctor->isCopyOrMoveConstructor()) 8426 return 2; 8427 8428 // Per discussion on core reflector, never inherit a constructor which 8429 // would become a default, copy, or move constructor of Derived either. 8430 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8431 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8432 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8433 } 8434 8435 /// Declare a single inheriting constructor, inheriting the specified 8436 /// constructor, with the given type. 8437 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8438 QualType DerivedType) { 8439 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8440 8441 // C++11 [class.inhctor]p3: 8442 // ... a constructor is implicitly declared with the same constructor 8443 // characteristics unless there is a user-declared constructor with 8444 // the same signature in the class where the using-declaration appears 8445 if (Entry.DeclaredInDerived) 8446 return; 8447 8448 // C++11 [class.inhctor]p7: 8449 // If two using-declarations declare inheriting constructors with the 8450 // same signature, the program is ill-formed 8451 if (Entry.DerivedCtor) { 8452 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8453 // Only diagnose this once per constructor. 8454 if (Entry.DerivedCtor->isInvalidDecl()) 8455 return; 8456 Entry.DerivedCtor->setInvalidDecl(); 8457 8458 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8459 SemaRef.Diag(BaseCtor->getLocation(), 8460 diag::note_using_decl_constructor_conflict_current_ctor); 8461 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8462 diag::note_using_decl_constructor_conflict_previous_ctor); 8463 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8464 diag::note_using_decl_constructor_conflict_previous_using); 8465 } else { 8466 // Core issue (no number): if the same inheriting constructor is 8467 // produced by multiple base class constructors from the same base 8468 // class, the inheriting constructor is defined as deleted. 8469 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8470 } 8471 8472 return; 8473 } 8474 8475 ASTContext &Context = SemaRef.Context; 8476 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8477 Context.getCanonicalType(Context.getRecordType(Derived))); 8478 DeclarationNameInfo NameInfo(Name, UsingLoc); 8479 8480 TemplateParameterList *TemplateParams = 0; 8481 if (const FunctionTemplateDecl *FTD = 8482 BaseCtor->getDescribedFunctionTemplate()) { 8483 TemplateParams = FTD->getTemplateParameters(); 8484 // We're reusing template parameters from a different DeclContext. This 8485 // is questionable at best, but works out because the template depth in 8486 // both places is guaranteed to be 0. 8487 // FIXME: Rebuild the template parameters in the new context, and 8488 // transform the function type to refer to them. 8489 } 8490 8491 // Build type source info pointing at the using-declaration. This is 8492 // required by template instantiation. 8493 TypeSourceInfo *TInfo = 8494 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8495 FunctionProtoTypeLoc ProtoLoc = 8496 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8497 8498 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8499 Context, Derived, UsingLoc, NameInfo, DerivedType, 8500 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8501 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8502 8503 // Build an unevaluated exception specification for this constructor. 8504 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8505 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8506 EPI.ExceptionSpecType = EST_Unevaluated; 8507 EPI.ExceptionSpecDecl = DerivedCtor; 8508 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(), 8509 FPT->getArgTypes(), EPI)); 8510 8511 // Build the parameter declarations. 8512 SmallVector<ParmVarDecl *, 16> ParamDecls; 8513 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) { 8514 TypeSourceInfo *TInfo = 8515 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc); 8516 ParmVarDecl *PD = ParmVarDecl::Create( 8517 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0, 8518 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0); 8519 PD->setScopeInfo(0, I); 8520 PD->setImplicit(); 8521 ParamDecls.push_back(PD); 8522 ProtoLoc.setArg(I, PD); 8523 } 8524 8525 // Set up the new constructor. 8526 DerivedCtor->setAccess(BaseCtor->getAccess()); 8527 DerivedCtor->setParams(ParamDecls); 8528 DerivedCtor->setInheritedConstructor(BaseCtor); 8529 if (BaseCtor->isDeleted()) 8530 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8531 8532 // If this is a constructor template, build the template declaration. 8533 if (TemplateParams) { 8534 FunctionTemplateDecl *DerivedTemplate = 8535 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8536 TemplateParams, DerivedCtor); 8537 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8538 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8539 Derived->addDecl(DerivedTemplate); 8540 } else { 8541 Derived->addDecl(DerivedCtor); 8542 } 8543 8544 Entry.BaseCtor = BaseCtor; 8545 Entry.DerivedCtor = DerivedCtor; 8546 } 8547 8548 Sema &SemaRef; 8549 CXXRecordDecl *Derived; 8550 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8551 MapType Map; 8552 }; 8553 } 8554 8555 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8556 // Defer declaring the inheriting constructors until the class is 8557 // instantiated. 8558 if (ClassDecl->isDependentContext()) 8559 return; 8560 8561 // Find base classes from which we might inherit constructors. 8562 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8563 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 8564 BaseE = ClassDecl->bases_end(); 8565 BaseIt != BaseE; ++BaseIt) 8566 if (BaseIt->getInheritConstructors()) 8567 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl()); 8568 8569 // Go no further if we're not inheriting any constructors. 8570 if (InheritedBases.empty()) 8571 return; 8572 8573 // Declare the inherited constructors. 8574 InheritingConstructorInfo ICI(*this, ClassDecl); 8575 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8576 ICI.inheritAll(InheritedBases[I]); 8577 } 8578 8579 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8580 CXXConstructorDecl *Constructor) { 8581 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8582 assert(Constructor->getInheritedConstructor() && 8583 !Constructor->doesThisDeclarationHaveABody() && 8584 !Constructor->isDeleted()); 8585 8586 SynthesizedFunctionScope Scope(*this, Constructor); 8587 DiagnosticErrorTrap Trap(Diags); 8588 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8589 Trap.hasErrorOccurred()) { 8590 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8591 << Context.getTagDeclType(ClassDecl); 8592 Constructor->setInvalidDecl(); 8593 return; 8594 } 8595 8596 SourceLocation Loc = Constructor->getLocation(); 8597 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8598 8599 Constructor->markUsed(Context); 8600 MarkVTableUsed(CurrentLocation, ClassDecl); 8601 8602 if (ASTMutationListener *L = getASTMutationListener()) { 8603 L->CompletedImplicitDefinition(Constructor); 8604 } 8605 } 8606 8607 8608 Sema::ImplicitExceptionSpecification 8609 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8610 CXXRecordDecl *ClassDecl = MD->getParent(); 8611 8612 // C++ [except.spec]p14: 8613 // An implicitly declared special member function (Clause 12) shall have 8614 // an exception-specification. 8615 ImplicitExceptionSpecification ExceptSpec(*this); 8616 if (ClassDecl->isInvalidDecl()) 8617 return ExceptSpec; 8618 8619 // Direct base-class destructors. 8620 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8621 BEnd = ClassDecl->bases_end(); 8622 B != BEnd; ++B) { 8623 if (B->isVirtual()) // Handled below. 8624 continue; 8625 8626 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8627 ExceptSpec.CalledDecl(B->getLocStart(), 8628 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8629 } 8630 8631 // Virtual base-class destructors. 8632 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8633 BEnd = ClassDecl->vbases_end(); 8634 B != BEnd; ++B) { 8635 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8636 ExceptSpec.CalledDecl(B->getLocStart(), 8637 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8638 } 8639 8640 // Field destructors. 8641 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8642 FEnd = ClassDecl->field_end(); 8643 F != FEnd; ++F) { 8644 if (const RecordType *RecordTy 8645 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8646 ExceptSpec.CalledDecl(F->getLocation(), 8647 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8648 } 8649 8650 return ExceptSpec; 8651 } 8652 8653 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8654 // C++ [class.dtor]p2: 8655 // If a class has no user-declared destructor, a destructor is 8656 // declared implicitly. An implicitly-declared destructor is an 8657 // inline public member of its class. 8658 assert(ClassDecl->needsImplicitDestructor()); 8659 8660 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8661 if (DSM.isAlreadyBeingDeclared()) 8662 return 0; 8663 8664 // Create the actual destructor declaration. 8665 CanQualType ClassType 8666 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8667 SourceLocation ClassLoc = ClassDecl->getLocation(); 8668 DeclarationName Name 8669 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8670 DeclarationNameInfo NameInfo(Name, ClassLoc); 8671 CXXDestructorDecl *Destructor 8672 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8673 QualType(), 0, /*isInline=*/true, 8674 /*isImplicitlyDeclared=*/true); 8675 Destructor->setAccess(AS_public); 8676 Destructor->setDefaulted(); 8677 Destructor->setImplicit(); 8678 8679 // Build an exception specification pointing back at this destructor. 8680 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 8681 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8682 8683 AddOverriddenMethods(ClassDecl, Destructor); 8684 8685 // We don't need to use SpecialMemberIsTrivial here; triviality for 8686 // destructors is easy to compute. 8687 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8688 8689 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8690 SetDeclDeleted(Destructor, ClassLoc); 8691 8692 // Note that we have declared this destructor. 8693 ++ASTContext::NumImplicitDestructorsDeclared; 8694 8695 // Introduce this destructor into its scope. 8696 if (Scope *S = getScopeForContext(ClassDecl)) 8697 PushOnScopeChains(Destructor, S, false); 8698 ClassDecl->addDecl(Destructor); 8699 8700 return Destructor; 8701 } 8702 8703 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8704 CXXDestructorDecl *Destructor) { 8705 assert((Destructor->isDefaulted() && 8706 !Destructor->doesThisDeclarationHaveABody() && 8707 !Destructor->isDeleted()) && 8708 "DefineImplicitDestructor - call it for implicit default dtor"); 8709 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8710 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8711 8712 if (Destructor->isInvalidDecl()) 8713 return; 8714 8715 SynthesizedFunctionScope Scope(*this, Destructor); 8716 8717 DiagnosticErrorTrap Trap(Diags); 8718 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8719 Destructor->getParent()); 8720 8721 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8722 Diag(CurrentLocation, diag::note_member_synthesized_at) 8723 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8724 8725 Destructor->setInvalidDecl(); 8726 return; 8727 } 8728 8729 SourceLocation Loc = Destructor->getLocation(); 8730 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8731 Destructor->markUsed(Context); 8732 MarkVTableUsed(CurrentLocation, ClassDecl); 8733 8734 if (ASTMutationListener *L = getASTMutationListener()) { 8735 L->CompletedImplicitDefinition(Destructor); 8736 } 8737 } 8738 8739 /// \brief Perform any semantic analysis which needs to be delayed until all 8740 /// pending class member declarations have been parsed. 8741 void Sema::ActOnFinishCXXMemberDecls() { 8742 // If the context is an invalid C++ class, just suppress these checks. 8743 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8744 if (Record->isInvalidDecl()) { 8745 DelayedDefaultedMemberExceptionSpecs.clear(); 8746 DelayedDestructorExceptionSpecChecks.clear(); 8747 return; 8748 } 8749 } 8750 } 8751 8752 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8753 CXXDestructorDecl *Destructor) { 8754 assert(getLangOpts().CPlusPlus11 && 8755 "adjusting dtor exception specs was introduced in c++11"); 8756 8757 // C++11 [class.dtor]p3: 8758 // A declaration of a destructor that does not have an exception- 8759 // specification is implicitly considered to have the same exception- 8760 // specification as an implicit declaration. 8761 const FunctionProtoType *DtorType = Destructor->getType()-> 8762 getAs<FunctionProtoType>(); 8763 if (DtorType->hasExceptionSpec()) 8764 return; 8765 8766 // Replace the destructor's type, building off the existing one. Fortunately, 8767 // the only thing of interest in the destructor type is its extended info. 8768 // The return and arguments are fixed. 8769 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8770 EPI.ExceptionSpecType = EST_Unevaluated; 8771 EPI.ExceptionSpecDecl = Destructor; 8772 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8773 8774 // FIXME: If the destructor has a body that could throw, and the newly created 8775 // spec doesn't allow exceptions, we should emit a warning, because this 8776 // change in behavior can break conforming C++03 programs at runtime. 8777 // However, we don't have a body or an exception specification yet, so it 8778 // needs to be done somewhere else. 8779 } 8780 8781 namespace { 8782 /// \brief An abstract base class for all helper classes used in building the 8783 // copy/move operators. These classes serve as factory functions and help us 8784 // avoid using the same Expr* in the AST twice. 8785 class ExprBuilder { 8786 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8787 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8788 8789 protected: 8790 static Expr *assertNotNull(Expr *E) { 8791 assert(E && "Expression construction must not fail."); 8792 return E; 8793 } 8794 8795 public: 8796 ExprBuilder() {} 8797 virtual ~ExprBuilder() {} 8798 8799 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 8800 }; 8801 8802 class RefBuilder: public ExprBuilder { 8803 VarDecl *Var; 8804 QualType VarType; 8805 8806 public: 8807 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8808 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take()); 8809 } 8810 8811 RefBuilder(VarDecl *Var, QualType VarType) 8812 : Var(Var), VarType(VarType) {} 8813 }; 8814 8815 class ThisBuilder: public ExprBuilder { 8816 public: 8817 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8818 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>()); 8819 } 8820 }; 8821 8822 class CastBuilder: public ExprBuilder { 8823 const ExprBuilder &Builder; 8824 QualType Type; 8825 ExprValueKind Kind; 8826 const CXXCastPath &Path; 8827 8828 public: 8829 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8830 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 8831 CK_UncheckedDerivedToBase, Kind, 8832 &Path).take()); 8833 } 8834 8835 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 8836 const CXXCastPath &Path) 8837 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 8838 }; 8839 8840 class DerefBuilder: public ExprBuilder { 8841 const ExprBuilder &Builder; 8842 8843 public: 8844 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8845 return assertNotNull( 8846 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take()); 8847 } 8848 8849 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8850 }; 8851 8852 class MemberBuilder: public ExprBuilder { 8853 const ExprBuilder &Builder; 8854 QualType Type; 8855 CXXScopeSpec SS; 8856 bool IsArrow; 8857 LookupResult &MemberLookup; 8858 8859 public: 8860 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8861 return assertNotNull(S.BuildMemberReferenceExpr( 8862 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0, 8863 MemberLookup, 0).take()); 8864 } 8865 8866 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 8867 LookupResult &MemberLookup) 8868 : Builder(Builder), Type(Type), IsArrow(IsArrow), 8869 MemberLookup(MemberLookup) {} 8870 }; 8871 8872 class MoveCastBuilder: public ExprBuilder { 8873 const ExprBuilder &Builder; 8874 8875 public: 8876 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8877 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 8878 } 8879 8880 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8881 }; 8882 8883 class LvalueConvBuilder: public ExprBuilder { 8884 const ExprBuilder &Builder; 8885 8886 public: 8887 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8888 return assertNotNull( 8889 S.DefaultLvalueConversion(Builder.build(S, Loc)).take()); 8890 } 8891 8892 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8893 }; 8894 8895 class SubscriptBuilder: public ExprBuilder { 8896 const ExprBuilder &Base; 8897 const ExprBuilder &Index; 8898 8899 public: 8900 virtual Expr *build(Sema &S, SourceLocation Loc) const 8901 LLVM_OVERRIDE { 8902 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 8903 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take()); 8904 } 8905 8906 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 8907 : Base(Base), Index(Index) {} 8908 }; 8909 8910 } // end anonymous namespace 8911 8912 /// When generating a defaulted copy or move assignment operator, if a field 8913 /// should be copied with __builtin_memcpy rather than via explicit assignments, 8914 /// do so. This optimization only applies for arrays of scalars, and for arrays 8915 /// of class type where the selected copy/move-assignment operator is trivial. 8916 static StmtResult 8917 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 8918 const ExprBuilder &ToB, const ExprBuilder &FromB) { 8919 // Compute the size of the memory buffer to be copied. 8920 QualType SizeType = S.Context.getSizeType(); 8921 llvm::APInt Size(S.Context.getTypeSize(SizeType), 8922 S.Context.getTypeSizeInChars(T).getQuantity()); 8923 8924 // Take the address of the field references for "from" and "to". We 8925 // directly construct UnaryOperators here because semantic analysis 8926 // does not permit us to take the address of an xvalue. 8927 Expr *From = FromB.build(S, Loc); 8928 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 8929 S.Context.getPointerType(From->getType()), 8930 VK_RValue, OK_Ordinary, Loc); 8931 Expr *To = ToB.build(S, Loc); 8932 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 8933 S.Context.getPointerType(To->getType()), 8934 VK_RValue, OK_Ordinary, Loc); 8935 8936 const Type *E = T->getBaseElementTypeUnsafe(); 8937 bool NeedsCollectableMemCpy = 8938 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 8939 8940 // Create a reference to the __builtin_objc_memmove_collectable function 8941 StringRef MemCpyName = NeedsCollectableMemCpy ? 8942 "__builtin_objc_memmove_collectable" : 8943 "__builtin_memcpy"; 8944 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 8945 Sema::LookupOrdinaryName); 8946 S.LookupName(R, S.TUScope, true); 8947 8948 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 8949 if (!MemCpy) 8950 // Something went horribly wrong earlier, and we will have complained 8951 // about it. 8952 return StmtError(); 8953 8954 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 8955 VK_RValue, Loc, 0); 8956 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 8957 8958 Expr *CallArgs[] = { 8959 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 8960 }; 8961 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(), 8962 Loc, CallArgs, Loc); 8963 8964 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8965 return S.Owned(Call.takeAs<Stmt>()); 8966 } 8967 8968 /// \brief Builds a statement that copies/moves the given entity from \p From to 8969 /// \c To. 8970 /// 8971 /// This routine is used to copy/move the members of a class with an 8972 /// implicitly-declared copy/move assignment operator. When the entities being 8973 /// copied are arrays, this routine builds for loops to copy them. 8974 /// 8975 /// \param S The Sema object used for type-checking. 8976 /// 8977 /// \param Loc The location where the implicit copy/move is being generated. 8978 /// 8979 /// \param T The type of the expressions being copied/moved. Both expressions 8980 /// must have this type. 8981 /// 8982 /// \param To The expression we are copying/moving to. 8983 /// 8984 /// \param From The expression we are copying/moving from. 8985 /// 8986 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 8987 /// Otherwise, it's a non-static member subobject. 8988 /// 8989 /// \param Copying Whether we're copying or moving. 8990 /// 8991 /// \param Depth Internal parameter recording the depth of the recursion. 8992 /// 8993 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 8994 /// if a memcpy should be used instead. 8995 static StmtResult 8996 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 8997 const ExprBuilder &To, const ExprBuilder &From, 8998 bool CopyingBaseSubobject, bool Copying, 8999 unsigned Depth = 0) { 9000 // C++11 [class.copy]p28: 9001 // Each subobject is assigned in the manner appropriate to its type: 9002 // 9003 // - if the subobject is of class type, as if by a call to operator= with 9004 // the subobject as the object expression and the corresponding 9005 // subobject of x as a single function argument (as if by explicit 9006 // qualification; that is, ignoring any possible virtual overriding 9007 // functions in more derived classes); 9008 // 9009 // C++03 [class.copy]p13: 9010 // - if the subobject is of class type, the copy assignment operator for 9011 // the class is used (as if by explicit qualification; that is, 9012 // ignoring any possible virtual overriding functions in more derived 9013 // classes); 9014 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9015 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9016 9017 // Look for operator=. 9018 DeclarationName Name 9019 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9020 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9021 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9022 9023 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9024 // operator. 9025 if (!S.getLangOpts().CPlusPlus11) { 9026 LookupResult::Filter F = OpLookup.makeFilter(); 9027 while (F.hasNext()) { 9028 NamedDecl *D = F.next(); 9029 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9030 if (Method->isCopyAssignmentOperator() || 9031 (!Copying && Method->isMoveAssignmentOperator())) 9032 continue; 9033 9034 F.erase(); 9035 } 9036 F.done(); 9037 } 9038 9039 // Suppress the protected check (C++ [class.protected]) for each of the 9040 // assignment operators we found. This strange dance is required when 9041 // we're assigning via a base classes's copy-assignment operator. To 9042 // ensure that we're getting the right base class subobject (without 9043 // ambiguities), we need to cast "this" to that subobject type; to 9044 // ensure that we don't go through the virtual call mechanism, we need 9045 // to qualify the operator= name with the base class (see below). However, 9046 // this means that if the base class has a protected copy assignment 9047 // operator, the protected member access check will fail. So, we 9048 // rewrite "protected" access to "public" access in this case, since we 9049 // know by construction that we're calling from a derived class. 9050 if (CopyingBaseSubobject) { 9051 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9052 L != LEnd; ++L) { 9053 if (L.getAccess() == AS_protected) 9054 L.setAccess(AS_public); 9055 } 9056 } 9057 9058 // Create the nested-name-specifier that will be used to qualify the 9059 // reference to operator=; this is required to suppress the virtual 9060 // call mechanism. 9061 CXXScopeSpec SS; 9062 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9063 SS.MakeTrivial(S.Context, 9064 NestedNameSpecifier::Create(S.Context, 0, false, 9065 CanonicalT), 9066 Loc); 9067 9068 // Create the reference to operator=. 9069 ExprResult OpEqualRef 9070 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9071 SS, /*TemplateKWLoc=*/SourceLocation(), 9072 /*FirstQualifierInScope=*/0, 9073 OpLookup, 9074 /*TemplateArgs=*/0, 9075 /*SuppressQualifierCheck=*/true); 9076 if (OpEqualRef.isInvalid()) 9077 return StmtError(); 9078 9079 // Build the call to the assignment operator. 9080 9081 Expr *FromInst = From.build(S, Loc); 9082 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 9083 OpEqualRef.takeAs<Expr>(), 9084 Loc, FromInst, Loc); 9085 if (Call.isInvalid()) 9086 return StmtError(); 9087 9088 // If we built a call to a trivial 'operator=' while copying an array, 9089 // bail out. We'll replace the whole shebang with a memcpy. 9090 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9091 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9092 return StmtResult((Stmt*)0); 9093 9094 // Convert to an expression-statement, and clean up any produced 9095 // temporaries. 9096 return S.ActOnExprStmt(Call); 9097 } 9098 9099 // - if the subobject is of scalar type, the built-in assignment 9100 // operator is used. 9101 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9102 if (!ArrayTy) { 9103 ExprResult Assignment = S.CreateBuiltinBinOp( 9104 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9105 if (Assignment.isInvalid()) 9106 return StmtError(); 9107 return S.ActOnExprStmt(Assignment); 9108 } 9109 9110 // - if the subobject is an array, each element is assigned, in the 9111 // manner appropriate to the element type; 9112 9113 // Construct a loop over the array bounds, e.g., 9114 // 9115 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9116 // 9117 // that will copy each of the array elements. 9118 QualType SizeType = S.Context.getSizeType(); 9119 9120 // Create the iteration variable. 9121 IdentifierInfo *IterationVarName = 0; 9122 { 9123 SmallString<8> Str; 9124 llvm::raw_svector_ostream OS(Str); 9125 OS << "__i" << Depth; 9126 IterationVarName = &S.Context.Idents.get(OS.str()); 9127 } 9128 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9129 IterationVarName, SizeType, 9130 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9131 SC_None); 9132 9133 // Initialize the iteration variable to zero. 9134 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9135 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9136 9137 // Creates a reference to the iteration variable. 9138 RefBuilder IterationVarRef(IterationVar, SizeType); 9139 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9140 9141 // Create the DeclStmt that holds the iteration variable. 9142 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9143 9144 // Subscript the "from" and "to" expressions with the iteration variable. 9145 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9146 MoveCastBuilder FromIndexMove(FromIndexCopy); 9147 const ExprBuilder *FromIndex; 9148 if (Copying) 9149 FromIndex = &FromIndexCopy; 9150 else 9151 FromIndex = &FromIndexMove; 9152 9153 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9154 9155 // Build the copy/move for an individual element of the array. 9156 StmtResult Copy = 9157 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9158 ToIndex, *FromIndex, CopyingBaseSubobject, 9159 Copying, Depth + 1); 9160 // Bail out if copying fails or if we determined that we should use memcpy. 9161 if (Copy.isInvalid() || !Copy.get()) 9162 return Copy; 9163 9164 // Create the comparison against the array bound. 9165 llvm::APInt Upper 9166 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9167 Expr *Comparison 9168 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9169 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9170 BO_NE, S.Context.BoolTy, 9171 VK_RValue, OK_Ordinary, Loc, false); 9172 9173 // Create the pre-increment of the iteration variable. 9174 Expr *Increment 9175 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9176 SizeType, VK_LValue, OK_Ordinary, Loc); 9177 9178 // Construct the loop that copies all elements of this array. 9179 return S.ActOnForStmt(Loc, Loc, InitStmt, 9180 S.MakeFullExpr(Comparison), 9181 0, S.MakeFullDiscardedValueExpr(Increment), 9182 Loc, Copy.take()); 9183 } 9184 9185 static StmtResult 9186 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9187 const ExprBuilder &To, const ExprBuilder &From, 9188 bool CopyingBaseSubobject, bool Copying) { 9189 // Maybe we should use a memcpy? 9190 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9191 T.isTriviallyCopyableType(S.Context)) 9192 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9193 9194 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9195 CopyingBaseSubobject, 9196 Copying, 0)); 9197 9198 // If we ended up picking a trivial assignment operator for an array of a 9199 // non-trivially-copyable class type, just emit a memcpy. 9200 if (!Result.isInvalid() && !Result.get()) 9201 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9202 9203 return Result; 9204 } 9205 9206 Sema::ImplicitExceptionSpecification 9207 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9208 CXXRecordDecl *ClassDecl = MD->getParent(); 9209 9210 ImplicitExceptionSpecification ExceptSpec(*this); 9211 if (ClassDecl->isInvalidDecl()) 9212 return ExceptSpec; 9213 9214 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9215 assert(T->getNumArgs() == 1 && "not a copy assignment op"); 9216 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 9217 9218 // C++ [except.spec]p14: 9219 // An implicitly declared special member function (Clause 12) shall have an 9220 // exception-specification. [...] 9221 9222 // It is unspecified whether or not an implicit copy assignment operator 9223 // attempts to deduplicate calls to assignment operators of virtual bases are 9224 // made. As such, this exception specification is effectively unspecified. 9225 // Based on a similar decision made for constness in C++0x, we're erring on 9226 // the side of assuming such calls to be made regardless of whether they 9227 // actually happen. 9228 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9229 BaseEnd = ClassDecl->bases_end(); 9230 Base != BaseEnd; ++Base) { 9231 if (Base->isVirtual()) 9232 continue; 9233 9234 CXXRecordDecl *BaseClassDecl 9235 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9236 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9237 ArgQuals, false, 0)) 9238 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 9239 } 9240 9241 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9242 BaseEnd = ClassDecl->vbases_end(); 9243 Base != BaseEnd; ++Base) { 9244 CXXRecordDecl *BaseClassDecl 9245 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9246 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9247 ArgQuals, false, 0)) 9248 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 9249 } 9250 9251 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9252 FieldEnd = ClassDecl->field_end(); 9253 Field != FieldEnd; 9254 ++Field) { 9255 QualType FieldType = Context.getBaseElementType(Field->getType()); 9256 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9257 if (CXXMethodDecl *CopyAssign = 9258 LookupCopyingAssignment(FieldClassDecl, 9259 ArgQuals | FieldType.getCVRQualifiers(), 9260 false, 0)) 9261 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9262 } 9263 } 9264 9265 return ExceptSpec; 9266 } 9267 9268 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9269 // Note: The following rules are largely analoguous to the copy 9270 // constructor rules. Note that virtual bases are not taken into account 9271 // for determining the argument type of the operator. Note also that 9272 // operators taking an object instead of a reference are allowed. 9273 assert(ClassDecl->needsImplicitCopyAssignment()); 9274 9275 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9276 if (DSM.isAlreadyBeingDeclared()) 9277 return 0; 9278 9279 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9280 QualType RetType = Context.getLValueReferenceType(ArgType); 9281 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9282 if (Const) 9283 ArgType = ArgType.withConst(); 9284 ArgType = Context.getLValueReferenceType(ArgType); 9285 9286 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9287 CXXCopyAssignment, 9288 Const); 9289 9290 // An implicitly-declared copy assignment operator is an inline public 9291 // member of its class. 9292 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9293 SourceLocation ClassLoc = ClassDecl->getLocation(); 9294 DeclarationNameInfo NameInfo(Name, ClassLoc); 9295 CXXMethodDecl *CopyAssignment = 9296 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9297 /*TInfo=*/ 0, /*StorageClass=*/ SC_None, 9298 /*isInline=*/ true, Constexpr, SourceLocation()); 9299 CopyAssignment->setAccess(AS_public); 9300 CopyAssignment->setDefaulted(); 9301 CopyAssignment->setImplicit(); 9302 9303 // Build an exception specification pointing back at this member. 9304 FunctionProtoType::ExtProtoInfo EPI = 9305 getImplicitMethodEPI(*this, CopyAssignment); 9306 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9307 9308 // Add the parameter to the operator. 9309 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9310 ClassLoc, ClassLoc, /*Id=*/0, 9311 ArgType, /*TInfo=*/0, 9312 SC_None, 0); 9313 CopyAssignment->setParams(FromParam); 9314 9315 AddOverriddenMethods(ClassDecl, CopyAssignment); 9316 9317 CopyAssignment->setTrivial( 9318 ClassDecl->needsOverloadResolutionForCopyAssignment() 9319 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9320 : ClassDecl->hasTrivialCopyAssignment()); 9321 9322 // C++11 [class.copy]p19: 9323 // .... If the class definition does not explicitly declare a copy 9324 // assignment operator, there is no user-declared move constructor, and 9325 // there is no user-declared move assignment operator, a copy assignment 9326 // operator is implicitly declared as defaulted. 9327 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9328 SetDeclDeleted(CopyAssignment, ClassLoc); 9329 9330 // Note that we have added this copy-assignment operator. 9331 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9332 9333 if (Scope *S = getScopeForContext(ClassDecl)) 9334 PushOnScopeChains(CopyAssignment, S, false); 9335 ClassDecl->addDecl(CopyAssignment); 9336 9337 return CopyAssignment; 9338 } 9339 9340 /// Diagnose an implicit copy operation for a class which is odr-used, but 9341 /// which is deprecated because the class has a user-declared copy constructor, 9342 /// copy assignment operator, or destructor. 9343 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 9344 SourceLocation UseLoc) { 9345 assert(CopyOp->isImplicit()); 9346 9347 CXXRecordDecl *RD = CopyOp->getParent(); 9348 CXXMethodDecl *UserDeclaredOperation = 0; 9349 9350 // In Microsoft mode, assignment operations don't affect constructors and 9351 // vice versa. 9352 if (RD->hasUserDeclaredDestructor()) { 9353 UserDeclaredOperation = RD->getDestructor(); 9354 } else if (!isa<CXXConstructorDecl>(CopyOp) && 9355 RD->hasUserDeclaredCopyConstructor() && 9356 !S.getLangOpts().MicrosoftMode) { 9357 // Find any user-declared copy constructor. 9358 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 9359 E = RD->ctor_end(); I != E; ++I) { 9360 if (I->isCopyConstructor()) { 9361 UserDeclaredOperation = *I; 9362 break; 9363 } 9364 } 9365 assert(UserDeclaredOperation); 9366 } else if (isa<CXXConstructorDecl>(CopyOp) && 9367 RD->hasUserDeclaredCopyAssignment() && 9368 !S.getLangOpts().MicrosoftMode) { 9369 // Find any user-declared move assignment operator. 9370 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 9371 E = RD->method_end(); I != E; ++I) { 9372 if (I->isCopyAssignmentOperator()) { 9373 UserDeclaredOperation = *I; 9374 break; 9375 } 9376 } 9377 assert(UserDeclaredOperation); 9378 } 9379 9380 if (UserDeclaredOperation) { 9381 S.Diag(UserDeclaredOperation->getLocation(), 9382 diag::warn_deprecated_copy_operation) 9383 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 9384 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 9385 S.Diag(UseLoc, diag::note_member_synthesized_at) 9386 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 9387 : Sema::CXXCopyAssignment) 9388 << RD; 9389 } 9390 } 9391 9392 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 9393 CXXMethodDecl *CopyAssignOperator) { 9394 assert((CopyAssignOperator->isDefaulted() && 9395 CopyAssignOperator->isOverloadedOperator() && 9396 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 9397 !CopyAssignOperator->doesThisDeclarationHaveABody() && 9398 !CopyAssignOperator->isDeleted()) && 9399 "DefineImplicitCopyAssignment called for wrong function"); 9400 9401 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 9402 9403 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 9404 CopyAssignOperator->setInvalidDecl(); 9405 return; 9406 } 9407 9408 // C++11 [class.copy]p18: 9409 // The [definition of an implicitly declared copy assignment operator] is 9410 // deprecated if the class has a user-declared copy constructor or a 9411 // user-declared destructor. 9412 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 9413 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 9414 9415 CopyAssignOperator->markUsed(Context); 9416 9417 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 9418 DiagnosticErrorTrap Trap(Diags); 9419 9420 // C++0x [class.copy]p30: 9421 // The implicitly-defined or explicitly-defaulted copy assignment operator 9422 // for a non-union class X performs memberwise copy assignment of its 9423 // subobjects. The direct base classes of X are assigned first, in the 9424 // order of their declaration in the base-specifier-list, and then the 9425 // immediate non-static data members of X are assigned, in the order in 9426 // which they were declared in the class definition. 9427 9428 // The statements that form the synthesized function body. 9429 SmallVector<Stmt*, 8> Statements; 9430 9431 // The parameter for the "other" object, which we are copying from. 9432 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 9433 Qualifiers OtherQuals = Other->getType().getQualifiers(); 9434 QualType OtherRefType = Other->getType(); 9435 if (const LValueReferenceType *OtherRef 9436 = OtherRefType->getAs<LValueReferenceType>()) { 9437 OtherRefType = OtherRef->getPointeeType(); 9438 OtherQuals = OtherRefType.getQualifiers(); 9439 } 9440 9441 // Our location for everything implicitly-generated. 9442 SourceLocation Loc = CopyAssignOperator->getLocation(); 9443 9444 // Builds a DeclRefExpr for the "other" object. 9445 RefBuilder OtherRef(Other, OtherRefType); 9446 9447 // Builds the "this" pointer. 9448 ThisBuilder This; 9449 9450 // Assign base classes. 9451 bool Invalid = false; 9452 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9453 E = ClassDecl->bases_end(); Base != E; ++Base) { 9454 // Form the assignment: 9455 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 9456 QualType BaseType = Base->getType().getUnqualifiedType(); 9457 if (!BaseType->isRecordType()) { 9458 Invalid = true; 9459 continue; 9460 } 9461 9462 CXXCastPath BasePath; 9463 BasePath.push_back(Base); 9464 9465 // Construct the "from" expression, which is an implicit cast to the 9466 // appropriately-qualified base type. 9467 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 9468 VK_LValue, BasePath); 9469 9470 // Dereference "this". 9471 DerefBuilder DerefThis(This); 9472 CastBuilder To(DerefThis, 9473 Context.getCVRQualifiedType( 9474 BaseType, CopyAssignOperator->getTypeQualifiers()), 9475 VK_LValue, BasePath); 9476 9477 // Build the copy. 9478 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 9479 To, From, 9480 /*CopyingBaseSubobject=*/true, 9481 /*Copying=*/true); 9482 if (Copy.isInvalid()) { 9483 Diag(CurrentLocation, diag::note_member_synthesized_at) 9484 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9485 CopyAssignOperator->setInvalidDecl(); 9486 return; 9487 } 9488 9489 // Success! Record the copy. 9490 Statements.push_back(Copy.takeAs<Expr>()); 9491 } 9492 9493 // Assign non-static members. 9494 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9495 FieldEnd = ClassDecl->field_end(); 9496 Field != FieldEnd; ++Field) { 9497 if (Field->isUnnamedBitfield()) 9498 continue; 9499 9500 if (Field->isInvalidDecl()) { 9501 Invalid = true; 9502 continue; 9503 } 9504 9505 // Check for members of reference type; we can't copy those. 9506 if (Field->getType()->isReferenceType()) { 9507 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9508 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9509 Diag(Field->getLocation(), diag::note_declared_at); 9510 Diag(CurrentLocation, diag::note_member_synthesized_at) 9511 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9512 Invalid = true; 9513 continue; 9514 } 9515 9516 // Check for members of const-qualified, non-class type. 9517 QualType BaseType = Context.getBaseElementType(Field->getType()); 9518 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9519 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9520 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9521 Diag(Field->getLocation(), diag::note_declared_at); 9522 Diag(CurrentLocation, diag::note_member_synthesized_at) 9523 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9524 Invalid = true; 9525 continue; 9526 } 9527 9528 // Suppress assigning zero-width bitfields. 9529 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9530 continue; 9531 9532 QualType FieldType = Field->getType().getNonReferenceType(); 9533 if (FieldType->isIncompleteArrayType()) { 9534 assert(ClassDecl->hasFlexibleArrayMember() && 9535 "Incomplete array type is not valid"); 9536 continue; 9537 } 9538 9539 // Build references to the field in the object we're copying from and to. 9540 CXXScopeSpec SS; // Intentionally empty 9541 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9542 LookupMemberName); 9543 MemberLookup.addDecl(*Field); 9544 MemberLookup.resolveKind(); 9545 9546 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 9547 9548 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 9549 9550 // Build the copy of this field. 9551 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 9552 To, From, 9553 /*CopyingBaseSubobject=*/false, 9554 /*Copying=*/true); 9555 if (Copy.isInvalid()) { 9556 Diag(CurrentLocation, diag::note_member_synthesized_at) 9557 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9558 CopyAssignOperator->setInvalidDecl(); 9559 return; 9560 } 9561 9562 // Success! Record the copy. 9563 Statements.push_back(Copy.takeAs<Stmt>()); 9564 } 9565 9566 if (!Invalid) { 9567 // Add a "return *this;" 9568 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9569 9570 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9571 if (Return.isInvalid()) 9572 Invalid = true; 9573 else { 9574 Statements.push_back(Return.takeAs<Stmt>()); 9575 9576 if (Trap.hasErrorOccurred()) { 9577 Diag(CurrentLocation, diag::note_member_synthesized_at) 9578 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9579 Invalid = true; 9580 } 9581 } 9582 } 9583 9584 if (Invalid) { 9585 CopyAssignOperator->setInvalidDecl(); 9586 return; 9587 } 9588 9589 StmtResult Body; 9590 { 9591 CompoundScopeRAII CompoundScope(*this); 9592 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9593 /*isStmtExpr=*/false); 9594 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9595 } 9596 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 9597 9598 if (ASTMutationListener *L = getASTMutationListener()) { 9599 L->CompletedImplicitDefinition(CopyAssignOperator); 9600 } 9601 } 9602 9603 Sema::ImplicitExceptionSpecification 9604 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9605 CXXRecordDecl *ClassDecl = MD->getParent(); 9606 9607 ImplicitExceptionSpecification ExceptSpec(*this); 9608 if (ClassDecl->isInvalidDecl()) 9609 return ExceptSpec; 9610 9611 // C++0x [except.spec]p14: 9612 // An implicitly declared special member function (Clause 12) shall have an 9613 // exception-specification. [...] 9614 9615 // It is unspecified whether or not an implicit move assignment operator 9616 // attempts to deduplicate calls to assignment operators of virtual bases are 9617 // made. As such, this exception specification is effectively unspecified. 9618 // Based on a similar decision made for constness in C++0x, we're erring on 9619 // the side of assuming such calls to be made regardless of whether they 9620 // actually happen. 9621 // Note that a move constructor is not implicitly declared when there are 9622 // virtual bases, but it can still be user-declared and explicitly defaulted. 9623 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9624 BaseEnd = ClassDecl->bases_end(); 9625 Base != BaseEnd; ++Base) { 9626 if (Base->isVirtual()) 9627 continue; 9628 9629 CXXRecordDecl *BaseClassDecl 9630 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9631 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9632 0, false, 0)) 9633 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9634 } 9635 9636 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9637 BaseEnd = ClassDecl->vbases_end(); 9638 Base != BaseEnd; ++Base) { 9639 CXXRecordDecl *BaseClassDecl 9640 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9641 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9642 0, false, 0)) 9643 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9644 } 9645 9646 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9647 FieldEnd = ClassDecl->field_end(); 9648 Field != FieldEnd; 9649 ++Field) { 9650 QualType FieldType = Context.getBaseElementType(Field->getType()); 9651 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9652 if (CXXMethodDecl *MoveAssign = 9653 LookupMovingAssignment(FieldClassDecl, 9654 FieldType.getCVRQualifiers(), 9655 false, 0)) 9656 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 9657 } 9658 } 9659 9660 return ExceptSpec; 9661 } 9662 9663 /// Determine whether the class type has any direct or indirect virtual base 9664 /// classes which have a non-trivial move assignment operator. 9665 static bool 9666 hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) { 9667 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9668 BaseEnd = ClassDecl->vbases_end(); 9669 Base != BaseEnd; ++Base) { 9670 CXXRecordDecl *BaseClass = 9671 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9672 9673 // Try to declare the move assignment. If it would be deleted, then the 9674 // class does not have a non-trivial move assignment. 9675 if (BaseClass->needsImplicitMoveAssignment()) 9676 S.DeclareImplicitMoveAssignment(BaseClass); 9677 9678 if (BaseClass->hasNonTrivialMoveAssignment()) 9679 return true; 9680 } 9681 9682 return false; 9683 } 9684 9685 /// Determine whether the given type either has a move constructor or is 9686 /// trivially copyable. 9687 static bool 9688 hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) { 9689 Type = S.Context.getBaseElementType(Type); 9690 9691 // FIXME: Technically, non-trivially-copyable non-class types, such as 9692 // reference types, are supposed to return false here, but that appears 9693 // to be a standard defect. 9694 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl(); 9695 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl()) 9696 return true; 9697 9698 if (Type.isTriviallyCopyableType(S.Context)) 9699 return true; 9700 9701 if (IsConstructor) { 9702 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to 9703 // give the right answer. 9704 if (ClassDecl->needsImplicitMoveConstructor()) 9705 S.DeclareImplicitMoveConstructor(ClassDecl); 9706 return ClassDecl->hasMoveConstructor(); 9707 } 9708 9709 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to 9710 // give the right answer. 9711 if (ClassDecl->needsImplicitMoveAssignment()) 9712 S.DeclareImplicitMoveAssignment(ClassDecl); 9713 return ClassDecl->hasMoveAssignment(); 9714 } 9715 9716 /// Determine whether all non-static data members and direct or virtual bases 9717 /// of class \p ClassDecl have either a move operation, or are trivially 9718 /// copyable. 9719 static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl, 9720 bool IsConstructor) { 9721 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9722 BaseEnd = ClassDecl->bases_end(); 9723 Base != BaseEnd; ++Base) { 9724 if (Base->isVirtual()) 9725 continue; 9726 9727 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9728 return false; 9729 } 9730 9731 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9732 BaseEnd = ClassDecl->vbases_end(); 9733 Base != BaseEnd; ++Base) { 9734 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9735 return false; 9736 } 9737 9738 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9739 FieldEnd = ClassDecl->field_end(); 9740 Field != FieldEnd; ++Field) { 9741 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor)) 9742 return false; 9743 } 9744 9745 return true; 9746 } 9747 9748 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9749 // C++11 [class.copy]p20: 9750 // If the definition of a class X does not explicitly declare a move 9751 // assignment operator, one will be implicitly declared as defaulted 9752 // if and only if: 9753 // 9754 // - [first 4 bullets] 9755 assert(ClassDecl->needsImplicitMoveAssignment()); 9756 9757 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9758 if (DSM.isAlreadyBeingDeclared()) 9759 return 0; 9760 9761 // [Checked after we build the declaration] 9762 // - the move assignment operator would not be implicitly defined as 9763 // deleted, 9764 9765 // [DR1402]: 9766 // - X has no direct or indirect virtual base class with a non-trivial 9767 // move assignment operator, and 9768 // - each of X's non-static data members and direct or virtual base classes 9769 // has a type that either has a move assignment operator or is trivially 9770 // copyable. 9771 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) || 9772 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) { 9773 ClassDecl->setFailedImplicitMoveAssignment(); 9774 return 0; 9775 } 9776 9777 // Note: The following rules are largely analoguous to the move 9778 // constructor rules. 9779 9780 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9781 QualType RetType = Context.getLValueReferenceType(ArgType); 9782 ArgType = Context.getRValueReferenceType(ArgType); 9783 9784 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9785 CXXMoveAssignment, 9786 false); 9787 9788 // An implicitly-declared move assignment operator is an inline public 9789 // member of its class. 9790 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9791 SourceLocation ClassLoc = ClassDecl->getLocation(); 9792 DeclarationNameInfo NameInfo(Name, ClassLoc); 9793 CXXMethodDecl *MoveAssignment = 9794 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9795 /*TInfo=*/0, /*StorageClass=*/SC_None, 9796 /*isInline=*/true, Constexpr, SourceLocation()); 9797 MoveAssignment->setAccess(AS_public); 9798 MoveAssignment->setDefaulted(); 9799 MoveAssignment->setImplicit(); 9800 9801 // Build an exception specification pointing back at this member. 9802 FunctionProtoType::ExtProtoInfo EPI = 9803 getImplicitMethodEPI(*this, MoveAssignment); 9804 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9805 9806 // Add the parameter to the operator. 9807 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9808 ClassLoc, ClassLoc, /*Id=*/0, 9809 ArgType, /*TInfo=*/0, 9810 SC_None, 0); 9811 MoveAssignment->setParams(FromParam); 9812 9813 AddOverriddenMethods(ClassDecl, MoveAssignment); 9814 9815 MoveAssignment->setTrivial( 9816 ClassDecl->needsOverloadResolutionForMoveAssignment() 9817 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9818 : ClassDecl->hasTrivialMoveAssignment()); 9819 9820 // C++0x [class.copy]p9: 9821 // If the definition of a class X does not explicitly declare a move 9822 // assignment operator, one will be implicitly declared as defaulted if and 9823 // only if: 9824 // [...] 9825 // - the move assignment operator would not be implicitly defined as 9826 // deleted. 9827 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9828 // Cache this result so that we don't try to generate this over and over 9829 // on every lookup, leaking memory and wasting time. 9830 ClassDecl->setFailedImplicitMoveAssignment(); 9831 return 0; 9832 } 9833 9834 // Note that we have added this copy-assignment operator. 9835 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9836 9837 if (Scope *S = getScopeForContext(ClassDecl)) 9838 PushOnScopeChains(MoveAssignment, S, false); 9839 ClassDecl->addDecl(MoveAssignment); 9840 9841 return MoveAssignment; 9842 } 9843 9844 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 9845 CXXMethodDecl *MoveAssignOperator) { 9846 assert((MoveAssignOperator->isDefaulted() && 9847 MoveAssignOperator->isOverloadedOperator() && 9848 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 9849 !MoveAssignOperator->doesThisDeclarationHaveABody() && 9850 !MoveAssignOperator->isDeleted()) && 9851 "DefineImplicitMoveAssignment called for wrong function"); 9852 9853 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 9854 9855 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 9856 MoveAssignOperator->setInvalidDecl(); 9857 return; 9858 } 9859 9860 MoveAssignOperator->markUsed(Context); 9861 9862 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 9863 DiagnosticErrorTrap Trap(Diags); 9864 9865 // C++0x [class.copy]p28: 9866 // The implicitly-defined or move assignment operator for a non-union class 9867 // X performs memberwise move assignment of its subobjects. The direct base 9868 // classes of X are assigned first, in the order of their declaration in the 9869 // base-specifier-list, and then the immediate non-static data members of X 9870 // are assigned, in the order in which they were declared in the class 9871 // definition. 9872 9873 // The statements that form the synthesized function body. 9874 SmallVector<Stmt*, 8> Statements; 9875 9876 // The parameter for the "other" object, which we are move from. 9877 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 9878 QualType OtherRefType = Other->getType()-> 9879 getAs<RValueReferenceType>()->getPointeeType(); 9880 assert(!OtherRefType.getQualifiers() && 9881 "Bad argument type of defaulted move assignment"); 9882 9883 // Our location for everything implicitly-generated. 9884 SourceLocation Loc = MoveAssignOperator->getLocation(); 9885 9886 // Builds a reference to the "other" object. 9887 RefBuilder OtherRef(Other, OtherRefType); 9888 // Cast to rvalue. 9889 MoveCastBuilder MoveOther(OtherRef); 9890 9891 // Builds the "this" pointer. 9892 ThisBuilder This; 9893 9894 // Assign base classes. 9895 bool Invalid = false; 9896 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9897 E = ClassDecl->bases_end(); Base != E; ++Base) { 9898 // Form the assignment: 9899 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 9900 QualType BaseType = Base->getType().getUnqualifiedType(); 9901 if (!BaseType->isRecordType()) { 9902 Invalid = true; 9903 continue; 9904 } 9905 9906 CXXCastPath BasePath; 9907 BasePath.push_back(Base); 9908 9909 // Construct the "from" expression, which is an implicit cast to the 9910 // appropriately-qualified base type. 9911 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 9912 9913 // Dereference "this". 9914 DerefBuilder DerefThis(This); 9915 9916 // Implicitly cast "this" to the appropriately-qualified base type. 9917 CastBuilder To(DerefThis, 9918 Context.getCVRQualifiedType( 9919 BaseType, MoveAssignOperator->getTypeQualifiers()), 9920 VK_LValue, BasePath); 9921 9922 // Build the move. 9923 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 9924 To, From, 9925 /*CopyingBaseSubobject=*/true, 9926 /*Copying=*/false); 9927 if (Move.isInvalid()) { 9928 Diag(CurrentLocation, diag::note_member_synthesized_at) 9929 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9930 MoveAssignOperator->setInvalidDecl(); 9931 return; 9932 } 9933 9934 // Success! Record the move. 9935 Statements.push_back(Move.takeAs<Expr>()); 9936 } 9937 9938 // Assign non-static members. 9939 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9940 FieldEnd = ClassDecl->field_end(); 9941 Field != FieldEnd; ++Field) { 9942 if (Field->isUnnamedBitfield()) 9943 continue; 9944 9945 if (Field->isInvalidDecl()) { 9946 Invalid = true; 9947 continue; 9948 } 9949 9950 // Check for members of reference type; we can't move those. 9951 if (Field->getType()->isReferenceType()) { 9952 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9953 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9954 Diag(Field->getLocation(), diag::note_declared_at); 9955 Diag(CurrentLocation, diag::note_member_synthesized_at) 9956 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9957 Invalid = true; 9958 continue; 9959 } 9960 9961 // Check for members of const-qualified, non-class type. 9962 QualType BaseType = Context.getBaseElementType(Field->getType()); 9963 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9964 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9965 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9966 Diag(Field->getLocation(), diag::note_declared_at); 9967 Diag(CurrentLocation, diag::note_member_synthesized_at) 9968 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9969 Invalid = true; 9970 continue; 9971 } 9972 9973 // Suppress assigning zero-width bitfields. 9974 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9975 continue; 9976 9977 QualType FieldType = Field->getType().getNonReferenceType(); 9978 if (FieldType->isIncompleteArrayType()) { 9979 assert(ClassDecl->hasFlexibleArrayMember() && 9980 "Incomplete array type is not valid"); 9981 continue; 9982 } 9983 9984 // Build references to the field in the object we're copying from and to. 9985 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9986 LookupMemberName); 9987 MemberLookup.addDecl(*Field); 9988 MemberLookup.resolveKind(); 9989 MemberBuilder From(MoveOther, OtherRefType, 9990 /*IsArrow=*/false, MemberLookup); 9991 MemberBuilder To(This, getCurrentThisType(), 9992 /*IsArrow=*/true, MemberLookup); 9993 9994 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 9995 "Member reference with rvalue base must be rvalue except for reference " 9996 "members, which aren't allowed for move assignment."); 9997 9998 // Build the move of this field. 9999 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 10000 To, From, 10001 /*CopyingBaseSubobject=*/false, 10002 /*Copying=*/false); 10003 if (Move.isInvalid()) { 10004 Diag(CurrentLocation, diag::note_member_synthesized_at) 10005 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10006 MoveAssignOperator->setInvalidDecl(); 10007 return; 10008 } 10009 10010 // Success! Record the copy. 10011 Statements.push_back(Move.takeAs<Stmt>()); 10012 } 10013 10014 if (!Invalid) { 10015 // Add a "return *this;" 10016 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 10017 10018 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 10019 if (Return.isInvalid()) 10020 Invalid = true; 10021 else { 10022 Statements.push_back(Return.takeAs<Stmt>()); 10023 10024 if (Trap.hasErrorOccurred()) { 10025 Diag(CurrentLocation, diag::note_member_synthesized_at) 10026 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 10027 Invalid = true; 10028 } 10029 } 10030 } 10031 10032 if (Invalid) { 10033 MoveAssignOperator->setInvalidDecl(); 10034 return; 10035 } 10036 10037 StmtResult Body; 10038 { 10039 CompoundScopeRAII CompoundScope(*this); 10040 Body = ActOnCompoundStmt(Loc, Loc, Statements, 10041 /*isStmtExpr=*/false); 10042 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 10043 } 10044 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 10045 10046 if (ASTMutationListener *L = getASTMutationListener()) { 10047 L->CompletedImplicitDefinition(MoveAssignOperator); 10048 } 10049 } 10050 10051 Sema::ImplicitExceptionSpecification 10052 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 10053 CXXRecordDecl *ClassDecl = MD->getParent(); 10054 10055 ImplicitExceptionSpecification ExceptSpec(*this); 10056 if (ClassDecl->isInvalidDecl()) 10057 return ExceptSpec; 10058 10059 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10060 assert(T->getNumArgs() >= 1 && "not a copy ctor"); 10061 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 10062 10063 // C++ [except.spec]p14: 10064 // An implicitly declared special member function (Clause 12) shall have an 10065 // exception-specification. [...] 10066 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 10067 BaseEnd = ClassDecl->bases_end(); 10068 Base != BaseEnd; 10069 ++Base) { 10070 // Virtual bases are handled below. 10071 if (Base->isVirtual()) 10072 continue; 10073 10074 CXXRecordDecl *BaseClassDecl 10075 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 10076 if (CXXConstructorDecl *CopyConstructor = 10077 LookupCopyingConstructor(BaseClassDecl, Quals)) 10078 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 10079 } 10080 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 10081 BaseEnd = ClassDecl->vbases_end(); 10082 Base != BaseEnd; 10083 ++Base) { 10084 CXXRecordDecl *BaseClassDecl 10085 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 10086 if (CXXConstructorDecl *CopyConstructor = 10087 LookupCopyingConstructor(BaseClassDecl, Quals)) 10088 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 10089 } 10090 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 10091 FieldEnd = ClassDecl->field_end(); 10092 Field != FieldEnd; 10093 ++Field) { 10094 QualType FieldType = Context.getBaseElementType(Field->getType()); 10095 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10096 if (CXXConstructorDecl *CopyConstructor = 10097 LookupCopyingConstructor(FieldClassDecl, 10098 Quals | FieldType.getCVRQualifiers())) 10099 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10100 } 10101 } 10102 10103 return ExceptSpec; 10104 } 10105 10106 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10107 CXXRecordDecl *ClassDecl) { 10108 // C++ [class.copy]p4: 10109 // If the class definition does not explicitly declare a copy 10110 // constructor, one is declared implicitly. 10111 assert(ClassDecl->needsImplicitCopyConstructor()); 10112 10113 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10114 if (DSM.isAlreadyBeingDeclared()) 10115 return 0; 10116 10117 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10118 QualType ArgType = ClassType; 10119 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10120 if (Const) 10121 ArgType = ArgType.withConst(); 10122 ArgType = Context.getLValueReferenceType(ArgType); 10123 10124 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10125 CXXCopyConstructor, 10126 Const); 10127 10128 DeclarationName Name 10129 = Context.DeclarationNames.getCXXConstructorName( 10130 Context.getCanonicalType(ClassType)); 10131 SourceLocation ClassLoc = ClassDecl->getLocation(); 10132 DeclarationNameInfo NameInfo(Name, ClassLoc); 10133 10134 // An implicitly-declared copy constructor is an inline public 10135 // member of its class. 10136 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10137 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 10138 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10139 Constexpr); 10140 CopyConstructor->setAccess(AS_public); 10141 CopyConstructor->setDefaulted(); 10142 10143 // Build an exception specification pointing back at this member. 10144 FunctionProtoType::ExtProtoInfo EPI = 10145 getImplicitMethodEPI(*this, CopyConstructor); 10146 CopyConstructor->setType( 10147 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10148 10149 // Add the parameter to the constructor. 10150 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10151 ClassLoc, ClassLoc, 10152 /*IdentifierInfo=*/0, 10153 ArgType, /*TInfo=*/0, 10154 SC_None, 0); 10155 CopyConstructor->setParams(FromParam); 10156 10157 CopyConstructor->setTrivial( 10158 ClassDecl->needsOverloadResolutionForCopyConstructor() 10159 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10160 : ClassDecl->hasTrivialCopyConstructor()); 10161 10162 // C++11 [class.copy]p8: 10163 // ... If the class definition does not explicitly declare a copy 10164 // constructor, there is no user-declared move constructor, and there is no 10165 // user-declared move assignment operator, a copy constructor is implicitly 10166 // declared as defaulted. 10167 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10168 SetDeclDeleted(CopyConstructor, ClassLoc); 10169 10170 // Note that we have declared this constructor. 10171 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10172 10173 if (Scope *S = getScopeForContext(ClassDecl)) 10174 PushOnScopeChains(CopyConstructor, S, false); 10175 ClassDecl->addDecl(CopyConstructor); 10176 10177 return CopyConstructor; 10178 } 10179 10180 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10181 CXXConstructorDecl *CopyConstructor) { 10182 assert((CopyConstructor->isDefaulted() && 10183 CopyConstructor->isCopyConstructor() && 10184 !CopyConstructor->doesThisDeclarationHaveABody() && 10185 !CopyConstructor->isDeleted()) && 10186 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10187 10188 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10189 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10190 10191 // C++11 [class.copy]p7: 10192 // The [definition of an implicitly declared copy constructor] is 10193 // deprecated if the class has a user-declared copy assignment operator 10194 // or a user-declared destructor. 10195 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10196 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10197 10198 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10199 DiagnosticErrorTrap Trap(Diags); 10200 10201 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10202 Trap.hasErrorOccurred()) { 10203 Diag(CurrentLocation, diag::note_member_synthesized_at) 10204 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10205 CopyConstructor->setInvalidDecl(); 10206 } else { 10207 Sema::CompoundScopeRAII CompoundScope(*this); 10208 CopyConstructor->setBody(ActOnCompoundStmt( 10209 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None, 10210 /*isStmtExpr=*/ false).takeAs<Stmt>()); 10211 } 10212 10213 CopyConstructor->markUsed(Context); 10214 if (ASTMutationListener *L = getASTMutationListener()) { 10215 L->CompletedImplicitDefinition(CopyConstructor); 10216 } 10217 } 10218 10219 Sema::ImplicitExceptionSpecification 10220 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10221 CXXRecordDecl *ClassDecl = MD->getParent(); 10222 10223 // C++ [except.spec]p14: 10224 // An implicitly declared special member function (Clause 12) shall have an 10225 // exception-specification. [...] 10226 ImplicitExceptionSpecification ExceptSpec(*this); 10227 if (ClassDecl->isInvalidDecl()) 10228 return ExceptSpec; 10229 10230 // Direct base-class constructors. 10231 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 10232 BEnd = ClassDecl->bases_end(); 10233 B != BEnd; ++B) { 10234 if (B->isVirtual()) // Handled below. 10235 continue; 10236 10237 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 10238 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10239 CXXConstructorDecl *Constructor = 10240 LookupMovingConstructor(BaseClassDecl, 0); 10241 // If this is a deleted function, add it anyway. This might be conformant 10242 // with the standard. This might not. I'm not sure. It might not matter. 10243 if (Constructor) 10244 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 10245 } 10246 } 10247 10248 // Virtual base-class constructors. 10249 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 10250 BEnd = ClassDecl->vbases_end(); 10251 B != BEnd; ++B) { 10252 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 10253 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10254 CXXConstructorDecl *Constructor = 10255 LookupMovingConstructor(BaseClassDecl, 0); 10256 // If this is a deleted function, add it anyway. This might be conformant 10257 // with the standard. This might not. I'm not sure. It might not matter. 10258 if (Constructor) 10259 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 10260 } 10261 } 10262 10263 // Field constructors. 10264 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 10265 FEnd = ClassDecl->field_end(); 10266 F != FEnd; ++F) { 10267 QualType FieldType = Context.getBaseElementType(F->getType()); 10268 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10269 CXXConstructorDecl *Constructor = 10270 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10271 // If this is a deleted function, add it anyway. This might be conformant 10272 // with the standard. This might not. I'm not sure. It might not matter. 10273 // In particular, the problem is that this function never gets called. It 10274 // might just be ill-formed because this function attempts to refer to 10275 // a deleted function here. 10276 if (Constructor) 10277 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10278 } 10279 } 10280 10281 return ExceptSpec; 10282 } 10283 10284 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10285 CXXRecordDecl *ClassDecl) { 10286 // C++11 [class.copy]p9: 10287 // If the definition of a class X does not explicitly declare a move 10288 // constructor, one will be implicitly declared as defaulted if and only if: 10289 // 10290 // - [first 4 bullets] 10291 assert(ClassDecl->needsImplicitMoveConstructor()); 10292 10293 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10294 if (DSM.isAlreadyBeingDeclared()) 10295 return 0; 10296 10297 // [Checked after we build the declaration] 10298 // - the move assignment operator would not be implicitly defined as 10299 // deleted, 10300 10301 // [DR1402]: 10302 // - each of X's non-static data members and direct or virtual base classes 10303 // has a type that either has a move constructor or is trivially copyable. 10304 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) { 10305 ClassDecl->setFailedImplicitMoveConstructor(); 10306 return 0; 10307 } 10308 10309 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10310 QualType ArgType = Context.getRValueReferenceType(ClassType); 10311 10312 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10313 CXXMoveConstructor, 10314 false); 10315 10316 DeclarationName Name 10317 = Context.DeclarationNames.getCXXConstructorName( 10318 Context.getCanonicalType(ClassType)); 10319 SourceLocation ClassLoc = ClassDecl->getLocation(); 10320 DeclarationNameInfo NameInfo(Name, ClassLoc); 10321 10322 // C++11 [class.copy]p11: 10323 // An implicitly-declared copy/move constructor is an inline public 10324 // member of its class. 10325 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10326 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 10327 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10328 Constexpr); 10329 MoveConstructor->setAccess(AS_public); 10330 MoveConstructor->setDefaulted(); 10331 10332 // Build an exception specification pointing back at this member. 10333 FunctionProtoType::ExtProtoInfo EPI = 10334 getImplicitMethodEPI(*this, MoveConstructor); 10335 MoveConstructor->setType( 10336 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10337 10338 // Add the parameter to the constructor. 10339 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10340 ClassLoc, ClassLoc, 10341 /*IdentifierInfo=*/0, 10342 ArgType, /*TInfo=*/0, 10343 SC_None, 0); 10344 MoveConstructor->setParams(FromParam); 10345 10346 MoveConstructor->setTrivial( 10347 ClassDecl->needsOverloadResolutionForMoveConstructor() 10348 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10349 : ClassDecl->hasTrivialMoveConstructor()); 10350 10351 // C++0x [class.copy]p9: 10352 // If the definition of a class X does not explicitly declare a move 10353 // constructor, one will be implicitly declared as defaulted if and only if: 10354 // [...] 10355 // - the move constructor would not be implicitly defined as deleted. 10356 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10357 // Cache this result so that we don't try to generate this over and over 10358 // on every lookup, leaking memory and wasting time. 10359 ClassDecl->setFailedImplicitMoveConstructor(); 10360 return 0; 10361 } 10362 10363 // Note that we have declared this constructor. 10364 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10365 10366 if (Scope *S = getScopeForContext(ClassDecl)) 10367 PushOnScopeChains(MoveConstructor, S, false); 10368 ClassDecl->addDecl(MoveConstructor); 10369 10370 return MoveConstructor; 10371 } 10372 10373 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 10374 CXXConstructorDecl *MoveConstructor) { 10375 assert((MoveConstructor->isDefaulted() && 10376 MoveConstructor->isMoveConstructor() && 10377 !MoveConstructor->doesThisDeclarationHaveABody() && 10378 !MoveConstructor->isDeleted()) && 10379 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 10380 10381 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 10382 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 10383 10384 SynthesizedFunctionScope Scope(*this, MoveConstructor); 10385 DiagnosticErrorTrap Trap(Diags); 10386 10387 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10388 Trap.hasErrorOccurred()) { 10389 Diag(CurrentLocation, diag::note_member_synthesized_at) 10390 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10391 MoveConstructor->setInvalidDecl(); 10392 } else { 10393 Sema::CompoundScopeRAII CompoundScope(*this); 10394 MoveConstructor->setBody(ActOnCompoundStmt( 10395 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None, 10396 /*isStmtExpr=*/ false).takeAs<Stmt>()); 10397 } 10398 10399 MoveConstructor->markUsed(Context); 10400 10401 if (ASTMutationListener *L = getASTMutationListener()) { 10402 L->CompletedImplicitDefinition(MoveConstructor); 10403 } 10404 } 10405 10406 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10407 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10408 } 10409 10410 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10411 SourceLocation CurrentLocation, 10412 CXXConversionDecl *Conv) { 10413 CXXRecordDecl *Lambda = Conv->getParent(); 10414 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 10415 // If we are defining a specialization of a conversion to function-ptr 10416 // cache the deduced template arguments for this specialization 10417 // so that we can use them to retrieve the corresponding call-operator 10418 // and static-invoker. 10419 const TemplateArgumentList *DeducedTemplateArgs = 0; 10420 10421 10422 // Retrieve the corresponding call-operator specialization. 10423 if (Lambda->isGenericLambda()) { 10424 assert(Conv->isFunctionTemplateSpecialization()); 10425 FunctionTemplateDecl *CallOpTemplate = 10426 CallOp->getDescribedFunctionTemplate(); 10427 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 10428 void *InsertPos = 0; 10429 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 10430 DeducedTemplateArgs->data(), 10431 DeducedTemplateArgs->size(), 10432 InsertPos); 10433 assert(CallOpSpec && 10434 "Conversion operator must have a corresponding call operator"); 10435 CallOp = cast<CXXMethodDecl>(CallOpSpec); 10436 } 10437 // Mark the call operator referenced (and add to pending instantiations 10438 // if necessary). 10439 // For both the conversion and static-invoker template specializations 10440 // we construct their body's in this function, so no need to add them 10441 // to the PendingInstantiations. 10442 MarkFunctionReferenced(CurrentLocation, CallOp); 10443 10444 SynthesizedFunctionScope Scope(*this, Conv); 10445 DiagnosticErrorTrap Trap(Diags); 10446 10447 // Retreive the static invoker... 10448 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 10449 // ... and get the corresponding specialization for a generic lambda. 10450 if (Lambda->isGenericLambda()) { 10451 assert(DeducedTemplateArgs && 10452 "Must have deduced template arguments from Conversion Operator"); 10453 FunctionTemplateDecl *InvokeTemplate = 10454 Invoker->getDescribedFunctionTemplate(); 10455 void *InsertPos = 0; 10456 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 10457 DeducedTemplateArgs->data(), 10458 DeducedTemplateArgs->size(), 10459 InsertPos); 10460 assert(InvokeSpec && 10461 "Must have a corresponding static invoker specialization"); 10462 Invoker = cast<CXXMethodDecl>(InvokeSpec); 10463 } 10464 // Construct the body of the conversion function { return __invoke; }. 10465 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 10466 VK_LValue, Conv->getLocation()).take(); 10467 assert(FunctionRef && "Can't refer to __invoke function?"); 10468 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 10469 Conv->setBody(new (Context) CompoundStmt(Context, Return, 10470 Conv->getLocation(), 10471 Conv->getLocation())); 10472 10473 Conv->markUsed(Context); 10474 Conv->setReferenced(); 10475 10476 // Fill in the __invoke function with a dummy implementation. IR generation 10477 // will fill in the actual details. 10478 Invoker->markUsed(Context); 10479 Invoker->setReferenced(); 10480 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 10481 10482 if (ASTMutationListener *L = getASTMutationListener()) { 10483 L->CompletedImplicitDefinition(Conv); 10484 L->CompletedImplicitDefinition(Invoker); 10485 } 10486 } 10487 10488 10489 10490 void Sema::DefineImplicitLambdaToBlockPointerConversion( 10491 SourceLocation CurrentLocation, 10492 CXXConversionDecl *Conv) 10493 { 10494 assert(!Conv->getParent()->isGenericLambda()); 10495 10496 Conv->markUsed(Context); 10497 10498 SynthesizedFunctionScope Scope(*this, Conv); 10499 DiagnosticErrorTrap Trap(Diags); 10500 10501 // Copy-initialize the lambda object as needed to capture it. 10502 Expr *This = ActOnCXXThis(CurrentLocation).take(); 10503 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 10504 10505 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 10506 Conv->getLocation(), 10507 Conv, DerefThis); 10508 10509 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 10510 // behavior. Note that only the general conversion function does this 10511 // (since it's unusable otherwise); in the case where we inline the 10512 // block literal, it has block literal lifetime semantics. 10513 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 10514 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 10515 CK_CopyAndAutoreleaseBlockObject, 10516 BuildBlock.get(), 0, VK_RValue); 10517 10518 if (BuildBlock.isInvalid()) { 10519 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10520 Conv->setInvalidDecl(); 10521 return; 10522 } 10523 10524 // Create the return statement that returns the block from the conversion 10525 // function. 10526 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 10527 if (Return.isInvalid()) { 10528 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10529 Conv->setInvalidDecl(); 10530 return; 10531 } 10532 10533 // Set the body of the conversion function. 10534 Stmt *ReturnS = Return.take(); 10535 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 10536 Conv->getLocation(), 10537 Conv->getLocation())); 10538 10539 // We're done; notify the mutation listener, if any. 10540 if (ASTMutationListener *L = getASTMutationListener()) { 10541 L->CompletedImplicitDefinition(Conv); 10542 } 10543 } 10544 10545 /// \brief Determine whether the given list arguments contains exactly one 10546 /// "real" (non-default) argument. 10547 static bool hasOneRealArgument(MultiExprArg Args) { 10548 switch (Args.size()) { 10549 case 0: 10550 return false; 10551 10552 default: 10553 if (!Args[1]->isDefaultArgument()) 10554 return false; 10555 10556 // fall through 10557 case 1: 10558 return !Args[0]->isDefaultArgument(); 10559 } 10560 10561 return false; 10562 } 10563 10564 ExprResult 10565 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10566 CXXConstructorDecl *Constructor, 10567 MultiExprArg ExprArgs, 10568 bool HadMultipleCandidates, 10569 bool IsListInitialization, 10570 bool RequiresZeroInit, 10571 unsigned ConstructKind, 10572 SourceRange ParenRange) { 10573 bool Elidable = false; 10574 10575 // C++0x [class.copy]p34: 10576 // When certain criteria are met, an implementation is allowed to 10577 // omit the copy/move construction of a class object, even if the 10578 // copy/move constructor and/or destructor for the object have 10579 // side effects. [...] 10580 // - when a temporary class object that has not been bound to a 10581 // reference (12.2) would be copied/moved to a class object 10582 // with the same cv-unqualified type, the copy/move operation 10583 // can be omitted by constructing the temporary object 10584 // directly into the target of the omitted copy/move 10585 if (ConstructKind == CXXConstructExpr::CK_Complete && 10586 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10587 Expr *SubExpr = ExprArgs[0]; 10588 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10589 } 10590 10591 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10592 Elidable, ExprArgs, HadMultipleCandidates, 10593 IsListInitialization, RequiresZeroInit, 10594 ConstructKind, ParenRange); 10595 } 10596 10597 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 10598 /// including handling of its default argument expressions. 10599 ExprResult 10600 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10601 CXXConstructorDecl *Constructor, bool Elidable, 10602 MultiExprArg ExprArgs, 10603 bool HadMultipleCandidates, 10604 bool IsListInitialization, 10605 bool RequiresZeroInit, 10606 unsigned ConstructKind, 10607 SourceRange ParenRange) { 10608 MarkFunctionReferenced(ConstructLoc, Constructor); 10609 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 10610 Constructor, Elidable, ExprArgs, 10611 HadMultipleCandidates, 10612 IsListInitialization, RequiresZeroInit, 10613 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10614 ParenRange)); 10615 } 10616 10617 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10618 if (VD->isInvalidDecl()) return; 10619 10620 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10621 if (ClassDecl->isInvalidDecl()) return; 10622 if (ClassDecl->hasIrrelevantDestructor()) return; 10623 if (ClassDecl->isDependentContext()) return; 10624 10625 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10626 MarkFunctionReferenced(VD->getLocation(), Destructor); 10627 CheckDestructorAccess(VD->getLocation(), Destructor, 10628 PDiag(diag::err_access_dtor_var) 10629 << VD->getDeclName() 10630 << VD->getType()); 10631 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10632 10633 if (!VD->hasGlobalStorage()) return; 10634 10635 // Emit warning for non-trivial dtor in global scope (a real global, 10636 // class-static, function-static). 10637 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10638 10639 // TODO: this should be re-enabled for static locals by !CXAAtExit 10640 if (!VD->isStaticLocal()) 10641 Diag(VD->getLocation(), diag::warn_global_destructor); 10642 } 10643 10644 /// \brief Given a constructor and the set of arguments provided for the 10645 /// constructor, convert the arguments and add any required default arguments 10646 /// to form a proper call to this constructor. 10647 /// 10648 /// \returns true if an error occurred, false otherwise. 10649 bool 10650 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10651 MultiExprArg ArgsPtr, 10652 SourceLocation Loc, 10653 SmallVectorImpl<Expr*> &ConvertedArgs, 10654 bool AllowExplicit, 10655 bool IsListInitialization) { 10656 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10657 unsigned NumArgs = ArgsPtr.size(); 10658 Expr **Args = ArgsPtr.data(); 10659 10660 const FunctionProtoType *Proto 10661 = Constructor->getType()->getAs<FunctionProtoType>(); 10662 assert(Proto && "Constructor without a prototype?"); 10663 unsigned NumArgsInProto = Proto->getNumArgs(); 10664 10665 // If too few arguments are available, we'll fill in the rest with defaults. 10666 if (NumArgs < NumArgsInProto) 10667 ConvertedArgs.reserve(NumArgsInProto); 10668 else 10669 ConvertedArgs.reserve(NumArgs); 10670 10671 VariadicCallType CallType = 10672 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10673 SmallVector<Expr *, 8> AllArgs; 10674 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10675 Proto, 0, 10676 llvm::makeArrayRef(Args, NumArgs), 10677 AllArgs, 10678 CallType, AllowExplicit, 10679 IsListInitialization); 10680 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 10681 10682 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 10683 10684 CheckConstructorCall(Constructor, 10685 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 10686 AllArgs.size()), 10687 Proto, Loc); 10688 10689 return Invalid; 10690 } 10691 10692 static inline bool 10693 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 10694 const FunctionDecl *FnDecl) { 10695 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 10696 if (isa<NamespaceDecl>(DC)) { 10697 return SemaRef.Diag(FnDecl->getLocation(), 10698 diag::err_operator_new_delete_declared_in_namespace) 10699 << FnDecl->getDeclName(); 10700 } 10701 10702 if (isa<TranslationUnitDecl>(DC) && 10703 FnDecl->getStorageClass() == SC_Static) { 10704 return SemaRef.Diag(FnDecl->getLocation(), 10705 diag::err_operator_new_delete_declared_static) 10706 << FnDecl->getDeclName(); 10707 } 10708 10709 return false; 10710 } 10711 10712 static inline bool 10713 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 10714 CanQualType ExpectedResultType, 10715 CanQualType ExpectedFirstParamType, 10716 unsigned DependentParamTypeDiag, 10717 unsigned InvalidParamTypeDiag) { 10718 QualType ResultType = 10719 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 10720 10721 // Check that the result type is not dependent. 10722 if (ResultType->isDependentType()) 10723 return SemaRef.Diag(FnDecl->getLocation(), 10724 diag::err_operator_new_delete_dependent_result_type) 10725 << FnDecl->getDeclName() << ExpectedResultType; 10726 10727 // Check that the result type is what we expect. 10728 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 10729 return SemaRef.Diag(FnDecl->getLocation(), 10730 diag::err_operator_new_delete_invalid_result_type) 10731 << FnDecl->getDeclName() << ExpectedResultType; 10732 10733 // A function template must have at least 2 parameters. 10734 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 10735 return SemaRef.Diag(FnDecl->getLocation(), 10736 diag::err_operator_new_delete_template_too_few_parameters) 10737 << FnDecl->getDeclName(); 10738 10739 // The function decl must have at least 1 parameter. 10740 if (FnDecl->getNumParams() == 0) 10741 return SemaRef.Diag(FnDecl->getLocation(), 10742 diag::err_operator_new_delete_too_few_parameters) 10743 << FnDecl->getDeclName(); 10744 10745 // Check the first parameter type is not dependent. 10746 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10747 if (FirstParamType->isDependentType()) 10748 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10749 << FnDecl->getDeclName() << ExpectedFirstParamType; 10750 10751 // Check that the first parameter type is what we expect. 10752 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10753 ExpectedFirstParamType) 10754 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10755 << FnDecl->getDeclName() << ExpectedFirstParamType; 10756 10757 return false; 10758 } 10759 10760 static bool 10761 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10762 // C++ [basic.stc.dynamic.allocation]p1: 10763 // A program is ill-formed if an allocation function is declared in a 10764 // namespace scope other than global scope or declared static in global 10765 // scope. 10766 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10767 return true; 10768 10769 CanQualType SizeTy = 10770 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10771 10772 // C++ [basic.stc.dynamic.allocation]p1: 10773 // The return type shall be void*. The first parameter shall have type 10774 // std::size_t. 10775 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10776 SizeTy, 10777 diag::err_operator_new_dependent_param_type, 10778 diag::err_operator_new_param_type)) 10779 return true; 10780 10781 // C++ [basic.stc.dynamic.allocation]p1: 10782 // The first parameter shall not have an associated default argument. 10783 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10784 return SemaRef.Diag(FnDecl->getLocation(), 10785 diag::err_operator_new_default_arg) 10786 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10787 10788 return false; 10789 } 10790 10791 static bool 10792 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10793 // C++ [basic.stc.dynamic.deallocation]p1: 10794 // A program is ill-formed if deallocation functions are declared in a 10795 // namespace scope other than global scope or declared static in global 10796 // scope. 10797 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10798 return true; 10799 10800 // C++ [basic.stc.dynamic.deallocation]p2: 10801 // Each deallocation function shall return void and its first parameter 10802 // shall be void*. 10803 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10804 SemaRef.Context.VoidPtrTy, 10805 diag::err_operator_delete_dependent_param_type, 10806 diag::err_operator_delete_param_type)) 10807 return true; 10808 10809 return false; 10810 } 10811 10812 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 10813 /// of this overloaded operator is well-formed. If so, returns false; 10814 /// otherwise, emits appropriate diagnostics and returns true. 10815 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10816 assert(FnDecl && FnDecl->isOverloadedOperator() && 10817 "Expected an overloaded operator declaration"); 10818 10819 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10820 10821 // C++ [over.oper]p5: 10822 // The allocation and deallocation functions, operator new, 10823 // operator new[], operator delete and operator delete[], are 10824 // described completely in 3.7.3. The attributes and restrictions 10825 // found in the rest of this subclause do not apply to them unless 10826 // explicitly stated in 3.7.3. 10827 if (Op == OO_Delete || Op == OO_Array_Delete) 10828 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10829 10830 if (Op == OO_New || Op == OO_Array_New) 10831 return CheckOperatorNewDeclaration(*this, FnDecl); 10832 10833 // C++ [over.oper]p6: 10834 // An operator function shall either be a non-static member 10835 // function or be a non-member function and have at least one 10836 // parameter whose type is a class, a reference to a class, an 10837 // enumeration, or a reference to an enumeration. 10838 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 10839 if (MethodDecl->isStatic()) 10840 return Diag(FnDecl->getLocation(), 10841 diag::err_operator_overload_static) << FnDecl->getDeclName(); 10842 } else { 10843 bool ClassOrEnumParam = false; 10844 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10845 ParamEnd = FnDecl->param_end(); 10846 Param != ParamEnd; ++Param) { 10847 QualType ParamType = (*Param)->getType().getNonReferenceType(); 10848 if (ParamType->isDependentType() || ParamType->isRecordType() || 10849 ParamType->isEnumeralType()) { 10850 ClassOrEnumParam = true; 10851 break; 10852 } 10853 } 10854 10855 if (!ClassOrEnumParam) 10856 return Diag(FnDecl->getLocation(), 10857 diag::err_operator_overload_needs_class_or_enum) 10858 << FnDecl->getDeclName(); 10859 } 10860 10861 // C++ [over.oper]p8: 10862 // An operator function cannot have default arguments (8.3.6), 10863 // except where explicitly stated below. 10864 // 10865 // Only the function-call operator allows default arguments 10866 // (C++ [over.call]p1). 10867 if (Op != OO_Call) { 10868 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10869 Param != FnDecl->param_end(); ++Param) { 10870 if ((*Param)->hasDefaultArg()) 10871 return Diag((*Param)->getLocation(), 10872 diag::err_operator_overload_default_arg) 10873 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 10874 } 10875 } 10876 10877 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 10878 { false, false, false } 10879 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 10880 , { Unary, Binary, MemberOnly } 10881 #include "clang/Basic/OperatorKinds.def" 10882 }; 10883 10884 bool CanBeUnaryOperator = OperatorUses[Op][0]; 10885 bool CanBeBinaryOperator = OperatorUses[Op][1]; 10886 bool MustBeMemberOperator = OperatorUses[Op][2]; 10887 10888 // C++ [over.oper]p8: 10889 // [...] Operator functions cannot have more or fewer parameters 10890 // than the number required for the corresponding operator, as 10891 // described in the rest of this subclause. 10892 unsigned NumParams = FnDecl->getNumParams() 10893 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 10894 if (Op != OO_Call && 10895 ((NumParams == 1 && !CanBeUnaryOperator) || 10896 (NumParams == 2 && !CanBeBinaryOperator) || 10897 (NumParams < 1) || (NumParams > 2))) { 10898 // We have the wrong number of parameters. 10899 unsigned ErrorKind; 10900 if (CanBeUnaryOperator && CanBeBinaryOperator) { 10901 ErrorKind = 2; // 2 -> unary or binary. 10902 } else if (CanBeUnaryOperator) { 10903 ErrorKind = 0; // 0 -> unary 10904 } else { 10905 assert(CanBeBinaryOperator && 10906 "All non-call overloaded operators are unary or binary!"); 10907 ErrorKind = 1; // 1 -> binary 10908 } 10909 10910 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 10911 << FnDecl->getDeclName() << NumParams << ErrorKind; 10912 } 10913 10914 // Overloaded operators other than operator() cannot be variadic. 10915 if (Op != OO_Call && 10916 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 10917 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 10918 << FnDecl->getDeclName(); 10919 } 10920 10921 // Some operators must be non-static member functions. 10922 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 10923 return Diag(FnDecl->getLocation(), 10924 diag::err_operator_overload_must_be_member) 10925 << FnDecl->getDeclName(); 10926 } 10927 10928 // C++ [over.inc]p1: 10929 // The user-defined function called operator++ implements the 10930 // prefix and postfix ++ operator. If this function is a member 10931 // function with no parameters, or a non-member function with one 10932 // parameter of class or enumeration type, it defines the prefix 10933 // increment operator ++ for objects of that type. If the function 10934 // is a member function with one parameter (which shall be of type 10935 // int) or a non-member function with two parameters (the second 10936 // of which shall be of type int), it defines the postfix 10937 // increment operator ++ for objects of that type. 10938 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 10939 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 10940 bool ParamIsInt = false; 10941 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 10942 ParamIsInt = BT->getKind() == BuiltinType::Int; 10943 10944 if (!ParamIsInt) 10945 return Diag(LastParam->getLocation(), 10946 diag::err_operator_overload_post_incdec_must_be_int) 10947 << LastParam->getType() << (Op == OO_MinusMinus); 10948 } 10949 10950 return false; 10951 } 10952 10953 /// CheckLiteralOperatorDeclaration - Check whether the declaration 10954 /// of this literal operator function is well-formed. If so, returns 10955 /// false; otherwise, emits appropriate diagnostics and returns true. 10956 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 10957 if (isa<CXXMethodDecl>(FnDecl)) { 10958 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 10959 << FnDecl->getDeclName(); 10960 return true; 10961 } 10962 10963 if (FnDecl->isExternC()) { 10964 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 10965 return true; 10966 } 10967 10968 bool Valid = false; 10969 10970 // This might be the definition of a literal operator template. 10971 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 10972 // This might be a specialization of a literal operator template. 10973 if (!TpDecl) 10974 TpDecl = FnDecl->getPrimaryTemplate(); 10975 10976 // template <char...> type operator "" name() and 10977 // template <class T, T...> type operator "" name() are the only valid 10978 // template signatures, and the only valid signatures with no parameters. 10979 if (TpDecl) { 10980 if (FnDecl->param_size() == 0) { 10981 // Must have one or two template parameters 10982 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 10983 if (Params->size() == 1) { 10984 NonTypeTemplateParmDecl *PmDecl = 10985 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 10986 10987 // The template parameter must be a char parameter pack. 10988 if (PmDecl && PmDecl->isTemplateParameterPack() && 10989 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 10990 Valid = true; 10991 } else if (Params->size() == 2) { 10992 TemplateTypeParmDecl *PmType = 10993 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 10994 NonTypeTemplateParmDecl *PmArgs = 10995 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 10996 10997 // The second template parameter must be a parameter pack with the 10998 // first template parameter as its type. 10999 if (PmType && PmArgs && 11000 !PmType->isTemplateParameterPack() && 11001 PmArgs->isTemplateParameterPack()) { 11002 const TemplateTypeParmType *TArgs = 11003 PmArgs->getType()->getAs<TemplateTypeParmType>(); 11004 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 11005 TArgs->getIndex() == PmType->getIndex()) { 11006 Valid = true; 11007 if (ActiveTemplateInstantiations.empty()) 11008 Diag(FnDecl->getLocation(), 11009 diag::ext_string_literal_operator_template); 11010 } 11011 } 11012 } 11013 } 11014 } else if (FnDecl->param_size()) { 11015 // Check the first parameter 11016 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 11017 11018 QualType T = (*Param)->getType().getUnqualifiedType(); 11019 11020 // unsigned long long int, long double, and any character type are allowed 11021 // as the only parameters. 11022 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 11023 Context.hasSameType(T, Context.LongDoubleTy) || 11024 Context.hasSameType(T, Context.CharTy) || 11025 Context.hasSameType(T, Context.WideCharTy) || 11026 Context.hasSameType(T, Context.Char16Ty) || 11027 Context.hasSameType(T, Context.Char32Ty)) { 11028 if (++Param == FnDecl->param_end()) 11029 Valid = true; 11030 goto FinishedParams; 11031 } 11032 11033 // Otherwise it must be a pointer to const; let's strip those qualifiers. 11034 const PointerType *PT = T->getAs<PointerType>(); 11035 if (!PT) 11036 goto FinishedParams; 11037 T = PT->getPointeeType(); 11038 if (!T.isConstQualified() || T.isVolatileQualified()) 11039 goto FinishedParams; 11040 T = T.getUnqualifiedType(); 11041 11042 // Move on to the second parameter; 11043 ++Param; 11044 11045 // If there is no second parameter, the first must be a const char * 11046 if (Param == FnDecl->param_end()) { 11047 if (Context.hasSameType(T, Context.CharTy)) 11048 Valid = true; 11049 goto FinishedParams; 11050 } 11051 11052 // const char *, const wchar_t*, const char16_t*, and const char32_t* 11053 // are allowed as the first parameter to a two-parameter function 11054 if (!(Context.hasSameType(T, Context.CharTy) || 11055 Context.hasSameType(T, Context.WideCharTy) || 11056 Context.hasSameType(T, Context.Char16Ty) || 11057 Context.hasSameType(T, Context.Char32Ty))) 11058 goto FinishedParams; 11059 11060 // The second and final parameter must be an std::size_t 11061 T = (*Param)->getType().getUnqualifiedType(); 11062 if (Context.hasSameType(T, Context.getSizeType()) && 11063 ++Param == FnDecl->param_end()) 11064 Valid = true; 11065 } 11066 11067 // FIXME: This diagnostic is absolutely terrible. 11068 FinishedParams: 11069 if (!Valid) { 11070 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 11071 << FnDecl->getDeclName(); 11072 return true; 11073 } 11074 11075 // A parameter-declaration-clause containing a default argument is not 11076 // equivalent to any of the permitted forms. 11077 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 11078 ParamEnd = FnDecl->param_end(); 11079 Param != ParamEnd; ++Param) { 11080 if ((*Param)->hasDefaultArg()) { 11081 Diag((*Param)->getDefaultArgRange().getBegin(), 11082 diag::err_literal_operator_default_argument) 11083 << (*Param)->getDefaultArgRange(); 11084 break; 11085 } 11086 } 11087 11088 StringRef LiteralName 11089 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 11090 if (LiteralName[0] != '_') { 11091 // C++11 [usrlit.suffix]p1: 11092 // Literal suffix identifiers that do not start with an underscore 11093 // are reserved for future standardization. 11094 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 11095 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 11096 } 11097 11098 return false; 11099 } 11100 11101 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 11102 /// linkage specification, including the language and (if present) 11103 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is 11104 /// the location of the language string literal, which is provided 11105 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of 11106 /// the '{' brace. Otherwise, this linkage specification does not 11107 /// have any braces. 11108 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11109 SourceLocation LangLoc, 11110 StringRef Lang, 11111 SourceLocation LBraceLoc) { 11112 LinkageSpecDecl::LanguageIDs Language; 11113 if (Lang == "\"C\"") 11114 Language = LinkageSpecDecl::lang_c; 11115 else if (Lang == "\"C++\"") 11116 Language = LinkageSpecDecl::lang_cxx; 11117 else { 11118 Diag(LangLoc, diag::err_bad_language); 11119 return 0; 11120 } 11121 11122 // FIXME: Add all the various semantics of linkage specifications 11123 11124 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 11125 ExternLoc, LangLoc, Language, 11126 LBraceLoc.isValid()); 11127 CurContext->addDecl(D); 11128 PushDeclContext(S, D); 11129 return D; 11130 } 11131 11132 /// ActOnFinishLinkageSpecification - Complete the definition of 11133 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11134 /// valid, it's the position of the closing '}' brace in a linkage 11135 /// specification that uses braces. 11136 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11137 Decl *LinkageSpec, 11138 SourceLocation RBraceLoc) { 11139 if (LinkageSpec) { 11140 if (RBraceLoc.isValid()) { 11141 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11142 LSDecl->setRBraceLoc(RBraceLoc); 11143 } 11144 PopDeclContext(); 11145 } 11146 return LinkageSpec; 11147 } 11148 11149 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11150 AttributeList *AttrList, 11151 SourceLocation SemiLoc) { 11152 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11153 // Attribute declarations appertain to empty declaration so we handle 11154 // them here. 11155 if (AttrList) 11156 ProcessDeclAttributeList(S, ED, AttrList); 11157 11158 CurContext->addDecl(ED); 11159 return ED; 11160 } 11161 11162 /// \brief Perform semantic analysis for the variable declaration that 11163 /// occurs within a C++ catch clause, returning the newly-created 11164 /// variable. 11165 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11166 TypeSourceInfo *TInfo, 11167 SourceLocation StartLoc, 11168 SourceLocation Loc, 11169 IdentifierInfo *Name) { 11170 bool Invalid = false; 11171 QualType ExDeclType = TInfo->getType(); 11172 11173 // Arrays and functions decay. 11174 if (ExDeclType->isArrayType()) 11175 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11176 else if (ExDeclType->isFunctionType()) 11177 ExDeclType = Context.getPointerType(ExDeclType); 11178 11179 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11180 // The exception-declaration shall not denote a pointer or reference to an 11181 // incomplete type, other than [cv] void*. 11182 // N2844 forbids rvalue references. 11183 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11184 Diag(Loc, diag::err_catch_rvalue_ref); 11185 Invalid = true; 11186 } 11187 11188 QualType BaseType = ExDeclType; 11189 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11190 unsigned DK = diag::err_catch_incomplete; 11191 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11192 BaseType = Ptr->getPointeeType(); 11193 Mode = 1; 11194 DK = diag::err_catch_incomplete_ptr; 11195 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11196 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11197 BaseType = Ref->getPointeeType(); 11198 Mode = 2; 11199 DK = diag::err_catch_incomplete_ref; 11200 } 11201 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11202 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11203 Invalid = true; 11204 11205 if (!Invalid && !ExDeclType->isDependentType() && 11206 RequireNonAbstractType(Loc, ExDeclType, 11207 diag::err_abstract_type_in_decl, 11208 AbstractVariableType)) 11209 Invalid = true; 11210 11211 // Only the non-fragile NeXT runtime currently supports C++ catches 11212 // of ObjC types, and no runtime supports catching ObjC types by value. 11213 if (!Invalid && getLangOpts().ObjC1) { 11214 QualType T = ExDeclType; 11215 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11216 T = RT->getPointeeType(); 11217 11218 if (T->isObjCObjectType()) { 11219 Diag(Loc, diag::err_objc_object_catch); 11220 Invalid = true; 11221 } else if (T->isObjCObjectPointerType()) { 11222 // FIXME: should this be a test for macosx-fragile specifically? 11223 if (getLangOpts().ObjCRuntime.isFragile()) 11224 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11225 } 11226 } 11227 11228 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11229 ExDeclType, TInfo, SC_None); 11230 ExDecl->setExceptionVariable(true); 11231 11232 // In ARC, infer 'retaining' for variables of retainable type. 11233 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11234 Invalid = true; 11235 11236 if (!Invalid && !ExDeclType->isDependentType()) { 11237 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11238 // Insulate this from anything else we might currently be parsing. 11239 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11240 11241 // C++ [except.handle]p16: 11242 // The object declared in an exception-declaration or, if the 11243 // exception-declaration does not specify a name, a temporary (12.2) is 11244 // copy-initialized (8.5) from the exception object. [...] 11245 // The object is destroyed when the handler exits, after the destruction 11246 // of any automatic objects initialized within the handler. 11247 // 11248 // We just pretend to initialize the object with itself, then make sure 11249 // it can be destroyed later. 11250 QualType initType = ExDeclType; 11251 11252 InitializedEntity entity = 11253 InitializedEntity::InitializeVariable(ExDecl); 11254 InitializationKind initKind = 11255 InitializationKind::CreateCopy(Loc, SourceLocation()); 11256 11257 Expr *opaqueValue = 11258 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11259 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11260 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11261 if (result.isInvalid()) 11262 Invalid = true; 11263 else { 11264 // If the constructor used was non-trivial, set this as the 11265 // "initializer". 11266 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>(); 11267 if (!construct->getConstructor()->isTrivial()) { 11268 Expr *init = MaybeCreateExprWithCleanups(construct); 11269 ExDecl->setInit(init); 11270 } 11271 11272 // And make sure it's destructable. 11273 FinalizeVarWithDestructor(ExDecl, recordType); 11274 } 11275 } 11276 } 11277 11278 if (Invalid) 11279 ExDecl->setInvalidDecl(); 11280 11281 return ExDecl; 11282 } 11283 11284 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11285 /// handler. 11286 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11287 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11288 bool Invalid = D.isInvalidType(); 11289 11290 // Check for unexpanded parameter packs. 11291 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11292 UPPC_ExceptionType)) { 11293 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11294 D.getIdentifierLoc()); 11295 Invalid = true; 11296 } 11297 11298 IdentifierInfo *II = D.getIdentifier(); 11299 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11300 LookupOrdinaryName, 11301 ForRedeclaration)) { 11302 // The scope should be freshly made just for us. There is just no way 11303 // it contains any previous declaration. 11304 assert(!S->isDeclScope(PrevDecl)); 11305 if (PrevDecl->isTemplateParameter()) { 11306 // Maybe we will complain about the shadowed template parameter. 11307 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11308 PrevDecl = 0; 11309 } 11310 } 11311 11312 if (D.getCXXScopeSpec().isSet() && !Invalid) { 11313 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 11314 << D.getCXXScopeSpec().getRange(); 11315 Invalid = true; 11316 } 11317 11318 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 11319 D.getLocStart(), 11320 D.getIdentifierLoc(), 11321 D.getIdentifier()); 11322 if (Invalid) 11323 ExDecl->setInvalidDecl(); 11324 11325 // Add the exception declaration into this scope. 11326 if (II) 11327 PushOnScopeChains(ExDecl, S); 11328 else 11329 CurContext->addDecl(ExDecl); 11330 11331 ProcessDeclAttributes(S, ExDecl, D); 11332 return ExDecl; 11333 } 11334 11335 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11336 Expr *AssertExpr, 11337 Expr *AssertMessageExpr, 11338 SourceLocation RParenLoc) { 11339 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 11340 11341 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 11342 return 0; 11343 11344 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 11345 AssertMessage, RParenLoc, false); 11346 } 11347 11348 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11349 Expr *AssertExpr, 11350 StringLiteral *AssertMessage, 11351 SourceLocation RParenLoc, 11352 bool Failed) { 11353 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 11354 !Failed) { 11355 // In a static_assert-declaration, the constant-expression shall be a 11356 // constant expression that can be contextually converted to bool. 11357 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 11358 if (Converted.isInvalid()) 11359 Failed = true; 11360 11361 llvm::APSInt Cond; 11362 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 11363 diag::err_static_assert_expression_is_not_constant, 11364 /*AllowFold=*/false).isInvalid()) 11365 Failed = true; 11366 11367 if (!Failed && !Cond) { 11368 SmallString<256> MsgBuffer; 11369 llvm::raw_svector_ostream Msg(MsgBuffer); 11370 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 11371 Diag(StaticAssertLoc, diag::err_static_assert_failed) 11372 << Msg.str() << AssertExpr->getSourceRange(); 11373 Failed = true; 11374 } 11375 } 11376 11377 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 11378 AssertExpr, AssertMessage, RParenLoc, 11379 Failed); 11380 11381 CurContext->addDecl(Decl); 11382 return Decl; 11383 } 11384 11385 /// \brief Perform semantic analysis of the given friend type declaration. 11386 /// 11387 /// \returns A friend declaration that. 11388 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 11389 SourceLocation FriendLoc, 11390 TypeSourceInfo *TSInfo) { 11391 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 11392 11393 QualType T = TSInfo->getType(); 11394 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 11395 11396 // C++03 [class.friend]p2: 11397 // An elaborated-type-specifier shall be used in a friend declaration 11398 // for a class.* 11399 // 11400 // * The class-key of the elaborated-type-specifier is required. 11401 if (!ActiveTemplateInstantiations.empty()) { 11402 // Do not complain about the form of friend template types during 11403 // template instantiation; we will already have complained when the 11404 // template was declared. 11405 } else { 11406 if (!T->isElaboratedTypeSpecifier()) { 11407 // If we evaluated the type to a record type, suggest putting 11408 // a tag in front. 11409 if (const RecordType *RT = T->getAs<RecordType>()) { 11410 RecordDecl *RD = RT->getDecl(); 11411 11412 std::string InsertionText = std::string(" ") + RD->getKindName(); 11413 11414 Diag(TypeRange.getBegin(), 11415 getLangOpts().CPlusPlus11 ? 11416 diag::warn_cxx98_compat_unelaborated_friend_type : 11417 diag::ext_unelaborated_friend_type) 11418 << (unsigned) RD->getTagKind() 11419 << T 11420 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 11421 InsertionText); 11422 } else { 11423 Diag(FriendLoc, 11424 getLangOpts().CPlusPlus11 ? 11425 diag::warn_cxx98_compat_nonclass_type_friend : 11426 diag::ext_nonclass_type_friend) 11427 << T 11428 << TypeRange; 11429 } 11430 } else if (T->getAs<EnumType>()) { 11431 Diag(FriendLoc, 11432 getLangOpts().CPlusPlus11 ? 11433 diag::warn_cxx98_compat_enum_friend : 11434 diag::ext_enum_friend) 11435 << T 11436 << TypeRange; 11437 } 11438 11439 // C++11 [class.friend]p3: 11440 // A friend declaration that does not declare a function shall have one 11441 // of the following forms: 11442 // friend elaborated-type-specifier ; 11443 // friend simple-type-specifier ; 11444 // friend typename-specifier ; 11445 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 11446 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 11447 } 11448 11449 // If the type specifier in a friend declaration designates a (possibly 11450 // cv-qualified) class type, that class is declared as a friend; otherwise, 11451 // the friend declaration is ignored. 11452 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 11453 } 11454 11455 /// Handle a friend tag declaration where the scope specifier was 11456 /// templated. 11457 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 11458 unsigned TagSpec, SourceLocation TagLoc, 11459 CXXScopeSpec &SS, 11460 IdentifierInfo *Name, 11461 SourceLocation NameLoc, 11462 AttributeList *Attr, 11463 MultiTemplateParamsArg TempParamLists) { 11464 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11465 11466 bool isExplicitSpecialization = false; 11467 bool Invalid = false; 11468 11469 if (TemplateParameterList *TemplateParams = 11470 MatchTemplateParametersToScopeSpecifier( 11471 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true, 11472 isExplicitSpecialization, Invalid)) { 11473 if (TemplateParams->size() > 0) { 11474 // This is a declaration of a class template. 11475 if (Invalid) 11476 return 0; 11477 11478 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 11479 SS, Name, NameLoc, Attr, 11480 TemplateParams, AS_public, 11481 /*ModulePrivateLoc=*/SourceLocation(), 11482 TempParamLists.size() - 1, 11483 TempParamLists.data()).take(); 11484 } else { 11485 // The "template<>" header is extraneous. 11486 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11487 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11488 isExplicitSpecialization = true; 11489 } 11490 } 11491 11492 if (Invalid) return 0; 11493 11494 bool isAllExplicitSpecializations = true; 11495 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 11496 if (TempParamLists[I]->size()) { 11497 isAllExplicitSpecializations = false; 11498 break; 11499 } 11500 } 11501 11502 // FIXME: don't ignore attributes. 11503 11504 // If it's explicit specializations all the way down, just forget 11505 // about the template header and build an appropriate non-templated 11506 // friend. TODO: for source fidelity, remember the headers. 11507 if (isAllExplicitSpecializations) { 11508 if (SS.isEmpty()) { 11509 bool Owned = false; 11510 bool IsDependent = false; 11511 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 11512 Attr, AS_public, 11513 /*ModulePrivateLoc=*/SourceLocation(), 11514 MultiTemplateParamsArg(), Owned, IsDependent, 11515 /*ScopedEnumKWLoc=*/SourceLocation(), 11516 /*ScopedEnumUsesClassTag=*/false, 11517 /*UnderlyingType=*/TypeResult()); 11518 } 11519 11520 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11521 ElaboratedTypeKeyword Keyword 11522 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11523 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 11524 *Name, NameLoc); 11525 if (T.isNull()) 11526 return 0; 11527 11528 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11529 if (isa<DependentNameType>(T)) { 11530 DependentNameTypeLoc TL = 11531 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11532 TL.setElaboratedKeywordLoc(TagLoc); 11533 TL.setQualifierLoc(QualifierLoc); 11534 TL.setNameLoc(NameLoc); 11535 } else { 11536 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11537 TL.setElaboratedKeywordLoc(TagLoc); 11538 TL.setQualifierLoc(QualifierLoc); 11539 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 11540 } 11541 11542 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11543 TSI, FriendLoc, TempParamLists); 11544 Friend->setAccess(AS_public); 11545 CurContext->addDecl(Friend); 11546 return Friend; 11547 } 11548 11549 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 11550 11551 11552 11553 // Handle the case of a templated-scope friend class. e.g. 11554 // template <class T> class A<T>::B; 11555 // FIXME: we don't support these right now. 11556 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11557 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 11558 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11559 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11560 TL.setElaboratedKeywordLoc(TagLoc); 11561 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11562 TL.setNameLoc(NameLoc); 11563 11564 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11565 TSI, FriendLoc, TempParamLists); 11566 Friend->setAccess(AS_public); 11567 Friend->setUnsupportedFriend(true); 11568 CurContext->addDecl(Friend); 11569 return Friend; 11570 } 11571 11572 11573 /// Handle a friend type declaration. This works in tandem with 11574 /// ActOnTag. 11575 /// 11576 /// Notes on friend class templates: 11577 /// 11578 /// We generally treat friend class declarations as if they were 11579 /// declaring a class. So, for example, the elaborated type specifier 11580 /// in a friend declaration is required to obey the restrictions of a 11581 /// class-head (i.e. no typedefs in the scope chain), template 11582 /// parameters are required to match up with simple template-ids, &c. 11583 /// However, unlike when declaring a template specialization, it's 11584 /// okay to refer to a template specialization without an empty 11585 /// template parameter declaration, e.g. 11586 /// friend class A<T>::B<unsigned>; 11587 /// We permit this as a special case; if there are any template 11588 /// parameters present at all, require proper matching, i.e. 11589 /// template <> template \<class T> friend class A<int>::B; 11590 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 11591 MultiTemplateParamsArg TempParams) { 11592 SourceLocation Loc = DS.getLocStart(); 11593 11594 assert(DS.isFriendSpecified()); 11595 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11596 11597 // Try to convert the decl specifier to a type. This works for 11598 // friend templates because ActOnTag never produces a ClassTemplateDecl 11599 // for a TUK_Friend. 11600 Declarator TheDeclarator(DS, Declarator::MemberContext); 11601 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11602 QualType T = TSI->getType(); 11603 if (TheDeclarator.isInvalidType()) 11604 return 0; 11605 11606 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11607 return 0; 11608 11609 // This is definitely an error in C++98. It's probably meant to 11610 // be forbidden in C++0x, too, but the specification is just 11611 // poorly written. 11612 // 11613 // The problem is with declarations like the following: 11614 // template <T> friend A<T>::foo; 11615 // where deciding whether a class C is a friend or not now hinges 11616 // on whether there exists an instantiation of A that causes 11617 // 'foo' to equal C. There are restrictions on class-heads 11618 // (which we declare (by fiat) elaborated friend declarations to 11619 // be) that makes this tractable. 11620 // 11621 // FIXME: handle "template <> friend class A<T>;", which 11622 // is possibly well-formed? Who even knows? 11623 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11624 Diag(Loc, diag::err_tagless_friend_type_template) 11625 << DS.getSourceRange(); 11626 return 0; 11627 } 11628 11629 // C++98 [class.friend]p1: A friend of a class is a function 11630 // or class that is not a member of the class . . . 11631 // This is fixed in DR77, which just barely didn't make the C++03 11632 // deadline. It's also a very silly restriction that seriously 11633 // affects inner classes and which nobody else seems to implement; 11634 // thus we never diagnose it, not even in -pedantic. 11635 // 11636 // But note that we could warn about it: it's always useless to 11637 // friend one of your own members (it's not, however, worthless to 11638 // friend a member of an arbitrary specialization of your template). 11639 11640 Decl *D; 11641 if (unsigned NumTempParamLists = TempParams.size()) 11642 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11643 NumTempParamLists, 11644 TempParams.data(), 11645 TSI, 11646 DS.getFriendSpecLoc()); 11647 else 11648 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11649 11650 if (!D) 11651 return 0; 11652 11653 D->setAccess(AS_public); 11654 CurContext->addDecl(D); 11655 11656 return D; 11657 } 11658 11659 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11660 MultiTemplateParamsArg TemplateParams) { 11661 const DeclSpec &DS = D.getDeclSpec(); 11662 11663 assert(DS.isFriendSpecified()); 11664 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11665 11666 SourceLocation Loc = D.getIdentifierLoc(); 11667 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11668 11669 // C++ [class.friend]p1 11670 // A friend of a class is a function or class.... 11671 // Note that this sees through typedefs, which is intended. 11672 // It *doesn't* see through dependent types, which is correct 11673 // according to [temp.arg.type]p3: 11674 // If a declaration acquires a function type through a 11675 // type dependent on a template-parameter and this causes 11676 // a declaration that does not use the syntactic form of a 11677 // function declarator to have a function type, the program 11678 // is ill-formed. 11679 if (!TInfo->getType()->isFunctionType()) { 11680 Diag(Loc, diag::err_unexpected_friend); 11681 11682 // It might be worthwhile to try to recover by creating an 11683 // appropriate declaration. 11684 return 0; 11685 } 11686 11687 // C++ [namespace.memdef]p3 11688 // - If a friend declaration in a non-local class first declares a 11689 // class or function, the friend class or function is a member 11690 // of the innermost enclosing namespace. 11691 // - The name of the friend is not found by simple name lookup 11692 // until a matching declaration is provided in that namespace 11693 // scope (either before or after the class declaration granting 11694 // friendship). 11695 // - If a friend function is called, its name may be found by the 11696 // name lookup that considers functions from namespaces and 11697 // classes associated with the types of the function arguments. 11698 // - When looking for a prior declaration of a class or a function 11699 // declared as a friend, scopes outside the innermost enclosing 11700 // namespace scope are not considered. 11701 11702 CXXScopeSpec &SS = D.getCXXScopeSpec(); 11703 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 11704 DeclarationName Name = NameInfo.getName(); 11705 assert(Name); 11706 11707 // Check for unexpanded parameter packs. 11708 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 11709 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 11710 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 11711 return 0; 11712 11713 // The context we found the declaration in, or in which we should 11714 // create the declaration. 11715 DeclContext *DC; 11716 Scope *DCScope = S; 11717 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11718 ForRedeclaration); 11719 11720 // There are five cases here. 11721 // - There's no scope specifier and we're in a local class. Only look 11722 // for functions declared in the immediately-enclosing block scope. 11723 // We recover from invalid scope qualifiers as if they just weren't there. 11724 FunctionDecl *FunctionContainingLocalClass = 0; 11725 if ((SS.isInvalid() || !SS.isSet()) && 11726 (FunctionContainingLocalClass = 11727 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 11728 // C++11 [class.friend]p11: 11729 // If a friend declaration appears in a local class and the name 11730 // specified is an unqualified name, a prior declaration is 11731 // looked up without considering scopes that are outside the 11732 // innermost enclosing non-class scope. For a friend function 11733 // declaration, if there is no prior declaration, the program is 11734 // ill-formed. 11735 11736 // Find the innermost enclosing non-class scope. This is the block 11737 // scope containing the local class definition (or for a nested class, 11738 // the outer local class). 11739 DCScope = S->getFnParent(); 11740 11741 // Look up the function name in the scope. 11742 Previous.clear(LookupLocalFriendName); 11743 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 11744 11745 if (!Previous.empty()) { 11746 // All possible previous declarations must have the same context: 11747 // either they were declared at block scope or they are members of 11748 // one of the enclosing local classes. 11749 DC = Previous.getRepresentativeDecl()->getDeclContext(); 11750 } else { 11751 // This is ill-formed, but provide the context that we would have 11752 // declared the function in, if we were permitted to, for error recovery. 11753 DC = FunctionContainingLocalClass; 11754 } 11755 adjustContextForLocalExternDecl(DC); 11756 11757 // C++ [class.friend]p6: 11758 // A function can be defined in a friend declaration of a class if and 11759 // only if the class is a non-local class (9.8), the function name is 11760 // unqualified, and the function has namespace scope. 11761 if (D.isFunctionDefinition()) { 11762 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11763 } 11764 11765 // - There's no scope specifier, in which case we just go to the 11766 // appropriate scope and look for a function or function template 11767 // there as appropriate. 11768 } else if (SS.isInvalid() || !SS.isSet()) { 11769 // C++11 [namespace.memdef]p3: 11770 // If the name in a friend declaration is neither qualified nor 11771 // a template-id and the declaration is a function or an 11772 // elaborated-type-specifier, the lookup to determine whether 11773 // the entity has been previously declared shall not consider 11774 // any scopes outside the innermost enclosing namespace. 11775 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 11776 11777 // Find the appropriate context according to the above. 11778 DC = CurContext; 11779 11780 // Skip class contexts. If someone can cite chapter and verse 11781 // for this behavior, that would be nice --- it's what GCC and 11782 // EDG do, and it seems like a reasonable intent, but the spec 11783 // really only says that checks for unqualified existing 11784 // declarations should stop at the nearest enclosing namespace, 11785 // not that they should only consider the nearest enclosing 11786 // namespace. 11787 while (DC->isRecord()) 11788 DC = DC->getParent(); 11789 11790 DeclContext *LookupDC = DC; 11791 while (LookupDC->isTransparentContext()) 11792 LookupDC = LookupDC->getParent(); 11793 11794 while (true) { 11795 LookupQualifiedName(Previous, LookupDC); 11796 11797 if (!Previous.empty()) { 11798 DC = LookupDC; 11799 break; 11800 } 11801 11802 if (isTemplateId) { 11803 if (isa<TranslationUnitDecl>(LookupDC)) break; 11804 } else { 11805 if (LookupDC->isFileContext()) break; 11806 } 11807 LookupDC = LookupDC->getParent(); 11808 } 11809 11810 DCScope = getScopeForDeclContext(S, DC); 11811 11812 // - There's a non-dependent scope specifier, in which case we 11813 // compute it and do a previous lookup there for a function 11814 // or function template. 11815 } else if (!SS.getScopeRep()->isDependent()) { 11816 DC = computeDeclContext(SS); 11817 if (!DC) return 0; 11818 11819 if (RequireCompleteDeclContext(SS, DC)) return 0; 11820 11821 LookupQualifiedName(Previous, DC); 11822 11823 // Ignore things found implicitly in the wrong scope. 11824 // TODO: better diagnostics for this case. Suggesting the right 11825 // qualified scope would be nice... 11826 LookupResult::Filter F = Previous.makeFilter(); 11827 while (F.hasNext()) { 11828 NamedDecl *D = F.next(); 11829 if (!DC->InEnclosingNamespaceSetOf( 11830 D->getDeclContext()->getRedeclContext())) 11831 F.erase(); 11832 } 11833 F.done(); 11834 11835 if (Previous.empty()) { 11836 D.setInvalidType(); 11837 Diag(Loc, diag::err_qualified_friend_not_found) 11838 << Name << TInfo->getType(); 11839 return 0; 11840 } 11841 11842 // C++ [class.friend]p1: A friend of a class is a function or 11843 // class that is not a member of the class . . . 11844 if (DC->Equals(CurContext)) 11845 Diag(DS.getFriendSpecLoc(), 11846 getLangOpts().CPlusPlus11 ? 11847 diag::warn_cxx98_compat_friend_is_member : 11848 diag::err_friend_is_member); 11849 11850 if (D.isFunctionDefinition()) { 11851 // C++ [class.friend]p6: 11852 // A function can be defined in a friend declaration of a class if and 11853 // only if the class is a non-local class (9.8), the function name is 11854 // unqualified, and the function has namespace scope. 11855 SemaDiagnosticBuilder DB 11856 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 11857 11858 DB << SS.getScopeRep(); 11859 if (DC->isFileContext()) 11860 DB << FixItHint::CreateRemoval(SS.getRange()); 11861 SS.clear(); 11862 } 11863 11864 // - There's a scope specifier that does not match any template 11865 // parameter lists, in which case we use some arbitrary context, 11866 // create a method or method template, and wait for instantiation. 11867 // - There's a scope specifier that does match some template 11868 // parameter lists, which we don't handle right now. 11869 } else { 11870 if (D.isFunctionDefinition()) { 11871 // C++ [class.friend]p6: 11872 // A function can be defined in a friend declaration of a class if and 11873 // only if the class is a non-local class (9.8), the function name is 11874 // unqualified, and the function has namespace scope. 11875 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 11876 << SS.getScopeRep(); 11877 } 11878 11879 DC = CurContext; 11880 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 11881 } 11882 11883 if (!DC->isRecord()) { 11884 // This implies that it has to be an operator or function. 11885 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 11886 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 11887 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 11888 Diag(Loc, diag::err_introducing_special_friend) << 11889 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 11890 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 11891 return 0; 11892 } 11893 } 11894 11895 // FIXME: This is an egregious hack to cope with cases where the scope stack 11896 // does not contain the declaration context, i.e., in an out-of-line 11897 // definition of a class. 11898 Scope FakeDCScope(S, Scope::DeclScope, Diags); 11899 if (!DCScope) { 11900 FakeDCScope.setEntity(DC); 11901 DCScope = &FakeDCScope; 11902 } 11903 11904 bool AddToScope = true; 11905 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 11906 TemplateParams, AddToScope); 11907 if (!ND) return 0; 11908 11909 assert(ND->getLexicalDeclContext() == CurContext); 11910 11911 // If we performed typo correction, we might have added a scope specifier 11912 // and changed the decl context. 11913 DC = ND->getDeclContext(); 11914 11915 // Add the function declaration to the appropriate lookup tables, 11916 // adjusting the redeclarations list as necessary. We don't 11917 // want to do this yet if the friending class is dependent. 11918 // 11919 // Also update the scope-based lookup if the target context's 11920 // lookup context is in lexical scope. 11921 if (!CurContext->isDependentContext()) { 11922 DC = DC->getRedeclContext(); 11923 DC->makeDeclVisibleInContext(ND); 11924 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11925 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 11926 } 11927 11928 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 11929 D.getIdentifierLoc(), ND, 11930 DS.getFriendSpecLoc()); 11931 FrD->setAccess(AS_public); 11932 CurContext->addDecl(FrD); 11933 11934 if (ND->isInvalidDecl()) { 11935 FrD->setInvalidDecl(); 11936 } else { 11937 if (DC->isRecord()) CheckFriendAccess(ND); 11938 11939 FunctionDecl *FD; 11940 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 11941 FD = FTD->getTemplatedDecl(); 11942 else 11943 FD = cast<FunctionDecl>(ND); 11944 11945 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 11946 // default argument expression, that declaration shall be a definition 11947 // and shall be the only declaration of the function or function 11948 // template in the translation unit. 11949 if (functionDeclHasDefaultArgument(FD)) { 11950 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 11951 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 11952 Diag(OldFD->getLocation(), diag::note_previous_declaration); 11953 } else if (!D.isFunctionDefinition()) 11954 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 11955 } 11956 11957 // Mark templated-scope function declarations as unsupported. 11958 if (FD->getNumTemplateParameterLists()) 11959 FrD->setUnsupportedFriend(true); 11960 } 11961 11962 return ND; 11963 } 11964 11965 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 11966 AdjustDeclIfTemplate(Dcl); 11967 11968 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 11969 if (!Fn) { 11970 Diag(DelLoc, diag::err_deleted_non_function); 11971 return; 11972 } 11973 11974 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 11975 // Don't consider the implicit declaration we generate for explicit 11976 // specializations. FIXME: Do not generate these implicit declarations. 11977 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization 11978 || Prev->getPreviousDecl()) && !Prev->isDefined()) { 11979 Diag(DelLoc, diag::err_deleted_decl_not_first); 11980 Diag(Prev->getLocation(), diag::note_previous_declaration); 11981 } 11982 // If the declaration wasn't the first, we delete the function anyway for 11983 // recovery. 11984 Fn = Fn->getCanonicalDecl(); 11985 } 11986 11987 if (Fn->isDeleted()) 11988 return; 11989 11990 // See if we're deleting a function which is already known to override a 11991 // non-deleted virtual function. 11992 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 11993 bool IssuedDiagnostic = false; 11994 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 11995 E = MD->end_overridden_methods(); 11996 I != E; ++I) { 11997 if (!(*MD->begin_overridden_methods())->isDeleted()) { 11998 if (!IssuedDiagnostic) { 11999 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 12000 IssuedDiagnostic = true; 12001 } 12002 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 12003 } 12004 } 12005 } 12006 12007 Fn->setDeletedAsWritten(); 12008 } 12009 12010 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 12011 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 12012 12013 if (MD) { 12014 if (MD->getParent()->isDependentType()) { 12015 MD->setDefaulted(); 12016 MD->setExplicitlyDefaulted(); 12017 return; 12018 } 12019 12020 CXXSpecialMember Member = getSpecialMember(MD); 12021 if (Member == CXXInvalid) { 12022 if (!MD->isInvalidDecl()) 12023 Diag(DefaultLoc, diag::err_default_special_members); 12024 return; 12025 } 12026 12027 MD->setDefaulted(); 12028 MD->setExplicitlyDefaulted(); 12029 12030 // If this definition appears within the record, do the checking when 12031 // the record is complete. 12032 const FunctionDecl *Primary = MD; 12033 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 12034 // Find the uninstantiated declaration that actually had the '= default' 12035 // on it. 12036 Pattern->isDefined(Primary); 12037 12038 // If the method was defaulted on its first declaration, we will have 12039 // already performed the checking in CheckCompletedCXXClass. Such a 12040 // declaration doesn't trigger an implicit definition. 12041 if (Primary == Primary->getCanonicalDecl()) 12042 return; 12043 12044 CheckExplicitlyDefaultedSpecialMember(MD); 12045 12046 // The exception specification is needed because we are defining the 12047 // function. 12048 ResolveExceptionSpec(DefaultLoc, 12049 MD->getType()->castAs<FunctionProtoType>()); 12050 12051 if (MD->isInvalidDecl()) 12052 return; 12053 12054 switch (Member) { 12055 case CXXDefaultConstructor: 12056 DefineImplicitDefaultConstructor(DefaultLoc, 12057 cast<CXXConstructorDecl>(MD)); 12058 break; 12059 case CXXCopyConstructor: 12060 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12061 break; 12062 case CXXCopyAssignment: 12063 DefineImplicitCopyAssignment(DefaultLoc, MD); 12064 break; 12065 case CXXDestructor: 12066 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 12067 break; 12068 case CXXMoveConstructor: 12069 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 12070 break; 12071 case CXXMoveAssignment: 12072 DefineImplicitMoveAssignment(DefaultLoc, MD); 12073 break; 12074 case CXXInvalid: 12075 llvm_unreachable("Invalid special member."); 12076 } 12077 } else { 12078 Diag(DefaultLoc, diag::err_default_special_members); 12079 } 12080 } 12081 12082 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 12083 for (Stmt::child_range CI = S->children(); CI; ++CI) { 12084 Stmt *SubStmt = *CI; 12085 if (!SubStmt) 12086 continue; 12087 if (isa<ReturnStmt>(SubStmt)) 12088 Self.Diag(SubStmt->getLocStart(), 12089 diag::err_return_in_constructor_handler); 12090 if (!isa<Expr>(SubStmt)) 12091 SearchForReturnInStmt(Self, SubStmt); 12092 } 12093 } 12094 12095 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12096 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12097 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12098 SearchForReturnInStmt(*this, Handler); 12099 } 12100 } 12101 12102 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12103 const CXXMethodDecl *Old) { 12104 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12105 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12106 12107 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12108 12109 // If the calling conventions match, everything is fine 12110 if (NewCC == OldCC) 12111 return false; 12112 12113 Diag(New->getLocation(), 12114 diag::err_conflicting_overriding_cc_attributes) 12115 << New->getDeclName() << New->getType() << Old->getType(); 12116 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12117 return true; 12118 } 12119 12120 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12121 const CXXMethodDecl *Old) { 12122 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 12123 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 12124 12125 if (Context.hasSameType(NewTy, OldTy) || 12126 NewTy->isDependentType() || OldTy->isDependentType()) 12127 return false; 12128 12129 // Check if the return types are covariant 12130 QualType NewClassTy, OldClassTy; 12131 12132 /// Both types must be pointers or references to classes. 12133 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12134 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12135 NewClassTy = NewPT->getPointeeType(); 12136 OldClassTy = OldPT->getPointeeType(); 12137 } 12138 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12139 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12140 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12141 NewClassTy = NewRT->getPointeeType(); 12142 OldClassTy = OldRT->getPointeeType(); 12143 } 12144 } 12145 } 12146 12147 // The return types aren't either both pointers or references to a class type. 12148 if (NewClassTy.isNull()) { 12149 Diag(New->getLocation(), 12150 diag::err_different_return_type_for_overriding_virtual_function) 12151 << New->getDeclName() << NewTy << OldTy; 12152 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12153 12154 return true; 12155 } 12156 12157 // C++ [class.virtual]p6: 12158 // If the return type of D::f differs from the return type of B::f, the 12159 // class type in the return type of D::f shall be complete at the point of 12160 // declaration of D::f or shall be the class type D. 12161 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12162 if (!RT->isBeingDefined() && 12163 RequireCompleteType(New->getLocation(), NewClassTy, 12164 diag::err_covariant_return_incomplete, 12165 New->getDeclName())) 12166 return true; 12167 } 12168 12169 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12170 // Check if the new class derives from the old class. 12171 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12172 Diag(New->getLocation(), 12173 diag::err_covariant_return_not_derived) 12174 << New->getDeclName() << NewTy << OldTy; 12175 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12176 return true; 12177 } 12178 12179 // Check if we the conversion from derived to base is valid. 12180 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 12181 diag::err_covariant_return_inaccessible_base, 12182 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12183 // FIXME: Should this point to the return type? 12184 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 12185 // FIXME: this note won't trigger for delayed access control 12186 // diagnostics, and it's impossible to get an undelayed error 12187 // here from access control during the original parse because 12188 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12189 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12190 return true; 12191 } 12192 } 12193 12194 // The qualifiers of the return types must be the same. 12195 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12196 Diag(New->getLocation(), 12197 diag::err_covariant_return_type_different_qualifications) 12198 << New->getDeclName() << NewTy << OldTy; 12199 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12200 return true; 12201 }; 12202 12203 12204 // The new class type must have the same or less qualifiers as the old type. 12205 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12206 Diag(New->getLocation(), 12207 diag::err_covariant_return_type_class_type_more_qualified) 12208 << New->getDeclName() << NewTy << OldTy; 12209 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12210 return true; 12211 }; 12212 12213 return false; 12214 } 12215 12216 /// \brief Mark the given method pure. 12217 /// 12218 /// \param Method the method to be marked pure. 12219 /// 12220 /// \param InitRange the source range that covers the "0" initializer. 12221 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12222 SourceLocation EndLoc = InitRange.getEnd(); 12223 if (EndLoc.isValid()) 12224 Method->setRangeEnd(EndLoc); 12225 12226 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12227 Method->setPure(); 12228 return false; 12229 } 12230 12231 if (!Method->isInvalidDecl()) 12232 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12233 << Method->getDeclName() << InitRange; 12234 return true; 12235 } 12236 12237 /// \brief Determine whether the given declaration is a static data member. 12238 static bool isStaticDataMember(const Decl *D) { 12239 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12240 return Var->isStaticDataMember(); 12241 12242 return false; 12243 } 12244 12245 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12246 /// an initializer for the out-of-line declaration 'Dcl'. The scope 12247 /// is a fresh scope pushed for just this purpose. 12248 /// 12249 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12250 /// static data member of class X, names should be looked up in the scope of 12251 /// class X. 12252 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12253 // If there is no declaration, there was an error parsing it. 12254 if (D == 0 || D->isInvalidDecl()) return; 12255 12256 // We should only get called for declarations with scope specifiers, like: 12257 // int foo::bar; 12258 assert(D->isOutOfLine()); 12259 EnterDeclaratorContext(S, D->getDeclContext()); 12260 12261 // If we are parsing the initializer for a static data member, push a 12262 // new expression evaluation context that is associated with this static 12263 // data member. 12264 if (isStaticDataMember(D)) 12265 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12266 } 12267 12268 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12269 /// initializer for the out-of-line declaration 'D'. 12270 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12271 // If there is no declaration, there was an error parsing it. 12272 if (D == 0 || D->isInvalidDecl()) return; 12273 12274 if (isStaticDataMember(D)) 12275 PopExpressionEvaluationContext(); 12276 12277 assert(D->isOutOfLine()); 12278 ExitDeclaratorContext(S); 12279 } 12280 12281 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 12282 /// C++ if/switch/while/for statement. 12283 /// e.g: "if (int x = f()) {...}" 12284 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 12285 // C++ 6.4p2: 12286 // The declarator shall not specify a function or an array. 12287 // The type-specifier-seq shall not contain typedef and shall not declare a 12288 // new class or enumeration. 12289 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 12290 "Parser allowed 'typedef' as storage class of condition decl."); 12291 12292 Decl *Dcl = ActOnDeclarator(S, D); 12293 if (!Dcl) 12294 return true; 12295 12296 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 12297 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 12298 << D.getSourceRange(); 12299 return true; 12300 } 12301 12302 return Dcl; 12303 } 12304 12305 void Sema::LoadExternalVTableUses() { 12306 if (!ExternalSource) 12307 return; 12308 12309 SmallVector<ExternalVTableUse, 4> VTables; 12310 ExternalSource->ReadUsedVTables(VTables); 12311 SmallVector<VTableUse, 4> NewUses; 12312 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 12313 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 12314 = VTablesUsed.find(VTables[I].Record); 12315 // Even if a definition wasn't required before, it may be required now. 12316 if (Pos != VTablesUsed.end()) { 12317 if (!Pos->second && VTables[I].DefinitionRequired) 12318 Pos->second = true; 12319 continue; 12320 } 12321 12322 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 12323 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 12324 } 12325 12326 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 12327 } 12328 12329 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 12330 bool DefinitionRequired) { 12331 // Ignore any vtable uses in unevaluated operands or for classes that do 12332 // not have a vtable. 12333 if (!Class->isDynamicClass() || Class->isDependentContext() || 12334 CurContext->isDependentContext() || isUnevaluatedContext()) 12335 return; 12336 12337 // Try to insert this class into the map. 12338 LoadExternalVTableUses(); 12339 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12340 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 12341 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 12342 if (!Pos.second) { 12343 // If we already had an entry, check to see if we are promoting this vtable 12344 // to required a definition. If so, we need to reappend to the VTableUses 12345 // list, since we may have already processed the first entry. 12346 if (DefinitionRequired && !Pos.first->second) { 12347 Pos.first->second = true; 12348 } else { 12349 // Otherwise, we can early exit. 12350 return; 12351 } 12352 } 12353 12354 // Local classes need to have their virtual members marked 12355 // immediately. For all other classes, we mark their virtual members 12356 // at the end of the translation unit. 12357 if (Class->isLocalClass()) 12358 MarkVirtualMembersReferenced(Loc, Class); 12359 else 12360 VTableUses.push_back(std::make_pair(Class, Loc)); 12361 } 12362 12363 bool Sema::DefineUsedVTables() { 12364 LoadExternalVTableUses(); 12365 if (VTableUses.empty()) 12366 return false; 12367 12368 // Note: The VTableUses vector could grow as a result of marking 12369 // the members of a class as "used", so we check the size each 12370 // time through the loop and prefer indices (which are stable) to 12371 // iterators (which are not). 12372 bool DefinedAnything = false; 12373 for (unsigned I = 0; I != VTableUses.size(); ++I) { 12374 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 12375 if (!Class) 12376 continue; 12377 12378 SourceLocation Loc = VTableUses[I].second; 12379 12380 bool DefineVTable = true; 12381 12382 // If this class has a key function, but that key function is 12383 // defined in another translation unit, we don't need to emit the 12384 // vtable even though we're using it. 12385 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 12386 if (KeyFunction && !KeyFunction->hasBody()) { 12387 // The key function is in another translation unit. 12388 DefineVTable = false; 12389 TemplateSpecializationKind TSK = 12390 KeyFunction->getTemplateSpecializationKind(); 12391 assert(TSK != TSK_ExplicitInstantiationDefinition && 12392 TSK != TSK_ImplicitInstantiation && 12393 "Instantiations don't have key functions"); 12394 (void)TSK; 12395 } else if (!KeyFunction) { 12396 // If we have a class with no key function that is the subject 12397 // of an explicit instantiation declaration, suppress the 12398 // vtable; it will live with the explicit instantiation 12399 // definition. 12400 bool IsExplicitInstantiationDeclaration 12401 = Class->getTemplateSpecializationKind() 12402 == TSK_ExplicitInstantiationDeclaration; 12403 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 12404 REnd = Class->redecls_end(); 12405 R != REnd; ++R) { 12406 TemplateSpecializationKind TSK 12407 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 12408 if (TSK == TSK_ExplicitInstantiationDeclaration) 12409 IsExplicitInstantiationDeclaration = true; 12410 else if (TSK == TSK_ExplicitInstantiationDefinition) { 12411 IsExplicitInstantiationDeclaration = false; 12412 break; 12413 } 12414 } 12415 12416 if (IsExplicitInstantiationDeclaration) 12417 DefineVTable = false; 12418 } 12419 12420 // The exception specifications for all virtual members may be needed even 12421 // if we are not providing an authoritative form of the vtable in this TU. 12422 // We may choose to emit it available_externally anyway. 12423 if (!DefineVTable) { 12424 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 12425 continue; 12426 } 12427 12428 // Mark all of the virtual members of this class as referenced, so 12429 // that we can build a vtable. Then, tell the AST consumer that a 12430 // vtable for this class is required. 12431 DefinedAnything = true; 12432 MarkVirtualMembersReferenced(Loc, Class); 12433 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12434 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 12435 12436 // Optionally warn if we're emitting a weak vtable. 12437 if (Class->isExternallyVisible() && 12438 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 12439 const FunctionDecl *KeyFunctionDef = 0; 12440 if (!KeyFunction || 12441 (KeyFunction->hasBody(KeyFunctionDef) && 12442 KeyFunctionDef->isInlined())) 12443 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 12444 TSK_ExplicitInstantiationDefinition 12445 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 12446 << Class; 12447 } 12448 } 12449 VTableUses.clear(); 12450 12451 return DefinedAnything; 12452 } 12453 12454 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 12455 const CXXRecordDecl *RD) { 12456 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 12457 E = RD->method_end(); I != E; ++I) 12458 if ((*I)->isVirtual() && !(*I)->isPure()) 12459 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 12460 } 12461 12462 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 12463 const CXXRecordDecl *RD) { 12464 // Mark all functions which will appear in RD's vtable as used. 12465 CXXFinalOverriderMap FinalOverriders; 12466 RD->getFinalOverriders(FinalOverriders); 12467 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 12468 E = FinalOverriders.end(); 12469 I != E; ++I) { 12470 for (OverridingMethods::const_iterator OI = I->second.begin(), 12471 OE = I->second.end(); 12472 OI != OE; ++OI) { 12473 assert(OI->second.size() > 0 && "no final overrider"); 12474 CXXMethodDecl *Overrider = OI->second.front().Method; 12475 12476 // C++ [basic.def.odr]p2: 12477 // [...] A virtual member function is used if it is not pure. [...] 12478 if (!Overrider->isPure()) 12479 MarkFunctionReferenced(Loc, Overrider); 12480 } 12481 } 12482 12483 // Only classes that have virtual bases need a VTT. 12484 if (RD->getNumVBases() == 0) 12485 return; 12486 12487 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 12488 e = RD->bases_end(); i != e; ++i) { 12489 const CXXRecordDecl *Base = 12490 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 12491 if (Base->getNumVBases() == 0) 12492 continue; 12493 MarkVirtualMembersReferenced(Loc, Base); 12494 } 12495 } 12496 12497 /// SetIvarInitializers - This routine builds initialization ASTs for the 12498 /// Objective-C implementation whose ivars need be initialized. 12499 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 12500 if (!getLangOpts().CPlusPlus) 12501 return; 12502 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 12503 SmallVector<ObjCIvarDecl*, 8> ivars; 12504 CollectIvarsToConstructOrDestruct(OID, ivars); 12505 if (ivars.empty()) 12506 return; 12507 SmallVector<CXXCtorInitializer*, 32> AllToInit; 12508 for (unsigned i = 0; i < ivars.size(); i++) { 12509 FieldDecl *Field = ivars[i]; 12510 if (Field->isInvalidDecl()) 12511 continue; 12512 12513 CXXCtorInitializer *Member; 12514 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 12515 InitializationKind InitKind = 12516 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 12517 12518 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 12519 ExprResult MemberInit = 12520 InitSeq.Perform(*this, InitEntity, InitKind, None); 12521 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 12522 // Note, MemberInit could actually come back empty if no initialization 12523 // is required (e.g., because it would call a trivial default constructor) 12524 if (!MemberInit.get() || MemberInit.isInvalid()) 12525 continue; 12526 12527 Member = 12528 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 12529 SourceLocation(), 12530 MemberInit.takeAs<Expr>(), 12531 SourceLocation()); 12532 AllToInit.push_back(Member); 12533 12534 // Be sure that the destructor is accessible and is marked as referenced. 12535 if (const RecordType *RecordTy 12536 = Context.getBaseElementType(Field->getType()) 12537 ->getAs<RecordType>()) { 12538 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 12539 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 12540 MarkFunctionReferenced(Field->getLocation(), Destructor); 12541 CheckDestructorAccess(Field->getLocation(), Destructor, 12542 PDiag(diag::err_access_dtor_ivar) 12543 << Context.getBaseElementType(Field->getType())); 12544 } 12545 } 12546 } 12547 ObjCImplementation->setIvarInitializers(Context, 12548 AllToInit.data(), AllToInit.size()); 12549 } 12550 } 12551 12552 static 12553 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 12554 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 12555 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 12556 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 12557 Sema &S) { 12558 if (Ctor->isInvalidDecl()) 12559 return; 12560 12561 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 12562 12563 // Target may not be determinable yet, for instance if this is a dependent 12564 // call in an uninstantiated template. 12565 if (Target) { 12566 const FunctionDecl *FNTarget = 0; 12567 (void)Target->hasBody(FNTarget); 12568 Target = const_cast<CXXConstructorDecl*>( 12569 cast_or_null<CXXConstructorDecl>(FNTarget)); 12570 } 12571 12572 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 12573 // Avoid dereferencing a null pointer here. 12574 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 12575 12576 if (!Current.insert(Canonical)) 12577 return; 12578 12579 // We know that beyond here, we aren't chaining into a cycle. 12580 if (!Target || !Target->isDelegatingConstructor() || 12581 Target->isInvalidDecl() || Valid.count(TCanonical)) { 12582 Valid.insert(Current.begin(), Current.end()); 12583 Current.clear(); 12584 // We've hit a cycle. 12585 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 12586 Current.count(TCanonical)) { 12587 // If we haven't diagnosed this cycle yet, do so now. 12588 if (!Invalid.count(TCanonical)) { 12589 S.Diag((*Ctor->init_begin())->getSourceLocation(), 12590 diag::warn_delegating_ctor_cycle) 12591 << Ctor; 12592 12593 // Don't add a note for a function delegating directly to itself. 12594 if (TCanonical != Canonical) 12595 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 12596 12597 CXXConstructorDecl *C = Target; 12598 while (C->getCanonicalDecl() != Canonical) { 12599 const FunctionDecl *FNTarget = 0; 12600 (void)C->getTargetConstructor()->hasBody(FNTarget); 12601 assert(FNTarget && "Ctor cycle through bodiless function"); 12602 12603 C = const_cast<CXXConstructorDecl*>( 12604 cast<CXXConstructorDecl>(FNTarget)); 12605 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12606 } 12607 } 12608 12609 Invalid.insert(Current.begin(), Current.end()); 12610 Current.clear(); 12611 } else { 12612 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12613 } 12614 } 12615 12616 12617 void Sema::CheckDelegatingCtorCycles() { 12618 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12619 12620 for (DelegatingCtorDeclsType::iterator 12621 I = DelegatingCtorDecls.begin(ExternalSource), 12622 E = DelegatingCtorDecls.end(); 12623 I != E; ++I) 12624 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 12625 12626 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 12627 CE = Invalid.end(); 12628 CI != CE; ++CI) 12629 (*CI)->setInvalidDecl(); 12630 } 12631 12632 namespace { 12633 /// \brief AST visitor that finds references to the 'this' expression. 12634 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 12635 Sema &S; 12636 12637 public: 12638 explicit FindCXXThisExpr(Sema &S) : S(S) { } 12639 12640 bool VisitCXXThisExpr(CXXThisExpr *E) { 12641 S.Diag(E->getLocation(), diag::err_this_static_member_func) 12642 << E->isImplicit(); 12643 return false; 12644 } 12645 }; 12646 } 12647 12648 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 12649 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12650 if (!TSInfo) 12651 return false; 12652 12653 TypeLoc TL = TSInfo->getTypeLoc(); 12654 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12655 if (!ProtoTL) 12656 return false; 12657 12658 // C++11 [expr.prim.general]p3: 12659 // [The expression this] shall not appear before the optional 12660 // cv-qualifier-seq and it shall not appear within the declaration of a 12661 // static member function (although its type and value category are defined 12662 // within a static member function as they are within a non-static member 12663 // function). [ Note: this is because declaration matching does not occur 12664 // until the complete declarator is known. - end note ] 12665 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12666 FindCXXThisExpr Finder(*this); 12667 12668 // If the return type came after the cv-qualifier-seq, check it now. 12669 if (Proto->hasTrailingReturn() && 12670 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc())) 12671 return true; 12672 12673 // Check the exception specification. 12674 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 12675 return true; 12676 12677 return checkThisInStaticMemberFunctionAttributes(Method); 12678 } 12679 12680 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 12681 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12682 if (!TSInfo) 12683 return false; 12684 12685 TypeLoc TL = TSInfo->getTypeLoc(); 12686 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12687 if (!ProtoTL) 12688 return false; 12689 12690 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12691 FindCXXThisExpr Finder(*this); 12692 12693 switch (Proto->getExceptionSpecType()) { 12694 case EST_Uninstantiated: 12695 case EST_Unevaluated: 12696 case EST_BasicNoexcept: 12697 case EST_DynamicNone: 12698 case EST_MSAny: 12699 case EST_None: 12700 break; 12701 12702 case EST_ComputedNoexcept: 12703 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 12704 return true; 12705 12706 case EST_Dynamic: 12707 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 12708 EEnd = Proto->exception_end(); 12709 E != EEnd; ++E) { 12710 if (!Finder.TraverseType(*E)) 12711 return true; 12712 } 12713 break; 12714 } 12715 12716 return false; 12717 } 12718 12719 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 12720 FindCXXThisExpr Finder(*this); 12721 12722 // Check attributes. 12723 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end(); 12724 A != AEnd; ++A) { 12725 // FIXME: This should be emitted by tblgen. 12726 Expr *Arg = 0; 12727 ArrayRef<Expr *> Args; 12728 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A)) 12729 Arg = G->getArg(); 12730 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A)) 12731 Arg = G->getArg(); 12732 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A)) 12733 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 12734 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A)) 12735 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 12736 else if (ExclusiveLockFunctionAttr *ELF 12737 = dyn_cast<ExclusiveLockFunctionAttr>(*A)) 12738 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 12739 else if (SharedLockFunctionAttr *SLF 12740 = dyn_cast<SharedLockFunctionAttr>(*A)) 12741 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 12742 else if (ExclusiveTrylockFunctionAttr *ETLF 12743 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) { 12744 Arg = ETLF->getSuccessValue(); 12745 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 12746 } else if (SharedTrylockFunctionAttr *STLF 12747 = dyn_cast<SharedTrylockFunctionAttr>(*A)) { 12748 Arg = STLF->getSuccessValue(); 12749 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 12750 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A)) 12751 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 12752 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A)) 12753 Arg = LR->getArg(); 12754 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A)) 12755 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 12756 else if (ExclusiveLocksRequiredAttr *ELR 12757 = dyn_cast<ExclusiveLocksRequiredAttr>(*A)) 12758 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size()); 12759 else if (SharedLocksRequiredAttr *SLR 12760 = dyn_cast<SharedLocksRequiredAttr>(*A)) 12761 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size()); 12762 12763 if (Arg && !Finder.TraverseStmt(Arg)) 12764 return true; 12765 12766 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12767 if (!Finder.TraverseStmt(Args[I])) 12768 return true; 12769 } 12770 } 12771 12772 return false; 12773 } 12774 12775 void 12776 Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12777 ArrayRef<ParsedType> DynamicExceptions, 12778 ArrayRef<SourceRange> DynamicExceptionRanges, 12779 Expr *NoexceptExpr, 12780 SmallVectorImpl<QualType> &Exceptions, 12781 FunctionProtoType::ExtProtoInfo &EPI) { 12782 Exceptions.clear(); 12783 EPI.ExceptionSpecType = EST; 12784 if (EST == EST_Dynamic) { 12785 Exceptions.reserve(DynamicExceptions.size()); 12786 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12787 // FIXME: Preserve type source info. 12788 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12789 12790 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12791 collectUnexpandedParameterPacks(ET, Unexpanded); 12792 if (!Unexpanded.empty()) { 12793 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 12794 UPPC_ExceptionType, 12795 Unexpanded); 12796 continue; 12797 } 12798 12799 // Check that the type is valid for an exception spec, and 12800 // drop it if not. 12801 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 12802 Exceptions.push_back(ET); 12803 } 12804 EPI.NumExceptions = Exceptions.size(); 12805 EPI.Exceptions = Exceptions.data(); 12806 return; 12807 } 12808 12809 if (EST == EST_ComputedNoexcept) { 12810 // If an error occurred, there's no expression here. 12811 if (NoexceptExpr) { 12812 assert((NoexceptExpr->isTypeDependent() || 12813 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 12814 Context.BoolTy) && 12815 "Parser should have made sure that the expression is boolean"); 12816 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 12817 EPI.ExceptionSpecType = EST_BasicNoexcept; 12818 return; 12819 } 12820 12821 if (!NoexceptExpr->isValueDependent()) 12822 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 12823 diag::err_noexcept_needs_constant_expression, 12824 /*AllowFold*/ false).take(); 12825 EPI.NoexceptExpr = NoexceptExpr; 12826 } 12827 return; 12828 } 12829 } 12830 12831 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function 12832 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 12833 // Implicitly declared functions (e.g. copy constructors) are 12834 // __host__ __device__ 12835 if (D->isImplicit()) 12836 return CFT_HostDevice; 12837 12838 if (D->hasAttr<CUDAGlobalAttr>()) 12839 return CFT_Global; 12840 12841 if (D->hasAttr<CUDADeviceAttr>()) { 12842 if (D->hasAttr<CUDAHostAttr>()) 12843 return CFT_HostDevice; 12844 return CFT_Device; 12845 } 12846 12847 return CFT_Host; 12848 } 12849 12850 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 12851 CUDAFunctionTarget CalleeTarget) { 12852 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 12853 // Callable from the device only." 12854 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 12855 return true; 12856 12857 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 12858 // Callable from the host only." 12859 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 12860 // Callable from the host only." 12861 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 12862 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 12863 return true; 12864 12865 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 12866 return true; 12867 12868 return false; 12869 } 12870 12871 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 12872 /// 12873 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 12874 SourceLocation DeclStart, 12875 Declarator &D, Expr *BitWidth, 12876 InClassInitStyle InitStyle, 12877 AccessSpecifier AS, 12878 AttributeList *MSPropertyAttr) { 12879 IdentifierInfo *II = D.getIdentifier(); 12880 if (!II) { 12881 Diag(DeclStart, diag::err_anonymous_property); 12882 return NULL; 12883 } 12884 SourceLocation Loc = D.getIdentifierLoc(); 12885 12886 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12887 QualType T = TInfo->getType(); 12888 if (getLangOpts().CPlusPlus) { 12889 CheckExtraCXXDefaultArguments(D); 12890 12891 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12892 UPPC_DataMemberType)) { 12893 D.setInvalidType(); 12894 T = Context.IntTy; 12895 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12896 } 12897 } 12898 12899 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12900 12901 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12902 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12903 diag::err_invalid_thread) 12904 << DeclSpec::getSpecifierName(TSCS); 12905 12906 // Check to see if this name was declared as a member previously 12907 NamedDecl *PrevDecl = 0; 12908 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12909 LookupName(Previous, S); 12910 switch (Previous.getResultKind()) { 12911 case LookupResult::Found: 12912 case LookupResult::FoundUnresolvedValue: 12913 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12914 break; 12915 12916 case LookupResult::FoundOverloaded: 12917 PrevDecl = Previous.getRepresentativeDecl(); 12918 break; 12919 12920 case LookupResult::NotFound: 12921 case LookupResult::NotFoundInCurrentInstantiation: 12922 case LookupResult::Ambiguous: 12923 break; 12924 } 12925 12926 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12927 // Maybe we will complain about the shadowed template parameter. 12928 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12929 // Just pretend that we didn't see the previous declaration. 12930 PrevDecl = 0; 12931 } 12932 12933 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12934 PrevDecl = 0; 12935 12936 SourceLocation TSSL = D.getLocStart(); 12937 MSPropertyDecl *NewPD; 12938 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 12939 NewPD = new (Context) MSPropertyDecl(Record, Loc, 12940 II, T, TInfo, TSSL, 12941 Data.GetterId, Data.SetterId); 12942 ProcessDeclAttributes(TUScope, NewPD, D); 12943 NewPD->setAccess(AS); 12944 12945 if (NewPD->isInvalidDecl()) 12946 Record->setInvalidDecl(); 12947 12948 if (D.getDeclSpec().isModulePrivateSpecified()) 12949 NewPD->setModulePrivate(); 12950 12951 if (NewPD->isInvalidDecl() && PrevDecl) { 12952 // Don't introduce NewFD into scope; there's already something 12953 // with the same name in the same scope. 12954 } else if (II) { 12955 PushOnScopeChains(NewPD, S); 12956 } else 12957 Record->addDecl(NewPD); 12958 12959 return NewPD; 12960 } 12961