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/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/DeclVisitor.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/RecordLayout.h" 24 #include "clang/AST/RecursiveASTVisitor.h" 25 #include "clang/AST/StmtVisitor.h" 26 #include "clang/AST/TypeLoc.h" 27 #include "clang/AST/TypeOrdering.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/CXXFieldCollector.h" 33 #include "clang/Sema/DeclSpec.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedTemplate.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "llvm/ADT/STLExtras.h" 40 #include "llvm/ADT/SmallString.h" 41 #include <map> 42 #include <set> 43 44 using namespace clang; 45 46 //===----------------------------------------------------------------------===// 47 // CheckDefaultArgumentVisitor 48 //===----------------------------------------------------------------------===// 49 50 namespace { 51 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 52 /// the default argument of a parameter to determine whether it 53 /// contains any ill-formed subexpressions. For example, this will 54 /// diagnose the use of local variables or parameters within the 55 /// default argument expression. 56 class CheckDefaultArgumentVisitor 57 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 58 Expr *DefaultArg; 59 Sema *S; 60 61 public: 62 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 63 : DefaultArg(defarg), S(s) {} 64 65 bool VisitExpr(Expr *Node); 66 bool VisitDeclRefExpr(DeclRefExpr *DRE); 67 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 68 bool VisitLambdaExpr(LambdaExpr *Lambda); 69 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 70 }; 71 72 /// VisitExpr - Visit all of the children of this expression. 73 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 74 bool IsInvalid = false; 75 for (Stmt::child_range I = Node->children(); I; ++I) 76 IsInvalid |= Visit(*I); 77 return IsInvalid; 78 } 79 80 /// VisitDeclRefExpr - Visit a reference to a declaration, to 81 /// determine whether this declaration can be used in the default 82 /// argument expression. 83 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 84 NamedDecl *Decl = DRE->getDecl(); 85 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 86 // C++ [dcl.fct.default]p9 87 // Default arguments are evaluated each time the function is 88 // called. The order of evaluation of function arguments is 89 // unspecified. Consequently, parameters of a function shall not 90 // be used in default argument expressions, even if they are not 91 // evaluated. Parameters of a function declared before a default 92 // argument expression are in scope and can hide namespace and 93 // class member names. 94 return S->Diag(DRE->getLocStart(), 95 diag::err_param_default_argument_references_param) 96 << Param->getDeclName() << DefaultArg->getSourceRange(); 97 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 98 // C++ [dcl.fct.default]p7 99 // Local variables shall not be used in default argument 100 // expressions. 101 if (VDecl->isLocalVarDecl()) 102 return S->Diag(DRE->getLocStart(), 103 diag::err_param_default_argument_references_local) 104 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 105 } 106 107 return false; 108 } 109 110 /// VisitCXXThisExpr - Visit a C++ "this" expression. 111 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 112 // C++ [dcl.fct.default]p8: 113 // The keyword this shall not be used in a default argument of a 114 // member function. 115 return S->Diag(ThisE->getLocStart(), 116 diag::err_param_default_argument_references_this) 117 << ThisE->getSourceRange(); 118 } 119 120 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 121 bool Invalid = false; 122 for (PseudoObjectExpr::semantics_iterator 123 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 124 Expr *E = *i; 125 126 // Look through bindings. 127 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 128 E = OVE->getSourceExpr(); 129 assert(E && "pseudo-object binding without source expression?"); 130 } 131 132 Invalid |= Visit(E); 133 } 134 return Invalid; 135 } 136 137 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 138 // C++11 [expr.lambda.prim]p13: 139 // A lambda-expression appearing in a default argument shall not 140 // implicitly or explicitly capture any entity. 141 if (Lambda->capture_begin() == Lambda->capture_end()) 142 return false; 143 144 return S->Diag(Lambda->getLocStart(), 145 diag::err_lambda_capture_default_arg); 146 } 147 } 148 149 void 150 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 151 const CXXMethodDecl *Method) { 152 // If we have an MSAny spec already, don't bother. 153 if (!Method || ComputedEST == EST_MSAny) 154 return; 155 156 const FunctionProtoType *Proto 157 = Method->getType()->getAs<FunctionProtoType>(); 158 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 159 if (!Proto) 160 return; 161 162 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 163 164 // If this function can throw any exceptions, make a note of that. 165 if (EST == EST_MSAny || EST == EST_None) { 166 ClearExceptions(); 167 ComputedEST = EST; 168 return; 169 } 170 171 // FIXME: If the call to this decl is using any of its default arguments, we 172 // need to search them for potentially-throwing calls. 173 174 // If this function has a basic noexcept, it doesn't affect the outcome. 175 if (EST == EST_BasicNoexcept) 176 return; 177 178 // If we have a throw-all spec at this point, ignore the function. 179 if (ComputedEST == EST_None) 180 return; 181 182 // If we're still at noexcept(true) and there's a nothrow() callee, 183 // change to that specification. 184 if (EST == EST_DynamicNone) { 185 if (ComputedEST == EST_BasicNoexcept) 186 ComputedEST = EST_DynamicNone; 187 return; 188 } 189 190 // Check out noexcept specs. 191 if (EST == EST_ComputedNoexcept) { 192 FunctionProtoType::NoexceptResult NR = 193 Proto->getNoexceptSpec(Self->Context); 194 assert(NR != FunctionProtoType::NR_NoNoexcept && 195 "Must have noexcept result for EST_ComputedNoexcept."); 196 assert(NR != FunctionProtoType::NR_Dependent && 197 "Should not generate implicit declarations for dependent cases, " 198 "and don't know how to handle them anyway."); 199 200 // noexcept(false) -> no spec on the new function 201 if (NR == FunctionProtoType::NR_Throw) { 202 ClearExceptions(); 203 ComputedEST = EST_None; 204 } 205 // noexcept(true) won't change anything either. 206 return; 207 } 208 209 assert(EST == EST_Dynamic && "EST case not considered earlier."); 210 assert(ComputedEST != EST_None && 211 "Shouldn't collect exceptions when throw-all is guaranteed."); 212 ComputedEST = EST_Dynamic; 213 // Record the exceptions in this function's exception specification. 214 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 215 EEnd = Proto->exception_end(); 216 E != EEnd; ++E) 217 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E))) 218 Exceptions.push_back(*E); 219 } 220 221 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 222 if (!E || ComputedEST == EST_MSAny) 223 return; 224 225 // FIXME: 226 // 227 // C++0x [except.spec]p14: 228 // [An] implicit exception-specification specifies the type-id T if and 229 // only if T is allowed by the exception-specification of a function directly 230 // invoked by f's implicit definition; f shall allow all exceptions if any 231 // function it directly invokes allows all exceptions, and f shall allow no 232 // exceptions if every function it directly invokes allows no exceptions. 233 // 234 // Note in particular that if an implicit exception-specification is generated 235 // for a function containing a throw-expression, that specification can still 236 // be noexcept(true). 237 // 238 // Note also that 'directly invoked' is not defined in the standard, and there 239 // is no indication that we should only consider potentially-evaluated calls. 240 // 241 // Ultimately we should implement the intent of the standard: the exception 242 // specification should be the set of exceptions which can be thrown by the 243 // implicit definition. For now, we assume that any non-nothrow expression can 244 // throw any exception. 245 246 if (Self->canThrow(E)) 247 ComputedEST = EST_None; 248 } 249 250 bool 251 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 252 SourceLocation EqualLoc) { 253 if (RequireCompleteType(Param->getLocation(), Param->getType(), 254 diag::err_typecheck_decl_incomplete_type)) { 255 Param->setInvalidDecl(); 256 return true; 257 } 258 259 // C++ [dcl.fct.default]p5 260 // A default argument expression is implicitly converted (clause 261 // 4) to the parameter type. The default argument expression has 262 // the same semantic constraints as the initializer expression in 263 // a declaration of a variable of the parameter type, using the 264 // copy-initialization semantics (8.5). 265 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 266 Param); 267 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 268 EqualLoc); 269 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 270 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 271 if (Result.isInvalid()) 272 return true; 273 Arg = Result.takeAs<Expr>(); 274 275 CheckCompletedExpr(Arg, EqualLoc); 276 Arg = MaybeCreateExprWithCleanups(Arg); 277 278 // Okay: add the default argument to the parameter 279 Param->setDefaultArg(Arg); 280 281 // We have already instantiated this parameter; provide each of the 282 // instantiations with the uninstantiated default argument. 283 UnparsedDefaultArgInstantiationsMap::iterator InstPos 284 = UnparsedDefaultArgInstantiations.find(Param); 285 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 286 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 287 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 288 289 // We're done tracking this parameter's instantiations. 290 UnparsedDefaultArgInstantiations.erase(InstPos); 291 } 292 293 return false; 294 } 295 296 /// ActOnParamDefaultArgument - Check whether the default argument 297 /// provided for a function parameter is well-formed. If so, attach it 298 /// to the parameter declaration. 299 void 300 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 301 Expr *DefaultArg) { 302 if (!param || !DefaultArg) 303 return; 304 305 ParmVarDecl *Param = cast<ParmVarDecl>(param); 306 UnparsedDefaultArgLocs.erase(Param); 307 308 // Default arguments are only permitted in C++ 309 if (!getLangOpts().CPlusPlus) { 310 Diag(EqualLoc, diag::err_param_default_argument) 311 << DefaultArg->getSourceRange(); 312 Param->setInvalidDecl(); 313 return; 314 } 315 316 // Check for unexpanded parameter packs. 317 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 318 Param->setInvalidDecl(); 319 return; 320 } 321 322 // Check that the default argument is well-formed 323 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 324 if (DefaultArgChecker.Visit(DefaultArg)) { 325 Param->setInvalidDecl(); 326 return; 327 } 328 329 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 330 } 331 332 /// ActOnParamUnparsedDefaultArgument - We've seen a default 333 /// argument for a function parameter, but we can't parse it yet 334 /// because we're inside a class definition. Note that this default 335 /// argument will be parsed later. 336 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 337 SourceLocation EqualLoc, 338 SourceLocation ArgLoc) { 339 if (!param) 340 return; 341 342 ParmVarDecl *Param = cast<ParmVarDecl>(param); 343 Param->setUnparsedDefaultArg(); 344 UnparsedDefaultArgLocs[Param] = ArgLoc; 345 } 346 347 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 348 /// the default argument for the parameter param failed. 349 void Sema::ActOnParamDefaultArgumentError(Decl *param) { 350 if (!param) 351 return; 352 353 ParmVarDecl *Param = cast<ParmVarDecl>(param); 354 Param->setInvalidDecl(); 355 UnparsedDefaultArgLocs.erase(Param); 356 } 357 358 /// CheckExtraCXXDefaultArguments - Check for any extra default 359 /// arguments in the declarator, which is not a function declaration 360 /// or definition and therefore is not permitted to have default 361 /// arguments. This routine should be invoked for every declarator 362 /// that is not a function declaration or definition. 363 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 364 // C++ [dcl.fct.default]p3 365 // A default argument expression shall be specified only in the 366 // parameter-declaration-clause of a function declaration or in a 367 // template-parameter (14.1). It shall not be specified for a 368 // parameter pack. If it is specified in a 369 // parameter-declaration-clause, it shall not occur within a 370 // declarator or abstract-declarator of a parameter-declaration. 371 bool MightBeFunction = D.isFunctionDeclarationContext(); 372 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 373 DeclaratorChunk &chunk = D.getTypeObject(i); 374 if (chunk.Kind == DeclaratorChunk::Function) { 375 if (MightBeFunction) { 376 // This is a function declaration. It can have default arguments, but 377 // keep looking in case its return type is a function type with default 378 // arguments. 379 MightBeFunction = false; 380 continue; 381 } 382 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 383 ParmVarDecl *Param = 384 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 385 if (Param->hasUnparsedDefaultArg()) { 386 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 387 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 388 << SourceRange((*Toks)[1].getLocation(), 389 Toks->back().getLocation()); 390 delete Toks; 391 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 392 } else if (Param->getDefaultArg()) { 393 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 394 << Param->getDefaultArg()->getSourceRange(); 395 Param->setDefaultArg(0); 396 } 397 } 398 } else if (chunk.Kind != DeclaratorChunk::Paren) { 399 MightBeFunction = false; 400 } 401 } 402 } 403 404 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 405 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 406 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 407 if (!PVD->hasDefaultArg()) 408 return false; 409 if (!PVD->hasInheritedDefaultArg()) 410 return true; 411 } 412 return false; 413 } 414 415 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 416 /// function, once we already know that they have the same 417 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 418 /// error, false otherwise. 419 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 420 Scope *S) { 421 bool Invalid = false; 422 423 // C++ [dcl.fct.default]p4: 424 // For non-template functions, default arguments can be added in 425 // later declarations of a function in the same 426 // scope. Declarations in different scopes have completely 427 // distinct sets of default arguments. That is, declarations in 428 // inner scopes do not acquire default arguments from 429 // declarations in outer scopes, and vice versa. In a given 430 // function declaration, all parameters subsequent to a 431 // parameter with a default argument shall have default 432 // arguments supplied in this or previous declarations. A 433 // default argument shall not be redefined by a later 434 // declaration (not even to the same value). 435 // 436 // C++ [dcl.fct.default]p6: 437 // Except for member functions of class templates, the default arguments 438 // in a member function definition that appears outside of the class 439 // definition are added to the set of default arguments provided by the 440 // member function declaration in the class definition. 441 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 442 ParmVarDecl *OldParam = Old->getParamDecl(p); 443 ParmVarDecl *NewParam = New->getParamDecl(p); 444 445 bool OldParamHasDfl = OldParam->hasDefaultArg(); 446 bool NewParamHasDfl = NewParam->hasDefaultArg(); 447 448 NamedDecl *ND = Old; 449 450 // The declaration context corresponding to the scope is the semantic 451 // parent, unless this is a local function declaration, in which case 452 // it is that surrounding function. 453 DeclContext *ScopeDC = New->getLexicalDeclContext(); 454 if (!ScopeDC->isFunctionOrMethod()) 455 ScopeDC = New->getDeclContext(); 456 if (S && !isDeclInScope(ND, ScopeDC, S) && 457 !New->getDeclContext()->isRecord()) 458 // Ignore default parameters of old decl if they are not in 459 // the same scope and this is not an out-of-line definition of 460 // a member function. 461 OldParamHasDfl = false; 462 463 if (OldParamHasDfl && NewParamHasDfl) { 464 465 unsigned DiagDefaultParamID = 466 diag::err_param_default_argument_redefinition; 467 468 // MSVC accepts that default parameters be redefined for member functions 469 // of template class. The new default parameter's value is ignored. 470 Invalid = true; 471 if (getLangOpts().MicrosoftExt) { 472 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 473 if (MD && MD->getParent()->getDescribedClassTemplate()) { 474 // Merge the old default argument into the new parameter. 475 NewParam->setHasInheritedDefaultArg(); 476 if (OldParam->hasUninstantiatedDefaultArg()) 477 NewParam->setUninstantiatedDefaultArg( 478 OldParam->getUninstantiatedDefaultArg()); 479 else 480 NewParam->setDefaultArg(OldParam->getInit()); 481 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 482 Invalid = false; 483 } 484 } 485 486 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 487 // hint here. Alternatively, we could walk the type-source information 488 // for NewParam to find the last source location in the type... but it 489 // isn't worth the effort right now. This is the kind of test case that 490 // is hard to get right: 491 // int f(int); 492 // void g(int (*fp)(int) = f); 493 // void g(int (*fp)(int) = &f); 494 Diag(NewParam->getLocation(), DiagDefaultParamID) 495 << NewParam->getDefaultArgRange(); 496 497 // Look for the function declaration where the default argument was 498 // actually written, which may be a declaration prior to Old. 499 for (FunctionDecl *Older = Old->getPreviousDecl(); 500 Older; Older = Older->getPreviousDecl()) { 501 if (!Older->getParamDecl(p)->hasDefaultArg()) 502 break; 503 504 OldParam = Older->getParamDecl(p); 505 } 506 507 Diag(OldParam->getLocation(), diag::note_previous_definition) 508 << OldParam->getDefaultArgRange(); 509 } else if (OldParamHasDfl) { 510 // Merge the old default argument into the new parameter. 511 // It's important to use getInit() here; getDefaultArg() 512 // strips off any top-level ExprWithCleanups. 513 NewParam->setHasInheritedDefaultArg(); 514 if (OldParam->hasUninstantiatedDefaultArg()) 515 NewParam->setUninstantiatedDefaultArg( 516 OldParam->getUninstantiatedDefaultArg()); 517 else 518 NewParam->setDefaultArg(OldParam->getInit()); 519 } else if (NewParamHasDfl) { 520 if (New->getDescribedFunctionTemplate()) { 521 // Paragraph 4, quoted above, only applies to non-template functions. 522 Diag(NewParam->getLocation(), 523 diag::err_param_default_argument_template_redecl) 524 << NewParam->getDefaultArgRange(); 525 Diag(Old->getLocation(), diag::note_template_prev_declaration) 526 << false; 527 } else if (New->getTemplateSpecializationKind() 528 != TSK_ImplicitInstantiation && 529 New->getTemplateSpecializationKind() != TSK_Undeclared) { 530 // C++ [temp.expr.spec]p21: 531 // Default function arguments shall not be specified in a declaration 532 // or a definition for one of the following explicit specializations: 533 // - the explicit specialization of a function template; 534 // - the explicit specialization of a member function template; 535 // - the explicit specialization of a member function of a class 536 // template where the class template specialization to which the 537 // member function specialization belongs is implicitly 538 // instantiated. 539 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 540 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 541 << New->getDeclName() 542 << NewParam->getDefaultArgRange(); 543 } else if (New->getDeclContext()->isDependentContext()) { 544 // C++ [dcl.fct.default]p6 (DR217): 545 // Default arguments for a member function of a class template shall 546 // be specified on the initial declaration of the member function 547 // within the class template. 548 // 549 // Reading the tea leaves a bit in DR217 and its reference to DR205 550 // leads me to the conclusion that one cannot add default function 551 // arguments for an out-of-line definition of a member function of a 552 // dependent type. 553 int WhichKind = 2; 554 if (CXXRecordDecl *Record 555 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 556 if (Record->getDescribedClassTemplate()) 557 WhichKind = 0; 558 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 559 WhichKind = 1; 560 else 561 WhichKind = 2; 562 } 563 564 Diag(NewParam->getLocation(), 565 diag::err_param_default_argument_member_template_redecl) 566 << WhichKind 567 << NewParam->getDefaultArgRange(); 568 } 569 } 570 } 571 572 // DR1344: If a default argument is added outside a class definition and that 573 // default argument makes the function a special member function, the program 574 // is ill-formed. This can only happen for constructors. 575 if (isa<CXXConstructorDecl>(New) && 576 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 577 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 578 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 579 if (NewSM != OldSM) { 580 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 581 assert(NewParam->hasDefaultArg()); 582 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 583 << NewParam->getDefaultArgRange() << NewSM; 584 Diag(Old->getLocation(), diag::note_previous_declaration); 585 } 586 } 587 588 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 589 // template has a constexpr specifier then all its declarations shall 590 // contain the constexpr specifier. 591 if (New->isConstexpr() != Old->isConstexpr()) { 592 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 593 << New << New->isConstexpr(); 594 Diag(Old->getLocation(), diag::note_previous_declaration); 595 Invalid = true; 596 } 597 598 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 599 // argument expression, that declaration shall be a definition and shall be 600 // the only declaration of the function or function template in the 601 // translation unit. 602 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 603 functionDeclHasDefaultArgument(Old)) { 604 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 605 Diag(Old->getLocation(), diag::note_previous_declaration); 606 Invalid = true; 607 } 608 609 if (CheckEquivalentExceptionSpec(Old, New)) 610 Invalid = true; 611 612 return Invalid; 613 } 614 615 /// \brief Merge the exception specifications of two variable declarations. 616 /// 617 /// This is called when there's a redeclaration of a VarDecl. The function 618 /// checks if the redeclaration might have an exception specification and 619 /// validates compatibility and merges the specs if necessary. 620 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 621 // Shortcut if exceptions are disabled. 622 if (!getLangOpts().CXXExceptions) 623 return; 624 625 assert(Context.hasSameType(New->getType(), Old->getType()) && 626 "Should only be called if types are otherwise the same."); 627 628 QualType NewType = New->getType(); 629 QualType OldType = Old->getType(); 630 631 // We're only interested in pointers and references to functions, as well 632 // as pointers to member functions. 633 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 634 NewType = R->getPointeeType(); 635 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 636 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 637 NewType = P->getPointeeType(); 638 OldType = OldType->getAs<PointerType>()->getPointeeType(); 639 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 640 NewType = M->getPointeeType(); 641 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 642 } 643 644 if (!NewType->isFunctionProtoType()) 645 return; 646 647 // There's lots of special cases for functions. For function pointers, system 648 // libraries are hopefully not as broken so that we don't need these 649 // workarounds. 650 if (CheckEquivalentExceptionSpec( 651 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 652 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 653 New->setInvalidDecl(); 654 } 655 } 656 657 /// CheckCXXDefaultArguments - Verify that the default arguments for a 658 /// function declaration are well-formed according to C++ 659 /// [dcl.fct.default]. 660 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 661 unsigned NumParams = FD->getNumParams(); 662 unsigned p; 663 664 // Find first parameter with a default argument 665 for (p = 0; p < NumParams; ++p) { 666 ParmVarDecl *Param = FD->getParamDecl(p); 667 if (Param->hasDefaultArg()) 668 break; 669 } 670 671 // C++ [dcl.fct.default]p4: 672 // In a given function declaration, all parameters 673 // subsequent to a parameter with a default argument shall 674 // have default arguments supplied in this or previous 675 // declarations. A default argument shall not be redefined 676 // by a later declaration (not even to the same value). 677 unsigned LastMissingDefaultArg = 0; 678 for (; p < NumParams; ++p) { 679 ParmVarDecl *Param = FD->getParamDecl(p); 680 if (!Param->hasDefaultArg()) { 681 if (Param->isInvalidDecl()) 682 /* We already complained about this parameter. */; 683 else if (Param->getIdentifier()) 684 Diag(Param->getLocation(), 685 diag::err_param_default_argument_missing_name) 686 << Param->getIdentifier(); 687 else 688 Diag(Param->getLocation(), 689 diag::err_param_default_argument_missing); 690 691 LastMissingDefaultArg = p; 692 } 693 } 694 695 if (LastMissingDefaultArg > 0) { 696 // Some default arguments were missing. Clear out all of the 697 // default arguments up to (and including) the last missing 698 // default argument, so that we leave the function parameters 699 // in a semantically valid state. 700 for (p = 0; p <= LastMissingDefaultArg; ++p) { 701 ParmVarDecl *Param = FD->getParamDecl(p); 702 if (Param->hasDefaultArg()) { 703 Param->setDefaultArg(0); 704 } 705 } 706 } 707 } 708 709 // CheckConstexprParameterTypes - Check whether a function's parameter types 710 // are all literal types. If so, return true. If not, produce a suitable 711 // diagnostic and return false. 712 static bool CheckConstexprParameterTypes(Sema &SemaRef, 713 const FunctionDecl *FD) { 714 unsigned ArgIndex = 0; 715 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 716 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(), 717 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) { 718 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 719 SourceLocation ParamLoc = PD->getLocation(); 720 if (!(*i)->isDependentType() && 721 SemaRef.RequireLiteralType(ParamLoc, *i, 722 diag::err_constexpr_non_literal_param, 723 ArgIndex+1, PD->getSourceRange(), 724 isa<CXXConstructorDecl>(FD))) 725 return false; 726 } 727 return true; 728 } 729 730 /// \brief Get diagnostic %select index for tag kind for 731 /// record diagnostic message. 732 /// WARNING: Indexes apply to particular diagnostics only! 733 /// 734 /// \returns diagnostic %select index. 735 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 736 switch (Tag) { 737 case TTK_Struct: return 0; 738 case TTK_Interface: return 1; 739 case TTK_Class: return 2; 740 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 741 } 742 } 743 744 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 745 // the requirements of a constexpr function definition or a constexpr 746 // constructor definition. If so, return true. If not, produce appropriate 747 // diagnostics and return false. 748 // 749 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 750 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 751 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 752 if (MD && MD->isInstance()) { 753 // C++11 [dcl.constexpr]p4: 754 // The definition of a constexpr constructor shall satisfy the following 755 // constraints: 756 // - the class shall not have any virtual base classes; 757 const CXXRecordDecl *RD = MD->getParent(); 758 if (RD->getNumVBases()) { 759 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 760 << isa<CXXConstructorDecl>(NewFD) 761 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 762 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(), 763 E = RD->vbases_end(); I != E; ++I) 764 Diag(I->getLocStart(), 765 diag::note_constexpr_virtual_base_here) << I->getSourceRange(); 766 return false; 767 } 768 } 769 770 if (!isa<CXXConstructorDecl>(NewFD)) { 771 // C++11 [dcl.constexpr]p3: 772 // The definition of a constexpr function shall satisfy the following 773 // constraints: 774 // - it shall not be virtual; 775 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 776 if (Method && Method->isVirtual()) { 777 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 778 779 // If it's not obvious why this function is virtual, find an overridden 780 // function which uses the 'virtual' keyword. 781 const CXXMethodDecl *WrittenVirtual = Method; 782 while (!WrittenVirtual->isVirtualAsWritten()) 783 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 784 if (WrittenVirtual != Method) 785 Diag(WrittenVirtual->getLocation(), 786 diag::note_overridden_virtual_function); 787 return false; 788 } 789 790 // - its return type shall be a literal type; 791 QualType RT = NewFD->getResultType(); 792 if (!RT->isDependentType() && 793 RequireLiteralType(NewFD->getLocation(), RT, 794 diag::err_constexpr_non_literal_return)) 795 return false; 796 } 797 798 // - each of its parameter types shall be a literal type; 799 if (!CheckConstexprParameterTypes(*this, NewFD)) 800 return false; 801 802 return true; 803 } 804 805 /// Check the given declaration statement is legal within a constexpr function 806 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 807 /// 808 /// \return true if the body is OK (maybe only as an extension), false if we 809 /// have diagnosed a problem. 810 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 811 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 812 // C++11 [dcl.constexpr]p3 and p4: 813 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 814 // contain only 815 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(), 816 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) { 817 switch ((*DclIt)->getKind()) { 818 case Decl::StaticAssert: 819 case Decl::Using: 820 case Decl::UsingShadow: 821 case Decl::UsingDirective: 822 case Decl::UnresolvedUsingTypename: 823 case Decl::UnresolvedUsingValue: 824 // - static_assert-declarations 825 // - using-declarations, 826 // - using-directives, 827 continue; 828 829 case Decl::Typedef: 830 case Decl::TypeAlias: { 831 // - typedef declarations and alias-declarations that do not define 832 // classes or enumerations, 833 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt); 834 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 835 // Don't allow variably-modified types in constexpr functions. 836 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 837 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 838 << TL.getSourceRange() << TL.getType() 839 << isa<CXXConstructorDecl>(Dcl); 840 return false; 841 } 842 continue; 843 } 844 845 case Decl::Enum: 846 case Decl::CXXRecord: 847 // C++1y allows types to be defined, not just declared. 848 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) 849 SemaRef.Diag(DS->getLocStart(), 850 SemaRef.getLangOpts().CPlusPlus1y 851 ? diag::warn_cxx11_compat_constexpr_type_definition 852 : diag::ext_constexpr_type_definition) 853 << isa<CXXConstructorDecl>(Dcl); 854 continue; 855 856 case Decl::EnumConstant: 857 case Decl::IndirectField: 858 case Decl::ParmVar: 859 // These can only appear with other declarations which are banned in 860 // C++11 and permitted in C++1y, so ignore them. 861 continue; 862 863 case Decl::Var: { 864 // C++1y [dcl.constexpr]p3 allows anything except: 865 // a definition of a variable of non-literal type or of static or 866 // thread storage duration or for which no initialization is performed. 867 VarDecl *VD = cast<VarDecl>(*DclIt); 868 if (VD->isThisDeclarationADefinition()) { 869 if (VD->isStaticLocal()) { 870 SemaRef.Diag(VD->getLocation(), 871 diag::err_constexpr_local_var_static) 872 << isa<CXXConstructorDecl>(Dcl) 873 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 874 return false; 875 } 876 if (!VD->getType()->isDependentType() && 877 SemaRef.RequireLiteralType( 878 VD->getLocation(), VD->getType(), 879 diag::err_constexpr_local_var_non_literal_type, 880 isa<CXXConstructorDecl>(Dcl))) 881 return false; 882 if (!VD->hasInit()) { 883 SemaRef.Diag(VD->getLocation(), 884 diag::err_constexpr_local_var_no_init) 885 << isa<CXXConstructorDecl>(Dcl); 886 return false; 887 } 888 } 889 SemaRef.Diag(VD->getLocation(), 890 SemaRef.getLangOpts().CPlusPlus1y 891 ? diag::warn_cxx11_compat_constexpr_local_var 892 : diag::ext_constexpr_local_var) 893 << isa<CXXConstructorDecl>(Dcl); 894 continue; 895 } 896 897 case Decl::NamespaceAlias: 898 case Decl::Function: 899 // These are disallowed in C++11 and permitted in C++1y. Allow them 900 // everywhere as an extension. 901 if (!Cxx1yLoc.isValid()) 902 Cxx1yLoc = DS->getLocStart(); 903 continue; 904 905 default: 906 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 907 << isa<CXXConstructorDecl>(Dcl); 908 return false; 909 } 910 } 911 912 return true; 913 } 914 915 /// Check that the given field is initialized within a constexpr constructor. 916 /// 917 /// \param Dcl The constexpr constructor being checked. 918 /// \param Field The field being checked. This may be a member of an anonymous 919 /// struct or union nested within the class being checked. 920 /// \param Inits All declarations, including anonymous struct/union members and 921 /// indirect members, for which any initialization was provided. 922 /// \param Diagnosed Set to true if an error is produced. 923 static void CheckConstexprCtorInitializer(Sema &SemaRef, 924 const FunctionDecl *Dcl, 925 FieldDecl *Field, 926 llvm::SmallSet<Decl*, 16> &Inits, 927 bool &Diagnosed) { 928 if (Field->isInvalidDecl()) 929 return; 930 931 if (Field->isUnnamedBitfield()) 932 return; 933 934 if (Field->isAnonymousStructOrUnion() && 935 Field->getType()->getAsCXXRecordDecl()->isEmpty()) 936 return; 937 938 if (!Inits.count(Field)) { 939 if (!Diagnosed) { 940 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 941 Diagnosed = true; 942 } 943 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 944 } else if (Field->isAnonymousStructOrUnion()) { 945 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 946 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 947 I != E; ++I) 948 // If an anonymous union contains an anonymous struct of which any member 949 // is initialized, all members must be initialized. 950 if (!RD->isUnion() || Inits.count(*I)) 951 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed); 952 } 953 } 954 955 /// Check the provided statement is allowed in a constexpr function 956 /// definition. 957 static bool 958 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 959 SmallVectorImpl<SourceLocation> &ReturnStmts, 960 SourceLocation &Cxx1yLoc) { 961 // - its function-body shall be [...] a compound-statement that contains only 962 switch (S->getStmtClass()) { 963 case Stmt::NullStmtClass: 964 // - null statements, 965 return true; 966 967 case Stmt::DeclStmtClass: 968 // - static_assert-declarations 969 // - using-declarations, 970 // - using-directives, 971 // - typedef declarations and alias-declarations that do not define 972 // classes or enumerations, 973 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 974 return false; 975 return true; 976 977 case Stmt::ReturnStmtClass: 978 // - and exactly one return statement; 979 if (isa<CXXConstructorDecl>(Dcl)) { 980 // C++1y allows return statements in constexpr constructors. 981 if (!Cxx1yLoc.isValid()) 982 Cxx1yLoc = S->getLocStart(); 983 return true; 984 } 985 986 ReturnStmts.push_back(S->getLocStart()); 987 return true; 988 989 case Stmt::CompoundStmtClass: { 990 // C++1y allows compound-statements. 991 if (!Cxx1yLoc.isValid()) 992 Cxx1yLoc = S->getLocStart(); 993 994 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 995 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(), 996 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) { 997 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts, 998 Cxx1yLoc)) 999 return false; 1000 } 1001 return true; 1002 } 1003 1004 case Stmt::AttributedStmtClass: 1005 if (!Cxx1yLoc.isValid()) 1006 Cxx1yLoc = S->getLocStart(); 1007 return true; 1008 1009 case Stmt::IfStmtClass: { 1010 // C++1y allows if-statements. 1011 if (!Cxx1yLoc.isValid()) 1012 Cxx1yLoc = S->getLocStart(); 1013 1014 IfStmt *If = cast<IfStmt>(S); 1015 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1016 Cxx1yLoc)) 1017 return false; 1018 if (If->getElse() && 1019 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1020 Cxx1yLoc)) 1021 return false; 1022 return true; 1023 } 1024 1025 case Stmt::WhileStmtClass: 1026 case Stmt::DoStmtClass: 1027 case Stmt::ForStmtClass: 1028 case Stmt::CXXForRangeStmtClass: 1029 case Stmt::ContinueStmtClass: 1030 // C++1y allows all of these. We don't allow them as extensions in C++11, 1031 // because they don't make sense without variable mutation. 1032 if (!SemaRef.getLangOpts().CPlusPlus1y) 1033 break; 1034 if (!Cxx1yLoc.isValid()) 1035 Cxx1yLoc = S->getLocStart(); 1036 for (Stmt::child_range Children = S->children(); Children; ++Children) 1037 if (*Children && 1038 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1039 Cxx1yLoc)) 1040 return false; 1041 return true; 1042 1043 case Stmt::SwitchStmtClass: 1044 case Stmt::CaseStmtClass: 1045 case Stmt::DefaultStmtClass: 1046 case Stmt::BreakStmtClass: 1047 // C++1y allows switch-statements, and since they don't need variable 1048 // mutation, we can reasonably allow them in C++11 as an extension. 1049 if (!Cxx1yLoc.isValid()) 1050 Cxx1yLoc = S->getLocStart(); 1051 for (Stmt::child_range Children = S->children(); Children; ++Children) 1052 if (*Children && 1053 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1054 Cxx1yLoc)) 1055 return false; 1056 return true; 1057 1058 default: 1059 if (!isa<Expr>(S)) 1060 break; 1061 1062 // C++1y allows expression-statements. 1063 if (!Cxx1yLoc.isValid()) 1064 Cxx1yLoc = S->getLocStart(); 1065 return true; 1066 } 1067 1068 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1069 << isa<CXXConstructorDecl>(Dcl); 1070 return false; 1071 } 1072 1073 /// Check the body for the given constexpr function declaration only contains 1074 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1075 /// 1076 /// \return true if the body is OK, false if we have diagnosed a problem. 1077 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1078 if (isa<CXXTryStmt>(Body)) { 1079 // C++11 [dcl.constexpr]p3: 1080 // The definition of a constexpr function shall satisfy the following 1081 // constraints: [...] 1082 // - its function-body shall be = delete, = default, or a 1083 // compound-statement 1084 // 1085 // C++11 [dcl.constexpr]p4: 1086 // In the definition of a constexpr constructor, [...] 1087 // - its function-body shall not be a function-try-block; 1088 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1089 << isa<CXXConstructorDecl>(Dcl); 1090 return false; 1091 } 1092 1093 SmallVector<SourceLocation, 4> ReturnStmts; 1094 1095 // - its function-body shall be [...] a compound-statement that contains only 1096 // [... list of cases ...] 1097 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1098 SourceLocation Cxx1yLoc; 1099 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(), 1100 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) { 1101 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc)) 1102 return false; 1103 } 1104 1105 if (Cxx1yLoc.isValid()) 1106 Diag(Cxx1yLoc, 1107 getLangOpts().CPlusPlus1y 1108 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1109 : diag::ext_constexpr_body_invalid_stmt) 1110 << isa<CXXConstructorDecl>(Dcl); 1111 1112 if (const CXXConstructorDecl *Constructor 1113 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1114 const CXXRecordDecl *RD = Constructor->getParent(); 1115 // DR1359: 1116 // - every non-variant non-static data member and base class sub-object 1117 // shall be initialized; 1118 // - if the class is a non-empty union, or for each non-empty anonymous 1119 // union member of a non-union class, exactly one non-static data member 1120 // shall be initialized; 1121 if (RD->isUnion()) { 1122 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) { 1123 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1124 return false; 1125 } 1126 } else if (!Constructor->isDependentContext() && 1127 !Constructor->isDelegatingConstructor()) { 1128 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1129 1130 // Skip detailed checking if we have enough initializers, and we would 1131 // allow at most one initializer per member. 1132 bool AnyAnonStructUnionMembers = false; 1133 unsigned Fields = 0; 1134 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1135 E = RD->field_end(); I != E; ++I, ++Fields) { 1136 if (I->isAnonymousStructOrUnion()) { 1137 AnyAnonStructUnionMembers = true; 1138 break; 1139 } 1140 } 1141 if (AnyAnonStructUnionMembers || 1142 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1143 // Check initialization of non-static data members. Base classes are 1144 // always initialized so do not need to be checked. Dependent bases 1145 // might not have initializers in the member initializer list. 1146 llvm::SmallSet<Decl*, 16> Inits; 1147 for (CXXConstructorDecl::init_const_iterator 1148 I = Constructor->init_begin(), E = Constructor->init_end(); 1149 I != E; ++I) { 1150 if (FieldDecl *FD = (*I)->getMember()) 1151 Inits.insert(FD); 1152 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember()) 1153 Inits.insert(ID->chain_begin(), ID->chain_end()); 1154 } 1155 1156 bool Diagnosed = false; 1157 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1158 E = RD->field_end(); I != E; ++I) 1159 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed); 1160 if (Diagnosed) 1161 return false; 1162 } 1163 } 1164 } else { 1165 if (ReturnStmts.empty()) { 1166 // C++1y doesn't require constexpr functions to contain a 'return' 1167 // statement. We still do, unless the return type is void, because 1168 // otherwise if there's no return statement, the function cannot 1169 // be used in a core constant expression. 1170 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType(); 1171 Diag(Dcl->getLocation(), 1172 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1173 : diag::err_constexpr_body_no_return); 1174 return OK; 1175 } 1176 if (ReturnStmts.size() > 1) { 1177 Diag(ReturnStmts.back(), 1178 getLangOpts().CPlusPlus1y 1179 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1180 : diag::ext_constexpr_body_multiple_return); 1181 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1182 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1183 } 1184 } 1185 1186 // C++11 [dcl.constexpr]p5: 1187 // if no function argument values exist such that the function invocation 1188 // substitution would produce a constant expression, the program is 1189 // ill-formed; no diagnostic required. 1190 // C++11 [dcl.constexpr]p3: 1191 // - every constructor call and implicit conversion used in initializing the 1192 // return value shall be one of those allowed in a constant expression. 1193 // C++11 [dcl.constexpr]p4: 1194 // - every constructor involved in initializing non-static data members and 1195 // base class sub-objects shall be a constexpr constructor. 1196 SmallVector<PartialDiagnosticAt, 8> Diags; 1197 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1198 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1199 << isa<CXXConstructorDecl>(Dcl); 1200 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1201 Diag(Diags[I].first, Diags[I].second); 1202 // Don't return false here: we allow this for compatibility in 1203 // system headers. 1204 } 1205 1206 return true; 1207 } 1208 1209 /// isCurrentClassName - Determine whether the identifier II is the 1210 /// name of the class type currently being defined. In the case of 1211 /// nested classes, this will only return true if II is the name of 1212 /// the innermost class. 1213 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1214 const CXXScopeSpec *SS) { 1215 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1216 1217 CXXRecordDecl *CurDecl; 1218 if (SS && SS->isSet() && !SS->isInvalid()) { 1219 DeclContext *DC = computeDeclContext(*SS, true); 1220 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1221 } else 1222 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1223 1224 if (CurDecl && CurDecl->getIdentifier()) 1225 return &II == CurDecl->getIdentifier(); 1226 return false; 1227 } 1228 1229 /// \brief Determine whether the given class is a base class of the given 1230 /// class, including looking at dependent bases. 1231 static bool findCircularInheritance(const CXXRecordDecl *Class, 1232 const CXXRecordDecl *Current) { 1233 SmallVector<const CXXRecordDecl*, 8> Queue; 1234 1235 Class = Class->getCanonicalDecl(); 1236 while (true) { 1237 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(), 1238 E = Current->bases_end(); 1239 I != E; ++I) { 1240 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); 1241 if (!Base) 1242 continue; 1243 1244 Base = Base->getDefinition(); 1245 if (!Base) 1246 continue; 1247 1248 if (Base->getCanonicalDecl() == Class) 1249 return true; 1250 1251 Queue.push_back(Base); 1252 } 1253 1254 if (Queue.empty()) 1255 return false; 1256 1257 Current = Queue.pop_back_val(); 1258 } 1259 1260 return false; 1261 } 1262 1263 /// \brief Check the validity of a C++ base class specifier. 1264 /// 1265 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1266 /// and returns NULL otherwise. 1267 CXXBaseSpecifier * 1268 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1269 SourceRange SpecifierRange, 1270 bool Virtual, AccessSpecifier Access, 1271 TypeSourceInfo *TInfo, 1272 SourceLocation EllipsisLoc) { 1273 QualType BaseType = TInfo->getType(); 1274 1275 // C++ [class.union]p1: 1276 // A union shall not have base classes. 1277 if (Class->isUnion()) { 1278 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1279 << SpecifierRange; 1280 return 0; 1281 } 1282 1283 if (EllipsisLoc.isValid() && 1284 !TInfo->getType()->containsUnexpandedParameterPack()) { 1285 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1286 << TInfo->getTypeLoc().getSourceRange(); 1287 EllipsisLoc = SourceLocation(); 1288 } 1289 1290 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1291 1292 if (BaseType->isDependentType()) { 1293 // Make sure that we don't have circular inheritance among our dependent 1294 // bases. For non-dependent bases, the check for completeness below handles 1295 // this. 1296 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1297 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1298 ((BaseDecl = BaseDecl->getDefinition()) && 1299 findCircularInheritance(Class, BaseDecl))) { 1300 Diag(BaseLoc, diag::err_circular_inheritance) 1301 << BaseType << Context.getTypeDeclType(Class); 1302 1303 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1304 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1305 << BaseType; 1306 1307 return 0; 1308 } 1309 } 1310 1311 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1312 Class->getTagKind() == TTK_Class, 1313 Access, TInfo, EllipsisLoc); 1314 } 1315 1316 // Base specifiers must be record types. 1317 if (!BaseType->isRecordType()) { 1318 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1319 return 0; 1320 } 1321 1322 // C++ [class.union]p1: 1323 // A union shall not be used as a base class. 1324 if (BaseType->isUnionType()) { 1325 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1326 return 0; 1327 } 1328 1329 // C++ [class.derived]p2: 1330 // The class-name in a base-specifier shall not be an incompletely 1331 // defined class. 1332 if (RequireCompleteType(BaseLoc, BaseType, 1333 diag::err_incomplete_base_class, SpecifierRange)) { 1334 Class->setInvalidDecl(); 1335 return 0; 1336 } 1337 1338 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1339 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1340 assert(BaseDecl && "Record type has no declaration"); 1341 BaseDecl = BaseDecl->getDefinition(); 1342 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1343 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1344 assert(CXXBaseDecl && "Base type is not a C++ type"); 1345 1346 // C++ [class]p3: 1347 // If a class is marked final and it appears as a base-type-specifier in 1348 // base-clause, the program is ill-formed. 1349 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 1350 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1351 << CXXBaseDecl->getDeclName(); 1352 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1353 << CXXBaseDecl->getDeclName(); 1354 return 0; 1355 } 1356 1357 if (BaseDecl->isInvalidDecl()) 1358 Class->setInvalidDecl(); 1359 1360 // Create the base specifier. 1361 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1362 Class->getTagKind() == TTK_Class, 1363 Access, TInfo, EllipsisLoc); 1364 } 1365 1366 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1367 /// one entry in the base class list of a class specifier, for 1368 /// example: 1369 /// class foo : public bar, virtual private baz { 1370 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1371 BaseResult 1372 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1373 ParsedAttributes &Attributes, 1374 bool Virtual, AccessSpecifier Access, 1375 ParsedType basetype, SourceLocation BaseLoc, 1376 SourceLocation EllipsisLoc) { 1377 if (!classdecl) 1378 return true; 1379 1380 AdjustDeclIfTemplate(classdecl); 1381 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1382 if (!Class) 1383 return true; 1384 1385 // We do not support any C++11 attributes on base-specifiers yet. 1386 // Diagnose any attributes we see. 1387 if (!Attributes.empty()) { 1388 for (AttributeList *Attr = Attributes.getList(); Attr; 1389 Attr = Attr->getNext()) { 1390 if (Attr->isInvalid() || 1391 Attr->getKind() == AttributeList::IgnoredAttribute) 1392 continue; 1393 Diag(Attr->getLoc(), 1394 Attr->getKind() == AttributeList::UnknownAttribute 1395 ? diag::warn_unknown_attribute_ignored 1396 : diag::err_base_specifier_attribute) 1397 << Attr->getName(); 1398 } 1399 } 1400 1401 TypeSourceInfo *TInfo = 0; 1402 GetTypeFromParser(basetype, &TInfo); 1403 1404 if (EllipsisLoc.isInvalid() && 1405 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1406 UPPC_BaseType)) 1407 return true; 1408 1409 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1410 Virtual, Access, TInfo, 1411 EllipsisLoc)) 1412 return BaseSpec; 1413 else 1414 Class->setInvalidDecl(); 1415 1416 return true; 1417 } 1418 1419 /// \brief Performs the actual work of attaching the given base class 1420 /// specifiers to a C++ class. 1421 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1422 unsigned NumBases) { 1423 if (NumBases == 0) 1424 return false; 1425 1426 // Used to keep track of which base types we have already seen, so 1427 // that we can properly diagnose redundant direct base types. Note 1428 // that the key is always the unqualified canonical type of the base 1429 // class. 1430 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1431 1432 // Copy non-redundant base specifiers into permanent storage. 1433 unsigned NumGoodBases = 0; 1434 bool Invalid = false; 1435 for (unsigned idx = 0; idx < NumBases; ++idx) { 1436 QualType NewBaseType 1437 = Context.getCanonicalType(Bases[idx]->getType()); 1438 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1439 1440 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1441 if (KnownBase) { 1442 // C++ [class.mi]p3: 1443 // A class shall not be specified as a direct base class of a 1444 // derived class more than once. 1445 Diag(Bases[idx]->getLocStart(), 1446 diag::err_duplicate_base_class) 1447 << KnownBase->getType() 1448 << Bases[idx]->getSourceRange(); 1449 1450 // Delete the duplicate base class specifier; we're going to 1451 // overwrite its pointer later. 1452 Context.Deallocate(Bases[idx]); 1453 1454 Invalid = true; 1455 } else { 1456 // Okay, add this new base class. 1457 KnownBase = Bases[idx]; 1458 Bases[NumGoodBases++] = Bases[idx]; 1459 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1460 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1461 if (Class->isInterface() && 1462 (!RD->isInterface() || 1463 KnownBase->getAccessSpecifier() != AS_public)) { 1464 // The Microsoft extension __interface does not permit bases that 1465 // are not themselves public interfaces. 1466 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1467 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1468 << RD->getSourceRange(); 1469 Invalid = true; 1470 } 1471 if (RD->hasAttr<WeakAttr>()) 1472 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context)); 1473 } 1474 } 1475 } 1476 1477 // Attach the remaining base class specifiers to the derived class. 1478 Class->setBases(Bases, NumGoodBases); 1479 1480 // Delete the remaining (good) base class specifiers, since their 1481 // data has been copied into the CXXRecordDecl. 1482 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1483 Context.Deallocate(Bases[idx]); 1484 1485 return Invalid; 1486 } 1487 1488 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1489 /// class, after checking whether there are any duplicate base 1490 /// classes. 1491 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1492 unsigned NumBases) { 1493 if (!ClassDecl || !Bases || !NumBases) 1494 return; 1495 1496 AdjustDeclIfTemplate(ClassDecl); 1497 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1498 } 1499 1500 /// \brief Determine whether the type \p Derived is a C++ class that is 1501 /// derived from the type \p Base. 1502 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1503 if (!getLangOpts().CPlusPlus) 1504 return false; 1505 1506 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1507 if (!DerivedRD) 1508 return false; 1509 1510 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1511 if (!BaseRD) 1512 return false; 1513 1514 // If either the base or the derived type is invalid, don't try to 1515 // check whether one is derived from the other. 1516 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1517 return false; 1518 1519 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1520 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1521 } 1522 1523 /// \brief Determine whether the type \p Derived is a C++ class that is 1524 /// derived from the type \p Base. 1525 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1526 if (!getLangOpts().CPlusPlus) 1527 return false; 1528 1529 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1530 if (!DerivedRD) 1531 return false; 1532 1533 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1534 if (!BaseRD) 1535 return false; 1536 1537 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1538 } 1539 1540 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1541 CXXCastPath &BasePathArray) { 1542 assert(BasePathArray.empty() && "Base path array must be empty!"); 1543 assert(Paths.isRecordingPaths() && "Must record paths!"); 1544 1545 const CXXBasePath &Path = Paths.front(); 1546 1547 // We first go backward and check if we have a virtual base. 1548 // FIXME: It would be better if CXXBasePath had the base specifier for 1549 // the nearest virtual base. 1550 unsigned Start = 0; 1551 for (unsigned I = Path.size(); I != 0; --I) { 1552 if (Path[I - 1].Base->isVirtual()) { 1553 Start = I - 1; 1554 break; 1555 } 1556 } 1557 1558 // Now add all bases. 1559 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1560 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1561 } 1562 1563 /// \brief Determine whether the given base path includes a virtual 1564 /// base class. 1565 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1566 for (CXXCastPath::const_iterator B = BasePath.begin(), 1567 BEnd = BasePath.end(); 1568 B != BEnd; ++B) 1569 if ((*B)->isVirtual()) 1570 return true; 1571 1572 return false; 1573 } 1574 1575 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1576 /// conversion (where Derived and Base are class types) is 1577 /// well-formed, meaning that the conversion is unambiguous (and 1578 /// that all of the base classes are accessible). Returns true 1579 /// and emits a diagnostic if the code is ill-formed, returns false 1580 /// otherwise. Loc is the location where this routine should point to 1581 /// if there is an error, and Range is the source range to highlight 1582 /// if there is an error. 1583 bool 1584 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1585 unsigned InaccessibleBaseID, 1586 unsigned AmbigiousBaseConvID, 1587 SourceLocation Loc, SourceRange Range, 1588 DeclarationName Name, 1589 CXXCastPath *BasePath) { 1590 // First, determine whether the path from Derived to Base is 1591 // ambiguous. This is slightly more expensive than checking whether 1592 // the Derived to Base conversion exists, because here we need to 1593 // explore multiple paths to determine if there is an ambiguity. 1594 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1595 /*DetectVirtual=*/false); 1596 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1597 assert(DerivationOkay && 1598 "Can only be used with a derived-to-base conversion"); 1599 (void)DerivationOkay; 1600 1601 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1602 if (InaccessibleBaseID) { 1603 // Check that the base class can be accessed. 1604 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1605 InaccessibleBaseID)) { 1606 case AR_inaccessible: 1607 return true; 1608 case AR_accessible: 1609 case AR_dependent: 1610 case AR_delayed: 1611 break; 1612 } 1613 } 1614 1615 // Build a base path if necessary. 1616 if (BasePath) 1617 BuildBasePathArray(Paths, *BasePath); 1618 return false; 1619 } 1620 1621 if (AmbigiousBaseConvID) { 1622 // We know that the derived-to-base conversion is ambiguous, and 1623 // we're going to produce a diagnostic. Perform the derived-to-base 1624 // search just one more time to compute all of the possible paths so 1625 // that we can print them out. This is more expensive than any of 1626 // the previous derived-to-base checks we've done, but at this point 1627 // performance isn't as much of an issue. 1628 Paths.clear(); 1629 Paths.setRecordingPaths(true); 1630 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1631 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1632 (void)StillOkay; 1633 1634 // Build up a textual representation of the ambiguous paths, e.g., 1635 // D -> B -> A, that will be used to illustrate the ambiguous 1636 // conversions in the diagnostic. We only print one of the paths 1637 // to each base class subobject. 1638 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1639 1640 Diag(Loc, AmbigiousBaseConvID) 1641 << Derived << Base << PathDisplayStr << Range << Name; 1642 } 1643 return true; 1644 } 1645 1646 bool 1647 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1648 SourceLocation Loc, SourceRange Range, 1649 CXXCastPath *BasePath, 1650 bool IgnoreAccess) { 1651 return CheckDerivedToBaseConversion(Derived, Base, 1652 IgnoreAccess ? 0 1653 : diag::err_upcast_to_inaccessible_base, 1654 diag::err_ambiguous_derived_to_base_conv, 1655 Loc, Range, DeclarationName(), 1656 BasePath); 1657 } 1658 1659 1660 /// @brief Builds a string representing ambiguous paths from a 1661 /// specific derived class to different subobjects of the same base 1662 /// class. 1663 /// 1664 /// This function builds a string that can be used in error messages 1665 /// to show the different paths that one can take through the 1666 /// inheritance hierarchy to go from the derived class to different 1667 /// subobjects of a base class. The result looks something like this: 1668 /// @code 1669 /// struct D -> struct B -> struct A 1670 /// struct D -> struct C -> struct A 1671 /// @endcode 1672 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1673 std::string PathDisplayStr; 1674 std::set<unsigned> DisplayedPaths; 1675 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1676 Path != Paths.end(); ++Path) { 1677 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1678 // We haven't displayed a path to this particular base 1679 // class subobject yet. 1680 PathDisplayStr += "\n "; 1681 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1682 for (CXXBasePath::const_iterator Element = Path->begin(); 1683 Element != Path->end(); ++Element) 1684 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1685 } 1686 } 1687 1688 return PathDisplayStr; 1689 } 1690 1691 //===----------------------------------------------------------------------===// 1692 // C++ class member Handling 1693 //===----------------------------------------------------------------------===// 1694 1695 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1696 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1697 SourceLocation ASLoc, 1698 SourceLocation ColonLoc, 1699 AttributeList *Attrs) { 1700 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1701 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1702 ASLoc, ColonLoc); 1703 CurContext->addHiddenDecl(ASDecl); 1704 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1705 } 1706 1707 /// CheckOverrideControl - Check C++11 override control semantics. 1708 void Sema::CheckOverrideControl(NamedDecl *D) { 1709 if (D->isInvalidDecl()) 1710 return; 1711 1712 // We only care about "override" and "final" declarations. 1713 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1714 return; 1715 1716 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1717 1718 // We can't check dependent instance methods. 1719 if (MD && MD->isInstance() && 1720 (MD->getParent()->hasAnyDependentBases() || 1721 MD->getType()->isDependentType())) 1722 return; 1723 1724 if (MD && !MD->isVirtual()) { 1725 // If we have a non-virtual method, check if if hides a virtual method. 1726 // (In that case, it's most likely the method has the wrong type.) 1727 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1728 FindHiddenVirtualMethods(MD, OverloadedMethods); 1729 1730 if (!OverloadedMethods.empty()) { 1731 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1732 Diag(OA->getLocation(), 1733 diag::override_keyword_hides_virtual_member_function) 1734 << "override" << (OverloadedMethods.size() > 1); 1735 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1736 Diag(FA->getLocation(), 1737 diag::override_keyword_hides_virtual_member_function) 1738 << "final" << (OverloadedMethods.size() > 1); 1739 } 1740 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1741 MD->setInvalidDecl(); 1742 return; 1743 } 1744 // Fall through into the general case diagnostic. 1745 // FIXME: We might want to attempt typo correction here. 1746 } 1747 1748 if (!MD || !MD->isVirtual()) { 1749 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1750 Diag(OA->getLocation(), 1751 diag::override_keyword_only_allowed_on_virtual_member_functions) 1752 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1753 D->dropAttr<OverrideAttr>(); 1754 } 1755 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1756 Diag(FA->getLocation(), 1757 diag::override_keyword_only_allowed_on_virtual_member_functions) 1758 << "final" << FixItHint::CreateRemoval(FA->getLocation()); 1759 D->dropAttr<FinalAttr>(); 1760 } 1761 return; 1762 } 1763 1764 // C++11 [class.virtual]p5: 1765 // If a virtual function is marked with the virt-specifier override and 1766 // does not override a member function of a base class, the program is 1767 // ill-formed. 1768 bool HasOverriddenMethods = 1769 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1770 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1771 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1772 << MD->getDeclName(); 1773 } 1774 1775 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1776 /// function overrides a virtual member function marked 'final', according to 1777 /// C++11 [class.virtual]p4. 1778 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1779 const CXXMethodDecl *Old) { 1780 if (!Old->hasAttr<FinalAttr>()) 1781 return false; 1782 1783 Diag(New->getLocation(), diag::err_final_function_overridden) 1784 << New->getDeclName(); 1785 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1786 return true; 1787 } 1788 1789 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1790 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1791 // FIXME: Destruction of ObjC lifetime types has side-effects. 1792 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1793 return !RD->isCompleteDefinition() || 1794 !RD->hasTrivialDefaultConstructor() || 1795 !RD->hasTrivialDestructor(); 1796 return false; 1797 } 1798 1799 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1800 for (AttributeList* it = list; it != 0; it = it->getNext()) 1801 if (it->isDeclspecPropertyAttribute()) 1802 return it; 1803 return 0; 1804 } 1805 1806 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1807 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1808 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1809 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1810 /// present (but parsing it has been deferred). 1811 NamedDecl * 1812 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1813 MultiTemplateParamsArg TemplateParameterLists, 1814 Expr *BW, const VirtSpecifiers &VS, 1815 InClassInitStyle InitStyle) { 1816 const DeclSpec &DS = D.getDeclSpec(); 1817 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1818 DeclarationName Name = NameInfo.getName(); 1819 SourceLocation Loc = NameInfo.getLoc(); 1820 1821 // For anonymous bitfields, the location should point to the type. 1822 if (Loc.isInvalid()) 1823 Loc = D.getLocStart(); 1824 1825 Expr *BitWidth = static_cast<Expr*>(BW); 1826 1827 assert(isa<CXXRecordDecl>(CurContext)); 1828 assert(!DS.isFriendSpecified()); 1829 1830 bool isFunc = D.isDeclarationOfFunction(); 1831 1832 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1833 // The Microsoft extension __interface only permits public member functions 1834 // and prohibits constructors, destructors, operators, non-public member 1835 // functions, static methods and data members. 1836 unsigned InvalidDecl; 1837 bool ShowDeclName = true; 1838 if (!isFunc) 1839 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1840 else if (AS != AS_public) 1841 InvalidDecl = 2; 1842 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1843 InvalidDecl = 3; 1844 else switch (Name.getNameKind()) { 1845 case DeclarationName::CXXConstructorName: 1846 InvalidDecl = 4; 1847 ShowDeclName = false; 1848 break; 1849 1850 case DeclarationName::CXXDestructorName: 1851 InvalidDecl = 5; 1852 ShowDeclName = false; 1853 break; 1854 1855 case DeclarationName::CXXOperatorName: 1856 case DeclarationName::CXXConversionFunctionName: 1857 InvalidDecl = 6; 1858 break; 1859 1860 default: 1861 InvalidDecl = 0; 1862 break; 1863 } 1864 1865 if (InvalidDecl) { 1866 if (ShowDeclName) 1867 Diag(Loc, diag::err_invalid_member_in_interface) 1868 << (InvalidDecl-1) << Name; 1869 else 1870 Diag(Loc, diag::err_invalid_member_in_interface) 1871 << (InvalidDecl-1) << ""; 1872 return 0; 1873 } 1874 } 1875 1876 // C++ 9.2p6: A member shall not be declared to have automatic storage 1877 // duration (auto, register) or with the extern storage-class-specifier. 1878 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1879 // data members and cannot be applied to names declared const or static, 1880 // and cannot be applied to reference members. 1881 switch (DS.getStorageClassSpec()) { 1882 case DeclSpec::SCS_unspecified: 1883 case DeclSpec::SCS_typedef: 1884 case DeclSpec::SCS_static: 1885 break; 1886 case DeclSpec::SCS_mutable: 1887 if (isFunc) { 1888 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1889 1890 // FIXME: It would be nicer if the keyword was ignored only for this 1891 // declarator. Otherwise we could get follow-up errors. 1892 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1893 } 1894 break; 1895 default: 1896 Diag(DS.getStorageClassSpecLoc(), 1897 diag::err_storageclass_invalid_for_member); 1898 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1899 break; 1900 } 1901 1902 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1903 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1904 !isFunc); 1905 1906 if (DS.isConstexprSpecified() && isInstField) { 1907 SemaDiagnosticBuilder B = 1908 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 1909 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 1910 if (InitStyle == ICIS_NoInit) { 1911 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const"); 1912 D.getMutableDeclSpec().ClearConstexprSpec(); 1913 const char *PrevSpec; 1914 unsigned DiagID; 1915 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc, 1916 PrevSpec, DiagID, getLangOpts()); 1917 (void)Failed; 1918 assert(!Failed && "Making a constexpr member const shouldn't fail"); 1919 } else { 1920 B << 1; 1921 const char *PrevSpec; 1922 unsigned DiagID; 1923 if (D.getMutableDeclSpec().SetStorageClassSpec( 1924 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) { 1925 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 1926 "This is the only DeclSpec that should fail to be applied"); 1927 B << 1; 1928 } else { 1929 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 1930 isInstField = false; 1931 } 1932 } 1933 } 1934 1935 NamedDecl *Member; 1936 if (isInstField) { 1937 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1938 1939 // Data members must have identifiers for names. 1940 if (!Name.isIdentifier()) { 1941 Diag(Loc, diag::err_bad_variable_name) 1942 << Name; 1943 return 0; 1944 } 1945 1946 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1947 1948 // Member field could not be with "template" keyword. 1949 // So TemplateParameterLists should be empty in this case. 1950 if (TemplateParameterLists.size()) { 1951 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 1952 if (TemplateParams->size()) { 1953 // There is no such thing as a member field template. 1954 Diag(D.getIdentifierLoc(), diag::err_template_member) 1955 << II 1956 << SourceRange(TemplateParams->getTemplateLoc(), 1957 TemplateParams->getRAngleLoc()); 1958 } else { 1959 // There is an extraneous 'template<>' for this member. 1960 Diag(TemplateParams->getTemplateLoc(), 1961 diag::err_template_member_noparams) 1962 << II 1963 << SourceRange(TemplateParams->getTemplateLoc(), 1964 TemplateParams->getRAngleLoc()); 1965 } 1966 return 0; 1967 } 1968 1969 if (SS.isSet() && !SS.isInvalid()) { 1970 // The user provided a superfluous scope specifier inside a class 1971 // definition: 1972 // 1973 // class X { 1974 // int X::member; 1975 // }; 1976 if (DeclContext *DC = computeDeclContext(SS, false)) 1977 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 1978 else 1979 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1980 << Name << SS.getRange(); 1981 1982 SS.clear(); 1983 } 1984 1985 AttributeList *MSPropertyAttr = 1986 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 1987 if (MSPropertyAttr) { 1988 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 1989 BitWidth, InitStyle, AS, MSPropertyAttr); 1990 if (!Member) 1991 return 0; 1992 isInstField = false; 1993 } else { 1994 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 1995 BitWidth, InitStyle, AS); 1996 assert(Member && "HandleField never returns null"); 1997 } 1998 } else { 1999 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2000 2001 Member = HandleDeclarator(S, D, TemplateParameterLists); 2002 if (!Member) 2003 return 0; 2004 2005 // Non-instance-fields can't have a bitfield. 2006 if (BitWidth) { 2007 if (Member->isInvalidDecl()) { 2008 // don't emit another diagnostic. 2009 } else if (isa<VarDecl>(Member)) { 2010 // C++ 9.6p3: A bit-field shall not be a static member. 2011 // "static member 'A' cannot be a bit-field" 2012 Diag(Loc, diag::err_static_not_bitfield) 2013 << Name << BitWidth->getSourceRange(); 2014 } else if (isa<TypedefDecl>(Member)) { 2015 // "typedef member 'x' cannot be a bit-field" 2016 Diag(Loc, diag::err_typedef_not_bitfield) 2017 << Name << BitWidth->getSourceRange(); 2018 } else { 2019 // A function typedef ("typedef int f(); f a;"). 2020 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2021 Diag(Loc, diag::err_not_integral_type_bitfield) 2022 << Name << cast<ValueDecl>(Member)->getType() 2023 << BitWidth->getSourceRange(); 2024 } 2025 2026 BitWidth = 0; 2027 Member->setInvalidDecl(); 2028 } 2029 2030 Member->setAccess(AS); 2031 2032 // If we have declared a member function template or static data member 2033 // template, set the access of the templated declaration as well. 2034 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2035 FunTmpl->getTemplatedDecl()->setAccess(AS); 2036 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2037 VarTmpl->getTemplatedDecl()->setAccess(AS); 2038 } 2039 2040 if (VS.isOverrideSpecified()) 2041 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 2042 if (VS.isFinalSpecified()) 2043 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 2044 2045 if (VS.getLastLocation().isValid()) { 2046 // Update the end location of a method that has a virt-specifiers. 2047 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2048 MD->setRangeEnd(VS.getLastLocation()); 2049 } 2050 2051 CheckOverrideControl(Member); 2052 2053 assert((Name || isInstField) && "No identifier for non-field ?"); 2054 2055 if (isInstField) { 2056 FieldDecl *FD = cast<FieldDecl>(Member); 2057 FieldCollector->Add(FD); 2058 2059 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 2060 FD->getLocation()) 2061 != DiagnosticsEngine::Ignored) { 2062 // Remember all explicit private FieldDecls that have a name, no side 2063 // effects and are not part of a dependent type declaration. 2064 if (!FD->isImplicit() && FD->getDeclName() && 2065 FD->getAccess() == AS_private && 2066 !FD->hasAttr<UnusedAttr>() && 2067 !FD->getParent()->isDependentContext() && 2068 !InitializationHasSideEffects(*FD)) 2069 UnusedPrivateFields.insert(FD); 2070 } 2071 } 2072 2073 return Member; 2074 } 2075 2076 namespace { 2077 class UninitializedFieldVisitor 2078 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2079 Sema &S; 2080 // If VD is null, this visitor will only update the Decls set. 2081 ValueDecl *VD; 2082 bool isReferenceType; 2083 // List of Decls to generate a warning on. 2084 llvm::SmallPtrSet<ValueDecl*, 4> &Decls; 2085 bool WarnOnSelfReference; 2086 // If non-null, add a note to the warning pointing back to the constructor. 2087 const CXXConstructorDecl *Constructor; 2088 public: 2089 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2090 UninitializedFieldVisitor(Sema &S, ValueDecl *VD, 2091 llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2092 bool WarnOnSelfReference, 2093 const CXXConstructorDecl *Constructor) 2094 : Inherited(S.Context), S(S), VD(VD), isReferenceType(false), Decls(Decls), 2095 WarnOnSelfReference(WarnOnSelfReference), Constructor(Constructor) { 2096 // When VD is null, this visitor is used to detect initialization of other 2097 // fields. 2098 if (VD) { 2099 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD)) 2100 this->VD = IFD->getAnonField(); 2101 else 2102 this->VD = VD; 2103 isReferenceType = this->VD->getType()->isReferenceType(); 2104 } 2105 } 2106 2107 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) { 2108 if (!VD) 2109 return; 2110 2111 if (CheckReferenceOnly && !isReferenceType) 2112 return; 2113 2114 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2115 return; 2116 2117 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2118 // or union. 2119 MemberExpr *FieldME = ME; 2120 2121 Expr *Base = ME; 2122 while (isa<MemberExpr>(Base)) { 2123 ME = cast<MemberExpr>(Base); 2124 2125 if (isa<VarDecl>(ME->getMemberDecl())) 2126 return; 2127 2128 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2129 if (!FD->isAnonymousStructOrUnion()) 2130 FieldME = ME; 2131 2132 Base = ME->getBase(); 2133 } 2134 2135 if (!isa<CXXThisExpr>(Base)) 2136 return; 2137 2138 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2139 2140 if (VD == FoundVD) { 2141 if (!WarnOnSelfReference) 2142 return; 2143 2144 unsigned diag = isReferenceType 2145 ? diag::warn_reference_field_is_uninit 2146 : diag::warn_field_is_uninit; 2147 S.Diag(FieldME->getExprLoc(), diag) << VD; 2148 if (Constructor) 2149 S.Diag(Constructor->getLocation(), 2150 diag::note_uninit_in_this_constructor); 2151 return; 2152 } 2153 2154 if (CheckReferenceOnly) 2155 return; 2156 2157 if (Decls.count(FoundVD)) { 2158 S.Diag(FieldME->getExprLoc(), diag::warn_field_is_uninit) << FoundVD; 2159 if (Constructor) 2160 S.Diag(Constructor->getLocation(), 2161 diag::note_uninit_in_this_constructor); 2162 2163 } 2164 } 2165 2166 void HandleValue(Expr *E) { 2167 if (!VD) 2168 return; 2169 2170 E = E->IgnoreParens(); 2171 2172 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2173 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2174 return; 2175 } 2176 2177 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2178 HandleValue(CO->getTrueExpr()); 2179 HandleValue(CO->getFalseExpr()); 2180 return; 2181 } 2182 2183 if (BinaryConditionalOperator *BCO = 2184 dyn_cast<BinaryConditionalOperator>(E)) { 2185 HandleValue(BCO->getCommon()); 2186 HandleValue(BCO->getFalseExpr()); 2187 return; 2188 } 2189 2190 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2191 switch (BO->getOpcode()) { 2192 default: 2193 return; 2194 case(BO_PtrMemD): 2195 case(BO_PtrMemI): 2196 HandleValue(BO->getLHS()); 2197 return; 2198 case(BO_Comma): 2199 HandleValue(BO->getRHS()); 2200 return; 2201 } 2202 } 2203 } 2204 2205 void VisitMemberExpr(MemberExpr *ME) { 2206 HandleMemberExpr(ME, true /*CheckReferenceOnly*/); 2207 2208 Inherited::VisitMemberExpr(ME); 2209 } 2210 2211 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2212 if (E->getCastKind() == CK_LValueToRValue) 2213 HandleValue(E->getSubExpr()); 2214 2215 Inherited::VisitImplicitCastExpr(E); 2216 } 2217 2218 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2219 if (E->getConstructor()->isCopyConstructor()) 2220 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0))) 2221 if (ICE->getCastKind() == CK_NoOp) 2222 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr())) 2223 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2224 2225 Inherited::VisitCXXConstructExpr(E); 2226 } 2227 2228 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2229 Expr *Callee = E->getCallee(); 2230 if (isa<MemberExpr>(Callee)) 2231 HandleValue(Callee); 2232 2233 Inherited::VisitCXXMemberCallExpr(E); 2234 } 2235 2236 void VisitBinaryOperator(BinaryOperator *E) { 2237 // If a field assignment is detected, remove the field from the 2238 // uninitiailized field set. 2239 if (E->getOpcode() == BO_Assign) 2240 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2241 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2242 Decls.erase(FD); 2243 2244 Inherited::VisitBinaryOperator(E); 2245 } 2246 }; 2247 static void CheckInitExprContainsUninitializedFields( 2248 Sema &S, Expr *E, ValueDecl *VD, llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2249 bool WarnOnSelfReference, const CXXConstructorDecl *Constructor = 0) { 2250 if (Decls.size() == 0 && !WarnOnSelfReference) 2251 return; 2252 2253 if (E) 2254 UninitializedFieldVisitor(S, VD, Decls, WarnOnSelfReference, Constructor) 2255 .Visit(E); 2256 } 2257 } // namespace 2258 2259 /// ActOnCXXInClassMemberInitializer - This is invoked after parsing an 2260 /// in-class initializer for a non-static C++ class member, and after 2261 /// instantiating an in-class initializer in a class template. Such actions 2262 /// are deferred until the class is complete. 2263 void 2264 Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc, 2265 Expr *InitExpr) { 2266 FieldDecl *FD = cast<FieldDecl>(D); 2267 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2268 "must set init style when field is created"); 2269 2270 if (!InitExpr) { 2271 FD->setInvalidDecl(); 2272 FD->removeInClassInitializer(); 2273 return; 2274 } 2275 2276 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2277 FD->setInvalidDecl(); 2278 FD->removeInClassInitializer(); 2279 return; 2280 } 2281 2282 ExprResult Init = InitExpr; 2283 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2284 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2285 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2286 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2287 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2288 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2289 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2290 if (Init.isInvalid()) { 2291 FD->setInvalidDecl(); 2292 return; 2293 } 2294 } 2295 2296 // C++11 [class.base.init]p7: 2297 // The initialization of each base and member constitutes a 2298 // full-expression. 2299 Init = ActOnFinishFullExpr(Init.take(), InitLoc); 2300 if (Init.isInvalid()) { 2301 FD->setInvalidDecl(); 2302 return; 2303 } 2304 2305 InitExpr = Init.release(); 2306 2307 FD->setInClassInitializer(InitExpr); 2308 } 2309 2310 /// \brief Find the direct and/or virtual base specifiers that 2311 /// correspond to the given base type, for use in base initialization 2312 /// within a constructor. 2313 static bool FindBaseInitializer(Sema &SemaRef, 2314 CXXRecordDecl *ClassDecl, 2315 QualType BaseType, 2316 const CXXBaseSpecifier *&DirectBaseSpec, 2317 const CXXBaseSpecifier *&VirtualBaseSpec) { 2318 // First, check for a direct base class. 2319 DirectBaseSpec = 0; 2320 for (CXXRecordDecl::base_class_const_iterator Base 2321 = ClassDecl->bases_begin(); 2322 Base != ClassDecl->bases_end(); ++Base) { 2323 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 2324 // We found a direct base of this type. That's what we're 2325 // initializing. 2326 DirectBaseSpec = &*Base; 2327 break; 2328 } 2329 } 2330 2331 // Check for a virtual base class. 2332 // FIXME: We might be able to short-circuit this if we know in advance that 2333 // there are no virtual bases. 2334 VirtualBaseSpec = 0; 2335 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2336 // We haven't found a base yet; search the class hierarchy for a 2337 // virtual base class. 2338 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2339 /*DetectVirtual=*/false); 2340 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2341 BaseType, Paths)) { 2342 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2343 Path != Paths.end(); ++Path) { 2344 if (Path->back().Base->isVirtual()) { 2345 VirtualBaseSpec = Path->back().Base; 2346 break; 2347 } 2348 } 2349 } 2350 } 2351 2352 return DirectBaseSpec || VirtualBaseSpec; 2353 } 2354 2355 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2356 MemInitResult 2357 Sema::ActOnMemInitializer(Decl *ConstructorD, 2358 Scope *S, 2359 CXXScopeSpec &SS, 2360 IdentifierInfo *MemberOrBase, 2361 ParsedType TemplateTypeTy, 2362 const DeclSpec &DS, 2363 SourceLocation IdLoc, 2364 Expr *InitList, 2365 SourceLocation EllipsisLoc) { 2366 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2367 DS, IdLoc, InitList, 2368 EllipsisLoc); 2369 } 2370 2371 /// \brief Handle a C++ member initializer using parentheses syntax. 2372 MemInitResult 2373 Sema::ActOnMemInitializer(Decl *ConstructorD, 2374 Scope *S, 2375 CXXScopeSpec &SS, 2376 IdentifierInfo *MemberOrBase, 2377 ParsedType TemplateTypeTy, 2378 const DeclSpec &DS, 2379 SourceLocation IdLoc, 2380 SourceLocation LParenLoc, 2381 ArrayRef<Expr *> Args, 2382 SourceLocation RParenLoc, 2383 SourceLocation EllipsisLoc) { 2384 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2385 Args, RParenLoc); 2386 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2387 DS, IdLoc, List, EllipsisLoc); 2388 } 2389 2390 namespace { 2391 2392 // Callback to only accept typo corrections that can be a valid C++ member 2393 // intializer: either a non-static field member or a base class. 2394 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2395 public: 2396 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2397 : ClassDecl(ClassDecl) {} 2398 2399 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE { 2400 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2401 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2402 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2403 return isa<TypeDecl>(ND); 2404 } 2405 return false; 2406 } 2407 2408 private: 2409 CXXRecordDecl *ClassDecl; 2410 }; 2411 2412 } 2413 2414 /// \brief Handle a C++ member initializer. 2415 MemInitResult 2416 Sema::BuildMemInitializer(Decl *ConstructorD, 2417 Scope *S, 2418 CXXScopeSpec &SS, 2419 IdentifierInfo *MemberOrBase, 2420 ParsedType TemplateTypeTy, 2421 const DeclSpec &DS, 2422 SourceLocation IdLoc, 2423 Expr *Init, 2424 SourceLocation EllipsisLoc) { 2425 if (!ConstructorD) 2426 return true; 2427 2428 AdjustDeclIfTemplate(ConstructorD); 2429 2430 CXXConstructorDecl *Constructor 2431 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2432 if (!Constructor) { 2433 // The user wrote a constructor initializer on a function that is 2434 // not a C++ constructor. Ignore the error for now, because we may 2435 // have more member initializers coming; we'll diagnose it just 2436 // once in ActOnMemInitializers. 2437 return true; 2438 } 2439 2440 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2441 2442 // C++ [class.base.init]p2: 2443 // Names in a mem-initializer-id are looked up in the scope of the 2444 // constructor's class and, if not found in that scope, are looked 2445 // up in the scope containing the constructor's definition. 2446 // [Note: if the constructor's class contains a member with the 2447 // same name as a direct or virtual base class of the class, a 2448 // mem-initializer-id naming the member or base class and composed 2449 // of a single identifier refers to the class member. A 2450 // mem-initializer-id for the hidden base class may be specified 2451 // using a qualified name. ] 2452 if (!SS.getScopeRep() && !TemplateTypeTy) { 2453 // Look for a member, first. 2454 DeclContext::lookup_result Result 2455 = ClassDecl->lookup(MemberOrBase); 2456 if (!Result.empty()) { 2457 ValueDecl *Member; 2458 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2459 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2460 if (EllipsisLoc.isValid()) 2461 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2462 << MemberOrBase 2463 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2464 2465 return BuildMemberInitializer(Member, Init, IdLoc); 2466 } 2467 } 2468 } 2469 // It didn't name a member, so see if it names a class. 2470 QualType BaseType; 2471 TypeSourceInfo *TInfo = 0; 2472 2473 if (TemplateTypeTy) { 2474 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2475 } else if (DS.getTypeSpecType() == TST_decltype) { 2476 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2477 } else { 2478 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2479 LookupParsedName(R, S, &SS); 2480 2481 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2482 if (!TyD) { 2483 if (R.isAmbiguous()) return true; 2484 2485 // We don't want access-control diagnostics here. 2486 R.suppressDiagnostics(); 2487 2488 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2489 bool NotUnknownSpecialization = false; 2490 DeclContext *DC = computeDeclContext(SS, false); 2491 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2492 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2493 2494 if (!NotUnknownSpecialization) { 2495 // When the scope specifier can refer to a member of an unknown 2496 // specialization, we take it as a type name. 2497 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2498 SS.getWithLocInContext(Context), 2499 *MemberOrBase, IdLoc); 2500 if (BaseType.isNull()) 2501 return true; 2502 2503 R.clear(); 2504 R.setLookupName(MemberOrBase); 2505 } 2506 } 2507 2508 // If no results were found, try to correct typos. 2509 TypoCorrection Corr; 2510 MemInitializerValidatorCCC Validator(ClassDecl); 2511 if (R.empty() && BaseType.isNull() && 2512 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2513 Validator, ClassDecl))) { 2514 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2515 // We have found a non-static data member with a similar 2516 // name to what was typed; complain and initialize that 2517 // member. 2518 diagnoseTypo(Corr, 2519 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2520 << MemberOrBase << true); 2521 return BuildMemberInitializer(Member, Init, IdLoc); 2522 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2523 const CXXBaseSpecifier *DirectBaseSpec; 2524 const CXXBaseSpecifier *VirtualBaseSpec; 2525 if (FindBaseInitializer(*this, ClassDecl, 2526 Context.getTypeDeclType(Type), 2527 DirectBaseSpec, VirtualBaseSpec)) { 2528 // We have found a direct or virtual base class with a 2529 // similar name to what was typed; complain and initialize 2530 // that base class. 2531 diagnoseTypo(Corr, 2532 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2533 << MemberOrBase << false, 2534 PDiag() /*Suppress note, we provide our own.*/); 2535 2536 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2537 : VirtualBaseSpec; 2538 Diag(BaseSpec->getLocStart(), 2539 diag::note_base_class_specified_here) 2540 << BaseSpec->getType() 2541 << BaseSpec->getSourceRange(); 2542 2543 TyD = Type; 2544 } 2545 } 2546 } 2547 2548 if (!TyD && BaseType.isNull()) { 2549 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2550 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2551 return true; 2552 } 2553 } 2554 2555 if (BaseType.isNull()) { 2556 BaseType = Context.getTypeDeclType(TyD); 2557 if (SS.isSet()) { 2558 NestedNameSpecifier *Qualifier = 2559 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 2560 2561 // FIXME: preserve source range information 2562 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 2563 } 2564 } 2565 } 2566 2567 if (!TInfo) 2568 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2569 2570 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2571 } 2572 2573 /// Checks a member initializer expression for cases where reference (or 2574 /// pointer) members are bound to by-value parameters (or their addresses). 2575 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2576 Expr *Init, 2577 SourceLocation IdLoc) { 2578 QualType MemberTy = Member->getType(); 2579 2580 // We only handle pointers and references currently. 2581 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2582 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2583 return; 2584 2585 const bool IsPointer = MemberTy->isPointerType(); 2586 if (IsPointer) { 2587 if (const UnaryOperator *Op 2588 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2589 // The only case we're worried about with pointers requires taking the 2590 // address. 2591 if (Op->getOpcode() != UO_AddrOf) 2592 return; 2593 2594 Init = Op->getSubExpr(); 2595 } else { 2596 // We only handle address-of expression initializers for pointers. 2597 return; 2598 } 2599 } 2600 2601 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2602 // We only warn when referring to a non-reference parameter declaration. 2603 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2604 if (!Parameter || Parameter->getType()->isReferenceType()) 2605 return; 2606 2607 S.Diag(Init->getExprLoc(), 2608 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2609 : diag::warn_bind_ref_member_to_parameter) 2610 << Member << Parameter << Init->getSourceRange(); 2611 } else { 2612 // Other initializers are fine. 2613 return; 2614 } 2615 2616 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2617 << (unsigned)IsPointer; 2618 } 2619 2620 MemInitResult 2621 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2622 SourceLocation IdLoc) { 2623 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2624 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2625 assert((DirectMember || IndirectMember) && 2626 "Member must be a FieldDecl or IndirectFieldDecl"); 2627 2628 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2629 return true; 2630 2631 if (Member->isInvalidDecl()) 2632 return true; 2633 2634 MultiExprArg Args; 2635 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2636 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2637 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2638 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2639 } else { 2640 // Template instantiation doesn't reconstruct ParenListExprs for us. 2641 Args = Init; 2642 } 2643 2644 SourceRange InitRange = Init->getSourceRange(); 2645 2646 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2647 // Can't check initialization for a member of dependent type or when 2648 // any of the arguments are type-dependent expressions. 2649 DiscardCleanupsInEvaluationContext(); 2650 } else { 2651 bool InitList = false; 2652 if (isa<InitListExpr>(Init)) { 2653 InitList = true; 2654 Args = Init; 2655 } 2656 2657 // Initialize the member. 2658 InitializedEntity MemberEntity = 2659 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2660 : InitializedEntity::InitializeMember(IndirectMember, 0); 2661 InitializationKind Kind = 2662 InitList ? InitializationKind::CreateDirectList(IdLoc) 2663 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2664 InitRange.getEnd()); 2665 2666 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 2667 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0); 2668 if (MemberInit.isInvalid()) 2669 return true; 2670 2671 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 2672 2673 // C++11 [class.base.init]p7: 2674 // The initialization of each base and member constitutes a 2675 // full-expression. 2676 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2677 if (MemberInit.isInvalid()) 2678 return true; 2679 2680 Init = MemberInit.get(); 2681 } 2682 2683 if (DirectMember) { 2684 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2685 InitRange.getBegin(), Init, 2686 InitRange.getEnd()); 2687 } else { 2688 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2689 InitRange.getBegin(), Init, 2690 InitRange.getEnd()); 2691 } 2692 } 2693 2694 MemInitResult 2695 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2696 CXXRecordDecl *ClassDecl) { 2697 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2698 if (!LangOpts.CPlusPlus11) 2699 return Diag(NameLoc, diag::err_delegating_ctor) 2700 << TInfo->getTypeLoc().getLocalSourceRange(); 2701 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2702 2703 bool InitList = true; 2704 MultiExprArg Args = Init; 2705 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2706 InitList = false; 2707 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2708 } 2709 2710 SourceRange InitRange = Init->getSourceRange(); 2711 // Initialize the object. 2712 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2713 QualType(ClassDecl->getTypeForDecl(), 0)); 2714 InitializationKind Kind = 2715 InitList ? InitializationKind::CreateDirectList(NameLoc) 2716 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2717 InitRange.getEnd()); 2718 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 2719 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2720 Args, 0); 2721 if (DelegationInit.isInvalid()) 2722 return true; 2723 2724 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2725 "Delegating constructor with no target?"); 2726 2727 // C++11 [class.base.init]p7: 2728 // The initialization of each base and member constitutes a 2729 // full-expression. 2730 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2731 InitRange.getBegin()); 2732 if (DelegationInit.isInvalid()) 2733 return true; 2734 2735 // If we are in a dependent context, template instantiation will 2736 // perform this type-checking again. Just save the arguments that we 2737 // received in a ParenListExpr. 2738 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2739 // of the information that we have about the base 2740 // initializer. However, deconstructing the ASTs is a dicey process, 2741 // and this approach is far more likely to get the corner cases right. 2742 if (CurContext->isDependentContext()) 2743 DelegationInit = Owned(Init); 2744 2745 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2746 DelegationInit.takeAs<Expr>(), 2747 InitRange.getEnd()); 2748 } 2749 2750 MemInitResult 2751 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2752 Expr *Init, CXXRecordDecl *ClassDecl, 2753 SourceLocation EllipsisLoc) { 2754 SourceLocation BaseLoc 2755 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2756 2757 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2758 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2759 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2760 2761 // C++ [class.base.init]p2: 2762 // [...] Unless the mem-initializer-id names a nonstatic data 2763 // member of the constructor's class or a direct or virtual base 2764 // of that class, the mem-initializer is ill-formed. A 2765 // mem-initializer-list can initialize a base class using any 2766 // name that denotes that base class type. 2767 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2768 2769 SourceRange InitRange = Init->getSourceRange(); 2770 if (EllipsisLoc.isValid()) { 2771 // This is a pack expansion. 2772 if (!BaseType->containsUnexpandedParameterPack()) { 2773 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2774 << SourceRange(BaseLoc, InitRange.getEnd()); 2775 2776 EllipsisLoc = SourceLocation(); 2777 } 2778 } else { 2779 // Check for any unexpanded parameter packs. 2780 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2781 return true; 2782 2783 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2784 return true; 2785 } 2786 2787 // Check for direct and virtual base classes. 2788 const CXXBaseSpecifier *DirectBaseSpec = 0; 2789 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2790 if (!Dependent) { 2791 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2792 BaseType)) 2793 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2794 2795 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2796 VirtualBaseSpec); 2797 2798 // C++ [base.class.init]p2: 2799 // Unless the mem-initializer-id names a nonstatic data member of the 2800 // constructor's class or a direct or virtual base of that class, the 2801 // mem-initializer is ill-formed. 2802 if (!DirectBaseSpec && !VirtualBaseSpec) { 2803 // If the class has any dependent bases, then it's possible that 2804 // one of those types will resolve to the same type as 2805 // BaseType. Therefore, just treat this as a dependent base 2806 // class initialization. FIXME: Should we try to check the 2807 // initialization anyway? It seems odd. 2808 if (ClassDecl->hasAnyDependentBases()) 2809 Dependent = true; 2810 else 2811 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2812 << BaseType << Context.getTypeDeclType(ClassDecl) 2813 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2814 } 2815 } 2816 2817 if (Dependent) { 2818 DiscardCleanupsInEvaluationContext(); 2819 2820 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2821 /*IsVirtual=*/false, 2822 InitRange.getBegin(), Init, 2823 InitRange.getEnd(), EllipsisLoc); 2824 } 2825 2826 // C++ [base.class.init]p2: 2827 // If a mem-initializer-id is ambiguous because it designates both 2828 // a direct non-virtual base class and an inherited virtual base 2829 // class, the mem-initializer is ill-formed. 2830 if (DirectBaseSpec && VirtualBaseSpec) 2831 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2832 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2833 2834 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 2835 if (!BaseSpec) 2836 BaseSpec = VirtualBaseSpec; 2837 2838 // Initialize the base. 2839 bool InitList = true; 2840 MultiExprArg Args = Init; 2841 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2842 InitList = false; 2843 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2844 } 2845 2846 InitializedEntity BaseEntity = 2847 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2848 InitializationKind Kind = 2849 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2850 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2851 InitRange.getEnd()); 2852 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 2853 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0); 2854 if (BaseInit.isInvalid()) 2855 return true; 2856 2857 // C++11 [class.base.init]p7: 2858 // The initialization of each base and member constitutes a 2859 // full-expression. 2860 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 2861 if (BaseInit.isInvalid()) 2862 return true; 2863 2864 // If we are in a dependent context, template instantiation will 2865 // perform this type-checking again. Just save the arguments that we 2866 // received in a ParenListExpr. 2867 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2868 // of the information that we have about the base 2869 // initializer. However, deconstructing the ASTs is a dicey process, 2870 // and this approach is far more likely to get the corner cases right. 2871 if (CurContext->isDependentContext()) 2872 BaseInit = Owned(Init); 2873 2874 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2875 BaseSpec->isVirtual(), 2876 InitRange.getBegin(), 2877 BaseInit.takeAs<Expr>(), 2878 InitRange.getEnd(), EllipsisLoc); 2879 } 2880 2881 // Create a static_cast\<T&&>(expr). 2882 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 2883 if (T.isNull()) T = E->getType(); 2884 QualType TargetType = SemaRef.BuildReferenceType( 2885 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 2886 SourceLocation ExprLoc = E->getLocStart(); 2887 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2888 TargetType, ExprLoc); 2889 2890 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2891 SourceRange(ExprLoc, ExprLoc), 2892 E->getSourceRange()).take(); 2893 } 2894 2895 /// ImplicitInitializerKind - How an implicit base or member initializer should 2896 /// initialize its base or member. 2897 enum ImplicitInitializerKind { 2898 IIK_Default, 2899 IIK_Copy, 2900 IIK_Move, 2901 IIK_Inherit 2902 }; 2903 2904 static bool 2905 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2906 ImplicitInitializerKind ImplicitInitKind, 2907 CXXBaseSpecifier *BaseSpec, 2908 bool IsInheritedVirtualBase, 2909 CXXCtorInitializer *&CXXBaseInit) { 2910 InitializedEntity InitEntity 2911 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2912 IsInheritedVirtualBase); 2913 2914 ExprResult BaseInit; 2915 2916 switch (ImplicitInitKind) { 2917 case IIK_Inherit: { 2918 const CXXRecordDecl *Inherited = 2919 Constructor->getInheritedConstructor()->getParent(); 2920 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 2921 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 2922 // C++11 [class.inhctor]p8: 2923 // Each expression in the expression-list is of the form 2924 // static_cast<T&&>(p), where p is the name of the corresponding 2925 // constructor parameter and T is the declared type of p. 2926 SmallVector<Expr*, 16> Args; 2927 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 2928 ParmVarDecl *PD = Constructor->getParamDecl(I); 2929 ExprResult ArgExpr = 2930 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 2931 VK_LValue, SourceLocation()); 2932 if (ArgExpr.isInvalid()) 2933 return true; 2934 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType())); 2935 } 2936 2937 InitializationKind InitKind = InitializationKind::CreateDirect( 2938 Constructor->getLocation(), SourceLocation(), SourceLocation()); 2939 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 2940 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 2941 break; 2942 } 2943 } 2944 // Fall through. 2945 case IIK_Default: { 2946 InitializationKind InitKind 2947 = InitializationKind::CreateDefault(Constructor->getLocation()); 2948 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 2949 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 2950 break; 2951 } 2952 2953 case IIK_Move: 2954 case IIK_Copy: { 2955 bool Moving = ImplicitInitKind == IIK_Move; 2956 ParmVarDecl *Param = Constructor->getParamDecl(0); 2957 QualType ParamType = Param->getType().getNonReferenceType(); 2958 2959 Expr *CopyCtorArg = 2960 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 2961 SourceLocation(), Param, false, 2962 Constructor->getLocation(), ParamType, 2963 VK_LValue, 0); 2964 2965 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 2966 2967 // Cast to the base class to avoid ambiguities. 2968 QualType ArgTy = 2969 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 2970 ParamType.getQualifiers()); 2971 2972 if (Moving) { 2973 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 2974 } 2975 2976 CXXCastPath BasePath; 2977 BasePath.push_back(BaseSpec); 2978 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 2979 CK_UncheckedDerivedToBase, 2980 Moving ? VK_XValue : VK_LValue, 2981 &BasePath).take(); 2982 2983 InitializationKind InitKind 2984 = InitializationKind::CreateDirect(Constructor->getLocation(), 2985 SourceLocation(), SourceLocation()); 2986 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 2987 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 2988 break; 2989 } 2990 } 2991 2992 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 2993 if (BaseInit.isInvalid()) 2994 return true; 2995 2996 CXXBaseInit = 2997 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 2998 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 2999 SourceLocation()), 3000 BaseSpec->isVirtual(), 3001 SourceLocation(), 3002 BaseInit.takeAs<Expr>(), 3003 SourceLocation(), 3004 SourceLocation()); 3005 3006 return false; 3007 } 3008 3009 static bool RefersToRValueRef(Expr *MemRef) { 3010 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3011 return Referenced->getType()->isRValueReferenceType(); 3012 } 3013 3014 static bool 3015 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3016 ImplicitInitializerKind ImplicitInitKind, 3017 FieldDecl *Field, IndirectFieldDecl *Indirect, 3018 CXXCtorInitializer *&CXXMemberInit) { 3019 if (Field->isInvalidDecl()) 3020 return true; 3021 3022 SourceLocation Loc = Constructor->getLocation(); 3023 3024 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3025 bool Moving = ImplicitInitKind == IIK_Move; 3026 ParmVarDecl *Param = Constructor->getParamDecl(0); 3027 QualType ParamType = Param->getType().getNonReferenceType(); 3028 3029 // Suppress copying zero-width bitfields. 3030 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3031 return false; 3032 3033 Expr *MemberExprBase = 3034 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3035 SourceLocation(), Param, false, 3036 Loc, ParamType, VK_LValue, 0); 3037 3038 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3039 3040 if (Moving) { 3041 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3042 } 3043 3044 // Build a reference to this field within the parameter. 3045 CXXScopeSpec SS; 3046 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3047 Sema::LookupMemberName); 3048 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3049 : cast<ValueDecl>(Field), AS_public); 3050 MemberLookup.resolveKind(); 3051 ExprResult CtorArg 3052 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3053 ParamType, Loc, 3054 /*IsArrow=*/false, 3055 SS, 3056 /*TemplateKWLoc=*/SourceLocation(), 3057 /*FirstQualifierInScope=*/0, 3058 MemberLookup, 3059 /*TemplateArgs=*/0); 3060 if (CtorArg.isInvalid()) 3061 return true; 3062 3063 // C++11 [class.copy]p15: 3064 // - if a member m has rvalue reference type T&&, it is direct-initialized 3065 // with static_cast<T&&>(x.m); 3066 if (RefersToRValueRef(CtorArg.get())) { 3067 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3068 } 3069 3070 // When the field we are copying is an array, create index variables for 3071 // each dimension of the array. We use these index variables to subscript 3072 // the source array, and other clients (e.g., CodeGen) will perform the 3073 // necessary iteration with these index variables. 3074 SmallVector<VarDecl *, 4> IndexVariables; 3075 QualType BaseType = Field->getType(); 3076 QualType SizeType = SemaRef.Context.getSizeType(); 3077 bool InitializingArray = false; 3078 while (const ConstantArrayType *Array 3079 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3080 InitializingArray = true; 3081 // Create the iteration variable for this array index. 3082 IdentifierInfo *IterationVarName = 0; 3083 { 3084 SmallString<8> Str; 3085 llvm::raw_svector_ostream OS(Str); 3086 OS << "__i" << IndexVariables.size(); 3087 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3088 } 3089 VarDecl *IterationVar 3090 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3091 IterationVarName, SizeType, 3092 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3093 SC_None); 3094 IndexVariables.push_back(IterationVar); 3095 3096 // Create a reference to the iteration variable. 3097 ExprResult IterationVarRef 3098 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3099 assert(!IterationVarRef.isInvalid() && 3100 "Reference to invented variable cannot fail!"); 3101 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 3102 assert(!IterationVarRef.isInvalid() && 3103 "Conversion of invented variable cannot fail!"); 3104 3105 // Subscript the array with this iteration variable. 3106 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 3107 IterationVarRef.take(), 3108 Loc); 3109 if (CtorArg.isInvalid()) 3110 return true; 3111 3112 BaseType = Array->getElementType(); 3113 } 3114 3115 // The array subscript expression is an lvalue, which is wrong for moving. 3116 if (Moving && InitializingArray) 3117 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3118 3119 // Construct the entity that we will be initializing. For an array, this 3120 // will be first element in the array, which may require several levels 3121 // of array-subscript entities. 3122 SmallVector<InitializedEntity, 4> Entities; 3123 Entities.reserve(1 + IndexVariables.size()); 3124 if (Indirect) 3125 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3126 else 3127 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3128 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3129 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3130 0, 3131 Entities.back())); 3132 3133 // Direct-initialize to use the copy constructor. 3134 InitializationKind InitKind = 3135 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3136 3137 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 3138 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3139 3140 ExprResult MemberInit 3141 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3142 MultiExprArg(&CtorArgE, 1)); 3143 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3144 if (MemberInit.isInvalid()) 3145 return true; 3146 3147 if (Indirect) { 3148 assert(IndexVariables.size() == 0 && 3149 "Indirect field improperly initialized"); 3150 CXXMemberInit 3151 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3152 Loc, Loc, 3153 MemberInit.takeAs<Expr>(), 3154 Loc); 3155 } else 3156 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3157 Loc, MemberInit.takeAs<Expr>(), 3158 Loc, 3159 IndexVariables.data(), 3160 IndexVariables.size()); 3161 return false; 3162 } 3163 3164 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3165 "Unhandled implicit init kind!"); 3166 3167 QualType FieldBaseElementType = 3168 SemaRef.Context.getBaseElementType(Field->getType()); 3169 3170 if (FieldBaseElementType->isRecordType()) { 3171 InitializedEntity InitEntity 3172 = Indirect? InitializedEntity::InitializeMember(Indirect) 3173 : InitializedEntity::InitializeMember(Field); 3174 InitializationKind InitKind = 3175 InitializationKind::CreateDefault(Loc); 3176 3177 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3178 ExprResult MemberInit = 3179 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3180 3181 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3182 if (MemberInit.isInvalid()) 3183 return true; 3184 3185 if (Indirect) 3186 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3187 Indirect, Loc, 3188 Loc, 3189 MemberInit.get(), 3190 Loc); 3191 else 3192 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3193 Field, Loc, Loc, 3194 MemberInit.get(), 3195 Loc); 3196 return false; 3197 } 3198 3199 if (!Field->getParent()->isUnion()) { 3200 if (FieldBaseElementType->isReferenceType()) { 3201 SemaRef.Diag(Constructor->getLocation(), 3202 diag::err_uninitialized_member_in_ctor) 3203 << (int)Constructor->isImplicit() 3204 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3205 << 0 << Field->getDeclName(); 3206 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3207 return true; 3208 } 3209 3210 if (FieldBaseElementType.isConstQualified()) { 3211 SemaRef.Diag(Constructor->getLocation(), 3212 diag::err_uninitialized_member_in_ctor) 3213 << (int)Constructor->isImplicit() 3214 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3215 << 1 << Field->getDeclName(); 3216 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3217 return true; 3218 } 3219 } 3220 3221 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3222 FieldBaseElementType->isObjCRetainableType() && 3223 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3224 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3225 // ARC: 3226 // Default-initialize Objective-C pointers to NULL. 3227 CXXMemberInit 3228 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3229 Loc, Loc, 3230 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3231 Loc); 3232 return false; 3233 } 3234 3235 // Nothing to initialize. 3236 CXXMemberInit = 0; 3237 return false; 3238 } 3239 3240 namespace { 3241 struct BaseAndFieldInfo { 3242 Sema &S; 3243 CXXConstructorDecl *Ctor; 3244 bool AnyErrorsInInits; 3245 ImplicitInitializerKind IIK; 3246 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3247 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3248 3249 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3250 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3251 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3252 if (Generated && Ctor->isCopyConstructor()) 3253 IIK = IIK_Copy; 3254 else if (Generated && Ctor->isMoveConstructor()) 3255 IIK = IIK_Move; 3256 else if (Ctor->getInheritedConstructor()) 3257 IIK = IIK_Inherit; 3258 else 3259 IIK = IIK_Default; 3260 } 3261 3262 bool isImplicitCopyOrMove() const { 3263 switch (IIK) { 3264 case IIK_Copy: 3265 case IIK_Move: 3266 return true; 3267 3268 case IIK_Default: 3269 case IIK_Inherit: 3270 return false; 3271 } 3272 3273 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3274 } 3275 3276 bool addFieldInitializer(CXXCtorInitializer *Init) { 3277 AllToInit.push_back(Init); 3278 3279 // Check whether this initializer makes the field "used". 3280 if (Init->getInit()->HasSideEffects(S.Context)) 3281 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3282 3283 return false; 3284 } 3285 }; 3286 } 3287 3288 /// \brief Determine whether the given indirect field declaration is somewhere 3289 /// within an anonymous union. 3290 static bool isWithinAnonymousUnion(IndirectFieldDecl *F) { 3291 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(), 3292 CEnd = F->chain_end(); 3293 C != CEnd; ++C) 3294 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext())) 3295 if (Record->isUnion()) 3296 return true; 3297 3298 return false; 3299 } 3300 3301 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3302 /// array type. 3303 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3304 if (T->isIncompleteArrayType()) 3305 return true; 3306 3307 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3308 if (!ArrayT->getSize()) 3309 return true; 3310 3311 T = ArrayT->getElementType(); 3312 } 3313 3314 return false; 3315 } 3316 3317 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3318 FieldDecl *Field, 3319 IndirectFieldDecl *Indirect = 0) { 3320 if (Field->isInvalidDecl()) 3321 return false; 3322 3323 // Overwhelmingly common case: we have a direct initializer for this field. 3324 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 3325 return Info.addFieldInitializer(Init); 3326 3327 // C++11 [class.base.init]p8: if the entity is a non-static data member that 3328 // has a brace-or-equal-initializer, the entity is initialized as specified 3329 // in [dcl.init]. 3330 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3331 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3332 Info.Ctor->getLocation(), Field); 3333 CXXCtorInitializer *Init; 3334 if (Indirect) 3335 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3336 SourceLocation(), 3337 SourceLocation(), DIE, 3338 SourceLocation()); 3339 else 3340 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3341 SourceLocation(), 3342 SourceLocation(), DIE, 3343 SourceLocation()); 3344 return Info.addFieldInitializer(Init); 3345 } 3346 3347 // Don't build an implicit initializer for union members if none was 3348 // explicitly specified. 3349 if (Field->getParent()->isUnion() || 3350 (Indirect && isWithinAnonymousUnion(Indirect))) 3351 return false; 3352 3353 // Don't initialize incomplete or zero-length arrays. 3354 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3355 return false; 3356 3357 // Don't try to build an implicit initializer if there were semantic 3358 // errors in any of the initializers (and therefore we might be 3359 // missing some that the user actually wrote). 3360 if (Info.AnyErrorsInInits) 3361 return false; 3362 3363 CXXCtorInitializer *Init = 0; 3364 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3365 Indirect, Init)) 3366 return true; 3367 3368 if (!Init) 3369 return false; 3370 3371 return Info.addFieldInitializer(Init); 3372 } 3373 3374 bool 3375 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3376 CXXCtorInitializer *Initializer) { 3377 assert(Initializer->isDelegatingInitializer()); 3378 Constructor->setNumCtorInitializers(1); 3379 CXXCtorInitializer **initializer = 3380 new (Context) CXXCtorInitializer*[1]; 3381 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3382 Constructor->setCtorInitializers(initializer); 3383 3384 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3385 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3386 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3387 } 3388 3389 DelegatingCtorDecls.push_back(Constructor); 3390 3391 return false; 3392 } 3393 3394 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3395 ArrayRef<CXXCtorInitializer *> Initializers) { 3396 if (Constructor->isDependentContext()) { 3397 // Just store the initializers as written, they will be checked during 3398 // instantiation. 3399 if (!Initializers.empty()) { 3400 Constructor->setNumCtorInitializers(Initializers.size()); 3401 CXXCtorInitializer **baseOrMemberInitializers = 3402 new (Context) CXXCtorInitializer*[Initializers.size()]; 3403 memcpy(baseOrMemberInitializers, Initializers.data(), 3404 Initializers.size() * sizeof(CXXCtorInitializer*)); 3405 Constructor->setCtorInitializers(baseOrMemberInitializers); 3406 } 3407 3408 // Let template instantiation know whether we had errors. 3409 if (AnyErrors) 3410 Constructor->setInvalidDecl(); 3411 3412 return false; 3413 } 3414 3415 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3416 3417 // We need to build the initializer AST according to order of construction 3418 // and not what user specified in the Initializers list. 3419 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3420 if (!ClassDecl) 3421 return true; 3422 3423 bool HadError = false; 3424 3425 for (unsigned i = 0; i < Initializers.size(); i++) { 3426 CXXCtorInitializer *Member = Initializers[i]; 3427 3428 if (Member->isBaseInitializer()) 3429 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3430 else 3431 Info.AllBaseFields[Member->getAnyMember()] = Member; 3432 } 3433 3434 // Keep track of the direct virtual bases. 3435 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3436 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 3437 E = ClassDecl->bases_end(); I != E; ++I) { 3438 if (I->isVirtual()) 3439 DirectVBases.insert(I); 3440 } 3441 3442 // Push virtual bases before others. 3443 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3444 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3445 3446 if (CXXCtorInitializer *Value 3447 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 3448 // [class.base.init]p7, per DR257: 3449 // A mem-initializer where the mem-initializer-id names a virtual base 3450 // class is ignored during execution of a constructor of any class that 3451 // is not the most derived class. 3452 if (ClassDecl->isAbstract()) { 3453 // FIXME: Provide a fixit to remove the base specifier. This requires 3454 // tracking the location of the associated comma for a base specifier. 3455 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3456 << VBase->getType() << ClassDecl; 3457 DiagnoseAbstractType(ClassDecl); 3458 } 3459 3460 Info.AllToInit.push_back(Value); 3461 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3462 // [class.base.init]p8, per DR257: 3463 // If a given [...] base class is not named by a mem-initializer-id 3464 // [...] and the entity is not a virtual base class of an abstract 3465 // class, then [...] the entity is default-initialized. 3466 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 3467 CXXCtorInitializer *CXXBaseInit; 3468 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3469 VBase, IsInheritedVirtualBase, 3470 CXXBaseInit)) { 3471 HadError = true; 3472 continue; 3473 } 3474 3475 Info.AllToInit.push_back(CXXBaseInit); 3476 } 3477 } 3478 3479 // Non-virtual bases. 3480 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3481 E = ClassDecl->bases_end(); Base != E; ++Base) { 3482 // Virtuals are in the virtual base list and already constructed. 3483 if (Base->isVirtual()) 3484 continue; 3485 3486 if (CXXCtorInitializer *Value 3487 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 3488 Info.AllToInit.push_back(Value); 3489 } else if (!AnyErrors) { 3490 CXXCtorInitializer *CXXBaseInit; 3491 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3492 Base, /*IsInheritedVirtualBase=*/false, 3493 CXXBaseInit)) { 3494 HadError = true; 3495 continue; 3496 } 3497 3498 Info.AllToInit.push_back(CXXBaseInit); 3499 } 3500 } 3501 3502 // Fields. 3503 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(), 3504 MemEnd = ClassDecl->decls_end(); 3505 Mem != MemEnd; ++Mem) { 3506 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) { 3507 // C++ [class.bit]p2: 3508 // A declaration for a bit-field that omits the identifier declares an 3509 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3510 // initialized. 3511 if (F->isUnnamedBitfield()) 3512 continue; 3513 3514 // If we're not generating the implicit copy/move constructor, then we'll 3515 // handle anonymous struct/union fields based on their individual 3516 // indirect fields. 3517 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3518 continue; 3519 3520 if (CollectFieldInitializer(*this, Info, F)) 3521 HadError = true; 3522 continue; 3523 } 3524 3525 // Beyond this point, we only consider default initialization. 3526 if (Info.isImplicitCopyOrMove()) 3527 continue; 3528 3529 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) { 3530 if (F->getType()->isIncompleteArrayType()) { 3531 assert(ClassDecl->hasFlexibleArrayMember() && 3532 "Incomplete array type is not valid"); 3533 continue; 3534 } 3535 3536 // Initialize each field of an anonymous struct individually. 3537 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3538 HadError = true; 3539 3540 continue; 3541 } 3542 } 3543 3544 unsigned NumInitializers = Info.AllToInit.size(); 3545 if (NumInitializers > 0) { 3546 Constructor->setNumCtorInitializers(NumInitializers); 3547 CXXCtorInitializer **baseOrMemberInitializers = 3548 new (Context) CXXCtorInitializer*[NumInitializers]; 3549 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3550 NumInitializers * sizeof(CXXCtorInitializer*)); 3551 Constructor->setCtorInitializers(baseOrMemberInitializers); 3552 3553 // Constructors implicitly reference the base and member 3554 // destructors. 3555 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3556 Constructor->getParent()); 3557 } 3558 3559 return HadError; 3560 } 3561 3562 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3563 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3564 const RecordDecl *RD = RT->getDecl(); 3565 if (RD->isAnonymousStructOrUnion()) { 3566 for (RecordDecl::field_iterator Field = RD->field_begin(), 3567 E = RD->field_end(); Field != E; ++Field) 3568 PopulateKeysForFields(*Field, IdealInits); 3569 return; 3570 } 3571 } 3572 IdealInits.push_back(Field); 3573 } 3574 3575 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3576 return Context.getCanonicalType(BaseType).getTypePtr(); 3577 } 3578 3579 static const void *GetKeyForMember(ASTContext &Context, 3580 CXXCtorInitializer *Member) { 3581 if (!Member->isAnyMemberInitializer()) 3582 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3583 3584 return Member->getAnyMember(); 3585 } 3586 3587 static void DiagnoseBaseOrMemInitializerOrder( 3588 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3589 ArrayRef<CXXCtorInitializer *> Inits) { 3590 if (Constructor->getDeclContext()->isDependentContext()) 3591 return; 3592 3593 // Don't check initializers order unless the warning is enabled at the 3594 // location of at least one initializer. 3595 bool ShouldCheckOrder = false; 3596 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3597 CXXCtorInitializer *Init = Inits[InitIndex]; 3598 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3599 Init->getSourceLocation()) 3600 != DiagnosticsEngine::Ignored) { 3601 ShouldCheckOrder = true; 3602 break; 3603 } 3604 } 3605 if (!ShouldCheckOrder) 3606 return; 3607 3608 // Build the list of bases and members in the order that they'll 3609 // actually be initialized. The explicit initializers should be in 3610 // this same order but may be missing things. 3611 SmallVector<const void*, 32> IdealInitKeys; 3612 3613 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3614 3615 // 1. Virtual bases. 3616 for (CXXRecordDecl::base_class_const_iterator VBase = 3617 ClassDecl->vbases_begin(), 3618 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 3619 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 3620 3621 // 2. Non-virtual bases. 3622 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 3623 E = ClassDecl->bases_end(); Base != E; ++Base) { 3624 if (Base->isVirtual()) 3625 continue; 3626 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 3627 } 3628 3629 // 3. Direct fields. 3630 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3631 E = ClassDecl->field_end(); Field != E; ++Field) { 3632 if (Field->isUnnamedBitfield()) 3633 continue; 3634 3635 PopulateKeysForFields(*Field, IdealInitKeys); 3636 } 3637 3638 unsigned NumIdealInits = IdealInitKeys.size(); 3639 unsigned IdealIndex = 0; 3640 3641 CXXCtorInitializer *PrevInit = 0; 3642 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3643 CXXCtorInitializer *Init = Inits[InitIndex]; 3644 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3645 3646 // Scan forward to try to find this initializer in the idealized 3647 // initializers list. 3648 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3649 if (InitKey == IdealInitKeys[IdealIndex]) 3650 break; 3651 3652 // If we didn't find this initializer, it must be because we 3653 // scanned past it on a previous iteration. That can only 3654 // happen if we're out of order; emit a warning. 3655 if (IdealIndex == NumIdealInits && PrevInit) { 3656 Sema::SemaDiagnosticBuilder D = 3657 SemaRef.Diag(PrevInit->getSourceLocation(), 3658 diag::warn_initializer_out_of_order); 3659 3660 if (PrevInit->isAnyMemberInitializer()) 3661 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3662 else 3663 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3664 3665 if (Init->isAnyMemberInitializer()) 3666 D << 0 << Init->getAnyMember()->getDeclName(); 3667 else 3668 D << 1 << Init->getTypeSourceInfo()->getType(); 3669 3670 // Move back to the initializer's location in the ideal list. 3671 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3672 if (InitKey == IdealInitKeys[IdealIndex]) 3673 break; 3674 3675 assert(IdealIndex != NumIdealInits && 3676 "initializer not found in initializer list"); 3677 } 3678 3679 PrevInit = Init; 3680 } 3681 } 3682 3683 namespace { 3684 bool CheckRedundantInit(Sema &S, 3685 CXXCtorInitializer *Init, 3686 CXXCtorInitializer *&PrevInit) { 3687 if (!PrevInit) { 3688 PrevInit = Init; 3689 return false; 3690 } 3691 3692 if (FieldDecl *Field = Init->getAnyMember()) 3693 S.Diag(Init->getSourceLocation(), 3694 diag::err_multiple_mem_initialization) 3695 << Field->getDeclName() 3696 << Init->getSourceRange(); 3697 else { 3698 const Type *BaseClass = Init->getBaseClass(); 3699 assert(BaseClass && "neither field nor base"); 3700 S.Diag(Init->getSourceLocation(), 3701 diag::err_multiple_base_initialization) 3702 << QualType(BaseClass, 0) 3703 << Init->getSourceRange(); 3704 } 3705 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3706 << 0 << PrevInit->getSourceRange(); 3707 3708 return true; 3709 } 3710 3711 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3712 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3713 3714 bool CheckRedundantUnionInit(Sema &S, 3715 CXXCtorInitializer *Init, 3716 RedundantUnionMap &Unions) { 3717 FieldDecl *Field = Init->getAnyMember(); 3718 RecordDecl *Parent = Field->getParent(); 3719 NamedDecl *Child = Field; 3720 3721 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3722 if (Parent->isUnion()) { 3723 UnionEntry &En = Unions[Parent]; 3724 if (En.first && En.first != Child) { 3725 S.Diag(Init->getSourceLocation(), 3726 diag::err_multiple_mem_union_initialization) 3727 << Field->getDeclName() 3728 << Init->getSourceRange(); 3729 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3730 << 0 << En.second->getSourceRange(); 3731 return true; 3732 } 3733 if (!En.first) { 3734 En.first = Child; 3735 En.second = Init; 3736 } 3737 if (!Parent->isAnonymousStructOrUnion()) 3738 return false; 3739 } 3740 3741 Child = Parent; 3742 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3743 } 3744 3745 return false; 3746 } 3747 } 3748 3749 // Diagnose value-uses of fields to initialize themselves, e.g. 3750 // foo(foo) 3751 // where foo is not also a parameter to the constructor. 3752 // Also diagnose across field uninitialized use such as 3753 // x(y), y(x) 3754 // TODO: implement -Wuninitialized and fold this into that framework. 3755 static void DiagnoseUnitializedFields( 3756 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3757 3758 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, 3759 Constructor->getLocation()) 3760 == DiagnosticsEngine::Ignored) { 3761 return; 3762 } 3763 3764 const CXXRecordDecl *RD = Constructor->getParent(); 3765 3766 // Holds fields that are uninitialized. 3767 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3768 3769 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end(); 3770 I != E; ++I) { 3771 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) { 3772 UninitializedFields.insert(FD); 3773 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) { 3774 UninitializedFields.insert(IFD->getAnonField()); 3775 } 3776 } 3777 3778 // Fields already checked when processing the in class initializers. 3779 llvm::SmallPtrSet<ValueDecl*, 4> 3780 InClassUninitializedFields = UninitializedFields; 3781 3782 for (CXXConstructorDecl::init_const_iterator FieldInit = 3783 Constructor->init_begin(), 3784 FieldInitEnd = Constructor->init_end(); 3785 FieldInit != FieldInitEnd; ++FieldInit) { 3786 3787 FieldDecl *Field = (*FieldInit)->getAnyMember(); 3788 Expr *InitExpr = (*FieldInit)->getInit(); 3789 3790 if (!Field) { 3791 CheckInitExprContainsUninitializedFields( 3792 SemaRef, InitExpr, 0, UninitializedFields, 3793 false/*WarnOnSelfReference*/); 3794 continue; 3795 } 3796 3797 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3798 // This field is initialized with an in-class initailzer. Remove the 3799 // fields already checked to prevent duplicate warnings. 3800 llvm::SmallPtrSet<ValueDecl*, 4> DiffSet = UninitializedFields; 3801 for (llvm::SmallPtrSet<ValueDecl*, 4>::iterator 3802 I = InClassUninitializedFields.begin(), 3803 E = InClassUninitializedFields.end(); 3804 I != E; ++I) { 3805 DiffSet.erase(*I); 3806 } 3807 CheckInitExprContainsUninitializedFields( 3808 SemaRef, Default->getExpr(), Field, DiffSet, 3809 DiffSet.count(Field), Constructor); 3810 3811 // Update the unitialized field sets. 3812 CheckInitExprContainsUninitializedFields( 3813 SemaRef, Default->getExpr(), 0, UninitializedFields, 3814 false); 3815 CheckInitExprContainsUninitializedFields( 3816 SemaRef, Default->getExpr(), 0, InClassUninitializedFields, 3817 false); 3818 } else { 3819 CheckInitExprContainsUninitializedFields( 3820 SemaRef, InitExpr, Field, UninitializedFields, 3821 UninitializedFields.count(Field)); 3822 if (Expr* InClassInit = Field->getInClassInitializer()) { 3823 CheckInitExprContainsUninitializedFields( 3824 SemaRef, InClassInit, 0, InClassUninitializedFields, 3825 false); 3826 } 3827 } 3828 UninitializedFields.erase(Field); 3829 InClassUninitializedFields.erase(Field); 3830 } 3831 } 3832 3833 /// ActOnMemInitializers - Handle the member initializers for a constructor. 3834 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3835 SourceLocation ColonLoc, 3836 ArrayRef<CXXCtorInitializer*> MemInits, 3837 bool AnyErrors) { 3838 if (!ConstructorDecl) 3839 return; 3840 3841 AdjustDeclIfTemplate(ConstructorDecl); 3842 3843 CXXConstructorDecl *Constructor 3844 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3845 3846 if (!Constructor) { 3847 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3848 return; 3849 } 3850 3851 // Mapping for the duplicate initializers check. 3852 // For member initializers, this is keyed with a FieldDecl*. 3853 // For base initializers, this is keyed with a Type*. 3854 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 3855 3856 // Mapping for the inconsistent anonymous-union initializers check. 3857 RedundantUnionMap MemberUnions; 3858 3859 bool HadError = false; 3860 for (unsigned i = 0; i < MemInits.size(); i++) { 3861 CXXCtorInitializer *Init = MemInits[i]; 3862 3863 // Set the source order index. 3864 Init->setSourceOrder(i); 3865 3866 if (Init->isAnyMemberInitializer()) { 3867 FieldDecl *Field = Init->getAnyMember(); 3868 if (CheckRedundantInit(*this, Init, Members[Field]) || 3869 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3870 HadError = true; 3871 } else if (Init->isBaseInitializer()) { 3872 const void *Key = 3873 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3874 if (CheckRedundantInit(*this, Init, Members[Key])) 3875 HadError = true; 3876 } else { 3877 assert(Init->isDelegatingInitializer()); 3878 // This must be the only initializer 3879 if (MemInits.size() != 1) { 3880 Diag(Init->getSourceLocation(), 3881 diag::err_delegating_initializer_alone) 3882 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3883 // We will treat this as being the only initializer. 3884 } 3885 SetDelegatingInitializer(Constructor, MemInits[i]); 3886 // Return immediately as the initializer is set. 3887 return; 3888 } 3889 } 3890 3891 if (HadError) 3892 return; 3893 3894 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 3895 3896 SetCtorInitializers(Constructor, AnyErrors, MemInits); 3897 3898 DiagnoseUnitializedFields(*this, Constructor); 3899 } 3900 3901 void 3902 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3903 CXXRecordDecl *ClassDecl) { 3904 // Ignore dependent contexts. Also ignore unions, since their members never 3905 // have destructors implicitly called. 3906 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3907 return; 3908 3909 // FIXME: all the access-control diagnostics are positioned on the 3910 // field/base declaration. That's probably good; that said, the 3911 // user might reasonably want to know why the destructor is being 3912 // emitted, and we currently don't say. 3913 3914 // Non-static data members. 3915 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 3916 E = ClassDecl->field_end(); I != E; ++I) { 3917 FieldDecl *Field = *I; 3918 if (Field->isInvalidDecl()) 3919 continue; 3920 3921 // Don't destroy incomplete or zero-length arrays. 3922 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3923 continue; 3924 3925 QualType FieldType = Context.getBaseElementType(Field->getType()); 3926 3927 const RecordType* RT = FieldType->getAs<RecordType>(); 3928 if (!RT) 3929 continue; 3930 3931 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3932 if (FieldClassDecl->isInvalidDecl()) 3933 continue; 3934 if (FieldClassDecl->hasIrrelevantDestructor()) 3935 continue; 3936 // The destructor for an implicit anonymous union member is never invoked. 3937 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3938 continue; 3939 3940 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3941 assert(Dtor && "No dtor found for FieldClassDecl!"); 3942 CheckDestructorAccess(Field->getLocation(), Dtor, 3943 PDiag(diag::err_access_dtor_field) 3944 << Field->getDeclName() 3945 << FieldType); 3946 3947 MarkFunctionReferenced(Location, Dtor); 3948 DiagnoseUseOfDecl(Dtor, Location); 3949 } 3950 3951 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3952 3953 // Bases. 3954 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3955 E = ClassDecl->bases_end(); Base != E; ++Base) { 3956 // Bases are always records in a well-formed non-dependent class. 3957 const RecordType *RT = Base->getType()->getAs<RecordType>(); 3958 3959 // Remember direct virtual bases. 3960 if (Base->isVirtual()) 3961 DirectVirtualBases.insert(RT); 3962 3963 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3964 // If our base class is invalid, we probably can't get its dtor anyway. 3965 if (BaseClassDecl->isInvalidDecl()) 3966 continue; 3967 if (BaseClassDecl->hasIrrelevantDestructor()) 3968 continue; 3969 3970 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 3971 assert(Dtor && "No dtor found for BaseClassDecl!"); 3972 3973 // FIXME: caret should be on the start of the class name 3974 CheckDestructorAccess(Base->getLocStart(), Dtor, 3975 PDiag(diag::err_access_dtor_base) 3976 << Base->getType() 3977 << Base->getSourceRange(), 3978 Context.getTypeDeclType(ClassDecl)); 3979 3980 MarkFunctionReferenced(Location, Dtor); 3981 DiagnoseUseOfDecl(Dtor, Location); 3982 } 3983 3984 // Virtual bases. 3985 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 3986 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 3987 3988 // Bases are always records in a well-formed non-dependent class. 3989 const RecordType *RT = VBase->getType()->castAs<RecordType>(); 3990 3991 // Ignore direct virtual bases. 3992 if (DirectVirtualBases.count(RT)) 3993 continue; 3994 3995 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3996 // If our base class is invalid, we probably can't get its dtor anyway. 3997 if (BaseClassDecl->isInvalidDecl()) 3998 continue; 3999 if (BaseClassDecl->hasIrrelevantDestructor()) 4000 continue; 4001 4002 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4003 assert(Dtor && "No dtor found for BaseClassDecl!"); 4004 if (CheckDestructorAccess( 4005 ClassDecl->getLocation(), Dtor, 4006 PDiag(diag::err_access_dtor_vbase) 4007 << Context.getTypeDeclType(ClassDecl) << VBase->getType(), 4008 Context.getTypeDeclType(ClassDecl)) == 4009 AR_accessible) { 4010 CheckDerivedToBaseConversion( 4011 Context.getTypeDeclType(ClassDecl), VBase->getType(), 4012 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4013 SourceRange(), DeclarationName(), 0); 4014 } 4015 4016 MarkFunctionReferenced(Location, Dtor); 4017 DiagnoseUseOfDecl(Dtor, Location); 4018 } 4019 } 4020 4021 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4022 if (!CDtorDecl) 4023 return; 4024 4025 if (CXXConstructorDecl *Constructor 4026 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 4027 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4028 } 4029 4030 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4031 unsigned DiagID, AbstractDiagSelID SelID) { 4032 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4033 unsigned DiagID; 4034 AbstractDiagSelID SelID; 4035 4036 public: 4037 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4038 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4039 4040 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE { 4041 if (Suppressed) return; 4042 if (SelID == -1) 4043 S.Diag(Loc, DiagID) << T; 4044 else 4045 S.Diag(Loc, DiagID) << SelID << T; 4046 } 4047 } Diagnoser(DiagID, SelID); 4048 4049 return RequireNonAbstractType(Loc, T, Diagnoser); 4050 } 4051 4052 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4053 TypeDiagnoser &Diagnoser) { 4054 if (!getLangOpts().CPlusPlus) 4055 return false; 4056 4057 if (const ArrayType *AT = Context.getAsArrayType(T)) 4058 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4059 4060 if (const PointerType *PT = T->getAs<PointerType>()) { 4061 // Find the innermost pointer type. 4062 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4063 PT = T; 4064 4065 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4066 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4067 } 4068 4069 const RecordType *RT = T->getAs<RecordType>(); 4070 if (!RT) 4071 return false; 4072 4073 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4074 4075 // We can't answer whether something is abstract until it has a 4076 // definition. If it's currently being defined, we'll walk back 4077 // over all the declarations when we have a full definition. 4078 const CXXRecordDecl *Def = RD->getDefinition(); 4079 if (!Def || Def->isBeingDefined()) 4080 return false; 4081 4082 if (!RD->isAbstract()) 4083 return false; 4084 4085 Diagnoser.diagnose(*this, Loc, T); 4086 DiagnoseAbstractType(RD); 4087 4088 return true; 4089 } 4090 4091 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4092 // Check if we've already emitted the list of pure virtual functions 4093 // for this class. 4094 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4095 return; 4096 4097 // If the diagnostic is suppressed, don't emit the notes. We're only 4098 // going to emit them once, so try to attach them to a diagnostic we're 4099 // actually going to show. 4100 if (Diags.isLastDiagnosticIgnored()) 4101 return; 4102 4103 CXXFinalOverriderMap FinalOverriders; 4104 RD->getFinalOverriders(FinalOverriders); 4105 4106 // Keep a set of seen pure methods so we won't diagnose the same method 4107 // more than once. 4108 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4109 4110 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4111 MEnd = FinalOverriders.end(); 4112 M != MEnd; 4113 ++M) { 4114 for (OverridingMethods::iterator SO = M->second.begin(), 4115 SOEnd = M->second.end(); 4116 SO != SOEnd; ++SO) { 4117 // C++ [class.abstract]p4: 4118 // A class is abstract if it contains or inherits at least one 4119 // pure virtual function for which the final overrider is pure 4120 // virtual. 4121 4122 // 4123 if (SO->second.size() != 1) 4124 continue; 4125 4126 if (!SO->second.front().Method->isPure()) 4127 continue; 4128 4129 if (!SeenPureMethods.insert(SO->second.front().Method)) 4130 continue; 4131 4132 Diag(SO->second.front().Method->getLocation(), 4133 diag::note_pure_virtual_function) 4134 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4135 } 4136 } 4137 4138 if (!PureVirtualClassDiagSet) 4139 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4140 PureVirtualClassDiagSet->insert(RD); 4141 } 4142 4143 namespace { 4144 struct AbstractUsageInfo { 4145 Sema &S; 4146 CXXRecordDecl *Record; 4147 CanQualType AbstractType; 4148 bool Invalid; 4149 4150 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4151 : S(S), Record(Record), 4152 AbstractType(S.Context.getCanonicalType( 4153 S.Context.getTypeDeclType(Record))), 4154 Invalid(false) {} 4155 4156 void DiagnoseAbstractType() { 4157 if (Invalid) return; 4158 S.DiagnoseAbstractType(Record); 4159 Invalid = true; 4160 } 4161 4162 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4163 }; 4164 4165 struct CheckAbstractUsage { 4166 AbstractUsageInfo &Info; 4167 const NamedDecl *Ctx; 4168 4169 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4170 : Info(Info), Ctx(Ctx) {} 4171 4172 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4173 switch (TL.getTypeLocClass()) { 4174 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4175 #define TYPELOC(CLASS, PARENT) \ 4176 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4177 #include "clang/AST/TypeLocNodes.def" 4178 } 4179 } 4180 4181 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4182 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 4183 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4184 if (!TL.getArg(I)) 4185 continue; 4186 4187 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 4188 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4189 } 4190 } 4191 4192 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4193 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4194 } 4195 4196 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4197 // Visit the type parameters from a permissive context. 4198 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4199 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4200 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4201 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4202 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4203 // TODO: other template argument types? 4204 } 4205 } 4206 4207 // Visit pointee types from a permissive context. 4208 #define CheckPolymorphic(Type) \ 4209 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4210 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4211 } 4212 CheckPolymorphic(PointerTypeLoc) 4213 CheckPolymorphic(ReferenceTypeLoc) 4214 CheckPolymorphic(MemberPointerTypeLoc) 4215 CheckPolymorphic(BlockPointerTypeLoc) 4216 CheckPolymorphic(AtomicTypeLoc) 4217 4218 /// Handle all the types we haven't given a more specific 4219 /// implementation for above. 4220 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4221 // Every other kind of type that we haven't called out already 4222 // that has an inner type is either (1) sugar or (2) contains that 4223 // inner type in some way as a subobject. 4224 if (TypeLoc Next = TL.getNextTypeLoc()) 4225 return Visit(Next, Sel); 4226 4227 // If there's no inner type and we're in a permissive context, 4228 // don't diagnose. 4229 if (Sel == Sema::AbstractNone) return; 4230 4231 // Check whether the type matches the abstract type. 4232 QualType T = TL.getType(); 4233 if (T->isArrayType()) { 4234 Sel = Sema::AbstractArrayType; 4235 T = Info.S.Context.getBaseElementType(T); 4236 } 4237 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4238 if (CT != Info.AbstractType) return; 4239 4240 // It matched; do some magic. 4241 if (Sel == Sema::AbstractArrayType) { 4242 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4243 << T << TL.getSourceRange(); 4244 } else { 4245 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4246 << Sel << T << TL.getSourceRange(); 4247 } 4248 Info.DiagnoseAbstractType(); 4249 } 4250 }; 4251 4252 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4253 Sema::AbstractDiagSelID Sel) { 4254 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4255 } 4256 4257 } 4258 4259 /// Check for invalid uses of an abstract type in a method declaration. 4260 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4261 CXXMethodDecl *MD) { 4262 // No need to do the check on definitions, which require that 4263 // the return/param types be complete. 4264 if (MD->doesThisDeclarationHaveABody()) 4265 return; 4266 4267 // For safety's sake, just ignore it if we don't have type source 4268 // information. This should never happen for non-implicit methods, 4269 // but... 4270 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4271 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4272 } 4273 4274 /// Check for invalid uses of an abstract type within a class definition. 4275 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4276 CXXRecordDecl *RD) { 4277 for (CXXRecordDecl::decl_iterator 4278 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 4279 Decl *D = *I; 4280 if (D->isImplicit()) continue; 4281 4282 // Methods and method templates. 4283 if (isa<CXXMethodDecl>(D)) { 4284 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4285 } else if (isa<FunctionTemplateDecl>(D)) { 4286 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4287 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4288 4289 // Fields and static variables. 4290 } else if (isa<FieldDecl>(D)) { 4291 FieldDecl *FD = cast<FieldDecl>(D); 4292 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4293 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4294 } else if (isa<VarDecl>(D)) { 4295 VarDecl *VD = cast<VarDecl>(D); 4296 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4297 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4298 4299 // Nested classes and class templates. 4300 } else if (isa<CXXRecordDecl>(D)) { 4301 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4302 } else if (isa<ClassTemplateDecl>(D)) { 4303 CheckAbstractClassUsage(Info, 4304 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4305 } 4306 } 4307 } 4308 4309 /// \brief Perform semantic checks on a class definition that has been 4310 /// completing, introducing implicitly-declared members, checking for 4311 /// abstract types, etc. 4312 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4313 if (!Record) 4314 return; 4315 4316 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4317 AbstractUsageInfo Info(*this, Record); 4318 CheckAbstractClassUsage(Info, Record); 4319 } 4320 4321 // If this is not an aggregate type and has no user-declared constructor, 4322 // complain about any non-static data members of reference or const scalar 4323 // type, since they will never get initializers. 4324 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4325 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4326 !Record->isLambda()) { 4327 bool Complained = false; 4328 for (RecordDecl::field_iterator F = Record->field_begin(), 4329 FEnd = Record->field_end(); 4330 F != FEnd; ++F) { 4331 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4332 continue; 4333 4334 if (F->getType()->isReferenceType() || 4335 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4336 if (!Complained) { 4337 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4338 << Record->getTagKind() << Record; 4339 Complained = true; 4340 } 4341 4342 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4343 << F->getType()->isReferenceType() 4344 << F->getDeclName(); 4345 } 4346 } 4347 } 4348 4349 if (Record->isDynamicClass() && !Record->isDependentType()) 4350 DynamicClasses.push_back(Record); 4351 4352 if (Record->getIdentifier()) { 4353 // C++ [class.mem]p13: 4354 // If T is the name of a class, then each of the following shall have a 4355 // name different from T: 4356 // - every member of every anonymous union that is a member of class T. 4357 // 4358 // C++ [class.mem]p14: 4359 // In addition, if class T has a user-declared constructor (12.1), every 4360 // non-static data member of class T shall have a name different from T. 4361 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4362 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4363 ++I) { 4364 NamedDecl *D = *I; 4365 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4366 isa<IndirectFieldDecl>(D)) { 4367 Diag(D->getLocation(), diag::err_member_name_of_class) 4368 << D->getDeclName(); 4369 break; 4370 } 4371 } 4372 } 4373 4374 // Warn if the class has virtual methods but non-virtual public destructor. 4375 if (Record->isPolymorphic() && !Record->isDependentType()) { 4376 CXXDestructorDecl *dtor = Record->getDestructor(); 4377 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 4378 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4379 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4380 } 4381 4382 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) { 4383 Diag(Record->getLocation(), diag::warn_abstract_final_class); 4384 DiagnoseAbstractType(Record); 4385 } 4386 4387 if (!Record->isDependentType()) { 4388 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4389 MEnd = Record->method_end(); 4390 M != MEnd; ++M) { 4391 // See if a method overloads virtual methods in a base 4392 // class without overriding any. 4393 if (!M->isStatic()) 4394 DiagnoseHiddenVirtualMethods(*M); 4395 4396 // Check whether the explicitly-defaulted special members are valid. 4397 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4398 CheckExplicitlyDefaultedSpecialMember(*M); 4399 4400 // For an explicitly defaulted or deleted special member, we defer 4401 // determining triviality until the class is complete. That time is now! 4402 if (!M->isImplicit() && !M->isUserProvided()) { 4403 CXXSpecialMember CSM = getSpecialMember(*M); 4404 if (CSM != CXXInvalid) { 4405 M->setTrivial(SpecialMemberIsTrivial(*M, CSM)); 4406 4407 // Inform the class that we've finished declaring this member. 4408 Record->finishedDefaultedOrDeletedMember(*M); 4409 } 4410 } 4411 } 4412 } 4413 4414 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4415 // function that is not a constructor declares that member function to be 4416 // const. [...] The class of which that function is a member shall be 4417 // a literal type. 4418 // 4419 // If the class has virtual bases, any constexpr members will already have 4420 // been diagnosed by the checks performed on the member declaration, so 4421 // suppress this (less useful) diagnostic. 4422 // 4423 // We delay this until we know whether an explicitly-defaulted (or deleted) 4424 // destructor for the class is trivial. 4425 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4426 !Record->isLiteral() && !Record->getNumVBases()) { 4427 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 4428 MEnd = Record->method_end(); 4429 M != MEnd; ++M) { 4430 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) { 4431 switch (Record->getTemplateSpecializationKind()) { 4432 case TSK_ImplicitInstantiation: 4433 case TSK_ExplicitInstantiationDeclaration: 4434 case TSK_ExplicitInstantiationDefinition: 4435 // If a template instantiates to a non-literal type, but its members 4436 // instantiate to constexpr functions, the template is technically 4437 // ill-formed, but we allow it for sanity. 4438 continue; 4439 4440 case TSK_Undeclared: 4441 case TSK_ExplicitSpecialization: 4442 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4443 diag::err_constexpr_method_non_literal); 4444 break; 4445 } 4446 4447 // Only produce one error per class. 4448 break; 4449 } 4450 } 4451 } 4452 4453 // Declare inheriting constructors. We do this eagerly here because: 4454 // - The standard requires an eager diagnostic for conflicting inheriting 4455 // constructors from different classes. 4456 // - The lazy declaration of the other implicit constructors is so as to not 4457 // waste space and performance on classes that are not meant to be 4458 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4459 // have inheriting constructors. 4460 DeclareInheritingConstructors(Record); 4461 } 4462 4463 /// Is the special member function which would be selected to perform the 4464 /// specified operation on the specified class type a constexpr constructor? 4465 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4466 Sema::CXXSpecialMember CSM, 4467 bool ConstArg) { 4468 Sema::SpecialMemberOverloadResult *SMOR = 4469 S.LookupSpecialMember(ClassDecl, CSM, ConstArg, 4470 false, false, false, false); 4471 if (!SMOR || !SMOR->getMethod()) 4472 // A constructor we wouldn't select can't be "involved in initializing" 4473 // anything. 4474 return true; 4475 return SMOR->getMethod()->isConstexpr(); 4476 } 4477 4478 /// Determine whether the specified special member function would be constexpr 4479 /// if it were implicitly defined. 4480 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4481 Sema::CXXSpecialMember CSM, 4482 bool ConstArg) { 4483 if (!S.getLangOpts().CPlusPlus11) 4484 return false; 4485 4486 // C++11 [dcl.constexpr]p4: 4487 // In the definition of a constexpr constructor [...] 4488 bool Ctor = true; 4489 switch (CSM) { 4490 case Sema::CXXDefaultConstructor: 4491 // Since default constructor lookup is essentially trivial (and cannot 4492 // involve, for instance, template instantiation), we compute whether a 4493 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4494 // 4495 // This is important for performance; we need to know whether the default 4496 // constructor is constexpr to determine whether the type is a literal type. 4497 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4498 4499 case Sema::CXXCopyConstructor: 4500 case Sema::CXXMoveConstructor: 4501 // For copy or move constructors, we need to perform overload resolution. 4502 break; 4503 4504 case Sema::CXXCopyAssignment: 4505 case Sema::CXXMoveAssignment: 4506 if (!S.getLangOpts().CPlusPlus1y) 4507 return false; 4508 // In C++1y, we need to perform overload resolution. 4509 Ctor = false; 4510 break; 4511 4512 case Sema::CXXDestructor: 4513 case Sema::CXXInvalid: 4514 return false; 4515 } 4516 4517 // -- if the class is a non-empty union, or for each non-empty anonymous 4518 // union member of a non-union class, exactly one non-static data member 4519 // shall be initialized; [DR1359] 4520 // 4521 // If we squint, this is guaranteed, since exactly one non-static data member 4522 // will be initialized (if the constructor isn't deleted), we just don't know 4523 // which one. 4524 if (Ctor && ClassDecl->isUnion()) 4525 return true; 4526 4527 // -- the class shall not have any virtual base classes; 4528 if (Ctor && ClassDecl->getNumVBases()) 4529 return false; 4530 4531 // C++1y [class.copy]p26: 4532 // -- [the class] is a literal type, and 4533 if (!Ctor && !ClassDecl->isLiteral()) 4534 return false; 4535 4536 // -- every constructor involved in initializing [...] base class 4537 // sub-objects shall be a constexpr constructor; 4538 // -- the assignment operator selected to copy/move each direct base 4539 // class is a constexpr function, and 4540 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4541 BEnd = ClassDecl->bases_end(); 4542 B != BEnd; ++B) { 4543 const RecordType *BaseType = B->getType()->getAs<RecordType>(); 4544 if (!BaseType) continue; 4545 4546 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4547 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg)) 4548 return false; 4549 } 4550 4551 // -- every constructor involved in initializing non-static data members 4552 // [...] shall be a constexpr constructor; 4553 // -- every non-static data member and base class sub-object shall be 4554 // initialized 4555 // -- for each non-stastic data member of X that is of class type (or array 4556 // thereof), the assignment operator selected to copy/move that member is 4557 // a constexpr function 4558 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4559 FEnd = ClassDecl->field_end(); 4560 F != FEnd; ++F) { 4561 if (F->isInvalidDecl()) 4562 continue; 4563 if (const RecordType *RecordTy = 4564 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4565 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4566 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg)) 4567 return false; 4568 } 4569 } 4570 4571 // All OK, it's constexpr! 4572 return true; 4573 } 4574 4575 static Sema::ImplicitExceptionSpecification 4576 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4577 switch (S.getSpecialMember(MD)) { 4578 case Sema::CXXDefaultConstructor: 4579 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4580 case Sema::CXXCopyConstructor: 4581 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4582 case Sema::CXXCopyAssignment: 4583 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4584 case Sema::CXXMoveConstructor: 4585 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4586 case Sema::CXXMoveAssignment: 4587 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4588 case Sema::CXXDestructor: 4589 return S.ComputeDefaultedDtorExceptionSpec(MD); 4590 case Sema::CXXInvalid: 4591 break; 4592 } 4593 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4594 "only special members have implicit exception specs"); 4595 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4596 } 4597 4598 static void 4599 updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT, 4600 const Sema::ImplicitExceptionSpecification &ExceptSpec) { 4601 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 4602 ExceptSpec.getEPI(EPI); 4603 FD->setType(S.Context.getFunctionType(FPT->getResultType(), 4604 FPT->getArgTypes(), EPI)); 4605 } 4606 4607 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 4608 CXXMethodDecl *MD) { 4609 FunctionProtoType::ExtProtoInfo EPI; 4610 4611 // Build an exception specification pointing back at this member. 4612 EPI.ExceptionSpecType = EST_Unevaluated; 4613 EPI.ExceptionSpecDecl = MD; 4614 4615 // Set the calling convention to the default for C++ instance methods. 4616 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 4617 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4618 /*IsCXXMethod=*/true)); 4619 return EPI; 4620 } 4621 4622 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4623 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4624 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4625 return; 4626 4627 // Evaluate the exception specification. 4628 ImplicitExceptionSpecification ExceptSpec = 4629 computeImplicitExceptionSpec(*this, Loc, MD); 4630 4631 // Update the type of the special member to use it. 4632 updateExceptionSpec(*this, MD, FPT, ExceptSpec); 4633 4634 // A user-provided destructor can be defined outside the class. When that 4635 // happens, be sure to update the exception specification on both 4636 // declarations. 4637 const FunctionProtoType *CanonicalFPT = 4638 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4639 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4640 updateExceptionSpec(*this, MD->getCanonicalDecl(), 4641 CanonicalFPT, ExceptSpec); 4642 } 4643 4644 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4645 CXXRecordDecl *RD = MD->getParent(); 4646 CXXSpecialMember CSM = getSpecialMember(MD); 4647 4648 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4649 "not an explicitly-defaulted special member"); 4650 4651 // Whether this was the first-declared instance of the constructor. 4652 // This affects whether we implicitly add an exception spec and constexpr. 4653 bool First = MD == MD->getCanonicalDecl(); 4654 4655 bool HadError = false; 4656 4657 // C++11 [dcl.fct.def.default]p1: 4658 // A function that is explicitly defaulted shall 4659 // -- be a special member function (checked elsewhere), 4660 // -- have the same type (except for ref-qualifiers, and except that a 4661 // copy operation can take a non-const reference) as an implicit 4662 // declaration, and 4663 // -- not have default arguments. 4664 unsigned ExpectedParams = 1; 4665 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4666 ExpectedParams = 0; 4667 if (MD->getNumParams() != ExpectedParams) { 4668 // This also checks for default arguments: a copy or move constructor with a 4669 // default argument is classified as a default constructor, and assignment 4670 // operations and destructors can't have default arguments. 4671 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4672 << CSM << MD->getSourceRange(); 4673 HadError = true; 4674 } else if (MD->isVariadic()) { 4675 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4676 << CSM << MD->getSourceRange(); 4677 HadError = true; 4678 } 4679 4680 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4681 4682 bool CanHaveConstParam = false; 4683 if (CSM == CXXCopyConstructor) 4684 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4685 else if (CSM == CXXCopyAssignment) 4686 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4687 4688 QualType ReturnType = Context.VoidTy; 4689 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4690 // Check for return type matching. 4691 ReturnType = Type->getResultType(); 4692 QualType ExpectedReturnType = 4693 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4694 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4695 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4696 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4697 HadError = true; 4698 } 4699 4700 // A defaulted special member cannot have cv-qualifiers. 4701 if (Type->getTypeQuals()) { 4702 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4703 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y; 4704 HadError = true; 4705 } 4706 } 4707 4708 // Check for parameter type matching. 4709 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType(); 4710 bool HasConstParam = false; 4711 if (ExpectedParams && ArgType->isReferenceType()) { 4712 // Argument must be reference to possibly-const T. 4713 QualType ReferentType = ArgType->getPointeeType(); 4714 HasConstParam = ReferentType.isConstQualified(); 4715 4716 if (ReferentType.isVolatileQualified()) { 4717 Diag(MD->getLocation(), 4718 diag::err_defaulted_special_member_volatile_param) << CSM; 4719 HadError = true; 4720 } 4721 4722 if (HasConstParam && !CanHaveConstParam) { 4723 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4724 Diag(MD->getLocation(), 4725 diag::err_defaulted_special_member_copy_const_param) 4726 << (CSM == CXXCopyAssignment); 4727 // FIXME: Explain why this special member can't be const. 4728 } else { 4729 Diag(MD->getLocation(), 4730 diag::err_defaulted_special_member_move_const_param) 4731 << (CSM == CXXMoveAssignment); 4732 } 4733 HadError = true; 4734 } 4735 } else if (ExpectedParams) { 4736 // A copy assignment operator can take its argument by value, but a 4737 // defaulted one cannot. 4738 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4739 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4740 HadError = true; 4741 } 4742 4743 // C++11 [dcl.fct.def.default]p2: 4744 // An explicitly-defaulted function may be declared constexpr only if it 4745 // would have been implicitly declared as constexpr, 4746 // Do not apply this rule to members of class templates, since core issue 1358 4747 // makes such functions always instantiate to constexpr functions. For 4748 // functions which cannot be constexpr (for non-constructors in C++11 and for 4749 // destructors in C++1y), this is checked elsewhere. 4750 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4751 HasConstParam); 4752 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD) 4753 : isa<CXXConstructorDecl>(MD)) && 4754 MD->isConstexpr() && !Constexpr && 4755 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4756 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4757 // FIXME: Explain why the special member can't be constexpr. 4758 HadError = true; 4759 } 4760 4761 // and may have an explicit exception-specification only if it is compatible 4762 // with the exception-specification on the implicit declaration. 4763 if (Type->hasExceptionSpec()) { 4764 // Delay the check if this is the first declaration of the special member, 4765 // since we may not have parsed some necessary in-class initializers yet. 4766 if (First) { 4767 // If the exception specification needs to be instantiated, do so now, 4768 // before we clobber it with an EST_Unevaluated specification below. 4769 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4770 InstantiateExceptionSpec(MD->getLocStart(), MD); 4771 Type = MD->getType()->getAs<FunctionProtoType>(); 4772 } 4773 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4774 } else 4775 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4776 } 4777 4778 // If a function is explicitly defaulted on its first declaration, 4779 if (First) { 4780 // -- it is implicitly considered to be constexpr if the implicit 4781 // definition would be, 4782 MD->setConstexpr(Constexpr); 4783 4784 // -- it is implicitly considered to have the same exception-specification 4785 // as if it had been implicitly declared, 4786 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4787 EPI.ExceptionSpecType = EST_Unevaluated; 4788 EPI.ExceptionSpecDecl = MD; 4789 MD->setType(Context.getFunctionType(ReturnType, 4790 ArrayRef<QualType>(&ArgType, 4791 ExpectedParams), 4792 EPI)); 4793 } 4794 4795 if (ShouldDeleteSpecialMember(MD, CSM)) { 4796 if (First) { 4797 SetDeclDeleted(MD, MD->getLocation()); 4798 } else { 4799 // C++11 [dcl.fct.def.default]p4: 4800 // [For a] user-provided explicitly-defaulted function [...] if such a 4801 // function is implicitly defined as deleted, the program is ill-formed. 4802 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4803 HadError = true; 4804 } 4805 } 4806 4807 if (HadError) 4808 MD->setInvalidDecl(); 4809 } 4810 4811 /// Check whether the exception specification provided for an 4812 /// explicitly-defaulted special member matches the exception specification 4813 /// that would have been generated for an implicit special member, per 4814 /// C++11 [dcl.fct.def.default]p2. 4815 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 4816 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 4817 // Compute the implicit exception specification. 4818 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4819 /*IsCXXMethod=*/true); 4820 FunctionProtoType::ExtProtoInfo EPI(CC); 4821 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4822 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 4823 Context.getFunctionType(Context.VoidTy, None, EPI)); 4824 4825 // Ensure that it matches. 4826 CheckEquivalentExceptionSpec( 4827 PDiag(diag::err_incorrect_defaulted_exception_spec) 4828 << getSpecialMember(MD), PDiag(), 4829 ImplicitType, SourceLocation(), 4830 SpecifiedType, MD->getLocation()); 4831 } 4832 4833 void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() { 4834 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size(); 4835 I != N; ++I) 4836 CheckExplicitlyDefaultedMemberExceptionSpec( 4837 DelayedDefaultedMemberExceptionSpecs[I].first, 4838 DelayedDefaultedMemberExceptionSpecs[I].second); 4839 4840 DelayedDefaultedMemberExceptionSpecs.clear(); 4841 } 4842 4843 namespace { 4844 struct SpecialMemberDeletionInfo { 4845 Sema &S; 4846 CXXMethodDecl *MD; 4847 Sema::CXXSpecialMember CSM; 4848 bool Diagnose; 4849 4850 // Properties of the special member, computed for convenience. 4851 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg; 4852 SourceLocation Loc; 4853 4854 bool AllFieldsAreConst; 4855 4856 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4857 Sema::CXXSpecialMember CSM, bool Diagnose) 4858 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4859 IsConstructor(false), IsAssignment(false), IsMove(false), 4860 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()), 4861 AllFieldsAreConst(true) { 4862 switch (CSM) { 4863 case Sema::CXXDefaultConstructor: 4864 case Sema::CXXCopyConstructor: 4865 IsConstructor = true; 4866 break; 4867 case Sema::CXXMoveConstructor: 4868 IsConstructor = true; 4869 IsMove = true; 4870 break; 4871 case Sema::CXXCopyAssignment: 4872 IsAssignment = true; 4873 break; 4874 case Sema::CXXMoveAssignment: 4875 IsAssignment = true; 4876 IsMove = true; 4877 break; 4878 case Sema::CXXDestructor: 4879 break; 4880 case Sema::CXXInvalid: 4881 llvm_unreachable("invalid special member kind"); 4882 } 4883 4884 if (MD->getNumParams()) { 4885 ConstArg = MD->getParamDecl(0)->getType().isConstQualified(); 4886 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified(); 4887 } 4888 } 4889 4890 bool inUnion() const { return MD->getParent()->isUnion(); } 4891 4892 /// Look up the corresponding special member in the given class. 4893 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4894 unsigned Quals) { 4895 unsigned TQ = MD->getTypeQualifiers(); 4896 // cv-qualifiers on class members don't affect default ctor / dtor calls. 4897 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4898 Quals = 0; 4899 return S.LookupSpecialMember(Class, CSM, 4900 ConstArg || (Quals & Qualifiers::Const), 4901 VolatileArg || (Quals & Qualifiers::Volatile), 4902 MD->getRefQualifier() == RQ_RValue, 4903 TQ & Qualifiers::Const, 4904 TQ & Qualifiers::Volatile); 4905 } 4906 4907 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4908 4909 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4910 bool shouldDeleteForField(FieldDecl *FD); 4911 bool shouldDeleteForAllConstMembers(); 4912 4913 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4914 unsigned Quals); 4915 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4916 Sema::SpecialMemberOverloadResult *SMOR, 4917 bool IsDtorCallInCtor); 4918 4919 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4920 }; 4921 } 4922 4923 /// Is the given special member inaccessible when used on the given 4924 /// sub-object. 4925 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4926 CXXMethodDecl *target) { 4927 /// If we're operating on a base class, the object type is the 4928 /// type of this special member. 4929 QualType objectTy; 4930 AccessSpecifier access = target->getAccess(); 4931 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 4932 objectTy = S.Context.getTypeDeclType(MD->getParent()); 4933 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 4934 4935 // If we're operating on a field, the object type is the type of the field. 4936 } else { 4937 objectTy = S.Context.getTypeDeclType(target->getParent()); 4938 } 4939 4940 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 4941 } 4942 4943 /// Check whether we should delete a special member due to the implicit 4944 /// definition containing a call to a special member of a subobject. 4945 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 4946 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 4947 bool IsDtorCallInCtor) { 4948 CXXMethodDecl *Decl = SMOR->getMethod(); 4949 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4950 4951 int DiagKind = -1; 4952 4953 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 4954 DiagKind = !Decl ? 0 : 1; 4955 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 4956 DiagKind = 2; 4957 else if (!isAccessible(Subobj, Decl)) 4958 DiagKind = 3; 4959 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 4960 !Decl->isTrivial()) { 4961 // A member of a union must have a trivial corresponding special member. 4962 // As a weird special case, a destructor call from a union's constructor 4963 // must be accessible and non-deleted, but need not be trivial. Such a 4964 // destructor is never actually called, but is semantically checked as 4965 // if it were. 4966 DiagKind = 4; 4967 } 4968 4969 if (DiagKind == -1) 4970 return false; 4971 4972 if (Diagnose) { 4973 if (Field) { 4974 S.Diag(Field->getLocation(), 4975 diag::note_deleted_special_member_class_subobject) 4976 << CSM << MD->getParent() << /*IsField*/true 4977 << Field << DiagKind << IsDtorCallInCtor; 4978 } else { 4979 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 4980 S.Diag(Base->getLocStart(), 4981 diag::note_deleted_special_member_class_subobject) 4982 << CSM << MD->getParent() << /*IsField*/false 4983 << Base->getType() << DiagKind << IsDtorCallInCtor; 4984 } 4985 4986 if (DiagKind == 1) 4987 S.NoteDeletedFunction(Decl); 4988 // FIXME: Explain inaccessibility if DiagKind == 3. 4989 } 4990 4991 return true; 4992 } 4993 4994 /// Check whether we should delete a special member function due to having a 4995 /// direct or virtual base class or non-static data member of class type M. 4996 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 4997 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 4998 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 4999 5000 // C++11 [class.ctor]p5: 5001 // -- any direct or virtual base class, or non-static data member with no 5002 // brace-or-equal-initializer, has class type M (or array thereof) and 5003 // either M has no default constructor or overload resolution as applied 5004 // to M's default constructor results in an ambiguity or in a function 5005 // that is deleted or inaccessible 5006 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5007 // -- a direct or virtual base class B that cannot be copied/moved because 5008 // overload resolution, as applied to B's corresponding special member, 5009 // results in an ambiguity or a function that is deleted or inaccessible 5010 // from the defaulted special member 5011 // C++11 [class.dtor]p5: 5012 // -- any direct or virtual base class [...] has a type with a destructor 5013 // that is deleted or inaccessible 5014 if (!(CSM == Sema::CXXDefaultConstructor && 5015 Field && Field->hasInClassInitializer()) && 5016 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false)) 5017 return true; 5018 5019 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5020 // -- any direct or virtual base class or non-static data member has a 5021 // type with a destructor that is deleted or inaccessible 5022 if (IsConstructor) { 5023 Sema::SpecialMemberOverloadResult *SMOR = 5024 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5025 false, false, false, false, false); 5026 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5027 return true; 5028 } 5029 5030 return false; 5031 } 5032 5033 /// Check whether we should delete a special member function due to the class 5034 /// having a particular direct or virtual base class. 5035 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5036 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5037 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5038 } 5039 5040 /// Check whether we should delete a special member function due to the class 5041 /// having a particular non-static data member. 5042 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5043 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5044 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5045 5046 if (CSM == Sema::CXXDefaultConstructor) { 5047 // For a default constructor, all references must be initialized in-class 5048 // and, if a union, it must have a non-const member. 5049 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5050 if (Diagnose) 5051 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5052 << MD->getParent() << FD << FieldType << /*Reference*/0; 5053 return true; 5054 } 5055 // C++11 [class.ctor]p5: any non-variant non-static data member of 5056 // const-qualified type (or array thereof) with no 5057 // brace-or-equal-initializer does not have a user-provided default 5058 // constructor. 5059 if (!inUnion() && FieldType.isConstQualified() && 5060 !FD->hasInClassInitializer() && 5061 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5062 if (Diagnose) 5063 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5064 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5065 return true; 5066 } 5067 5068 if (inUnion() && !FieldType.isConstQualified()) 5069 AllFieldsAreConst = false; 5070 } else if (CSM == Sema::CXXCopyConstructor) { 5071 // For a copy constructor, data members must not be of rvalue reference 5072 // type. 5073 if (FieldType->isRValueReferenceType()) { 5074 if (Diagnose) 5075 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5076 << MD->getParent() << FD << FieldType; 5077 return true; 5078 } 5079 } else if (IsAssignment) { 5080 // For an assignment operator, data members must not be of reference type. 5081 if (FieldType->isReferenceType()) { 5082 if (Diagnose) 5083 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5084 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5085 return true; 5086 } 5087 if (!FieldRecord && FieldType.isConstQualified()) { 5088 // C++11 [class.copy]p23: 5089 // -- a non-static data member of const non-class type (or array thereof) 5090 if (Diagnose) 5091 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5092 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5093 return true; 5094 } 5095 } 5096 5097 if (FieldRecord) { 5098 // Some additional restrictions exist on the variant members. 5099 if (!inUnion() && FieldRecord->isUnion() && 5100 FieldRecord->isAnonymousStructOrUnion()) { 5101 bool AllVariantFieldsAreConst = true; 5102 5103 // FIXME: Handle anonymous unions declared within anonymous unions. 5104 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(), 5105 UE = FieldRecord->field_end(); 5106 UI != UE; ++UI) { 5107 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5108 5109 if (!UnionFieldType.isConstQualified()) 5110 AllVariantFieldsAreConst = false; 5111 5112 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5113 if (UnionFieldRecord && 5114 shouldDeleteForClassSubobject(UnionFieldRecord, *UI, 5115 UnionFieldType.getCVRQualifiers())) 5116 return true; 5117 } 5118 5119 // At least one member in each anonymous union must be non-const 5120 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5121 FieldRecord->field_begin() != FieldRecord->field_end()) { 5122 if (Diagnose) 5123 S.Diag(FieldRecord->getLocation(), 5124 diag::note_deleted_default_ctor_all_const) 5125 << MD->getParent() << /*anonymous union*/1; 5126 return true; 5127 } 5128 5129 // Don't check the implicit member of the anonymous union type. 5130 // This is technically non-conformant, but sanity demands it. 5131 return false; 5132 } 5133 5134 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5135 FieldType.getCVRQualifiers())) 5136 return true; 5137 } 5138 5139 return false; 5140 } 5141 5142 /// C++11 [class.ctor] p5: 5143 /// A defaulted default constructor for a class X is defined as deleted if 5144 /// X is a union and all of its variant members are of const-qualified type. 5145 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5146 // This is a silly definition, because it gives an empty union a deleted 5147 // default constructor. Don't do that. 5148 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5149 (MD->getParent()->field_begin() != MD->getParent()->field_end())) { 5150 if (Diagnose) 5151 S.Diag(MD->getParent()->getLocation(), 5152 diag::note_deleted_default_ctor_all_const) 5153 << MD->getParent() << /*not anonymous union*/0; 5154 return true; 5155 } 5156 return false; 5157 } 5158 5159 /// Determine whether a defaulted special member function should be defined as 5160 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5161 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5162 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5163 bool Diagnose) { 5164 if (MD->isInvalidDecl()) 5165 return false; 5166 CXXRecordDecl *RD = MD->getParent(); 5167 assert(!RD->isDependentType() && "do deletion after instantiation"); 5168 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5169 return false; 5170 5171 // C++11 [expr.lambda.prim]p19: 5172 // The closure type associated with a lambda-expression has a 5173 // deleted (8.4.3) default constructor and a deleted copy 5174 // assignment operator. 5175 if (RD->isLambda() && 5176 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5177 if (Diagnose) 5178 Diag(RD->getLocation(), diag::note_lambda_decl); 5179 return true; 5180 } 5181 5182 // For an anonymous struct or union, the copy and assignment special members 5183 // will never be used, so skip the check. For an anonymous union declared at 5184 // namespace scope, the constructor and destructor are used. 5185 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5186 RD->isAnonymousStructOrUnion()) 5187 return false; 5188 5189 // C++11 [class.copy]p7, p18: 5190 // If the class definition declares a move constructor or move assignment 5191 // operator, an implicitly declared copy constructor or copy assignment 5192 // operator is defined as deleted. 5193 if (MD->isImplicit() && 5194 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5195 CXXMethodDecl *UserDeclaredMove = 0; 5196 5197 // In Microsoft mode, a user-declared move only causes the deletion of the 5198 // corresponding copy operation, not both copy operations. 5199 if (RD->hasUserDeclaredMoveConstructor() && 5200 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) { 5201 if (!Diagnose) return true; 5202 5203 // Find any user-declared move constructor. 5204 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 5205 E = RD->ctor_end(); I != E; ++I) { 5206 if (I->isMoveConstructor()) { 5207 UserDeclaredMove = *I; 5208 break; 5209 } 5210 } 5211 assert(UserDeclaredMove); 5212 } else if (RD->hasUserDeclaredMoveAssignment() && 5213 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) { 5214 if (!Diagnose) return true; 5215 5216 // Find any user-declared move assignment operator. 5217 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 5218 E = RD->method_end(); I != E; ++I) { 5219 if (I->isMoveAssignmentOperator()) { 5220 UserDeclaredMove = *I; 5221 break; 5222 } 5223 } 5224 assert(UserDeclaredMove); 5225 } 5226 5227 if (UserDeclaredMove) { 5228 Diag(UserDeclaredMove->getLocation(), 5229 diag::note_deleted_copy_user_declared_move) 5230 << (CSM == CXXCopyAssignment) << RD 5231 << UserDeclaredMove->isMoveAssignmentOperator(); 5232 return true; 5233 } 5234 } 5235 5236 // Do access control from the special member function 5237 ContextRAII MethodContext(*this, MD); 5238 5239 // C++11 [class.dtor]p5: 5240 // -- for a virtual destructor, lookup of the non-array deallocation function 5241 // results in an ambiguity or in a function that is deleted or inaccessible 5242 if (CSM == CXXDestructor && MD->isVirtual()) { 5243 FunctionDecl *OperatorDelete = 0; 5244 DeclarationName Name = 5245 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5246 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5247 OperatorDelete, false)) { 5248 if (Diagnose) 5249 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5250 return true; 5251 } 5252 } 5253 5254 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5255 5256 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5257 BE = RD->bases_end(); BI != BE; ++BI) 5258 if (!BI->isVirtual() && 5259 SMI.shouldDeleteForBase(BI)) 5260 return true; 5261 5262 // Per DR1611, do not consider virtual bases of constructors of abstract 5263 // classes, since we are not going to construct them. 5264 if (!RD->isAbstract() || !SMI.IsConstructor) { 5265 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(), 5266 BE = RD->vbases_end(); 5267 BI != BE; ++BI) 5268 if (SMI.shouldDeleteForBase(BI)) 5269 return true; 5270 } 5271 5272 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5273 FE = RD->field_end(); FI != FE; ++FI) 5274 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5275 SMI.shouldDeleteForField(*FI)) 5276 return true; 5277 5278 if (SMI.shouldDeleteForAllConstMembers()) 5279 return true; 5280 5281 return false; 5282 } 5283 5284 /// Perform lookup for a special member of the specified kind, and determine 5285 /// whether it is trivial. If the triviality can be determined without the 5286 /// lookup, skip it. This is intended for use when determining whether a 5287 /// special member of a containing object is trivial, and thus does not ever 5288 /// perform overload resolution for default constructors. 5289 /// 5290 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5291 /// member that was most likely to be intended to be trivial, if any. 5292 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5293 Sema::CXXSpecialMember CSM, unsigned Quals, 5294 CXXMethodDecl **Selected) { 5295 if (Selected) 5296 *Selected = 0; 5297 5298 switch (CSM) { 5299 case Sema::CXXInvalid: 5300 llvm_unreachable("not a special member"); 5301 5302 case Sema::CXXDefaultConstructor: 5303 // C++11 [class.ctor]p5: 5304 // A default constructor is trivial if: 5305 // - all the [direct subobjects] have trivial default constructors 5306 // 5307 // Note, no overload resolution is performed in this case. 5308 if (RD->hasTrivialDefaultConstructor()) 5309 return true; 5310 5311 if (Selected) { 5312 // If there's a default constructor which could have been trivial, dig it 5313 // out. Otherwise, if there's any user-provided default constructor, point 5314 // to that as an example of why there's not a trivial one. 5315 CXXConstructorDecl *DefCtor = 0; 5316 if (RD->needsImplicitDefaultConstructor()) 5317 S.DeclareImplicitDefaultConstructor(RD); 5318 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), 5319 CE = RD->ctor_end(); CI != CE; ++CI) { 5320 if (!CI->isDefaultConstructor()) 5321 continue; 5322 DefCtor = *CI; 5323 if (!DefCtor->isUserProvided()) 5324 break; 5325 } 5326 5327 *Selected = DefCtor; 5328 } 5329 5330 return false; 5331 5332 case Sema::CXXDestructor: 5333 // C++11 [class.dtor]p5: 5334 // A destructor is trivial if: 5335 // - all the direct [subobjects] have trivial destructors 5336 if (RD->hasTrivialDestructor()) 5337 return true; 5338 5339 if (Selected) { 5340 if (RD->needsImplicitDestructor()) 5341 S.DeclareImplicitDestructor(RD); 5342 *Selected = RD->getDestructor(); 5343 } 5344 5345 return false; 5346 5347 case Sema::CXXCopyConstructor: 5348 // C++11 [class.copy]p12: 5349 // A copy constructor is trivial if: 5350 // - the constructor selected to copy each direct [subobject] is trivial 5351 if (RD->hasTrivialCopyConstructor()) { 5352 if (Quals == Qualifiers::Const) 5353 // We must either select the trivial copy constructor or reach an 5354 // ambiguity; no need to actually perform overload resolution. 5355 return true; 5356 } else if (!Selected) { 5357 return false; 5358 } 5359 // In C++98, we are not supposed to perform overload resolution here, but we 5360 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5361 // cases like B as having a non-trivial copy constructor: 5362 // struct A { template<typename T> A(T&); }; 5363 // struct B { mutable A a; }; 5364 goto NeedOverloadResolution; 5365 5366 case Sema::CXXCopyAssignment: 5367 // C++11 [class.copy]p25: 5368 // A copy assignment operator is trivial if: 5369 // - the assignment operator selected to copy each direct [subobject] is 5370 // trivial 5371 if (RD->hasTrivialCopyAssignment()) { 5372 if (Quals == Qualifiers::Const) 5373 return true; 5374 } else if (!Selected) { 5375 return false; 5376 } 5377 // In C++98, we are not supposed to perform overload resolution here, but we 5378 // treat that as a language defect. 5379 goto NeedOverloadResolution; 5380 5381 case Sema::CXXMoveConstructor: 5382 case Sema::CXXMoveAssignment: 5383 NeedOverloadResolution: 5384 Sema::SpecialMemberOverloadResult *SMOR = 5385 S.LookupSpecialMember(RD, CSM, 5386 Quals & Qualifiers::Const, 5387 Quals & Qualifiers::Volatile, 5388 /*RValueThis*/false, /*ConstThis*/false, 5389 /*VolatileThis*/false); 5390 5391 // The standard doesn't describe how to behave if the lookup is ambiguous. 5392 // We treat it as not making the member non-trivial, just like the standard 5393 // mandates for the default constructor. This should rarely matter, because 5394 // the member will also be deleted. 5395 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5396 return true; 5397 5398 if (!SMOR->getMethod()) { 5399 assert(SMOR->getKind() == 5400 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5401 return false; 5402 } 5403 5404 // We deliberately don't check if we found a deleted special member. We're 5405 // not supposed to! 5406 if (Selected) 5407 *Selected = SMOR->getMethod(); 5408 return SMOR->getMethod()->isTrivial(); 5409 } 5410 5411 llvm_unreachable("unknown special method kind"); 5412 } 5413 5414 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5415 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end(); 5416 CI != CE; ++CI) 5417 if (!CI->isImplicit()) 5418 return *CI; 5419 5420 // Look for constructor templates. 5421 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5422 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5423 if (CXXConstructorDecl *CD = 5424 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5425 return CD; 5426 } 5427 5428 return 0; 5429 } 5430 5431 /// The kind of subobject we are checking for triviality. The values of this 5432 /// enumeration are used in diagnostics. 5433 enum TrivialSubobjectKind { 5434 /// The subobject is a base class. 5435 TSK_BaseClass, 5436 /// The subobject is a non-static data member. 5437 TSK_Field, 5438 /// The object is actually the complete object. 5439 TSK_CompleteObject 5440 }; 5441 5442 /// Check whether the special member selected for a given type would be trivial. 5443 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5444 QualType SubType, 5445 Sema::CXXSpecialMember CSM, 5446 TrivialSubobjectKind Kind, 5447 bool Diagnose) { 5448 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5449 if (!SubRD) 5450 return true; 5451 5452 CXXMethodDecl *Selected; 5453 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5454 Diagnose ? &Selected : 0)) 5455 return true; 5456 5457 if (Diagnose) { 5458 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5459 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5460 << Kind << SubType.getUnqualifiedType(); 5461 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5462 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5463 } else if (!Selected) 5464 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5465 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5466 else if (Selected->isUserProvided()) { 5467 if (Kind == TSK_CompleteObject) 5468 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5469 << Kind << SubType.getUnqualifiedType() << CSM; 5470 else { 5471 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5472 << Kind << SubType.getUnqualifiedType() << CSM; 5473 S.Diag(Selected->getLocation(), diag::note_declared_at); 5474 } 5475 } else { 5476 if (Kind != TSK_CompleteObject) 5477 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5478 << Kind << SubType.getUnqualifiedType() << CSM; 5479 5480 // Explain why the defaulted or deleted special member isn't trivial. 5481 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5482 } 5483 } 5484 5485 return false; 5486 } 5487 5488 /// Check whether the members of a class type allow a special member to be 5489 /// trivial. 5490 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5491 Sema::CXXSpecialMember CSM, 5492 bool ConstArg, bool Diagnose) { 5493 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 5494 FE = RD->field_end(); FI != FE; ++FI) { 5495 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5496 continue; 5497 5498 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5499 5500 // Pretend anonymous struct or union members are members of this class. 5501 if (FI->isAnonymousStructOrUnion()) { 5502 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5503 CSM, ConstArg, Diagnose)) 5504 return false; 5505 continue; 5506 } 5507 5508 // C++11 [class.ctor]p5: 5509 // A default constructor is trivial if [...] 5510 // -- no non-static data member of its class has a 5511 // brace-or-equal-initializer 5512 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5513 if (Diagnose) 5514 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI; 5515 return false; 5516 } 5517 5518 // Objective C ARC 4.3.5: 5519 // [...] nontrivally ownership-qualified types are [...] not trivially 5520 // default constructible, copy constructible, move constructible, copy 5521 // assignable, move assignable, or destructible [...] 5522 if (S.getLangOpts().ObjCAutoRefCount && 5523 FieldType.hasNonTrivialObjCLifetime()) { 5524 if (Diagnose) 5525 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5526 << RD << FieldType.getObjCLifetime(); 5527 return false; 5528 } 5529 5530 if (ConstArg && !FI->isMutable()) 5531 FieldType.addConst(); 5532 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM, 5533 TSK_Field, Diagnose)) 5534 return false; 5535 } 5536 5537 return true; 5538 } 5539 5540 /// Diagnose why the specified class does not have a trivial special member of 5541 /// the given kind. 5542 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5543 QualType Ty = Context.getRecordType(RD); 5544 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) 5545 Ty.addConst(); 5546 5547 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM, 5548 TSK_CompleteObject, /*Diagnose*/true); 5549 } 5550 5551 /// Determine whether a defaulted or deleted special member function is trivial, 5552 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5553 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5554 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5555 bool Diagnose) { 5556 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5557 5558 CXXRecordDecl *RD = MD->getParent(); 5559 5560 bool ConstArg = false; 5561 5562 // C++11 [class.copy]p12, p25: 5563 // A [special member] is trivial if its declared parameter type is the same 5564 // as if it had been implicitly declared [...] 5565 switch (CSM) { 5566 case CXXDefaultConstructor: 5567 case CXXDestructor: 5568 // Trivial default constructors and destructors cannot have parameters. 5569 break; 5570 5571 case CXXCopyConstructor: 5572 case CXXCopyAssignment: { 5573 // Trivial copy operations always have const, non-volatile parameter types. 5574 ConstArg = true; 5575 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5576 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5577 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5578 if (Diagnose) 5579 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5580 << Param0->getSourceRange() << Param0->getType() 5581 << Context.getLValueReferenceType( 5582 Context.getRecordType(RD).withConst()); 5583 return false; 5584 } 5585 break; 5586 } 5587 5588 case CXXMoveConstructor: 5589 case CXXMoveAssignment: { 5590 // Trivial move operations always have non-cv-qualified parameters. 5591 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5592 const RValueReferenceType *RT = 5593 Param0->getType()->getAs<RValueReferenceType>(); 5594 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5595 if (Diagnose) 5596 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5597 << Param0->getSourceRange() << Param0->getType() 5598 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5599 return false; 5600 } 5601 break; 5602 } 5603 5604 case CXXInvalid: 5605 llvm_unreachable("not a special member"); 5606 } 5607 5608 // FIXME: We require that the parameter-declaration-clause is equivalent to 5609 // that of an implicit declaration, not just that the declared parameter type 5610 // matches, in order to prevent absuridities like a function simultaneously 5611 // being a trivial copy constructor and a non-trivial default constructor. 5612 // This issue has not yet been assigned a core issue number. 5613 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5614 if (Diagnose) 5615 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5616 diag::note_nontrivial_default_arg) 5617 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5618 return false; 5619 } 5620 if (MD->isVariadic()) { 5621 if (Diagnose) 5622 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5623 return false; 5624 } 5625 5626 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5627 // A copy/move [constructor or assignment operator] is trivial if 5628 // -- the [member] selected to copy/move each direct base class subobject 5629 // is trivial 5630 // 5631 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5632 // A [default constructor or destructor] is trivial if 5633 // -- all the direct base classes have trivial [default constructors or 5634 // destructors] 5635 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(), 5636 BE = RD->bases_end(); BI != BE; ++BI) 5637 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(), 5638 ConstArg ? BI->getType().withConst() 5639 : BI->getType(), 5640 CSM, TSK_BaseClass, Diagnose)) 5641 return false; 5642 5643 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5644 // A copy/move [constructor or assignment operator] for a class X is 5645 // trivial if 5646 // -- for each non-static data member of X that is of class type (or array 5647 // thereof), the constructor selected to copy/move that member is 5648 // trivial 5649 // 5650 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5651 // A [default constructor or destructor] is trivial if 5652 // -- for all of the non-static data members of its class that are of class 5653 // type (or array thereof), each such class has a trivial [default 5654 // constructor or destructor] 5655 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5656 return false; 5657 5658 // C++11 [class.dtor]p5: 5659 // A destructor is trivial if [...] 5660 // -- the destructor is not virtual 5661 if (CSM == CXXDestructor && MD->isVirtual()) { 5662 if (Diagnose) 5663 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5664 return false; 5665 } 5666 5667 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5668 // A [special member] for class X is trivial if [...] 5669 // -- class X has no virtual functions and no virtual base classes 5670 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5671 if (!Diagnose) 5672 return false; 5673 5674 if (RD->getNumVBases()) { 5675 // Check for virtual bases. We already know that the corresponding 5676 // member in all bases is trivial, so vbases must all be direct. 5677 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5678 assert(BS.isVirtual()); 5679 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5680 return false; 5681 } 5682 5683 // Must have a virtual method. 5684 for (CXXRecordDecl::method_iterator MI = RD->method_begin(), 5685 ME = RD->method_end(); MI != ME; ++MI) { 5686 if (MI->isVirtual()) { 5687 SourceLocation MLoc = MI->getLocStart(); 5688 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5689 return false; 5690 } 5691 } 5692 5693 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5694 } 5695 5696 // Looks like it's trivial! 5697 return true; 5698 } 5699 5700 /// \brief Data used with FindHiddenVirtualMethod 5701 namespace { 5702 struct FindHiddenVirtualMethodData { 5703 Sema *S; 5704 CXXMethodDecl *Method; 5705 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5706 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5707 }; 5708 } 5709 5710 /// \brief Check whether any most overriden method from MD in Methods 5711 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5712 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5713 if (MD->size_overridden_methods() == 0) 5714 return Methods.count(MD->getCanonicalDecl()); 5715 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5716 E = MD->end_overridden_methods(); 5717 I != E; ++I) 5718 if (CheckMostOverridenMethods(*I, Methods)) 5719 return true; 5720 return false; 5721 } 5722 5723 /// \brief Member lookup function that determines whether a given C++ 5724 /// method overloads virtual methods in a base class without overriding any, 5725 /// to be used with CXXRecordDecl::lookupInBases(). 5726 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5727 CXXBasePath &Path, 5728 void *UserData) { 5729 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5730 5731 FindHiddenVirtualMethodData &Data 5732 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5733 5734 DeclarationName Name = Data.Method->getDeclName(); 5735 assert(Name.getNameKind() == DeclarationName::Identifier); 5736 5737 bool foundSameNameMethod = false; 5738 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5739 for (Path.Decls = BaseRecord->lookup(Name); 5740 !Path.Decls.empty(); 5741 Path.Decls = Path.Decls.slice(1)) { 5742 NamedDecl *D = Path.Decls.front(); 5743 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5744 MD = MD->getCanonicalDecl(); 5745 foundSameNameMethod = true; 5746 // Interested only in hidden virtual methods. 5747 if (!MD->isVirtual()) 5748 continue; 5749 // If the method we are checking overrides a method from its base 5750 // don't warn about the other overloaded methods. 5751 if (!Data.S->IsOverload(Data.Method, MD, false)) 5752 return true; 5753 // Collect the overload only if its hidden. 5754 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5755 overloadedMethods.push_back(MD); 5756 } 5757 } 5758 5759 if (foundSameNameMethod) 5760 Data.OverloadedMethods.append(overloadedMethods.begin(), 5761 overloadedMethods.end()); 5762 return foundSameNameMethod; 5763 } 5764 5765 /// \brief Add the most overriden methods from MD to Methods 5766 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5767 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5768 if (MD->size_overridden_methods() == 0) 5769 Methods.insert(MD->getCanonicalDecl()); 5770 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5771 E = MD->end_overridden_methods(); 5772 I != E; ++I) 5773 AddMostOverridenMethods(*I, Methods); 5774 } 5775 5776 /// \brief Check if a method overloads virtual methods in a base class without 5777 /// overriding any. 5778 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 5779 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5780 if (!MD->getDeclName().isIdentifier()) 5781 return; 5782 5783 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5784 /*bool RecordPaths=*/false, 5785 /*bool DetectVirtual=*/false); 5786 FindHiddenVirtualMethodData Data; 5787 Data.Method = MD; 5788 Data.S = this; 5789 5790 // Keep the base methods that were overriden or introduced in the subclass 5791 // by 'using' in a set. A base method not in this set is hidden. 5792 CXXRecordDecl *DC = MD->getParent(); 5793 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5794 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5795 NamedDecl *ND = *I; 5796 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5797 ND = shad->getTargetDecl(); 5798 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5799 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5800 } 5801 5802 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 5803 OverloadedMethods = Data.OverloadedMethods; 5804 } 5805 5806 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 5807 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5808 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 5809 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 5810 PartialDiagnostic PD = PDiag( 5811 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5812 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 5813 Diag(overloadedMD->getLocation(), PD); 5814 } 5815 } 5816 5817 /// \brief Diagnose methods which overload virtual methods in a base class 5818 /// without overriding any. 5819 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 5820 if (MD->isInvalidDecl()) 5821 return; 5822 5823 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5824 MD->getLocation()) == DiagnosticsEngine::Ignored) 5825 return; 5826 5827 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5828 FindHiddenVirtualMethods(MD, OverloadedMethods); 5829 if (!OverloadedMethods.empty()) { 5830 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5831 << MD << (OverloadedMethods.size() > 1); 5832 5833 NoteHiddenVirtualMethods(MD, OverloadedMethods); 5834 } 5835 } 5836 5837 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5838 Decl *TagDecl, 5839 SourceLocation LBrac, 5840 SourceLocation RBrac, 5841 AttributeList *AttrList) { 5842 if (!TagDecl) 5843 return; 5844 5845 AdjustDeclIfTemplate(TagDecl); 5846 5847 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5848 if (l->getKind() != AttributeList::AT_Visibility) 5849 continue; 5850 l->setInvalid(); 5851 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5852 l->getName(); 5853 } 5854 5855 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5856 // strict aliasing violation! 5857 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5858 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5859 5860 CheckCompletedCXXClass( 5861 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5862 } 5863 5864 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5865 /// special functions, such as the default constructor, copy 5866 /// constructor, or destructor, to the given C++ class (C++ 5867 /// [special]p1). This routine can only be executed just before the 5868 /// definition of the class is complete. 5869 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5870 if (!ClassDecl->hasUserDeclaredConstructor()) 5871 ++ASTContext::NumImplicitDefaultConstructors; 5872 5873 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 5874 ++ASTContext::NumImplicitCopyConstructors; 5875 5876 // If the properties or semantics of the copy constructor couldn't be 5877 // determined while the class was being declared, force a declaration 5878 // of it now. 5879 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 5880 DeclareImplicitCopyConstructor(ClassDecl); 5881 } 5882 5883 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 5884 ++ASTContext::NumImplicitMoveConstructors; 5885 5886 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 5887 DeclareImplicitMoveConstructor(ClassDecl); 5888 } 5889 5890 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5891 ++ASTContext::NumImplicitCopyAssignmentOperators; 5892 5893 // If we have a dynamic class, then the copy assignment operator may be 5894 // virtual, so we have to declare it immediately. This ensures that, e.g., 5895 // it shows up in the right place in the vtable and that we diagnose 5896 // problems with the implicit exception specification. 5897 if (ClassDecl->isDynamicClass() || 5898 ClassDecl->needsOverloadResolutionForCopyAssignment()) 5899 DeclareImplicitCopyAssignment(ClassDecl); 5900 } 5901 5902 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 5903 ++ASTContext::NumImplicitMoveAssignmentOperators; 5904 5905 // Likewise for the move assignment operator. 5906 if (ClassDecl->isDynamicClass() || 5907 ClassDecl->needsOverloadResolutionForMoveAssignment()) 5908 DeclareImplicitMoveAssignment(ClassDecl); 5909 } 5910 5911 if (!ClassDecl->hasUserDeclaredDestructor()) { 5912 ++ASTContext::NumImplicitDestructors; 5913 5914 // If we have a dynamic class, then the destructor may be virtual, so we 5915 // have to declare the destructor immediately. This ensures that, e.g., it 5916 // shows up in the right place in the vtable and that we diagnose problems 5917 // with the implicit exception specification. 5918 if (ClassDecl->isDynamicClass() || 5919 ClassDecl->needsOverloadResolutionForDestructor()) 5920 DeclareImplicitDestructor(ClassDecl); 5921 } 5922 } 5923 5924 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5925 if (!D) 5926 return; 5927 5928 int NumParamList = D->getNumTemplateParameterLists(); 5929 for (int i = 0; i < NumParamList; i++) { 5930 TemplateParameterList* Params = D->getTemplateParameterList(i); 5931 for (TemplateParameterList::iterator Param = Params->begin(), 5932 ParamEnd = Params->end(); 5933 Param != ParamEnd; ++Param) { 5934 NamedDecl *Named = cast<NamedDecl>(*Param); 5935 if (Named->getDeclName()) { 5936 S->AddDecl(Named); 5937 IdResolver.AddDecl(Named); 5938 } 5939 } 5940 } 5941 } 5942 5943 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 5944 if (!D) 5945 return; 5946 5947 TemplateParameterList *Params = 0; 5948 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 5949 Params = Template->getTemplateParameters(); 5950 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5951 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 5952 Params = PartialSpec->getTemplateParameters(); 5953 else 5954 return; 5955 5956 for (TemplateParameterList::iterator Param = Params->begin(), 5957 ParamEnd = Params->end(); 5958 Param != ParamEnd; ++Param) { 5959 NamedDecl *Named = cast<NamedDecl>(*Param); 5960 if (Named->getDeclName()) { 5961 S->AddDecl(Named); 5962 IdResolver.AddDecl(Named); 5963 } 5964 } 5965 } 5966 5967 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5968 if (!RecordD) return; 5969 AdjustDeclIfTemplate(RecordD); 5970 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 5971 PushDeclContext(S, Record); 5972 } 5973 5974 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 5975 if (!RecordD) return; 5976 PopDeclContext(); 5977 } 5978 5979 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 5980 /// parsing a top-level (non-nested) C++ class, and we are now 5981 /// parsing those parts of the given Method declaration that could 5982 /// not be parsed earlier (C++ [class.mem]p2), such as default 5983 /// arguments. This action should enter the scope of the given 5984 /// Method declaration as if we had just parsed the qualified method 5985 /// name. However, it should not bring the parameters into scope; 5986 /// that will be performed by ActOnDelayedCXXMethodParameter. 5987 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 5988 } 5989 5990 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 5991 /// C++ method declaration. We're (re-)introducing the given 5992 /// function parameter into scope for use in parsing later parts of 5993 /// the method declaration. For example, we could see an 5994 /// ActOnParamDefaultArgument event for this parameter. 5995 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 5996 if (!ParamD) 5997 return; 5998 5999 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6000 6001 // If this parameter has an unparsed default argument, clear it out 6002 // to make way for the parsed default argument. 6003 if (Param->hasUnparsedDefaultArg()) 6004 Param->setDefaultArg(0); 6005 6006 S->AddDecl(Param); 6007 if (Param->getDeclName()) 6008 IdResolver.AddDecl(Param); 6009 } 6010 6011 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6012 /// processing the delayed method declaration for Method. The method 6013 /// declaration is now considered finished. There may be a separate 6014 /// ActOnStartOfFunctionDef action later (not necessarily 6015 /// immediately!) for this method, if it was also defined inside the 6016 /// class body. 6017 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6018 if (!MethodD) 6019 return; 6020 6021 AdjustDeclIfTemplate(MethodD); 6022 6023 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6024 6025 // Now that we have our default arguments, check the constructor 6026 // again. It could produce additional diagnostics or affect whether 6027 // the class has implicitly-declared destructors, among other 6028 // things. 6029 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6030 CheckConstructor(Constructor); 6031 6032 // Check the default arguments, which we may have added. 6033 if (!Method->isInvalidDecl()) 6034 CheckCXXDefaultArguments(Method); 6035 } 6036 6037 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6038 /// the well-formedness of the constructor declarator @p D with type @p 6039 /// R. If there are any errors in the declarator, this routine will 6040 /// emit diagnostics and set the invalid bit to true. In any case, the type 6041 /// will be updated to reflect a well-formed type for the constructor and 6042 /// returned. 6043 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6044 StorageClass &SC) { 6045 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6046 6047 // C++ [class.ctor]p3: 6048 // A constructor shall not be virtual (10.3) or static (9.4). A 6049 // constructor can be invoked for a const, volatile or const 6050 // volatile object. A constructor shall not be declared const, 6051 // volatile, or const volatile (9.3.2). 6052 if (isVirtual) { 6053 if (!D.isInvalidType()) 6054 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6055 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6056 << SourceRange(D.getIdentifierLoc()); 6057 D.setInvalidType(); 6058 } 6059 if (SC == SC_Static) { 6060 if (!D.isInvalidType()) 6061 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6062 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6063 << SourceRange(D.getIdentifierLoc()); 6064 D.setInvalidType(); 6065 SC = SC_None; 6066 } 6067 6068 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6069 if (FTI.TypeQuals != 0) { 6070 if (FTI.TypeQuals & Qualifiers::Const) 6071 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6072 << "const" << SourceRange(D.getIdentifierLoc()); 6073 if (FTI.TypeQuals & Qualifiers::Volatile) 6074 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6075 << "volatile" << SourceRange(D.getIdentifierLoc()); 6076 if (FTI.TypeQuals & Qualifiers::Restrict) 6077 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6078 << "restrict" << SourceRange(D.getIdentifierLoc()); 6079 D.setInvalidType(); 6080 } 6081 6082 // C++0x [class.ctor]p4: 6083 // A constructor shall not be declared with a ref-qualifier. 6084 if (FTI.hasRefQualifier()) { 6085 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6086 << FTI.RefQualifierIsLValueRef 6087 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6088 D.setInvalidType(); 6089 } 6090 6091 // Rebuild the function type "R" without any type qualifiers (in 6092 // case any of the errors above fired) and with "void" as the 6093 // return type, since constructors don't have return types. 6094 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6095 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 6096 return R; 6097 6098 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6099 EPI.TypeQuals = 0; 6100 EPI.RefQualifier = RQ_None; 6101 6102 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI); 6103 } 6104 6105 /// CheckConstructor - Checks a fully-formed constructor for 6106 /// well-formedness, issuing any diagnostics required. Returns true if 6107 /// the constructor declarator is invalid. 6108 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6109 CXXRecordDecl *ClassDecl 6110 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6111 if (!ClassDecl) 6112 return Constructor->setInvalidDecl(); 6113 6114 // C++ [class.copy]p3: 6115 // A declaration of a constructor for a class X is ill-formed if 6116 // its first parameter is of type (optionally cv-qualified) X and 6117 // either there are no other parameters or else all other 6118 // parameters have default arguments. 6119 if (!Constructor->isInvalidDecl() && 6120 ((Constructor->getNumParams() == 1) || 6121 (Constructor->getNumParams() > 1 && 6122 Constructor->getParamDecl(1)->hasDefaultArg())) && 6123 Constructor->getTemplateSpecializationKind() 6124 != TSK_ImplicitInstantiation) { 6125 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6126 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6127 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6128 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6129 const char *ConstRef 6130 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6131 : " const &"; 6132 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6133 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6134 6135 // FIXME: Rather that making the constructor invalid, we should endeavor 6136 // to fix the type. 6137 Constructor->setInvalidDecl(); 6138 } 6139 } 6140 } 6141 6142 /// CheckDestructor - Checks a fully-formed destructor definition for 6143 /// well-formedness, issuing any diagnostics required. Returns true 6144 /// on error. 6145 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6146 CXXRecordDecl *RD = Destructor->getParent(); 6147 6148 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6149 SourceLocation Loc; 6150 6151 if (!Destructor->isImplicit()) 6152 Loc = Destructor->getLocation(); 6153 else 6154 Loc = RD->getLocation(); 6155 6156 // If we have a virtual destructor, look up the deallocation function 6157 FunctionDecl *OperatorDelete = 0; 6158 DeclarationName Name = 6159 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6160 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6161 return true; 6162 6163 MarkFunctionReferenced(Loc, OperatorDelete); 6164 6165 Destructor->setOperatorDelete(OperatorDelete); 6166 } 6167 6168 return false; 6169 } 6170 6171 static inline bool 6172 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 6173 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 6174 FTI.ArgInfo[0].Param && 6175 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 6176 } 6177 6178 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6179 /// the well-formednes of the destructor declarator @p D with type @p 6180 /// R. If there are any errors in the declarator, this routine will 6181 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6182 /// will be updated to reflect a well-formed type for the destructor and 6183 /// returned. 6184 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6185 StorageClass& SC) { 6186 // C++ [class.dtor]p1: 6187 // [...] A typedef-name that names a class is a class-name 6188 // (7.1.3); however, a typedef-name that names a class shall not 6189 // be used as the identifier in the declarator for a destructor 6190 // declaration. 6191 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6192 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6193 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6194 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6195 else if (const TemplateSpecializationType *TST = 6196 DeclaratorType->getAs<TemplateSpecializationType>()) 6197 if (TST->isTypeAlias()) 6198 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6199 << DeclaratorType << 1; 6200 6201 // C++ [class.dtor]p2: 6202 // A destructor is used to destroy objects of its class type. A 6203 // destructor takes no parameters, and no return type can be 6204 // specified for it (not even void). The address of a destructor 6205 // shall not be taken. A destructor shall not be static. A 6206 // destructor can be invoked for a const, volatile or const 6207 // volatile object. A destructor shall not be declared const, 6208 // volatile or const volatile (9.3.2). 6209 if (SC == SC_Static) { 6210 if (!D.isInvalidType()) 6211 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6212 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6213 << SourceRange(D.getIdentifierLoc()) 6214 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6215 6216 SC = SC_None; 6217 } 6218 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6219 // Destructors don't have return types, but the parser will 6220 // happily parse something like: 6221 // 6222 // class X { 6223 // float ~X(); 6224 // }; 6225 // 6226 // The return type will be eliminated later. 6227 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6228 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6229 << SourceRange(D.getIdentifierLoc()); 6230 } 6231 6232 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6233 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6234 if (FTI.TypeQuals & Qualifiers::Const) 6235 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6236 << "const" << SourceRange(D.getIdentifierLoc()); 6237 if (FTI.TypeQuals & Qualifiers::Volatile) 6238 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6239 << "volatile" << SourceRange(D.getIdentifierLoc()); 6240 if (FTI.TypeQuals & Qualifiers::Restrict) 6241 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6242 << "restrict" << SourceRange(D.getIdentifierLoc()); 6243 D.setInvalidType(); 6244 } 6245 6246 // C++0x [class.dtor]p2: 6247 // A destructor shall not be declared with a ref-qualifier. 6248 if (FTI.hasRefQualifier()) { 6249 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6250 << FTI.RefQualifierIsLValueRef 6251 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6252 D.setInvalidType(); 6253 } 6254 6255 // Make sure we don't have any parameters. 6256 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 6257 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6258 6259 // Delete the parameters. 6260 FTI.freeArgs(); 6261 D.setInvalidType(); 6262 } 6263 6264 // Make sure the destructor isn't variadic. 6265 if (FTI.isVariadic) { 6266 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6267 D.setInvalidType(); 6268 } 6269 6270 // Rebuild the function type "R" without any type qualifiers or 6271 // parameters (in case any of the errors above fired) and with 6272 // "void" as the return type, since destructors don't have return 6273 // types. 6274 if (!D.isInvalidType()) 6275 return R; 6276 6277 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6278 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6279 EPI.Variadic = false; 6280 EPI.TypeQuals = 0; 6281 EPI.RefQualifier = RQ_None; 6282 return Context.getFunctionType(Context.VoidTy, None, EPI); 6283 } 6284 6285 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6286 /// well-formednes of the conversion function declarator @p D with 6287 /// type @p R. If there are any errors in the declarator, this routine 6288 /// will emit diagnostics and return true. Otherwise, it will return 6289 /// false. Either way, the type @p R will be updated to reflect a 6290 /// well-formed type for the conversion operator. 6291 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6292 StorageClass& SC) { 6293 // C++ [class.conv.fct]p1: 6294 // Neither parameter types nor return type can be specified. The 6295 // type of a conversion function (8.3.5) is "function taking no 6296 // parameter returning conversion-type-id." 6297 if (SC == SC_Static) { 6298 if (!D.isInvalidType()) 6299 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6300 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6301 << D.getName().getSourceRange(); 6302 D.setInvalidType(); 6303 SC = SC_None; 6304 } 6305 6306 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6307 6308 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6309 // Conversion functions don't have return types, but the parser will 6310 // happily parse something like: 6311 // 6312 // class X { 6313 // float operator bool(); 6314 // }; 6315 // 6316 // The return type will be changed later anyway. 6317 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6318 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6319 << SourceRange(D.getIdentifierLoc()); 6320 D.setInvalidType(); 6321 } 6322 6323 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6324 6325 // Make sure we don't have any parameters. 6326 if (Proto->getNumArgs() > 0) { 6327 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6328 6329 // Delete the parameters. 6330 D.getFunctionTypeInfo().freeArgs(); 6331 D.setInvalidType(); 6332 } else if (Proto->isVariadic()) { 6333 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6334 D.setInvalidType(); 6335 } 6336 6337 // Diagnose "&operator bool()" and other such nonsense. This 6338 // is actually a gcc extension which we don't support. 6339 if (Proto->getResultType() != ConvType) { 6340 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6341 << Proto->getResultType(); 6342 D.setInvalidType(); 6343 ConvType = Proto->getResultType(); 6344 } 6345 6346 // C++ [class.conv.fct]p4: 6347 // The conversion-type-id shall not represent a function type nor 6348 // an array type. 6349 if (ConvType->isArrayType()) { 6350 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6351 ConvType = Context.getPointerType(ConvType); 6352 D.setInvalidType(); 6353 } else if (ConvType->isFunctionType()) { 6354 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6355 ConvType = Context.getPointerType(ConvType); 6356 D.setInvalidType(); 6357 } 6358 6359 // Rebuild the function type "R" without any parameters (in case any 6360 // of the errors above fired) and with the conversion type as the 6361 // return type. 6362 if (D.isInvalidType()) 6363 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6364 6365 // C++0x explicit conversion operators. 6366 if (D.getDeclSpec().isExplicitSpecified()) 6367 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6368 getLangOpts().CPlusPlus11 ? 6369 diag::warn_cxx98_compat_explicit_conversion_functions : 6370 diag::ext_explicit_conversion_functions) 6371 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6372 } 6373 6374 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6375 /// the declaration of the given C++ conversion function. This routine 6376 /// is responsible for recording the conversion function in the C++ 6377 /// class, if possible. 6378 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6379 assert(Conversion && "Expected to receive a conversion function declaration"); 6380 6381 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6382 6383 // Make sure we aren't redeclaring the conversion function. 6384 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6385 6386 // C++ [class.conv.fct]p1: 6387 // [...] A conversion function is never used to convert a 6388 // (possibly cv-qualified) object to the (possibly cv-qualified) 6389 // same object type (or a reference to it), to a (possibly 6390 // cv-qualified) base class of that type (or a reference to it), 6391 // or to (possibly cv-qualified) void. 6392 // FIXME: Suppress this warning if the conversion function ends up being a 6393 // virtual function that overrides a virtual function in a base class. 6394 QualType ClassType 6395 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6396 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6397 ConvType = ConvTypeRef->getPointeeType(); 6398 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6399 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6400 /* Suppress diagnostics for instantiations. */; 6401 else if (ConvType->isRecordType()) { 6402 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6403 if (ConvType == ClassType) 6404 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6405 << ClassType; 6406 else if (IsDerivedFrom(ClassType, ConvType)) 6407 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6408 << ClassType << ConvType; 6409 } else if (ConvType->isVoidType()) { 6410 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6411 << ClassType << ConvType; 6412 } 6413 6414 if (FunctionTemplateDecl *ConversionTemplate 6415 = Conversion->getDescribedFunctionTemplate()) 6416 return ConversionTemplate; 6417 6418 return Conversion; 6419 } 6420 6421 //===----------------------------------------------------------------------===// 6422 // Namespace Handling 6423 //===----------------------------------------------------------------------===// 6424 6425 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6426 /// reopened. 6427 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6428 SourceLocation Loc, 6429 IdentifierInfo *II, bool *IsInline, 6430 NamespaceDecl *PrevNS) { 6431 assert(*IsInline != PrevNS->isInline()); 6432 6433 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6434 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6435 // inline namespaces, with the intention of bringing names into namespace std. 6436 // 6437 // We support this just well enough to get that case working; this is not 6438 // sufficient to support reopening namespaces as inline in general. 6439 if (*IsInline && II && II->getName().startswith("__atomic") && 6440 S.getSourceManager().isInSystemHeader(Loc)) { 6441 // Mark all prior declarations of the namespace as inline. 6442 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6443 NS = NS->getPreviousDecl()) 6444 NS->setInline(*IsInline); 6445 // Patch up the lookup table for the containing namespace. This isn't really 6446 // correct, but it's good enough for this particular case. 6447 for (DeclContext::decl_iterator I = PrevNS->decls_begin(), 6448 E = PrevNS->decls_end(); I != E; ++I) 6449 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I)) 6450 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6451 return; 6452 } 6453 6454 if (PrevNS->isInline()) 6455 // The user probably just forgot the 'inline', so suggest that it 6456 // be added back. 6457 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6458 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6459 else 6460 S.Diag(Loc, diag::err_inline_namespace_mismatch) 6461 << IsInline; 6462 6463 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6464 *IsInline = PrevNS->isInline(); 6465 } 6466 6467 /// ActOnStartNamespaceDef - This is called at the start of a namespace 6468 /// definition. 6469 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6470 SourceLocation InlineLoc, 6471 SourceLocation NamespaceLoc, 6472 SourceLocation IdentLoc, 6473 IdentifierInfo *II, 6474 SourceLocation LBrace, 6475 AttributeList *AttrList) { 6476 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6477 // For anonymous namespace, take the location of the left brace. 6478 SourceLocation Loc = II ? IdentLoc : LBrace; 6479 bool IsInline = InlineLoc.isValid(); 6480 bool IsInvalid = false; 6481 bool IsStd = false; 6482 bool AddToKnown = false; 6483 Scope *DeclRegionScope = NamespcScope->getParent(); 6484 6485 NamespaceDecl *PrevNS = 0; 6486 if (II) { 6487 // C++ [namespace.def]p2: 6488 // The identifier in an original-namespace-definition shall not 6489 // have been previously defined in the declarative region in 6490 // which the original-namespace-definition appears. The 6491 // identifier in an original-namespace-definition is the name of 6492 // the namespace. Subsequently in that declarative region, it is 6493 // treated as an original-namespace-name. 6494 // 6495 // Since namespace names are unique in their scope, and we don't 6496 // look through using directives, just look for any ordinary names. 6497 6498 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6499 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6500 Decl::IDNS_Namespace; 6501 NamedDecl *PrevDecl = 0; 6502 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6503 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6504 ++I) { 6505 if ((*I)->getIdentifierNamespace() & IDNS) { 6506 PrevDecl = *I; 6507 break; 6508 } 6509 } 6510 6511 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6512 6513 if (PrevNS) { 6514 // This is an extended namespace definition. 6515 if (IsInline != PrevNS->isInline()) 6516 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6517 &IsInline, PrevNS); 6518 } else if (PrevDecl) { 6519 // This is an invalid name redefinition. 6520 Diag(Loc, diag::err_redefinition_different_kind) 6521 << II; 6522 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6523 IsInvalid = true; 6524 // Continue on to push Namespc as current DeclContext and return it. 6525 } else if (II->isStr("std") && 6526 CurContext->getRedeclContext()->isTranslationUnit()) { 6527 // This is the first "real" definition of the namespace "std", so update 6528 // our cache of the "std" namespace to point at this definition. 6529 PrevNS = getStdNamespace(); 6530 IsStd = true; 6531 AddToKnown = !IsInline; 6532 } else { 6533 // We've seen this namespace for the first time. 6534 AddToKnown = !IsInline; 6535 } 6536 } else { 6537 // Anonymous namespaces. 6538 6539 // Determine whether the parent already has an anonymous namespace. 6540 DeclContext *Parent = CurContext->getRedeclContext(); 6541 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6542 PrevNS = TU->getAnonymousNamespace(); 6543 } else { 6544 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6545 PrevNS = ND->getAnonymousNamespace(); 6546 } 6547 6548 if (PrevNS && IsInline != PrevNS->isInline()) 6549 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6550 &IsInline, PrevNS); 6551 } 6552 6553 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6554 StartLoc, Loc, II, PrevNS); 6555 if (IsInvalid) 6556 Namespc->setInvalidDecl(); 6557 6558 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6559 6560 // FIXME: Should we be merging attributes? 6561 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6562 PushNamespaceVisibilityAttr(Attr, Loc); 6563 6564 if (IsStd) 6565 StdNamespace = Namespc; 6566 if (AddToKnown) 6567 KnownNamespaces[Namespc] = false; 6568 6569 if (II) { 6570 PushOnScopeChains(Namespc, DeclRegionScope); 6571 } else { 6572 // Link the anonymous namespace into its parent. 6573 DeclContext *Parent = CurContext->getRedeclContext(); 6574 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6575 TU->setAnonymousNamespace(Namespc); 6576 } else { 6577 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6578 } 6579 6580 CurContext->addDecl(Namespc); 6581 6582 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6583 // behaves as if it were replaced by 6584 // namespace unique { /* empty body */ } 6585 // using namespace unique; 6586 // namespace unique { namespace-body } 6587 // where all occurrences of 'unique' in a translation unit are 6588 // replaced by the same identifier and this identifier differs 6589 // from all other identifiers in the entire program. 6590 6591 // We just create the namespace with an empty name and then add an 6592 // implicit using declaration, just like the standard suggests. 6593 // 6594 // CodeGen enforces the "universally unique" aspect by giving all 6595 // declarations semantically contained within an anonymous 6596 // namespace internal linkage. 6597 6598 if (!PrevNS) { 6599 UsingDirectiveDecl* UD 6600 = UsingDirectiveDecl::Create(Context, Parent, 6601 /* 'using' */ LBrace, 6602 /* 'namespace' */ SourceLocation(), 6603 /* qualifier */ NestedNameSpecifierLoc(), 6604 /* identifier */ SourceLocation(), 6605 Namespc, 6606 /* Ancestor */ Parent); 6607 UD->setImplicit(); 6608 Parent->addDecl(UD); 6609 } 6610 } 6611 6612 ActOnDocumentableDecl(Namespc); 6613 6614 // Although we could have an invalid decl (i.e. the namespace name is a 6615 // redefinition), push it as current DeclContext and try to continue parsing. 6616 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6617 // for the namespace has the declarations that showed up in that particular 6618 // namespace definition. 6619 PushDeclContext(NamespcScope, Namespc); 6620 return Namespc; 6621 } 6622 6623 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6624 /// is a namespace alias, returns the namespace it points to. 6625 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6626 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6627 return AD->getNamespace(); 6628 return dyn_cast_or_null<NamespaceDecl>(D); 6629 } 6630 6631 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 6632 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6633 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6634 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6635 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6636 Namespc->setRBraceLoc(RBrace); 6637 PopDeclContext(); 6638 if (Namespc->hasAttr<VisibilityAttr>()) 6639 PopPragmaVisibility(true, RBrace); 6640 } 6641 6642 CXXRecordDecl *Sema::getStdBadAlloc() const { 6643 return cast_or_null<CXXRecordDecl>( 6644 StdBadAlloc.get(Context.getExternalSource())); 6645 } 6646 6647 NamespaceDecl *Sema::getStdNamespace() const { 6648 return cast_or_null<NamespaceDecl>( 6649 StdNamespace.get(Context.getExternalSource())); 6650 } 6651 6652 /// \brief Retrieve the special "std" namespace, which may require us to 6653 /// implicitly define the namespace. 6654 NamespaceDecl *Sema::getOrCreateStdNamespace() { 6655 if (!StdNamespace) { 6656 // The "std" namespace has not yet been defined, so build one implicitly. 6657 StdNamespace = NamespaceDecl::Create(Context, 6658 Context.getTranslationUnitDecl(), 6659 /*Inline=*/false, 6660 SourceLocation(), SourceLocation(), 6661 &PP.getIdentifierTable().get("std"), 6662 /*PrevDecl=*/0); 6663 getStdNamespace()->setImplicit(true); 6664 } 6665 6666 return getStdNamespace(); 6667 } 6668 6669 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6670 assert(getLangOpts().CPlusPlus && 6671 "Looking for std::initializer_list outside of C++."); 6672 6673 // We're looking for implicit instantiations of 6674 // template <typename E> class std::initializer_list. 6675 6676 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6677 return false; 6678 6679 ClassTemplateDecl *Template = 0; 6680 const TemplateArgument *Arguments = 0; 6681 6682 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6683 6684 ClassTemplateSpecializationDecl *Specialization = 6685 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6686 if (!Specialization) 6687 return false; 6688 6689 Template = Specialization->getSpecializedTemplate(); 6690 Arguments = Specialization->getTemplateArgs().data(); 6691 } else if (const TemplateSpecializationType *TST = 6692 Ty->getAs<TemplateSpecializationType>()) { 6693 Template = dyn_cast_or_null<ClassTemplateDecl>( 6694 TST->getTemplateName().getAsTemplateDecl()); 6695 Arguments = TST->getArgs(); 6696 } 6697 if (!Template) 6698 return false; 6699 6700 if (!StdInitializerList) { 6701 // Haven't recognized std::initializer_list yet, maybe this is it. 6702 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6703 if (TemplateClass->getIdentifier() != 6704 &PP.getIdentifierTable().get("initializer_list") || 6705 !getStdNamespace()->InEnclosingNamespaceSetOf( 6706 TemplateClass->getDeclContext())) 6707 return false; 6708 // This is a template called std::initializer_list, but is it the right 6709 // template? 6710 TemplateParameterList *Params = Template->getTemplateParameters(); 6711 if (Params->getMinRequiredArguments() != 1) 6712 return false; 6713 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6714 return false; 6715 6716 // It's the right template. 6717 StdInitializerList = Template; 6718 } 6719 6720 if (Template != StdInitializerList) 6721 return false; 6722 6723 // This is an instance of std::initializer_list. Find the argument type. 6724 if (Element) 6725 *Element = Arguments[0].getAsType(); 6726 return true; 6727 } 6728 6729 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6730 NamespaceDecl *Std = S.getStdNamespace(); 6731 if (!Std) { 6732 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6733 return 0; 6734 } 6735 6736 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6737 Loc, Sema::LookupOrdinaryName); 6738 if (!S.LookupQualifiedName(Result, Std)) { 6739 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6740 return 0; 6741 } 6742 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6743 if (!Template) { 6744 Result.suppressDiagnostics(); 6745 // We found something weird. Complain about the first thing we found. 6746 NamedDecl *Found = *Result.begin(); 6747 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6748 return 0; 6749 } 6750 6751 // We found some template called std::initializer_list. Now verify that it's 6752 // correct. 6753 TemplateParameterList *Params = Template->getTemplateParameters(); 6754 if (Params->getMinRequiredArguments() != 1 || 6755 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6756 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6757 return 0; 6758 } 6759 6760 return Template; 6761 } 6762 6763 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6764 if (!StdInitializerList) { 6765 StdInitializerList = LookupStdInitializerList(*this, Loc); 6766 if (!StdInitializerList) 6767 return QualType(); 6768 } 6769 6770 TemplateArgumentListInfo Args(Loc, Loc); 6771 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6772 Context.getTrivialTypeSourceInfo(Element, 6773 Loc))); 6774 return Context.getCanonicalType( 6775 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6776 } 6777 6778 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6779 // C++ [dcl.init.list]p2: 6780 // A constructor is an initializer-list constructor if its first parameter 6781 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6782 // std::initializer_list<E> for some type E, and either there are no other 6783 // parameters or else all other parameters have default arguments. 6784 if (Ctor->getNumParams() < 1 || 6785 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6786 return false; 6787 6788 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6789 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6790 ArgType = RT->getPointeeType().getUnqualifiedType(); 6791 6792 return isStdInitializerList(ArgType, 0); 6793 } 6794 6795 /// \brief Determine whether a using statement is in a context where it will be 6796 /// apply in all contexts. 6797 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6798 switch (CurContext->getDeclKind()) { 6799 case Decl::TranslationUnit: 6800 return true; 6801 case Decl::LinkageSpec: 6802 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6803 default: 6804 return false; 6805 } 6806 } 6807 6808 namespace { 6809 6810 // Callback to only accept typo corrections that are namespaces. 6811 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6812 public: 6813 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE { 6814 if (NamedDecl *ND = candidate.getCorrectionDecl()) 6815 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6816 return false; 6817 } 6818 }; 6819 6820 } 6821 6822 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6823 CXXScopeSpec &SS, 6824 SourceLocation IdentLoc, 6825 IdentifierInfo *Ident) { 6826 NamespaceValidatorCCC Validator; 6827 R.clear(); 6828 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6829 R.getLookupKind(), Sc, &SS, 6830 Validator)) { 6831 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 6832 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6833 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 6834 Ident->getName().equals(CorrectedStr); 6835 S.diagnoseTypo(Corrected, 6836 S.PDiag(diag::err_using_directive_member_suggest) 6837 << Ident << DC << DroppedSpecifier << SS.getRange(), 6838 S.PDiag(diag::note_namespace_defined_here)); 6839 } else { 6840 S.diagnoseTypo(Corrected, 6841 S.PDiag(diag::err_using_directive_suggest) << Ident, 6842 S.PDiag(diag::note_namespace_defined_here)); 6843 } 6844 R.addDecl(Corrected.getCorrectionDecl()); 6845 return true; 6846 } 6847 return false; 6848 } 6849 6850 Decl *Sema::ActOnUsingDirective(Scope *S, 6851 SourceLocation UsingLoc, 6852 SourceLocation NamespcLoc, 6853 CXXScopeSpec &SS, 6854 SourceLocation IdentLoc, 6855 IdentifierInfo *NamespcName, 6856 AttributeList *AttrList) { 6857 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6858 assert(NamespcName && "Invalid NamespcName."); 6859 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6860 6861 // This can only happen along a recovery path. 6862 while (S->getFlags() & Scope::TemplateParamScope) 6863 S = S->getParent(); 6864 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6865 6866 UsingDirectiveDecl *UDir = 0; 6867 NestedNameSpecifier *Qualifier = 0; 6868 if (SS.isSet()) 6869 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6870 6871 // Lookup namespace name. 6872 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6873 LookupParsedName(R, S, &SS); 6874 if (R.isAmbiguous()) 6875 return 0; 6876 6877 if (R.empty()) { 6878 R.clear(); 6879 // Allow "using namespace std;" or "using namespace ::std;" even if 6880 // "std" hasn't been defined yet, for GCC compatibility. 6881 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6882 NamespcName->isStr("std")) { 6883 Diag(IdentLoc, diag::ext_using_undefined_std); 6884 R.addDecl(getOrCreateStdNamespace()); 6885 R.resolveKind(); 6886 } 6887 // Otherwise, attempt typo correction. 6888 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6889 } 6890 6891 if (!R.empty()) { 6892 NamedDecl *Named = R.getFoundDecl(); 6893 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6894 && "expected namespace decl"); 6895 // C++ [namespace.udir]p1: 6896 // A using-directive specifies that the names in the nominated 6897 // namespace can be used in the scope in which the 6898 // using-directive appears after the using-directive. During 6899 // unqualified name lookup (3.4.1), the names appear as if they 6900 // were declared in the nearest enclosing namespace which 6901 // contains both the using-directive and the nominated 6902 // namespace. [Note: in this context, "contains" means "contains 6903 // directly or indirectly". ] 6904 6905 // Find enclosing context containing both using-directive and 6906 // nominated namespace. 6907 NamespaceDecl *NS = getNamespaceDecl(Named); 6908 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6909 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6910 CommonAncestor = CommonAncestor->getParent(); 6911 6912 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6913 SS.getWithLocInContext(Context), 6914 IdentLoc, Named, CommonAncestor); 6915 6916 if (IsUsingDirectiveInToplevelContext(CurContext) && 6917 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6918 Diag(IdentLoc, diag::warn_using_directive_in_header); 6919 } 6920 6921 PushUsingDirective(S, UDir); 6922 } else { 6923 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6924 } 6925 6926 if (UDir) 6927 ProcessDeclAttributeList(S, UDir, AttrList); 6928 6929 return UDir; 6930 } 6931 6932 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 6933 // If the scope has an associated entity and the using directive is at 6934 // namespace or translation unit scope, add the UsingDirectiveDecl into 6935 // its lookup structure so qualified name lookup can find it. 6936 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()); 6937 if (Ctx && !Ctx->isFunctionOrMethod()) 6938 Ctx->addDecl(UDir); 6939 else 6940 // Otherwise, it is at block sope. The using-directives will affect lookup 6941 // only to the end of the scope. 6942 S->PushUsingDirective(UDir); 6943 } 6944 6945 6946 Decl *Sema::ActOnUsingDeclaration(Scope *S, 6947 AccessSpecifier AS, 6948 bool HasUsingKeyword, 6949 SourceLocation UsingLoc, 6950 CXXScopeSpec &SS, 6951 UnqualifiedId &Name, 6952 AttributeList *AttrList, 6953 bool HasTypenameKeyword, 6954 SourceLocation TypenameLoc) { 6955 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6956 6957 switch (Name.getKind()) { 6958 case UnqualifiedId::IK_ImplicitSelfParam: 6959 case UnqualifiedId::IK_Identifier: 6960 case UnqualifiedId::IK_OperatorFunctionId: 6961 case UnqualifiedId::IK_LiteralOperatorId: 6962 case UnqualifiedId::IK_ConversionFunctionId: 6963 break; 6964 6965 case UnqualifiedId::IK_ConstructorName: 6966 case UnqualifiedId::IK_ConstructorTemplateId: 6967 // C++11 inheriting constructors. 6968 Diag(Name.getLocStart(), 6969 getLangOpts().CPlusPlus11 ? 6970 diag::warn_cxx98_compat_using_decl_constructor : 6971 diag::err_using_decl_constructor) 6972 << SS.getRange(); 6973 6974 if (getLangOpts().CPlusPlus11) break; 6975 6976 return 0; 6977 6978 case UnqualifiedId::IK_DestructorName: 6979 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 6980 << SS.getRange(); 6981 return 0; 6982 6983 case UnqualifiedId::IK_TemplateId: 6984 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 6985 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 6986 return 0; 6987 } 6988 6989 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 6990 DeclarationName TargetName = TargetNameInfo.getName(); 6991 if (!TargetName) 6992 return 0; 6993 6994 // Warn about access declarations. 6995 if (!HasUsingKeyword) { 6996 Diag(Name.getLocStart(), 6997 getLangOpts().CPlusPlus11 ? diag::err_access_decl 6998 : diag::warn_access_decl_deprecated) 6999 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7000 } 7001 7002 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7003 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7004 return 0; 7005 7006 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7007 TargetNameInfo, AttrList, 7008 /* IsInstantiation */ false, 7009 HasTypenameKeyword, TypenameLoc); 7010 if (UD) 7011 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7012 7013 return UD; 7014 } 7015 7016 /// \brief Determine whether a using declaration considers the given 7017 /// declarations as "equivalent", e.g., if they are redeclarations of 7018 /// the same entity or are both typedefs of the same type. 7019 static bool 7020 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 7021 bool &SuppressRedeclaration) { 7022 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 7023 SuppressRedeclaration = false; 7024 return true; 7025 } 7026 7027 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7028 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) { 7029 SuppressRedeclaration = true; 7030 return Context.hasSameType(TD1->getUnderlyingType(), 7031 TD2->getUnderlyingType()); 7032 } 7033 7034 return false; 7035 } 7036 7037 7038 /// Determines whether to create a using shadow decl for a particular 7039 /// decl, given the set of decls existing prior to this using lookup. 7040 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7041 const LookupResult &Previous) { 7042 // Diagnose finding a decl which is not from a base class of the 7043 // current class. We do this now because there are cases where this 7044 // function will silently decide not to build a shadow decl, which 7045 // will pre-empt further diagnostics. 7046 // 7047 // We don't need to do this in C++0x because we do the check once on 7048 // the qualifier. 7049 // 7050 // FIXME: diagnose the following if we care enough: 7051 // struct A { int foo; }; 7052 // struct B : A { using A::foo; }; 7053 // template <class T> struct C : A {}; 7054 // template <class T> struct D : C<T> { using B::foo; } // <--- 7055 // This is invalid (during instantiation) in C++03 because B::foo 7056 // resolves to the using decl in B, which is not a base class of D<T>. 7057 // We can't diagnose it immediately because C<T> is an unknown 7058 // specialization. The UsingShadowDecl in D<T> then points directly 7059 // to A::foo, which will look well-formed when we instantiate. 7060 // The right solution is to not collapse the shadow-decl chain. 7061 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7062 DeclContext *OrigDC = Orig->getDeclContext(); 7063 7064 // Handle enums and anonymous structs. 7065 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7066 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7067 while (OrigRec->isAnonymousStructOrUnion()) 7068 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7069 7070 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7071 if (OrigDC == CurContext) { 7072 Diag(Using->getLocation(), 7073 diag::err_using_decl_nested_name_specifier_is_current_class) 7074 << Using->getQualifierLoc().getSourceRange(); 7075 Diag(Orig->getLocation(), diag::note_using_decl_target); 7076 return true; 7077 } 7078 7079 Diag(Using->getQualifierLoc().getBeginLoc(), 7080 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7081 << Using->getQualifier() 7082 << cast<CXXRecordDecl>(CurContext) 7083 << Using->getQualifierLoc().getSourceRange(); 7084 Diag(Orig->getLocation(), diag::note_using_decl_target); 7085 return true; 7086 } 7087 } 7088 7089 if (Previous.empty()) return false; 7090 7091 NamedDecl *Target = Orig; 7092 if (isa<UsingShadowDecl>(Target)) 7093 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7094 7095 // If the target happens to be one of the previous declarations, we 7096 // don't have a conflict. 7097 // 7098 // FIXME: but we might be increasing its access, in which case we 7099 // should redeclare it. 7100 NamedDecl *NonTag = 0, *Tag = 0; 7101 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7102 I != E; ++I) { 7103 NamedDecl *D = (*I)->getUnderlyingDecl(); 7104 bool Result; 7105 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 7106 return Result; 7107 7108 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7109 } 7110 7111 if (Target->isFunctionOrFunctionTemplate()) { 7112 FunctionDecl *FD; 7113 if (isa<FunctionTemplateDecl>(Target)) 7114 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 7115 else 7116 FD = cast<FunctionDecl>(Target); 7117 7118 NamedDecl *OldDecl = 0; 7119 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 7120 case Ovl_Overload: 7121 return false; 7122 7123 case Ovl_NonFunction: 7124 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7125 break; 7126 7127 // We found a decl with the exact signature. 7128 case Ovl_Match: 7129 // If we're in a record, we want to hide the target, so we 7130 // return true (without a diagnostic) to tell the caller not to 7131 // build a shadow decl. 7132 if (CurContext->isRecord()) 7133 return true; 7134 7135 // If we're not in a record, this is an error. 7136 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7137 break; 7138 } 7139 7140 Diag(Target->getLocation(), diag::note_using_decl_target); 7141 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7142 return true; 7143 } 7144 7145 // Target is not a function. 7146 7147 if (isa<TagDecl>(Target)) { 7148 // No conflict between a tag and a non-tag. 7149 if (!Tag) return false; 7150 7151 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7152 Diag(Target->getLocation(), diag::note_using_decl_target); 7153 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7154 return true; 7155 } 7156 7157 // No conflict between a tag and a non-tag. 7158 if (!NonTag) return false; 7159 7160 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7161 Diag(Target->getLocation(), diag::note_using_decl_target); 7162 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7163 return true; 7164 } 7165 7166 /// Builds a shadow declaration corresponding to a 'using' declaration. 7167 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7168 UsingDecl *UD, 7169 NamedDecl *Orig) { 7170 7171 // If we resolved to another shadow declaration, just coalesce them. 7172 NamedDecl *Target = Orig; 7173 if (isa<UsingShadowDecl>(Target)) { 7174 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7175 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7176 } 7177 7178 UsingShadowDecl *Shadow 7179 = UsingShadowDecl::Create(Context, CurContext, 7180 UD->getLocation(), UD, Target); 7181 UD->addShadowDecl(Shadow); 7182 7183 Shadow->setAccess(UD->getAccess()); 7184 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7185 Shadow->setInvalidDecl(); 7186 7187 if (S) 7188 PushOnScopeChains(Shadow, S); 7189 else 7190 CurContext->addDecl(Shadow); 7191 7192 7193 return Shadow; 7194 } 7195 7196 /// Hides a using shadow declaration. This is required by the current 7197 /// using-decl implementation when a resolvable using declaration in a 7198 /// class is followed by a declaration which would hide or override 7199 /// one or more of the using decl's targets; for example: 7200 /// 7201 /// struct Base { void foo(int); }; 7202 /// struct Derived : Base { 7203 /// using Base::foo; 7204 /// void foo(int); 7205 /// }; 7206 /// 7207 /// The governing language is C++03 [namespace.udecl]p12: 7208 /// 7209 /// When a using-declaration brings names from a base class into a 7210 /// derived class scope, member functions in the derived class 7211 /// override and/or hide member functions with the same name and 7212 /// parameter types in a base class (rather than conflicting). 7213 /// 7214 /// There are two ways to implement this: 7215 /// (1) optimistically create shadow decls when they're not hidden 7216 /// by existing declarations, or 7217 /// (2) don't create any shadow decls (or at least don't make them 7218 /// visible) until we've fully parsed/instantiated the class. 7219 /// The problem with (1) is that we might have to retroactively remove 7220 /// a shadow decl, which requires several O(n) operations because the 7221 /// decl structures are (very reasonably) not designed for removal. 7222 /// (2) avoids this but is very fiddly and phase-dependent. 7223 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7224 if (Shadow->getDeclName().getNameKind() == 7225 DeclarationName::CXXConversionFunctionName) 7226 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7227 7228 // Remove it from the DeclContext... 7229 Shadow->getDeclContext()->removeDecl(Shadow); 7230 7231 // ...and the scope, if applicable... 7232 if (S) { 7233 S->RemoveDecl(Shadow); 7234 IdResolver.RemoveDecl(Shadow); 7235 } 7236 7237 // ...and the using decl. 7238 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7239 7240 // TODO: complain somehow if Shadow was used. It shouldn't 7241 // be possible for this to happen, because...? 7242 } 7243 7244 namespace { 7245 class UsingValidatorCCC : public CorrectionCandidateCallback { 7246 public: 7247 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation) 7248 : HasTypenameKeyword(HasTypenameKeyword), 7249 IsInstantiation(IsInstantiation) {} 7250 7251 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE { 7252 NamedDecl *ND = Candidate.getCorrectionDecl(); 7253 7254 // Keywords are not valid here. 7255 if (!ND || isa<NamespaceDecl>(ND)) 7256 return false; 7257 7258 // Completely unqualified names are invalid for a 'using' declaration. 7259 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7260 return false; 7261 7262 if (isa<TypeDecl>(ND)) 7263 return HasTypenameKeyword || !IsInstantiation; 7264 7265 return !HasTypenameKeyword; 7266 } 7267 7268 private: 7269 bool HasTypenameKeyword; 7270 bool IsInstantiation; 7271 }; 7272 } // end anonymous namespace 7273 7274 /// Builds a using declaration. 7275 /// 7276 /// \param IsInstantiation - Whether this call arises from an 7277 /// instantiation of an unresolved using declaration. We treat 7278 /// the lookup differently for these declarations. 7279 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7280 SourceLocation UsingLoc, 7281 CXXScopeSpec &SS, 7282 const DeclarationNameInfo &NameInfo, 7283 AttributeList *AttrList, 7284 bool IsInstantiation, 7285 bool HasTypenameKeyword, 7286 SourceLocation TypenameLoc) { 7287 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7288 SourceLocation IdentLoc = NameInfo.getLoc(); 7289 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7290 7291 // FIXME: We ignore attributes for now. 7292 7293 if (SS.isEmpty()) { 7294 Diag(IdentLoc, diag::err_using_requires_qualname); 7295 return 0; 7296 } 7297 7298 // Do the redeclaration lookup in the current scope. 7299 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7300 ForRedeclaration); 7301 Previous.setHideTags(false); 7302 if (S) { 7303 LookupName(Previous, S); 7304 7305 // It is really dumb that we have to do this. 7306 LookupResult::Filter F = Previous.makeFilter(); 7307 while (F.hasNext()) { 7308 NamedDecl *D = F.next(); 7309 if (!isDeclInScope(D, CurContext, S)) 7310 F.erase(); 7311 } 7312 F.done(); 7313 } else { 7314 assert(IsInstantiation && "no scope in non-instantiation"); 7315 assert(CurContext->isRecord() && "scope not record in instantiation"); 7316 LookupQualifiedName(Previous, CurContext); 7317 } 7318 7319 // Check for invalid redeclarations. 7320 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7321 SS, IdentLoc, Previous)) 7322 return 0; 7323 7324 // Check for bad qualifiers. 7325 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 7326 return 0; 7327 7328 DeclContext *LookupContext = computeDeclContext(SS); 7329 NamedDecl *D; 7330 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7331 if (!LookupContext) { 7332 if (HasTypenameKeyword) { 7333 // FIXME: not all declaration name kinds are legal here 7334 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7335 UsingLoc, TypenameLoc, 7336 QualifierLoc, 7337 IdentLoc, NameInfo.getName()); 7338 } else { 7339 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7340 QualifierLoc, NameInfo); 7341 } 7342 } else { 7343 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 7344 NameInfo, HasTypenameKeyword); 7345 } 7346 D->setAccess(AS); 7347 CurContext->addDecl(D); 7348 7349 if (!LookupContext) return D; 7350 UsingDecl *UD = cast<UsingDecl>(D); 7351 7352 if (RequireCompleteDeclContext(SS, LookupContext)) { 7353 UD->setInvalidDecl(); 7354 return UD; 7355 } 7356 7357 // The normal rules do not apply to inheriting constructor declarations. 7358 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7359 if (CheckInheritingConstructorUsingDecl(UD)) 7360 UD->setInvalidDecl(); 7361 return UD; 7362 } 7363 7364 // Otherwise, look up the target name. 7365 7366 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7367 7368 // Unlike most lookups, we don't always want to hide tag 7369 // declarations: tag names are visible through the using declaration 7370 // even if hidden by ordinary names, *except* in a dependent context 7371 // where it's important for the sanity of two-phase lookup. 7372 if (!IsInstantiation) 7373 R.setHideTags(false); 7374 7375 // For the purposes of this lookup, we have a base object type 7376 // equal to that of the current context. 7377 if (CurContext->isRecord()) { 7378 R.setBaseObjectType( 7379 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7380 } 7381 7382 LookupQualifiedName(R, LookupContext); 7383 7384 // Try to correct typos if possible. 7385 if (R.empty()) { 7386 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation); 7387 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(), 7388 R.getLookupKind(), S, &SS, CCC)){ 7389 // We reject any correction for which ND would be NULL. 7390 NamedDecl *ND = Corrected.getCorrectionDecl(); 7391 R.setLookupName(Corrected.getCorrection()); 7392 R.addDecl(ND); 7393 // We reject candidates where DroppedSpecifier == true, hence the 7394 // literal '0' below. 7395 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 7396 << NameInfo.getName() << LookupContext << 0 7397 << SS.getRange()); 7398 } else { 7399 Diag(IdentLoc, diag::err_no_member) 7400 << NameInfo.getName() << LookupContext << SS.getRange(); 7401 UD->setInvalidDecl(); 7402 return UD; 7403 } 7404 } 7405 7406 if (R.isAmbiguous()) { 7407 UD->setInvalidDecl(); 7408 return UD; 7409 } 7410 7411 if (HasTypenameKeyword) { 7412 // If we asked for a typename and got a non-type decl, error out. 7413 if (!R.getAsSingle<TypeDecl>()) { 7414 Diag(IdentLoc, diag::err_using_typename_non_type); 7415 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7416 Diag((*I)->getUnderlyingDecl()->getLocation(), 7417 diag::note_using_decl_target); 7418 UD->setInvalidDecl(); 7419 return UD; 7420 } 7421 } else { 7422 // If we asked for a non-typename and we got a type, error out, 7423 // but only if this is an instantiation of an unresolved using 7424 // decl. Otherwise just silently find the type name. 7425 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7426 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7427 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7428 UD->setInvalidDecl(); 7429 return UD; 7430 } 7431 } 7432 7433 // C++0x N2914 [namespace.udecl]p6: 7434 // A using-declaration shall not name a namespace. 7435 if (R.getAsSingle<NamespaceDecl>()) { 7436 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7437 << SS.getRange(); 7438 UD->setInvalidDecl(); 7439 return UD; 7440 } 7441 7442 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7443 if (!CheckUsingShadowDecl(UD, *I, Previous)) 7444 BuildUsingShadowDecl(S, UD, *I); 7445 } 7446 7447 return UD; 7448 } 7449 7450 /// Additional checks for a using declaration referring to a constructor name. 7451 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7452 assert(!UD->hasTypename() && "expecting a constructor name"); 7453 7454 const Type *SourceType = UD->getQualifier()->getAsType(); 7455 assert(SourceType && 7456 "Using decl naming constructor doesn't have type in scope spec."); 7457 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7458 7459 // Check whether the named type is a direct base class. 7460 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 7461 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 7462 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 7463 BaseIt != BaseE; ++BaseIt) { 7464 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 7465 if (CanonicalSourceType == BaseType) 7466 break; 7467 if (BaseIt->getType()->isDependentType()) 7468 break; 7469 } 7470 7471 if (BaseIt == BaseE) { 7472 // Did not find SourceType in the bases. 7473 Diag(UD->getUsingLoc(), 7474 diag::err_using_decl_constructor_not_in_direct_base) 7475 << UD->getNameInfo().getSourceRange() 7476 << QualType(SourceType, 0) << TargetClass; 7477 return true; 7478 } 7479 7480 if (!CurContext->isDependentContext()) 7481 BaseIt->setInheritConstructors(); 7482 7483 return false; 7484 } 7485 7486 /// Checks that the given using declaration is not an invalid 7487 /// redeclaration. Note that this is checking only for the using decl 7488 /// itself, not for any ill-formedness among the UsingShadowDecls. 7489 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7490 bool HasTypenameKeyword, 7491 const CXXScopeSpec &SS, 7492 SourceLocation NameLoc, 7493 const LookupResult &Prev) { 7494 // C++03 [namespace.udecl]p8: 7495 // C++0x [namespace.udecl]p10: 7496 // A using-declaration is a declaration and can therefore be used 7497 // repeatedly where (and only where) multiple declarations are 7498 // allowed. 7499 // 7500 // That's in non-member contexts. 7501 if (!CurContext->getRedeclContext()->isRecord()) 7502 return false; 7503 7504 NestedNameSpecifier *Qual 7505 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 7506 7507 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7508 NamedDecl *D = *I; 7509 7510 bool DTypename; 7511 NestedNameSpecifier *DQual; 7512 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7513 DTypename = UD->hasTypename(); 7514 DQual = UD->getQualifier(); 7515 } else if (UnresolvedUsingValueDecl *UD 7516 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7517 DTypename = false; 7518 DQual = UD->getQualifier(); 7519 } else if (UnresolvedUsingTypenameDecl *UD 7520 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7521 DTypename = true; 7522 DQual = UD->getQualifier(); 7523 } else continue; 7524 7525 // using decls differ if one says 'typename' and the other doesn't. 7526 // FIXME: non-dependent using decls? 7527 if (HasTypenameKeyword != DTypename) continue; 7528 7529 // using decls differ if they name different scopes (but note that 7530 // template instantiation can cause this check to trigger when it 7531 // didn't before instantiation). 7532 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7533 Context.getCanonicalNestedNameSpecifier(DQual)) 7534 continue; 7535 7536 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7537 Diag(D->getLocation(), diag::note_using_decl) << 1; 7538 return true; 7539 } 7540 7541 return false; 7542 } 7543 7544 7545 /// Checks that the given nested-name qualifier used in a using decl 7546 /// in the current context is appropriately related to the current 7547 /// scope. If an error is found, diagnoses it and returns true. 7548 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7549 const CXXScopeSpec &SS, 7550 SourceLocation NameLoc) { 7551 DeclContext *NamedContext = computeDeclContext(SS); 7552 7553 if (!CurContext->isRecord()) { 7554 // C++03 [namespace.udecl]p3: 7555 // C++0x [namespace.udecl]p8: 7556 // A using-declaration for a class member shall be a member-declaration. 7557 7558 // If we weren't able to compute a valid scope, it must be a 7559 // dependent class scope. 7560 if (!NamedContext || NamedContext->isRecord()) { 7561 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7562 << SS.getRange(); 7563 return true; 7564 } 7565 7566 // Otherwise, everything is known to be fine. 7567 return false; 7568 } 7569 7570 // The current scope is a record. 7571 7572 // If the named context is dependent, we can't decide much. 7573 if (!NamedContext) { 7574 // FIXME: in C++0x, we can diagnose if we can prove that the 7575 // nested-name-specifier does not refer to a base class, which is 7576 // still possible in some cases. 7577 7578 // Otherwise we have to conservatively report that things might be 7579 // okay. 7580 return false; 7581 } 7582 7583 if (!NamedContext->isRecord()) { 7584 // Ideally this would point at the last name in the specifier, 7585 // but we don't have that level of source info. 7586 Diag(SS.getRange().getBegin(), 7587 diag::err_using_decl_nested_name_specifier_is_not_class) 7588 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 7589 return true; 7590 } 7591 7592 if (!NamedContext->isDependentContext() && 7593 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7594 return true; 7595 7596 if (getLangOpts().CPlusPlus11) { 7597 // C++0x [namespace.udecl]p3: 7598 // In a using-declaration used as a member-declaration, the 7599 // nested-name-specifier shall name a base class of the class 7600 // being defined. 7601 7602 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7603 cast<CXXRecordDecl>(NamedContext))) { 7604 if (CurContext == NamedContext) { 7605 Diag(NameLoc, 7606 diag::err_using_decl_nested_name_specifier_is_current_class) 7607 << SS.getRange(); 7608 return true; 7609 } 7610 7611 Diag(SS.getRange().getBegin(), 7612 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7613 << (NestedNameSpecifier*) SS.getScopeRep() 7614 << cast<CXXRecordDecl>(CurContext) 7615 << SS.getRange(); 7616 return true; 7617 } 7618 7619 return false; 7620 } 7621 7622 // C++03 [namespace.udecl]p4: 7623 // A using-declaration used as a member-declaration shall refer 7624 // to a member of a base class of the class being defined [etc.]. 7625 7626 // Salient point: SS doesn't have to name a base class as long as 7627 // lookup only finds members from base classes. Therefore we can 7628 // diagnose here only if we can prove that that can't happen, 7629 // i.e. if the class hierarchies provably don't intersect. 7630 7631 // TODO: it would be nice if "definitely valid" results were cached 7632 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7633 // need to be repeated. 7634 7635 struct UserData { 7636 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7637 7638 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7639 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7640 Data->Bases.insert(Base); 7641 return true; 7642 } 7643 7644 bool hasDependentBases(const CXXRecordDecl *Class) { 7645 return !Class->forallBases(collect, this); 7646 } 7647 7648 /// Returns true if the base is dependent or is one of the 7649 /// accumulated base classes. 7650 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7651 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7652 return !Data->Bases.count(Base); 7653 } 7654 7655 bool mightShareBases(const CXXRecordDecl *Class) { 7656 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7657 } 7658 }; 7659 7660 UserData Data; 7661 7662 // Returns false if we find a dependent base. 7663 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7664 return false; 7665 7666 // Returns false if the class has a dependent base or if it or one 7667 // of its bases is present in the base set of the current context. 7668 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7669 return false; 7670 7671 Diag(SS.getRange().getBegin(), 7672 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7673 << (NestedNameSpecifier*) SS.getScopeRep() 7674 << cast<CXXRecordDecl>(CurContext) 7675 << SS.getRange(); 7676 7677 return true; 7678 } 7679 7680 Decl *Sema::ActOnAliasDeclaration(Scope *S, 7681 AccessSpecifier AS, 7682 MultiTemplateParamsArg TemplateParamLists, 7683 SourceLocation UsingLoc, 7684 UnqualifiedId &Name, 7685 AttributeList *AttrList, 7686 TypeResult Type) { 7687 // Skip up to the relevant declaration scope. 7688 while (S->getFlags() & Scope::TemplateParamScope) 7689 S = S->getParent(); 7690 assert((S->getFlags() & Scope::DeclScope) && 7691 "got alias-declaration outside of declaration scope"); 7692 7693 if (Type.isInvalid()) 7694 return 0; 7695 7696 bool Invalid = false; 7697 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7698 TypeSourceInfo *TInfo = 0; 7699 GetTypeFromParser(Type.get(), &TInfo); 7700 7701 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7702 return 0; 7703 7704 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7705 UPPC_DeclarationType)) { 7706 Invalid = true; 7707 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7708 TInfo->getTypeLoc().getBeginLoc()); 7709 } 7710 7711 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7712 LookupName(Previous, S); 7713 7714 // Warn about shadowing the name of a template parameter. 7715 if (Previous.isSingleResult() && 7716 Previous.getFoundDecl()->isTemplateParameter()) { 7717 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7718 Previous.clear(); 7719 } 7720 7721 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7722 "name in alias declaration must be an identifier"); 7723 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7724 Name.StartLocation, 7725 Name.Identifier, TInfo); 7726 7727 NewTD->setAccess(AS); 7728 7729 if (Invalid) 7730 NewTD->setInvalidDecl(); 7731 7732 ProcessDeclAttributeList(S, NewTD, AttrList); 7733 7734 CheckTypedefForVariablyModifiedType(S, NewTD); 7735 Invalid |= NewTD->isInvalidDecl(); 7736 7737 bool Redeclaration = false; 7738 7739 NamedDecl *NewND; 7740 if (TemplateParamLists.size()) { 7741 TypeAliasTemplateDecl *OldDecl = 0; 7742 TemplateParameterList *OldTemplateParams = 0; 7743 7744 if (TemplateParamLists.size() != 1) { 7745 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7746 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7747 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7748 } 7749 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7750 7751 // Only consider previous declarations in the same scope. 7752 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7753 /*ExplicitInstantiationOrSpecialization*/false); 7754 if (!Previous.empty()) { 7755 Redeclaration = true; 7756 7757 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7758 if (!OldDecl && !Invalid) { 7759 Diag(UsingLoc, diag::err_redefinition_different_kind) 7760 << Name.Identifier; 7761 7762 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7763 if (OldD->getLocation().isValid()) 7764 Diag(OldD->getLocation(), diag::note_previous_definition); 7765 7766 Invalid = true; 7767 } 7768 7769 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7770 if (TemplateParameterListsAreEqual(TemplateParams, 7771 OldDecl->getTemplateParameters(), 7772 /*Complain=*/true, 7773 TPL_TemplateMatch)) 7774 OldTemplateParams = OldDecl->getTemplateParameters(); 7775 else 7776 Invalid = true; 7777 7778 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7779 if (!Invalid && 7780 !Context.hasSameType(OldTD->getUnderlyingType(), 7781 NewTD->getUnderlyingType())) { 7782 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7783 // but we can't reasonably accept it. 7784 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7785 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7786 if (OldTD->getLocation().isValid()) 7787 Diag(OldTD->getLocation(), diag::note_previous_definition); 7788 Invalid = true; 7789 } 7790 } 7791 } 7792 7793 // Merge any previous default template arguments into our parameters, 7794 // and check the parameter list. 7795 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7796 TPC_TypeAliasTemplate)) 7797 return 0; 7798 7799 TypeAliasTemplateDecl *NewDecl = 7800 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7801 Name.Identifier, TemplateParams, 7802 NewTD); 7803 7804 NewDecl->setAccess(AS); 7805 7806 if (Invalid) 7807 NewDecl->setInvalidDecl(); 7808 else if (OldDecl) 7809 NewDecl->setPreviousDeclaration(OldDecl); 7810 7811 NewND = NewDecl; 7812 } else { 7813 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7814 NewND = NewTD; 7815 } 7816 7817 if (!Redeclaration) 7818 PushOnScopeChains(NewND, S); 7819 7820 ActOnDocumentableDecl(NewND); 7821 return NewND; 7822 } 7823 7824 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7825 SourceLocation NamespaceLoc, 7826 SourceLocation AliasLoc, 7827 IdentifierInfo *Alias, 7828 CXXScopeSpec &SS, 7829 SourceLocation IdentLoc, 7830 IdentifierInfo *Ident) { 7831 7832 // Lookup the namespace name. 7833 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7834 LookupParsedName(R, S, &SS); 7835 7836 // Check if we have a previous declaration with the same name. 7837 NamedDecl *PrevDecl 7838 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7839 ForRedeclaration); 7840 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7841 PrevDecl = 0; 7842 7843 if (PrevDecl) { 7844 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7845 // We already have an alias with the same name that points to the same 7846 // namespace, so don't create a new one. 7847 // FIXME: At some point, we'll want to create the (redundant) 7848 // declaration to maintain better source information. 7849 if (!R.isAmbiguous() && !R.empty() && 7850 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7851 return 0; 7852 } 7853 7854 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7855 diag::err_redefinition_different_kind; 7856 Diag(AliasLoc, DiagID) << Alias; 7857 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7858 return 0; 7859 } 7860 7861 if (R.isAmbiguous()) 7862 return 0; 7863 7864 if (R.empty()) { 7865 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 7866 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7867 return 0; 7868 } 7869 } 7870 7871 NamespaceAliasDecl *AliasDecl = 7872 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 7873 Alias, SS.getWithLocInContext(Context), 7874 IdentLoc, R.getFoundDecl()); 7875 7876 PushOnScopeChains(AliasDecl, S); 7877 return AliasDecl; 7878 } 7879 7880 Sema::ImplicitExceptionSpecification 7881 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 7882 CXXMethodDecl *MD) { 7883 CXXRecordDecl *ClassDecl = MD->getParent(); 7884 7885 // C++ [except.spec]p14: 7886 // An implicitly declared special member function (Clause 12) shall have an 7887 // exception-specification. [...] 7888 ImplicitExceptionSpecification ExceptSpec(*this); 7889 if (ClassDecl->isInvalidDecl()) 7890 return ExceptSpec; 7891 7892 // Direct base-class constructors. 7893 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7894 BEnd = ClassDecl->bases_end(); 7895 B != BEnd; ++B) { 7896 if (B->isVirtual()) // Handled below. 7897 continue; 7898 7899 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7900 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7901 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7902 // If this is a deleted function, add it anyway. This might be conformant 7903 // with the standard. This might not. I'm not sure. It might not matter. 7904 if (Constructor) 7905 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7906 } 7907 } 7908 7909 // Virtual base-class constructors. 7910 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 7911 BEnd = ClassDecl->vbases_end(); 7912 B != BEnd; ++B) { 7913 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7914 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7915 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7916 // If this is a deleted function, add it anyway. This might be conformant 7917 // with the standard. This might not. I'm not sure. It might not matter. 7918 if (Constructor) 7919 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7920 } 7921 } 7922 7923 // Field constructors. 7924 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 7925 FEnd = ClassDecl->field_end(); 7926 F != FEnd; ++F) { 7927 if (F->hasInClassInitializer()) { 7928 if (Expr *E = F->getInClassInitializer()) 7929 ExceptSpec.CalledExpr(E); 7930 else if (!F->isInvalidDecl()) 7931 // DR1351: 7932 // If the brace-or-equal-initializer of a non-static data member 7933 // invokes a defaulted default constructor of its class or of an 7934 // enclosing class in a potentially evaluated subexpression, the 7935 // program is ill-formed. 7936 // 7937 // This resolution is unworkable: the exception specification of the 7938 // default constructor can be needed in an unevaluated context, in 7939 // particular, in the operand of a noexcept-expression, and we can be 7940 // unable to compute an exception specification for an enclosed class. 7941 // 7942 // We do not allow an in-class initializer to require the evaluation 7943 // of the exception specification for any in-class initializer whose 7944 // definition is not lexically complete. 7945 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 7946 } else if (const RecordType *RecordTy 7947 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 7948 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7949 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 7950 // If this is a deleted function, add it anyway. This might be conformant 7951 // with the standard. This might not. I'm not sure. It might not matter. 7952 // In particular, the problem is that this function never gets called. It 7953 // might just be ill-formed because this function attempts to refer to 7954 // a deleted function here. 7955 if (Constructor) 7956 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 7957 } 7958 } 7959 7960 return ExceptSpec; 7961 } 7962 7963 Sema::ImplicitExceptionSpecification 7964 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 7965 CXXRecordDecl *ClassDecl = CD->getParent(); 7966 7967 // C++ [except.spec]p14: 7968 // An inheriting constructor [...] shall have an exception-specification. [...] 7969 ImplicitExceptionSpecification ExceptSpec(*this); 7970 if (ClassDecl->isInvalidDecl()) 7971 return ExceptSpec; 7972 7973 // Inherited constructor. 7974 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 7975 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 7976 // FIXME: Copying or moving the parameters could add extra exceptions to the 7977 // set, as could the default arguments for the inherited constructor. This 7978 // will be addressed when we implement the resolution of core issue 1351. 7979 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 7980 7981 // Direct base-class constructors. 7982 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 7983 BEnd = ClassDecl->bases_end(); 7984 B != BEnd; ++B) { 7985 if (B->isVirtual()) // Handled below. 7986 continue; 7987 7988 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 7989 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7990 if (BaseClassDecl == InheritedDecl) 7991 continue; 7992 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 7993 if (Constructor) 7994 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 7995 } 7996 } 7997 7998 // Virtual base-class constructors. 7999 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8000 BEnd = ClassDecl->vbases_end(); 8001 B != BEnd; ++B) { 8002 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 8003 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8004 if (BaseClassDecl == InheritedDecl) 8005 continue; 8006 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8007 if (Constructor) 8008 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 8009 } 8010 } 8011 8012 // Field constructors. 8013 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8014 FEnd = ClassDecl->field_end(); 8015 F != FEnd; ++F) { 8016 if (F->hasInClassInitializer()) { 8017 if (Expr *E = F->getInClassInitializer()) 8018 ExceptSpec.CalledExpr(E); 8019 else if (!F->isInvalidDecl()) 8020 Diag(CD->getLocation(), 8021 diag::err_in_class_initializer_references_def_ctor) << CD; 8022 } else if (const RecordType *RecordTy 8023 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8024 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8025 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8026 if (Constructor) 8027 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8028 } 8029 } 8030 8031 return ExceptSpec; 8032 } 8033 8034 namespace { 8035 /// RAII object to register a special member as being currently declared. 8036 struct DeclaringSpecialMember { 8037 Sema &S; 8038 Sema::SpecialMemberDecl D; 8039 bool WasAlreadyBeingDeclared; 8040 8041 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8042 : S(S), D(RD, CSM) { 8043 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 8044 if (WasAlreadyBeingDeclared) 8045 // This almost never happens, but if it does, ensure that our cache 8046 // doesn't contain a stale result. 8047 S.SpecialMemberCache.clear(); 8048 8049 // FIXME: Register a note to be produced if we encounter an error while 8050 // declaring the special member. 8051 } 8052 ~DeclaringSpecialMember() { 8053 if (!WasAlreadyBeingDeclared) 8054 S.SpecialMembersBeingDeclared.erase(D); 8055 } 8056 8057 /// \brief Are we already trying to declare this special member? 8058 bool isAlreadyBeingDeclared() const { 8059 return WasAlreadyBeingDeclared; 8060 } 8061 }; 8062 } 8063 8064 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8065 CXXRecordDecl *ClassDecl) { 8066 // C++ [class.ctor]p5: 8067 // A default constructor for a class X is a constructor of class X 8068 // that can be called without an argument. If there is no 8069 // user-declared constructor for class X, a default constructor is 8070 // implicitly declared. An implicitly-declared default constructor 8071 // is an inline public member of its class. 8072 assert(ClassDecl->needsImplicitDefaultConstructor() && 8073 "Should not build implicit default constructor!"); 8074 8075 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8076 if (DSM.isAlreadyBeingDeclared()) 8077 return 0; 8078 8079 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8080 CXXDefaultConstructor, 8081 false); 8082 8083 // Create the actual constructor declaration. 8084 CanQualType ClassType 8085 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8086 SourceLocation ClassLoc = ClassDecl->getLocation(); 8087 DeclarationName Name 8088 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8089 DeclarationNameInfo NameInfo(Name, ClassLoc); 8090 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8091 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 8092 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8093 Constexpr); 8094 DefaultCon->setAccess(AS_public); 8095 DefaultCon->setDefaulted(); 8096 DefaultCon->setImplicit(); 8097 8098 // Build an exception specification pointing back at this constructor. 8099 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8100 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8101 8102 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8103 // constructors is easy to compute. 8104 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8105 8106 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8107 SetDeclDeleted(DefaultCon, ClassLoc); 8108 8109 // Note that we have declared this constructor. 8110 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8111 8112 if (Scope *S = getScopeForContext(ClassDecl)) 8113 PushOnScopeChains(DefaultCon, S, false); 8114 ClassDecl->addDecl(DefaultCon); 8115 8116 return DefaultCon; 8117 } 8118 8119 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8120 CXXConstructorDecl *Constructor) { 8121 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8122 !Constructor->doesThisDeclarationHaveABody() && 8123 !Constructor->isDeleted()) && 8124 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8125 8126 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8127 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8128 8129 SynthesizedFunctionScope Scope(*this, Constructor); 8130 DiagnosticErrorTrap Trap(Diags); 8131 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8132 Trap.hasErrorOccurred()) { 8133 Diag(CurrentLocation, diag::note_member_synthesized_at) 8134 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8135 Constructor->setInvalidDecl(); 8136 return; 8137 } 8138 8139 SourceLocation Loc = Constructor->getLocation(); 8140 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8141 8142 Constructor->markUsed(Context); 8143 MarkVTableUsed(CurrentLocation, ClassDecl); 8144 8145 if (ASTMutationListener *L = getASTMutationListener()) { 8146 L->CompletedImplicitDefinition(Constructor); 8147 } 8148 } 8149 8150 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8151 // Check that any explicitly-defaulted methods have exception specifications 8152 // compatible with their implicit exception specifications. 8153 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs(); 8154 8155 // Once all the member initializers are processed, perform checks to see if 8156 // any unintialized use is happeneing. 8157 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, 8158 D->getLocation()) 8159 == DiagnosticsEngine::Ignored) 8160 return; 8161 8162 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D); 8163 if (!RD) return; 8164 8165 // Holds fields that are uninitialized. 8166 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 8167 8168 // In the beginning, every field is uninitialized. 8169 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end(); 8170 I != E; ++I) { 8171 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) { 8172 UninitializedFields.insert(FD); 8173 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) { 8174 UninitializedFields.insert(IFD->getAnonField()); 8175 } 8176 } 8177 8178 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end(); 8179 I != E; ++I) { 8180 FieldDecl *FD = dyn_cast<FieldDecl>(*I); 8181 if (!FD) 8182 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) 8183 FD = IFD->getAnonField(); 8184 8185 if (!FD) 8186 continue; 8187 8188 Expr *InitExpr = FD->getInClassInitializer(); 8189 if (!InitExpr) { 8190 // Uninitialized reference types will give an error. 8191 // Record types with an initializer are default initialized. 8192 QualType FieldType = FD->getType(); 8193 if (FieldType->isReferenceType() || FieldType->isRecordType()) 8194 UninitializedFields.erase(FD); 8195 continue; 8196 } 8197 8198 CheckInitExprContainsUninitializedFields( 8199 *this, InitExpr, FD, UninitializedFields, 8200 UninitializedFields.count(FD)/*WarnOnSelfReference*/); 8201 8202 UninitializedFields.erase(FD); 8203 } 8204 } 8205 8206 namespace { 8207 /// Information on inheriting constructors to declare. 8208 class InheritingConstructorInfo { 8209 public: 8210 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8211 : SemaRef(SemaRef), Derived(Derived) { 8212 // Mark the constructors that we already have in the derived class. 8213 // 8214 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8215 // unless there is a user-declared constructor with the same signature in 8216 // the class where the using-declaration appears. 8217 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8218 } 8219 8220 void inheritAll(CXXRecordDecl *RD) { 8221 visitAll(RD, &InheritingConstructorInfo::inherit); 8222 } 8223 8224 private: 8225 /// Information about an inheriting constructor. 8226 struct InheritingConstructor { 8227 InheritingConstructor() 8228 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {} 8229 8230 /// If \c true, a constructor with this signature is already declared 8231 /// in the derived class. 8232 bool DeclaredInDerived; 8233 8234 /// The constructor which is inherited. 8235 const CXXConstructorDecl *BaseCtor; 8236 8237 /// The derived constructor we declared. 8238 CXXConstructorDecl *DerivedCtor; 8239 }; 8240 8241 /// Inheriting constructors with a given canonical type. There can be at 8242 /// most one such non-template constructor, and any number of templated 8243 /// constructors. 8244 struct InheritingConstructorsForType { 8245 InheritingConstructor NonTemplate; 8246 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8247 Templates; 8248 8249 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8250 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8251 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8252 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8253 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8254 false, S.TPL_TemplateMatch)) 8255 return Templates[I].second; 8256 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8257 return Templates.back().second; 8258 } 8259 8260 return NonTemplate; 8261 } 8262 }; 8263 8264 /// Get or create the inheriting constructor record for a constructor. 8265 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8266 QualType CtorType) { 8267 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8268 .getEntry(SemaRef, Ctor); 8269 } 8270 8271 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8272 8273 /// Process all constructors for a class. 8274 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8275 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(), 8276 CtorE = RD->ctor_end(); 8277 CtorIt != CtorE; ++CtorIt) 8278 (this->*Callback)(*CtorIt); 8279 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8280 I(RD->decls_begin()), E(RD->decls_end()); 8281 I != E; ++I) { 8282 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8283 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8284 (this->*Callback)(CD); 8285 } 8286 } 8287 8288 /// Note that a constructor (or constructor template) was declared in Derived. 8289 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8290 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8291 } 8292 8293 /// Inherit a single constructor. 8294 void inherit(const CXXConstructorDecl *Ctor) { 8295 const FunctionProtoType *CtorType = 8296 Ctor->getType()->castAs<FunctionProtoType>(); 8297 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes()); 8298 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8299 8300 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8301 8302 // Core issue (no number yet): the ellipsis is always discarded. 8303 if (EPI.Variadic) { 8304 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8305 SemaRef.Diag(Ctor->getLocation(), 8306 diag::note_using_decl_constructor_ellipsis); 8307 EPI.Variadic = false; 8308 } 8309 8310 // Declare a constructor for each number of parameters. 8311 // 8312 // C++11 [class.inhctor]p1: 8313 // The candidate set of inherited constructors from the class X named in 8314 // the using-declaration consists of [... modulo defects ...] for each 8315 // constructor or constructor template of X, the set of constructors or 8316 // constructor templates that results from omitting any ellipsis parameter 8317 // specification and successively omitting parameters with a default 8318 // argument from the end of the parameter-type-list 8319 unsigned MinParams = minParamsToInherit(Ctor); 8320 unsigned Params = Ctor->getNumParams(); 8321 if (Params >= MinParams) { 8322 do 8323 declareCtor(UsingLoc, Ctor, 8324 SemaRef.Context.getFunctionType( 8325 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI)); 8326 while (Params > MinParams && 8327 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8328 } 8329 } 8330 8331 /// Find the using-declaration which specified that we should inherit the 8332 /// constructors of \p Base. 8333 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8334 // No fancy lookup required; just look for the base constructor name 8335 // directly within the derived class. 8336 ASTContext &Context = SemaRef.Context; 8337 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8338 Context.getCanonicalType(Context.getRecordType(Base))); 8339 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8340 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8341 } 8342 8343 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8344 // C++11 [class.inhctor]p3: 8345 // [F]or each constructor template in the candidate set of inherited 8346 // constructors, a constructor template is implicitly declared 8347 if (Ctor->getDescribedFunctionTemplate()) 8348 return 0; 8349 8350 // For each non-template constructor in the candidate set of inherited 8351 // constructors other than a constructor having no parameters or a 8352 // copy/move constructor having a single parameter, a constructor is 8353 // implicitly declared [...] 8354 if (Ctor->getNumParams() == 0) 8355 return 1; 8356 if (Ctor->isCopyOrMoveConstructor()) 8357 return 2; 8358 8359 // Per discussion on core reflector, never inherit a constructor which 8360 // would become a default, copy, or move constructor of Derived either. 8361 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8362 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8363 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8364 } 8365 8366 /// Declare a single inheriting constructor, inheriting the specified 8367 /// constructor, with the given type. 8368 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8369 QualType DerivedType) { 8370 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8371 8372 // C++11 [class.inhctor]p3: 8373 // ... a constructor is implicitly declared with the same constructor 8374 // characteristics unless there is a user-declared constructor with 8375 // the same signature in the class where the using-declaration appears 8376 if (Entry.DeclaredInDerived) 8377 return; 8378 8379 // C++11 [class.inhctor]p7: 8380 // If two using-declarations declare inheriting constructors with the 8381 // same signature, the program is ill-formed 8382 if (Entry.DerivedCtor) { 8383 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8384 // Only diagnose this once per constructor. 8385 if (Entry.DerivedCtor->isInvalidDecl()) 8386 return; 8387 Entry.DerivedCtor->setInvalidDecl(); 8388 8389 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8390 SemaRef.Diag(BaseCtor->getLocation(), 8391 diag::note_using_decl_constructor_conflict_current_ctor); 8392 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8393 diag::note_using_decl_constructor_conflict_previous_ctor); 8394 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8395 diag::note_using_decl_constructor_conflict_previous_using); 8396 } else { 8397 // Core issue (no number): if the same inheriting constructor is 8398 // produced by multiple base class constructors from the same base 8399 // class, the inheriting constructor is defined as deleted. 8400 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8401 } 8402 8403 return; 8404 } 8405 8406 ASTContext &Context = SemaRef.Context; 8407 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8408 Context.getCanonicalType(Context.getRecordType(Derived))); 8409 DeclarationNameInfo NameInfo(Name, UsingLoc); 8410 8411 TemplateParameterList *TemplateParams = 0; 8412 if (const FunctionTemplateDecl *FTD = 8413 BaseCtor->getDescribedFunctionTemplate()) { 8414 TemplateParams = FTD->getTemplateParameters(); 8415 // We're reusing template parameters from a different DeclContext. This 8416 // is questionable at best, but works out because the template depth in 8417 // both places is guaranteed to be 0. 8418 // FIXME: Rebuild the template parameters in the new context, and 8419 // transform the function type to refer to them. 8420 } 8421 8422 // Build type source info pointing at the using-declaration. This is 8423 // required by template instantiation. 8424 TypeSourceInfo *TInfo = 8425 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8426 FunctionProtoTypeLoc ProtoLoc = 8427 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8428 8429 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8430 Context, Derived, UsingLoc, NameInfo, DerivedType, 8431 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8432 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8433 8434 // Build an unevaluated exception specification for this constructor. 8435 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8436 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8437 EPI.ExceptionSpecType = EST_Unevaluated; 8438 EPI.ExceptionSpecDecl = DerivedCtor; 8439 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(), 8440 FPT->getArgTypes(), EPI)); 8441 8442 // Build the parameter declarations. 8443 SmallVector<ParmVarDecl *, 16> ParamDecls; 8444 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) { 8445 TypeSourceInfo *TInfo = 8446 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc); 8447 ParmVarDecl *PD = ParmVarDecl::Create( 8448 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0, 8449 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0); 8450 PD->setScopeInfo(0, I); 8451 PD->setImplicit(); 8452 ParamDecls.push_back(PD); 8453 ProtoLoc.setArg(I, PD); 8454 } 8455 8456 // Set up the new constructor. 8457 DerivedCtor->setAccess(BaseCtor->getAccess()); 8458 DerivedCtor->setParams(ParamDecls); 8459 DerivedCtor->setInheritedConstructor(BaseCtor); 8460 if (BaseCtor->isDeleted()) 8461 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8462 8463 // If this is a constructor template, build the template declaration. 8464 if (TemplateParams) { 8465 FunctionTemplateDecl *DerivedTemplate = 8466 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8467 TemplateParams, DerivedCtor); 8468 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8469 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8470 Derived->addDecl(DerivedTemplate); 8471 } else { 8472 Derived->addDecl(DerivedCtor); 8473 } 8474 8475 Entry.BaseCtor = BaseCtor; 8476 Entry.DerivedCtor = DerivedCtor; 8477 } 8478 8479 Sema &SemaRef; 8480 CXXRecordDecl *Derived; 8481 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8482 MapType Map; 8483 }; 8484 } 8485 8486 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8487 // Defer declaring the inheriting constructors until the class is 8488 // instantiated. 8489 if (ClassDecl->isDependentContext()) 8490 return; 8491 8492 // Find base classes from which we might inherit constructors. 8493 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8494 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 8495 BaseE = ClassDecl->bases_end(); 8496 BaseIt != BaseE; ++BaseIt) 8497 if (BaseIt->getInheritConstructors()) 8498 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl()); 8499 8500 // Go no further if we're not inheriting any constructors. 8501 if (InheritedBases.empty()) 8502 return; 8503 8504 // Declare the inherited constructors. 8505 InheritingConstructorInfo ICI(*this, ClassDecl); 8506 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8507 ICI.inheritAll(InheritedBases[I]); 8508 } 8509 8510 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8511 CXXConstructorDecl *Constructor) { 8512 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8513 assert(Constructor->getInheritedConstructor() && 8514 !Constructor->doesThisDeclarationHaveABody() && 8515 !Constructor->isDeleted()); 8516 8517 SynthesizedFunctionScope Scope(*this, Constructor); 8518 DiagnosticErrorTrap Trap(Diags); 8519 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8520 Trap.hasErrorOccurred()) { 8521 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8522 << Context.getTagDeclType(ClassDecl); 8523 Constructor->setInvalidDecl(); 8524 return; 8525 } 8526 8527 SourceLocation Loc = Constructor->getLocation(); 8528 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8529 8530 Constructor->markUsed(Context); 8531 MarkVTableUsed(CurrentLocation, ClassDecl); 8532 8533 if (ASTMutationListener *L = getASTMutationListener()) { 8534 L->CompletedImplicitDefinition(Constructor); 8535 } 8536 } 8537 8538 8539 Sema::ImplicitExceptionSpecification 8540 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8541 CXXRecordDecl *ClassDecl = MD->getParent(); 8542 8543 // C++ [except.spec]p14: 8544 // An implicitly declared special member function (Clause 12) shall have 8545 // an exception-specification. 8546 ImplicitExceptionSpecification ExceptSpec(*this); 8547 if (ClassDecl->isInvalidDecl()) 8548 return ExceptSpec; 8549 8550 // Direct base-class destructors. 8551 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 8552 BEnd = ClassDecl->bases_end(); 8553 B != BEnd; ++B) { 8554 if (B->isVirtual()) // Handled below. 8555 continue; 8556 8557 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8558 ExceptSpec.CalledDecl(B->getLocStart(), 8559 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8560 } 8561 8562 // Virtual base-class destructors. 8563 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 8564 BEnd = ClassDecl->vbases_end(); 8565 B != BEnd; ++B) { 8566 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 8567 ExceptSpec.CalledDecl(B->getLocStart(), 8568 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8569 } 8570 8571 // Field destructors. 8572 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 8573 FEnd = ClassDecl->field_end(); 8574 F != FEnd; ++F) { 8575 if (const RecordType *RecordTy 8576 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8577 ExceptSpec.CalledDecl(F->getLocation(), 8578 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8579 } 8580 8581 return ExceptSpec; 8582 } 8583 8584 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8585 // C++ [class.dtor]p2: 8586 // If a class has no user-declared destructor, a destructor is 8587 // declared implicitly. An implicitly-declared destructor is an 8588 // inline public member of its class. 8589 assert(ClassDecl->needsImplicitDestructor()); 8590 8591 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8592 if (DSM.isAlreadyBeingDeclared()) 8593 return 0; 8594 8595 // Create the actual destructor declaration. 8596 CanQualType ClassType 8597 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8598 SourceLocation ClassLoc = ClassDecl->getLocation(); 8599 DeclarationName Name 8600 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8601 DeclarationNameInfo NameInfo(Name, ClassLoc); 8602 CXXDestructorDecl *Destructor 8603 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8604 QualType(), 0, /*isInline=*/true, 8605 /*isImplicitlyDeclared=*/true); 8606 Destructor->setAccess(AS_public); 8607 Destructor->setDefaulted(); 8608 Destructor->setImplicit(); 8609 8610 // Build an exception specification pointing back at this destructor. 8611 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 8612 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8613 8614 AddOverriddenMethods(ClassDecl, Destructor); 8615 8616 // We don't need to use SpecialMemberIsTrivial here; triviality for 8617 // destructors is easy to compute. 8618 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8619 8620 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8621 SetDeclDeleted(Destructor, ClassLoc); 8622 8623 // Note that we have declared this destructor. 8624 ++ASTContext::NumImplicitDestructorsDeclared; 8625 8626 // Introduce this destructor into its scope. 8627 if (Scope *S = getScopeForContext(ClassDecl)) 8628 PushOnScopeChains(Destructor, S, false); 8629 ClassDecl->addDecl(Destructor); 8630 8631 return Destructor; 8632 } 8633 8634 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8635 CXXDestructorDecl *Destructor) { 8636 assert((Destructor->isDefaulted() && 8637 !Destructor->doesThisDeclarationHaveABody() && 8638 !Destructor->isDeleted()) && 8639 "DefineImplicitDestructor - call it for implicit default dtor"); 8640 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8641 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8642 8643 if (Destructor->isInvalidDecl()) 8644 return; 8645 8646 SynthesizedFunctionScope Scope(*this, Destructor); 8647 8648 DiagnosticErrorTrap Trap(Diags); 8649 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8650 Destructor->getParent()); 8651 8652 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8653 Diag(CurrentLocation, diag::note_member_synthesized_at) 8654 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8655 8656 Destructor->setInvalidDecl(); 8657 return; 8658 } 8659 8660 SourceLocation Loc = Destructor->getLocation(); 8661 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8662 Destructor->markUsed(Context); 8663 MarkVTableUsed(CurrentLocation, ClassDecl); 8664 8665 if (ASTMutationListener *L = getASTMutationListener()) { 8666 L->CompletedImplicitDefinition(Destructor); 8667 } 8668 } 8669 8670 /// \brief Perform any semantic analysis which needs to be delayed until all 8671 /// pending class member declarations have been parsed. 8672 void Sema::ActOnFinishCXXMemberDecls() { 8673 // If the context is an invalid C++ class, just suppress these checks. 8674 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8675 if (Record->isInvalidDecl()) { 8676 DelayedDestructorExceptionSpecChecks.clear(); 8677 return; 8678 } 8679 } 8680 8681 // Perform any deferred checking of exception specifications for virtual 8682 // destructors. 8683 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size(); 8684 i != e; ++i) { 8685 const CXXDestructorDecl *Dtor = 8686 DelayedDestructorExceptionSpecChecks[i].first; 8687 assert(!Dtor->getParent()->isDependentType() && 8688 "Should not ever add destructors of templates into the list."); 8689 CheckOverridingFunctionExceptionSpec(Dtor, 8690 DelayedDestructorExceptionSpecChecks[i].second); 8691 } 8692 DelayedDestructorExceptionSpecChecks.clear(); 8693 } 8694 8695 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8696 CXXDestructorDecl *Destructor) { 8697 assert(getLangOpts().CPlusPlus11 && 8698 "adjusting dtor exception specs was introduced in c++11"); 8699 8700 // C++11 [class.dtor]p3: 8701 // A declaration of a destructor that does not have an exception- 8702 // specification is implicitly considered to have the same exception- 8703 // specification as an implicit declaration. 8704 const FunctionProtoType *DtorType = Destructor->getType()-> 8705 getAs<FunctionProtoType>(); 8706 if (DtorType->hasExceptionSpec()) 8707 return; 8708 8709 // Replace the destructor's type, building off the existing one. Fortunately, 8710 // the only thing of interest in the destructor type is its extended info. 8711 // The return and arguments are fixed. 8712 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8713 EPI.ExceptionSpecType = EST_Unevaluated; 8714 EPI.ExceptionSpecDecl = Destructor; 8715 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8716 8717 // FIXME: If the destructor has a body that could throw, and the newly created 8718 // spec doesn't allow exceptions, we should emit a warning, because this 8719 // change in behavior can break conforming C++03 programs at runtime. 8720 // However, we don't have a body or an exception specification yet, so it 8721 // needs to be done somewhere else. 8722 } 8723 8724 namespace { 8725 /// \brief An abstract base class for all helper classes used in building the 8726 // copy/move operators. These classes serve as factory functions and help us 8727 // avoid using the same Expr* in the AST twice. 8728 class ExprBuilder { 8729 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8730 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8731 8732 protected: 8733 static Expr *assertNotNull(Expr *E) { 8734 assert(E && "Expression construction must not fail."); 8735 return E; 8736 } 8737 8738 public: 8739 ExprBuilder() {} 8740 virtual ~ExprBuilder() {} 8741 8742 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 8743 }; 8744 8745 class RefBuilder: public ExprBuilder { 8746 VarDecl *Var; 8747 QualType VarType; 8748 8749 public: 8750 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8751 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take()); 8752 } 8753 8754 RefBuilder(VarDecl *Var, QualType VarType) 8755 : Var(Var), VarType(VarType) {} 8756 }; 8757 8758 class ThisBuilder: public ExprBuilder { 8759 public: 8760 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8761 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>()); 8762 } 8763 }; 8764 8765 class CastBuilder: public ExprBuilder { 8766 const ExprBuilder &Builder; 8767 QualType Type; 8768 ExprValueKind Kind; 8769 const CXXCastPath &Path; 8770 8771 public: 8772 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8773 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 8774 CK_UncheckedDerivedToBase, Kind, 8775 &Path).take()); 8776 } 8777 8778 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 8779 const CXXCastPath &Path) 8780 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 8781 }; 8782 8783 class DerefBuilder: public ExprBuilder { 8784 const ExprBuilder &Builder; 8785 8786 public: 8787 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8788 return assertNotNull( 8789 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take()); 8790 } 8791 8792 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8793 }; 8794 8795 class MemberBuilder: public ExprBuilder { 8796 const ExprBuilder &Builder; 8797 QualType Type; 8798 CXXScopeSpec SS; 8799 bool IsArrow; 8800 LookupResult &MemberLookup; 8801 8802 public: 8803 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8804 return assertNotNull(S.BuildMemberReferenceExpr( 8805 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0, 8806 MemberLookup, 0).take()); 8807 } 8808 8809 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 8810 LookupResult &MemberLookup) 8811 : Builder(Builder), Type(Type), IsArrow(IsArrow), 8812 MemberLookup(MemberLookup) {} 8813 }; 8814 8815 class MoveCastBuilder: public ExprBuilder { 8816 const ExprBuilder &Builder; 8817 8818 public: 8819 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8820 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 8821 } 8822 8823 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8824 }; 8825 8826 class LvalueConvBuilder: public ExprBuilder { 8827 const ExprBuilder &Builder; 8828 8829 public: 8830 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE { 8831 return assertNotNull( 8832 S.DefaultLvalueConversion(Builder.build(S, Loc)).take()); 8833 } 8834 8835 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8836 }; 8837 8838 class SubscriptBuilder: public ExprBuilder { 8839 const ExprBuilder &Base; 8840 const ExprBuilder &Index; 8841 8842 public: 8843 virtual Expr *build(Sema &S, SourceLocation Loc) const 8844 LLVM_OVERRIDE { 8845 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 8846 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take()); 8847 } 8848 8849 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 8850 : Base(Base), Index(Index) {} 8851 }; 8852 8853 } // end anonymous namespace 8854 8855 /// When generating a defaulted copy or move assignment operator, if a field 8856 /// should be copied with __builtin_memcpy rather than via explicit assignments, 8857 /// do so. This optimization only applies for arrays of scalars, and for arrays 8858 /// of class type where the selected copy/move-assignment operator is trivial. 8859 static StmtResult 8860 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 8861 const ExprBuilder &ToB, const ExprBuilder &FromB) { 8862 // Compute the size of the memory buffer to be copied. 8863 QualType SizeType = S.Context.getSizeType(); 8864 llvm::APInt Size(S.Context.getTypeSize(SizeType), 8865 S.Context.getTypeSizeInChars(T).getQuantity()); 8866 8867 // Take the address of the field references for "from" and "to". We 8868 // directly construct UnaryOperators here because semantic analysis 8869 // does not permit us to take the address of an xvalue. 8870 Expr *From = FromB.build(S, Loc); 8871 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 8872 S.Context.getPointerType(From->getType()), 8873 VK_RValue, OK_Ordinary, Loc); 8874 Expr *To = ToB.build(S, Loc); 8875 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 8876 S.Context.getPointerType(To->getType()), 8877 VK_RValue, OK_Ordinary, Loc); 8878 8879 const Type *E = T->getBaseElementTypeUnsafe(); 8880 bool NeedsCollectableMemCpy = 8881 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 8882 8883 // Create a reference to the __builtin_objc_memmove_collectable function 8884 StringRef MemCpyName = NeedsCollectableMemCpy ? 8885 "__builtin_objc_memmove_collectable" : 8886 "__builtin_memcpy"; 8887 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 8888 Sema::LookupOrdinaryName); 8889 S.LookupName(R, S.TUScope, true); 8890 8891 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 8892 if (!MemCpy) 8893 // Something went horribly wrong earlier, and we will have complained 8894 // about it. 8895 return StmtError(); 8896 8897 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 8898 VK_RValue, Loc, 0); 8899 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 8900 8901 Expr *CallArgs[] = { 8902 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 8903 }; 8904 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(), 8905 Loc, CallArgs, Loc); 8906 8907 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8908 return S.Owned(Call.takeAs<Stmt>()); 8909 } 8910 8911 /// \brief Builds a statement that copies/moves the given entity from \p From to 8912 /// \c To. 8913 /// 8914 /// This routine is used to copy/move the members of a class with an 8915 /// implicitly-declared copy/move assignment operator. When the entities being 8916 /// copied are arrays, this routine builds for loops to copy them. 8917 /// 8918 /// \param S The Sema object used for type-checking. 8919 /// 8920 /// \param Loc The location where the implicit copy/move is being generated. 8921 /// 8922 /// \param T The type of the expressions being copied/moved. Both expressions 8923 /// must have this type. 8924 /// 8925 /// \param To The expression we are copying/moving to. 8926 /// 8927 /// \param From The expression we are copying/moving from. 8928 /// 8929 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 8930 /// Otherwise, it's a non-static member subobject. 8931 /// 8932 /// \param Copying Whether we're copying or moving. 8933 /// 8934 /// \param Depth Internal parameter recording the depth of the recursion. 8935 /// 8936 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 8937 /// if a memcpy should be used instead. 8938 static StmtResult 8939 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 8940 const ExprBuilder &To, const ExprBuilder &From, 8941 bool CopyingBaseSubobject, bool Copying, 8942 unsigned Depth = 0) { 8943 // C++11 [class.copy]p28: 8944 // Each subobject is assigned in the manner appropriate to its type: 8945 // 8946 // - if the subobject is of class type, as if by a call to operator= with 8947 // the subobject as the object expression and the corresponding 8948 // subobject of x as a single function argument (as if by explicit 8949 // qualification; that is, ignoring any possible virtual overriding 8950 // functions in more derived classes); 8951 // 8952 // C++03 [class.copy]p13: 8953 // - if the subobject is of class type, the copy assignment operator for 8954 // the class is used (as if by explicit qualification; that is, 8955 // ignoring any possible virtual overriding functions in more derived 8956 // classes); 8957 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 8958 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8959 8960 // Look for operator=. 8961 DeclarationName Name 8962 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 8963 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 8964 S.LookupQualifiedName(OpLookup, ClassDecl, false); 8965 8966 // Prior to C++11, filter out any result that isn't a copy/move-assignment 8967 // operator. 8968 if (!S.getLangOpts().CPlusPlus11) { 8969 LookupResult::Filter F = OpLookup.makeFilter(); 8970 while (F.hasNext()) { 8971 NamedDecl *D = F.next(); 8972 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 8973 if (Method->isCopyAssignmentOperator() || 8974 (!Copying && Method->isMoveAssignmentOperator())) 8975 continue; 8976 8977 F.erase(); 8978 } 8979 F.done(); 8980 } 8981 8982 // Suppress the protected check (C++ [class.protected]) for each of the 8983 // assignment operators we found. This strange dance is required when 8984 // we're assigning via a base classes's copy-assignment operator. To 8985 // ensure that we're getting the right base class subobject (without 8986 // ambiguities), we need to cast "this" to that subobject type; to 8987 // ensure that we don't go through the virtual call mechanism, we need 8988 // to qualify the operator= name with the base class (see below). However, 8989 // this means that if the base class has a protected copy assignment 8990 // operator, the protected member access check will fail. So, we 8991 // rewrite "protected" access to "public" access in this case, since we 8992 // know by construction that we're calling from a derived class. 8993 if (CopyingBaseSubobject) { 8994 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 8995 L != LEnd; ++L) { 8996 if (L.getAccess() == AS_protected) 8997 L.setAccess(AS_public); 8998 } 8999 } 9000 9001 // Create the nested-name-specifier that will be used to qualify the 9002 // reference to operator=; this is required to suppress the virtual 9003 // call mechanism. 9004 CXXScopeSpec SS; 9005 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9006 SS.MakeTrivial(S.Context, 9007 NestedNameSpecifier::Create(S.Context, 0, false, 9008 CanonicalT), 9009 Loc); 9010 9011 // Create the reference to operator=. 9012 ExprResult OpEqualRef 9013 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9014 SS, /*TemplateKWLoc=*/SourceLocation(), 9015 /*FirstQualifierInScope=*/0, 9016 OpLookup, 9017 /*TemplateArgs=*/0, 9018 /*SuppressQualifierCheck=*/true); 9019 if (OpEqualRef.isInvalid()) 9020 return StmtError(); 9021 9022 // Build the call to the assignment operator. 9023 9024 Expr *FromInst = From.build(S, Loc); 9025 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 9026 OpEqualRef.takeAs<Expr>(), 9027 Loc, FromInst, Loc); 9028 if (Call.isInvalid()) 9029 return StmtError(); 9030 9031 // If we built a call to a trivial 'operator=' while copying an array, 9032 // bail out. We'll replace the whole shebang with a memcpy. 9033 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9034 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9035 return StmtResult((Stmt*)0); 9036 9037 // Convert to an expression-statement, and clean up any produced 9038 // temporaries. 9039 return S.ActOnExprStmt(Call); 9040 } 9041 9042 // - if the subobject is of scalar type, the built-in assignment 9043 // operator is used. 9044 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9045 if (!ArrayTy) { 9046 ExprResult Assignment = S.CreateBuiltinBinOp( 9047 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9048 if (Assignment.isInvalid()) 9049 return StmtError(); 9050 return S.ActOnExprStmt(Assignment); 9051 } 9052 9053 // - if the subobject is an array, each element is assigned, in the 9054 // manner appropriate to the element type; 9055 9056 // Construct a loop over the array bounds, e.g., 9057 // 9058 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9059 // 9060 // that will copy each of the array elements. 9061 QualType SizeType = S.Context.getSizeType(); 9062 9063 // Create the iteration variable. 9064 IdentifierInfo *IterationVarName = 0; 9065 { 9066 SmallString<8> Str; 9067 llvm::raw_svector_ostream OS(Str); 9068 OS << "__i" << Depth; 9069 IterationVarName = &S.Context.Idents.get(OS.str()); 9070 } 9071 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9072 IterationVarName, SizeType, 9073 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9074 SC_None); 9075 9076 // Initialize the iteration variable to zero. 9077 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9078 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9079 9080 // Creates a reference to the iteration variable. 9081 RefBuilder IterationVarRef(IterationVar, SizeType); 9082 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9083 9084 // Create the DeclStmt that holds the iteration variable. 9085 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9086 9087 // Subscript the "from" and "to" expressions with the iteration variable. 9088 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9089 MoveCastBuilder FromIndexMove(FromIndexCopy); 9090 const ExprBuilder *FromIndex; 9091 if (Copying) 9092 FromIndex = &FromIndexCopy; 9093 else 9094 FromIndex = &FromIndexMove; 9095 9096 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9097 9098 // Build the copy/move for an individual element of the array. 9099 StmtResult Copy = 9100 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9101 ToIndex, *FromIndex, CopyingBaseSubobject, 9102 Copying, Depth + 1); 9103 // Bail out if copying fails or if we determined that we should use memcpy. 9104 if (Copy.isInvalid() || !Copy.get()) 9105 return Copy; 9106 9107 // Create the comparison against the array bound. 9108 llvm::APInt Upper 9109 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9110 Expr *Comparison 9111 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9112 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9113 BO_NE, S.Context.BoolTy, 9114 VK_RValue, OK_Ordinary, Loc, false); 9115 9116 // Create the pre-increment of the iteration variable. 9117 Expr *Increment 9118 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9119 SizeType, VK_LValue, OK_Ordinary, Loc); 9120 9121 // Construct the loop that copies all elements of this array. 9122 return S.ActOnForStmt(Loc, Loc, InitStmt, 9123 S.MakeFullExpr(Comparison), 9124 0, S.MakeFullDiscardedValueExpr(Increment), 9125 Loc, Copy.take()); 9126 } 9127 9128 static StmtResult 9129 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9130 const ExprBuilder &To, const ExprBuilder &From, 9131 bool CopyingBaseSubobject, bool Copying) { 9132 // Maybe we should use a memcpy? 9133 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9134 T.isTriviallyCopyableType(S.Context)) 9135 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9136 9137 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9138 CopyingBaseSubobject, 9139 Copying, 0)); 9140 9141 // If we ended up picking a trivial assignment operator for an array of a 9142 // non-trivially-copyable class type, just emit a memcpy. 9143 if (!Result.isInvalid() && !Result.get()) 9144 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9145 9146 return Result; 9147 } 9148 9149 Sema::ImplicitExceptionSpecification 9150 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9151 CXXRecordDecl *ClassDecl = MD->getParent(); 9152 9153 ImplicitExceptionSpecification ExceptSpec(*this); 9154 if (ClassDecl->isInvalidDecl()) 9155 return ExceptSpec; 9156 9157 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9158 assert(T->getNumArgs() == 1 && "not a copy assignment op"); 9159 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 9160 9161 // C++ [except.spec]p14: 9162 // An implicitly declared special member function (Clause 12) shall have an 9163 // exception-specification. [...] 9164 9165 // It is unspecified whether or not an implicit copy assignment operator 9166 // attempts to deduplicate calls to assignment operators of virtual bases are 9167 // made. As such, this exception specification is effectively unspecified. 9168 // Based on a similar decision made for constness in C++0x, we're erring on 9169 // the side of assuming such calls to be made regardless of whether they 9170 // actually happen. 9171 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9172 BaseEnd = ClassDecl->bases_end(); 9173 Base != BaseEnd; ++Base) { 9174 if (Base->isVirtual()) 9175 continue; 9176 9177 CXXRecordDecl *BaseClassDecl 9178 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9179 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9180 ArgQuals, false, 0)) 9181 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 9182 } 9183 9184 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9185 BaseEnd = ClassDecl->vbases_end(); 9186 Base != BaseEnd; ++Base) { 9187 CXXRecordDecl *BaseClassDecl 9188 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9189 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9190 ArgQuals, false, 0)) 9191 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign); 9192 } 9193 9194 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9195 FieldEnd = ClassDecl->field_end(); 9196 Field != FieldEnd; 9197 ++Field) { 9198 QualType FieldType = Context.getBaseElementType(Field->getType()); 9199 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9200 if (CXXMethodDecl *CopyAssign = 9201 LookupCopyingAssignment(FieldClassDecl, 9202 ArgQuals | FieldType.getCVRQualifiers(), 9203 false, 0)) 9204 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9205 } 9206 } 9207 9208 return ExceptSpec; 9209 } 9210 9211 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9212 // Note: The following rules are largely analoguous to the copy 9213 // constructor rules. Note that virtual bases are not taken into account 9214 // for determining the argument type of the operator. Note also that 9215 // operators taking an object instead of a reference are allowed. 9216 assert(ClassDecl->needsImplicitCopyAssignment()); 9217 9218 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9219 if (DSM.isAlreadyBeingDeclared()) 9220 return 0; 9221 9222 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9223 QualType RetType = Context.getLValueReferenceType(ArgType); 9224 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9225 if (Const) 9226 ArgType = ArgType.withConst(); 9227 ArgType = Context.getLValueReferenceType(ArgType); 9228 9229 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9230 CXXCopyAssignment, 9231 Const); 9232 9233 // An implicitly-declared copy assignment operator is an inline public 9234 // member of its class. 9235 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9236 SourceLocation ClassLoc = ClassDecl->getLocation(); 9237 DeclarationNameInfo NameInfo(Name, ClassLoc); 9238 CXXMethodDecl *CopyAssignment = 9239 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9240 /*TInfo=*/ 0, /*StorageClass=*/ SC_None, 9241 /*isInline=*/ true, Constexpr, SourceLocation()); 9242 CopyAssignment->setAccess(AS_public); 9243 CopyAssignment->setDefaulted(); 9244 CopyAssignment->setImplicit(); 9245 9246 // Build an exception specification pointing back at this member. 9247 FunctionProtoType::ExtProtoInfo EPI = 9248 getImplicitMethodEPI(*this, CopyAssignment); 9249 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9250 9251 // Add the parameter to the operator. 9252 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9253 ClassLoc, ClassLoc, /*Id=*/0, 9254 ArgType, /*TInfo=*/0, 9255 SC_None, 0); 9256 CopyAssignment->setParams(FromParam); 9257 9258 AddOverriddenMethods(ClassDecl, CopyAssignment); 9259 9260 CopyAssignment->setTrivial( 9261 ClassDecl->needsOverloadResolutionForCopyAssignment() 9262 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9263 : ClassDecl->hasTrivialCopyAssignment()); 9264 9265 // C++11 [class.copy]p19: 9266 // .... If the class definition does not explicitly declare a copy 9267 // assignment operator, there is no user-declared move constructor, and 9268 // there is no user-declared move assignment operator, a copy assignment 9269 // operator is implicitly declared as defaulted. 9270 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9271 SetDeclDeleted(CopyAssignment, ClassLoc); 9272 9273 // Note that we have added this copy-assignment operator. 9274 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9275 9276 if (Scope *S = getScopeForContext(ClassDecl)) 9277 PushOnScopeChains(CopyAssignment, S, false); 9278 ClassDecl->addDecl(CopyAssignment); 9279 9280 return CopyAssignment; 9281 } 9282 9283 /// Diagnose an implicit copy operation for a class which is odr-used, but 9284 /// which is deprecated because the class has a user-declared copy constructor, 9285 /// copy assignment operator, or destructor. 9286 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 9287 SourceLocation UseLoc) { 9288 assert(CopyOp->isImplicit()); 9289 9290 CXXRecordDecl *RD = CopyOp->getParent(); 9291 CXXMethodDecl *UserDeclaredOperation = 0; 9292 9293 // In Microsoft mode, assignment operations don't affect constructors and 9294 // vice versa. 9295 if (RD->hasUserDeclaredDestructor()) { 9296 UserDeclaredOperation = RD->getDestructor(); 9297 } else if (!isa<CXXConstructorDecl>(CopyOp) && 9298 RD->hasUserDeclaredCopyConstructor() && 9299 !S.getLangOpts().MicrosoftMode) { 9300 // Find any user-declared copy constructor. 9301 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(), 9302 E = RD->ctor_end(); I != E; ++I) { 9303 if (I->isCopyConstructor()) { 9304 UserDeclaredOperation = *I; 9305 break; 9306 } 9307 } 9308 assert(UserDeclaredOperation); 9309 } else if (isa<CXXConstructorDecl>(CopyOp) && 9310 RD->hasUserDeclaredCopyAssignment() && 9311 !S.getLangOpts().MicrosoftMode) { 9312 // Find any user-declared move assignment operator. 9313 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 9314 E = RD->method_end(); I != E; ++I) { 9315 if (I->isCopyAssignmentOperator()) { 9316 UserDeclaredOperation = *I; 9317 break; 9318 } 9319 } 9320 assert(UserDeclaredOperation); 9321 } 9322 9323 if (UserDeclaredOperation) { 9324 S.Diag(UserDeclaredOperation->getLocation(), 9325 diag::warn_deprecated_copy_operation) 9326 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 9327 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 9328 S.Diag(UseLoc, diag::note_member_synthesized_at) 9329 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 9330 : Sema::CXXCopyAssignment) 9331 << RD; 9332 } 9333 } 9334 9335 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 9336 CXXMethodDecl *CopyAssignOperator) { 9337 assert((CopyAssignOperator->isDefaulted() && 9338 CopyAssignOperator->isOverloadedOperator() && 9339 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 9340 !CopyAssignOperator->doesThisDeclarationHaveABody() && 9341 !CopyAssignOperator->isDeleted()) && 9342 "DefineImplicitCopyAssignment called for wrong function"); 9343 9344 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 9345 9346 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 9347 CopyAssignOperator->setInvalidDecl(); 9348 return; 9349 } 9350 9351 // C++11 [class.copy]p18: 9352 // The [definition of an implicitly declared copy assignment operator] is 9353 // deprecated if the class has a user-declared copy constructor or a 9354 // user-declared destructor. 9355 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 9356 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 9357 9358 CopyAssignOperator->markUsed(Context); 9359 9360 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 9361 DiagnosticErrorTrap Trap(Diags); 9362 9363 // C++0x [class.copy]p30: 9364 // The implicitly-defined or explicitly-defaulted copy assignment operator 9365 // for a non-union class X performs memberwise copy assignment of its 9366 // subobjects. The direct base classes of X are assigned first, in the 9367 // order of their declaration in the base-specifier-list, and then the 9368 // immediate non-static data members of X are assigned, in the order in 9369 // which they were declared in the class definition. 9370 9371 // The statements that form the synthesized function body. 9372 SmallVector<Stmt*, 8> Statements; 9373 9374 // The parameter for the "other" object, which we are copying from. 9375 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 9376 Qualifiers OtherQuals = Other->getType().getQualifiers(); 9377 QualType OtherRefType = Other->getType(); 9378 if (const LValueReferenceType *OtherRef 9379 = OtherRefType->getAs<LValueReferenceType>()) { 9380 OtherRefType = OtherRef->getPointeeType(); 9381 OtherQuals = OtherRefType.getQualifiers(); 9382 } 9383 9384 // Our location for everything implicitly-generated. 9385 SourceLocation Loc = CopyAssignOperator->getLocation(); 9386 9387 // Builds a DeclRefExpr for the "other" object. 9388 RefBuilder OtherRef(Other, OtherRefType); 9389 9390 // Builds the "this" pointer. 9391 ThisBuilder This; 9392 9393 // Assign base classes. 9394 bool Invalid = false; 9395 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9396 E = ClassDecl->bases_end(); Base != E; ++Base) { 9397 // Form the assignment: 9398 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 9399 QualType BaseType = Base->getType().getUnqualifiedType(); 9400 if (!BaseType->isRecordType()) { 9401 Invalid = true; 9402 continue; 9403 } 9404 9405 CXXCastPath BasePath; 9406 BasePath.push_back(Base); 9407 9408 // Construct the "from" expression, which is an implicit cast to the 9409 // appropriately-qualified base type. 9410 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 9411 VK_LValue, BasePath); 9412 9413 // Dereference "this". 9414 DerefBuilder DerefThis(This); 9415 CastBuilder To(DerefThis, 9416 Context.getCVRQualifiedType( 9417 BaseType, CopyAssignOperator->getTypeQualifiers()), 9418 VK_LValue, BasePath); 9419 9420 // Build the copy. 9421 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 9422 To, From, 9423 /*CopyingBaseSubobject=*/true, 9424 /*Copying=*/true); 9425 if (Copy.isInvalid()) { 9426 Diag(CurrentLocation, diag::note_member_synthesized_at) 9427 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9428 CopyAssignOperator->setInvalidDecl(); 9429 return; 9430 } 9431 9432 // Success! Record the copy. 9433 Statements.push_back(Copy.takeAs<Expr>()); 9434 } 9435 9436 // Assign non-static members. 9437 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9438 FieldEnd = ClassDecl->field_end(); 9439 Field != FieldEnd; ++Field) { 9440 if (Field->isUnnamedBitfield()) 9441 continue; 9442 9443 if (Field->isInvalidDecl()) { 9444 Invalid = true; 9445 continue; 9446 } 9447 9448 // Check for members of reference type; we can't copy those. 9449 if (Field->getType()->isReferenceType()) { 9450 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9451 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9452 Diag(Field->getLocation(), diag::note_declared_at); 9453 Diag(CurrentLocation, diag::note_member_synthesized_at) 9454 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9455 Invalid = true; 9456 continue; 9457 } 9458 9459 // Check for members of const-qualified, non-class type. 9460 QualType BaseType = Context.getBaseElementType(Field->getType()); 9461 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9462 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9463 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9464 Diag(Field->getLocation(), diag::note_declared_at); 9465 Diag(CurrentLocation, diag::note_member_synthesized_at) 9466 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9467 Invalid = true; 9468 continue; 9469 } 9470 9471 // Suppress assigning zero-width bitfields. 9472 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9473 continue; 9474 9475 QualType FieldType = Field->getType().getNonReferenceType(); 9476 if (FieldType->isIncompleteArrayType()) { 9477 assert(ClassDecl->hasFlexibleArrayMember() && 9478 "Incomplete array type is not valid"); 9479 continue; 9480 } 9481 9482 // Build references to the field in the object we're copying from and to. 9483 CXXScopeSpec SS; // Intentionally empty 9484 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9485 LookupMemberName); 9486 MemberLookup.addDecl(*Field); 9487 MemberLookup.resolveKind(); 9488 9489 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 9490 9491 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 9492 9493 // Build the copy of this field. 9494 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 9495 To, From, 9496 /*CopyingBaseSubobject=*/false, 9497 /*Copying=*/true); 9498 if (Copy.isInvalid()) { 9499 Diag(CurrentLocation, diag::note_member_synthesized_at) 9500 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9501 CopyAssignOperator->setInvalidDecl(); 9502 return; 9503 } 9504 9505 // Success! Record the copy. 9506 Statements.push_back(Copy.takeAs<Stmt>()); 9507 } 9508 9509 if (!Invalid) { 9510 // Add a "return *this;" 9511 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9512 9513 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9514 if (Return.isInvalid()) 9515 Invalid = true; 9516 else { 9517 Statements.push_back(Return.takeAs<Stmt>()); 9518 9519 if (Trap.hasErrorOccurred()) { 9520 Diag(CurrentLocation, diag::note_member_synthesized_at) 9521 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9522 Invalid = true; 9523 } 9524 } 9525 } 9526 9527 if (Invalid) { 9528 CopyAssignOperator->setInvalidDecl(); 9529 return; 9530 } 9531 9532 StmtResult Body; 9533 { 9534 CompoundScopeRAII CompoundScope(*this); 9535 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9536 /*isStmtExpr=*/false); 9537 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9538 } 9539 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 9540 9541 if (ASTMutationListener *L = getASTMutationListener()) { 9542 L->CompletedImplicitDefinition(CopyAssignOperator); 9543 } 9544 } 9545 9546 Sema::ImplicitExceptionSpecification 9547 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9548 CXXRecordDecl *ClassDecl = MD->getParent(); 9549 9550 ImplicitExceptionSpecification ExceptSpec(*this); 9551 if (ClassDecl->isInvalidDecl()) 9552 return ExceptSpec; 9553 9554 // C++0x [except.spec]p14: 9555 // An implicitly declared special member function (Clause 12) shall have an 9556 // exception-specification. [...] 9557 9558 // It is unspecified whether or not an implicit move assignment operator 9559 // attempts to deduplicate calls to assignment operators of virtual bases are 9560 // made. As such, this exception specification is effectively unspecified. 9561 // Based on a similar decision made for constness in C++0x, we're erring on 9562 // the side of assuming such calls to be made regardless of whether they 9563 // actually happen. 9564 // Note that a move constructor is not implicitly declared when there are 9565 // virtual bases, but it can still be user-declared and explicitly defaulted. 9566 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9567 BaseEnd = ClassDecl->bases_end(); 9568 Base != BaseEnd; ++Base) { 9569 if (Base->isVirtual()) 9570 continue; 9571 9572 CXXRecordDecl *BaseClassDecl 9573 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9574 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9575 0, false, 0)) 9576 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9577 } 9578 9579 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9580 BaseEnd = ClassDecl->vbases_end(); 9581 Base != BaseEnd; ++Base) { 9582 CXXRecordDecl *BaseClassDecl 9583 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9584 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9585 0, false, 0)) 9586 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign); 9587 } 9588 9589 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9590 FieldEnd = ClassDecl->field_end(); 9591 Field != FieldEnd; 9592 ++Field) { 9593 QualType FieldType = Context.getBaseElementType(Field->getType()); 9594 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9595 if (CXXMethodDecl *MoveAssign = 9596 LookupMovingAssignment(FieldClassDecl, 9597 FieldType.getCVRQualifiers(), 9598 false, 0)) 9599 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 9600 } 9601 } 9602 9603 return ExceptSpec; 9604 } 9605 9606 /// Determine whether the class type has any direct or indirect virtual base 9607 /// classes which have a non-trivial move assignment operator. 9608 static bool 9609 hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) { 9610 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9611 BaseEnd = ClassDecl->vbases_end(); 9612 Base != BaseEnd; ++Base) { 9613 CXXRecordDecl *BaseClass = 9614 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 9615 9616 // Try to declare the move assignment. If it would be deleted, then the 9617 // class does not have a non-trivial move assignment. 9618 if (BaseClass->needsImplicitMoveAssignment()) 9619 S.DeclareImplicitMoveAssignment(BaseClass); 9620 9621 if (BaseClass->hasNonTrivialMoveAssignment()) 9622 return true; 9623 } 9624 9625 return false; 9626 } 9627 9628 /// Determine whether the given type either has a move constructor or is 9629 /// trivially copyable. 9630 static bool 9631 hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) { 9632 Type = S.Context.getBaseElementType(Type); 9633 9634 // FIXME: Technically, non-trivially-copyable non-class types, such as 9635 // reference types, are supposed to return false here, but that appears 9636 // to be a standard defect. 9637 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl(); 9638 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl()) 9639 return true; 9640 9641 if (Type.isTriviallyCopyableType(S.Context)) 9642 return true; 9643 9644 if (IsConstructor) { 9645 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to 9646 // give the right answer. 9647 if (ClassDecl->needsImplicitMoveConstructor()) 9648 S.DeclareImplicitMoveConstructor(ClassDecl); 9649 return ClassDecl->hasMoveConstructor(); 9650 } 9651 9652 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to 9653 // give the right answer. 9654 if (ClassDecl->needsImplicitMoveAssignment()) 9655 S.DeclareImplicitMoveAssignment(ClassDecl); 9656 return ClassDecl->hasMoveAssignment(); 9657 } 9658 9659 /// Determine whether all non-static data members and direct or virtual bases 9660 /// of class \p ClassDecl have either a move operation, or are trivially 9661 /// copyable. 9662 static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl, 9663 bool IsConstructor) { 9664 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9665 BaseEnd = ClassDecl->bases_end(); 9666 Base != BaseEnd; ++Base) { 9667 if (Base->isVirtual()) 9668 continue; 9669 9670 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9671 return false; 9672 } 9673 9674 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 9675 BaseEnd = ClassDecl->vbases_end(); 9676 Base != BaseEnd; ++Base) { 9677 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor)) 9678 return false; 9679 } 9680 9681 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9682 FieldEnd = ClassDecl->field_end(); 9683 Field != FieldEnd; ++Field) { 9684 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor)) 9685 return false; 9686 } 9687 9688 return true; 9689 } 9690 9691 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9692 // C++11 [class.copy]p20: 9693 // If the definition of a class X does not explicitly declare a move 9694 // assignment operator, one will be implicitly declared as defaulted 9695 // if and only if: 9696 // 9697 // - [first 4 bullets] 9698 assert(ClassDecl->needsImplicitMoveAssignment()); 9699 9700 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9701 if (DSM.isAlreadyBeingDeclared()) 9702 return 0; 9703 9704 // [Checked after we build the declaration] 9705 // - the move assignment operator would not be implicitly defined as 9706 // deleted, 9707 9708 // [DR1402]: 9709 // - X has no direct or indirect virtual base class with a non-trivial 9710 // move assignment operator, and 9711 // - each of X's non-static data members and direct or virtual base classes 9712 // has a type that either has a move assignment operator or is trivially 9713 // copyable. 9714 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) || 9715 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) { 9716 ClassDecl->setFailedImplicitMoveAssignment(); 9717 return 0; 9718 } 9719 9720 // Note: The following rules are largely analoguous to the move 9721 // constructor rules. 9722 9723 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9724 QualType RetType = Context.getLValueReferenceType(ArgType); 9725 ArgType = Context.getRValueReferenceType(ArgType); 9726 9727 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9728 CXXMoveAssignment, 9729 false); 9730 9731 // An implicitly-declared move assignment operator is an inline public 9732 // member of its class. 9733 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9734 SourceLocation ClassLoc = ClassDecl->getLocation(); 9735 DeclarationNameInfo NameInfo(Name, ClassLoc); 9736 CXXMethodDecl *MoveAssignment = 9737 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9738 /*TInfo=*/0, /*StorageClass=*/SC_None, 9739 /*isInline=*/true, Constexpr, SourceLocation()); 9740 MoveAssignment->setAccess(AS_public); 9741 MoveAssignment->setDefaulted(); 9742 MoveAssignment->setImplicit(); 9743 9744 // Build an exception specification pointing back at this member. 9745 FunctionProtoType::ExtProtoInfo EPI = 9746 getImplicitMethodEPI(*this, MoveAssignment); 9747 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9748 9749 // Add the parameter to the operator. 9750 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9751 ClassLoc, ClassLoc, /*Id=*/0, 9752 ArgType, /*TInfo=*/0, 9753 SC_None, 0); 9754 MoveAssignment->setParams(FromParam); 9755 9756 AddOverriddenMethods(ClassDecl, MoveAssignment); 9757 9758 MoveAssignment->setTrivial( 9759 ClassDecl->needsOverloadResolutionForMoveAssignment() 9760 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9761 : ClassDecl->hasTrivialMoveAssignment()); 9762 9763 // C++0x [class.copy]p9: 9764 // If the definition of a class X does not explicitly declare a move 9765 // assignment operator, one will be implicitly declared as defaulted if and 9766 // only if: 9767 // [...] 9768 // - the move assignment operator would not be implicitly defined as 9769 // deleted. 9770 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9771 // Cache this result so that we don't try to generate this over and over 9772 // on every lookup, leaking memory and wasting time. 9773 ClassDecl->setFailedImplicitMoveAssignment(); 9774 return 0; 9775 } 9776 9777 // Note that we have added this copy-assignment operator. 9778 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9779 9780 if (Scope *S = getScopeForContext(ClassDecl)) 9781 PushOnScopeChains(MoveAssignment, S, false); 9782 ClassDecl->addDecl(MoveAssignment); 9783 9784 return MoveAssignment; 9785 } 9786 9787 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 9788 CXXMethodDecl *MoveAssignOperator) { 9789 assert((MoveAssignOperator->isDefaulted() && 9790 MoveAssignOperator->isOverloadedOperator() && 9791 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 9792 !MoveAssignOperator->doesThisDeclarationHaveABody() && 9793 !MoveAssignOperator->isDeleted()) && 9794 "DefineImplicitMoveAssignment called for wrong function"); 9795 9796 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 9797 9798 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 9799 MoveAssignOperator->setInvalidDecl(); 9800 return; 9801 } 9802 9803 MoveAssignOperator->markUsed(Context); 9804 9805 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 9806 DiagnosticErrorTrap Trap(Diags); 9807 9808 // C++0x [class.copy]p28: 9809 // The implicitly-defined or move assignment operator for a non-union class 9810 // X performs memberwise move assignment of its subobjects. The direct base 9811 // classes of X are assigned first, in the order of their declaration in the 9812 // base-specifier-list, and then the immediate non-static data members of X 9813 // are assigned, in the order in which they were declared in the class 9814 // definition. 9815 9816 // The statements that form the synthesized function body. 9817 SmallVector<Stmt*, 8> Statements; 9818 9819 // The parameter for the "other" object, which we are move from. 9820 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 9821 QualType OtherRefType = Other->getType()-> 9822 getAs<RValueReferenceType>()->getPointeeType(); 9823 assert(!OtherRefType.getQualifiers() && 9824 "Bad argument type of defaulted move assignment"); 9825 9826 // Our location for everything implicitly-generated. 9827 SourceLocation Loc = MoveAssignOperator->getLocation(); 9828 9829 // Builds a reference to the "other" object. 9830 RefBuilder OtherRef(Other, OtherRefType); 9831 // Cast to rvalue. 9832 MoveCastBuilder MoveOther(OtherRef); 9833 9834 // Builds the "this" pointer. 9835 ThisBuilder This; 9836 9837 // Assign base classes. 9838 bool Invalid = false; 9839 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 9840 E = ClassDecl->bases_end(); Base != E; ++Base) { 9841 // Form the assignment: 9842 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 9843 QualType BaseType = Base->getType().getUnqualifiedType(); 9844 if (!BaseType->isRecordType()) { 9845 Invalid = true; 9846 continue; 9847 } 9848 9849 CXXCastPath BasePath; 9850 BasePath.push_back(Base); 9851 9852 // Construct the "from" expression, which is an implicit cast to the 9853 // appropriately-qualified base type. 9854 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 9855 9856 // Dereference "this". 9857 DerefBuilder DerefThis(This); 9858 9859 // Implicitly cast "this" to the appropriately-qualified base type. 9860 CastBuilder To(DerefThis, 9861 Context.getCVRQualifiedType( 9862 BaseType, MoveAssignOperator->getTypeQualifiers()), 9863 VK_LValue, BasePath); 9864 9865 // Build the move. 9866 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 9867 To, From, 9868 /*CopyingBaseSubobject=*/true, 9869 /*Copying=*/false); 9870 if (Move.isInvalid()) { 9871 Diag(CurrentLocation, diag::note_member_synthesized_at) 9872 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9873 MoveAssignOperator->setInvalidDecl(); 9874 return; 9875 } 9876 9877 // Success! Record the move. 9878 Statements.push_back(Move.takeAs<Expr>()); 9879 } 9880 9881 // Assign non-static members. 9882 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 9883 FieldEnd = ClassDecl->field_end(); 9884 Field != FieldEnd; ++Field) { 9885 if (Field->isUnnamedBitfield()) 9886 continue; 9887 9888 if (Field->isInvalidDecl()) { 9889 Invalid = true; 9890 continue; 9891 } 9892 9893 // Check for members of reference type; we can't move those. 9894 if (Field->getType()->isReferenceType()) { 9895 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9896 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9897 Diag(Field->getLocation(), diag::note_declared_at); 9898 Diag(CurrentLocation, diag::note_member_synthesized_at) 9899 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9900 Invalid = true; 9901 continue; 9902 } 9903 9904 // Check for members of const-qualified, non-class type. 9905 QualType BaseType = Context.getBaseElementType(Field->getType()); 9906 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9907 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9908 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9909 Diag(Field->getLocation(), diag::note_declared_at); 9910 Diag(CurrentLocation, diag::note_member_synthesized_at) 9911 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9912 Invalid = true; 9913 continue; 9914 } 9915 9916 // Suppress assigning zero-width bitfields. 9917 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9918 continue; 9919 9920 QualType FieldType = Field->getType().getNonReferenceType(); 9921 if (FieldType->isIncompleteArrayType()) { 9922 assert(ClassDecl->hasFlexibleArrayMember() && 9923 "Incomplete array type is not valid"); 9924 continue; 9925 } 9926 9927 // Build references to the field in the object we're copying from and to. 9928 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9929 LookupMemberName); 9930 MemberLookup.addDecl(*Field); 9931 MemberLookup.resolveKind(); 9932 MemberBuilder From(MoveOther, OtherRefType, 9933 /*IsArrow=*/false, MemberLookup); 9934 MemberBuilder To(This, getCurrentThisType(), 9935 /*IsArrow=*/true, MemberLookup); 9936 9937 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 9938 "Member reference with rvalue base must be rvalue except for reference " 9939 "members, which aren't allowed for move assignment."); 9940 9941 // Build the move of this field. 9942 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 9943 To, From, 9944 /*CopyingBaseSubobject=*/false, 9945 /*Copying=*/false); 9946 if (Move.isInvalid()) { 9947 Diag(CurrentLocation, diag::note_member_synthesized_at) 9948 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9949 MoveAssignOperator->setInvalidDecl(); 9950 return; 9951 } 9952 9953 // Success! Record the copy. 9954 Statements.push_back(Move.takeAs<Stmt>()); 9955 } 9956 9957 if (!Invalid) { 9958 // Add a "return *this;" 9959 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9960 9961 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9962 if (Return.isInvalid()) 9963 Invalid = true; 9964 else { 9965 Statements.push_back(Return.takeAs<Stmt>()); 9966 9967 if (Trap.hasErrorOccurred()) { 9968 Diag(CurrentLocation, diag::note_member_synthesized_at) 9969 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9970 Invalid = true; 9971 } 9972 } 9973 } 9974 9975 if (Invalid) { 9976 MoveAssignOperator->setInvalidDecl(); 9977 return; 9978 } 9979 9980 StmtResult Body; 9981 { 9982 CompoundScopeRAII CompoundScope(*this); 9983 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9984 /*isStmtExpr=*/false); 9985 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9986 } 9987 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 9988 9989 if (ASTMutationListener *L = getASTMutationListener()) { 9990 L->CompletedImplicitDefinition(MoveAssignOperator); 9991 } 9992 } 9993 9994 Sema::ImplicitExceptionSpecification 9995 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 9996 CXXRecordDecl *ClassDecl = MD->getParent(); 9997 9998 ImplicitExceptionSpecification ExceptSpec(*this); 9999 if (ClassDecl->isInvalidDecl()) 10000 return ExceptSpec; 10001 10002 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10003 assert(T->getNumArgs() >= 1 && "not a copy ctor"); 10004 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers(); 10005 10006 // C++ [except.spec]p14: 10007 // An implicitly declared special member function (Clause 12) shall have an 10008 // exception-specification. [...] 10009 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 10010 BaseEnd = ClassDecl->bases_end(); 10011 Base != BaseEnd; 10012 ++Base) { 10013 // Virtual bases are handled below. 10014 if (Base->isVirtual()) 10015 continue; 10016 10017 CXXRecordDecl *BaseClassDecl 10018 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 10019 if (CXXConstructorDecl *CopyConstructor = 10020 LookupCopyingConstructor(BaseClassDecl, Quals)) 10021 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 10022 } 10023 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 10024 BaseEnd = ClassDecl->vbases_end(); 10025 Base != BaseEnd; 10026 ++Base) { 10027 CXXRecordDecl *BaseClassDecl 10028 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 10029 if (CXXConstructorDecl *CopyConstructor = 10030 LookupCopyingConstructor(BaseClassDecl, Quals)) 10031 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor); 10032 } 10033 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 10034 FieldEnd = ClassDecl->field_end(); 10035 Field != FieldEnd; 10036 ++Field) { 10037 QualType FieldType = Context.getBaseElementType(Field->getType()); 10038 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10039 if (CXXConstructorDecl *CopyConstructor = 10040 LookupCopyingConstructor(FieldClassDecl, 10041 Quals | FieldType.getCVRQualifiers())) 10042 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10043 } 10044 } 10045 10046 return ExceptSpec; 10047 } 10048 10049 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10050 CXXRecordDecl *ClassDecl) { 10051 // C++ [class.copy]p4: 10052 // If the class definition does not explicitly declare a copy 10053 // constructor, one is declared implicitly. 10054 assert(ClassDecl->needsImplicitCopyConstructor()); 10055 10056 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10057 if (DSM.isAlreadyBeingDeclared()) 10058 return 0; 10059 10060 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10061 QualType ArgType = ClassType; 10062 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10063 if (Const) 10064 ArgType = ArgType.withConst(); 10065 ArgType = Context.getLValueReferenceType(ArgType); 10066 10067 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10068 CXXCopyConstructor, 10069 Const); 10070 10071 DeclarationName Name 10072 = Context.DeclarationNames.getCXXConstructorName( 10073 Context.getCanonicalType(ClassType)); 10074 SourceLocation ClassLoc = ClassDecl->getLocation(); 10075 DeclarationNameInfo NameInfo(Name, ClassLoc); 10076 10077 // An implicitly-declared copy constructor is an inline public 10078 // member of its class. 10079 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10080 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 10081 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10082 Constexpr); 10083 CopyConstructor->setAccess(AS_public); 10084 CopyConstructor->setDefaulted(); 10085 10086 // Build an exception specification pointing back at this member. 10087 FunctionProtoType::ExtProtoInfo EPI = 10088 getImplicitMethodEPI(*this, CopyConstructor); 10089 CopyConstructor->setType( 10090 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10091 10092 // Add the parameter to the constructor. 10093 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10094 ClassLoc, ClassLoc, 10095 /*IdentifierInfo=*/0, 10096 ArgType, /*TInfo=*/0, 10097 SC_None, 0); 10098 CopyConstructor->setParams(FromParam); 10099 10100 CopyConstructor->setTrivial( 10101 ClassDecl->needsOverloadResolutionForCopyConstructor() 10102 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10103 : ClassDecl->hasTrivialCopyConstructor()); 10104 10105 // C++11 [class.copy]p8: 10106 // ... If the class definition does not explicitly declare a copy 10107 // constructor, there is no user-declared move constructor, and there is no 10108 // user-declared move assignment operator, a copy constructor is implicitly 10109 // declared as defaulted. 10110 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10111 SetDeclDeleted(CopyConstructor, ClassLoc); 10112 10113 // Note that we have declared this constructor. 10114 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10115 10116 if (Scope *S = getScopeForContext(ClassDecl)) 10117 PushOnScopeChains(CopyConstructor, S, false); 10118 ClassDecl->addDecl(CopyConstructor); 10119 10120 return CopyConstructor; 10121 } 10122 10123 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10124 CXXConstructorDecl *CopyConstructor) { 10125 assert((CopyConstructor->isDefaulted() && 10126 CopyConstructor->isCopyConstructor() && 10127 !CopyConstructor->doesThisDeclarationHaveABody() && 10128 !CopyConstructor->isDeleted()) && 10129 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10130 10131 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10132 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10133 10134 // C++11 [class.copy]p7: 10135 // The [definition of an implicitly declared copy constructor] is 10136 // deprecated if the class has a user-declared copy assignment operator 10137 // or a user-declared destructor. 10138 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10139 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10140 10141 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10142 DiagnosticErrorTrap Trap(Diags); 10143 10144 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10145 Trap.hasErrorOccurred()) { 10146 Diag(CurrentLocation, diag::note_member_synthesized_at) 10147 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10148 CopyConstructor->setInvalidDecl(); 10149 } else { 10150 Sema::CompoundScopeRAII CompoundScope(*this); 10151 CopyConstructor->setBody(ActOnCompoundStmt( 10152 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None, 10153 /*isStmtExpr=*/ false).takeAs<Stmt>()); 10154 } 10155 10156 CopyConstructor->markUsed(Context); 10157 if (ASTMutationListener *L = getASTMutationListener()) { 10158 L->CompletedImplicitDefinition(CopyConstructor); 10159 } 10160 } 10161 10162 Sema::ImplicitExceptionSpecification 10163 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10164 CXXRecordDecl *ClassDecl = MD->getParent(); 10165 10166 // C++ [except.spec]p14: 10167 // An implicitly declared special member function (Clause 12) shall have an 10168 // exception-specification. [...] 10169 ImplicitExceptionSpecification ExceptSpec(*this); 10170 if (ClassDecl->isInvalidDecl()) 10171 return ExceptSpec; 10172 10173 // Direct base-class constructors. 10174 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 10175 BEnd = ClassDecl->bases_end(); 10176 B != BEnd; ++B) { 10177 if (B->isVirtual()) // Handled below. 10178 continue; 10179 10180 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 10181 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10182 CXXConstructorDecl *Constructor = 10183 LookupMovingConstructor(BaseClassDecl, 0); 10184 // If this is a deleted function, add it anyway. This might be conformant 10185 // with the standard. This might not. I'm not sure. It might not matter. 10186 if (Constructor) 10187 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 10188 } 10189 } 10190 10191 // Virtual base-class constructors. 10192 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 10193 BEnd = ClassDecl->vbases_end(); 10194 B != BEnd; ++B) { 10195 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 10196 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10197 CXXConstructorDecl *Constructor = 10198 LookupMovingConstructor(BaseClassDecl, 0); 10199 // If this is a deleted function, add it anyway. This might be conformant 10200 // with the standard. This might not. I'm not sure. It might not matter. 10201 if (Constructor) 10202 ExceptSpec.CalledDecl(B->getLocStart(), Constructor); 10203 } 10204 } 10205 10206 // Field constructors. 10207 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 10208 FEnd = ClassDecl->field_end(); 10209 F != FEnd; ++F) { 10210 QualType FieldType = Context.getBaseElementType(F->getType()); 10211 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10212 CXXConstructorDecl *Constructor = 10213 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10214 // If this is a deleted function, add it anyway. This might be conformant 10215 // with the standard. This might not. I'm not sure. It might not matter. 10216 // In particular, the problem is that this function never gets called. It 10217 // might just be ill-formed because this function attempts to refer to 10218 // a deleted function here. 10219 if (Constructor) 10220 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10221 } 10222 } 10223 10224 return ExceptSpec; 10225 } 10226 10227 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10228 CXXRecordDecl *ClassDecl) { 10229 // C++11 [class.copy]p9: 10230 // If the definition of a class X does not explicitly declare a move 10231 // constructor, one will be implicitly declared as defaulted if and only if: 10232 // 10233 // - [first 4 bullets] 10234 assert(ClassDecl->needsImplicitMoveConstructor()); 10235 10236 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10237 if (DSM.isAlreadyBeingDeclared()) 10238 return 0; 10239 10240 // [Checked after we build the declaration] 10241 // - the move assignment operator would not be implicitly defined as 10242 // deleted, 10243 10244 // [DR1402]: 10245 // - each of X's non-static data members and direct or virtual base classes 10246 // has a type that either has a move constructor or is trivially copyable. 10247 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) { 10248 ClassDecl->setFailedImplicitMoveConstructor(); 10249 return 0; 10250 } 10251 10252 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10253 QualType ArgType = Context.getRValueReferenceType(ClassType); 10254 10255 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10256 CXXMoveConstructor, 10257 false); 10258 10259 DeclarationName Name 10260 = Context.DeclarationNames.getCXXConstructorName( 10261 Context.getCanonicalType(ClassType)); 10262 SourceLocation ClassLoc = ClassDecl->getLocation(); 10263 DeclarationNameInfo NameInfo(Name, ClassLoc); 10264 10265 // C++11 [class.copy]p11: 10266 // An implicitly-declared copy/move constructor is an inline public 10267 // member of its class. 10268 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10269 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 10270 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10271 Constexpr); 10272 MoveConstructor->setAccess(AS_public); 10273 MoveConstructor->setDefaulted(); 10274 10275 // Build an exception specification pointing back at this member. 10276 FunctionProtoType::ExtProtoInfo EPI = 10277 getImplicitMethodEPI(*this, MoveConstructor); 10278 MoveConstructor->setType( 10279 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10280 10281 // Add the parameter to the constructor. 10282 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10283 ClassLoc, ClassLoc, 10284 /*IdentifierInfo=*/0, 10285 ArgType, /*TInfo=*/0, 10286 SC_None, 0); 10287 MoveConstructor->setParams(FromParam); 10288 10289 MoveConstructor->setTrivial( 10290 ClassDecl->needsOverloadResolutionForMoveConstructor() 10291 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10292 : ClassDecl->hasTrivialMoveConstructor()); 10293 10294 // C++0x [class.copy]p9: 10295 // If the definition of a class X does not explicitly declare a move 10296 // constructor, one will be implicitly declared as defaulted if and only if: 10297 // [...] 10298 // - the move constructor would not be implicitly defined as deleted. 10299 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10300 // Cache this result so that we don't try to generate this over and over 10301 // on every lookup, leaking memory and wasting time. 10302 ClassDecl->setFailedImplicitMoveConstructor(); 10303 return 0; 10304 } 10305 10306 // Note that we have declared this constructor. 10307 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10308 10309 if (Scope *S = getScopeForContext(ClassDecl)) 10310 PushOnScopeChains(MoveConstructor, S, false); 10311 ClassDecl->addDecl(MoveConstructor); 10312 10313 return MoveConstructor; 10314 } 10315 10316 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 10317 CXXConstructorDecl *MoveConstructor) { 10318 assert((MoveConstructor->isDefaulted() && 10319 MoveConstructor->isMoveConstructor() && 10320 !MoveConstructor->doesThisDeclarationHaveABody() && 10321 !MoveConstructor->isDeleted()) && 10322 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 10323 10324 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 10325 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 10326 10327 SynthesizedFunctionScope Scope(*this, MoveConstructor); 10328 DiagnosticErrorTrap Trap(Diags); 10329 10330 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10331 Trap.hasErrorOccurred()) { 10332 Diag(CurrentLocation, diag::note_member_synthesized_at) 10333 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10334 MoveConstructor->setInvalidDecl(); 10335 } else { 10336 Sema::CompoundScopeRAII CompoundScope(*this); 10337 MoveConstructor->setBody(ActOnCompoundStmt( 10338 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None, 10339 /*isStmtExpr=*/ false).takeAs<Stmt>()); 10340 } 10341 10342 MoveConstructor->markUsed(Context); 10343 10344 if (ASTMutationListener *L = getASTMutationListener()) { 10345 L->CompletedImplicitDefinition(MoveConstructor); 10346 } 10347 } 10348 10349 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10350 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10351 } 10352 10353 /// \brief Mark the call operator of the given lambda closure type as "used". 10354 static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) { 10355 CXXMethodDecl *CallOperator 10356 = cast<CXXMethodDecl>( 10357 Lambda->lookup( 10358 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); 10359 CallOperator->setReferenced(); 10360 CallOperator->markUsed(S.Context); 10361 } 10362 10363 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10364 SourceLocation CurrentLocation, 10365 CXXConversionDecl *Conv) 10366 { 10367 CXXRecordDecl *Lambda = Conv->getParent(); 10368 10369 // Make sure that the lambda call operator is marked used. 10370 markLambdaCallOperatorUsed(*this, Lambda); 10371 10372 Conv->markUsed(Context); 10373 10374 SynthesizedFunctionScope Scope(*this, Conv); 10375 DiagnosticErrorTrap Trap(Diags); 10376 10377 // Return the address of the __invoke function. 10378 DeclarationName InvokeName = &Context.Idents.get("__invoke"); 10379 CXXMethodDecl *Invoke 10380 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front()); 10381 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(), 10382 VK_LValue, Conv->getLocation()).take(); 10383 assert(FunctionRef && "Can't refer to __invoke function?"); 10384 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 10385 Conv->setBody(new (Context) CompoundStmt(Context, Return, 10386 Conv->getLocation(), 10387 Conv->getLocation())); 10388 10389 // Fill in the __invoke function with a dummy implementation. IR generation 10390 // will fill in the actual details. 10391 Invoke->markUsed(Context); 10392 Invoke->setReferenced(); 10393 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation())); 10394 10395 if (ASTMutationListener *L = getASTMutationListener()) { 10396 L->CompletedImplicitDefinition(Conv); 10397 L->CompletedImplicitDefinition(Invoke); 10398 } 10399 } 10400 10401 void Sema::DefineImplicitLambdaToBlockPointerConversion( 10402 SourceLocation CurrentLocation, 10403 CXXConversionDecl *Conv) 10404 { 10405 Conv->markUsed(Context); 10406 10407 SynthesizedFunctionScope Scope(*this, Conv); 10408 DiagnosticErrorTrap Trap(Diags); 10409 10410 // Copy-initialize the lambda object as needed to capture it. 10411 Expr *This = ActOnCXXThis(CurrentLocation).take(); 10412 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 10413 10414 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 10415 Conv->getLocation(), 10416 Conv, DerefThis); 10417 10418 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 10419 // behavior. Note that only the general conversion function does this 10420 // (since it's unusable otherwise); in the case where we inline the 10421 // block literal, it has block literal lifetime semantics. 10422 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 10423 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 10424 CK_CopyAndAutoreleaseBlockObject, 10425 BuildBlock.get(), 0, VK_RValue); 10426 10427 if (BuildBlock.isInvalid()) { 10428 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10429 Conv->setInvalidDecl(); 10430 return; 10431 } 10432 10433 // Create the return statement that returns the block from the conversion 10434 // function. 10435 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 10436 if (Return.isInvalid()) { 10437 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10438 Conv->setInvalidDecl(); 10439 return; 10440 } 10441 10442 // Set the body of the conversion function. 10443 Stmt *ReturnS = Return.take(); 10444 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 10445 Conv->getLocation(), 10446 Conv->getLocation())); 10447 10448 // We're done; notify the mutation listener, if any. 10449 if (ASTMutationListener *L = getASTMutationListener()) { 10450 L->CompletedImplicitDefinition(Conv); 10451 } 10452 } 10453 10454 /// \brief Determine whether the given list arguments contains exactly one 10455 /// "real" (non-default) argument. 10456 static bool hasOneRealArgument(MultiExprArg Args) { 10457 switch (Args.size()) { 10458 case 0: 10459 return false; 10460 10461 default: 10462 if (!Args[1]->isDefaultArgument()) 10463 return false; 10464 10465 // fall through 10466 case 1: 10467 return !Args[0]->isDefaultArgument(); 10468 } 10469 10470 return false; 10471 } 10472 10473 ExprResult 10474 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10475 CXXConstructorDecl *Constructor, 10476 MultiExprArg ExprArgs, 10477 bool HadMultipleCandidates, 10478 bool IsListInitialization, 10479 bool RequiresZeroInit, 10480 unsigned ConstructKind, 10481 SourceRange ParenRange) { 10482 bool Elidable = false; 10483 10484 // C++0x [class.copy]p34: 10485 // When certain criteria are met, an implementation is allowed to 10486 // omit the copy/move construction of a class object, even if the 10487 // copy/move constructor and/or destructor for the object have 10488 // side effects. [...] 10489 // - when a temporary class object that has not been bound to a 10490 // reference (12.2) would be copied/moved to a class object 10491 // with the same cv-unqualified type, the copy/move operation 10492 // can be omitted by constructing the temporary object 10493 // directly into the target of the omitted copy/move 10494 if (ConstructKind == CXXConstructExpr::CK_Complete && 10495 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10496 Expr *SubExpr = ExprArgs[0]; 10497 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10498 } 10499 10500 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10501 Elidable, ExprArgs, HadMultipleCandidates, 10502 IsListInitialization, RequiresZeroInit, 10503 ConstructKind, ParenRange); 10504 } 10505 10506 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 10507 /// including handling of its default argument expressions. 10508 ExprResult 10509 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10510 CXXConstructorDecl *Constructor, bool Elidable, 10511 MultiExprArg ExprArgs, 10512 bool HadMultipleCandidates, 10513 bool IsListInitialization, 10514 bool RequiresZeroInit, 10515 unsigned ConstructKind, 10516 SourceRange ParenRange) { 10517 MarkFunctionReferenced(ConstructLoc, Constructor); 10518 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 10519 Constructor, Elidable, ExprArgs, 10520 HadMultipleCandidates, 10521 IsListInitialization, RequiresZeroInit, 10522 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10523 ParenRange)); 10524 } 10525 10526 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10527 if (VD->isInvalidDecl()) return; 10528 10529 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10530 if (ClassDecl->isInvalidDecl()) return; 10531 if (ClassDecl->hasIrrelevantDestructor()) return; 10532 if (ClassDecl->isDependentContext()) return; 10533 10534 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10535 MarkFunctionReferenced(VD->getLocation(), Destructor); 10536 CheckDestructorAccess(VD->getLocation(), Destructor, 10537 PDiag(diag::err_access_dtor_var) 10538 << VD->getDeclName() 10539 << VD->getType()); 10540 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10541 10542 if (!VD->hasGlobalStorage()) return; 10543 10544 // Emit warning for non-trivial dtor in global scope (a real global, 10545 // class-static, function-static). 10546 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10547 10548 // TODO: this should be re-enabled for static locals by !CXAAtExit 10549 if (!VD->isStaticLocal()) 10550 Diag(VD->getLocation(), diag::warn_global_destructor); 10551 } 10552 10553 /// \brief Given a constructor and the set of arguments provided for the 10554 /// constructor, convert the arguments and add any required default arguments 10555 /// to form a proper call to this constructor. 10556 /// 10557 /// \returns true if an error occurred, false otherwise. 10558 bool 10559 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10560 MultiExprArg ArgsPtr, 10561 SourceLocation Loc, 10562 SmallVectorImpl<Expr*> &ConvertedArgs, 10563 bool AllowExplicit, 10564 bool IsListInitialization) { 10565 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10566 unsigned NumArgs = ArgsPtr.size(); 10567 Expr **Args = ArgsPtr.data(); 10568 10569 const FunctionProtoType *Proto 10570 = Constructor->getType()->getAs<FunctionProtoType>(); 10571 assert(Proto && "Constructor without a prototype?"); 10572 unsigned NumArgsInProto = Proto->getNumArgs(); 10573 10574 // If too few arguments are available, we'll fill in the rest with defaults. 10575 if (NumArgs < NumArgsInProto) 10576 ConvertedArgs.reserve(NumArgsInProto); 10577 else 10578 ConvertedArgs.reserve(NumArgs); 10579 10580 VariadicCallType CallType = 10581 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10582 SmallVector<Expr *, 8> AllArgs; 10583 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10584 Proto, 0, 10585 llvm::makeArrayRef(Args, NumArgs), 10586 AllArgs, 10587 CallType, AllowExplicit, 10588 IsListInitialization); 10589 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 10590 10591 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 10592 10593 CheckConstructorCall(Constructor, 10594 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 10595 AllArgs.size()), 10596 Proto, Loc); 10597 10598 return Invalid; 10599 } 10600 10601 static inline bool 10602 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 10603 const FunctionDecl *FnDecl) { 10604 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 10605 if (isa<NamespaceDecl>(DC)) { 10606 return SemaRef.Diag(FnDecl->getLocation(), 10607 diag::err_operator_new_delete_declared_in_namespace) 10608 << FnDecl->getDeclName(); 10609 } 10610 10611 if (isa<TranslationUnitDecl>(DC) && 10612 FnDecl->getStorageClass() == SC_Static) { 10613 return SemaRef.Diag(FnDecl->getLocation(), 10614 diag::err_operator_new_delete_declared_static) 10615 << FnDecl->getDeclName(); 10616 } 10617 10618 return false; 10619 } 10620 10621 static inline bool 10622 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 10623 CanQualType ExpectedResultType, 10624 CanQualType ExpectedFirstParamType, 10625 unsigned DependentParamTypeDiag, 10626 unsigned InvalidParamTypeDiag) { 10627 QualType ResultType = 10628 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 10629 10630 // Check that the result type is not dependent. 10631 if (ResultType->isDependentType()) 10632 return SemaRef.Diag(FnDecl->getLocation(), 10633 diag::err_operator_new_delete_dependent_result_type) 10634 << FnDecl->getDeclName() << ExpectedResultType; 10635 10636 // Check that the result type is what we expect. 10637 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 10638 return SemaRef.Diag(FnDecl->getLocation(), 10639 diag::err_operator_new_delete_invalid_result_type) 10640 << FnDecl->getDeclName() << ExpectedResultType; 10641 10642 // A function template must have at least 2 parameters. 10643 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 10644 return SemaRef.Diag(FnDecl->getLocation(), 10645 diag::err_operator_new_delete_template_too_few_parameters) 10646 << FnDecl->getDeclName(); 10647 10648 // The function decl must have at least 1 parameter. 10649 if (FnDecl->getNumParams() == 0) 10650 return SemaRef.Diag(FnDecl->getLocation(), 10651 diag::err_operator_new_delete_too_few_parameters) 10652 << FnDecl->getDeclName(); 10653 10654 // Check the first parameter type is not dependent. 10655 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10656 if (FirstParamType->isDependentType()) 10657 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10658 << FnDecl->getDeclName() << ExpectedFirstParamType; 10659 10660 // Check that the first parameter type is what we expect. 10661 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10662 ExpectedFirstParamType) 10663 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10664 << FnDecl->getDeclName() << ExpectedFirstParamType; 10665 10666 return false; 10667 } 10668 10669 static bool 10670 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10671 // C++ [basic.stc.dynamic.allocation]p1: 10672 // A program is ill-formed if an allocation function is declared in a 10673 // namespace scope other than global scope or declared static in global 10674 // scope. 10675 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10676 return true; 10677 10678 CanQualType SizeTy = 10679 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10680 10681 // C++ [basic.stc.dynamic.allocation]p1: 10682 // The return type shall be void*. The first parameter shall have type 10683 // std::size_t. 10684 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10685 SizeTy, 10686 diag::err_operator_new_dependent_param_type, 10687 diag::err_operator_new_param_type)) 10688 return true; 10689 10690 // C++ [basic.stc.dynamic.allocation]p1: 10691 // The first parameter shall not have an associated default argument. 10692 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10693 return SemaRef.Diag(FnDecl->getLocation(), 10694 diag::err_operator_new_default_arg) 10695 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10696 10697 return false; 10698 } 10699 10700 static bool 10701 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10702 // C++ [basic.stc.dynamic.deallocation]p1: 10703 // A program is ill-formed if deallocation functions are declared in a 10704 // namespace scope other than global scope or declared static in global 10705 // scope. 10706 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10707 return true; 10708 10709 // C++ [basic.stc.dynamic.deallocation]p2: 10710 // Each deallocation function shall return void and its first parameter 10711 // shall be void*. 10712 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10713 SemaRef.Context.VoidPtrTy, 10714 diag::err_operator_delete_dependent_param_type, 10715 diag::err_operator_delete_param_type)) 10716 return true; 10717 10718 return false; 10719 } 10720 10721 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 10722 /// of this overloaded operator is well-formed. If so, returns false; 10723 /// otherwise, emits appropriate diagnostics and returns true. 10724 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10725 assert(FnDecl && FnDecl->isOverloadedOperator() && 10726 "Expected an overloaded operator declaration"); 10727 10728 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10729 10730 // C++ [over.oper]p5: 10731 // The allocation and deallocation functions, operator new, 10732 // operator new[], operator delete and operator delete[], are 10733 // described completely in 3.7.3. The attributes and restrictions 10734 // found in the rest of this subclause do not apply to them unless 10735 // explicitly stated in 3.7.3. 10736 if (Op == OO_Delete || Op == OO_Array_Delete) 10737 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10738 10739 if (Op == OO_New || Op == OO_Array_New) 10740 return CheckOperatorNewDeclaration(*this, FnDecl); 10741 10742 // C++ [over.oper]p6: 10743 // An operator function shall either be a non-static member 10744 // function or be a non-member function and have at least one 10745 // parameter whose type is a class, a reference to a class, an 10746 // enumeration, or a reference to an enumeration. 10747 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 10748 if (MethodDecl->isStatic()) 10749 return Diag(FnDecl->getLocation(), 10750 diag::err_operator_overload_static) << FnDecl->getDeclName(); 10751 } else { 10752 bool ClassOrEnumParam = false; 10753 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10754 ParamEnd = FnDecl->param_end(); 10755 Param != ParamEnd; ++Param) { 10756 QualType ParamType = (*Param)->getType().getNonReferenceType(); 10757 if (ParamType->isDependentType() || ParamType->isRecordType() || 10758 ParamType->isEnumeralType()) { 10759 ClassOrEnumParam = true; 10760 break; 10761 } 10762 } 10763 10764 if (!ClassOrEnumParam) 10765 return Diag(FnDecl->getLocation(), 10766 diag::err_operator_overload_needs_class_or_enum) 10767 << FnDecl->getDeclName(); 10768 } 10769 10770 // C++ [over.oper]p8: 10771 // An operator function cannot have default arguments (8.3.6), 10772 // except where explicitly stated below. 10773 // 10774 // Only the function-call operator allows default arguments 10775 // (C++ [over.call]p1). 10776 if (Op != OO_Call) { 10777 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10778 Param != FnDecl->param_end(); ++Param) { 10779 if ((*Param)->hasDefaultArg()) 10780 return Diag((*Param)->getLocation(), 10781 diag::err_operator_overload_default_arg) 10782 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 10783 } 10784 } 10785 10786 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 10787 { false, false, false } 10788 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 10789 , { Unary, Binary, MemberOnly } 10790 #include "clang/Basic/OperatorKinds.def" 10791 }; 10792 10793 bool CanBeUnaryOperator = OperatorUses[Op][0]; 10794 bool CanBeBinaryOperator = OperatorUses[Op][1]; 10795 bool MustBeMemberOperator = OperatorUses[Op][2]; 10796 10797 // C++ [over.oper]p8: 10798 // [...] Operator functions cannot have more or fewer parameters 10799 // than the number required for the corresponding operator, as 10800 // described in the rest of this subclause. 10801 unsigned NumParams = FnDecl->getNumParams() 10802 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 10803 if (Op != OO_Call && 10804 ((NumParams == 1 && !CanBeUnaryOperator) || 10805 (NumParams == 2 && !CanBeBinaryOperator) || 10806 (NumParams < 1) || (NumParams > 2))) { 10807 // We have the wrong number of parameters. 10808 unsigned ErrorKind; 10809 if (CanBeUnaryOperator && CanBeBinaryOperator) { 10810 ErrorKind = 2; // 2 -> unary or binary. 10811 } else if (CanBeUnaryOperator) { 10812 ErrorKind = 0; // 0 -> unary 10813 } else { 10814 assert(CanBeBinaryOperator && 10815 "All non-call overloaded operators are unary or binary!"); 10816 ErrorKind = 1; // 1 -> binary 10817 } 10818 10819 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 10820 << FnDecl->getDeclName() << NumParams << ErrorKind; 10821 } 10822 10823 // Overloaded operators other than operator() cannot be variadic. 10824 if (Op != OO_Call && 10825 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 10826 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 10827 << FnDecl->getDeclName(); 10828 } 10829 10830 // Some operators must be non-static member functions. 10831 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 10832 return Diag(FnDecl->getLocation(), 10833 diag::err_operator_overload_must_be_member) 10834 << FnDecl->getDeclName(); 10835 } 10836 10837 // C++ [over.inc]p1: 10838 // The user-defined function called operator++ implements the 10839 // prefix and postfix ++ operator. If this function is a member 10840 // function with no parameters, or a non-member function with one 10841 // parameter of class or enumeration type, it defines the prefix 10842 // increment operator ++ for objects of that type. If the function 10843 // is a member function with one parameter (which shall be of type 10844 // int) or a non-member function with two parameters (the second 10845 // of which shall be of type int), it defines the postfix 10846 // increment operator ++ for objects of that type. 10847 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 10848 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 10849 bool ParamIsInt = false; 10850 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 10851 ParamIsInt = BT->getKind() == BuiltinType::Int; 10852 10853 if (!ParamIsInt) 10854 return Diag(LastParam->getLocation(), 10855 diag::err_operator_overload_post_incdec_must_be_int) 10856 << LastParam->getType() << (Op == OO_MinusMinus); 10857 } 10858 10859 return false; 10860 } 10861 10862 /// CheckLiteralOperatorDeclaration - Check whether the declaration 10863 /// of this literal operator function is well-formed. If so, returns 10864 /// false; otherwise, emits appropriate diagnostics and returns true. 10865 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 10866 if (isa<CXXMethodDecl>(FnDecl)) { 10867 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 10868 << FnDecl->getDeclName(); 10869 return true; 10870 } 10871 10872 if (FnDecl->isExternC()) { 10873 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 10874 return true; 10875 } 10876 10877 bool Valid = false; 10878 10879 // This might be the definition of a literal operator template. 10880 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 10881 // This might be a specialization of a literal operator template. 10882 if (!TpDecl) 10883 TpDecl = FnDecl->getPrimaryTemplate(); 10884 10885 // template <char...> type operator "" name() is the only valid template 10886 // signature, and the only valid signature with no parameters. 10887 if (TpDecl) { 10888 if (FnDecl->param_size() == 0) { 10889 // Must have only one template parameter 10890 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 10891 if (Params->size() == 1) { 10892 NonTypeTemplateParmDecl *PmDecl = 10893 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 10894 10895 // The template parameter must be a char parameter pack. 10896 if (PmDecl && PmDecl->isTemplateParameterPack() && 10897 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 10898 Valid = true; 10899 } 10900 } 10901 } else if (FnDecl->param_size()) { 10902 // Check the first parameter 10903 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10904 10905 QualType T = (*Param)->getType().getUnqualifiedType(); 10906 10907 // unsigned long long int, long double, and any character type are allowed 10908 // as the only parameters. 10909 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 10910 Context.hasSameType(T, Context.LongDoubleTy) || 10911 Context.hasSameType(T, Context.CharTy) || 10912 Context.hasSameType(T, Context.WideCharTy) || 10913 Context.hasSameType(T, Context.Char16Ty) || 10914 Context.hasSameType(T, Context.Char32Ty)) { 10915 if (++Param == FnDecl->param_end()) 10916 Valid = true; 10917 goto FinishedParams; 10918 } 10919 10920 // Otherwise it must be a pointer to const; let's strip those qualifiers. 10921 const PointerType *PT = T->getAs<PointerType>(); 10922 if (!PT) 10923 goto FinishedParams; 10924 T = PT->getPointeeType(); 10925 if (!T.isConstQualified() || T.isVolatileQualified()) 10926 goto FinishedParams; 10927 T = T.getUnqualifiedType(); 10928 10929 // Move on to the second parameter; 10930 ++Param; 10931 10932 // If there is no second parameter, the first must be a const char * 10933 if (Param == FnDecl->param_end()) { 10934 if (Context.hasSameType(T, Context.CharTy)) 10935 Valid = true; 10936 goto FinishedParams; 10937 } 10938 10939 // const char *, const wchar_t*, const char16_t*, and const char32_t* 10940 // are allowed as the first parameter to a two-parameter function 10941 if (!(Context.hasSameType(T, Context.CharTy) || 10942 Context.hasSameType(T, Context.WideCharTy) || 10943 Context.hasSameType(T, Context.Char16Ty) || 10944 Context.hasSameType(T, Context.Char32Ty))) 10945 goto FinishedParams; 10946 10947 // The second and final parameter must be an std::size_t 10948 T = (*Param)->getType().getUnqualifiedType(); 10949 if (Context.hasSameType(T, Context.getSizeType()) && 10950 ++Param == FnDecl->param_end()) 10951 Valid = true; 10952 } 10953 10954 // FIXME: This diagnostic is absolutely terrible. 10955 FinishedParams: 10956 if (!Valid) { 10957 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 10958 << FnDecl->getDeclName(); 10959 return true; 10960 } 10961 10962 // A parameter-declaration-clause containing a default argument is not 10963 // equivalent to any of the permitted forms. 10964 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 10965 ParamEnd = FnDecl->param_end(); 10966 Param != ParamEnd; ++Param) { 10967 if ((*Param)->hasDefaultArg()) { 10968 Diag((*Param)->getDefaultArgRange().getBegin(), 10969 diag::err_literal_operator_default_argument) 10970 << (*Param)->getDefaultArgRange(); 10971 break; 10972 } 10973 } 10974 10975 StringRef LiteralName 10976 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 10977 if (LiteralName[0] != '_') { 10978 // C++11 [usrlit.suffix]p1: 10979 // Literal suffix identifiers that do not start with an underscore 10980 // are reserved for future standardization. 10981 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 10982 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 10983 } 10984 10985 return false; 10986 } 10987 10988 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 10989 /// linkage specification, including the language and (if present) 10990 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is 10991 /// the location of the language string literal, which is provided 10992 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of 10993 /// the '{' brace. Otherwise, this linkage specification does not 10994 /// have any braces. 10995 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 10996 SourceLocation LangLoc, 10997 StringRef Lang, 10998 SourceLocation LBraceLoc) { 10999 LinkageSpecDecl::LanguageIDs Language; 11000 if (Lang == "\"C\"") 11001 Language = LinkageSpecDecl::lang_c; 11002 else if (Lang == "\"C++\"") 11003 Language = LinkageSpecDecl::lang_cxx; 11004 else { 11005 Diag(LangLoc, diag::err_bad_language); 11006 return 0; 11007 } 11008 11009 // FIXME: Add all the various semantics of linkage specifications 11010 11011 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 11012 ExternLoc, LangLoc, Language, 11013 LBraceLoc.isValid()); 11014 CurContext->addDecl(D); 11015 PushDeclContext(S, D); 11016 return D; 11017 } 11018 11019 /// ActOnFinishLinkageSpecification - Complete the definition of 11020 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11021 /// valid, it's the position of the closing '}' brace in a linkage 11022 /// specification that uses braces. 11023 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11024 Decl *LinkageSpec, 11025 SourceLocation RBraceLoc) { 11026 if (LinkageSpec) { 11027 if (RBraceLoc.isValid()) { 11028 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11029 LSDecl->setRBraceLoc(RBraceLoc); 11030 } 11031 PopDeclContext(); 11032 } 11033 return LinkageSpec; 11034 } 11035 11036 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11037 AttributeList *AttrList, 11038 SourceLocation SemiLoc) { 11039 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11040 // Attribute declarations appertain to empty declaration so we handle 11041 // them here. 11042 if (AttrList) 11043 ProcessDeclAttributeList(S, ED, AttrList); 11044 11045 CurContext->addDecl(ED); 11046 return ED; 11047 } 11048 11049 /// \brief Perform semantic analysis for the variable declaration that 11050 /// occurs within a C++ catch clause, returning the newly-created 11051 /// variable. 11052 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11053 TypeSourceInfo *TInfo, 11054 SourceLocation StartLoc, 11055 SourceLocation Loc, 11056 IdentifierInfo *Name) { 11057 bool Invalid = false; 11058 QualType ExDeclType = TInfo->getType(); 11059 11060 // Arrays and functions decay. 11061 if (ExDeclType->isArrayType()) 11062 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11063 else if (ExDeclType->isFunctionType()) 11064 ExDeclType = Context.getPointerType(ExDeclType); 11065 11066 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11067 // The exception-declaration shall not denote a pointer or reference to an 11068 // incomplete type, other than [cv] void*. 11069 // N2844 forbids rvalue references. 11070 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11071 Diag(Loc, diag::err_catch_rvalue_ref); 11072 Invalid = true; 11073 } 11074 11075 QualType BaseType = ExDeclType; 11076 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11077 unsigned DK = diag::err_catch_incomplete; 11078 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11079 BaseType = Ptr->getPointeeType(); 11080 Mode = 1; 11081 DK = diag::err_catch_incomplete_ptr; 11082 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11083 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11084 BaseType = Ref->getPointeeType(); 11085 Mode = 2; 11086 DK = diag::err_catch_incomplete_ref; 11087 } 11088 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11089 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11090 Invalid = true; 11091 11092 if (!Invalid && !ExDeclType->isDependentType() && 11093 RequireNonAbstractType(Loc, ExDeclType, 11094 diag::err_abstract_type_in_decl, 11095 AbstractVariableType)) 11096 Invalid = true; 11097 11098 // Only the non-fragile NeXT runtime currently supports C++ catches 11099 // of ObjC types, and no runtime supports catching ObjC types by value. 11100 if (!Invalid && getLangOpts().ObjC1) { 11101 QualType T = ExDeclType; 11102 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11103 T = RT->getPointeeType(); 11104 11105 if (T->isObjCObjectType()) { 11106 Diag(Loc, diag::err_objc_object_catch); 11107 Invalid = true; 11108 } else if (T->isObjCObjectPointerType()) { 11109 // FIXME: should this be a test for macosx-fragile specifically? 11110 if (getLangOpts().ObjCRuntime.isFragile()) 11111 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11112 } 11113 } 11114 11115 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11116 ExDeclType, TInfo, SC_None); 11117 ExDecl->setExceptionVariable(true); 11118 11119 // In ARC, infer 'retaining' for variables of retainable type. 11120 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11121 Invalid = true; 11122 11123 if (!Invalid && !ExDeclType->isDependentType()) { 11124 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11125 // Insulate this from anything else we might currently be parsing. 11126 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11127 11128 // C++ [except.handle]p16: 11129 // The object declared in an exception-declaration or, if the 11130 // exception-declaration does not specify a name, a temporary (12.2) is 11131 // copy-initialized (8.5) from the exception object. [...] 11132 // The object is destroyed when the handler exits, after the destruction 11133 // of any automatic objects initialized within the handler. 11134 // 11135 // We just pretend to initialize the object with itself, then make sure 11136 // it can be destroyed later. 11137 QualType initType = ExDeclType; 11138 11139 InitializedEntity entity = 11140 InitializedEntity::InitializeVariable(ExDecl); 11141 InitializationKind initKind = 11142 InitializationKind::CreateCopy(Loc, SourceLocation()); 11143 11144 Expr *opaqueValue = 11145 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11146 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11147 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11148 if (result.isInvalid()) 11149 Invalid = true; 11150 else { 11151 // If the constructor used was non-trivial, set this as the 11152 // "initializer". 11153 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>(); 11154 if (!construct->getConstructor()->isTrivial()) { 11155 Expr *init = MaybeCreateExprWithCleanups(construct); 11156 ExDecl->setInit(init); 11157 } 11158 11159 // And make sure it's destructable. 11160 FinalizeVarWithDestructor(ExDecl, recordType); 11161 } 11162 } 11163 } 11164 11165 if (Invalid) 11166 ExDecl->setInvalidDecl(); 11167 11168 return ExDecl; 11169 } 11170 11171 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11172 /// handler. 11173 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11174 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11175 bool Invalid = D.isInvalidType(); 11176 11177 // Check for unexpanded parameter packs. 11178 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11179 UPPC_ExceptionType)) { 11180 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11181 D.getIdentifierLoc()); 11182 Invalid = true; 11183 } 11184 11185 IdentifierInfo *II = D.getIdentifier(); 11186 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11187 LookupOrdinaryName, 11188 ForRedeclaration)) { 11189 // The scope should be freshly made just for us. There is just no way 11190 // it contains any previous declaration. 11191 assert(!S->isDeclScope(PrevDecl)); 11192 if (PrevDecl->isTemplateParameter()) { 11193 // Maybe we will complain about the shadowed template parameter. 11194 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11195 PrevDecl = 0; 11196 } 11197 } 11198 11199 if (D.getCXXScopeSpec().isSet() && !Invalid) { 11200 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 11201 << D.getCXXScopeSpec().getRange(); 11202 Invalid = true; 11203 } 11204 11205 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 11206 D.getLocStart(), 11207 D.getIdentifierLoc(), 11208 D.getIdentifier()); 11209 if (Invalid) 11210 ExDecl->setInvalidDecl(); 11211 11212 // Add the exception declaration into this scope. 11213 if (II) 11214 PushOnScopeChains(ExDecl, S); 11215 else 11216 CurContext->addDecl(ExDecl); 11217 11218 ProcessDeclAttributes(S, ExDecl, D); 11219 return ExDecl; 11220 } 11221 11222 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11223 Expr *AssertExpr, 11224 Expr *AssertMessageExpr, 11225 SourceLocation RParenLoc) { 11226 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 11227 11228 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 11229 return 0; 11230 11231 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 11232 AssertMessage, RParenLoc, false); 11233 } 11234 11235 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11236 Expr *AssertExpr, 11237 StringLiteral *AssertMessage, 11238 SourceLocation RParenLoc, 11239 bool Failed) { 11240 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 11241 !Failed) { 11242 // In a static_assert-declaration, the constant-expression shall be a 11243 // constant expression that can be contextually converted to bool. 11244 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 11245 if (Converted.isInvalid()) 11246 Failed = true; 11247 11248 llvm::APSInt Cond; 11249 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 11250 diag::err_static_assert_expression_is_not_constant, 11251 /*AllowFold=*/false).isInvalid()) 11252 Failed = true; 11253 11254 if (!Failed && !Cond) { 11255 SmallString<256> MsgBuffer; 11256 llvm::raw_svector_ostream Msg(MsgBuffer); 11257 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 11258 Diag(StaticAssertLoc, diag::err_static_assert_failed) 11259 << Msg.str() << AssertExpr->getSourceRange(); 11260 Failed = true; 11261 } 11262 } 11263 11264 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 11265 AssertExpr, AssertMessage, RParenLoc, 11266 Failed); 11267 11268 CurContext->addDecl(Decl); 11269 return Decl; 11270 } 11271 11272 /// \brief Perform semantic analysis of the given friend type declaration. 11273 /// 11274 /// \returns A friend declaration that. 11275 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 11276 SourceLocation FriendLoc, 11277 TypeSourceInfo *TSInfo) { 11278 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 11279 11280 QualType T = TSInfo->getType(); 11281 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 11282 11283 // C++03 [class.friend]p2: 11284 // An elaborated-type-specifier shall be used in a friend declaration 11285 // for a class.* 11286 // 11287 // * The class-key of the elaborated-type-specifier is required. 11288 if (!ActiveTemplateInstantiations.empty()) { 11289 // Do not complain about the form of friend template types during 11290 // template instantiation; we will already have complained when the 11291 // template was declared. 11292 } else { 11293 if (!T->isElaboratedTypeSpecifier()) { 11294 // If we evaluated the type to a record type, suggest putting 11295 // a tag in front. 11296 if (const RecordType *RT = T->getAs<RecordType>()) { 11297 RecordDecl *RD = RT->getDecl(); 11298 11299 std::string InsertionText = std::string(" ") + RD->getKindName(); 11300 11301 Diag(TypeRange.getBegin(), 11302 getLangOpts().CPlusPlus11 ? 11303 diag::warn_cxx98_compat_unelaborated_friend_type : 11304 diag::ext_unelaborated_friend_type) 11305 << (unsigned) RD->getTagKind() 11306 << T 11307 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 11308 InsertionText); 11309 } else { 11310 Diag(FriendLoc, 11311 getLangOpts().CPlusPlus11 ? 11312 diag::warn_cxx98_compat_nonclass_type_friend : 11313 diag::ext_nonclass_type_friend) 11314 << T 11315 << TypeRange; 11316 } 11317 } else if (T->getAs<EnumType>()) { 11318 Diag(FriendLoc, 11319 getLangOpts().CPlusPlus11 ? 11320 diag::warn_cxx98_compat_enum_friend : 11321 diag::ext_enum_friend) 11322 << T 11323 << TypeRange; 11324 } 11325 11326 // C++11 [class.friend]p3: 11327 // A friend declaration that does not declare a function shall have one 11328 // of the following forms: 11329 // friend elaborated-type-specifier ; 11330 // friend simple-type-specifier ; 11331 // friend typename-specifier ; 11332 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 11333 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 11334 } 11335 11336 // If the type specifier in a friend declaration designates a (possibly 11337 // cv-qualified) class type, that class is declared as a friend; otherwise, 11338 // the friend declaration is ignored. 11339 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 11340 } 11341 11342 /// Handle a friend tag declaration where the scope specifier was 11343 /// templated. 11344 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 11345 unsigned TagSpec, SourceLocation TagLoc, 11346 CXXScopeSpec &SS, 11347 IdentifierInfo *Name, 11348 SourceLocation NameLoc, 11349 AttributeList *Attr, 11350 MultiTemplateParamsArg TempParamLists) { 11351 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11352 11353 bool isExplicitSpecialization = false; 11354 bool Invalid = false; 11355 11356 if (TemplateParameterList *TemplateParams = 11357 MatchTemplateParametersToScopeSpecifier( 11358 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true, 11359 isExplicitSpecialization, Invalid)) { 11360 if (TemplateParams->size() > 0) { 11361 // This is a declaration of a class template. 11362 if (Invalid) 11363 return 0; 11364 11365 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 11366 SS, Name, NameLoc, Attr, 11367 TemplateParams, AS_public, 11368 /*ModulePrivateLoc=*/SourceLocation(), 11369 TempParamLists.size() - 1, 11370 TempParamLists.data()).take(); 11371 } else { 11372 // The "template<>" header is extraneous. 11373 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11374 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11375 isExplicitSpecialization = true; 11376 } 11377 } 11378 11379 if (Invalid) return 0; 11380 11381 bool isAllExplicitSpecializations = true; 11382 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 11383 if (TempParamLists[I]->size()) { 11384 isAllExplicitSpecializations = false; 11385 break; 11386 } 11387 } 11388 11389 // FIXME: don't ignore attributes. 11390 11391 // If it's explicit specializations all the way down, just forget 11392 // about the template header and build an appropriate non-templated 11393 // friend. TODO: for source fidelity, remember the headers. 11394 if (isAllExplicitSpecializations) { 11395 if (SS.isEmpty()) { 11396 bool Owned = false; 11397 bool IsDependent = false; 11398 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 11399 Attr, AS_public, 11400 /*ModulePrivateLoc=*/SourceLocation(), 11401 MultiTemplateParamsArg(), Owned, IsDependent, 11402 /*ScopedEnumKWLoc=*/SourceLocation(), 11403 /*ScopedEnumUsesClassTag=*/false, 11404 /*UnderlyingType=*/TypeResult()); 11405 } 11406 11407 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11408 ElaboratedTypeKeyword Keyword 11409 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11410 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 11411 *Name, NameLoc); 11412 if (T.isNull()) 11413 return 0; 11414 11415 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11416 if (isa<DependentNameType>(T)) { 11417 DependentNameTypeLoc TL = 11418 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11419 TL.setElaboratedKeywordLoc(TagLoc); 11420 TL.setQualifierLoc(QualifierLoc); 11421 TL.setNameLoc(NameLoc); 11422 } else { 11423 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11424 TL.setElaboratedKeywordLoc(TagLoc); 11425 TL.setQualifierLoc(QualifierLoc); 11426 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 11427 } 11428 11429 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11430 TSI, FriendLoc, TempParamLists); 11431 Friend->setAccess(AS_public); 11432 CurContext->addDecl(Friend); 11433 return Friend; 11434 } 11435 11436 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 11437 11438 11439 11440 // Handle the case of a templated-scope friend class. e.g. 11441 // template <class T> class A<T>::B; 11442 // FIXME: we don't support these right now. 11443 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11444 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 11445 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11446 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11447 TL.setElaboratedKeywordLoc(TagLoc); 11448 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11449 TL.setNameLoc(NameLoc); 11450 11451 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11452 TSI, FriendLoc, TempParamLists); 11453 Friend->setAccess(AS_public); 11454 Friend->setUnsupportedFriend(true); 11455 CurContext->addDecl(Friend); 11456 return Friend; 11457 } 11458 11459 11460 /// Handle a friend type declaration. This works in tandem with 11461 /// ActOnTag. 11462 /// 11463 /// Notes on friend class templates: 11464 /// 11465 /// We generally treat friend class declarations as if they were 11466 /// declaring a class. So, for example, the elaborated type specifier 11467 /// in a friend declaration is required to obey the restrictions of a 11468 /// class-head (i.e. no typedefs in the scope chain), template 11469 /// parameters are required to match up with simple template-ids, &c. 11470 /// However, unlike when declaring a template specialization, it's 11471 /// okay to refer to a template specialization without an empty 11472 /// template parameter declaration, e.g. 11473 /// friend class A<T>::B<unsigned>; 11474 /// We permit this as a special case; if there are any template 11475 /// parameters present at all, require proper matching, i.e. 11476 /// template <> template \<class T> friend class A<int>::B; 11477 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 11478 MultiTemplateParamsArg TempParams) { 11479 SourceLocation Loc = DS.getLocStart(); 11480 11481 assert(DS.isFriendSpecified()); 11482 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11483 11484 // Try to convert the decl specifier to a type. This works for 11485 // friend templates because ActOnTag never produces a ClassTemplateDecl 11486 // for a TUK_Friend. 11487 Declarator TheDeclarator(DS, Declarator::MemberContext); 11488 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11489 QualType T = TSI->getType(); 11490 if (TheDeclarator.isInvalidType()) 11491 return 0; 11492 11493 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11494 return 0; 11495 11496 // This is definitely an error in C++98. It's probably meant to 11497 // be forbidden in C++0x, too, but the specification is just 11498 // poorly written. 11499 // 11500 // The problem is with declarations like the following: 11501 // template <T> friend A<T>::foo; 11502 // where deciding whether a class C is a friend or not now hinges 11503 // on whether there exists an instantiation of A that causes 11504 // 'foo' to equal C. There are restrictions on class-heads 11505 // (which we declare (by fiat) elaborated friend declarations to 11506 // be) that makes this tractable. 11507 // 11508 // FIXME: handle "template <> friend class A<T>;", which 11509 // is possibly well-formed? Who even knows? 11510 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11511 Diag(Loc, diag::err_tagless_friend_type_template) 11512 << DS.getSourceRange(); 11513 return 0; 11514 } 11515 11516 // C++98 [class.friend]p1: A friend of a class is a function 11517 // or class that is not a member of the class . . . 11518 // This is fixed in DR77, which just barely didn't make the C++03 11519 // deadline. It's also a very silly restriction that seriously 11520 // affects inner classes and which nobody else seems to implement; 11521 // thus we never diagnose it, not even in -pedantic. 11522 // 11523 // But note that we could warn about it: it's always useless to 11524 // friend one of your own members (it's not, however, worthless to 11525 // friend a member of an arbitrary specialization of your template). 11526 11527 Decl *D; 11528 if (unsigned NumTempParamLists = TempParams.size()) 11529 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11530 NumTempParamLists, 11531 TempParams.data(), 11532 TSI, 11533 DS.getFriendSpecLoc()); 11534 else 11535 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11536 11537 if (!D) 11538 return 0; 11539 11540 D->setAccess(AS_public); 11541 CurContext->addDecl(D); 11542 11543 return D; 11544 } 11545 11546 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11547 MultiTemplateParamsArg TemplateParams) { 11548 const DeclSpec &DS = D.getDeclSpec(); 11549 11550 assert(DS.isFriendSpecified()); 11551 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11552 11553 SourceLocation Loc = D.getIdentifierLoc(); 11554 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11555 11556 // C++ [class.friend]p1 11557 // A friend of a class is a function or class.... 11558 // Note that this sees through typedefs, which is intended. 11559 // It *doesn't* see through dependent types, which is correct 11560 // according to [temp.arg.type]p3: 11561 // If a declaration acquires a function type through a 11562 // type dependent on a template-parameter and this causes 11563 // a declaration that does not use the syntactic form of a 11564 // function declarator to have a function type, the program 11565 // is ill-formed. 11566 if (!TInfo->getType()->isFunctionType()) { 11567 Diag(Loc, diag::err_unexpected_friend); 11568 11569 // It might be worthwhile to try to recover by creating an 11570 // appropriate declaration. 11571 return 0; 11572 } 11573 11574 // C++ [namespace.memdef]p3 11575 // - If a friend declaration in a non-local class first declares a 11576 // class or function, the friend class or function is a member 11577 // of the innermost enclosing namespace. 11578 // - The name of the friend is not found by simple name lookup 11579 // until a matching declaration is provided in that namespace 11580 // scope (either before or after the class declaration granting 11581 // friendship). 11582 // - If a friend function is called, its name may be found by the 11583 // name lookup that considers functions from namespaces and 11584 // classes associated with the types of the function arguments. 11585 // - When looking for a prior declaration of a class or a function 11586 // declared as a friend, scopes outside the innermost enclosing 11587 // namespace scope are not considered. 11588 11589 CXXScopeSpec &SS = D.getCXXScopeSpec(); 11590 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 11591 DeclarationName Name = NameInfo.getName(); 11592 assert(Name); 11593 11594 // Check for unexpanded parameter packs. 11595 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 11596 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 11597 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 11598 return 0; 11599 11600 // The context we found the declaration in, or in which we should 11601 // create the declaration. 11602 DeclContext *DC; 11603 Scope *DCScope = S; 11604 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11605 ForRedeclaration); 11606 11607 // There are five cases here. 11608 // - There's no scope specifier and we're in a local class. Only look 11609 // for functions declared in the immediately-enclosing block scope. 11610 // We recover from invalid scope qualifiers as if they just weren't there. 11611 FunctionDecl *FunctionContainingLocalClass = 0; 11612 if ((SS.isInvalid() || !SS.isSet()) && 11613 (FunctionContainingLocalClass = 11614 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 11615 // C++11 [class.friend]p11: 11616 // If a friend declaration appears in a local class and the name 11617 // specified is an unqualified name, a prior declaration is 11618 // looked up without considering scopes that are outside the 11619 // innermost enclosing non-class scope. For a friend function 11620 // declaration, if there is no prior declaration, the program is 11621 // ill-formed. 11622 11623 // Find the innermost enclosing non-class scope. This is the block 11624 // scope containing the local class definition (or for a nested class, 11625 // the outer local class). 11626 DCScope = S->getFnParent(); 11627 11628 // Look up the function name in the scope. 11629 Previous.clear(LookupLocalFriendName); 11630 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 11631 11632 if (!Previous.empty()) { 11633 // All possible previous declarations must have the same context: 11634 // either they were declared at block scope or they are members of 11635 // one of the enclosing local classes. 11636 DC = Previous.getRepresentativeDecl()->getDeclContext(); 11637 } else { 11638 // This is ill-formed, but provide the context that we would have 11639 // declared the function in, if we were permitted to, for error recovery. 11640 DC = FunctionContainingLocalClass; 11641 } 11642 adjustContextForLocalExternDecl(DC); 11643 11644 // C++ [class.friend]p6: 11645 // A function can be defined in a friend declaration of a class if and 11646 // only if the class is a non-local class (9.8), the function name is 11647 // unqualified, and the function has namespace scope. 11648 if (D.isFunctionDefinition()) { 11649 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11650 } 11651 11652 // - There's no scope specifier, in which case we just go to the 11653 // appropriate scope and look for a function or function template 11654 // there as appropriate. 11655 } else if (SS.isInvalid() || !SS.isSet()) { 11656 // C++11 [namespace.memdef]p3: 11657 // If the name in a friend declaration is neither qualified nor 11658 // a template-id and the declaration is a function or an 11659 // elaborated-type-specifier, the lookup to determine whether 11660 // the entity has been previously declared shall not consider 11661 // any scopes outside the innermost enclosing namespace. 11662 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 11663 11664 // Find the appropriate context according to the above. 11665 DC = CurContext; 11666 11667 // Skip class contexts. If someone can cite chapter and verse 11668 // for this behavior, that would be nice --- it's what GCC and 11669 // EDG do, and it seems like a reasonable intent, but the spec 11670 // really only says that checks for unqualified existing 11671 // declarations should stop at the nearest enclosing namespace, 11672 // not that they should only consider the nearest enclosing 11673 // namespace. 11674 while (DC->isRecord()) 11675 DC = DC->getParent(); 11676 11677 DeclContext *LookupDC = DC; 11678 while (LookupDC->isTransparentContext()) 11679 LookupDC = LookupDC->getParent(); 11680 11681 while (true) { 11682 LookupQualifiedName(Previous, LookupDC); 11683 11684 if (!Previous.empty()) { 11685 DC = LookupDC; 11686 break; 11687 } 11688 11689 if (isTemplateId) { 11690 if (isa<TranslationUnitDecl>(LookupDC)) break; 11691 } else { 11692 if (LookupDC->isFileContext()) break; 11693 } 11694 LookupDC = LookupDC->getParent(); 11695 } 11696 11697 DCScope = getScopeForDeclContext(S, DC); 11698 11699 // - There's a non-dependent scope specifier, in which case we 11700 // compute it and do a previous lookup there for a function 11701 // or function template. 11702 } else if (!SS.getScopeRep()->isDependent()) { 11703 DC = computeDeclContext(SS); 11704 if (!DC) return 0; 11705 11706 if (RequireCompleteDeclContext(SS, DC)) return 0; 11707 11708 LookupQualifiedName(Previous, DC); 11709 11710 // Ignore things found implicitly in the wrong scope. 11711 // TODO: better diagnostics for this case. Suggesting the right 11712 // qualified scope would be nice... 11713 LookupResult::Filter F = Previous.makeFilter(); 11714 while (F.hasNext()) { 11715 NamedDecl *D = F.next(); 11716 if (!DC->InEnclosingNamespaceSetOf( 11717 D->getDeclContext()->getRedeclContext())) 11718 F.erase(); 11719 } 11720 F.done(); 11721 11722 if (Previous.empty()) { 11723 D.setInvalidType(); 11724 Diag(Loc, diag::err_qualified_friend_not_found) 11725 << Name << TInfo->getType(); 11726 return 0; 11727 } 11728 11729 // C++ [class.friend]p1: A friend of a class is a function or 11730 // class that is not a member of the class . . . 11731 if (DC->Equals(CurContext)) 11732 Diag(DS.getFriendSpecLoc(), 11733 getLangOpts().CPlusPlus11 ? 11734 diag::warn_cxx98_compat_friend_is_member : 11735 diag::err_friend_is_member); 11736 11737 if (D.isFunctionDefinition()) { 11738 // C++ [class.friend]p6: 11739 // A function can be defined in a friend declaration of a class if and 11740 // only if the class is a non-local class (9.8), the function name is 11741 // unqualified, and the function has namespace scope. 11742 SemaDiagnosticBuilder DB 11743 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 11744 11745 DB << SS.getScopeRep(); 11746 if (DC->isFileContext()) 11747 DB << FixItHint::CreateRemoval(SS.getRange()); 11748 SS.clear(); 11749 } 11750 11751 // - There's a scope specifier that does not match any template 11752 // parameter lists, in which case we use some arbitrary context, 11753 // create a method or method template, and wait for instantiation. 11754 // - There's a scope specifier that does match some template 11755 // parameter lists, which we don't handle right now. 11756 } else { 11757 if (D.isFunctionDefinition()) { 11758 // C++ [class.friend]p6: 11759 // A function can be defined in a friend declaration of a class if and 11760 // only if the class is a non-local class (9.8), the function name is 11761 // unqualified, and the function has namespace scope. 11762 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 11763 << SS.getScopeRep(); 11764 } 11765 11766 DC = CurContext; 11767 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 11768 } 11769 11770 if (!DC->isRecord()) { 11771 // This implies that it has to be an operator or function. 11772 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 11773 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 11774 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 11775 Diag(Loc, diag::err_introducing_special_friend) << 11776 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 11777 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 11778 return 0; 11779 } 11780 } 11781 11782 // FIXME: This is an egregious hack to cope with cases where the scope stack 11783 // does not contain the declaration context, i.e., in an out-of-line 11784 // definition of a class. 11785 Scope FakeDCScope(S, Scope::DeclScope, Diags); 11786 if (!DCScope) { 11787 FakeDCScope.setEntity(DC); 11788 DCScope = &FakeDCScope; 11789 } 11790 11791 bool AddToScope = true; 11792 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 11793 TemplateParams, AddToScope); 11794 if (!ND) return 0; 11795 11796 assert(ND->getLexicalDeclContext() == CurContext); 11797 11798 // If we performed typo correction, we might have added a scope specifier 11799 // and changed the decl context. 11800 DC = ND->getDeclContext(); 11801 11802 // Add the function declaration to the appropriate lookup tables, 11803 // adjusting the redeclarations list as necessary. We don't 11804 // want to do this yet if the friending class is dependent. 11805 // 11806 // Also update the scope-based lookup if the target context's 11807 // lookup context is in lexical scope. 11808 if (!CurContext->isDependentContext()) { 11809 DC = DC->getRedeclContext(); 11810 DC->makeDeclVisibleInContext(ND); 11811 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11812 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 11813 } 11814 11815 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 11816 D.getIdentifierLoc(), ND, 11817 DS.getFriendSpecLoc()); 11818 FrD->setAccess(AS_public); 11819 CurContext->addDecl(FrD); 11820 11821 if (ND->isInvalidDecl()) { 11822 FrD->setInvalidDecl(); 11823 } else { 11824 if (DC->isRecord()) CheckFriendAccess(ND); 11825 11826 FunctionDecl *FD; 11827 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 11828 FD = FTD->getTemplatedDecl(); 11829 else 11830 FD = cast<FunctionDecl>(ND); 11831 11832 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 11833 // default argument expression, that declaration shall be a definition 11834 // and shall be the only declaration of the function or function 11835 // template in the translation unit. 11836 if (functionDeclHasDefaultArgument(FD)) { 11837 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 11838 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 11839 Diag(OldFD->getLocation(), diag::note_previous_declaration); 11840 } else if (!D.isFunctionDefinition()) 11841 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 11842 } 11843 11844 // Mark templated-scope function declarations as unsupported. 11845 if (FD->getNumTemplateParameterLists()) 11846 FrD->setUnsupportedFriend(true); 11847 } 11848 11849 return ND; 11850 } 11851 11852 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 11853 AdjustDeclIfTemplate(Dcl); 11854 11855 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 11856 if (!Fn) { 11857 Diag(DelLoc, diag::err_deleted_non_function); 11858 return; 11859 } 11860 11861 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 11862 // Don't consider the implicit declaration we generate for explicit 11863 // specializations. FIXME: Do not generate these implicit declarations. 11864 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization 11865 || Prev->getPreviousDecl()) && !Prev->isDefined()) { 11866 Diag(DelLoc, diag::err_deleted_decl_not_first); 11867 Diag(Prev->getLocation(), diag::note_previous_declaration); 11868 } 11869 // If the declaration wasn't the first, we delete the function anyway for 11870 // recovery. 11871 Fn = Fn->getCanonicalDecl(); 11872 } 11873 11874 if (Fn->isDeleted()) 11875 return; 11876 11877 // See if we're deleting a function which is already known to override a 11878 // non-deleted virtual function. 11879 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 11880 bool IssuedDiagnostic = false; 11881 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 11882 E = MD->end_overridden_methods(); 11883 I != E; ++I) { 11884 if (!(*MD->begin_overridden_methods())->isDeleted()) { 11885 if (!IssuedDiagnostic) { 11886 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 11887 IssuedDiagnostic = true; 11888 } 11889 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 11890 } 11891 } 11892 } 11893 11894 Fn->setDeletedAsWritten(); 11895 } 11896 11897 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 11898 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 11899 11900 if (MD) { 11901 if (MD->getParent()->isDependentType()) { 11902 MD->setDefaulted(); 11903 MD->setExplicitlyDefaulted(); 11904 return; 11905 } 11906 11907 CXXSpecialMember Member = getSpecialMember(MD); 11908 if (Member == CXXInvalid) { 11909 if (!MD->isInvalidDecl()) 11910 Diag(DefaultLoc, diag::err_default_special_members); 11911 return; 11912 } 11913 11914 MD->setDefaulted(); 11915 MD->setExplicitlyDefaulted(); 11916 11917 // If this definition appears within the record, do the checking when 11918 // the record is complete. 11919 const FunctionDecl *Primary = MD; 11920 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 11921 // Find the uninstantiated declaration that actually had the '= default' 11922 // on it. 11923 Pattern->isDefined(Primary); 11924 11925 // If the method was defaulted on its first declaration, we will have 11926 // already performed the checking in CheckCompletedCXXClass. Such a 11927 // declaration doesn't trigger an implicit definition. 11928 if (Primary == Primary->getCanonicalDecl()) 11929 return; 11930 11931 CheckExplicitlyDefaultedSpecialMember(MD); 11932 11933 // The exception specification is needed because we are defining the 11934 // function. 11935 ResolveExceptionSpec(DefaultLoc, 11936 MD->getType()->castAs<FunctionProtoType>()); 11937 11938 if (MD->isInvalidDecl()) 11939 return; 11940 11941 switch (Member) { 11942 case CXXDefaultConstructor: 11943 DefineImplicitDefaultConstructor(DefaultLoc, 11944 cast<CXXConstructorDecl>(MD)); 11945 break; 11946 case CXXCopyConstructor: 11947 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 11948 break; 11949 case CXXCopyAssignment: 11950 DefineImplicitCopyAssignment(DefaultLoc, MD); 11951 break; 11952 case CXXDestructor: 11953 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 11954 break; 11955 case CXXMoveConstructor: 11956 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 11957 break; 11958 case CXXMoveAssignment: 11959 DefineImplicitMoveAssignment(DefaultLoc, MD); 11960 break; 11961 case CXXInvalid: 11962 llvm_unreachable("Invalid special member."); 11963 } 11964 } else { 11965 Diag(DefaultLoc, diag::err_default_special_members); 11966 } 11967 } 11968 11969 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 11970 for (Stmt::child_range CI = S->children(); CI; ++CI) { 11971 Stmt *SubStmt = *CI; 11972 if (!SubStmt) 11973 continue; 11974 if (isa<ReturnStmt>(SubStmt)) 11975 Self.Diag(SubStmt->getLocStart(), 11976 diag::err_return_in_constructor_handler); 11977 if (!isa<Expr>(SubStmt)) 11978 SearchForReturnInStmt(Self, SubStmt); 11979 } 11980 } 11981 11982 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 11983 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 11984 CXXCatchStmt *Handler = TryBlock->getHandler(I); 11985 SearchForReturnInStmt(*this, Handler); 11986 } 11987 } 11988 11989 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 11990 const CXXMethodDecl *Old) { 11991 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 11992 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 11993 11994 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 11995 11996 // If the calling conventions match, everything is fine 11997 if (NewCC == OldCC) 11998 return false; 11999 12000 Diag(New->getLocation(), 12001 diag::err_conflicting_overriding_cc_attributes) 12002 << New->getDeclName() << New->getType() << Old->getType(); 12003 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12004 return true; 12005 } 12006 12007 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12008 const CXXMethodDecl *Old) { 12009 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 12010 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 12011 12012 if (Context.hasSameType(NewTy, OldTy) || 12013 NewTy->isDependentType() || OldTy->isDependentType()) 12014 return false; 12015 12016 // Check if the return types are covariant 12017 QualType NewClassTy, OldClassTy; 12018 12019 /// Both types must be pointers or references to classes. 12020 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12021 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12022 NewClassTy = NewPT->getPointeeType(); 12023 OldClassTy = OldPT->getPointeeType(); 12024 } 12025 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12026 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12027 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12028 NewClassTy = NewRT->getPointeeType(); 12029 OldClassTy = OldRT->getPointeeType(); 12030 } 12031 } 12032 } 12033 12034 // The return types aren't either both pointers or references to a class type. 12035 if (NewClassTy.isNull()) { 12036 Diag(New->getLocation(), 12037 diag::err_different_return_type_for_overriding_virtual_function) 12038 << New->getDeclName() << NewTy << OldTy; 12039 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12040 12041 return true; 12042 } 12043 12044 // C++ [class.virtual]p6: 12045 // If the return type of D::f differs from the return type of B::f, the 12046 // class type in the return type of D::f shall be complete at the point of 12047 // declaration of D::f or shall be the class type D. 12048 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12049 if (!RT->isBeingDefined() && 12050 RequireCompleteType(New->getLocation(), NewClassTy, 12051 diag::err_covariant_return_incomplete, 12052 New->getDeclName())) 12053 return true; 12054 } 12055 12056 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12057 // Check if the new class derives from the old class. 12058 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12059 Diag(New->getLocation(), 12060 diag::err_covariant_return_not_derived) 12061 << New->getDeclName() << NewTy << OldTy; 12062 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12063 return true; 12064 } 12065 12066 // Check if we the conversion from derived to base is valid. 12067 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 12068 diag::err_covariant_return_inaccessible_base, 12069 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12070 // FIXME: Should this point to the return type? 12071 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 12072 // FIXME: this note won't trigger for delayed access control 12073 // diagnostics, and it's impossible to get an undelayed error 12074 // here from access control during the original parse because 12075 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12076 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12077 return true; 12078 } 12079 } 12080 12081 // The qualifiers of the return types must be the same. 12082 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12083 Diag(New->getLocation(), 12084 diag::err_covariant_return_type_different_qualifications) 12085 << New->getDeclName() << NewTy << OldTy; 12086 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12087 return true; 12088 }; 12089 12090 12091 // The new class type must have the same or less qualifiers as the old type. 12092 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12093 Diag(New->getLocation(), 12094 diag::err_covariant_return_type_class_type_more_qualified) 12095 << New->getDeclName() << NewTy << OldTy; 12096 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12097 return true; 12098 }; 12099 12100 return false; 12101 } 12102 12103 /// \brief Mark the given method pure. 12104 /// 12105 /// \param Method the method to be marked pure. 12106 /// 12107 /// \param InitRange the source range that covers the "0" initializer. 12108 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12109 SourceLocation EndLoc = InitRange.getEnd(); 12110 if (EndLoc.isValid()) 12111 Method->setRangeEnd(EndLoc); 12112 12113 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12114 Method->setPure(); 12115 return false; 12116 } 12117 12118 if (!Method->isInvalidDecl()) 12119 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12120 << Method->getDeclName() << InitRange; 12121 return true; 12122 } 12123 12124 /// \brief Determine whether the given declaration is a static data member. 12125 static bool isStaticDataMember(const Decl *D) { 12126 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12127 return Var->isStaticDataMember(); 12128 12129 return false; 12130 } 12131 12132 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12133 /// an initializer for the out-of-line declaration 'Dcl'. The scope 12134 /// is a fresh scope pushed for just this purpose. 12135 /// 12136 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12137 /// static data member of class X, names should be looked up in the scope of 12138 /// class X. 12139 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12140 // If there is no declaration, there was an error parsing it. 12141 if (D == 0 || D->isInvalidDecl()) return; 12142 12143 // We should only get called for declarations with scope specifiers, like: 12144 // int foo::bar; 12145 assert(D->isOutOfLine()); 12146 EnterDeclaratorContext(S, D->getDeclContext()); 12147 12148 // If we are parsing the initializer for a static data member, push a 12149 // new expression evaluation context that is associated with this static 12150 // data member. 12151 if (isStaticDataMember(D)) 12152 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12153 } 12154 12155 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12156 /// initializer for the out-of-line declaration 'D'. 12157 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12158 // If there is no declaration, there was an error parsing it. 12159 if (D == 0 || D->isInvalidDecl()) return; 12160 12161 if (isStaticDataMember(D)) 12162 PopExpressionEvaluationContext(); 12163 12164 assert(D->isOutOfLine()); 12165 ExitDeclaratorContext(S); 12166 } 12167 12168 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 12169 /// C++ if/switch/while/for statement. 12170 /// e.g: "if (int x = f()) {...}" 12171 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 12172 // C++ 6.4p2: 12173 // The declarator shall not specify a function or an array. 12174 // The type-specifier-seq shall not contain typedef and shall not declare a 12175 // new class or enumeration. 12176 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 12177 "Parser allowed 'typedef' as storage class of condition decl."); 12178 12179 Decl *Dcl = ActOnDeclarator(S, D); 12180 if (!Dcl) 12181 return true; 12182 12183 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 12184 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 12185 << D.getSourceRange(); 12186 return true; 12187 } 12188 12189 return Dcl; 12190 } 12191 12192 void Sema::LoadExternalVTableUses() { 12193 if (!ExternalSource) 12194 return; 12195 12196 SmallVector<ExternalVTableUse, 4> VTables; 12197 ExternalSource->ReadUsedVTables(VTables); 12198 SmallVector<VTableUse, 4> NewUses; 12199 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 12200 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 12201 = VTablesUsed.find(VTables[I].Record); 12202 // Even if a definition wasn't required before, it may be required now. 12203 if (Pos != VTablesUsed.end()) { 12204 if (!Pos->second && VTables[I].DefinitionRequired) 12205 Pos->second = true; 12206 continue; 12207 } 12208 12209 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 12210 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 12211 } 12212 12213 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 12214 } 12215 12216 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 12217 bool DefinitionRequired) { 12218 // Ignore any vtable uses in unevaluated operands or for classes that do 12219 // not have a vtable. 12220 if (!Class->isDynamicClass() || Class->isDependentContext() || 12221 CurContext->isDependentContext() || isUnevaluatedContext()) 12222 return; 12223 12224 // Try to insert this class into the map. 12225 LoadExternalVTableUses(); 12226 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12227 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 12228 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 12229 if (!Pos.second) { 12230 // If we already had an entry, check to see if we are promoting this vtable 12231 // to required a definition. If so, we need to reappend to the VTableUses 12232 // list, since we may have already processed the first entry. 12233 if (DefinitionRequired && !Pos.first->second) { 12234 Pos.first->second = true; 12235 } else { 12236 // Otherwise, we can early exit. 12237 return; 12238 } 12239 } 12240 12241 // Local classes need to have their virtual members marked 12242 // immediately. For all other classes, we mark their virtual members 12243 // at the end of the translation unit. 12244 if (Class->isLocalClass()) 12245 MarkVirtualMembersReferenced(Loc, Class); 12246 else 12247 VTableUses.push_back(std::make_pair(Class, Loc)); 12248 } 12249 12250 bool Sema::DefineUsedVTables() { 12251 LoadExternalVTableUses(); 12252 if (VTableUses.empty()) 12253 return false; 12254 12255 // Note: The VTableUses vector could grow as a result of marking 12256 // the members of a class as "used", so we check the size each 12257 // time through the loop and prefer indices (which are stable) to 12258 // iterators (which are not). 12259 bool DefinedAnything = false; 12260 for (unsigned I = 0; I != VTableUses.size(); ++I) { 12261 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 12262 if (!Class) 12263 continue; 12264 12265 SourceLocation Loc = VTableUses[I].second; 12266 12267 bool DefineVTable = true; 12268 12269 // If this class has a key function, but that key function is 12270 // defined in another translation unit, we don't need to emit the 12271 // vtable even though we're using it. 12272 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 12273 if (KeyFunction && !KeyFunction->hasBody()) { 12274 // The key function is in another translation unit. 12275 DefineVTable = false; 12276 TemplateSpecializationKind TSK = 12277 KeyFunction->getTemplateSpecializationKind(); 12278 assert(TSK != TSK_ExplicitInstantiationDefinition && 12279 TSK != TSK_ImplicitInstantiation && 12280 "Instantiations don't have key functions"); 12281 (void)TSK; 12282 } else if (!KeyFunction) { 12283 // If we have a class with no key function that is the subject 12284 // of an explicit instantiation declaration, suppress the 12285 // vtable; it will live with the explicit instantiation 12286 // definition. 12287 bool IsExplicitInstantiationDeclaration 12288 = Class->getTemplateSpecializationKind() 12289 == TSK_ExplicitInstantiationDeclaration; 12290 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 12291 REnd = Class->redecls_end(); 12292 R != REnd; ++R) { 12293 TemplateSpecializationKind TSK 12294 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 12295 if (TSK == TSK_ExplicitInstantiationDeclaration) 12296 IsExplicitInstantiationDeclaration = true; 12297 else if (TSK == TSK_ExplicitInstantiationDefinition) { 12298 IsExplicitInstantiationDeclaration = false; 12299 break; 12300 } 12301 } 12302 12303 if (IsExplicitInstantiationDeclaration) 12304 DefineVTable = false; 12305 } 12306 12307 // The exception specifications for all virtual members may be needed even 12308 // if we are not providing an authoritative form of the vtable in this TU. 12309 // We may choose to emit it available_externally anyway. 12310 if (!DefineVTable) { 12311 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 12312 continue; 12313 } 12314 12315 // Mark all of the virtual members of this class as referenced, so 12316 // that we can build a vtable. Then, tell the AST consumer that a 12317 // vtable for this class is required. 12318 DefinedAnything = true; 12319 MarkVirtualMembersReferenced(Loc, Class); 12320 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12321 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 12322 12323 // Optionally warn if we're emitting a weak vtable. 12324 if (Class->isExternallyVisible() && 12325 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 12326 const FunctionDecl *KeyFunctionDef = 0; 12327 if (!KeyFunction || 12328 (KeyFunction->hasBody(KeyFunctionDef) && 12329 KeyFunctionDef->isInlined())) 12330 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 12331 TSK_ExplicitInstantiationDefinition 12332 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 12333 << Class; 12334 } 12335 } 12336 VTableUses.clear(); 12337 12338 return DefinedAnything; 12339 } 12340 12341 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 12342 const CXXRecordDecl *RD) { 12343 for (CXXRecordDecl::method_iterator I = RD->method_begin(), 12344 E = RD->method_end(); I != E; ++I) 12345 if ((*I)->isVirtual() && !(*I)->isPure()) 12346 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>()); 12347 } 12348 12349 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 12350 const CXXRecordDecl *RD) { 12351 // Mark all functions which will appear in RD's vtable as used. 12352 CXXFinalOverriderMap FinalOverriders; 12353 RD->getFinalOverriders(FinalOverriders); 12354 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 12355 E = FinalOverriders.end(); 12356 I != E; ++I) { 12357 for (OverridingMethods::const_iterator OI = I->second.begin(), 12358 OE = I->second.end(); 12359 OI != OE; ++OI) { 12360 assert(OI->second.size() > 0 && "no final overrider"); 12361 CXXMethodDecl *Overrider = OI->second.front().Method; 12362 12363 // C++ [basic.def.odr]p2: 12364 // [...] A virtual member function is used if it is not pure. [...] 12365 if (!Overrider->isPure()) 12366 MarkFunctionReferenced(Loc, Overrider); 12367 } 12368 } 12369 12370 // Only classes that have virtual bases need a VTT. 12371 if (RD->getNumVBases() == 0) 12372 return; 12373 12374 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 12375 e = RD->bases_end(); i != e; ++i) { 12376 const CXXRecordDecl *Base = 12377 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 12378 if (Base->getNumVBases() == 0) 12379 continue; 12380 MarkVirtualMembersReferenced(Loc, Base); 12381 } 12382 } 12383 12384 /// SetIvarInitializers - This routine builds initialization ASTs for the 12385 /// Objective-C implementation whose ivars need be initialized. 12386 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 12387 if (!getLangOpts().CPlusPlus) 12388 return; 12389 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 12390 SmallVector<ObjCIvarDecl*, 8> ivars; 12391 CollectIvarsToConstructOrDestruct(OID, ivars); 12392 if (ivars.empty()) 12393 return; 12394 SmallVector<CXXCtorInitializer*, 32> AllToInit; 12395 for (unsigned i = 0; i < ivars.size(); i++) { 12396 FieldDecl *Field = ivars[i]; 12397 if (Field->isInvalidDecl()) 12398 continue; 12399 12400 CXXCtorInitializer *Member; 12401 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 12402 InitializationKind InitKind = 12403 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 12404 12405 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 12406 ExprResult MemberInit = 12407 InitSeq.Perform(*this, InitEntity, InitKind, None); 12408 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 12409 // Note, MemberInit could actually come back empty if no initialization 12410 // is required (e.g., because it would call a trivial default constructor) 12411 if (!MemberInit.get() || MemberInit.isInvalid()) 12412 continue; 12413 12414 Member = 12415 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 12416 SourceLocation(), 12417 MemberInit.takeAs<Expr>(), 12418 SourceLocation()); 12419 AllToInit.push_back(Member); 12420 12421 // Be sure that the destructor is accessible and is marked as referenced. 12422 if (const RecordType *RecordTy 12423 = Context.getBaseElementType(Field->getType()) 12424 ->getAs<RecordType>()) { 12425 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 12426 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 12427 MarkFunctionReferenced(Field->getLocation(), Destructor); 12428 CheckDestructorAccess(Field->getLocation(), Destructor, 12429 PDiag(diag::err_access_dtor_ivar) 12430 << Context.getBaseElementType(Field->getType())); 12431 } 12432 } 12433 } 12434 ObjCImplementation->setIvarInitializers(Context, 12435 AllToInit.data(), AllToInit.size()); 12436 } 12437 } 12438 12439 static 12440 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 12441 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 12442 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 12443 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 12444 Sema &S) { 12445 if (Ctor->isInvalidDecl()) 12446 return; 12447 12448 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 12449 12450 // Target may not be determinable yet, for instance if this is a dependent 12451 // call in an uninstantiated template. 12452 if (Target) { 12453 const FunctionDecl *FNTarget = 0; 12454 (void)Target->hasBody(FNTarget); 12455 Target = const_cast<CXXConstructorDecl*>( 12456 cast_or_null<CXXConstructorDecl>(FNTarget)); 12457 } 12458 12459 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 12460 // Avoid dereferencing a null pointer here. 12461 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 12462 12463 if (!Current.insert(Canonical)) 12464 return; 12465 12466 // We know that beyond here, we aren't chaining into a cycle. 12467 if (!Target || !Target->isDelegatingConstructor() || 12468 Target->isInvalidDecl() || Valid.count(TCanonical)) { 12469 Valid.insert(Current.begin(), Current.end()); 12470 Current.clear(); 12471 // We've hit a cycle. 12472 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 12473 Current.count(TCanonical)) { 12474 // If we haven't diagnosed this cycle yet, do so now. 12475 if (!Invalid.count(TCanonical)) { 12476 S.Diag((*Ctor->init_begin())->getSourceLocation(), 12477 diag::warn_delegating_ctor_cycle) 12478 << Ctor; 12479 12480 // Don't add a note for a function delegating directly to itself. 12481 if (TCanonical != Canonical) 12482 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 12483 12484 CXXConstructorDecl *C = Target; 12485 while (C->getCanonicalDecl() != Canonical) { 12486 const FunctionDecl *FNTarget = 0; 12487 (void)C->getTargetConstructor()->hasBody(FNTarget); 12488 assert(FNTarget && "Ctor cycle through bodiless function"); 12489 12490 C = const_cast<CXXConstructorDecl*>( 12491 cast<CXXConstructorDecl>(FNTarget)); 12492 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12493 } 12494 } 12495 12496 Invalid.insert(Current.begin(), Current.end()); 12497 Current.clear(); 12498 } else { 12499 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12500 } 12501 } 12502 12503 12504 void Sema::CheckDelegatingCtorCycles() { 12505 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12506 12507 for (DelegatingCtorDeclsType::iterator 12508 I = DelegatingCtorDecls.begin(ExternalSource), 12509 E = DelegatingCtorDecls.end(); 12510 I != E; ++I) 12511 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 12512 12513 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 12514 CE = Invalid.end(); 12515 CI != CE; ++CI) 12516 (*CI)->setInvalidDecl(); 12517 } 12518 12519 namespace { 12520 /// \brief AST visitor that finds references to the 'this' expression. 12521 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 12522 Sema &S; 12523 12524 public: 12525 explicit FindCXXThisExpr(Sema &S) : S(S) { } 12526 12527 bool VisitCXXThisExpr(CXXThisExpr *E) { 12528 S.Diag(E->getLocation(), diag::err_this_static_member_func) 12529 << E->isImplicit(); 12530 return false; 12531 } 12532 }; 12533 } 12534 12535 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 12536 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12537 if (!TSInfo) 12538 return false; 12539 12540 TypeLoc TL = TSInfo->getTypeLoc(); 12541 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12542 if (!ProtoTL) 12543 return false; 12544 12545 // C++11 [expr.prim.general]p3: 12546 // [The expression this] shall not appear before the optional 12547 // cv-qualifier-seq and it shall not appear within the declaration of a 12548 // static member function (although its type and value category are defined 12549 // within a static member function as they are within a non-static member 12550 // function). [ Note: this is because declaration matching does not occur 12551 // until the complete declarator is known. - end note ] 12552 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12553 FindCXXThisExpr Finder(*this); 12554 12555 // If the return type came after the cv-qualifier-seq, check it now. 12556 if (Proto->hasTrailingReturn() && 12557 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc())) 12558 return true; 12559 12560 // Check the exception specification. 12561 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 12562 return true; 12563 12564 return checkThisInStaticMemberFunctionAttributes(Method); 12565 } 12566 12567 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 12568 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12569 if (!TSInfo) 12570 return false; 12571 12572 TypeLoc TL = TSInfo->getTypeLoc(); 12573 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12574 if (!ProtoTL) 12575 return false; 12576 12577 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12578 FindCXXThisExpr Finder(*this); 12579 12580 switch (Proto->getExceptionSpecType()) { 12581 case EST_Uninstantiated: 12582 case EST_Unevaluated: 12583 case EST_BasicNoexcept: 12584 case EST_DynamicNone: 12585 case EST_MSAny: 12586 case EST_None: 12587 break; 12588 12589 case EST_ComputedNoexcept: 12590 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 12591 return true; 12592 12593 case EST_Dynamic: 12594 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 12595 EEnd = Proto->exception_end(); 12596 E != EEnd; ++E) { 12597 if (!Finder.TraverseType(*E)) 12598 return true; 12599 } 12600 break; 12601 } 12602 12603 return false; 12604 } 12605 12606 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 12607 FindCXXThisExpr Finder(*this); 12608 12609 // Check attributes. 12610 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end(); 12611 A != AEnd; ++A) { 12612 // FIXME: This should be emitted by tblgen. 12613 Expr *Arg = 0; 12614 ArrayRef<Expr *> Args; 12615 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A)) 12616 Arg = G->getArg(); 12617 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A)) 12618 Arg = G->getArg(); 12619 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A)) 12620 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 12621 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A)) 12622 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 12623 else if (ExclusiveLockFunctionAttr *ELF 12624 = dyn_cast<ExclusiveLockFunctionAttr>(*A)) 12625 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size()); 12626 else if (SharedLockFunctionAttr *SLF 12627 = dyn_cast<SharedLockFunctionAttr>(*A)) 12628 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size()); 12629 else if (ExclusiveTrylockFunctionAttr *ETLF 12630 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) { 12631 Arg = ETLF->getSuccessValue(); 12632 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 12633 } else if (SharedTrylockFunctionAttr *STLF 12634 = dyn_cast<SharedTrylockFunctionAttr>(*A)) { 12635 Arg = STLF->getSuccessValue(); 12636 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 12637 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A)) 12638 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size()); 12639 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A)) 12640 Arg = LR->getArg(); 12641 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A)) 12642 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 12643 else if (ExclusiveLocksRequiredAttr *ELR 12644 = dyn_cast<ExclusiveLocksRequiredAttr>(*A)) 12645 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size()); 12646 else if (SharedLocksRequiredAttr *SLR 12647 = dyn_cast<SharedLocksRequiredAttr>(*A)) 12648 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size()); 12649 12650 if (Arg && !Finder.TraverseStmt(Arg)) 12651 return true; 12652 12653 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12654 if (!Finder.TraverseStmt(Args[I])) 12655 return true; 12656 } 12657 } 12658 12659 return false; 12660 } 12661 12662 void 12663 Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12664 ArrayRef<ParsedType> DynamicExceptions, 12665 ArrayRef<SourceRange> DynamicExceptionRanges, 12666 Expr *NoexceptExpr, 12667 SmallVectorImpl<QualType> &Exceptions, 12668 FunctionProtoType::ExtProtoInfo &EPI) { 12669 Exceptions.clear(); 12670 EPI.ExceptionSpecType = EST; 12671 if (EST == EST_Dynamic) { 12672 Exceptions.reserve(DynamicExceptions.size()); 12673 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12674 // FIXME: Preserve type source info. 12675 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12676 12677 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12678 collectUnexpandedParameterPacks(ET, Unexpanded); 12679 if (!Unexpanded.empty()) { 12680 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 12681 UPPC_ExceptionType, 12682 Unexpanded); 12683 continue; 12684 } 12685 12686 // Check that the type is valid for an exception spec, and 12687 // drop it if not. 12688 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 12689 Exceptions.push_back(ET); 12690 } 12691 EPI.NumExceptions = Exceptions.size(); 12692 EPI.Exceptions = Exceptions.data(); 12693 return; 12694 } 12695 12696 if (EST == EST_ComputedNoexcept) { 12697 // If an error occurred, there's no expression here. 12698 if (NoexceptExpr) { 12699 assert((NoexceptExpr->isTypeDependent() || 12700 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 12701 Context.BoolTy) && 12702 "Parser should have made sure that the expression is boolean"); 12703 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 12704 EPI.ExceptionSpecType = EST_BasicNoexcept; 12705 return; 12706 } 12707 12708 if (!NoexceptExpr->isValueDependent()) 12709 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 12710 diag::err_noexcept_needs_constant_expression, 12711 /*AllowFold*/ false).take(); 12712 EPI.NoexceptExpr = NoexceptExpr; 12713 } 12714 return; 12715 } 12716 } 12717 12718 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function 12719 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 12720 // Implicitly declared functions (e.g. copy constructors) are 12721 // __host__ __device__ 12722 if (D->isImplicit()) 12723 return CFT_HostDevice; 12724 12725 if (D->hasAttr<CUDAGlobalAttr>()) 12726 return CFT_Global; 12727 12728 if (D->hasAttr<CUDADeviceAttr>()) { 12729 if (D->hasAttr<CUDAHostAttr>()) 12730 return CFT_HostDevice; 12731 return CFT_Device; 12732 } 12733 12734 return CFT_Host; 12735 } 12736 12737 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 12738 CUDAFunctionTarget CalleeTarget) { 12739 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 12740 // Callable from the device only." 12741 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 12742 return true; 12743 12744 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 12745 // Callable from the host only." 12746 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 12747 // Callable from the host only." 12748 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 12749 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 12750 return true; 12751 12752 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 12753 return true; 12754 12755 return false; 12756 } 12757 12758 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 12759 /// 12760 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 12761 SourceLocation DeclStart, 12762 Declarator &D, Expr *BitWidth, 12763 InClassInitStyle InitStyle, 12764 AccessSpecifier AS, 12765 AttributeList *MSPropertyAttr) { 12766 IdentifierInfo *II = D.getIdentifier(); 12767 if (!II) { 12768 Diag(DeclStart, diag::err_anonymous_property); 12769 return NULL; 12770 } 12771 SourceLocation Loc = D.getIdentifierLoc(); 12772 12773 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12774 QualType T = TInfo->getType(); 12775 if (getLangOpts().CPlusPlus) { 12776 CheckExtraCXXDefaultArguments(D); 12777 12778 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12779 UPPC_DataMemberType)) { 12780 D.setInvalidType(); 12781 T = Context.IntTy; 12782 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12783 } 12784 } 12785 12786 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12787 12788 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12789 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12790 diag::err_invalid_thread) 12791 << DeclSpec::getSpecifierName(TSCS); 12792 12793 // Check to see if this name was declared as a member previously 12794 NamedDecl *PrevDecl = 0; 12795 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12796 LookupName(Previous, S); 12797 switch (Previous.getResultKind()) { 12798 case LookupResult::Found: 12799 case LookupResult::FoundUnresolvedValue: 12800 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12801 break; 12802 12803 case LookupResult::FoundOverloaded: 12804 PrevDecl = Previous.getRepresentativeDecl(); 12805 break; 12806 12807 case LookupResult::NotFound: 12808 case LookupResult::NotFoundInCurrentInstantiation: 12809 case LookupResult::Ambiguous: 12810 break; 12811 } 12812 12813 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12814 // Maybe we will complain about the shadowed template parameter. 12815 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12816 // Just pretend that we didn't see the previous declaration. 12817 PrevDecl = 0; 12818 } 12819 12820 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12821 PrevDecl = 0; 12822 12823 SourceLocation TSSL = D.getLocStart(); 12824 MSPropertyDecl *NewPD; 12825 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 12826 NewPD = new (Context) MSPropertyDecl(Record, Loc, 12827 II, T, TInfo, TSSL, 12828 Data.GetterId, Data.SetterId); 12829 ProcessDeclAttributes(TUScope, NewPD, D); 12830 NewPD->setAccess(AS); 12831 12832 if (NewPD->isInvalidDecl()) 12833 Record->setInvalidDecl(); 12834 12835 if (D.getDeclSpec().isModulePrivateSpecified()) 12836 NewPD->setModulePrivate(); 12837 12838 if (NewPD->isInvalidDecl() && PrevDecl) { 12839 // Don't introduce NewFD into scope; there's already something 12840 // with the same name in the same scope. 12841 } else if (II) { 12842 PushOnScopeChains(NewPD, S); 12843 } else 12844 Record->addDecl(NewPD); 12845 12846 return NewPD; 12847 } 12848