1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for C++ declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/DeclVisitor.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/RecordLayout.h" 25 #include "clang/AST/RecursiveASTVisitor.h" 26 #include "clang/AST/StmtVisitor.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/AST/TypeOrdering.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/LiteralSupport.h" 32 #include "clang/Lex/Preprocessor.h" 33 #include "clang/Sema/CXXFieldCollector.h" 34 #include "clang/Sema/DeclSpec.h" 35 #include "clang/Sema/Initialization.h" 36 #include "clang/Sema/Lookup.h" 37 #include "clang/Sema/ParsedTemplate.h" 38 #include "clang/Sema/Scope.h" 39 #include "clang/Sema/ScopeInfo.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include "llvm/ADT/SmallString.h" 42 #include <map> 43 #include <set> 44 45 using namespace clang; 46 47 //===----------------------------------------------------------------------===// 48 // CheckDefaultArgumentVisitor 49 //===----------------------------------------------------------------------===// 50 51 namespace { 52 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 53 /// the default argument of a parameter to determine whether it 54 /// contains any ill-formed subexpressions. For example, this will 55 /// diagnose the use of local variables or parameters within the 56 /// default argument expression. 57 class CheckDefaultArgumentVisitor 58 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 59 Expr *DefaultArg; 60 Sema *S; 61 62 public: 63 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 64 : DefaultArg(defarg), S(s) {} 65 66 bool VisitExpr(Expr *Node); 67 bool VisitDeclRefExpr(DeclRefExpr *DRE); 68 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 69 bool VisitLambdaExpr(LambdaExpr *Lambda); 70 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 71 }; 72 73 /// VisitExpr - Visit all of the children of this expression. 74 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 75 bool IsInvalid = false; 76 for (Stmt::child_range I = Node->children(); I; ++I) 77 IsInvalid |= Visit(*I); 78 return IsInvalid; 79 } 80 81 /// VisitDeclRefExpr - Visit a reference to a declaration, to 82 /// determine whether this declaration can be used in the default 83 /// argument expression. 84 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 85 NamedDecl *Decl = DRE->getDecl(); 86 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 87 // C++ [dcl.fct.default]p9 88 // Default arguments are evaluated each time the function is 89 // called. The order of evaluation of function arguments is 90 // unspecified. Consequently, parameters of a function shall not 91 // be used in default argument expressions, even if they are not 92 // evaluated. Parameters of a function declared before a default 93 // argument expression are in scope and can hide namespace and 94 // class member names. 95 return S->Diag(DRE->getLocStart(), 96 diag::err_param_default_argument_references_param) 97 << Param->getDeclName() << DefaultArg->getSourceRange(); 98 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 99 // C++ [dcl.fct.default]p7 100 // Local variables shall not be used in default argument 101 // expressions. 102 if (VDecl->isLocalVarDecl()) 103 return S->Diag(DRE->getLocStart(), 104 diag::err_param_default_argument_references_local) 105 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 106 } 107 108 return false; 109 } 110 111 /// VisitCXXThisExpr - Visit a C++ "this" expression. 112 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 113 // C++ [dcl.fct.default]p8: 114 // The keyword this shall not be used in a default argument of a 115 // member function. 116 return S->Diag(ThisE->getLocStart(), 117 diag::err_param_default_argument_references_this) 118 << ThisE->getSourceRange(); 119 } 120 121 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 122 bool Invalid = false; 123 for (PseudoObjectExpr::semantics_iterator 124 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 125 Expr *E = *i; 126 127 // Look through bindings. 128 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 129 E = OVE->getSourceExpr(); 130 assert(E && "pseudo-object binding without source expression?"); 131 } 132 133 Invalid |= Visit(E); 134 } 135 return Invalid; 136 } 137 138 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 139 // C++11 [expr.lambda.prim]p13: 140 // A lambda-expression appearing in a default argument shall not 141 // implicitly or explicitly capture any entity. 142 if (Lambda->capture_begin() == Lambda->capture_end()) 143 return false; 144 145 return S->Diag(Lambda->getLocStart(), 146 diag::err_lambda_capture_default_arg); 147 } 148 } 149 150 void 151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 152 const CXXMethodDecl *Method) { 153 // If we have an MSAny spec already, don't bother. 154 if (!Method || ComputedEST == EST_MSAny) 155 return; 156 157 const FunctionProtoType *Proto 158 = Method->getType()->getAs<FunctionProtoType>(); 159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 160 if (!Proto) 161 return; 162 163 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 164 165 // If this function can throw any exceptions, make a note of that. 166 if (EST == EST_MSAny || EST == EST_None) { 167 ClearExceptions(); 168 ComputedEST = EST; 169 return; 170 } 171 172 // FIXME: If the call to this decl is using any of its default arguments, we 173 // need to search them for potentially-throwing calls. 174 175 // If this function has a basic noexcept, it doesn't affect the outcome. 176 if (EST == EST_BasicNoexcept) 177 return; 178 179 // If we have a throw-all spec at this point, ignore the function. 180 if (ComputedEST == EST_None) 181 return; 182 183 // If we're still at noexcept(true) and there's a nothrow() callee, 184 // change to that specification. 185 if (EST == EST_DynamicNone) { 186 if (ComputedEST == EST_BasicNoexcept) 187 ComputedEST = EST_DynamicNone; 188 return; 189 } 190 191 // Check out noexcept specs. 192 if (EST == EST_ComputedNoexcept) { 193 FunctionProtoType::NoexceptResult NR = 194 Proto->getNoexceptSpec(Self->Context); 195 assert(NR != FunctionProtoType::NR_NoNoexcept && 196 "Must have noexcept result for EST_ComputedNoexcept."); 197 assert(NR != FunctionProtoType::NR_Dependent && 198 "Should not generate implicit declarations for dependent cases, " 199 "and don't know how to handle them anyway."); 200 201 // noexcept(false) -> no spec on the new function 202 if (NR == FunctionProtoType::NR_Throw) { 203 ClearExceptions(); 204 ComputedEST = EST_None; 205 } 206 // noexcept(true) won't change anything either. 207 return; 208 } 209 210 assert(EST == EST_Dynamic && "EST case not considered earlier."); 211 assert(ComputedEST != EST_None && 212 "Shouldn't collect exceptions when throw-all is guaranteed."); 213 ComputedEST = EST_Dynamic; 214 // Record the exceptions in this function's exception specification. 215 for (const auto &E : Proto->exceptions()) 216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E))) 217 Exceptions.push_back(E); 218 } 219 220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 221 if (!E || ComputedEST == EST_MSAny) 222 return; 223 224 // FIXME: 225 // 226 // C++0x [except.spec]p14: 227 // [An] implicit exception-specification specifies the type-id T if and 228 // only if T is allowed by the exception-specification of a function directly 229 // invoked by f's implicit definition; f shall allow all exceptions if any 230 // function it directly invokes allows all exceptions, and f shall allow no 231 // exceptions if every function it directly invokes allows no exceptions. 232 // 233 // Note in particular that if an implicit exception-specification is generated 234 // for a function containing a throw-expression, that specification can still 235 // be noexcept(true). 236 // 237 // Note also that 'directly invoked' is not defined in the standard, and there 238 // is no indication that we should only consider potentially-evaluated calls. 239 // 240 // Ultimately we should implement the intent of the standard: the exception 241 // specification should be the set of exceptions which can be thrown by the 242 // implicit definition. For now, we assume that any non-nothrow expression can 243 // throw any exception. 244 245 if (Self->canThrow(E)) 246 ComputedEST = EST_None; 247 } 248 249 bool 250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 251 SourceLocation EqualLoc) { 252 if (RequireCompleteType(Param->getLocation(), Param->getType(), 253 diag::err_typecheck_decl_incomplete_type)) { 254 Param->setInvalidDecl(); 255 return true; 256 } 257 258 // C++ [dcl.fct.default]p5 259 // A default argument expression is implicitly converted (clause 260 // 4) to the parameter type. The default argument expression has 261 // the same semantic constraints as the initializer expression in 262 // a declaration of a variable of the parameter type, using the 263 // copy-initialization semantics (8.5). 264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 265 Param); 266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 267 EqualLoc); 268 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 270 if (Result.isInvalid()) 271 return true; 272 Arg = Result.takeAs<Expr>(); 273 274 CheckCompletedExpr(Arg, EqualLoc); 275 Arg = MaybeCreateExprWithCleanups(Arg); 276 277 // Okay: add the default argument to the parameter 278 Param->setDefaultArg(Arg); 279 280 // We have already instantiated this parameter; provide each of the 281 // instantiations with the uninstantiated default argument. 282 UnparsedDefaultArgInstantiationsMap::iterator InstPos 283 = UnparsedDefaultArgInstantiations.find(Param); 284 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 287 288 // We're done tracking this parameter's instantiations. 289 UnparsedDefaultArgInstantiations.erase(InstPos); 290 } 291 292 return false; 293 } 294 295 /// ActOnParamDefaultArgument - Check whether the default argument 296 /// provided for a function parameter is well-formed. If so, attach it 297 /// to the parameter declaration. 298 void 299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 300 Expr *DefaultArg) { 301 if (!param || !DefaultArg) 302 return; 303 304 ParmVarDecl *Param = cast<ParmVarDecl>(param); 305 UnparsedDefaultArgLocs.erase(Param); 306 307 // Default arguments are only permitted in C++ 308 if (!getLangOpts().CPlusPlus) { 309 Diag(EqualLoc, diag::err_param_default_argument) 310 << DefaultArg->getSourceRange(); 311 Param->setInvalidDecl(); 312 return; 313 } 314 315 // Check for unexpanded parameter packs. 316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 317 Param->setInvalidDecl(); 318 return; 319 } 320 321 // Check that the default argument is well-formed 322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 323 if (DefaultArgChecker.Visit(DefaultArg)) { 324 Param->setInvalidDecl(); 325 return; 326 } 327 328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 329 } 330 331 /// ActOnParamUnparsedDefaultArgument - We've seen a default 332 /// argument for a function parameter, but we can't parse it yet 333 /// because we're inside a class definition. Note that this default 334 /// argument will be parsed later. 335 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 336 SourceLocation EqualLoc, 337 SourceLocation ArgLoc) { 338 if (!param) 339 return; 340 341 ParmVarDecl *Param = cast<ParmVarDecl>(param); 342 Param->setUnparsedDefaultArg(); 343 UnparsedDefaultArgLocs[Param] = ArgLoc; 344 } 345 346 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 347 /// the default argument for the parameter param failed. 348 void Sema::ActOnParamDefaultArgumentError(Decl *param) { 349 if (!param) 350 return; 351 352 ParmVarDecl *Param = cast<ParmVarDecl>(param); 353 Param->setInvalidDecl(); 354 UnparsedDefaultArgLocs.erase(Param); 355 } 356 357 /// CheckExtraCXXDefaultArguments - Check for any extra default 358 /// arguments in the declarator, which is not a function declaration 359 /// or definition and therefore is not permitted to have default 360 /// arguments. This routine should be invoked for every declarator 361 /// that is not a function declaration or definition. 362 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 363 // C++ [dcl.fct.default]p3 364 // A default argument expression shall be specified only in the 365 // parameter-declaration-clause of a function declaration or in a 366 // template-parameter (14.1). It shall not be specified for a 367 // parameter pack. If it is specified in a 368 // parameter-declaration-clause, it shall not occur within a 369 // declarator or abstract-declarator of a parameter-declaration. 370 bool MightBeFunction = D.isFunctionDeclarationContext(); 371 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 372 DeclaratorChunk &chunk = D.getTypeObject(i); 373 if (chunk.Kind == DeclaratorChunk::Function) { 374 if (MightBeFunction) { 375 // This is a function declaration. It can have default arguments, but 376 // keep looking in case its return type is a function type with default 377 // arguments. 378 MightBeFunction = false; 379 continue; 380 } 381 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 382 ++argIdx) { 383 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 384 if (Param->hasUnparsedDefaultArg()) { 385 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens; 386 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 387 << SourceRange((*Toks)[1].getLocation(), 388 Toks->back().getLocation()); 389 delete Toks; 390 chunk.Fun.Params[argIdx].DefaultArgTokens = 0; 391 } else if (Param->getDefaultArg()) { 392 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 393 << Param->getDefaultArg()->getSourceRange(); 394 Param->setDefaultArg(0); 395 } 396 } 397 } else if (chunk.Kind != DeclaratorChunk::Paren) { 398 MightBeFunction = false; 399 } 400 } 401 } 402 403 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 404 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 405 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 406 if (!PVD->hasDefaultArg()) 407 return false; 408 if (!PVD->hasInheritedDefaultArg()) 409 return true; 410 } 411 return false; 412 } 413 414 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 415 /// function, once we already know that they have the same 416 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 417 /// error, false otherwise. 418 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 419 Scope *S) { 420 bool Invalid = false; 421 422 // C++ [dcl.fct.default]p4: 423 // For non-template functions, default arguments can be added in 424 // later declarations of a function in the same 425 // scope. Declarations in different scopes have completely 426 // distinct sets of default arguments. That is, declarations in 427 // inner scopes do not acquire default arguments from 428 // declarations in outer scopes, and vice versa. In a given 429 // function declaration, all parameters subsequent to a 430 // parameter with a default argument shall have default 431 // arguments supplied in this or previous declarations. A 432 // default argument shall not be redefined by a later 433 // declaration (not even to the same value). 434 // 435 // C++ [dcl.fct.default]p6: 436 // Except for member functions of class templates, the default arguments 437 // in a member function definition that appears outside of the class 438 // definition are added to the set of default arguments provided by the 439 // member function declaration in the class definition. 440 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 441 ParmVarDecl *OldParam = Old->getParamDecl(p); 442 ParmVarDecl *NewParam = New->getParamDecl(p); 443 444 bool OldParamHasDfl = OldParam->hasDefaultArg(); 445 bool NewParamHasDfl = NewParam->hasDefaultArg(); 446 447 NamedDecl *ND = Old; 448 449 // The declaration context corresponding to the scope is the semantic 450 // parent, unless this is a local function declaration, in which case 451 // it is that surrounding function. 452 DeclContext *ScopeDC = New->getLexicalDeclContext(); 453 if (!ScopeDC->isFunctionOrMethod()) 454 ScopeDC = New->getDeclContext(); 455 if (S && !isDeclInScope(ND, ScopeDC, S) && 456 !New->getDeclContext()->isRecord()) 457 // Ignore default parameters of old decl if they are not in 458 // the same scope and this is not an out-of-line definition of 459 // a member function. 460 OldParamHasDfl = false; 461 462 if (OldParamHasDfl && NewParamHasDfl) { 463 464 unsigned DiagDefaultParamID = 465 diag::err_param_default_argument_redefinition; 466 467 // MSVC accepts that default parameters be redefined for member functions 468 // of template class. The new default parameter's value is ignored. 469 Invalid = true; 470 if (getLangOpts().MicrosoftExt) { 471 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New); 472 if (MD && MD->getParent()->getDescribedClassTemplate()) { 473 // Merge the old default argument into the new parameter. 474 NewParam->setHasInheritedDefaultArg(); 475 if (OldParam->hasUninstantiatedDefaultArg()) 476 NewParam->setUninstantiatedDefaultArg( 477 OldParam->getUninstantiatedDefaultArg()); 478 else 479 NewParam->setDefaultArg(OldParam->getInit()); 480 DiagDefaultParamID = diag::warn_param_default_argument_redefinition; 481 Invalid = false; 482 } 483 } 484 485 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 486 // hint here. Alternatively, we could walk the type-source information 487 // for NewParam to find the last source location in the type... but it 488 // isn't worth the effort right now. This is the kind of test case that 489 // is hard to get right: 490 // int f(int); 491 // void g(int (*fp)(int) = f); 492 // void g(int (*fp)(int) = &f); 493 Diag(NewParam->getLocation(), DiagDefaultParamID) 494 << NewParam->getDefaultArgRange(); 495 496 // Look for the function declaration where the default argument was 497 // actually written, which may be a declaration prior to Old. 498 for (FunctionDecl *Older = Old->getPreviousDecl(); 499 Older; Older = Older->getPreviousDecl()) { 500 if (!Older->getParamDecl(p)->hasDefaultArg()) 501 break; 502 503 OldParam = Older->getParamDecl(p); 504 } 505 506 Diag(OldParam->getLocation(), diag::note_previous_definition) 507 << OldParam->getDefaultArgRange(); 508 } else if (OldParamHasDfl) { 509 // Merge the old default argument into the new parameter. 510 // It's important to use getInit() here; getDefaultArg() 511 // strips off any top-level ExprWithCleanups. 512 NewParam->setHasInheritedDefaultArg(); 513 if (OldParam->hasUninstantiatedDefaultArg()) 514 NewParam->setUninstantiatedDefaultArg( 515 OldParam->getUninstantiatedDefaultArg()); 516 else 517 NewParam->setDefaultArg(OldParam->getInit()); 518 } else if (NewParamHasDfl) { 519 if (New->getDescribedFunctionTemplate()) { 520 // Paragraph 4, quoted above, only applies to non-template functions. 521 Diag(NewParam->getLocation(), 522 diag::err_param_default_argument_template_redecl) 523 << NewParam->getDefaultArgRange(); 524 Diag(Old->getLocation(), diag::note_template_prev_declaration) 525 << false; 526 } else if (New->getTemplateSpecializationKind() 527 != TSK_ImplicitInstantiation && 528 New->getTemplateSpecializationKind() != TSK_Undeclared) { 529 // C++ [temp.expr.spec]p21: 530 // Default function arguments shall not be specified in a declaration 531 // or a definition for one of the following explicit specializations: 532 // - the explicit specialization of a function template; 533 // - the explicit specialization of a member function template; 534 // - the explicit specialization of a member function of a class 535 // template where the class template specialization to which the 536 // member function specialization belongs is implicitly 537 // instantiated. 538 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 539 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 540 << New->getDeclName() 541 << NewParam->getDefaultArgRange(); 542 } else if (New->getDeclContext()->isDependentContext()) { 543 // C++ [dcl.fct.default]p6 (DR217): 544 // Default arguments for a member function of a class template shall 545 // be specified on the initial declaration of the member function 546 // within the class template. 547 // 548 // Reading the tea leaves a bit in DR217 and its reference to DR205 549 // leads me to the conclusion that one cannot add default function 550 // arguments for an out-of-line definition of a member function of a 551 // dependent type. 552 int WhichKind = 2; 553 if (CXXRecordDecl *Record 554 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 555 if (Record->getDescribedClassTemplate()) 556 WhichKind = 0; 557 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 558 WhichKind = 1; 559 else 560 WhichKind = 2; 561 } 562 563 Diag(NewParam->getLocation(), 564 diag::err_param_default_argument_member_template_redecl) 565 << WhichKind 566 << NewParam->getDefaultArgRange(); 567 } 568 } 569 } 570 571 // DR1344: If a default argument is added outside a class definition and that 572 // default argument makes the function a special member function, the program 573 // is ill-formed. This can only happen for constructors. 574 if (isa<CXXConstructorDecl>(New) && 575 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 576 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 577 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 578 if (NewSM != OldSM) { 579 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 580 assert(NewParam->hasDefaultArg()); 581 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 582 << NewParam->getDefaultArgRange() << NewSM; 583 Diag(Old->getLocation(), diag::note_previous_declaration); 584 } 585 } 586 587 const FunctionDecl *Def; 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 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) { 597 // C++11 [dcl.fcn.spec]p4: 598 // If the definition of a function appears in a translation unit before its 599 // first declaration as inline, the program is ill-formed. 600 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 601 Diag(Def->getLocation(), diag::note_previous_definition); 602 Invalid = true; 603 } 604 605 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 606 // argument expression, that declaration shall be a definition and shall be 607 // the only declaration of the function or function template in the 608 // translation unit. 609 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 610 functionDeclHasDefaultArgument(Old)) { 611 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 612 Diag(Old->getLocation(), diag::note_previous_declaration); 613 Invalid = true; 614 } 615 616 if (CheckEquivalentExceptionSpec(Old, New)) 617 Invalid = true; 618 619 return Invalid; 620 } 621 622 /// \brief Merge the exception specifications of two variable declarations. 623 /// 624 /// This is called when there's a redeclaration of a VarDecl. The function 625 /// checks if the redeclaration might have an exception specification and 626 /// validates compatibility and merges the specs if necessary. 627 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 628 // Shortcut if exceptions are disabled. 629 if (!getLangOpts().CXXExceptions) 630 return; 631 632 assert(Context.hasSameType(New->getType(), Old->getType()) && 633 "Should only be called if types are otherwise the same."); 634 635 QualType NewType = New->getType(); 636 QualType OldType = Old->getType(); 637 638 // We're only interested in pointers and references to functions, as well 639 // as pointers to member functions. 640 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 641 NewType = R->getPointeeType(); 642 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 643 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 644 NewType = P->getPointeeType(); 645 OldType = OldType->getAs<PointerType>()->getPointeeType(); 646 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 647 NewType = M->getPointeeType(); 648 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 649 } 650 651 if (!NewType->isFunctionProtoType()) 652 return; 653 654 // There's lots of special cases for functions. For function pointers, system 655 // libraries are hopefully not as broken so that we don't need these 656 // workarounds. 657 if (CheckEquivalentExceptionSpec( 658 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 659 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 660 New->setInvalidDecl(); 661 } 662 } 663 664 /// CheckCXXDefaultArguments - Verify that the default arguments for a 665 /// function declaration are well-formed according to C++ 666 /// [dcl.fct.default]. 667 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 668 unsigned NumParams = FD->getNumParams(); 669 unsigned p; 670 671 // Find first parameter with a default argument 672 for (p = 0; p < NumParams; ++p) { 673 ParmVarDecl *Param = FD->getParamDecl(p); 674 if (Param->hasDefaultArg()) 675 break; 676 } 677 678 // C++ [dcl.fct.default]p4: 679 // In a given function declaration, all parameters 680 // subsequent to a parameter with a default argument shall 681 // have default arguments supplied in this or previous 682 // declarations. A default argument shall not be redefined 683 // by a later declaration (not even to the same value). 684 unsigned LastMissingDefaultArg = 0; 685 for (; p < NumParams; ++p) { 686 ParmVarDecl *Param = FD->getParamDecl(p); 687 if (!Param->hasDefaultArg()) { 688 if (Param->isInvalidDecl()) 689 /* We already complained about this parameter. */; 690 else if (Param->getIdentifier()) 691 Diag(Param->getLocation(), 692 diag::err_param_default_argument_missing_name) 693 << Param->getIdentifier(); 694 else 695 Diag(Param->getLocation(), 696 diag::err_param_default_argument_missing); 697 698 LastMissingDefaultArg = p; 699 } 700 } 701 702 if (LastMissingDefaultArg > 0) { 703 // Some default arguments were missing. Clear out all of the 704 // default arguments up to (and including) the last missing 705 // default argument, so that we leave the function parameters 706 // in a semantically valid state. 707 for (p = 0; p <= LastMissingDefaultArg; ++p) { 708 ParmVarDecl *Param = FD->getParamDecl(p); 709 if (Param->hasDefaultArg()) { 710 Param->setDefaultArg(0); 711 } 712 } 713 } 714 } 715 716 // CheckConstexprParameterTypes - Check whether a function's parameter types 717 // are all literal types. If so, return true. If not, produce a suitable 718 // diagnostic and return false. 719 static bool CheckConstexprParameterTypes(Sema &SemaRef, 720 const FunctionDecl *FD) { 721 unsigned ArgIndex = 0; 722 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 723 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 724 e = FT->param_type_end(); 725 i != e; ++i, ++ArgIndex) { 726 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 727 SourceLocation ParamLoc = PD->getLocation(); 728 if (!(*i)->isDependentType() && 729 SemaRef.RequireLiteralType(ParamLoc, *i, 730 diag::err_constexpr_non_literal_param, 731 ArgIndex+1, PD->getSourceRange(), 732 isa<CXXConstructorDecl>(FD))) 733 return false; 734 } 735 return true; 736 } 737 738 /// \brief Get diagnostic %select index for tag kind for 739 /// record diagnostic message. 740 /// WARNING: Indexes apply to particular diagnostics only! 741 /// 742 /// \returns diagnostic %select index. 743 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 744 switch (Tag) { 745 case TTK_Struct: return 0; 746 case TTK_Interface: return 1; 747 case TTK_Class: return 2; 748 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 749 } 750 } 751 752 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies 753 // the requirements of a constexpr function definition or a constexpr 754 // constructor definition. If so, return true. If not, produce appropriate 755 // diagnostics and return false. 756 // 757 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 758 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) { 759 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 760 if (MD && MD->isInstance()) { 761 // C++11 [dcl.constexpr]p4: 762 // The definition of a constexpr constructor shall satisfy the following 763 // constraints: 764 // - the class shall not have any virtual base classes; 765 const CXXRecordDecl *RD = MD->getParent(); 766 if (RD->getNumVBases()) { 767 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 768 << isa<CXXConstructorDecl>(NewFD) 769 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 770 for (const auto &I : RD->vbases()) 771 Diag(I.getLocStart(), 772 diag::note_constexpr_virtual_base_here) << I.getSourceRange(); 773 return false; 774 } 775 } 776 777 if (!isa<CXXConstructorDecl>(NewFD)) { 778 // C++11 [dcl.constexpr]p3: 779 // The definition of a constexpr function shall satisfy the following 780 // constraints: 781 // - it shall not be virtual; 782 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 783 if (Method && Method->isVirtual()) { 784 Diag(NewFD->getLocation(), diag::err_constexpr_virtual); 785 786 // If it's not obvious why this function is virtual, find an overridden 787 // function which uses the 'virtual' keyword. 788 const CXXMethodDecl *WrittenVirtual = Method; 789 while (!WrittenVirtual->isVirtualAsWritten()) 790 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 791 if (WrittenVirtual != Method) 792 Diag(WrittenVirtual->getLocation(), 793 diag::note_overridden_virtual_function); 794 return false; 795 } 796 797 // - its return type shall be a literal type; 798 QualType RT = NewFD->getReturnType(); 799 if (!RT->isDependentType() && 800 RequireLiteralType(NewFD->getLocation(), RT, 801 diag::err_constexpr_non_literal_return)) 802 return false; 803 } 804 805 // - each of its parameter types shall be a literal type; 806 if (!CheckConstexprParameterTypes(*this, NewFD)) 807 return false; 808 809 return true; 810 } 811 812 /// Check the given declaration statement is legal within a constexpr function 813 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 814 /// 815 /// \return true if the body is OK (maybe only as an extension), false if we 816 /// have diagnosed a problem. 817 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 818 DeclStmt *DS, SourceLocation &Cxx1yLoc) { 819 // C++11 [dcl.constexpr]p3 and p4: 820 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 821 // contain only 822 for (const auto *DclIt : DS->decls()) { 823 switch (DclIt->getKind()) { 824 case Decl::StaticAssert: 825 case Decl::Using: 826 case Decl::UsingShadow: 827 case Decl::UsingDirective: 828 case Decl::UnresolvedUsingTypename: 829 case Decl::UnresolvedUsingValue: 830 // - static_assert-declarations 831 // - using-declarations, 832 // - using-directives, 833 continue; 834 835 case Decl::Typedef: 836 case Decl::TypeAlias: { 837 // - typedef declarations and alias-declarations that do not define 838 // classes or enumerations, 839 const auto *TN = cast<TypedefNameDecl>(DclIt); 840 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 841 // Don't allow variably-modified types in constexpr functions. 842 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 843 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 844 << TL.getSourceRange() << TL.getType() 845 << isa<CXXConstructorDecl>(Dcl); 846 return false; 847 } 848 continue; 849 } 850 851 case Decl::Enum: 852 case Decl::CXXRecord: 853 // C++1y allows types to be defined, not just declared. 854 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) 855 SemaRef.Diag(DS->getLocStart(), 856 SemaRef.getLangOpts().CPlusPlus1y 857 ? diag::warn_cxx11_compat_constexpr_type_definition 858 : diag::ext_constexpr_type_definition) 859 << isa<CXXConstructorDecl>(Dcl); 860 continue; 861 862 case Decl::EnumConstant: 863 case Decl::IndirectField: 864 case Decl::ParmVar: 865 // These can only appear with other declarations which are banned in 866 // C++11 and permitted in C++1y, so ignore them. 867 continue; 868 869 case Decl::Var: { 870 // C++1y [dcl.constexpr]p3 allows anything except: 871 // a definition of a variable of non-literal type or of static or 872 // thread storage duration or for which no initialization is performed. 873 const auto *VD = cast<VarDecl>(DclIt); 874 if (VD->isThisDeclarationADefinition()) { 875 if (VD->isStaticLocal()) { 876 SemaRef.Diag(VD->getLocation(), 877 diag::err_constexpr_local_var_static) 878 << isa<CXXConstructorDecl>(Dcl) 879 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 880 return false; 881 } 882 if (!VD->getType()->isDependentType() && 883 SemaRef.RequireLiteralType( 884 VD->getLocation(), VD->getType(), 885 diag::err_constexpr_local_var_non_literal_type, 886 isa<CXXConstructorDecl>(Dcl))) 887 return false; 888 if (!VD->getType()->isDependentType() && 889 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 890 SemaRef.Diag(VD->getLocation(), 891 diag::err_constexpr_local_var_no_init) 892 << isa<CXXConstructorDecl>(Dcl); 893 return false; 894 } 895 } 896 SemaRef.Diag(VD->getLocation(), 897 SemaRef.getLangOpts().CPlusPlus1y 898 ? diag::warn_cxx11_compat_constexpr_local_var 899 : diag::ext_constexpr_local_var) 900 << isa<CXXConstructorDecl>(Dcl); 901 continue; 902 } 903 904 case Decl::NamespaceAlias: 905 case Decl::Function: 906 // These are disallowed in C++11 and permitted in C++1y. Allow them 907 // everywhere as an extension. 908 if (!Cxx1yLoc.isValid()) 909 Cxx1yLoc = DS->getLocStart(); 910 continue; 911 912 default: 913 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt) 914 << isa<CXXConstructorDecl>(Dcl); 915 return false; 916 } 917 } 918 919 return true; 920 } 921 922 /// Check that the given field is initialized within a constexpr constructor. 923 /// 924 /// \param Dcl The constexpr constructor being checked. 925 /// \param Field The field being checked. This may be a member of an anonymous 926 /// struct or union nested within the class being checked. 927 /// \param Inits All declarations, including anonymous struct/union members and 928 /// indirect members, for which any initialization was provided. 929 /// \param Diagnosed Set to true if an error is produced. 930 static void CheckConstexprCtorInitializer(Sema &SemaRef, 931 const FunctionDecl *Dcl, 932 FieldDecl *Field, 933 llvm::SmallSet<Decl*, 16> &Inits, 934 bool &Diagnosed) { 935 if (Field->isInvalidDecl()) 936 return; 937 938 if (Field->isUnnamedBitfield()) 939 return; 940 941 // Anonymous unions with no variant members and empty anonymous structs do not 942 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 943 // indirect fields don't need initializing. 944 if (Field->isAnonymousStructOrUnion() && 945 (Field->getType()->isUnionType() 946 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 947 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 948 return; 949 950 if (!Inits.count(Field)) { 951 if (!Diagnosed) { 952 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init); 953 Diagnosed = true; 954 } 955 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init); 956 } else if (Field->isAnonymousStructOrUnion()) { 957 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 958 for (auto *I : RD->fields()) 959 // If an anonymous union contains an anonymous struct of which any member 960 // is initialized, all members must be initialized. 961 if (!RD->isUnion() || Inits.count(I)) 962 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed); 963 } 964 } 965 966 /// Check the provided statement is allowed in a constexpr function 967 /// definition. 968 static bool 969 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 970 SmallVectorImpl<SourceLocation> &ReturnStmts, 971 SourceLocation &Cxx1yLoc) { 972 // - its function-body shall be [...] a compound-statement that contains only 973 switch (S->getStmtClass()) { 974 case Stmt::NullStmtClass: 975 // - null statements, 976 return true; 977 978 case Stmt::DeclStmtClass: 979 // - static_assert-declarations 980 // - using-declarations, 981 // - using-directives, 982 // - typedef declarations and alias-declarations that do not define 983 // classes or enumerations, 984 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc)) 985 return false; 986 return true; 987 988 case Stmt::ReturnStmtClass: 989 // - and exactly one return statement; 990 if (isa<CXXConstructorDecl>(Dcl)) { 991 // C++1y allows return statements in constexpr constructors. 992 if (!Cxx1yLoc.isValid()) 993 Cxx1yLoc = S->getLocStart(); 994 return true; 995 } 996 997 ReturnStmts.push_back(S->getLocStart()); 998 return true; 999 1000 case Stmt::CompoundStmtClass: { 1001 // C++1y allows compound-statements. 1002 if (!Cxx1yLoc.isValid()) 1003 Cxx1yLoc = S->getLocStart(); 1004 1005 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1006 for (auto *BodyIt : CompStmt->body()) { 1007 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1008 Cxx1yLoc)) 1009 return false; 1010 } 1011 return true; 1012 } 1013 1014 case Stmt::AttributedStmtClass: 1015 if (!Cxx1yLoc.isValid()) 1016 Cxx1yLoc = S->getLocStart(); 1017 return true; 1018 1019 case Stmt::IfStmtClass: { 1020 // C++1y allows if-statements. 1021 if (!Cxx1yLoc.isValid()) 1022 Cxx1yLoc = S->getLocStart(); 1023 1024 IfStmt *If = cast<IfStmt>(S); 1025 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 1026 Cxx1yLoc)) 1027 return false; 1028 if (If->getElse() && 1029 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 1030 Cxx1yLoc)) 1031 return false; 1032 return true; 1033 } 1034 1035 case Stmt::WhileStmtClass: 1036 case Stmt::DoStmtClass: 1037 case Stmt::ForStmtClass: 1038 case Stmt::CXXForRangeStmtClass: 1039 case Stmt::ContinueStmtClass: 1040 // C++1y allows all of these. We don't allow them as extensions in C++11, 1041 // because they don't make sense without variable mutation. 1042 if (!SemaRef.getLangOpts().CPlusPlus1y) 1043 break; 1044 if (!Cxx1yLoc.isValid()) 1045 Cxx1yLoc = S->getLocStart(); 1046 for (Stmt::child_range Children = S->children(); Children; ++Children) 1047 if (*Children && 1048 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1049 Cxx1yLoc)) 1050 return false; 1051 return true; 1052 1053 case Stmt::SwitchStmtClass: 1054 case Stmt::CaseStmtClass: 1055 case Stmt::DefaultStmtClass: 1056 case Stmt::BreakStmtClass: 1057 // C++1y allows switch-statements, and since they don't need variable 1058 // mutation, we can reasonably allow them in C++11 as an extension. 1059 if (!Cxx1yLoc.isValid()) 1060 Cxx1yLoc = S->getLocStart(); 1061 for (Stmt::child_range Children = S->children(); Children; ++Children) 1062 if (*Children && 1063 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts, 1064 Cxx1yLoc)) 1065 return false; 1066 return true; 1067 1068 default: 1069 if (!isa<Expr>(S)) 1070 break; 1071 1072 // C++1y allows expression-statements. 1073 if (!Cxx1yLoc.isValid()) 1074 Cxx1yLoc = S->getLocStart(); 1075 return true; 1076 } 1077 1078 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt) 1079 << isa<CXXConstructorDecl>(Dcl); 1080 return false; 1081 } 1082 1083 /// Check the body for the given constexpr function declaration only contains 1084 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 1085 /// 1086 /// \return true if the body is OK, false if we have diagnosed a problem. 1087 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) { 1088 if (isa<CXXTryStmt>(Body)) { 1089 // C++11 [dcl.constexpr]p3: 1090 // The definition of a constexpr function shall satisfy the following 1091 // constraints: [...] 1092 // - its function-body shall be = delete, = default, or a 1093 // compound-statement 1094 // 1095 // C++11 [dcl.constexpr]p4: 1096 // In the definition of a constexpr constructor, [...] 1097 // - its function-body shall not be a function-try-block; 1098 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block) 1099 << isa<CXXConstructorDecl>(Dcl); 1100 return false; 1101 } 1102 1103 SmallVector<SourceLocation, 4> ReturnStmts; 1104 1105 // - its function-body shall be [...] a compound-statement that contains only 1106 // [... list of cases ...] 1107 CompoundStmt *CompBody = cast<CompoundStmt>(Body); 1108 SourceLocation Cxx1yLoc; 1109 for (auto *BodyIt : CompBody->body()) { 1110 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc)) 1111 return false; 1112 } 1113 1114 if (Cxx1yLoc.isValid()) 1115 Diag(Cxx1yLoc, 1116 getLangOpts().CPlusPlus1y 1117 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 1118 : diag::ext_constexpr_body_invalid_stmt) 1119 << isa<CXXConstructorDecl>(Dcl); 1120 1121 if (const CXXConstructorDecl *Constructor 1122 = dyn_cast<CXXConstructorDecl>(Dcl)) { 1123 const CXXRecordDecl *RD = Constructor->getParent(); 1124 // DR1359: 1125 // - every non-variant non-static data member and base class sub-object 1126 // shall be initialized; 1127 // DR1460: 1128 // - if the class is a union having variant members, exactly one of them 1129 // shall be initialized; 1130 if (RD->isUnion()) { 1131 if (Constructor->getNumCtorInitializers() == 0 && 1132 RD->hasVariantMembers()) { 1133 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init); 1134 return false; 1135 } 1136 } else if (!Constructor->isDependentContext() && 1137 !Constructor->isDelegatingConstructor()) { 1138 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 1139 1140 // Skip detailed checking if we have enough initializers, and we would 1141 // allow at most one initializer per member. 1142 bool AnyAnonStructUnionMembers = false; 1143 unsigned Fields = 0; 1144 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 1145 E = RD->field_end(); I != E; ++I, ++Fields) { 1146 if (I->isAnonymousStructOrUnion()) { 1147 AnyAnonStructUnionMembers = true; 1148 break; 1149 } 1150 } 1151 // DR1460: 1152 // - if the class is a union-like class, but is not a union, for each of 1153 // its anonymous union members having variant members, exactly one of 1154 // them shall be initialized; 1155 if (AnyAnonStructUnionMembers || 1156 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 1157 // Check initialization of non-static data members. Base classes are 1158 // always initialized so do not need to be checked. Dependent bases 1159 // might not have initializers in the member initializer list. 1160 llvm::SmallSet<Decl*, 16> Inits; 1161 for (const auto *I: Constructor->inits()) { 1162 if (FieldDecl *FD = I->getMember()) 1163 Inits.insert(FD); 1164 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 1165 Inits.insert(ID->chain_begin(), ID->chain_end()); 1166 } 1167 1168 bool Diagnosed = false; 1169 for (auto *I : RD->fields()) 1170 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed); 1171 if (Diagnosed) 1172 return false; 1173 } 1174 } 1175 } else { 1176 if (ReturnStmts.empty()) { 1177 // C++1y doesn't require constexpr functions to contain a 'return' 1178 // statement. We still do, unless the return type is void, because 1179 // otherwise if there's no return statement, the function cannot 1180 // be used in a core constant expression. 1181 bool OK = getLangOpts().CPlusPlus1y && Dcl->getReturnType()->isVoidType(); 1182 Diag(Dcl->getLocation(), 1183 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 1184 : diag::err_constexpr_body_no_return); 1185 return OK; 1186 } 1187 if (ReturnStmts.size() > 1) { 1188 Diag(ReturnStmts.back(), 1189 getLangOpts().CPlusPlus1y 1190 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 1191 : diag::ext_constexpr_body_multiple_return); 1192 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 1193 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return); 1194 } 1195 } 1196 1197 // C++11 [dcl.constexpr]p5: 1198 // if no function argument values exist such that the function invocation 1199 // substitution would produce a constant expression, the program is 1200 // ill-formed; no diagnostic required. 1201 // C++11 [dcl.constexpr]p3: 1202 // - every constructor call and implicit conversion used in initializing the 1203 // return value shall be one of those allowed in a constant expression. 1204 // C++11 [dcl.constexpr]p4: 1205 // - every constructor involved in initializing non-static data members and 1206 // base class sub-objects shall be a constexpr constructor. 1207 SmallVector<PartialDiagnosticAt, 8> Diags; 1208 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) { 1209 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr) 1210 << isa<CXXConstructorDecl>(Dcl); 1211 for (size_t I = 0, N = Diags.size(); I != N; ++I) 1212 Diag(Diags[I].first, Diags[I].second); 1213 // Don't return false here: we allow this for compatibility in 1214 // system headers. 1215 } 1216 1217 return true; 1218 } 1219 1220 /// isCurrentClassName - Determine whether the identifier II is the 1221 /// name of the class type currently being defined. In the case of 1222 /// nested classes, this will only return true if II is the name of 1223 /// the innermost class. 1224 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 1225 const CXXScopeSpec *SS) { 1226 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1227 1228 CXXRecordDecl *CurDecl; 1229 if (SS && SS->isSet() && !SS->isInvalid()) { 1230 DeclContext *DC = computeDeclContext(*SS, true); 1231 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1232 } else 1233 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1234 1235 if (CurDecl && CurDecl->getIdentifier()) 1236 return &II == CurDecl->getIdentifier(); 1237 return false; 1238 } 1239 1240 /// \brief Determine whether the identifier II is a typo for the name of 1241 /// the class type currently being defined. If so, update it to the identifier 1242 /// that should have been used. 1243 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 1244 assert(getLangOpts().CPlusPlus && "No class names in C!"); 1245 1246 if (!getLangOpts().SpellChecking) 1247 return false; 1248 1249 CXXRecordDecl *CurDecl; 1250 if (SS && SS->isSet() && !SS->isInvalid()) { 1251 DeclContext *DC = computeDeclContext(*SS, true); 1252 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 1253 } else 1254 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1255 1256 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 1257 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 1258 < II->getLength()) { 1259 II = CurDecl->getIdentifier(); 1260 return true; 1261 } 1262 1263 return false; 1264 } 1265 1266 /// \brief Determine whether the given class is a base class of the given 1267 /// class, including looking at dependent bases. 1268 static bool findCircularInheritance(const CXXRecordDecl *Class, 1269 const CXXRecordDecl *Current) { 1270 SmallVector<const CXXRecordDecl*, 8> Queue; 1271 1272 Class = Class->getCanonicalDecl(); 1273 while (true) { 1274 for (const auto &I : Current->bases()) { 1275 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 1276 if (!Base) 1277 continue; 1278 1279 Base = Base->getDefinition(); 1280 if (!Base) 1281 continue; 1282 1283 if (Base->getCanonicalDecl() == Class) 1284 return true; 1285 1286 Queue.push_back(Base); 1287 } 1288 1289 if (Queue.empty()) 1290 return false; 1291 1292 Current = Queue.pop_back_val(); 1293 } 1294 1295 return false; 1296 } 1297 1298 /// \brief Check the validity of a C++ base class specifier. 1299 /// 1300 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 1301 /// and returns NULL otherwise. 1302 CXXBaseSpecifier * 1303 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 1304 SourceRange SpecifierRange, 1305 bool Virtual, AccessSpecifier Access, 1306 TypeSourceInfo *TInfo, 1307 SourceLocation EllipsisLoc) { 1308 QualType BaseType = TInfo->getType(); 1309 1310 // C++ [class.union]p1: 1311 // A union shall not have base classes. 1312 if (Class->isUnion()) { 1313 Diag(Class->getLocation(), diag::err_base_clause_on_union) 1314 << SpecifierRange; 1315 return 0; 1316 } 1317 1318 if (EllipsisLoc.isValid() && 1319 !TInfo->getType()->containsUnexpandedParameterPack()) { 1320 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1321 << TInfo->getTypeLoc().getSourceRange(); 1322 EllipsisLoc = SourceLocation(); 1323 } 1324 1325 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 1326 1327 if (BaseType->isDependentType()) { 1328 // Make sure that we don't have circular inheritance among our dependent 1329 // bases. For non-dependent bases, the check for completeness below handles 1330 // this. 1331 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 1332 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 1333 ((BaseDecl = BaseDecl->getDefinition()) && 1334 findCircularInheritance(Class, BaseDecl))) { 1335 Diag(BaseLoc, diag::err_circular_inheritance) 1336 << BaseType << Context.getTypeDeclType(Class); 1337 1338 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 1339 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 1340 << BaseType; 1341 1342 return 0; 1343 } 1344 } 1345 1346 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1347 Class->getTagKind() == TTK_Class, 1348 Access, TInfo, EllipsisLoc); 1349 } 1350 1351 // Base specifiers must be record types. 1352 if (!BaseType->isRecordType()) { 1353 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 1354 return 0; 1355 } 1356 1357 // C++ [class.union]p1: 1358 // A union shall not be used as a base class. 1359 if (BaseType->isUnionType()) { 1360 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 1361 return 0; 1362 } 1363 1364 // C++ [class.derived]p2: 1365 // The class-name in a base-specifier shall not be an incompletely 1366 // defined class. 1367 if (RequireCompleteType(BaseLoc, BaseType, 1368 diag::err_incomplete_base_class, SpecifierRange)) { 1369 Class->setInvalidDecl(); 1370 return 0; 1371 } 1372 1373 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 1374 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 1375 assert(BaseDecl && "Record type has no declaration"); 1376 BaseDecl = BaseDecl->getDefinition(); 1377 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 1378 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 1379 assert(CXXBaseDecl && "Base type is not a C++ type"); 1380 1381 // A class which contains a flexible array member is not suitable for use as a 1382 // base class: 1383 // - If the layout determines that a base comes before another base, 1384 // the flexible array member would index into the subsequent base. 1385 // - If the layout determines that base comes before the derived class, 1386 // the flexible array member would index into the derived class. 1387 if (CXXBaseDecl->hasFlexibleArrayMember()) { 1388 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 1389 << CXXBaseDecl->getDeclName(); 1390 return 0; 1391 } 1392 1393 // C++ [class]p3: 1394 // If a class is marked final and it appears as a base-type-specifier in 1395 // base-clause, the program is ill-formed. 1396 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 1397 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 1398 << CXXBaseDecl->getDeclName() 1399 << FA->isSpelledAsSealed(); 1400 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 1401 << CXXBaseDecl->getDeclName(); 1402 return 0; 1403 } 1404 1405 if (BaseDecl->isInvalidDecl()) 1406 Class->setInvalidDecl(); 1407 1408 // Create the base specifier. 1409 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 1410 Class->getTagKind() == TTK_Class, 1411 Access, TInfo, EllipsisLoc); 1412 } 1413 1414 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 1415 /// one entry in the base class list of a class specifier, for 1416 /// example: 1417 /// class foo : public bar, virtual private baz { 1418 /// 'public bar' and 'virtual private baz' are each base-specifiers. 1419 BaseResult 1420 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 1421 ParsedAttributes &Attributes, 1422 bool Virtual, AccessSpecifier Access, 1423 ParsedType basetype, SourceLocation BaseLoc, 1424 SourceLocation EllipsisLoc) { 1425 if (!classdecl) 1426 return true; 1427 1428 AdjustDeclIfTemplate(classdecl); 1429 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 1430 if (!Class) 1431 return true; 1432 1433 // We do not support any C++11 attributes on base-specifiers yet. 1434 // Diagnose any attributes we see. 1435 if (!Attributes.empty()) { 1436 for (AttributeList *Attr = Attributes.getList(); Attr; 1437 Attr = Attr->getNext()) { 1438 if (Attr->isInvalid() || 1439 Attr->getKind() == AttributeList::IgnoredAttribute) 1440 continue; 1441 Diag(Attr->getLoc(), 1442 Attr->getKind() == AttributeList::UnknownAttribute 1443 ? diag::warn_unknown_attribute_ignored 1444 : diag::err_base_specifier_attribute) 1445 << Attr->getName(); 1446 } 1447 } 1448 1449 TypeSourceInfo *TInfo = 0; 1450 GetTypeFromParser(basetype, &TInfo); 1451 1452 if (EllipsisLoc.isInvalid() && 1453 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 1454 UPPC_BaseType)) 1455 return true; 1456 1457 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 1458 Virtual, Access, TInfo, 1459 EllipsisLoc)) 1460 return BaseSpec; 1461 else 1462 Class->setInvalidDecl(); 1463 1464 return true; 1465 } 1466 1467 /// \brief Performs the actual work of attaching the given base class 1468 /// specifiers to a C++ class. 1469 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 1470 unsigned NumBases) { 1471 if (NumBases == 0) 1472 return false; 1473 1474 // Used to keep track of which base types we have already seen, so 1475 // that we can properly diagnose redundant direct base types. Note 1476 // that the key is always the unqualified canonical type of the base 1477 // class. 1478 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 1479 1480 // Copy non-redundant base specifiers into permanent storage. 1481 unsigned NumGoodBases = 0; 1482 bool Invalid = false; 1483 for (unsigned idx = 0; idx < NumBases; ++idx) { 1484 QualType NewBaseType 1485 = Context.getCanonicalType(Bases[idx]->getType()); 1486 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 1487 1488 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 1489 if (KnownBase) { 1490 // C++ [class.mi]p3: 1491 // A class shall not be specified as a direct base class of a 1492 // derived class more than once. 1493 Diag(Bases[idx]->getLocStart(), 1494 diag::err_duplicate_base_class) 1495 << KnownBase->getType() 1496 << Bases[idx]->getSourceRange(); 1497 1498 // Delete the duplicate base class specifier; we're going to 1499 // overwrite its pointer later. 1500 Context.Deallocate(Bases[idx]); 1501 1502 Invalid = true; 1503 } else { 1504 // Okay, add this new base class. 1505 KnownBase = Bases[idx]; 1506 Bases[NumGoodBases++] = Bases[idx]; 1507 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 1508 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 1509 if (Class->isInterface() && 1510 (!RD->isInterface() || 1511 KnownBase->getAccessSpecifier() != AS_public)) { 1512 // The Microsoft extension __interface does not permit bases that 1513 // are not themselves public interfaces. 1514 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface) 1515 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName() 1516 << RD->getSourceRange(); 1517 Invalid = true; 1518 } 1519 if (RD->hasAttr<WeakAttr>()) 1520 Class->addAttr(WeakAttr::CreateImplicit(Context)); 1521 } 1522 } 1523 } 1524 1525 // Attach the remaining base class specifiers to the derived class. 1526 Class->setBases(Bases, NumGoodBases); 1527 1528 // Delete the remaining (good) base class specifiers, since their 1529 // data has been copied into the CXXRecordDecl. 1530 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 1531 Context.Deallocate(Bases[idx]); 1532 1533 return Invalid; 1534 } 1535 1536 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 1537 /// class, after checking whether there are any duplicate base 1538 /// classes. 1539 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 1540 unsigned NumBases) { 1541 if (!ClassDecl || !Bases || !NumBases) 1542 return; 1543 1544 AdjustDeclIfTemplate(ClassDecl); 1545 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases); 1546 } 1547 1548 /// \brief Determine whether the type \p Derived is a C++ class that is 1549 /// derived from the type \p Base. 1550 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 1551 if (!getLangOpts().CPlusPlus) 1552 return false; 1553 1554 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1555 if (!DerivedRD) 1556 return false; 1557 1558 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1559 if (!BaseRD) 1560 return false; 1561 1562 // If either the base or the derived type is invalid, don't try to 1563 // check whether one is derived from the other. 1564 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 1565 return false; 1566 1567 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 1568 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 1569 } 1570 1571 /// \brief Determine whether the type \p Derived is a C++ class that is 1572 /// derived from the type \p Base. 1573 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 1574 if (!getLangOpts().CPlusPlus) 1575 return false; 1576 1577 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 1578 if (!DerivedRD) 1579 return false; 1580 1581 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 1582 if (!BaseRD) 1583 return false; 1584 1585 return DerivedRD->isDerivedFrom(BaseRD, Paths); 1586 } 1587 1588 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 1589 CXXCastPath &BasePathArray) { 1590 assert(BasePathArray.empty() && "Base path array must be empty!"); 1591 assert(Paths.isRecordingPaths() && "Must record paths!"); 1592 1593 const CXXBasePath &Path = Paths.front(); 1594 1595 // We first go backward and check if we have a virtual base. 1596 // FIXME: It would be better if CXXBasePath had the base specifier for 1597 // the nearest virtual base. 1598 unsigned Start = 0; 1599 for (unsigned I = Path.size(); I != 0; --I) { 1600 if (Path[I - 1].Base->isVirtual()) { 1601 Start = I - 1; 1602 break; 1603 } 1604 } 1605 1606 // Now add all bases. 1607 for (unsigned I = Start, E = Path.size(); I != E; ++I) 1608 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 1609 } 1610 1611 /// \brief Determine whether the given base path includes a virtual 1612 /// base class. 1613 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 1614 for (CXXCastPath::const_iterator B = BasePath.begin(), 1615 BEnd = BasePath.end(); 1616 B != BEnd; ++B) 1617 if ((*B)->isVirtual()) 1618 return true; 1619 1620 return false; 1621 } 1622 1623 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 1624 /// conversion (where Derived and Base are class types) is 1625 /// well-formed, meaning that the conversion is unambiguous (and 1626 /// that all of the base classes are accessible). Returns true 1627 /// and emits a diagnostic if the code is ill-formed, returns false 1628 /// otherwise. Loc is the location where this routine should point to 1629 /// if there is an error, and Range is the source range to highlight 1630 /// if there is an error. 1631 bool 1632 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1633 unsigned InaccessibleBaseID, 1634 unsigned AmbigiousBaseConvID, 1635 SourceLocation Loc, SourceRange Range, 1636 DeclarationName Name, 1637 CXXCastPath *BasePath) { 1638 // First, determine whether the path from Derived to Base is 1639 // ambiguous. This is slightly more expensive than checking whether 1640 // the Derived to Base conversion exists, because here we need to 1641 // explore multiple paths to determine if there is an ambiguity. 1642 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1643 /*DetectVirtual=*/false); 1644 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 1645 assert(DerivationOkay && 1646 "Can only be used with a derived-to-base conversion"); 1647 (void)DerivationOkay; 1648 1649 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 1650 if (InaccessibleBaseID) { 1651 // Check that the base class can be accessed. 1652 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 1653 InaccessibleBaseID)) { 1654 case AR_inaccessible: 1655 return true; 1656 case AR_accessible: 1657 case AR_dependent: 1658 case AR_delayed: 1659 break; 1660 } 1661 } 1662 1663 // Build a base path if necessary. 1664 if (BasePath) 1665 BuildBasePathArray(Paths, *BasePath); 1666 return false; 1667 } 1668 1669 if (AmbigiousBaseConvID) { 1670 // We know that the derived-to-base conversion is ambiguous, and 1671 // we're going to produce a diagnostic. Perform the derived-to-base 1672 // search just one more time to compute all of the possible paths so 1673 // that we can print them out. This is more expensive than any of 1674 // the previous derived-to-base checks we've done, but at this point 1675 // performance isn't as much of an issue. 1676 Paths.clear(); 1677 Paths.setRecordingPaths(true); 1678 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 1679 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 1680 (void)StillOkay; 1681 1682 // Build up a textual representation of the ambiguous paths, e.g., 1683 // D -> B -> A, that will be used to illustrate the ambiguous 1684 // conversions in the diagnostic. We only print one of the paths 1685 // to each base class subobject. 1686 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 1687 1688 Diag(Loc, AmbigiousBaseConvID) 1689 << Derived << Base << PathDisplayStr << Range << Name; 1690 } 1691 return true; 1692 } 1693 1694 bool 1695 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 1696 SourceLocation Loc, SourceRange Range, 1697 CXXCastPath *BasePath, 1698 bool IgnoreAccess) { 1699 return CheckDerivedToBaseConversion(Derived, Base, 1700 IgnoreAccess ? 0 1701 : diag::err_upcast_to_inaccessible_base, 1702 diag::err_ambiguous_derived_to_base_conv, 1703 Loc, Range, DeclarationName(), 1704 BasePath); 1705 } 1706 1707 1708 /// @brief Builds a string representing ambiguous paths from a 1709 /// specific derived class to different subobjects of the same base 1710 /// class. 1711 /// 1712 /// This function builds a string that can be used in error messages 1713 /// to show the different paths that one can take through the 1714 /// inheritance hierarchy to go from the derived class to different 1715 /// subobjects of a base class. The result looks something like this: 1716 /// @code 1717 /// struct D -> struct B -> struct A 1718 /// struct D -> struct C -> struct A 1719 /// @endcode 1720 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 1721 std::string PathDisplayStr; 1722 std::set<unsigned> DisplayedPaths; 1723 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1724 Path != Paths.end(); ++Path) { 1725 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 1726 // We haven't displayed a path to this particular base 1727 // class subobject yet. 1728 PathDisplayStr += "\n "; 1729 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 1730 for (CXXBasePath::const_iterator Element = Path->begin(); 1731 Element != Path->end(); ++Element) 1732 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 1733 } 1734 } 1735 1736 return PathDisplayStr; 1737 } 1738 1739 //===----------------------------------------------------------------------===// 1740 // C++ class member Handling 1741 //===----------------------------------------------------------------------===// 1742 1743 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 1744 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, 1745 SourceLocation ASLoc, 1746 SourceLocation ColonLoc, 1747 AttributeList *Attrs) { 1748 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 1749 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 1750 ASLoc, ColonLoc); 1751 CurContext->addHiddenDecl(ASDecl); 1752 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 1753 } 1754 1755 /// CheckOverrideControl - Check C++11 override control semantics. 1756 void Sema::CheckOverrideControl(NamedDecl *D) { 1757 if (D->isInvalidDecl()) 1758 return; 1759 1760 // We only care about "override" and "final" declarations. 1761 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 1762 return; 1763 1764 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 1765 1766 // We can't check dependent instance methods. 1767 if (MD && MD->isInstance() && 1768 (MD->getParent()->hasAnyDependentBases() || 1769 MD->getType()->isDependentType())) 1770 return; 1771 1772 if (MD && !MD->isVirtual()) { 1773 // If we have a non-virtual method, check if if hides a virtual method. 1774 // (In that case, it's most likely the method has the wrong type.) 1775 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 1776 FindHiddenVirtualMethods(MD, OverloadedMethods); 1777 1778 if (!OverloadedMethods.empty()) { 1779 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1780 Diag(OA->getLocation(), 1781 diag::override_keyword_hides_virtual_member_function) 1782 << "override" << (OverloadedMethods.size() > 1); 1783 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1784 Diag(FA->getLocation(), 1785 diag::override_keyword_hides_virtual_member_function) 1786 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1787 << (OverloadedMethods.size() > 1); 1788 } 1789 NoteHiddenVirtualMethods(MD, OverloadedMethods); 1790 MD->setInvalidDecl(); 1791 return; 1792 } 1793 // Fall through into the general case diagnostic. 1794 // FIXME: We might want to attempt typo correction here. 1795 } 1796 1797 if (!MD || !MD->isVirtual()) { 1798 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 1799 Diag(OA->getLocation(), 1800 diag::override_keyword_only_allowed_on_virtual_member_functions) 1801 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 1802 D->dropAttr<OverrideAttr>(); 1803 } 1804 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 1805 Diag(FA->getLocation(), 1806 diag::override_keyword_only_allowed_on_virtual_member_functions) 1807 << (FA->isSpelledAsSealed() ? "sealed" : "final") 1808 << FixItHint::CreateRemoval(FA->getLocation()); 1809 D->dropAttr<FinalAttr>(); 1810 } 1811 return; 1812 } 1813 1814 // C++11 [class.virtual]p5: 1815 // If a virtual function is marked with the virt-specifier override and 1816 // does not override a member function of a base class, the program is 1817 // ill-formed. 1818 bool HasOverriddenMethods = 1819 MD->begin_overridden_methods() != MD->end_overridden_methods(); 1820 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 1821 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 1822 << MD->getDeclName(); 1823 } 1824 1825 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 1826 /// function overrides a virtual member function marked 'final', according to 1827 /// C++11 [class.virtual]p4. 1828 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 1829 const CXXMethodDecl *Old) { 1830 FinalAttr *FA = Old->getAttr<FinalAttr>(); 1831 if (!FA) 1832 return false; 1833 1834 Diag(New->getLocation(), diag::err_final_function_overridden) 1835 << New->getDeclName() 1836 << FA->isSpelledAsSealed(); 1837 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 1838 return true; 1839 } 1840 1841 static bool InitializationHasSideEffects(const FieldDecl &FD) { 1842 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 1843 // FIXME: Destruction of ObjC lifetime types has side-effects. 1844 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 1845 return !RD->isCompleteDefinition() || 1846 !RD->hasTrivialDefaultConstructor() || 1847 !RD->hasTrivialDestructor(); 1848 return false; 1849 } 1850 1851 static AttributeList *getMSPropertyAttr(AttributeList *list) { 1852 for (AttributeList* it = list; it != 0; it = it->getNext()) 1853 if (it->isDeclspecPropertyAttribute()) 1854 return it; 1855 return 0; 1856 } 1857 1858 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 1859 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 1860 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 1861 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 1862 /// present (but parsing it has been deferred). 1863 NamedDecl * 1864 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 1865 MultiTemplateParamsArg TemplateParameterLists, 1866 Expr *BW, const VirtSpecifiers &VS, 1867 InClassInitStyle InitStyle) { 1868 const DeclSpec &DS = D.getDeclSpec(); 1869 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 1870 DeclarationName Name = NameInfo.getName(); 1871 SourceLocation Loc = NameInfo.getLoc(); 1872 1873 // For anonymous bitfields, the location should point to the type. 1874 if (Loc.isInvalid()) 1875 Loc = D.getLocStart(); 1876 1877 Expr *BitWidth = static_cast<Expr*>(BW); 1878 1879 assert(isa<CXXRecordDecl>(CurContext)); 1880 assert(!DS.isFriendSpecified()); 1881 1882 bool isFunc = D.isDeclarationOfFunction(); 1883 1884 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 1885 // The Microsoft extension __interface only permits public member functions 1886 // and prohibits constructors, destructors, operators, non-public member 1887 // functions, static methods and data members. 1888 unsigned InvalidDecl; 1889 bool ShowDeclName = true; 1890 if (!isFunc) 1891 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1; 1892 else if (AS != AS_public) 1893 InvalidDecl = 2; 1894 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 1895 InvalidDecl = 3; 1896 else switch (Name.getNameKind()) { 1897 case DeclarationName::CXXConstructorName: 1898 InvalidDecl = 4; 1899 ShowDeclName = false; 1900 break; 1901 1902 case DeclarationName::CXXDestructorName: 1903 InvalidDecl = 5; 1904 ShowDeclName = false; 1905 break; 1906 1907 case DeclarationName::CXXOperatorName: 1908 case DeclarationName::CXXConversionFunctionName: 1909 InvalidDecl = 6; 1910 break; 1911 1912 default: 1913 InvalidDecl = 0; 1914 break; 1915 } 1916 1917 if (InvalidDecl) { 1918 if (ShowDeclName) 1919 Diag(Loc, diag::err_invalid_member_in_interface) 1920 << (InvalidDecl-1) << Name; 1921 else 1922 Diag(Loc, diag::err_invalid_member_in_interface) 1923 << (InvalidDecl-1) << ""; 1924 return 0; 1925 } 1926 } 1927 1928 // C++ 9.2p6: A member shall not be declared to have automatic storage 1929 // duration (auto, register) or with the extern storage-class-specifier. 1930 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 1931 // data members and cannot be applied to names declared const or static, 1932 // and cannot be applied to reference members. 1933 switch (DS.getStorageClassSpec()) { 1934 case DeclSpec::SCS_unspecified: 1935 case DeclSpec::SCS_typedef: 1936 case DeclSpec::SCS_static: 1937 break; 1938 case DeclSpec::SCS_mutable: 1939 if (isFunc) { 1940 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 1941 1942 // FIXME: It would be nicer if the keyword was ignored only for this 1943 // declarator. Otherwise we could get follow-up errors. 1944 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1945 } 1946 break; 1947 default: 1948 Diag(DS.getStorageClassSpecLoc(), 1949 diag::err_storageclass_invalid_for_member); 1950 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1951 break; 1952 } 1953 1954 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1955 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1956 !isFunc); 1957 1958 if (DS.isConstexprSpecified() && isInstField) { 1959 SemaDiagnosticBuilder B = 1960 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 1961 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 1962 if (InitStyle == ICIS_NoInit) { 1963 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const"); 1964 D.getMutableDeclSpec().ClearConstexprSpec(); 1965 const char *PrevSpec; 1966 unsigned DiagID; 1967 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc, 1968 PrevSpec, DiagID, getLangOpts()); 1969 (void)Failed; 1970 assert(!Failed && "Making a constexpr member const shouldn't fail"); 1971 } else { 1972 B << 1; 1973 const char *PrevSpec; 1974 unsigned DiagID; 1975 if (D.getMutableDeclSpec().SetStorageClassSpec( 1976 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 1977 Context.getPrintingPolicy())) { 1978 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 1979 "This is the only DeclSpec that should fail to be applied"); 1980 B << 1; 1981 } else { 1982 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 1983 isInstField = false; 1984 } 1985 } 1986 } 1987 1988 NamedDecl *Member; 1989 if (isInstField) { 1990 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1991 1992 // Data members must have identifiers for names. 1993 if (!Name.isIdentifier()) { 1994 Diag(Loc, diag::err_bad_variable_name) 1995 << Name; 1996 return 0; 1997 } 1998 1999 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2000 2001 // Member field could not be with "template" keyword. 2002 // So TemplateParameterLists should be empty in this case. 2003 if (TemplateParameterLists.size()) { 2004 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 2005 if (TemplateParams->size()) { 2006 // There is no such thing as a member field template. 2007 Diag(D.getIdentifierLoc(), diag::err_template_member) 2008 << II 2009 << SourceRange(TemplateParams->getTemplateLoc(), 2010 TemplateParams->getRAngleLoc()); 2011 } else { 2012 // There is an extraneous 'template<>' for this member. 2013 Diag(TemplateParams->getTemplateLoc(), 2014 diag::err_template_member_noparams) 2015 << II 2016 << SourceRange(TemplateParams->getTemplateLoc(), 2017 TemplateParams->getRAngleLoc()); 2018 } 2019 return 0; 2020 } 2021 2022 if (SS.isSet() && !SS.isInvalid()) { 2023 // The user provided a superfluous scope specifier inside a class 2024 // definition: 2025 // 2026 // class X { 2027 // int X::member; 2028 // }; 2029 if (DeclContext *DC = computeDeclContext(SS, false)) 2030 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc()); 2031 else 2032 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 2033 << Name << SS.getRange(); 2034 2035 SS.clear(); 2036 } 2037 2038 AttributeList *MSPropertyAttr = 2039 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList()); 2040 if (MSPropertyAttr) { 2041 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2042 BitWidth, InitStyle, AS, MSPropertyAttr); 2043 if (!Member) 2044 return 0; 2045 isInstField = false; 2046 } else { 2047 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 2048 BitWidth, InitStyle, AS); 2049 assert(Member && "HandleField never returns null"); 2050 } 2051 } else { 2052 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static); 2053 2054 Member = HandleDeclarator(S, D, TemplateParameterLists); 2055 if (!Member) 2056 return 0; 2057 2058 // Non-instance-fields can't have a bitfield. 2059 if (BitWidth) { 2060 if (Member->isInvalidDecl()) { 2061 // don't emit another diagnostic. 2062 } else if (isa<VarDecl>(Member)) { 2063 // C++ 9.6p3: A bit-field shall not be a static member. 2064 // "static member 'A' cannot be a bit-field" 2065 Diag(Loc, diag::err_static_not_bitfield) 2066 << Name << BitWidth->getSourceRange(); 2067 } else if (isa<TypedefDecl>(Member)) { 2068 // "typedef member 'x' cannot be a bit-field" 2069 Diag(Loc, diag::err_typedef_not_bitfield) 2070 << Name << BitWidth->getSourceRange(); 2071 } else { 2072 // A function typedef ("typedef int f(); f a;"). 2073 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 2074 Diag(Loc, diag::err_not_integral_type_bitfield) 2075 << Name << cast<ValueDecl>(Member)->getType() 2076 << BitWidth->getSourceRange(); 2077 } 2078 2079 BitWidth = 0; 2080 Member->setInvalidDecl(); 2081 } 2082 2083 Member->setAccess(AS); 2084 2085 // If we have declared a member function template or static data member 2086 // template, set the access of the templated declaration as well. 2087 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 2088 FunTmpl->getTemplatedDecl()->setAccess(AS); 2089 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 2090 VarTmpl->getTemplatedDecl()->setAccess(AS); 2091 } 2092 2093 if (VS.isOverrideSpecified()) 2094 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0)); 2095 if (VS.isFinalSpecified()) 2096 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context, 2097 VS.isFinalSpelledSealed())); 2098 2099 if (VS.getLastLocation().isValid()) { 2100 // Update the end location of a method that has a virt-specifiers. 2101 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 2102 MD->setRangeEnd(VS.getLastLocation()); 2103 } 2104 2105 CheckOverrideControl(Member); 2106 2107 assert((Name || isInstField) && "No identifier for non-field ?"); 2108 2109 if (isInstField) { 2110 FieldDecl *FD = cast<FieldDecl>(Member); 2111 FieldCollector->Add(FD); 2112 2113 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 2114 FD->getLocation()) 2115 != DiagnosticsEngine::Ignored) { 2116 // Remember all explicit private FieldDecls that have a name, no side 2117 // effects and are not part of a dependent type declaration. 2118 if (!FD->isImplicit() && FD->getDeclName() && 2119 FD->getAccess() == AS_private && 2120 !FD->hasAttr<UnusedAttr>() && 2121 !FD->getParent()->isDependentContext() && 2122 !InitializationHasSideEffects(*FD)) 2123 UnusedPrivateFields.insert(FD); 2124 } 2125 } 2126 2127 return Member; 2128 } 2129 2130 namespace { 2131 class UninitializedFieldVisitor 2132 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 2133 Sema &S; 2134 // List of Decls to generate a warning on. Also remove Decls that become 2135 // initialized. 2136 llvm::SmallPtrSet<ValueDecl*, 4> &Decls; 2137 // If non-null, add a note to the warning pointing back to the constructor. 2138 const CXXConstructorDecl *Constructor; 2139 public: 2140 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 2141 UninitializedFieldVisitor(Sema &S, 2142 llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2143 const CXXConstructorDecl *Constructor) 2144 : Inherited(S.Context), S(S), Decls(Decls), 2145 Constructor(Constructor) { } 2146 2147 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) { 2148 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 2149 return; 2150 2151 // FieldME is the inner-most MemberExpr that is not an anonymous struct 2152 // or union. 2153 MemberExpr *FieldME = ME; 2154 2155 Expr *Base = ME; 2156 while (isa<MemberExpr>(Base)) { 2157 ME = cast<MemberExpr>(Base); 2158 2159 if (isa<VarDecl>(ME->getMemberDecl())) 2160 return; 2161 2162 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2163 if (!FD->isAnonymousStructOrUnion()) 2164 FieldME = ME; 2165 2166 Base = ME->getBase(); 2167 } 2168 2169 if (!isa<CXXThisExpr>(Base)) 2170 return; 2171 2172 ValueDecl* FoundVD = FieldME->getMemberDecl(); 2173 2174 if (!Decls.count(FoundVD)) 2175 return; 2176 2177 const bool IsReference = FoundVD->getType()->isReferenceType(); 2178 2179 // Prevent double warnings on use of unbounded references. 2180 if (IsReference != CheckReferenceOnly) 2181 return; 2182 2183 unsigned diag = IsReference 2184 ? diag::warn_reference_field_is_uninit 2185 : diag::warn_field_is_uninit; 2186 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 2187 if (Constructor) 2188 S.Diag(Constructor->getLocation(), 2189 diag::note_uninit_in_this_constructor) 2190 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 2191 2192 } 2193 2194 void HandleValue(Expr *E) { 2195 E = E->IgnoreParens(); 2196 2197 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 2198 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2199 return; 2200 } 2201 2202 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 2203 HandleValue(CO->getTrueExpr()); 2204 HandleValue(CO->getFalseExpr()); 2205 return; 2206 } 2207 2208 if (BinaryConditionalOperator *BCO = 2209 dyn_cast<BinaryConditionalOperator>(E)) { 2210 HandleValue(BCO->getCommon()); 2211 HandleValue(BCO->getFalseExpr()); 2212 return; 2213 } 2214 2215 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 2216 switch (BO->getOpcode()) { 2217 default: 2218 return; 2219 case(BO_PtrMemD): 2220 case(BO_PtrMemI): 2221 HandleValue(BO->getLHS()); 2222 return; 2223 case(BO_Comma): 2224 HandleValue(BO->getRHS()); 2225 return; 2226 } 2227 } 2228 } 2229 2230 void VisitMemberExpr(MemberExpr *ME) { 2231 // All uses of unbounded reference fields will warn. 2232 HandleMemberExpr(ME, true /*CheckReferenceOnly*/); 2233 2234 Inherited::VisitMemberExpr(ME); 2235 } 2236 2237 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 2238 if (E->getCastKind() == CK_LValueToRValue) 2239 HandleValue(E->getSubExpr()); 2240 2241 Inherited::VisitImplicitCastExpr(E); 2242 } 2243 2244 void VisitCXXConstructExpr(CXXConstructExpr *E) { 2245 if (E->getConstructor()->isCopyConstructor()) 2246 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0))) 2247 if (ICE->getCastKind() == CK_NoOp) 2248 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr())) 2249 HandleMemberExpr(ME, false /*CheckReferenceOnly*/); 2250 2251 Inherited::VisitCXXConstructExpr(E); 2252 } 2253 2254 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2255 Expr *Callee = E->getCallee(); 2256 if (isa<MemberExpr>(Callee)) 2257 HandleValue(Callee); 2258 2259 Inherited::VisitCXXMemberCallExpr(E); 2260 } 2261 2262 void VisitBinaryOperator(BinaryOperator *E) { 2263 // If a field assignment is detected, remove the field from the 2264 // uninitiailized field set. 2265 if (E->getOpcode() == BO_Assign) 2266 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 2267 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2268 if (!FD->getType()->isReferenceType()) 2269 Decls.erase(FD); 2270 2271 Inherited::VisitBinaryOperator(E); 2272 } 2273 }; 2274 static void CheckInitExprContainsUninitializedFields( 2275 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls, 2276 const CXXConstructorDecl *Constructor) { 2277 if (Decls.size() == 0) 2278 return; 2279 2280 if (!E) 2281 return; 2282 2283 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) { 2284 E = Default->getExpr(); 2285 if (!E) 2286 return; 2287 // In class initializers will point to the constructor. 2288 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E); 2289 } else { 2290 UninitializedFieldVisitor(S, Decls, 0).Visit(E); 2291 } 2292 } 2293 2294 // Diagnose value-uses of fields to initialize themselves, e.g. 2295 // foo(foo) 2296 // where foo is not also a parameter to the constructor. 2297 // Also diagnose across field uninitialized use such as 2298 // x(y), y(x) 2299 // TODO: implement -Wuninitialized and fold this into that framework. 2300 static void DiagnoseUninitializedFields( 2301 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 2302 2303 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, 2304 Constructor->getLocation()) 2305 == DiagnosticsEngine::Ignored) { 2306 return; 2307 } 2308 2309 if (Constructor->isInvalidDecl()) 2310 return; 2311 2312 const CXXRecordDecl *RD = Constructor->getParent(); 2313 2314 // Holds fields that are uninitialized. 2315 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 2316 2317 // At the beginning, all fields are uninitialized. 2318 for (auto *I : RD->decls()) { 2319 if (auto *FD = dyn_cast<FieldDecl>(I)) { 2320 UninitializedFields.insert(FD); 2321 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 2322 UninitializedFields.insert(IFD->getAnonField()); 2323 } 2324 } 2325 2326 for (const auto *FieldInit : Constructor->inits()) { 2327 Expr *InitExpr = FieldInit->getInit(); 2328 2329 CheckInitExprContainsUninitializedFields( 2330 SemaRef, InitExpr, UninitializedFields, Constructor); 2331 2332 if (FieldDecl *Field = FieldInit->getAnyMember()) 2333 UninitializedFields.erase(Field); 2334 } 2335 } 2336 } // namespace 2337 2338 /// \brief Enter a new C++ default initializer scope. After calling this, the 2339 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 2340 /// parsing or instantiating the initializer failed. 2341 void Sema::ActOnStartCXXInClassMemberInitializer() { 2342 // Create a synthetic function scope to represent the call to the constructor 2343 // that notionally surrounds a use of this initializer. 2344 PushFunctionScope(); 2345 } 2346 2347 /// \brief This is invoked after parsing an in-class initializer for a 2348 /// non-static C++ class member, and after instantiating an in-class initializer 2349 /// in a class template. Such actions are deferred until the class is complete. 2350 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 2351 SourceLocation InitLoc, 2352 Expr *InitExpr) { 2353 // Pop the notional constructor scope we created earlier. 2354 PopFunctionScopeInfo(0, D); 2355 2356 FieldDecl *FD = cast<FieldDecl>(D); 2357 assert(FD->getInClassInitStyle() != ICIS_NoInit && 2358 "must set init style when field is created"); 2359 2360 if (!InitExpr) { 2361 FD->setInvalidDecl(); 2362 FD->removeInClassInitializer(); 2363 return; 2364 } 2365 2366 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 2367 FD->setInvalidDecl(); 2368 FD->removeInClassInitializer(); 2369 return; 2370 } 2371 2372 ExprResult Init = InitExpr; 2373 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 2374 InitializedEntity Entity = InitializedEntity::InitializeMember(FD); 2375 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit 2376 ? InitializationKind::CreateDirectList(InitExpr->getLocStart()) 2377 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc); 2378 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 2379 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 2380 if (Init.isInvalid()) { 2381 FD->setInvalidDecl(); 2382 return; 2383 } 2384 } 2385 2386 // C++11 [class.base.init]p7: 2387 // The initialization of each base and member constitutes a 2388 // full-expression. 2389 Init = ActOnFinishFullExpr(Init.take(), InitLoc); 2390 if (Init.isInvalid()) { 2391 FD->setInvalidDecl(); 2392 return; 2393 } 2394 2395 InitExpr = Init.release(); 2396 2397 FD->setInClassInitializer(InitExpr); 2398 } 2399 2400 /// \brief Find the direct and/or virtual base specifiers that 2401 /// correspond to the given base type, for use in base initialization 2402 /// within a constructor. 2403 static bool FindBaseInitializer(Sema &SemaRef, 2404 CXXRecordDecl *ClassDecl, 2405 QualType BaseType, 2406 const CXXBaseSpecifier *&DirectBaseSpec, 2407 const CXXBaseSpecifier *&VirtualBaseSpec) { 2408 // First, check for a direct base class. 2409 DirectBaseSpec = 0; 2410 for (const auto &Base : ClassDecl->bases()) { 2411 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 2412 // We found a direct base of this type. That's what we're 2413 // initializing. 2414 DirectBaseSpec = &Base; 2415 break; 2416 } 2417 } 2418 2419 // Check for a virtual base class. 2420 // FIXME: We might be able to short-circuit this if we know in advance that 2421 // there are no virtual bases. 2422 VirtualBaseSpec = 0; 2423 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 2424 // We haven't found a base yet; search the class hierarchy for a 2425 // virtual base class. 2426 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2427 /*DetectVirtual=*/false); 2428 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 2429 BaseType, Paths)) { 2430 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2431 Path != Paths.end(); ++Path) { 2432 if (Path->back().Base->isVirtual()) { 2433 VirtualBaseSpec = Path->back().Base; 2434 break; 2435 } 2436 } 2437 } 2438 } 2439 2440 return DirectBaseSpec || VirtualBaseSpec; 2441 } 2442 2443 /// \brief Handle a C++ member initializer using braced-init-list syntax. 2444 MemInitResult 2445 Sema::ActOnMemInitializer(Decl *ConstructorD, 2446 Scope *S, 2447 CXXScopeSpec &SS, 2448 IdentifierInfo *MemberOrBase, 2449 ParsedType TemplateTypeTy, 2450 const DeclSpec &DS, 2451 SourceLocation IdLoc, 2452 Expr *InitList, 2453 SourceLocation EllipsisLoc) { 2454 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2455 DS, IdLoc, InitList, 2456 EllipsisLoc); 2457 } 2458 2459 /// \brief Handle a C++ member initializer using parentheses syntax. 2460 MemInitResult 2461 Sema::ActOnMemInitializer(Decl *ConstructorD, 2462 Scope *S, 2463 CXXScopeSpec &SS, 2464 IdentifierInfo *MemberOrBase, 2465 ParsedType TemplateTypeTy, 2466 const DeclSpec &DS, 2467 SourceLocation IdLoc, 2468 SourceLocation LParenLoc, 2469 ArrayRef<Expr *> Args, 2470 SourceLocation RParenLoc, 2471 SourceLocation EllipsisLoc) { 2472 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, 2473 Args, RParenLoc); 2474 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 2475 DS, IdLoc, List, EllipsisLoc); 2476 } 2477 2478 namespace { 2479 2480 // Callback to only accept typo corrections that can be a valid C++ member 2481 // intializer: either a non-static field member or a base class. 2482 class MemInitializerValidatorCCC : public CorrectionCandidateCallback { 2483 public: 2484 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 2485 : ClassDecl(ClassDecl) {} 2486 2487 bool ValidateCandidate(const TypoCorrection &candidate) override { 2488 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 2489 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 2490 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 2491 return isa<TypeDecl>(ND); 2492 } 2493 return false; 2494 } 2495 2496 private: 2497 CXXRecordDecl *ClassDecl; 2498 }; 2499 2500 } 2501 2502 /// \brief Handle a C++ member initializer. 2503 MemInitResult 2504 Sema::BuildMemInitializer(Decl *ConstructorD, 2505 Scope *S, 2506 CXXScopeSpec &SS, 2507 IdentifierInfo *MemberOrBase, 2508 ParsedType TemplateTypeTy, 2509 const DeclSpec &DS, 2510 SourceLocation IdLoc, 2511 Expr *Init, 2512 SourceLocation EllipsisLoc) { 2513 if (!ConstructorD) 2514 return true; 2515 2516 AdjustDeclIfTemplate(ConstructorD); 2517 2518 CXXConstructorDecl *Constructor 2519 = dyn_cast<CXXConstructorDecl>(ConstructorD); 2520 if (!Constructor) { 2521 // The user wrote a constructor initializer on a function that is 2522 // not a C++ constructor. Ignore the error for now, because we may 2523 // have more member initializers coming; we'll diagnose it just 2524 // once in ActOnMemInitializers. 2525 return true; 2526 } 2527 2528 CXXRecordDecl *ClassDecl = Constructor->getParent(); 2529 2530 // C++ [class.base.init]p2: 2531 // Names in a mem-initializer-id are looked up in the scope of the 2532 // constructor's class and, if not found in that scope, are looked 2533 // up in the scope containing the constructor's definition. 2534 // [Note: if the constructor's class contains a member with the 2535 // same name as a direct or virtual base class of the class, a 2536 // mem-initializer-id naming the member or base class and composed 2537 // of a single identifier refers to the class member. A 2538 // mem-initializer-id for the hidden base class may be specified 2539 // using a qualified name. ] 2540 if (!SS.getScopeRep() && !TemplateTypeTy) { 2541 // Look for a member, first. 2542 DeclContext::lookup_result Result 2543 = ClassDecl->lookup(MemberOrBase); 2544 if (!Result.empty()) { 2545 ValueDecl *Member; 2546 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 2547 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) { 2548 if (EllipsisLoc.isValid()) 2549 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 2550 << MemberOrBase 2551 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 2552 2553 return BuildMemberInitializer(Member, Init, IdLoc); 2554 } 2555 } 2556 } 2557 // It didn't name a member, so see if it names a class. 2558 QualType BaseType; 2559 TypeSourceInfo *TInfo = 0; 2560 2561 if (TemplateTypeTy) { 2562 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 2563 } else if (DS.getTypeSpecType() == TST_decltype) { 2564 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 2565 } else { 2566 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 2567 LookupParsedName(R, S, &SS); 2568 2569 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 2570 if (!TyD) { 2571 if (R.isAmbiguous()) return true; 2572 2573 // We don't want access-control diagnostics here. 2574 R.suppressDiagnostics(); 2575 2576 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 2577 bool NotUnknownSpecialization = false; 2578 DeclContext *DC = computeDeclContext(SS, false); 2579 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 2580 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 2581 2582 if (!NotUnknownSpecialization) { 2583 // When the scope specifier can refer to a member of an unknown 2584 // specialization, we take it as a type name. 2585 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 2586 SS.getWithLocInContext(Context), 2587 *MemberOrBase, IdLoc); 2588 if (BaseType.isNull()) 2589 return true; 2590 2591 R.clear(); 2592 R.setLookupName(MemberOrBase); 2593 } 2594 } 2595 2596 // If no results were found, try to correct typos. 2597 TypoCorrection Corr; 2598 MemInitializerValidatorCCC Validator(ClassDecl); 2599 if (R.empty() && BaseType.isNull() && 2600 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 2601 Validator, ClassDecl))) { 2602 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 2603 // We have found a non-static data member with a similar 2604 // name to what was typed; complain and initialize that 2605 // member. 2606 diagnoseTypo(Corr, 2607 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2608 << MemberOrBase << true); 2609 return BuildMemberInitializer(Member, Init, IdLoc); 2610 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 2611 const CXXBaseSpecifier *DirectBaseSpec; 2612 const CXXBaseSpecifier *VirtualBaseSpec; 2613 if (FindBaseInitializer(*this, ClassDecl, 2614 Context.getTypeDeclType(Type), 2615 DirectBaseSpec, VirtualBaseSpec)) { 2616 // We have found a direct or virtual base class with a 2617 // similar name to what was typed; complain and initialize 2618 // that base class. 2619 diagnoseTypo(Corr, 2620 PDiag(diag::err_mem_init_not_member_or_class_suggest) 2621 << MemberOrBase << false, 2622 PDiag() /*Suppress note, we provide our own.*/); 2623 2624 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 2625 : VirtualBaseSpec; 2626 Diag(BaseSpec->getLocStart(), 2627 diag::note_base_class_specified_here) 2628 << BaseSpec->getType() 2629 << BaseSpec->getSourceRange(); 2630 2631 TyD = Type; 2632 } 2633 } 2634 } 2635 2636 if (!TyD && BaseType.isNull()) { 2637 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 2638 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 2639 return true; 2640 } 2641 } 2642 2643 if (BaseType.isNull()) { 2644 BaseType = Context.getTypeDeclType(TyD); 2645 if (SS.isSet()) 2646 // FIXME: preserve source range information 2647 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 2648 BaseType); 2649 } 2650 } 2651 2652 if (!TInfo) 2653 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 2654 2655 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 2656 } 2657 2658 /// Checks a member initializer expression for cases where reference (or 2659 /// pointer) members are bound to by-value parameters (or their addresses). 2660 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member, 2661 Expr *Init, 2662 SourceLocation IdLoc) { 2663 QualType MemberTy = Member->getType(); 2664 2665 // We only handle pointers and references currently. 2666 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers? 2667 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType()) 2668 return; 2669 2670 const bool IsPointer = MemberTy->isPointerType(); 2671 if (IsPointer) { 2672 if (const UnaryOperator *Op 2673 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) { 2674 // The only case we're worried about with pointers requires taking the 2675 // address. 2676 if (Op->getOpcode() != UO_AddrOf) 2677 return; 2678 2679 Init = Op->getSubExpr(); 2680 } else { 2681 // We only handle address-of expression initializers for pointers. 2682 return; 2683 } 2684 } 2685 2686 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) { 2687 // We only warn when referring to a non-reference parameter declaration. 2688 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl()); 2689 if (!Parameter || Parameter->getType()->isReferenceType()) 2690 return; 2691 2692 S.Diag(Init->getExprLoc(), 2693 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr 2694 : diag::warn_bind_ref_member_to_parameter) 2695 << Member << Parameter << Init->getSourceRange(); 2696 } else { 2697 // Other initializers are fine. 2698 return; 2699 } 2700 2701 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here) 2702 << (unsigned)IsPointer; 2703 } 2704 2705 MemInitResult 2706 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 2707 SourceLocation IdLoc) { 2708 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 2709 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 2710 assert((DirectMember || IndirectMember) && 2711 "Member must be a FieldDecl or IndirectFieldDecl"); 2712 2713 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2714 return true; 2715 2716 if (Member->isInvalidDecl()) 2717 return true; 2718 2719 MultiExprArg Args; 2720 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2721 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2722 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 2723 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 2724 } else { 2725 // Template instantiation doesn't reconstruct ParenListExprs for us. 2726 Args = Init; 2727 } 2728 2729 SourceRange InitRange = Init->getSourceRange(); 2730 2731 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 2732 // Can't check initialization for a member of dependent type or when 2733 // any of the arguments are type-dependent expressions. 2734 DiscardCleanupsInEvaluationContext(); 2735 } else { 2736 bool InitList = false; 2737 if (isa<InitListExpr>(Init)) { 2738 InitList = true; 2739 Args = Init; 2740 } 2741 2742 // Initialize the member. 2743 InitializedEntity MemberEntity = 2744 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 2745 : InitializedEntity::InitializeMember(IndirectMember, 0); 2746 InitializationKind Kind = 2747 InitList ? InitializationKind::CreateDirectList(IdLoc) 2748 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 2749 InitRange.getEnd()); 2750 2751 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 2752 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0); 2753 if (MemberInit.isInvalid()) 2754 return true; 2755 2756 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc); 2757 2758 // C++11 [class.base.init]p7: 2759 // The initialization of each base and member constitutes a 2760 // full-expression. 2761 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin()); 2762 if (MemberInit.isInvalid()) 2763 return true; 2764 2765 Init = MemberInit.get(); 2766 } 2767 2768 if (DirectMember) { 2769 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 2770 InitRange.getBegin(), Init, 2771 InitRange.getEnd()); 2772 } else { 2773 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 2774 InitRange.getBegin(), Init, 2775 InitRange.getEnd()); 2776 } 2777 } 2778 2779 MemInitResult 2780 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 2781 CXXRecordDecl *ClassDecl) { 2782 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2783 if (!LangOpts.CPlusPlus11) 2784 return Diag(NameLoc, diag::err_delegating_ctor) 2785 << TInfo->getTypeLoc().getLocalSourceRange(); 2786 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 2787 2788 bool InitList = true; 2789 MultiExprArg Args = Init; 2790 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2791 InitList = false; 2792 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2793 } 2794 2795 SourceRange InitRange = Init->getSourceRange(); 2796 // Initialize the object. 2797 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 2798 QualType(ClassDecl->getTypeForDecl(), 0)); 2799 InitializationKind Kind = 2800 InitList ? InitializationKind::CreateDirectList(NameLoc) 2801 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 2802 InitRange.getEnd()); 2803 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 2804 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 2805 Args, 0); 2806 if (DelegationInit.isInvalid()) 2807 return true; 2808 2809 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 2810 "Delegating constructor with no target?"); 2811 2812 // C++11 [class.base.init]p7: 2813 // The initialization of each base and member constitutes a 2814 // full-expression. 2815 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(), 2816 InitRange.getBegin()); 2817 if (DelegationInit.isInvalid()) 2818 return true; 2819 2820 // If we are in a dependent context, template instantiation will 2821 // perform this type-checking again. Just save the arguments that we 2822 // received in a ParenListExpr. 2823 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2824 // of the information that we have about the base 2825 // initializer. However, deconstructing the ASTs is a dicey process, 2826 // and this approach is far more likely to get the corner cases right. 2827 if (CurContext->isDependentContext()) 2828 DelegationInit = Owned(Init); 2829 2830 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 2831 DelegationInit.takeAs<Expr>(), 2832 InitRange.getEnd()); 2833 } 2834 2835 MemInitResult 2836 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 2837 Expr *Init, CXXRecordDecl *ClassDecl, 2838 SourceLocation EllipsisLoc) { 2839 SourceLocation BaseLoc 2840 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 2841 2842 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 2843 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 2844 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2845 2846 // C++ [class.base.init]p2: 2847 // [...] Unless the mem-initializer-id names a nonstatic data 2848 // member of the constructor's class or a direct or virtual base 2849 // of that class, the mem-initializer is ill-formed. A 2850 // mem-initializer-list can initialize a base class using any 2851 // name that denotes that base class type. 2852 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 2853 2854 SourceRange InitRange = Init->getSourceRange(); 2855 if (EllipsisLoc.isValid()) { 2856 // This is a pack expansion. 2857 if (!BaseType->containsUnexpandedParameterPack()) { 2858 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2859 << SourceRange(BaseLoc, InitRange.getEnd()); 2860 2861 EllipsisLoc = SourceLocation(); 2862 } 2863 } else { 2864 // Check for any unexpanded parameter packs. 2865 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 2866 return true; 2867 2868 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 2869 return true; 2870 } 2871 2872 // Check for direct and virtual base classes. 2873 const CXXBaseSpecifier *DirectBaseSpec = 0; 2874 const CXXBaseSpecifier *VirtualBaseSpec = 0; 2875 if (!Dependent) { 2876 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 2877 BaseType)) 2878 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 2879 2880 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 2881 VirtualBaseSpec); 2882 2883 // C++ [base.class.init]p2: 2884 // Unless the mem-initializer-id names a nonstatic data member of the 2885 // constructor's class or a direct or virtual base of that class, the 2886 // mem-initializer is ill-formed. 2887 if (!DirectBaseSpec && !VirtualBaseSpec) { 2888 // If the class has any dependent bases, then it's possible that 2889 // one of those types will resolve to the same type as 2890 // BaseType. Therefore, just treat this as a dependent base 2891 // class initialization. FIXME: Should we try to check the 2892 // initialization anyway? It seems odd. 2893 if (ClassDecl->hasAnyDependentBases()) 2894 Dependent = true; 2895 else 2896 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 2897 << BaseType << Context.getTypeDeclType(ClassDecl) 2898 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2899 } 2900 } 2901 2902 if (Dependent) { 2903 DiscardCleanupsInEvaluationContext(); 2904 2905 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2906 /*IsVirtual=*/false, 2907 InitRange.getBegin(), Init, 2908 InitRange.getEnd(), EllipsisLoc); 2909 } 2910 2911 // C++ [base.class.init]p2: 2912 // If a mem-initializer-id is ambiguous because it designates both 2913 // a direct non-virtual base class and an inherited virtual base 2914 // class, the mem-initializer is ill-formed. 2915 if (DirectBaseSpec && VirtualBaseSpec) 2916 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 2917 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 2918 2919 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 2920 if (!BaseSpec) 2921 BaseSpec = VirtualBaseSpec; 2922 2923 // Initialize the base. 2924 bool InitList = true; 2925 MultiExprArg Args = Init; 2926 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 2927 InitList = false; 2928 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 2929 } 2930 2931 InitializedEntity BaseEntity = 2932 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 2933 InitializationKind Kind = 2934 InitList ? InitializationKind::CreateDirectList(BaseLoc) 2935 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 2936 InitRange.getEnd()); 2937 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 2938 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0); 2939 if (BaseInit.isInvalid()) 2940 return true; 2941 2942 // C++11 [class.base.init]p7: 2943 // The initialization of each base and member constitutes a 2944 // full-expression. 2945 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin()); 2946 if (BaseInit.isInvalid()) 2947 return true; 2948 2949 // If we are in a dependent context, template instantiation will 2950 // perform this type-checking again. Just save the arguments that we 2951 // received in a ParenListExpr. 2952 // FIXME: This isn't quite ideal, since our ASTs don't capture all 2953 // of the information that we have about the base 2954 // initializer. However, deconstructing the ASTs is a dicey process, 2955 // and this approach is far more likely to get the corner cases right. 2956 if (CurContext->isDependentContext()) 2957 BaseInit = Owned(Init); 2958 2959 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 2960 BaseSpec->isVirtual(), 2961 InitRange.getBegin(), 2962 BaseInit.takeAs<Expr>(), 2963 InitRange.getEnd(), EllipsisLoc); 2964 } 2965 2966 // Create a static_cast\<T&&>(expr). 2967 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 2968 if (T.isNull()) T = E->getType(); 2969 QualType TargetType = SemaRef.BuildReferenceType( 2970 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 2971 SourceLocation ExprLoc = E->getLocStart(); 2972 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 2973 TargetType, ExprLoc); 2974 2975 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 2976 SourceRange(ExprLoc, ExprLoc), 2977 E->getSourceRange()).take(); 2978 } 2979 2980 /// ImplicitInitializerKind - How an implicit base or member initializer should 2981 /// initialize its base or member. 2982 enum ImplicitInitializerKind { 2983 IIK_Default, 2984 IIK_Copy, 2985 IIK_Move, 2986 IIK_Inherit 2987 }; 2988 2989 static bool 2990 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 2991 ImplicitInitializerKind ImplicitInitKind, 2992 CXXBaseSpecifier *BaseSpec, 2993 bool IsInheritedVirtualBase, 2994 CXXCtorInitializer *&CXXBaseInit) { 2995 InitializedEntity InitEntity 2996 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 2997 IsInheritedVirtualBase); 2998 2999 ExprResult BaseInit; 3000 3001 switch (ImplicitInitKind) { 3002 case IIK_Inherit: { 3003 const CXXRecordDecl *Inherited = 3004 Constructor->getInheritedConstructor()->getParent(); 3005 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 3006 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) { 3007 // C++11 [class.inhctor]p8: 3008 // Each expression in the expression-list is of the form 3009 // static_cast<T&&>(p), where p is the name of the corresponding 3010 // constructor parameter and T is the declared type of p. 3011 SmallVector<Expr*, 16> Args; 3012 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) { 3013 ParmVarDecl *PD = Constructor->getParamDecl(I); 3014 ExprResult ArgExpr = 3015 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 3016 VK_LValue, SourceLocation()); 3017 if (ArgExpr.isInvalid()) 3018 return true; 3019 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType())); 3020 } 3021 3022 InitializationKind InitKind = InitializationKind::CreateDirect( 3023 Constructor->getLocation(), SourceLocation(), SourceLocation()); 3024 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args); 3025 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args); 3026 break; 3027 } 3028 } 3029 // Fall through. 3030 case IIK_Default: { 3031 InitializationKind InitKind 3032 = InitializationKind::CreateDefault(Constructor->getLocation()); 3033 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3034 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3035 break; 3036 } 3037 3038 case IIK_Move: 3039 case IIK_Copy: { 3040 bool Moving = ImplicitInitKind == IIK_Move; 3041 ParmVarDecl *Param = Constructor->getParamDecl(0); 3042 QualType ParamType = Param->getType().getNonReferenceType(); 3043 3044 Expr *CopyCtorArg = 3045 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3046 SourceLocation(), Param, false, 3047 Constructor->getLocation(), ParamType, 3048 VK_LValue, 0); 3049 3050 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 3051 3052 // Cast to the base class to avoid ambiguities. 3053 QualType ArgTy = 3054 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 3055 ParamType.getQualifiers()); 3056 3057 if (Moving) { 3058 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 3059 } 3060 3061 CXXCastPath BasePath; 3062 BasePath.push_back(BaseSpec); 3063 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 3064 CK_UncheckedDerivedToBase, 3065 Moving ? VK_XValue : VK_LValue, 3066 &BasePath).take(); 3067 3068 InitializationKind InitKind 3069 = InitializationKind::CreateDirect(Constructor->getLocation(), 3070 SourceLocation(), SourceLocation()); 3071 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 3072 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 3073 break; 3074 } 3075 } 3076 3077 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 3078 if (BaseInit.isInvalid()) 3079 return true; 3080 3081 CXXBaseInit = 3082 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3083 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 3084 SourceLocation()), 3085 BaseSpec->isVirtual(), 3086 SourceLocation(), 3087 BaseInit.takeAs<Expr>(), 3088 SourceLocation(), 3089 SourceLocation()); 3090 3091 return false; 3092 } 3093 3094 static bool RefersToRValueRef(Expr *MemRef) { 3095 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 3096 return Referenced->getType()->isRValueReferenceType(); 3097 } 3098 3099 static bool 3100 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 3101 ImplicitInitializerKind ImplicitInitKind, 3102 FieldDecl *Field, IndirectFieldDecl *Indirect, 3103 CXXCtorInitializer *&CXXMemberInit) { 3104 if (Field->isInvalidDecl()) 3105 return true; 3106 3107 SourceLocation Loc = Constructor->getLocation(); 3108 3109 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 3110 bool Moving = ImplicitInitKind == IIK_Move; 3111 ParmVarDecl *Param = Constructor->getParamDecl(0); 3112 QualType ParamType = Param->getType().getNonReferenceType(); 3113 3114 // Suppress copying zero-width bitfields. 3115 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0) 3116 return false; 3117 3118 Expr *MemberExprBase = 3119 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 3120 SourceLocation(), Param, false, 3121 Loc, ParamType, VK_LValue, 0); 3122 3123 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 3124 3125 if (Moving) { 3126 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 3127 } 3128 3129 // Build a reference to this field within the parameter. 3130 CXXScopeSpec SS; 3131 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 3132 Sema::LookupMemberName); 3133 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 3134 : cast<ValueDecl>(Field), AS_public); 3135 MemberLookup.resolveKind(); 3136 ExprResult CtorArg 3137 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 3138 ParamType, Loc, 3139 /*IsArrow=*/false, 3140 SS, 3141 /*TemplateKWLoc=*/SourceLocation(), 3142 /*FirstQualifierInScope=*/0, 3143 MemberLookup, 3144 /*TemplateArgs=*/0); 3145 if (CtorArg.isInvalid()) 3146 return true; 3147 3148 // C++11 [class.copy]p15: 3149 // - if a member m has rvalue reference type T&&, it is direct-initialized 3150 // with static_cast<T&&>(x.m); 3151 if (RefersToRValueRef(CtorArg.get())) { 3152 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3153 } 3154 3155 // When the field we are copying is an array, create index variables for 3156 // each dimension of the array. We use these index variables to subscript 3157 // the source array, and other clients (e.g., CodeGen) will perform the 3158 // necessary iteration with these index variables. 3159 SmallVector<VarDecl *, 4> IndexVariables; 3160 QualType BaseType = Field->getType(); 3161 QualType SizeType = SemaRef.Context.getSizeType(); 3162 bool InitializingArray = false; 3163 while (const ConstantArrayType *Array 3164 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 3165 InitializingArray = true; 3166 // Create the iteration variable for this array index. 3167 IdentifierInfo *IterationVarName = 0; 3168 { 3169 SmallString<8> Str; 3170 llvm::raw_svector_ostream OS(Str); 3171 OS << "__i" << IndexVariables.size(); 3172 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 3173 } 3174 VarDecl *IterationVar 3175 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 3176 IterationVarName, SizeType, 3177 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 3178 SC_None); 3179 IndexVariables.push_back(IterationVar); 3180 3181 // Create a reference to the iteration variable. 3182 ExprResult IterationVarRef 3183 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 3184 assert(!IterationVarRef.isInvalid() && 3185 "Reference to invented variable cannot fail!"); 3186 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take()); 3187 assert(!IterationVarRef.isInvalid() && 3188 "Conversion of invented variable cannot fail!"); 3189 3190 // Subscript the array with this iteration variable. 3191 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc, 3192 IterationVarRef.take(), 3193 Loc); 3194 if (CtorArg.isInvalid()) 3195 return true; 3196 3197 BaseType = Array->getElementType(); 3198 } 3199 3200 // The array subscript expression is an lvalue, which is wrong for moving. 3201 if (Moving && InitializingArray) 3202 CtorArg = CastForMoving(SemaRef, CtorArg.take()); 3203 3204 // Construct the entity that we will be initializing. For an array, this 3205 // will be first element in the array, which may require several levels 3206 // of array-subscript entities. 3207 SmallVector<InitializedEntity, 4> Entities; 3208 Entities.reserve(1 + IndexVariables.size()); 3209 if (Indirect) 3210 Entities.push_back(InitializedEntity::InitializeMember(Indirect)); 3211 else 3212 Entities.push_back(InitializedEntity::InitializeMember(Field)); 3213 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 3214 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 3215 0, 3216 Entities.back())); 3217 3218 // Direct-initialize to use the copy constructor. 3219 InitializationKind InitKind = 3220 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 3221 3222 Expr *CtorArgE = CtorArg.takeAs<Expr>(); 3223 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE); 3224 3225 ExprResult MemberInit 3226 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 3227 MultiExprArg(&CtorArgE, 1)); 3228 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3229 if (MemberInit.isInvalid()) 3230 return true; 3231 3232 if (Indirect) { 3233 assert(IndexVariables.size() == 0 && 3234 "Indirect field improperly initialized"); 3235 CXXMemberInit 3236 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3237 Loc, Loc, 3238 MemberInit.takeAs<Expr>(), 3239 Loc); 3240 } else 3241 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 3242 Loc, MemberInit.takeAs<Expr>(), 3243 Loc, 3244 IndexVariables.data(), 3245 IndexVariables.size()); 3246 return false; 3247 } 3248 3249 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 3250 "Unhandled implicit init kind!"); 3251 3252 QualType FieldBaseElementType = 3253 SemaRef.Context.getBaseElementType(Field->getType()); 3254 3255 if (FieldBaseElementType->isRecordType()) { 3256 InitializedEntity InitEntity 3257 = Indirect? InitializedEntity::InitializeMember(Indirect) 3258 : InitializedEntity::InitializeMember(Field); 3259 InitializationKind InitKind = 3260 InitializationKind::CreateDefault(Loc); 3261 3262 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 3263 ExprResult MemberInit = 3264 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 3265 3266 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 3267 if (MemberInit.isInvalid()) 3268 return true; 3269 3270 if (Indirect) 3271 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3272 Indirect, Loc, 3273 Loc, 3274 MemberInit.get(), 3275 Loc); 3276 else 3277 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 3278 Field, Loc, Loc, 3279 MemberInit.get(), 3280 Loc); 3281 return false; 3282 } 3283 3284 if (!Field->getParent()->isUnion()) { 3285 if (FieldBaseElementType->isReferenceType()) { 3286 SemaRef.Diag(Constructor->getLocation(), 3287 diag::err_uninitialized_member_in_ctor) 3288 << (int)Constructor->isImplicit() 3289 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3290 << 0 << Field->getDeclName(); 3291 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3292 return true; 3293 } 3294 3295 if (FieldBaseElementType.isConstQualified()) { 3296 SemaRef.Diag(Constructor->getLocation(), 3297 diag::err_uninitialized_member_in_ctor) 3298 << (int)Constructor->isImplicit() 3299 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 3300 << 1 << Field->getDeclName(); 3301 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 3302 return true; 3303 } 3304 } 3305 3306 if (SemaRef.getLangOpts().ObjCAutoRefCount && 3307 FieldBaseElementType->isObjCRetainableType() && 3308 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None && 3309 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) { 3310 // ARC: 3311 // Default-initialize Objective-C pointers to NULL. 3312 CXXMemberInit 3313 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3314 Loc, Loc, 3315 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 3316 Loc); 3317 return false; 3318 } 3319 3320 // Nothing to initialize. 3321 CXXMemberInit = 0; 3322 return false; 3323 } 3324 3325 namespace { 3326 struct BaseAndFieldInfo { 3327 Sema &S; 3328 CXXConstructorDecl *Ctor; 3329 bool AnyErrorsInInits; 3330 ImplicitInitializerKind IIK; 3331 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 3332 SmallVector<CXXCtorInitializer*, 8> AllToInit; 3333 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 3334 3335 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 3336 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 3337 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 3338 if (Generated && Ctor->isCopyConstructor()) 3339 IIK = IIK_Copy; 3340 else if (Generated && Ctor->isMoveConstructor()) 3341 IIK = IIK_Move; 3342 else if (Ctor->getInheritedConstructor()) 3343 IIK = IIK_Inherit; 3344 else 3345 IIK = IIK_Default; 3346 } 3347 3348 bool isImplicitCopyOrMove() const { 3349 switch (IIK) { 3350 case IIK_Copy: 3351 case IIK_Move: 3352 return true; 3353 3354 case IIK_Default: 3355 case IIK_Inherit: 3356 return false; 3357 } 3358 3359 llvm_unreachable("Invalid ImplicitInitializerKind!"); 3360 } 3361 3362 bool addFieldInitializer(CXXCtorInitializer *Init) { 3363 AllToInit.push_back(Init); 3364 3365 // Check whether this initializer makes the field "used". 3366 if (Init->getInit()->HasSideEffects(S.Context)) 3367 S.UnusedPrivateFields.remove(Init->getAnyMember()); 3368 3369 return false; 3370 } 3371 3372 bool isInactiveUnionMember(FieldDecl *Field) { 3373 RecordDecl *Record = Field->getParent(); 3374 if (!Record->isUnion()) 3375 return false; 3376 3377 if (FieldDecl *Active = 3378 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 3379 return Active != Field->getCanonicalDecl(); 3380 3381 // In an implicit copy or move constructor, ignore any in-class initializer. 3382 if (isImplicitCopyOrMove()) 3383 return true; 3384 3385 // If there's no explicit initialization, the field is active only if it 3386 // has an in-class initializer... 3387 if (Field->hasInClassInitializer()) 3388 return false; 3389 // ... or it's an anonymous struct or union whose class has an in-class 3390 // initializer. 3391 if (!Field->isAnonymousStructOrUnion()) 3392 return true; 3393 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 3394 return !FieldRD->hasInClassInitializer(); 3395 } 3396 3397 /// \brief Determine whether the given field is, or is within, a union member 3398 /// that is inactive (because there was an initializer given for a different 3399 /// member of the union, or because the union was not initialized at all). 3400 bool isWithinInactiveUnionMember(FieldDecl *Field, 3401 IndirectFieldDecl *Indirect) { 3402 if (!Indirect) 3403 return isInactiveUnionMember(Field); 3404 3405 for (auto *C : Indirect->chain()) { 3406 FieldDecl *Field = dyn_cast<FieldDecl>(C); 3407 if (Field && isInactiveUnionMember(Field)) 3408 return true; 3409 } 3410 return false; 3411 } 3412 }; 3413 } 3414 3415 /// \brief Determine whether the given type is an incomplete or zero-lenfgth 3416 /// array type. 3417 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 3418 if (T->isIncompleteArrayType()) 3419 return true; 3420 3421 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 3422 if (!ArrayT->getSize()) 3423 return true; 3424 3425 T = ArrayT->getElementType(); 3426 } 3427 3428 return false; 3429 } 3430 3431 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 3432 FieldDecl *Field, 3433 IndirectFieldDecl *Indirect = 0) { 3434 if (Field->isInvalidDecl()) 3435 return false; 3436 3437 // Overwhelmingly common case: we have a direct initializer for this field. 3438 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) 3439 return Info.addFieldInitializer(Init); 3440 3441 // C++11 [class.base.init]p8: 3442 // if the entity is a non-static data member that has a 3443 // brace-or-equal-initializer and either 3444 // -- the constructor's class is a union and no other variant member of that 3445 // union is designated by a mem-initializer-id or 3446 // -- the constructor's class is not a union, and, if the entity is a member 3447 // of an anonymous union, no other member of that union is designated by 3448 // a mem-initializer-id, 3449 // the entity is initialized as specified in [dcl.init]. 3450 // 3451 // We also apply the same rules to handle anonymous structs within anonymous 3452 // unions. 3453 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 3454 return false; 3455 3456 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 3457 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context, 3458 Info.Ctor->getLocation(), Field); 3459 CXXCtorInitializer *Init; 3460 if (Indirect) 3461 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 3462 SourceLocation(), 3463 SourceLocation(), DIE, 3464 SourceLocation()); 3465 else 3466 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 3467 SourceLocation(), 3468 SourceLocation(), DIE, 3469 SourceLocation()); 3470 return Info.addFieldInitializer(Init); 3471 } 3472 3473 // Don't initialize incomplete or zero-length arrays. 3474 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 3475 return false; 3476 3477 // Don't try to build an implicit initializer if there were semantic 3478 // errors in any of the initializers (and therefore we might be 3479 // missing some that the user actually wrote). 3480 if (Info.AnyErrorsInInits) 3481 return false; 3482 3483 CXXCtorInitializer *Init = 0; 3484 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 3485 Indirect, Init)) 3486 return true; 3487 3488 if (!Init) 3489 return false; 3490 3491 return Info.addFieldInitializer(Init); 3492 } 3493 3494 bool 3495 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 3496 CXXCtorInitializer *Initializer) { 3497 assert(Initializer->isDelegatingInitializer()); 3498 Constructor->setNumCtorInitializers(1); 3499 CXXCtorInitializer **initializer = 3500 new (Context) CXXCtorInitializer*[1]; 3501 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 3502 Constructor->setCtorInitializers(initializer); 3503 3504 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 3505 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 3506 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 3507 } 3508 3509 DelegatingCtorDecls.push_back(Constructor); 3510 3511 return false; 3512 } 3513 3514 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 3515 ArrayRef<CXXCtorInitializer *> Initializers) { 3516 if (Constructor->isDependentContext()) { 3517 // Just store the initializers as written, they will be checked during 3518 // instantiation. 3519 if (!Initializers.empty()) { 3520 Constructor->setNumCtorInitializers(Initializers.size()); 3521 CXXCtorInitializer **baseOrMemberInitializers = 3522 new (Context) CXXCtorInitializer*[Initializers.size()]; 3523 memcpy(baseOrMemberInitializers, Initializers.data(), 3524 Initializers.size() * sizeof(CXXCtorInitializer*)); 3525 Constructor->setCtorInitializers(baseOrMemberInitializers); 3526 } 3527 3528 // Let template instantiation know whether we had errors. 3529 if (AnyErrors) 3530 Constructor->setInvalidDecl(); 3531 3532 return false; 3533 } 3534 3535 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 3536 3537 // We need to build the initializer AST according to order of construction 3538 // and not what user specified in the Initializers list. 3539 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 3540 if (!ClassDecl) 3541 return true; 3542 3543 bool HadError = false; 3544 3545 for (unsigned i = 0; i < Initializers.size(); i++) { 3546 CXXCtorInitializer *Member = Initializers[i]; 3547 3548 if (Member->isBaseInitializer()) 3549 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 3550 else { 3551 Info.AllBaseFields[Member->getAnyMember()] = Member; 3552 3553 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 3554 for (auto *C : F->chain()) { 3555 FieldDecl *FD = dyn_cast<FieldDecl>(C); 3556 if (FD && FD->getParent()->isUnion()) 3557 Info.ActiveUnionMember.insert(std::make_pair( 3558 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3559 } 3560 } else if (FieldDecl *FD = Member->getMember()) { 3561 if (FD->getParent()->isUnion()) 3562 Info.ActiveUnionMember.insert(std::make_pair( 3563 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 3564 } 3565 } 3566 } 3567 3568 // Keep track of the direct virtual bases. 3569 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 3570 for (auto &I : ClassDecl->bases()) { 3571 if (I.isVirtual()) 3572 DirectVBases.insert(&I); 3573 } 3574 3575 // Push virtual bases before others. 3576 for (auto &VBase : ClassDecl->vbases()) { 3577 if (CXXCtorInitializer *Value 3578 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 3579 // [class.base.init]p7, per DR257: 3580 // A mem-initializer where the mem-initializer-id names a virtual base 3581 // class is ignored during execution of a constructor of any class that 3582 // is not the most derived class. 3583 if (ClassDecl->isAbstract()) { 3584 // FIXME: Provide a fixit to remove the base specifier. This requires 3585 // tracking the location of the associated comma for a base specifier. 3586 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 3587 << VBase.getType() << ClassDecl; 3588 DiagnoseAbstractType(ClassDecl); 3589 } 3590 3591 Info.AllToInit.push_back(Value); 3592 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 3593 // [class.base.init]p8, per DR257: 3594 // If a given [...] base class is not named by a mem-initializer-id 3595 // [...] and the entity is not a virtual base class of an abstract 3596 // class, then [...] the entity is default-initialized. 3597 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 3598 CXXCtorInitializer *CXXBaseInit; 3599 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3600 &VBase, IsInheritedVirtualBase, 3601 CXXBaseInit)) { 3602 HadError = true; 3603 continue; 3604 } 3605 3606 Info.AllToInit.push_back(CXXBaseInit); 3607 } 3608 } 3609 3610 // Non-virtual bases. 3611 for (auto &Base : ClassDecl->bases()) { 3612 // Virtuals are in the virtual base list and already constructed. 3613 if (Base.isVirtual()) 3614 continue; 3615 3616 if (CXXCtorInitializer *Value 3617 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 3618 Info.AllToInit.push_back(Value); 3619 } else if (!AnyErrors) { 3620 CXXCtorInitializer *CXXBaseInit; 3621 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 3622 &Base, /*IsInheritedVirtualBase=*/false, 3623 CXXBaseInit)) { 3624 HadError = true; 3625 continue; 3626 } 3627 3628 Info.AllToInit.push_back(CXXBaseInit); 3629 } 3630 } 3631 3632 // Fields. 3633 for (auto *Mem : ClassDecl->decls()) { 3634 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 3635 // C++ [class.bit]p2: 3636 // A declaration for a bit-field that omits the identifier declares an 3637 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 3638 // initialized. 3639 if (F->isUnnamedBitfield()) 3640 continue; 3641 3642 // If we're not generating the implicit copy/move constructor, then we'll 3643 // handle anonymous struct/union fields based on their individual 3644 // indirect fields. 3645 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 3646 continue; 3647 3648 if (CollectFieldInitializer(*this, Info, F)) 3649 HadError = true; 3650 continue; 3651 } 3652 3653 // Beyond this point, we only consider default initialization. 3654 if (Info.isImplicitCopyOrMove()) 3655 continue; 3656 3657 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 3658 if (F->getType()->isIncompleteArrayType()) { 3659 assert(ClassDecl->hasFlexibleArrayMember() && 3660 "Incomplete array type is not valid"); 3661 continue; 3662 } 3663 3664 // Initialize each field of an anonymous struct individually. 3665 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 3666 HadError = true; 3667 3668 continue; 3669 } 3670 } 3671 3672 unsigned NumInitializers = Info.AllToInit.size(); 3673 if (NumInitializers > 0) { 3674 Constructor->setNumCtorInitializers(NumInitializers); 3675 CXXCtorInitializer **baseOrMemberInitializers = 3676 new (Context) CXXCtorInitializer*[NumInitializers]; 3677 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 3678 NumInitializers * sizeof(CXXCtorInitializer*)); 3679 Constructor->setCtorInitializers(baseOrMemberInitializers); 3680 3681 // Constructors implicitly reference the base and member 3682 // destructors. 3683 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 3684 Constructor->getParent()); 3685 } 3686 3687 return HadError; 3688 } 3689 3690 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 3691 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 3692 const RecordDecl *RD = RT->getDecl(); 3693 if (RD->isAnonymousStructOrUnion()) { 3694 for (auto *Field : RD->fields()) 3695 PopulateKeysForFields(Field, IdealInits); 3696 return; 3697 } 3698 } 3699 IdealInits.push_back(Field); 3700 } 3701 3702 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 3703 return Context.getCanonicalType(BaseType).getTypePtr(); 3704 } 3705 3706 static const void *GetKeyForMember(ASTContext &Context, 3707 CXXCtorInitializer *Member) { 3708 if (!Member->isAnyMemberInitializer()) 3709 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 3710 3711 return Member->getAnyMember(); 3712 } 3713 3714 static void DiagnoseBaseOrMemInitializerOrder( 3715 Sema &SemaRef, const CXXConstructorDecl *Constructor, 3716 ArrayRef<CXXCtorInitializer *> Inits) { 3717 if (Constructor->getDeclContext()->isDependentContext()) 3718 return; 3719 3720 // Don't check initializers order unless the warning is enabled at the 3721 // location of at least one initializer. 3722 bool ShouldCheckOrder = false; 3723 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3724 CXXCtorInitializer *Init = Inits[InitIndex]; 3725 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 3726 Init->getSourceLocation()) 3727 != DiagnosticsEngine::Ignored) { 3728 ShouldCheckOrder = true; 3729 break; 3730 } 3731 } 3732 if (!ShouldCheckOrder) 3733 return; 3734 3735 // Build the list of bases and members in the order that they'll 3736 // actually be initialized. The explicit initializers should be in 3737 // this same order but may be missing things. 3738 SmallVector<const void*, 32> IdealInitKeys; 3739 3740 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 3741 3742 // 1. Virtual bases. 3743 for (const auto &VBase : ClassDecl->vbases()) 3744 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 3745 3746 // 2. Non-virtual bases. 3747 for (const auto &Base : ClassDecl->bases()) { 3748 if (Base.isVirtual()) 3749 continue; 3750 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 3751 } 3752 3753 // 3. Direct fields. 3754 for (auto *Field : ClassDecl->fields()) { 3755 if (Field->isUnnamedBitfield()) 3756 continue; 3757 3758 PopulateKeysForFields(Field, IdealInitKeys); 3759 } 3760 3761 unsigned NumIdealInits = IdealInitKeys.size(); 3762 unsigned IdealIndex = 0; 3763 3764 CXXCtorInitializer *PrevInit = 0; 3765 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 3766 CXXCtorInitializer *Init = Inits[InitIndex]; 3767 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 3768 3769 // Scan forward to try to find this initializer in the idealized 3770 // initializers list. 3771 for (; IdealIndex != NumIdealInits; ++IdealIndex) 3772 if (InitKey == IdealInitKeys[IdealIndex]) 3773 break; 3774 3775 // If we didn't find this initializer, it must be because we 3776 // scanned past it on a previous iteration. That can only 3777 // happen if we're out of order; emit a warning. 3778 if (IdealIndex == NumIdealInits && PrevInit) { 3779 Sema::SemaDiagnosticBuilder D = 3780 SemaRef.Diag(PrevInit->getSourceLocation(), 3781 diag::warn_initializer_out_of_order); 3782 3783 if (PrevInit->isAnyMemberInitializer()) 3784 D << 0 << PrevInit->getAnyMember()->getDeclName(); 3785 else 3786 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 3787 3788 if (Init->isAnyMemberInitializer()) 3789 D << 0 << Init->getAnyMember()->getDeclName(); 3790 else 3791 D << 1 << Init->getTypeSourceInfo()->getType(); 3792 3793 // Move back to the initializer's location in the ideal list. 3794 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 3795 if (InitKey == IdealInitKeys[IdealIndex]) 3796 break; 3797 3798 assert(IdealIndex != NumIdealInits && 3799 "initializer not found in initializer list"); 3800 } 3801 3802 PrevInit = Init; 3803 } 3804 } 3805 3806 namespace { 3807 bool CheckRedundantInit(Sema &S, 3808 CXXCtorInitializer *Init, 3809 CXXCtorInitializer *&PrevInit) { 3810 if (!PrevInit) { 3811 PrevInit = Init; 3812 return false; 3813 } 3814 3815 if (FieldDecl *Field = Init->getAnyMember()) 3816 S.Diag(Init->getSourceLocation(), 3817 diag::err_multiple_mem_initialization) 3818 << Field->getDeclName() 3819 << Init->getSourceRange(); 3820 else { 3821 const Type *BaseClass = Init->getBaseClass(); 3822 assert(BaseClass && "neither field nor base"); 3823 S.Diag(Init->getSourceLocation(), 3824 diag::err_multiple_base_initialization) 3825 << QualType(BaseClass, 0) 3826 << Init->getSourceRange(); 3827 } 3828 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 3829 << 0 << PrevInit->getSourceRange(); 3830 3831 return true; 3832 } 3833 3834 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 3835 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 3836 3837 bool CheckRedundantUnionInit(Sema &S, 3838 CXXCtorInitializer *Init, 3839 RedundantUnionMap &Unions) { 3840 FieldDecl *Field = Init->getAnyMember(); 3841 RecordDecl *Parent = Field->getParent(); 3842 NamedDecl *Child = Field; 3843 3844 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 3845 if (Parent->isUnion()) { 3846 UnionEntry &En = Unions[Parent]; 3847 if (En.first && En.first != Child) { 3848 S.Diag(Init->getSourceLocation(), 3849 diag::err_multiple_mem_union_initialization) 3850 << Field->getDeclName() 3851 << Init->getSourceRange(); 3852 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 3853 << 0 << En.second->getSourceRange(); 3854 return true; 3855 } 3856 if (!En.first) { 3857 En.first = Child; 3858 En.second = Init; 3859 } 3860 if (!Parent->isAnonymousStructOrUnion()) 3861 return false; 3862 } 3863 3864 Child = Parent; 3865 Parent = cast<RecordDecl>(Parent->getDeclContext()); 3866 } 3867 3868 return false; 3869 } 3870 } 3871 3872 /// ActOnMemInitializers - Handle the member initializers for a constructor. 3873 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 3874 SourceLocation ColonLoc, 3875 ArrayRef<CXXCtorInitializer*> MemInits, 3876 bool AnyErrors) { 3877 if (!ConstructorDecl) 3878 return; 3879 3880 AdjustDeclIfTemplate(ConstructorDecl); 3881 3882 CXXConstructorDecl *Constructor 3883 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 3884 3885 if (!Constructor) { 3886 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 3887 return; 3888 } 3889 3890 // Mapping for the duplicate initializers check. 3891 // For member initializers, this is keyed with a FieldDecl*. 3892 // For base initializers, this is keyed with a Type*. 3893 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 3894 3895 // Mapping for the inconsistent anonymous-union initializers check. 3896 RedundantUnionMap MemberUnions; 3897 3898 bool HadError = false; 3899 for (unsigned i = 0; i < MemInits.size(); i++) { 3900 CXXCtorInitializer *Init = MemInits[i]; 3901 3902 // Set the source order index. 3903 Init->setSourceOrder(i); 3904 3905 if (Init->isAnyMemberInitializer()) { 3906 FieldDecl *Field = Init->getAnyMember(); 3907 if (CheckRedundantInit(*this, Init, Members[Field]) || 3908 CheckRedundantUnionInit(*this, Init, MemberUnions)) 3909 HadError = true; 3910 } else if (Init->isBaseInitializer()) { 3911 const void *Key = 3912 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 3913 if (CheckRedundantInit(*this, Init, Members[Key])) 3914 HadError = true; 3915 } else { 3916 assert(Init->isDelegatingInitializer()); 3917 // This must be the only initializer 3918 if (MemInits.size() != 1) { 3919 Diag(Init->getSourceLocation(), 3920 diag::err_delegating_initializer_alone) 3921 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 3922 // We will treat this as being the only initializer. 3923 } 3924 SetDelegatingInitializer(Constructor, MemInits[i]); 3925 // Return immediately as the initializer is set. 3926 return; 3927 } 3928 } 3929 3930 if (HadError) 3931 return; 3932 3933 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 3934 3935 SetCtorInitializers(Constructor, AnyErrors, MemInits); 3936 3937 DiagnoseUninitializedFields(*this, Constructor); 3938 } 3939 3940 void 3941 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 3942 CXXRecordDecl *ClassDecl) { 3943 // Ignore dependent contexts. Also ignore unions, since their members never 3944 // have destructors implicitly called. 3945 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 3946 return; 3947 3948 // FIXME: all the access-control diagnostics are positioned on the 3949 // field/base declaration. That's probably good; that said, the 3950 // user might reasonably want to know why the destructor is being 3951 // emitted, and we currently don't say. 3952 3953 // Non-static data members. 3954 for (auto *Field : ClassDecl->fields()) { 3955 if (Field->isInvalidDecl()) 3956 continue; 3957 3958 // Don't destroy incomplete or zero-length arrays. 3959 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 3960 continue; 3961 3962 QualType FieldType = Context.getBaseElementType(Field->getType()); 3963 3964 const RecordType* RT = FieldType->getAs<RecordType>(); 3965 if (!RT) 3966 continue; 3967 3968 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 3969 if (FieldClassDecl->isInvalidDecl()) 3970 continue; 3971 if (FieldClassDecl->hasIrrelevantDestructor()) 3972 continue; 3973 // The destructor for an implicit anonymous union member is never invoked. 3974 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 3975 continue; 3976 3977 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 3978 assert(Dtor && "No dtor found for FieldClassDecl!"); 3979 CheckDestructorAccess(Field->getLocation(), Dtor, 3980 PDiag(diag::err_access_dtor_field) 3981 << Field->getDeclName() 3982 << FieldType); 3983 3984 MarkFunctionReferenced(Location, Dtor); 3985 DiagnoseUseOfDecl(Dtor, Location); 3986 } 3987 3988 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 3989 3990 // Bases. 3991 for (const auto &Base : ClassDecl->bases()) { 3992 // Bases are always records in a well-formed non-dependent class. 3993 const RecordType *RT = Base.getType()->getAs<RecordType>(); 3994 3995 // Remember direct virtual bases. 3996 if (Base.isVirtual()) 3997 DirectVirtualBases.insert(RT); 3998 3999 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4000 // If our base class is invalid, we probably can't get its dtor anyway. 4001 if (BaseClassDecl->isInvalidDecl()) 4002 continue; 4003 if (BaseClassDecl->hasIrrelevantDestructor()) 4004 continue; 4005 4006 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4007 assert(Dtor && "No dtor found for BaseClassDecl!"); 4008 4009 // FIXME: caret should be on the start of the class name 4010 CheckDestructorAccess(Base.getLocStart(), Dtor, 4011 PDiag(diag::err_access_dtor_base) 4012 << Base.getType() 4013 << Base.getSourceRange(), 4014 Context.getTypeDeclType(ClassDecl)); 4015 4016 MarkFunctionReferenced(Location, Dtor); 4017 DiagnoseUseOfDecl(Dtor, Location); 4018 } 4019 4020 // Virtual bases. 4021 for (const auto &VBase : ClassDecl->vbases()) { 4022 // Bases are always records in a well-formed non-dependent class. 4023 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 4024 4025 // Ignore direct virtual bases. 4026 if (DirectVirtualBases.count(RT)) 4027 continue; 4028 4029 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 4030 // If our base class is invalid, we probably can't get its dtor anyway. 4031 if (BaseClassDecl->isInvalidDecl()) 4032 continue; 4033 if (BaseClassDecl->hasIrrelevantDestructor()) 4034 continue; 4035 4036 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 4037 assert(Dtor && "No dtor found for BaseClassDecl!"); 4038 if (CheckDestructorAccess( 4039 ClassDecl->getLocation(), Dtor, 4040 PDiag(diag::err_access_dtor_vbase) 4041 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 4042 Context.getTypeDeclType(ClassDecl)) == 4043 AR_accessible) { 4044 CheckDerivedToBaseConversion( 4045 Context.getTypeDeclType(ClassDecl), VBase.getType(), 4046 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 4047 SourceRange(), DeclarationName(), 0); 4048 } 4049 4050 MarkFunctionReferenced(Location, Dtor); 4051 DiagnoseUseOfDecl(Dtor, Location); 4052 } 4053 } 4054 4055 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 4056 if (!CDtorDecl) 4057 return; 4058 4059 if (CXXConstructorDecl *Constructor 4060 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 4061 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 4062 DiagnoseUninitializedFields(*this, Constructor); 4063 } 4064 } 4065 4066 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4067 unsigned DiagID, AbstractDiagSelID SelID) { 4068 class NonAbstractTypeDiagnoser : public TypeDiagnoser { 4069 unsigned DiagID; 4070 AbstractDiagSelID SelID; 4071 4072 public: 4073 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID) 4074 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { } 4075 4076 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 4077 if (Suppressed) return; 4078 if (SelID == -1) 4079 S.Diag(Loc, DiagID) << T; 4080 else 4081 S.Diag(Loc, DiagID) << SelID << T; 4082 } 4083 } Diagnoser(DiagID, SelID); 4084 4085 return RequireNonAbstractType(Loc, T, Diagnoser); 4086 } 4087 4088 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 4089 TypeDiagnoser &Diagnoser) { 4090 if (!getLangOpts().CPlusPlus) 4091 return false; 4092 4093 if (const ArrayType *AT = Context.getAsArrayType(T)) 4094 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4095 4096 if (const PointerType *PT = T->getAs<PointerType>()) { 4097 // Find the innermost pointer type. 4098 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 4099 PT = T; 4100 4101 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 4102 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser); 4103 } 4104 4105 const RecordType *RT = T->getAs<RecordType>(); 4106 if (!RT) 4107 return false; 4108 4109 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4110 4111 // We can't answer whether something is abstract until it has a 4112 // definition. If it's currently being defined, we'll walk back 4113 // over all the declarations when we have a full definition. 4114 const CXXRecordDecl *Def = RD->getDefinition(); 4115 if (!Def || Def->isBeingDefined()) 4116 return false; 4117 4118 if (!RD->isAbstract()) 4119 return false; 4120 4121 Diagnoser.diagnose(*this, Loc, T); 4122 DiagnoseAbstractType(RD); 4123 4124 return true; 4125 } 4126 4127 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 4128 // Check if we've already emitted the list of pure virtual functions 4129 // for this class. 4130 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 4131 return; 4132 4133 // If the diagnostic is suppressed, don't emit the notes. We're only 4134 // going to emit them once, so try to attach them to a diagnostic we're 4135 // actually going to show. 4136 if (Diags.isLastDiagnosticIgnored()) 4137 return; 4138 4139 CXXFinalOverriderMap FinalOverriders; 4140 RD->getFinalOverriders(FinalOverriders); 4141 4142 // Keep a set of seen pure methods so we won't diagnose the same method 4143 // more than once. 4144 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 4145 4146 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 4147 MEnd = FinalOverriders.end(); 4148 M != MEnd; 4149 ++M) { 4150 for (OverridingMethods::iterator SO = M->second.begin(), 4151 SOEnd = M->second.end(); 4152 SO != SOEnd; ++SO) { 4153 // C++ [class.abstract]p4: 4154 // A class is abstract if it contains or inherits at least one 4155 // pure virtual function for which the final overrider is pure 4156 // virtual. 4157 4158 // 4159 if (SO->second.size() != 1) 4160 continue; 4161 4162 if (!SO->second.front().Method->isPure()) 4163 continue; 4164 4165 if (!SeenPureMethods.insert(SO->second.front().Method)) 4166 continue; 4167 4168 Diag(SO->second.front().Method->getLocation(), 4169 diag::note_pure_virtual_function) 4170 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 4171 } 4172 } 4173 4174 if (!PureVirtualClassDiagSet) 4175 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 4176 PureVirtualClassDiagSet->insert(RD); 4177 } 4178 4179 namespace { 4180 struct AbstractUsageInfo { 4181 Sema &S; 4182 CXXRecordDecl *Record; 4183 CanQualType AbstractType; 4184 bool Invalid; 4185 4186 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 4187 : S(S), Record(Record), 4188 AbstractType(S.Context.getCanonicalType( 4189 S.Context.getTypeDeclType(Record))), 4190 Invalid(false) {} 4191 4192 void DiagnoseAbstractType() { 4193 if (Invalid) return; 4194 S.DiagnoseAbstractType(Record); 4195 Invalid = true; 4196 } 4197 4198 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 4199 }; 4200 4201 struct CheckAbstractUsage { 4202 AbstractUsageInfo &Info; 4203 const NamedDecl *Ctx; 4204 4205 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 4206 : Info(Info), Ctx(Ctx) {} 4207 4208 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4209 switch (TL.getTypeLocClass()) { 4210 #define ABSTRACT_TYPELOC(CLASS, PARENT) 4211 #define TYPELOC(CLASS, PARENT) \ 4212 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 4213 #include "clang/AST/TypeLocNodes.def" 4214 } 4215 } 4216 4217 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4218 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 4219 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 4220 if (!TL.getParam(I)) 4221 continue; 4222 4223 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 4224 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 4225 } 4226 } 4227 4228 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4229 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 4230 } 4231 4232 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 4233 // Visit the type parameters from a permissive context. 4234 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 4235 TemplateArgumentLoc TAL = TL.getArgLoc(I); 4236 if (TAL.getArgument().getKind() == TemplateArgument::Type) 4237 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 4238 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 4239 // TODO: other template argument types? 4240 } 4241 } 4242 4243 // Visit pointee types from a permissive context. 4244 #define CheckPolymorphic(Type) \ 4245 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 4246 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 4247 } 4248 CheckPolymorphic(PointerTypeLoc) 4249 CheckPolymorphic(ReferenceTypeLoc) 4250 CheckPolymorphic(MemberPointerTypeLoc) 4251 CheckPolymorphic(BlockPointerTypeLoc) 4252 CheckPolymorphic(AtomicTypeLoc) 4253 4254 /// Handle all the types we haven't given a more specific 4255 /// implementation for above. 4256 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 4257 // Every other kind of type that we haven't called out already 4258 // that has an inner type is either (1) sugar or (2) contains that 4259 // inner type in some way as a subobject. 4260 if (TypeLoc Next = TL.getNextTypeLoc()) 4261 return Visit(Next, Sel); 4262 4263 // If there's no inner type and we're in a permissive context, 4264 // don't diagnose. 4265 if (Sel == Sema::AbstractNone) return; 4266 4267 // Check whether the type matches the abstract type. 4268 QualType T = TL.getType(); 4269 if (T->isArrayType()) { 4270 Sel = Sema::AbstractArrayType; 4271 T = Info.S.Context.getBaseElementType(T); 4272 } 4273 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 4274 if (CT != Info.AbstractType) return; 4275 4276 // It matched; do some magic. 4277 if (Sel == Sema::AbstractArrayType) { 4278 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 4279 << T << TL.getSourceRange(); 4280 } else { 4281 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 4282 << Sel << T << TL.getSourceRange(); 4283 } 4284 Info.DiagnoseAbstractType(); 4285 } 4286 }; 4287 4288 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 4289 Sema::AbstractDiagSelID Sel) { 4290 CheckAbstractUsage(*this, D).Visit(TL, Sel); 4291 } 4292 4293 } 4294 4295 /// Check for invalid uses of an abstract type in a method declaration. 4296 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4297 CXXMethodDecl *MD) { 4298 // No need to do the check on definitions, which require that 4299 // the return/param types be complete. 4300 if (MD->doesThisDeclarationHaveABody()) 4301 return; 4302 4303 // For safety's sake, just ignore it if we don't have type source 4304 // information. This should never happen for non-implicit methods, 4305 // but... 4306 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 4307 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 4308 } 4309 4310 /// Check for invalid uses of an abstract type within a class definition. 4311 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 4312 CXXRecordDecl *RD) { 4313 for (auto *D : RD->decls()) { 4314 if (D->isImplicit()) continue; 4315 4316 // Methods and method templates. 4317 if (isa<CXXMethodDecl>(D)) { 4318 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 4319 } else if (isa<FunctionTemplateDecl>(D)) { 4320 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 4321 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 4322 4323 // Fields and static variables. 4324 } else if (isa<FieldDecl>(D)) { 4325 FieldDecl *FD = cast<FieldDecl>(D); 4326 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 4327 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 4328 } else if (isa<VarDecl>(D)) { 4329 VarDecl *VD = cast<VarDecl>(D); 4330 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 4331 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 4332 4333 // Nested classes and class templates. 4334 } else if (isa<CXXRecordDecl>(D)) { 4335 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 4336 } else if (isa<ClassTemplateDecl>(D)) { 4337 CheckAbstractClassUsage(Info, 4338 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 4339 } 4340 } 4341 } 4342 4343 /// \brief Perform semantic checks on a class definition that has been 4344 /// completing, introducing implicitly-declared members, checking for 4345 /// abstract types, etc. 4346 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 4347 if (!Record) 4348 return; 4349 4350 if (Record->isAbstract() && !Record->isInvalidDecl()) { 4351 AbstractUsageInfo Info(*this, Record); 4352 CheckAbstractClassUsage(Info, Record); 4353 } 4354 4355 // If this is not an aggregate type and has no user-declared constructor, 4356 // complain about any non-static data members of reference or const scalar 4357 // type, since they will never get initializers. 4358 if (!Record->isInvalidDecl() && !Record->isDependentType() && 4359 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 4360 !Record->isLambda()) { 4361 bool Complained = false; 4362 for (const auto *F : Record->fields()) { 4363 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 4364 continue; 4365 4366 if (F->getType()->isReferenceType() || 4367 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 4368 if (!Complained) { 4369 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 4370 << Record->getTagKind() << Record; 4371 Complained = true; 4372 } 4373 4374 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 4375 << F->getType()->isReferenceType() 4376 << F->getDeclName(); 4377 } 4378 } 4379 } 4380 4381 if (Record->isDynamicClass() && !Record->isDependentType()) 4382 DynamicClasses.push_back(Record); 4383 4384 if (Record->getIdentifier()) { 4385 // C++ [class.mem]p13: 4386 // If T is the name of a class, then each of the following shall have a 4387 // name different from T: 4388 // - every member of every anonymous union that is a member of class T. 4389 // 4390 // C++ [class.mem]p14: 4391 // In addition, if class T has a user-declared constructor (12.1), every 4392 // non-static data member of class T shall have a name different from T. 4393 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 4394 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 4395 ++I) { 4396 NamedDecl *D = *I; 4397 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 4398 isa<IndirectFieldDecl>(D)) { 4399 Diag(D->getLocation(), diag::err_member_name_of_class) 4400 << D->getDeclName(); 4401 break; 4402 } 4403 } 4404 } 4405 4406 // Warn if the class has virtual methods but non-virtual public destructor. 4407 if (Record->isPolymorphic() && !Record->isDependentType()) { 4408 CXXDestructorDecl *dtor = Record->getDestructor(); 4409 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 4410 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 4411 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 4412 } 4413 4414 if (Record->isAbstract()) { 4415 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 4416 Diag(Record->getLocation(), diag::warn_abstract_final_class) 4417 << FA->isSpelledAsSealed(); 4418 DiagnoseAbstractType(Record); 4419 } 4420 } 4421 4422 if (!Record->isDependentType()) { 4423 for (auto *M : Record->methods()) { 4424 // See if a method overloads virtual methods in a base 4425 // class without overriding any. 4426 if (!M->isStatic()) 4427 DiagnoseHiddenVirtualMethods(M); 4428 4429 // Check whether the explicitly-defaulted special members are valid. 4430 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 4431 CheckExplicitlyDefaultedSpecialMember(M); 4432 4433 // For an explicitly defaulted or deleted special member, we defer 4434 // determining triviality until the class is complete. That time is now! 4435 if (!M->isImplicit() && !M->isUserProvided()) { 4436 CXXSpecialMember CSM = getSpecialMember(M); 4437 if (CSM != CXXInvalid) { 4438 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 4439 4440 // Inform the class that we've finished declaring this member. 4441 Record->finishedDefaultedOrDeletedMember(M); 4442 } 4443 } 4444 } 4445 } 4446 4447 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member 4448 // function that is not a constructor declares that member function to be 4449 // const. [...] The class of which that function is a member shall be 4450 // a literal type. 4451 // 4452 // If the class has virtual bases, any constexpr members will already have 4453 // been diagnosed by the checks performed on the member declaration, so 4454 // suppress this (less useful) diagnostic. 4455 // 4456 // We delay this until we know whether an explicitly-defaulted (or deleted) 4457 // destructor for the class is trivial. 4458 if (LangOpts.CPlusPlus11 && !Record->isDependentType() && 4459 !Record->isLiteral() && !Record->getNumVBases()) { 4460 for (const auto *M : Record->methods()) { 4461 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) { 4462 switch (Record->getTemplateSpecializationKind()) { 4463 case TSK_ImplicitInstantiation: 4464 case TSK_ExplicitInstantiationDeclaration: 4465 case TSK_ExplicitInstantiationDefinition: 4466 // If a template instantiates to a non-literal type, but its members 4467 // instantiate to constexpr functions, the template is technically 4468 // ill-formed, but we allow it for sanity. 4469 continue; 4470 4471 case TSK_Undeclared: 4472 case TSK_ExplicitSpecialization: 4473 RequireLiteralType(M->getLocation(), Context.getRecordType(Record), 4474 diag::err_constexpr_method_non_literal); 4475 break; 4476 } 4477 4478 // Only produce one error per class. 4479 break; 4480 } 4481 } 4482 } 4483 4484 // ms_struct is a request to use the same ABI rules as MSVC. Check 4485 // whether this class uses any C++ features that are implemented 4486 // completely differently in MSVC, and if so, emit a diagnostic. 4487 // That diagnostic defaults to an error, but we allow projects to 4488 // map it down to a warning (or ignore it). It's a fairly common 4489 // practice among users of the ms_struct pragma to mass-annotate 4490 // headers, sweeping up a bunch of types that the project doesn't 4491 // really rely on MSVC-compatible layout for. We must therefore 4492 // support "ms_struct except for C++ stuff" as a secondary ABI. 4493 if (Record->isMsStruct(Context) && 4494 (Record->isPolymorphic() || Record->getNumBases())) { 4495 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 4496 } 4497 4498 // Declare inheriting constructors. We do this eagerly here because: 4499 // - The standard requires an eager diagnostic for conflicting inheriting 4500 // constructors from different classes. 4501 // - The lazy declaration of the other implicit constructors is so as to not 4502 // waste space and performance on classes that are not meant to be 4503 // instantiated (e.g. meta-functions). This doesn't apply to classes that 4504 // have inheriting constructors. 4505 DeclareInheritingConstructors(Record); 4506 } 4507 4508 /// Look up the special member function that would be called by a special 4509 /// member function for a subobject of class type. 4510 /// 4511 /// \param Class The class type of the subobject. 4512 /// \param CSM The kind of special member function. 4513 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 4514 /// \param ConstRHS True if this is a copy operation with a const object 4515 /// on its RHS, that is, if the argument to the outer special member 4516 /// function is 'const' and this is not a field marked 'mutable'. 4517 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember( 4518 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 4519 unsigned FieldQuals, bool ConstRHS) { 4520 unsigned LHSQuals = 0; 4521 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 4522 LHSQuals = FieldQuals; 4523 4524 unsigned RHSQuals = FieldQuals; 4525 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 4526 RHSQuals = 0; 4527 else if (ConstRHS) 4528 RHSQuals |= Qualifiers::Const; 4529 4530 return S.LookupSpecialMember(Class, CSM, 4531 RHSQuals & Qualifiers::Const, 4532 RHSQuals & Qualifiers::Volatile, 4533 false, 4534 LHSQuals & Qualifiers::Const, 4535 LHSQuals & Qualifiers::Volatile); 4536 } 4537 4538 /// Is the special member function which would be selected to perform the 4539 /// specified operation on the specified class type a constexpr constructor? 4540 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4541 Sema::CXXSpecialMember CSM, 4542 unsigned Quals, bool ConstRHS) { 4543 Sema::SpecialMemberOverloadResult *SMOR = 4544 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 4545 if (!SMOR || !SMOR->getMethod()) 4546 // A constructor we wouldn't select can't be "involved in initializing" 4547 // anything. 4548 return true; 4549 return SMOR->getMethod()->isConstexpr(); 4550 } 4551 4552 /// Determine whether the specified special member function would be constexpr 4553 /// if it were implicitly defined. 4554 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 4555 Sema::CXXSpecialMember CSM, 4556 bool ConstArg) { 4557 if (!S.getLangOpts().CPlusPlus11) 4558 return false; 4559 4560 // C++11 [dcl.constexpr]p4: 4561 // In the definition of a constexpr constructor [...] 4562 bool Ctor = true; 4563 switch (CSM) { 4564 case Sema::CXXDefaultConstructor: 4565 // Since default constructor lookup is essentially trivial (and cannot 4566 // involve, for instance, template instantiation), we compute whether a 4567 // defaulted default constructor is constexpr directly within CXXRecordDecl. 4568 // 4569 // This is important for performance; we need to know whether the default 4570 // constructor is constexpr to determine whether the type is a literal type. 4571 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 4572 4573 case Sema::CXXCopyConstructor: 4574 case Sema::CXXMoveConstructor: 4575 // For copy or move constructors, we need to perform overload resolution. 4576 break; 4577 4578 case Sema::CXXCopyAssignment: 4579 case Sema::CXXMoveAssignment: 4580 if (!S.getLangOpts().CPlusPlus1y) 4581 return false; 4582 // In C++1y, we need to perform overload resolution. 4583 Ctor = false; 4584 break; 4585 4586 case Sema::CXXDestructor: 4587 case Sema::CXXInvalid: 4588 return false; 4589 } 4590 4591 // -- if the class is a non-empty union, or for each non-empty anonymous 4592 // union member of a non-union class, exactly one non-static data member 4593 // shall be initialized; [DR1359] 4594 // 4595 // If we squint, this is guaranteed, since exactly one non-static data member 4596 // will be initialized (if the constructor isn't deleted), we just don't know 4597 // which one. 4598 if (Ctor && ClassDecl->isUnion()) 4599 return true; 4600 4601 // -- the class shall not have any virtual base classes; 4602 if (Ctor && ClassDecl->getNumVBases()) 4603 return false; 4604 4605 // C++1y [class.copy]p26: 4606 // -- [the class] is a literal type, and 4607 if (!Ctor && !ClassDecl->isLiteral()) 4608 return false; 4609 4610 // -- every constructor involved in initializing [...] base class 4611 // sub-objects shall be a constexpr constructor; 4612 // -- the assignment operator selected to copy/move each direct base 4613 // class is a constexpr function, and 4614 for (const auto &B : ClassDecl->bases()) { 4615 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 4616 if (!BaseType) continue; 4617 4618 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4619 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg)) 4620 return false; 4621 } 4622 4623 // -- every constructor involved in initializing non-static data members 4624 // [...] shall be a constexpr constructor; 4625 // -- every non-static data member and base class sub-object shall be 4626 // initialized 4627 // -- for each non-static data member of X that is of class type (or array 4628 // thereof), the assignment operator selected to copy/move that member is 4629 // a constexpr function 4630 for (const auto *F : ClassDecl->fields()) { 4631 if (F->isInvalidDecl()) 4632 continue; 4633 QualType BaseType = S.Context.getBaseElementType(F->getType()); 4634 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 4635 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4636 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 4637 BaseType.getCVRQualifiers(), 4638 ConstArg && !F->isMutable())) 4639 return false; 4640 } 4641 } 4642 4643 // All OK, it's constexpr! 4644 return true; 4645 } 4646 4647 static Sema::ImplicitExceptionSpecification 4648 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 4649 switch (S.getSpecialMember(MD)) { 4650 case Sema::CXXDefaultConstructor: 4651 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD); 4652 case Sema::CXXCopyConstructor: 4653 return S.ComputeDefaultedCopyCtorExceptionSpec(MD); 4654 case Sema::CXXCopyAssignment: 4655 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD); 4656 case Sema::CXXMoveConstructor: 4657 return S.ComputeDefaultedMoveCtorExceptionSpec(MD); 4658 case Sema::CXXMoveAssignment: 4659 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD); 4660 case Sema::CXXDestructor: 4661 return S.ComputeDefaultedDtorExceptionSpec(MD); 4662 case Sema::CXXInvalid: 4663 break; 4664 } 4665 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() && 4666 "only special members have implicit exception specs"); 4667 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD)); 4668 } 4669 4670 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 4671 CXXMethodDecl *MD) { 4672 FunctionProtoType::ExtProtoInfo EPI; 4673 4674 // Build an exception specification pointing back at this member. 4675 EPI.ExceptionSpecType = EST_Unevaluated; 4676 EPI.ExceptionSpecDecl = MD; 4677 4678 // Set the calling convention to the default for C++ instance methods. 4679 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 4680 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4681 /*IsCXXMethod=*/true)); 4682 return EPI; 4683 } 4684 4685 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 4686 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 4687 if (FPT->getExceptionSpecType() != EST_Unevaluated) 4688 return; 4689 4690 // Evaluate the exception specification. 4691 ImplicitExceptionSpecification ExceptSpec = 4692 computeImplicitExceptionSpec(*this, Loc, MD); 4693 4694 FunctionProtoType::ExtProtoInfo EPI; 4695 ExceptSpec.getEPI(EPI); 4696 4697 // Update the type of the special member to use it. 4698 UpdateExceptionSpec(MD, EPI); 4699 4700 // A user-provided destructor can be defined outside the class. When that 4701 // happens, be sure to update the exception specification on both 4702 // declarations. 4703 const FunctionProtoType *CanonicalFPT = 4704 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 4705 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 4706 UpdateExceptionSpec(MD->getCanonicalDecl(), EPI); 4707 } 4708 4709 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 4710 CXXRecordDecl *RD = MD->getParent(); 4711 CXXSpecialMember CSM = getSpecialMember(MD); 4712 4713 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 4714 "not an explicitly-defaulted special member"); 4715 4716 // Whether this was the first-declared instance of the constructor. 4717 // This affects whether we implicitly add an exception spec and constexpr. 4718 bool First = MD == MD->getCanonicalDecl(); 4719 4720 bool HadError = false; 4721 4722 // C++11 [dcl.fct.def.default]p1: 4723 // A function that is explicitly defaulted shall 4724 // -- be a special member function (checked elsewhere), 4725 // -- have the same type (except for ref-qualifiers, and except that a 4726 // copy operation can take a non-const reference) as an implicit 4727 // declaration, and 4728 // -- not have default arguments. 4729 unsigned ExpectedParams = 1; 4730 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 4731 ExpectedParams = 0; 4732 if (MD->getNumParams() != ExpectedParams) { 4733 // This also checks for default arguments: a copy or move constructor with a 4734 // default argument is classified as a default constructor, and assignment 4735 // operations and destructors can't have default arguments. 4736 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 4737 << CSM << MD->getSourceRange(); 4738 HadError = true; 4739 } else if (MD->isVariadic()) { 4740 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 4741 << CSM << MD->getSourceRange(); 4742 HadError = true; 4743 } 4744 4745 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 4746 4747 bool CanHaveConstParam = false; 4748 if (CSM == CXXCopyConstructor) 4749 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 4750 else if (CSM == CXXCopyAssignment) 4751 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 4752 4753 QualType ReturnType = Context.VoidTy; 4754 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 4755 // Check for return type matching. 4756 ReturnType = Type->getReturnType(); 4757 QualType ExpectedReturnType = 4758 Context.getLValueReferenceType(Context.getTypeDeclType(RD)); 4759 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 4760 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 4761 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 4762 HadError = true; 4763 } 4764 4765 // A defaulted special member cannot have cv-qualifiers. 4766 if (Type->getTypeQuals()) { 4767 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 4768 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y; 4769 HadError = true; 4770 } 4771 } 4772 4773 // Check for parameter type matching. 4774 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 4775 bool HasConstParam = false; 4776 if (ExpectedParams && ArgType->isReferenceType()) { 4777 // Argument must be reference to possibly-const T. 4778 QualType ReferentType = ArgType->getPointeeType(); 4779 HasConstParam = ReferentType.isConstQualified(); 4780 4781 if (ReferentType.isVolatileQualified()) { 4782 Diag(MD->getLocation(), 4783 diag::err_defaulted_special_member_volatile_param) << CSM; 4784 HadError = true; 4785 } 4786 4787 if (HasConstParam && !CanHaveConstParam) { 4788 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 4789 Diag(MD->getLocation(), 4790 diag::err_defaulted_special_member_copy_const_param) 4791 << (CSM == CXXCopyAssignment); 4792 // FIXME: Explain why this special member can't be const. 4793 } else { 4794 Diag(MD->getLocation(), 4795 diag::err_defaulted_special_member_move_const_param) 4796 << (CSM == CXXMoveAssignment); 4797 } 4798 HadError = true; 4799 } 4800 } else if (ExpectedParams) { 4801 // A copy assignment operator can take its argument by value, but a 4802 // defaulted one cannot. 4803 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 4804 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 4805 HadError = true; 4806 } 4807 4808 // C++11 [dcl.fct.def.default]p2: 4809 // An explicitly-defaulted function may be declared constexpr only if it 4810 // would have been implicitly declared as constexpr, 4811 // Do not apply this rule to members of class templates, since core issue 1358 4812 // makes such functions always instantiate to constexpr functions. For 4813 // functions which cannot be constexpr (for non-constructors in C++11 and for 4814 // destructors in C++1y), this is checked elsewhere. 4815 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 4816 HasConstParam); 4817 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD) 4818 : isa<CXXConstructorDecl>(MD)) && 4819 MD->isConstexpr() && !Constexpr && 4820 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 4821 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM; 4822 // FIXME: Explain why the special member can't be constexpr. 4823 HadError = true; 4824 } 4825 4826 // and may have an explicit exception-specification only if it is compatible 4827 // with the exception-specification on the implicit declaration. 4828 if (Type->hasExceptionSpec()) { 4829 // Delay the check if this is the first declaration of the special member, 4830 // since we may not have parsed some necessary in-class initializers yet. 4831 if (First) { 4832 // If the exception specification needs to be instantiated, do so now, 4833 // before we clobber it with an EST_Unevaluated specification below. 4834 if (Type->getExceptionSpecType() == EST_Uninstantiated) { 4835 InstantiateExceptionSpec(MD->getLocStart(), MD); 4836 Type = MD->getType()->getAs<FunctionProtoType>(); 4837 } 4838 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type)); 4839 } else 4840 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type); 4841 } 4842 4843 // If a function is explicitly defaulted on its first declaration, 4844 if (First) { 4845 // -- it is implicitly considered to be constexpr if the implicit 4846 // definition would be, 4847 MD->setConstexpr(Constexpr); 4848 4849 // -- it is implicitly considered to have the same exception-specification 4850 // as if it had been implicitly declared, 4851 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 4852 EPI.ExceptionSpecType = EST_Unevaluated; 4853 EPI.ExceptionSpecDecl = MD; 4854 MD->setType(Context.getFunctionType(ReturnType, 4855 ArrayRef<QualType>(&ArgType, 4856 ExpectedParams), 4857 EPI)); 4858 } 4859 4860 if (ShouldDeleteSpecialMember(MD, CSM)) { 4861 if (First) { 4862 SetDeclDeleted(MD, MD->getLocation()); 4863 } else { 4864 // C++11 [dcl.fct.def.default]p4: 4865 // [For a] user-provided explicitly-defaulted function [...] if such a 4866 // function is implicitly defined as deleted, the program is ill-formed. 4867 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 4868 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true); 4869 HadError = true; 4870 } 4871 } 4872 4873 if (HadError) 4874 MD->setInvalidDecl(); 4875 } 4876 4877 /// Check whether the exception specification provided for an 4878 /// explicitly-defaulted special member matches the exception specification 4879 /// that would have been generated for an implicit special member, per 4880 /// C++11 [dcl.fct.def.default]p2. 4881 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec( 4882 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) { 4883 // Compute the implicit exception specification. 4884 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false, 4885 /*IsCXXMethod=*/true); 4886 FunctionProtoType::ExtProtoInfo EPI(CC); 4887 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI); 4888 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>( 4889 Context.getFunctionType(Context.VoidTy, None, EPI)); 4890 4891 // Ensure that it matches. 4892 CheckEquivalentExceptionSpec( 4893 PDiag(diag::err_incorrect_defaulted_exception_spec) 4894 << getSpecialMember(MD), PDiag(), 4895 ImplicitType, SourceLocation(), 4896 SpecifiedType, MD->getLocation()); 4897 } 4898 4899 void Sema::CheckDelayedMemberExceptionSpecs() { 4900 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>, 4901 2> Checks; 4902 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs; 4903 4904 std::swap(Checks, DelayedDestructorExceptionSpecChecks); 4905 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs); 4906 4907 // Perform any deferred checking of exception specifications for virtual 4908 // destructors. 4909 for (unsigned i = 0, e = Checks.size(); i != e; ++i) { 4910 const CXXDestructorDecl *Dtor = Checks[i].first; 4911 assert(!Dtor->getParent()->isDependentType() && 4912 "Should not ever add destructors of templates into the list."); 4913 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second); 4914 } 4915 4916 // Check that any explicitly-defaulted methods have exception specifications 4917 // compatible with their implicit exception specifications. 4918 for (unsigned I = 0, N = Specs.size(); I != N; ++I) 4919 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first, 4920 Specs[I].second); 4921 } 4922 4923 namespace { 4924 struct SpecialMemberDeletionInfo { 4925 Sema &S; 4926 CXXMethodDecl *MD; 4927 Sema::CXXSpecialMember CSM; 4928 bool Diagnose; 4929 4930 // Properties of the special member, computed for convenience. 4931 bool IsConstructor, IsAssignment, IsMove, ConstArg; 4932 SourceLocation Loc; 4933 4934 bool AllFieldsAreConst; 4935 4936 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 4937 Sema::CXXSpecialMember CSM, bool Diagnose) 4938 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose), 4939 IsConstructor(false), IsAssignment(false), IsMove(false), 4940 ConstArg(false), Loc(MD->getLocation()), 4941 AllFieldsAreConst(true) { 4942 switch (CSM) { 4943 case Sema::CXXDefaultConstructor: 4944 case Sema::CXXCopyConstructor: 4945 IsConstructor = true; 4946 break; 4947 case Sema::CXXMoveConstructor: 4948 IsConstructor = true; 4949 IsMove = true; 4950 break; 4951 case Sema::CXXCopyAssignment: 4952 IsAssignment = true; 4953 break; 4954 case Sema::CXXMoveAssignment: 4955 IsAssignment = true; 4956 IsMove = true; 4957 break; 4958 case Sema::CXXDestructor: 4959 break; 4960 case Sema::CXXInvalid: 4961 llvm_unreachable("invalid special member kind"); 4962 } 4963 4964 if (MD->getNumParams()) { 4965 if (const ReferenceType *RT = 4966 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 4967 ConstArg = RT->getPointeeType().isConstQualified(); 4968 } 4969 } 4970 4971 bool inUnion() const { return MD->getParent()->isUnion(); } 4972 4973 /// Look up the corresponding special member in the given class. 4974 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class, 4975 unsigned Quals, bool IsMutable) { 4976 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 4977 ConstArg && !IsMutable); 4978 } 4979 4980 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 4981 4982 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 4983 bool shouldDeleteForField(FieldDecl *FD); 4984 bool shouldDeleteForAllConstMembers(); 4985 4986 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 4987 unsigned Quals); 4988 bool shouldDeleteForSubobjectCall(Subobject Subobj, 4989 Sema::SpecialMemberOverloadResult *SMOR, 4990 bool IsDtorCallInCtor); 4991 4992 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 4993 }; 4994 } 4995 4996 /// Is the given special member inaccessible when used on the given 4997 /// sub-object. 4998 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 4999 CXXMethodDecl *target) { 5000 /// If we're operating on a base class, the object type is the 5001 /// type of this special member. 5002 QualType objectTy; 5003 AccessSpecifier access = target->getAccess(); 5004 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 5005 objectTy = S.Context.getTypeDeclType(MD->getParent()); 5006 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 5007 5008 // If we're operating on a field, the object type is the type of the field. 5009 } else { 5010 objectTy = S.Context.getTypeDeclType(target->getParent()); 5011 } 5012 5013 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 5014 } 5015 5016 /// Check whether we should delete a special member due to the implicit 5017 /// definition containing a call to a special member of a subobject. 5018 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 5019 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR, 5020 bool IsDtorCallInCtor) { 5021 CXXMethodDecl *Decl = SMOR->getMethod(); 5022 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5023 5024 int DiagKind = -1; 5025 5026 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 5027 DiagKind = !Decl ? 0 : 1; 5028 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5029 DiagKind = 2; 5030 else if (!isAccessible(Subobj, Decl)) 5031 DiagKind = 3; 5032 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 5033 !Decl->isTrivial()) { 5034 // A member of a union must have a trivial corresponding special member. 5035 // As a weird special case, a destructor call from a union's constructor 5036 // must be accessible and non-deleted, but need not be trivial. Such a 5037 // destructor is never actually called, but is semantically checked as 5038 // if it were. 5039 DiagKind = 4; 5040 } 5041 5042 if (DiagKind == -1) 5043 return false; 5044 5045 if (Diagnose) { 5046 if (Field) { 5047 S.Diag(Field->getLocation(), 5048 diag::note_deleted_special_member_class_subobject) 5049 << CSM << MD->getParent() << /*IsField*/true 5050 << Field << DiagKind << IsDtorCallInCtor; 5051 } else { 5052 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 5053 S.Diag(Base->getLocStart(), 5054 diag::note_deleted_special_member_class_subobject) 5055 << CSM << MD->getParent() << /*IsField*/false 5056 << Base->getType() << DiagKind << IsDtorCallInCtor; 5057 } 5058 5059 if (DiagKind == 1) 5060 S.NoteDeletedFunction(Decl); 5061 // FIXME: Explain inaccessibility if DiagKind == 3. 5062 } 5063 5064 return true; 5065 } 5066 5067 /// Check whether we should delete a special member function due to having a 5068 /// direct or virtual base class or non-static data member of class type M. 5069 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 5070 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 5071 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 5072 bool IsMutable = Field && Field->isMutable(); 5073 5074 // C++11 [class.ctor]p5: 5075 // -- any direct or virtual base class, or non-static data member with no 5076 // brace-or-equal-initializer, has class type M (or array thereof) and 5077 // either M has no default constructor or overload resolution as applied 5078 // to M's default constructor results in an ambiguity or in a function 5079 // that is deleted or inaccessible 5080 // C++11 [class.copy]p11, C++11 [class.copy]p23: 5081 // -- a direct or virtual base class B that cannot be copied/moved because 5082 // overload resolution, as applied to B's corresponding special member, 5083 // results in an ambiguity or a function that is deleted or inaccessible 5084 // from the defaulted special member 5085 // C++11 [class.dtor]p5: 5086 // -- any direct or virtual base class [...] has a type with a destructor 5087 // that is deleted or inaccessible 5088 if (!(CSM == Sema::CXXDefaultConstructor && 5089 Field && Field->hasInClassInitializer()) && 5090 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 5091 false)) 5092 return true; 5093 5094 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 5095 // -- any direct or virtual base class or non-static data member has a 5096 // type with a destructor that is deleted or inaccessible 5097 if (IsConstructor) { 5098 Sema::SpecialMemberOverloadResult *SMOR = 5099 S.LookupSpecialMember(Class, Sema::CXXDestructor, 5100 false, false, false, false, false); 5101 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 5102 return true; 5103 } 5104 5105 return false; 5106 } 5107 5108 /// Check whether we should delete a special member function due to the class 5109 /// having a particular direct or virtual base class. 5110 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 5111 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 5112 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 5113 } 5114 5115 /// Check whether we should delete a special member function due to the class 5116 /// having a particular non-static data member. 5117 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 5118 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 5119 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 5120 5121 if (CSM == Sema::CXXDefaultConstructor) { 5122 // For a default constructor, all references must be initialized in-class 5123 // and, if a union, it must have a non-const member. 5124 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 5125 if (Diagnose) 5126 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5127 << MD->getParent() << FD << FieldType << /*Reference*/0; 5128 return true; 5129 } 5130 // C++11 [class.ctor]p5: any non-variant non-static data member of 5131 // const-qualified type (or array thereof) with no 5132 // brace-or-equal-initializer does not have a user-provided default 5133 // constructor. 5134 if (!inUnion() && FieldType.isConstQualified() && 5135 !FD->hasInClassInitializer() && 5136 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 5137 if (Diagnose) 5138 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 5139 << MD->getParent() << FD << FD->getType() << /*Const*/1; 5140 return true; 5141 } 5142 5143 if (inUnion() && !FieldType.isConstQualified()) 5144 AllFieldsAreConst = false; 5145 } else if (CSM == Sema::CXXCopyConstructor) { 5146 // For a copy constructor, data members must not be of rvalue reference 5147 // type. 5148 if (FieldType->isRValueReferenceType()) { 5149 if (Diagnose) 5150 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 5151 << MD->getParent() << FD << FieldType; 5152 return true; 5153 } 5154 } else if (IsAssignment) { 5155 // For an assignment operator, data members must not be of reference type. 5156 if (FieldType->isReferenceType()) { 5157 if (Diagnose) 5158 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5159 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0; 5160 return true; 5161 } 5162 if (!FieldRecord && FieldType.isConstQualified()) { 5163 // C++11 [class.copy]p23: 5164 // -- a non-static data member of const non-class type (or array thereof) 5165 if (Diagnose) 5166 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 5167 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1; 5168 return true; 5169 } 5170 } 5171 5172 if (FieldRecord) { 5173 // Some additional restrictions exist on the variant members. 5174 if (!inUnion() && FieldRecord->isUnion() && 5175 FieldRecord->isAnonymousStructOrUnion()) { 5176 bool AllVariantFieldsAreConst = true; 5177 5178 // FIXME: Handle anonymous unions declared within anonymous unions. 5179 for (auto *UI : FieldRecord->fields()) { 5180 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 5181 5182 if (!UnionFieldType.isConstQualified()) 5183 AllVariantFieldsAreConst = false; 5184 5185 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 5186 if (UnionFieldRecord && 5187 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 5188 UnionFieldType.getCVRQualifiers())) 5189 return true; 5190 } 5191 5192 // At least one member in each anonymous union must be non-const 5193 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 5194 !FieldRecord->field_empty()) { 5195 if (Diagnose) 5196 S.Diag(FieldRecord->getLocation(), 5197 diag::note_deleted_default_ctor_all_const) 5198 << MD->getParent() << /*anonymous union*/1; 5199 return true; 5200 } 5201 5202 // Don't check the implicit member of the anonymous union type. 5203 // This is technically non-conformant, but sanity demands it. 5204 return false; 5205 } 5206 5207 if (shouldDeleteForClassSubobject(FieldRecord, FD, 5208 FieldType.getCVRQualifiers())) 5209 return true; 5210 } 5211 5212 return false; 5213 } 5214 5215 /// C++11 [class.ctor] p5: 5216 /// A defaulted default constructor for a class X is defined as deleted if 5217 /// X is a union and all of its variant members are of const-qualified type. 5218 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 5219 // This is a silly definition, because it gives an empty union a deleted 5220 // default constructor. Don't do that. 5221 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst && 5222 !MD->getParent()->field_empty()) { 5223 if (Diagnose) 5224 S.Diag(MD->getParent()->getLocation(), 5225 diag::note_deleted_default_ctor_all_const) 5226 << MD->getParent() << /*not anonymous union*/0; 5227 return true; 5228 } 5229 return false; 5230 } 5231 5232 /// Determine whether a defaulted special member function should be defined as 5233 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 5234 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 5235 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 5236 bool Diagnose) { 5237 if (MD->isInvalidDecl()) 5238 return false; 5239 CXXRecordDecl *RD = MD->getParent(); 5240 assert(!RD->isDependentType() && "do deletion after instantiation"); 5241 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 5242 return false; 5243 5244 // C++11 [expr.lambda.prim]p19: 5245 // The closure type associated with a lambda-expression has a 5246 // deleted (8.4.3) default constructor and a deleted copy 5247 // assignment operator. 5248 if (RD->isLambda() && 5249 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 5250 if (Diagnose) 5251 Diag(RD->getLocation(), diag::note_lambda_decl); 5252 return true; 5253 } 5254 5255 // For an anonymous struct or union, the copy and assignment special members 5256 // will never be used, so skip the check. For an anonymous union declared at 5257 // namespace scope, the constructor and destructor are used. 5258 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 5259 RD->isAnonymousStructOrUnion()) 5260 return false; 5261 5262 // C++11 [class.copy]p7, p18: 5263 // If the class definition declares a move constructor or move assignment 5264 // operator, an implicitly declared copy constructor or copy assignment 5265 // operator is defined as deleted. 5266 if (MD->isImplicit() && 5267 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 5268 CXXMethodDecl *UserDeclaredMove = 0; 5269 5270 // In Microsoft mode, a user-declared move only causes the deletion of the 5271 // corresponding copy operation, not both copy operations. 5272 if (RD->hasUserDeclaredMoveConstructor() && 5273 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) { 5274 if (!Diagnose) return true; 5275 5276 // Find any user-declared move constructor. 5277 for (auto *I : RD->ctors()) { 5278 if (I->isMoveConstructor()) { 5279 UserDeclaredMove = I; 5280 break; 5281 } 5282 } 5283 assert(UserDeclaredMove); 5284 } else if (RD->hasUserDeclaredMoveAssignment() && 5285 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) { 5286 if (!Diagnose) return true; 5287 5288 // Find any user-declared move assignment operator. 5289 for (auto *I : RD->methods()) { 5290 if (I->isMoveAssignmentOperator()) { 5291 UserDeclaredMove = I; 5292 break; 5293 } 5294 } 5295 assert(UserDeclaredMove); 5296 } 5297 5298 if (UserDeclaredMove) { 5299 Diag(UserDeclaredMove->getLocation(), 5300 diag::note_deleted_copy_user_declared_move) 5301 << (CSM == CXXCopyAssignment) << RD 5302 << UserDeclaredMove->isMoveAssignmentOperator(); 5303 return true; 5304 } 5305 } 5306 5307 // Do access control from the special member function 5308 ContextRAII MethodContext(*this, MD); 5309 5310 // C++11 [class.dtor]p5: 5311 // -- for a virtual destructor, lookup of the non-array deallocation function 5312 // results in an ambiguity or in a function that is deleted or inaccessible 5313 if (CSM == CXXDestructor && MD->isVirtual()) { 5314 FunctionDecl *OperatorDelete = 0; 5315 DeclarationName Name = 5316 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 5317 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 5318 OperatorDelete, false)) { 5319 if (Diagnose) 5320 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 5321 return true; 5322 } 5323 } 5324 5325 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose); 5326 5327 for (auto &BI : RD->bases()) 5328 if (!BI.isVirtual() && 5329 SMI.shouldDeleteForBase(&BI)) 5330 return true; 5331 5332 // Per DR1611, do not consider virtual bases of constructors of abstract 5333 // classes, since we are not going to construct them. 5334 if (!RD->isAbstract() || !SMI.IsConstructor) { 5335 for (auto &BI : RD->vbases()) 5336 if (SMI.shouldDeleteForBase(&BI)) 5337 return true; 5338 } 5339 5340 for (auto *FI : RD->fields()) 5341 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() && 5342 SMI.shouldDeleteForField(FI)) 5343 return true; 5344 5345 if (SMI.shouldDeleteForAllConstMembers()) 5346 return true; 5347 5348 return false; 5349 } 5350 5351 /// Perform lookup for a special member of the specified kind, and determine 5352 /// whether it is trivial. If the triviality can be determined without the 5353 /// lookup, skip it. This is intended for use when determining whether a 5354 /// special member of a containing object is trivial, and thus does not ever 5355 /// perform overload resolution for default constructors. 5356 /// 5357 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 5358 /// member that was most likely to be intended to be trivial, if any. 5359 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 5360 Sema::CXXSpecialMember CSM, unsigned Quals, 5361 bool ConstRHS, CXXMethodDecl **Selected) { 5362 if (Selected) 5363 *Selected = 0; 5364 5365 switch (CSM) { 5366 case Sema::CXXInvalid: 5367 llvm_unreachable("not a special member"); 5368 5369 case Sema::CXXDefaultConstructor: 5370 // C++11 [class.ctor]p5: 5371 // A default constructor is trivial if: 5372 // - all the [direct subobjects] have trivial default constructors 5373 // 5374 // Note, no overload resolution is performed in this case. 5375 if (RD->hasTrivialDefaultConstructor()) 5376 return true; 5377 5378 if (Selected) { 5379 // If there's a default constructor which could have been trivial, dig it 5380 // out. Otherwise, if there's any user-provided default constructor, point 5381 // to that as an example of why there's not a trivial one. 5382 CXXConstructorDecl *DefCtor = 0; 5383 if (RD->needsImplicitDefaultConstructor()) 5384 S.DeclareImplicitDefaultConstructor(RD); 5385 for (auto *CI : RD->ctors()) { 5386 if (!CI->isDefaultConstructor()) 5387 continue; 5388 DefCtor = CI; 5389 if (!DefCtor->isUserProvided()) 5390 break; 5391 } 5392 5393 *Selected = DefCtor; 5394 } 5395 5396 return false; 5397 5398 case Sema::CXXDestructor: 5399 // C++11 [class.dtor]p5: 5400 // A destructor is trivial if: 5401 // - all the direct [subobjects] have trivial destructors 5402 if (RD->hasTrivialDestructor()) 5403 return true; 5404 5405 if (Selected) { 5406 if (RD->needsImplicitDestructor()) 5407 S.DeclareImplicitDestructor(RD); 5408 *Selected = RD->getDestructor(); 5409 } 5410 5411 return false; 5412 5413 case Sema::CXXCopyConstructor: 5414 // C++11 [class.copy]p12: 5415 // A copy constructor is trivial if: 5416 // - the constructor selected to copy each direct [subobject] is trivial 5417 if (RD->hasTrivialCopyConstructor()) { 5418 if (Quals == Qualifiers::Const) 5419 // We must either select the trivial copy constructor or reach an 5420 // ambiguity; no need to actually perform overload resolution. 5421 return true; 5422 } else if (!Selected) { 5423 return false; 5424 } 5425 // In C++98, we are not supposed to perform overload resolution here, but we 5426 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 5427 // cases like B as having a non-trivial copy constructor: 5428 // struct A { template<typename T> A(T&); }; 5429 // struct B { mutable A a; }; 5430 goto NeedOverloadResolution; 5431 5432 case Sema::CXXCopyAssignment: 5433 // C++11 [class.copy]p25: 5434 // A copy assignment operator is trivial if: 5435 // - the assignment operator selected to copy each direct [subobject] is 5436 // trivial 5437 if (RD->hasTrivialCopyAssignment()) { 5438 if (Quals == Qualifiers::Const) 5439 return true; 5440 } else if (!Selected) { 5441 return false; 5442 } 5443 // In C++98, we are not supposed to perform overload resolution here, but we 5444 // treat that as a language defect. 5445 goto NeedOverloadResolution; 5446 5447 case Sema::CXXMoveConstructor: 5448 case Sema::CXXMoveAssignment: 5449 NeedOverloadResolution: 5450 Sema::SpecialMemberOverloadResult *SMOR = 5451 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 5452 5453 // The standard doesn't describe how to behave if the lookup is ambiguous. 5454 // We treat it as not making the member non-trivial, just like the standard 5455 // mandates for the default constructor. This should rarely matter, because 5456 // the member will also be deleted. 5457 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 5458 return true; 5459 5460 if (!SMOR->getMethod()) { 5461 assert(SMOR->getKind() == 5462 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 5463 return false; 5464 } 5465 5466 // We deliberately don't check if we found a deleted special member. We're 5467 // not supposed to! 5468 if (Selected) 5469 *Selected = SMOR->getMethod(); 5470 return SMOR->getMethod()->isTrivial(); 5471 } 5472 5473 llvm_unreachable("unknown special method kind"); 5474 } 5475 5476 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 5477 for (auto *CI : RD->ctors()) 5478 if (!CI->isImplicit()) 5479 return CI; 5480 5481 // Look for constructor templates. 5482 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 5483 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 5484 if (CXXConstructorDecl *CD = 5485 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 5486 return CD; 5487 } 5488 5489 return 0; 5490 } 5491 5492 /// The kind of subobject we are checking for triviality. The values of this 5493 /// enumeration are used in diagnostics. 5494 enum TrivialSubobjectKind { 5495 /// The subobject is a base class. 5496 TSK_BaseClass, 5497 /// The subobject is a non-static data member. 5498 TSK_Field, 5499 /// The object is actually the complete object. 5500 TSK_CompleteObject 5501 }; 5502 5503 /// Check whether the special member selected for a given type would be trivial. 5504 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 5505 QualType SubType, bool ConstRHS, 5506 Sema::CXXSpecialMember CSM, 5507 TrivialSubobjectKind Kind, 5508 bool Diagnose) { 5509 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 5510 if (!SubRD) 5511 return true; 5512 5513 CXXMethodDecl *Selected; 5514 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 5515 ConstRHS, Diagnose ? &Selected : 0)) 5516 return true; 5517 5518 if (Diagnose) { 5519 if (ConstRHS) 5520 SubType.addConst(); 5521 5522 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 5523 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 5524 << Kind << SubType.getUnqualifiedType(); 5525 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 5526 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 5527 } else if (!Selected) 5528 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 5529 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 5530 else if (Selected->isUserProvided()) { 5531 if (Kind == TSK_CompleteObject) 5532 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 5533 << Kind << SubType.getUnqualifiedType() << CSM; 5534 else { 5535 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 5536 << Kind << SubType.getUnqualifiedType() << CSM; 5537 S.Diag(Selected->getLocation(), diag::note_declared_at); 5538 } 5539 } else { 5540 if (Kind != TSK_CompleteObject) 5541 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 5542 << Kind << SubType.getUnqualifiedType() << CSM; 5543 5544 // Explain why the defaulted or deleted special member isn't trivial. 5545 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose); 5546 } 5547 } 5548 5549 return false; 5550 } 5551 5552 /// Check whether the members of a class type allow a special member to be 5553 /// trivial. 5554 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 5555 Sema::CXXSpecialMember CSM, 5556 bool ConstArg, bool Diagnose) { 5557 for (const auto *FI : RD->fields()) { 5558 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 5559 continue; 5560 5561 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 5562 5563 // Pretend anonymous struct or union members are members of this class. 5564 if (FI->isAnonymousStructOrUnion()) { 5565 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 5566 CSM, ConstArg, Diagnose)) 5567 return false; 5568 continue; 5569 } 5570 5571 // C++11 [class.ctor]p5: 5572 // A default constructor is trivial if [...] 5573 // -- no non-static data member of its class has a 5574 // brace-or-equal-initializer 5575 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 5576 if (Diagnose) 5577 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 5578 return false; 5579 } 5580 5581 // Objective C ARC 4.3.5: 5582 // [...] nontrivally ownership-qualified types are [...] not trivially 5583 // default constructible, copy constructible, move constructible, copy 5584 // assignable, move assignable, or destructible [...] 5585 if (S.getLangOpts().ObjCAutoRefCount && 5586 FieldType.hasNonTrivialObjCLifetime()) { 5587 if (Diagnose) 5588 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 5589 << RD << FieldType.getObjCLifetime(); 5590 return false; 5591 } 5592 5593 bool ConstRHS = ConstArg && !FI->isMutable(); 5594 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 5595 CSM, TSK_Field, Diagnose)) 5596 return false; 5597 } 5598 5599 return true; 5600 } 5601 5602 /// Diagnose why the specified class does not have a trivial special member of 5603 /// the given kind. 5604 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 5605 QualType Ty = Context.getRecordType(RD); 5606 5607 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 5608 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 5609 TSK_CompleteObject, /*Diagnose*/true); 5610 } 5611 5612 /// Determine whether a defaulted or deleted special member function is trivial, 5613 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 5614 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 5615 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 5616 bool Diagnose) { 5617 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 5618 5619 CXXRecordDecl *RD = MD->getParent(); 5620 5621 bool ConstArg = false; 5622 5623 // C++11 [class.copy]p12, p25: [DR1593] 5624 // A [special member] is trivial if [...] its parameter-type-list is 5625 // equivalent to the parameter-type-list of an implicit declaration [...] 5626 switch (CSM) { 5627 case CXXDefaultConstructor: 5628 case CXXDestructor: 5629 // Trivial default constructors and destructors cannot have parameters. 5630 break; 5631 5632 case CXXCopyConstructor: 5633 case CXXCopyAssignment: { 5634 // Trivial copy operations always have const, non-volatile parameter types. 5635 ConstArg = true; 5636 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5637 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 5638 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 5639 if (Diagnose) 5640 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5641 << Param0->getSourceRange() << Param0->getType() 5642 << Context.getLValueReferenceType( 5643 Context.getRecordType(RD).withConst()); 5644 return false; 5645 } 5646 break; 5647 } 5648 5649 case CXXMoveConstructor: 5650 case CXXMoveAssignment: { 5651 // Trivial move operations always have non-cv-qualified parameters. 5652 const ParmVarDecl *Param0 = MD->getParamDecl(0); 5653 const RValueReferenceType *RT = 5654 Param0->getType()->getAs<RValueReferenceType>(); 5655 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 5656 if (Diagnose) 5657 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 5658 << Param0->getSourceRange() << Param0->getType() 5659 << Context.getRValueReferenceType(Context.getRecordType(RD)); 5660 return false; 5661 } 5662 break; 5663 } 5664 5665 case CXXInvalid: 5666 llvm_unreachable("not a special member"); 5667 } 5668 5669 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 5670 if (Diagnose) 5671 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 5672 diag::note_nontrivial_default_arg) 5673 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 5674 return false; 5675 } 5676 if (MD->isVariadic()) { 5677 if (Diagnose) 5678 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 5679 return false; 5680 } 5681 5682 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5683 // A copy/move [constructor or assignment operator] is trivial if 5684 // -- the [member] selected to copy/move each direct base class subobject 5685 // is trivial 5686 // 5687 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5688 // A [default constructor or destructor] is trivial if 5689 // -- all the direct base classes have trivial [default constructors or 5690 // destructors] 5691 for (const auto &BI : RD->bases()) 5692 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(), 5693 ConstArg, CSM, TSK_BaseClass, Diagnose)) 5694 return false; 5695 5696 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 5697 // A copy/move [constructor or assignment operator] for a class X is 5698 // trivial if 5699 // -- for each non-static data member of X that is of class type (or array 5700 // thereof), the constructor selected to copy/move that member is 5701 // trivial 5702 // 5703 // C++11 [class.copy]p12, C++11 [class.copy]p25: 5704 // A [default constructor or destructor] is trivial if 5705 // -- for all of the non-static data members of its class that are of class 5706 // type (or array thereof), each such class has a trivial [default 5707 // constructor or destructor] 5708 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose)) 5709 return false; 5710 5711 // C++11 [class.dtor]p5: 5712 // A destructor is trivial if [...] 5713 // -- the destructor is not virtual 5714 if (CSM == CXXDestructor && MD->isVirtual()) { 5715 if (Diagnose) 5716 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 5717 return false; 5718 } 5719 5720 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 5721 // A [special member] for class X is trivial if [...] 5722 // -- class X has no virtual functions and no virtual base classes 5723 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 5724 if (!Diagnose) 5725 return false; 5726 5727 if (RD->getNumVBases()) { 5728 // Check for virtual bases. We already know that the corresponding 5729 // member in all bases is trivial, so vbases must all be direct. 5730 CXXBaseSpecifier &BS = *RD->vbases_begin(); 5731 assert(BS.isVirtual()); 5732 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1; 5733 return false; 5734 } 5735 5736 // Must have a virtual method. 5737 for (const auto *MI : RD->methods()) { 5738 if (MI->isVirtual()) { 5739 SourceLocation MLoc = MI->getLocStart(); 5740 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 5741 return false; 5742 } 5743 } 5744 5745 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 5746 } 5747 5748 // Looks like it's trivial! 5749 return true; 5750 } 5751 5752 /// \brief Data used with FindHiddenVirtualMethod 5753 namespace { 5754 struct FindHiddenVirtualMethodData { 5755 Sema *S; 5756 CXXMethodDecl *Method; 5757 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 5758 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5759 }; 5760 } 5761 5762 /// \brief Check whether any most overriden method from MD in Methods 5763 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD, 5764 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5765 if (MD->size_overridden_methods() == 0) 5766 return Methods.count(MD->getCanonicalDecl()); 5767 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5768 E = MD->end_overridden_methods(); 5769 I != E; ++I) 5770 if (CheckMostOverridenMethods(*I, Methods)) 5771 return true; 5772 return false; 5773 } 5774 5775 /// \brief Member lookup function that determines whether a given C++ 5776 /// method overloads virtual methods in a base class without overriding any, 5777 /// to be used with CXXRecordDecl::lookupInBases(). 5778 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 5779 CXXBasePath &Path, 5780 void *UserData) { 5781 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 5782 5783 FindHiddenVirtualMethodData &Data 5784 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 5785 5786 DeclarationName Name = Data.Method->getDeclName(); 5787 assert(Name.getNameKind() == DeclarationName::Identifier); 5788 5789 bool foundSameNameMethod = false; 5790 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 5791 for (Path.Decls = BaseRecord->lookup(Name); 5792 !Path.Decls.empty(); 5793 Path.Decls = Path.Decls.slice(1)) { 5794 NamedDecl *D = Path.Decls.front(); 5795 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 5796 MD = MD->getCanonicalDecl(); 5797 foundSameNameMethod = true; 5798 // Interested only in hidden virtual methods. 5799 if (!MD->isVirtual()) 5800 continue; 5801 // If the method we are checking overrides a method from its base 5802 // don't warn about the other overloaded methods. 5803 if (!Data.S->IsOverload(Data.Method, MD, false)) 5804 return true; 5805 // Collect the overload only if its hidden. 5806 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods)) 5807 overloadedMethods.push_back(MD); 5808 } 5809 } 5810 5811 if (foundSameNameMethod) 5812 Data.OverloadedMethods.append(overloadedMethods.begin(), 5813 overloadedMethods.end()); 5814 return foundSameNameMethod; 5815 } 5816 5817 /// \brief Add the most overriden methods from MD to Methods 5818 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 5819 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) { 5820 if (MD->size_overridden_methods() == 0) 5821 Methods.insert(MD->getCanonicalDecl()); 5822 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 5823 E = MD->end_overridden_methods(); 5824 I != E; ++I) 5825 AddMostOverridenMethods(*I, Methods); 5826 } 5827 5828 /// \brief Check if a method overloads virtual methods in a base class without 5829 /// overriding any. 5830 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 5831 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5832 if (!MD->getDeclName().isIdentifier()) 5833 return; 5834 5835 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 5836 /*bool RecordPaths=*/false, 5837 /*bool DetectVirtual=*/false); 5838 FindHiddenVirtualMethodData Data; 5839 Data.Method = MD; 5840 Data.S = this; 5841 5842 // Keep the base methods that were overriden or introduced in the subclass 5843 // by 'using' in a set. A base method not in this set is hidden. 5844 CXXRecordDecl *DC = MD->getParent(); 5845 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 5846 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 5847 NamedDecl *ND = *I; 5848 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 5849 ND = shad->getTargetDecl(); 5850 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 5851 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods); 5852 } 5853 5854 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths)) 5855 OverloadedMethods = Data.OverloadedMethods; 5856 } 5857 5858 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 5859 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 5860 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 5861 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 5862 PartialDiagnostic PD = PDiag( 5863 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 5864 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 5865 Diag(overloadedMD->getLocation(), PD); 5866 } 5867 } 5868 5869 /// \brief Diagnose methods which overload virtual methods in a base class 5870 /// without overriding any. 5871 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 5872 if (MD->isInvalidDecl()) 5873 return; 5874 5875 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 5876 MD->getLocation()) == DiagnosticsEngine::Ignored) 5877 return; 5878 5879 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 5880 FindHiddenVirtualMethods(MD, OverloadedMethods); 5881 if (!OverloadedMethods.empty()) { 5882 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 5883 << MD << (OverloadedMethods.size() > 1); 5884 5885 NoteHiddenVirtualMethods(MD, OverloadedMethods); 5886 } 5887 } 5888 5889 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 5890 Decl *TagDecl, 5891 SourceLocation LBrac, 5892 SourceLocation RBrac, 5893 AttributeList *AttrList) { 5894 if (!TagDecl) 5895 return; 5896 5897 AdjustDeclIfTemplate(TagDecl); 5898 5899 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5900 if (l->getKind() != AttributeList::AT_Visibility) 5901 continue; 5902 l->setInvalid(); 5903 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) << 5904 l->getName(); 5905 } 5906 5907 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 5908 // strict aliasing violation! 5909 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 5910 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 5911 5912 CheckCompletedCXXClass( 5913 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 5914 } 5915 5916 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 5917 /// special functions, such as the default constructor, copy 5918 /// constructor, or destructor, to the given C++ class (C++ 5919 /// [special]p1). This routine can only be executed just before the 5920 /// definition of the class is complete. 5921 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 5922 if (!ClassDecl->hasUserDeclaredConstructor()) 5923 ++ASTContext::NumImplicitDefaultConstructors; 5924 5925 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 5926 ++ASTContext::NumImplicitCopyConstructors; 5927 5928 // If the properties or semantics of the copy constructor couldn't be 5929 // determined while the class was being declared, force a declaration 5930 // of it now. 5931 if (ClassDecl->needsOverloadResolutionForCopyConstructor()) 5932 DeclareImplicitCopyConstructor(ClassDecl); 5933 } 5934 5935 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 5936 ++ASTContext::NumImplicitMoveConstructors; 5937 5938 if (ClassDecl->needsOverloadResolutionForMoveConstructor()) 5939 DeclareImplicitMoveConstructor(ClassDecl); 5940 } 5941 5942 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 5943 ++ASTContext::NumImplicitCopyAssignmentOperators; 5944 5945 // If we have a dynamic class, then the copy assignment operator may be 5946 // virtual, so we have to declare it immediately. This ensures that, e.g., 5947 // it shows up in the right place in the vtable and that we diagnose 5948 // problems with the implicit exception specification. 5949 if (ClassDecl->isDynamicClass() || 5950 ClassDecl->needsOverloadResolutionForCopyAssignment()) 5951 DeclareImplicitCopyAssignment(ClassDecl); 5952 } 5953 5954 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 5955 ++ASTContext::NumImplicitMoveAssignmentOperators; 5956 5957 // Likewise for the move assignment operator. 5958 if (ClassDecl->isDynamicClass() || 5959 ClassDecl->needsOverloadResolutionForMoveAssignment()) 5960 DeclareImplicitMoveAssignment(ClassDecl); 5961 } 5962 5963 if (!ClassDecl->hasUserDeclaredDestructor()) { 5964 ++ASTContext::NumImplicitDestructors; 5965 5966 // If we have a dynamic class, then the destructor may be virtual, so we 5967 // have to declare the destructor immediately. This ensures that, e.g., it 5968 // shows up in the right place in the vtable and that we diagnose problems 5969 // with the implicit exception specification. 5970 if (ClassDecl->isDynamicClass() || 5971 ClassDecl->needsOverloadResolutionForDestructor()) 5972 DeclareImplicitDestructor(ClassDecl); 5973 } 5974 } 5975 5976 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) { 5977 if (!D) 5978 return; 5979 5980 int NumParamList = D->getNumTemplateParameterLists(); 5981 for (int i = 0; i < NumParamList; i++) { 5982 TemplateParameterList* Params = D->getTemplateParameterList(i); 5983 for (TemplateParameterList::iterator Param = Params->begin(), 5984 ParamEnd = Params->end(); 5985 Param != ParamEnd; ++Param) { 5986 NamedDecl *Named = cast<NamedDecl>(*Param); 5987 if (Named->getDeclName()) { 5988 S->AddDecl(Named); 5989 IdResolver.AddDecl(Named); 5990 } 5991 } 5992 } 5993 } 5994 5995 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 5996 if (!D) 5997 return; 5998 5999 TemplateParameterList *Params = 0; 6000 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 6001 Params = Template->getTemplateParameters(); 6002 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 6003 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 6004 Params = PartialSpec->getTemplateParameters(); 6005 else 6006 return; 6007 6008 for (TemplateParameterList::iterator Param = Params->begin(), 6009 ParamEnd = Params->end(); 6010 Param != ParamEnd; ++Param) { 6011 NamedDecl *Named = cast<NamedDecl>(*Param); 6012 if (Named->getDeclName()) { 6013 S->AddDecl(Named); 6014 IdResolver.AddDecl(Named); 6015 } 6016 } 6017 } 6018 6019 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6020 if (!RecordD) return; 6021 AdjustDeclIfTemplate(RecordD); 6022 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 6023 PushDeclContext(S, Record); 6024 } 6025 6026 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 6027 if (!RecordD) return; 6028 PopDeclContext(); 6029 } 6030 6031 /// This is used to implement the constant expression evaluation part of the 6032 /// attribute enable_if extension. There is nothing in standard C++ which would 6033 /// require reentering parameters. 6034 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 6035 if (!Param) 6036 return; 6037 6038 S->AddDecl(Param); 6039 if (Param->getDeclName()) 6040 IdResolver.AddDecl(Param); 6041 } 6042 6043 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 6044 /// parsing a top-level (non-nested) C++ class, and we are now 6045 /// parsing those parts of the given Method declaration that could 6046 /// not be parsed earlier (C++ [class.mem]p2), such as default 6047 /// arguments. This action should enter the scope of the given 6048 /// Method declaration as if we had just parsed the qualified method 6049 /// name. However, it should not bring the parameters into scope; 6050 /// that will be performed by ActOnDelayedCXXMethodParameter. 6051 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6052 } 6053 6054 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 6055 /// C++ method declaration. We're (re-)introducing the given 6056 /// function parameter into scope for use in parsing later parts of 6057 /// the method declaration. For example, we could see an 6058 /// ActOnParamDefaultArgument event for this parameter. 6059 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 6060 if (!ParamD) 6061 return; 6062 6063 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 6064 6065 // If this parameter has an unparsed default argument, clear it out 6066 // to make way for the parsed default argument. 6067 if (Param->hasUnparsedDefaultArg()) 6068 Param->setDefaultArg(0); 6069 6070 S->AddDecl(Param); 6071 if (Param->getDeclName()) 6072 IdResolver.AddDecl(Param); 6073 } 6074 6075 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 6076 /// processing the delayed method declaration for Method. The method 6077 /// declaration is now considered finished. There may be a separate 6078 /// ActOnStartOfFunctionDef action later (not necessarily 6079 /// immediately!) for this method, if it was also defined inside the 6080 /// class body. 6081 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 6082 if (!MethodD) 6083 return; 6084 6085 AdjustDeclIfTemplate(MethodD); 6086 6087 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 6088 6089 // Now that we have our default arguments, check the constructor 6090 // again. It could produce additional diagnostics or affect whether 6091 // the class has implicitly-declared destructors, among other 6092 // things. 6093 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 6094 CheckConstructor(Constructor); 6095 6096 // Check the default arguments, which we may have added. 6097 if (!Method->isInvalidDecl()) 6098 CheckCXXDefaultArguments(Method); 6099 } 6100 6101 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 6102 /// the well-formedness of the constructor declarator @p D with type @p 6103 /// R. If there are any errors in the declarator, this routine will 6104 /// emit diagnostics and set the invalid bit to true. In any case, the type 6105 /// will be updated to reflect a well-formed type for the constructor and 6106 /// returned. 6107 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 6108 StorageClass &SC) { 6109 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6110 6111 // C++ [class.ctor]p3: 6112 // A constructor shall not be virtual (10.3) or static (9.4). A 6113 // constructor can be invoked for a const, volatile or const 6114 // volatile object. A constructor shall not be declared const, 6115 // volatile, or const volatile (9.3.2). 6116 if (isVirtual) { 6117 if (!D.isInvalidType()) 6118 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6119 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 6120 << SourceRange(D.getIdentifierLoc()); 6121 D.setInvalidType(); 6122 } 6123 if (SC == SC_Static) { 6124 if (!D.isInvalidType()) 6125 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 6126 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6127 << SourceRange(D.getIdentifierLoc()); 6128 D.setInvalidType(); 6129 SC = SC_None; 6130 } 6131 6132 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6133 if (FTI.TypeQuals != 0) { 6134 if (FTI.TypeQuals & Qualifiers::Const) 6135 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6136 << "const" << SourceRange(D.getIdentifierLoc()); 6137 if (FTI.TypeQuals & Qualifiers::Volatile) 6138 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6139 << "volatile" << SourceRange(D.getIdentifierLoc()); 6140 if (FTI.TypeQuals & Qualifiers::Restrict) 6141 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 6142 << "restrict" << SourceRange(D.getIdentifierLoc()); 6143 D.setInvalidType(); 6144 } 6145 6146 // C++0x [class.ctor]p4: 6147 // A constructor shall not be declared with a ref-qualifier. 6148 if (FTI.hasRefQualifier()) { 6149 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 6150 << FTI.RefQualifierIsLValueRef 6151 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6152 D.setInvalidType(); 6153 } 6154 6155 // Rebuild the function type "R" without any type qualifiers (in 6156 // case any of the errors above fired) and with "void" as the 6157 // return type, since constructors don't have return types. 6158 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6159 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 6160 return R; 6161 6162 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6163 EPI.TypeQuals = 0; 6164 EPI.RefQualifier = RQ_None; 6165 6166 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 6167 } 6168 6169 /// CheckConstructor - Checks a fully-formed constructor for 6170 /// well-formedness, issuing any diagnostics required. Returns true if 6171 /// the constructor declarator is invalid. 6172 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 6173 CXXRecordDecl *ClassDecl 6174 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 6175 if (!ClassDecl) 6176 return Constructor->setInvalidDecl(); 6177 6178 // C++ [class.copy]p3: 6179 // A declaration of a constructor for a class X is ill-formed if 6180 // its first parameter is of type (optionally cv-qualified) X and 6181 // either there are no other parameters or else all other 6182 // parameters have default arguments. 6183 if (!Constructor->isInvalidDecl() && 6184 ((Constructor->getNumParams() == 1) || 6185 (Constructor->getNumParams() > 1 && 6186 Constructor->getParamDecl(1)->hasDefaultArg())) && 6187 Constructor->getTemplateSpecializationKind() 6188 != TSK_ImplicitInstantiation) { 6189 QualType ParamType = Constructor->getParamDecl(0)->getType(); 6190 QualType ClassTy = Context.getTagDeclType(ClassDecl); 6191 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 6192 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 6193 const char *ConstRef 6194 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 6195 : " const &"; 6196 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 6197 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 6198 6199 // FIXME: Rather that making the constructor invalid, we should endeavor 6200 // to fix the type. 6201 Constructor->setInvalidDecl(); 6202 } 6203 } 6204 } 6205 6206 /// CheckDestructor - Checks a fully-formed destructor definition for 6207 /// well-formedness, issuing any diagnostics required. Returns true 6208 /// on error. 6209 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 6210 CXXRecordDecl *RD = Destructor->getParent(); 6211 6212 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 6213 SourceLocation Loc; 6214 6215 if (!Destructor->isImplicit()) 6216 Loc = Destructor->getLocation(); 6217 else 6218 Loc = RD->getLocation(); 6219 6220 // If we have a virtual destructor, look up the deallocation function 6221 FunctionDecl *OperatorDelete = 0; 6222 DeclarationName Name = 6223 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 6224 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 6225 return true; 6226 // If there's no class-specific operator delete, look up the global 6227 // non-array delete. 6228 if (!OperatorDelete) 6229 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name); 6230 6231 MarkFunctionReferenced(Loc, OperatorDelete); 6232 6233 Destructor->setOperatorDelete(OperatorDelete); 6234 } 6235 6236 return false; 6237 } 6238 6239 static inline bool 6240 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 6241 return (FTI.NumParams == 1 && !FTI.isVariadic && FTI.Params[0].Ident == 0 && 6242 FTI.Params[0].Param && 6243 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()); 6244 } 6245 6246 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 6247 /// the well-formednes of the destructor declarator @p D with type @p 6248 /// R. If there are any errors in the declarator, this routine will 6249 /// emit diagnostics and set the declarator to invalid. Even if this happens, 6250 /// will be updated to reflect a well-formed type for the destructor and 6251 /// returned. 6252 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 6253 StorageClass& SC) { 6254 // C++ [class.dtor]p1: 6255 // [...] A typedef-name that names a class is a class-name 6256 // (7.1.3); however, a typedef-name that names a class shall not 6257 // be used as the identifier in the declarator for a destructor 6258 // declaration. 6259 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 6260 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 6261 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6262 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 6263 else if (const TemplateSpecializationType *TST = 6264 DeclaratorType->getAs<TemplateSpecializationType>()) 6265 if (TST->isTypeAlias()) 6266 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 6267 << DeclaratorType << 1; 6268 6269 // C++ [class.dtor]p2: 6270 // A destructor is used to destroy objects of its class type. A 6271 // destructor takes no parameters, and no return type can be 6272 // specified for it (not even void). The address of a destructor 6273 // shall not be taken. A destructor shall not be static. A 6274 // destructor can be invoked for a const, volatile or const 6275 // volatile object. A destructor shall not be declared const, 6276 // volatile or const volatile (9.3.2). 6277 if (SC == SC_Static) { 6278 if (!D.isInvalidType()) 6279 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 6280 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6281 << SourceRange(D.getIdentifierLoc()) 6282 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6283 6284 SC = SC_None; 6285 } 6286 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6287 // Destructors don't have return types, but the parser will 6288 // happily parse something like: 6289 // 6290 // class X { 6291 // float ~X(); 6292 // }; 6293 // 6294 // The return type will be eliminated later. 6295 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 6296 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6297 << SourceRange(D.getIdentifierLoc()); 6298 } 6299 6300 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 6301 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 6302 if (FTI.TypeQuals & Qualifiers::Const) 6303 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6304 << "const" << SourceRange(D.getIdentifierLoc()); 6305 if (FTI.TypeQuals & Qualifiers::Volatile) 6306 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6307 << "volatile" << SourceRange(D.getIdentifierLoc()); 6308 if (FTI.TypeQuals & Qualifiers::Restrict) 6309 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 6310 << "restrict" << SourceRange(D.getIdentifierLoc()); 6311 D.setInvalidType(); 6312 } 6313 6314 // C++0x [class.dtor]p2: 6315 // A destructor shall not be declared with a ref-qualifier. 6316 if (FTI.hasRefQualifier()) { 6317 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 6318 << FTI.RefQualifierIsLValueRef 6319 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 6320 D.setInvalidType(); 6321 } 6322 6323 // Make sure we don't have any parameters. 6324 if (FTI.NumParams > 0 && !FTIHasSingleVoidArgument(FTI)) { 6325 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 6326 6327 // Delete the parameters. 6328 FTI.freeParams(); 6329 D.setInvalidType(); 6330 } 6331 6332 // Make sure the destructor isn't variadic. 6333 if (FTI.isVariadic) { 6334 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 6335 D.setInvalidType(); 6336 } 6337 6338 // Rebuild the function type "R" without any type qualifiers or 6339 // parameters (in case any of the errors above fired) and with 6340 // "void" as the return type, since destructors don't have return 6341 // types. 6342 if (!D.isInvalidType()) 6343 return R; 6344 6345 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6346 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 6347 EPI.Variadic = false; 6348 EPI.TypeQuals = 0; 6349 EPI.RefQualifier = RQ_None; 6350 return Context.getFunctionType(Context.VoidTy, None, EPI); 6351 } 6352 6353 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 6354 /// well-formednes of the conversion function declarator @p D with 6355 /// type @p R. If there are any errors in the declarator, this routine 6356 /// will emit diagnostics and return true. Otherwise, it will return 6357 /// false. Either way, the type @p R will be updated to reflect a 6358 /// well-formed type for the conversion operator. 6359 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 6360 StorageClass& SC) { 6361 // C++ [class.conv.fct]p1: 6362 // Neither parameter types nor return type can be specified. The 6363 // type of a conversion function (8.3.5) is "function taking no 6364 // parameter returning conversion-type-id." 6365 if (SC == SC_Static) { 6366 if (!D.isInvalidType()) 6367 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 6368 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 6369 << D.getName().getSourceRange(); 6370 D.setInvalidType(); 6371 SC = SC_None; 6372 } 6373 6374 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 6375 6376 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 6377 // Conversion functions don't have return types, but the parser will 6378 // happily parse something like: 6379 // 6380 // class X { 6381 // float operator bool(); 6382 // }; 6383 // 6384 // The return type will be changed later anyway. 6385 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 6386 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6387 << SourceRange(D.getIdentifierLoc()); 6388 D.setInvalidType(); 6389 } 6390 6391 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 6392 6393 // Make sure we don't have any parameters. 6394 if (Proto->getNumParams() > 0) { 6395 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 6396 6397 // Delete the parameters. 6398 D.getFunctionTypeInfo().freeParams(); 6399 D.setInvalidType(); 6400 } else if (Proto->isVariadic()) { 6401 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 6402 D.setInvalidType(); 6403 } 6404 6405 // Diagnose "&operator bool()" and other such nonsense. This 6406 // is actually a gcc extension which we don't support. 6407 if (Proto->getReturnType() != ConvType) { 6408 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 6409 << Proto->getReturnType(); 6410 D.setInvalidType(); 6411 ConvType = Proto->getReturnType(); 6412 } 6413 6414 // C++ [class.conv.fct]p4: 6415 // The conversion-type-id shall not represent a function type nor 6416 // an array type. 6417 if (ConvType->isArrayType()) { 6418 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 6419 ConvType = Context.getPointerType(ConvType); 6420 D.setInvalidType(); 6421 } else if (ConvType->isFunctionType()) { 6422 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 6423 ConvType = Context.getPointerType(ConvType); 6424 D.setInvalidType(); 6425 } 6426 6427 // Rebuild the function type "R" without any parameters (in case any 6428 // of the errors above fired) and with the conversion type as the 6429 // return type. 6430 if (D.isInvalidType()) 6431 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 6432 6433 // C++0x explicit conversion operators. 6434 if (D.getDeclSpec().isExplicitSpecified()) 6435 Diag(D.getDeclSpec().getExplicitSpecLoc(), 6436 getLangOpts().CPlusPlus11 ? 6437 diag::warn_cxx98_compat_explicit_conversion_functions : 6438 diag::ext_explicit_conversion_functions) 6439 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 6440 } 6441 6442 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 6443 /// the declaration of the given C++ conversion function. This routine 6444 /// is responsible for recording the conversion function in the C++ 6445 /// class, if possible. 6446 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 6447 assert(Conversion && "Expected to receive a conversion function declaration"); 6448 6449 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 6450 6451 // Make sure we aren't redeclaring the conversion function. 6452 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 6453 6454 // C++ [class.conv.fct]p1: 6455 // [...] A conversion function is never used to convert a 6456 // (possibly cv-qualified) object to the (possibly cv-qualified) 6457 // same object type (or a reference to it), to a (possibly 6458 // cv-qualified) base class of that type (or a reference to it), 6459 // or to (possibly cv-qualified) void. 6460 // FIXME: Suppress this warning if the conversion function ends up being a 6461 // virtual function that overrides a virtual function in a base class. 6462 QualType ClassType 6463 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 6464 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 6465 ConvType = ConvTypeRef->getPointeeType(); 6466 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 6467 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 6468 /* Suppress diagnostics for instantiations. */; 6469 else if (ConvType->isRecordType()) { 6470 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 6471 if (ConvType == ClassType) 6472 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 6473 << ClassType; 6474 else if (IsDerivedFrom(ClassType, ConvType)) 6475 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 6476 << ClassType << ConvType; 6477 } else if (ConvType->isVoidType()) { 6478 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 6479 << ClassType << ConvType; 6480 } 6481 6482 if (FunctionTemplateDecl *ConversionTemplate 6483 = Conversion->getDescribedFunctionTemplate()) 6484 return ConversionTemplate; 6485 6486 return Conversion; 6487 } 6488 6489 //===----------------------------------------------------------------------===// 6490 // Namespace Handling 6491 //===----------------------------------------------------------------------===// 6492 6493 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is 6494 /// reopened. 6495 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 6496 SourceLocation Loc, 6497 IdentifierInfo *II, bool *IsInline, 6498 NamespaceDecl *PrevNS) { 6499 assert(*IsInline != PrevNS->isInline()); 6500 6501 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 6502 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 6503 // inline namespaces, with the intention of bringing names into namespace std. 6504 // 6505 // We support this just well enough to get that case working; this is not 6506 // sufficient to support reopening namespaces as inline in general. 6507 if (*IsInline && II && II->getName().startswith("__atomic") && 6508 S.getSourceManager().isInSystemHeader(Loc)) { 6509 // Mark all prior declarations of the namespace as inline. 6510 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 6511 NS = NS->getPreviousDecl()) 6512 NS->setInline(*IsInline); 6513 // Patch up the lookup table for the containing namespace. This isn't really 6514 // correct, but it's good enough for this particular case. 6515 for (auto *I : PrevNS->decls()) 6516 if (auto *ND = dyn_cast<NamedDecl>(I)) 6517 PrevNS->getParent()->makeDeclVisibleInContext(ND); 6518 return; 6519 } 6520 6521 if (PrevNS->isInline()) 6522 // The user probably just forgot the 'inline', so suggest that it 6523 // be added back. 6524 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 6525 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 6526 else 6527 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline; 6528 6529 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 6530 *IsInline = PrevNS->isInline(); 6531 } 6532 6533 /// ActOnStartNamespaceDef - This is called at the start of a namespace 6534 /// definition. 6535 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 6536 SourceLocation InlineLoc, 6537 SourceLocation NamespaceLoc, 6538 SourceLocation IdentLoc, 6539 IdentifierInfo *II, 6540 SourceLocation LBrace, 6541 AttributeList *AttrList) { 6542 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 6543 // For anonymous namespace, take the location of the left brace. 6544 SourceLocation Loc = II ? IdentLoc : LBrace; 6545 bool IsInline = InlineLoc.isValid(); 6546 bool IsInvalid = false; 6547 bool IsStd = false; 6548 bool AddToKnown = false; 6549 Scope *DeclRegionScope = NamespcScope->getParent(); 6550 6551 NamespaceDecl *PrevNS = 0; 6552 if (II) { 6553 // C++ [namespace.def]p2: 6554 // The identifier in an original-namespace-definition shall not 6555 // have been previously defined in the declarative region in 6556 // which the original-namespace-definition appears. The 6557 // identifier in an original-namespace-definition is the name of 6558 // the namespace. Subsequently in that declarative region, it is 6559 // treated as an original-namespace-name. 6560 // 6561 // Since namespace names are unique in their scope, and we don't 6562 // look through using directives, just look for any ordinary names. 6563 6564 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 6565 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 6566 Decl::IDNS_Namespace; 6567 NamedDecl *PrevDecl = 0; 6568 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 6569 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6570 ++I) { 6571 if ((*I)->getIdentifierNamespace() & IDNS) { 6572 PrevDecl = *I; 6573 break; 6574 } 6575 } 6576 6577 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 6578 6579 if (PrevNS) { 6580 // This is an extended namespace definition. 6581 if (IsInline != PrevNS->isInline()) 6582 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 6583 &IsInline, PrevNS); 6584 } else if (PrevDecl) { 6585 // This is an invalid name redefinition. 6586 Diag(Loc, diag::err_redefinition_different_kind) 6587 << II; 6588 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 6589 IsInvalid = true; 6590 // Continue on to push Namespc as current DeclContext and return it. 6591 } else if (II->isStr("std") && 6592 CurContext->getRedeclContext()->isTranslationUnit()) { 6593 // This is the first "real" definition of the namespace "std", so update 6594 // our cache of the "std" namespace to point at this definition. 6595 PrevNS = getStdNamespace(); 6596 IsStd = true; 6597 AddToKnown = !IsInline; 6598 } else { 6599 // We've seen this namespace for the first time. 6600 AddToKnown = !IsInline; 6601 } 6602 } else { 6603 // Anonymous namespaces. 6604 6605 // Determine whether the parent already has an anonymous namespace. 6606 DeclContext *Parent = CurContext->getRedeclContext(); 6607 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6608 PrevNS = TU->getAnonymousNamespace(); 6609 } else { 6610 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 6611 PrevNS = ND->getAnonymousNamespace(); 6612 } 6613 6614 if (PrevNS && IsInline != PrevNS->isInline()) 6615 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 6616 &IsInline, PrevNS); 6617 } 6618 6619 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 6620 StartLoc, Loc, II, PrevNS); 6621 if (IsInvalid) 6622 Namespc->setInvalidDecl(); 6623 6624 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 6625 6626 // FIXME: Should we be merging attributes? 6627 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 6628 PushNamespaceVisibilityAttr(Attr, Loc); 6629 6630 if (IsStd) 6631 StdNamespace = Namespc; 6632 if (AddToKnown) 6633 KnownNamespaces[Namespc] = false; 6634 6635 if (II) { 6636 PushOnScopeChains(Namespc, DeclRegionScope); 6637 } else { 6638 // Link the anonymous namespace into its parent. 6639 DeclContext *Parent = CurContext->getRedeclContext(); 6640 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 6641 TU->setAnonymousNamespace(Namespc); 6642 } else { 6643 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 6644 } 6645 6646 CurContext->addDecl(Namespc); 6647 6648 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 6649 // behaves as if it were replaced by 6650 // namespace unique { /* empty body */ } 6651 // using namespace unique; 6652 // namespace unique { namespace-body } 6653 // where all occurrences of 'unique' in a translation unit are 6654 // replaced by the same identifier and this identifier differs 6655 // from all other identifiers in the entire program. 6656 6657 // We just create the namespace with an empty name and then add an 6658 // implicit using declaration, just like the standard suggests. 6659 // 6660 // CodeGen enforces the "universally unique" aspect by giving all 6661 // declarations semantically contained within an anonymous 6662 // namespace internal linkage. 6663 6664 if (!PrevNS) { 6665 UsingDirectiveDecl* UD 6666 = UsingDirectiveDecl::Create(Context, Parent, 6667 /* 'using' */ LBrace, 6668 /* 'namespace' */ SourceLocation(), 6669 /* qualifier */ NestedNameSpecifierLoc(), 6670 /* identifier */ SourceLocation(), 6671 Namespc, 6672 /* Ancestor */ Parent); 6673 UD->setImplicit(); 6674 Parent->addDecl(UD); 6675 } 6676 } 6677 6678 ActOnDocumentableDecl(Namespc); 6679 6680 // Although we could have an invalid decl (i.e. the namespace name is a 6681 // redefinition), push it as current DeclContext and try to continue parsing. 6682 // FIXME: We should be able to push Namespc here, so that the each DeclContext 6683 // for the namespace has the declarations that showed up in that particular 6684 // namespace definition. 6685 PushDeclContext(NamespcScope, Namespc); 6686 return Namespc; 6687 } 6688 6689 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 6690 /// is a namespace alias, returns the namespace it points to. 6691 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 6692 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 6693 return AD->getNamespace(); 6694 return dyn_cast_or_null<NamespaceDecl>(D); 6695 } 6696 6697 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 6698 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 6699 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 6700 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 6701 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 6702 Namespc->setRBraceLoc(RBrace); 6703 PopDeclContext(); 6704 if (Namespc->hasAttr<VisibilityAttr>()) 6705 PopPragmaVisibility(true, RBrace); 6706 } 6707 6708 CXXRecordDecl *Sema::getStdBadAlloc() const { 6709 return cast_or_null<CXXRecordDecl>( 6710 StdBadAlloc.get(Context.getExternalSource())); 6711 } 6712 6713 NamespaceDecl *Sema::getStdNamespace() const { 6714 return cast_or_null<NamespaceDecl>( 6715 StdNamespace.get(Context.getExternalSource())); 6716 } 6717 6718 /// \brief Retrieve the special "std" namespace, which may require us to 6719 /// implicitly define the namespace. 6720 NamespaceDecl *Sema::getOrCreateStdNamespace() { 6721 if (!StdNamespace) { 6722 // The "std" namespace has not yet been defined, so build one implicitly. 6723 StdNamespace = NamespaceDecl::Create(Context, 6724 Context.getTranslationUnitDecl(), 6725 /*Inline=*/false, 6726 SourceLocation(), SourceLocation(), 6727 &PP.getIdentifierTable().get("std"), 6728 /*PrevDecl=*/0); 6729 getStdNamespace()->setImplicit(true); 6730 } 6731 6732 return getStdNamespace(); 6733 } 6734 6735 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 6736 assert(getLangOpts().CPlusPlus && 6737 "Looking for std::initializer_list outside of C++."); 6738 6739 // We're looking for implicit instantiations of 6740 // template <typename E> class std::initializer_list. 6741 6742 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 6743 return false; 6744 6745 ClassTemplateDecl *Template = 0; 6746 const TemplateArgument *Arguments = 0; 6747 6748 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6749 6750 ClassTemplateSpecializationDecl *Specialization = 6751 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6752 if (!Specialization) 6753 return false; 6754 6755 Template = Specialization->getSpecializedTemplate(); 6756 Arguments = Specialization->getTemplateArgs().data(); 6757 } else if (const TemplateSpecializationType *TST = 6758 Ty->getAs<TemplateSpecializationType>()) { 6759 Template = dyn_cast_or_null<ClassTemplateDecl>( 6760 TST->getTemplateName().getAsTemplateDecl()); 6761 Arguments = TST->getArgs(); 6762 } 6763 if (!Template) 6764 return false; 6765 6766 if (!StdInitializerList) { 6767 // Haven't recognized std::initializer_list yet, maybe this is it. 6768 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 6769 if (TemplateClass->getIdentifier() != 6770 &PP.getIdentifierTable().get("initializer_list") || 6771 !getStdNamespace()->InEnclosingNamespaceSetOf( 6772 TemplateClass->getDeclContext())) 6773 return false; 6774 // This is a template called std::initializer_list, but is it the right 6775 // template? 6776 TemplateParameterList *Params = Template->getTemplateParameters(); 6777 if (Params->getMinRequiredArguments() != 1) 6778 return false; 6779 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 6780 return false; 6781 6782 // It's the right template. 6783 StdInitializerList = Template; 6784 } 6785 6786 if (Template != StdInitializerList) 6787 return false; 6788 6789 // This is an instance of std::initializer_list. Find the argument type. 6790 if (Element) 6791 *Element = Arguments[0].getAsType(); 6792 return true; 6793 } 6794 6795 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 6796 NamespaceDecl *Std = S.getStdNamespace(); 6797 if (!Std) { 6798 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6799 return 0; 6800 } 6801 6802 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 6803 Loc, Sema::LookupOrdinaryName); 6804 if (!S.LookupQualifiedName(Result, Std)) { 6805 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 6806 return 0; 6807 } 6808 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 6809 if (!Template) { 6810 Result.suppressDiagnostics(); 6811 // We found something weird. Complain about the first thing we found. 6812 NamedDecl *Found = *Result.begin(); 6813 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 6814 return 0; 6815 } 6816 6817 // We found some template called std::initializer_list. Now verify that it's 6818 // correct. 6819 TemplateParameterList *Params = Template->getTemplateParameters(); 6820 if (Params->getMinRequiredArguments() != 1 || 6821 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6822 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 6823 return 0; 6824 } 6825 6826 return Template; 6827 } 6828 6829 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 6830 if (!StdInitializerList) { 6831 StdInitializerList = LookupStdInitializerList(*this, Loc); 6832 if (!StdInitializerList) 6833 return QualType(); 6834 } 6835 6836 TemplateArgumentListInfo Args(Loc, Loc); 6837 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 6838 Context.getTrivialTypeSourceInfo(Element, 6839 Loc))); 6840 return Context.getCanonicalType( 6841 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 6842 } 6843 6844 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) { 6845 // C++ [dcl.init.list]p2: 6846 // A constructor is an initializer-list constructor if its first parameter 6847 // is of type std::initializer_list<E> or reference to possibly cv-qualified 6848 // std::initializer_list<E> for some type E, and either there are no other 6849 // parameters or else all other parameters have default arguments. 6850 if (Ctor->getNumParams() < 1 || 6851 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 6852 return false; 6853 6854 QualType ArgType = Ctor->getParamDecl(0)->getType(); 6855 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 6856 ArgType = RT->getPointeeType().getUnqualifiedType(); 6857 6858 return isStdInitializerList(ArgType, 0); 6859 } 6860 6861 /// \brief Determine whether a using statement is in a context where it will be 6862 /// apply in all contexts. 6863 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 6864 switch (CurContext->getDeclKind()) { 6865 case Decl::TranslationUnit: 6866 return true; 6867 case Decl::LinkageSpec: 6868 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 6869 default: 6870 return false; 6871 } 6872 } 6873 6874 namespace { 6875 6876 // Callback to only accept typo corrections that are namespaces. 6877 class NamespaceValidatorCCC : public CorrectionCandidateCallback { 6878 public: 6879 bool ValidateCandidate(const TypoCorrection &candidate) override { 6880 if (NamedDecl *ND = candidate.getCorrectionDecl()) 6881 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 6882 return false; 6883 } 6884 }; 6885 6886 } 6887 6888 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 6889 CXXScopeSpec &SS, 6890 SourceLocation IdentLoc, 6891 IdentifierInfo *Ident) { 6892 NamespaceValidatorCCC Validator; 6893 R.clear(); 6894 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(), 6895 R.getLookupKind(), Sc, &SS, 6896 Validator)) { 6897 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 6898 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 6899 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 6900 Ident->getName().equals(CorrectedStr); 6901 S.diagnoseTypo(Corrected, 6902 S.PDiag(diag::err_using_directive_member_suggest) 6903 << Ident << DC << DroppedSpecifier << SS.getRange(), 6904 S.PDiag(diag::note_namespace_defined_here)); 6905 } else { 6906 S.diagnoseTypo(Corrected, 6907 S.PDiag(diag::err_using_directive_suggest) << Ident, 6908 S.PDiag(diag::note_namespace_defined_here)); 6909 } 6910 R.addDecl(Corrected.getCorrectionDecl()); 6911 return true; 6912 } 6913 return false; 6914 } 6915 6916 Decl *Sema::ActOnUsingDirective(Scope *S, 6917 SourceLocation UsingLoc, 6918 SourceLocation NamespcLoc, 6919 CXXScopeSpec &SS, 6920 SourceLocation IdentLoc, 6921 IdentifierInfo *NamespcName, 6922 AttributeList *AttrList) { 6923 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 6924 assert(NamespcName && "Invalid NamespcName."); 6925 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 6926 6927 // This can only happen along a recovery path. 6928 while (S->getFlags() & Scope::TemplateParamScope) 6929 S = S->getParent(); 6930 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 6931 6932 UsingDirectiveDecl *UDir = 0; 6933 NestedNameSpecifier *Qualifier = 0; 6934 if (SS.isSet()) 6935 Qualifier = SS.getScopeRep(); 6936 6937 // Lookup namespace name. 6938 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 6939 LookupParsedName(R, S, &SS); 6940 if (R.isAmbiguous()) 6941 return 0; 6942 6943 if (R.empty()) { 6944 R.clear(); 6945 // Allow "using namespace std;" or "using namespace ::std;" even if 6946 // "std" hasn't been defined yet, for GCC compatibility. 6947 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 6948 NamespcName->isStr("std")) { 6949 Diag(IdentLoc, diag::ext_using_undefined_std); 6950 R.addDecl(getOrCreateStdNamespace()); 6951 R.resolveKind(); 6952 } 6953 // Otherwise, attempt typo correction. 6954 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 6955 } 6956 6957 if (!R.empty()) { 6958 NamedDecl *Named = R.getFoundDecl(); 6959 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 6960 && "expected namespace decl"); 6961 // C++ [namespace.udir]p1: 6962 // A using-directive specifies that the names in the nominated 6963 // namespace can be used in the scope in which the 6964 // using-directive appears after the using-directive. During 6965 // unqualified name lookup (3.4.1), the names appear as if they 6966 // were declared in the nearest enclosing namespace which 6967 // contains both the using-directive and the nominated 6968 // namespace. [Note: in this context, "contains" means "contains 6969 // directly or indirectly". ] 6970 6971 // Find enclosing context containing both using-directive and 6972 // nominated namespace. 6973 NamespaceDecl *NS = getNamespaceDecl(Named); 6974 DeclContext *CommonAncestor = cast<DeclContext>(NS); 6975 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 6976 CommonAncestor = CommonAncestor->getParent(); 6977 6978 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 6979 SS.getWithLocInContext(Context), 6980 IdentLoc, Named, CommonAncestor); 6981 6982 if (IsUsingDirectiveInToplevelContext(CurContext) && 6983 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 6984 Diag(IdentLoc, diag::warn_using_directive_in_header); 6985 } 6986 6987 PushUsingDirective(S, UDir); 6988 } else { 6989 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 6990 } 6991 6992 if (UDir) 6993 ProcessDeclAttributeList(S, UDir, AttrList); 6994 6995 return UDir; 6996 } 6997 6998 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 6999 // If the scope has an associated entity and the using directive is at 7000 // namespace or translation unit scope, add the UsingDirectiveDecl into 7001 // its lookup structure so qualified name lookup can find it. 7002 DeclContext *Ctx = S->getEntity(); 7003 if (Ctx && !Ctx->isFunctionOrMethod()) 7004 Ctx->addDecl(UDir); 7005 else 7006 // Otherwise, it is at block sope. The using-directives will affect lookup 7007 // only to the end of the scope. 7008 S->PushUsingDirective(UDir); 7009 } 7010 7011 7012 Decl *Sema::ActOnUsingDeclaration(Scope *S, 7013 AccessSpecifier AS, 7014 bool HasUsingKeyword, 7015 SourceLocation UsingLoc, 7016 CXXScopeSpec &SS, 7017 UnqualifiedId &Name, 7018 AttributeList *AttrList, 7019 bool HasTypenameKeyword, 7020 SourceLocation TypenameLoc) { 7021 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 7022 7023 switch (Name.getKind()) { 7024 case UnqualifiedId::IK_ImplicitSelfParam: 7025 case UnqualifiedId::IK_Identifier: 7026 case UnqualifiedId::IK_OperatorFunctionId: 7027 case UnqualifiedId::IK_LiteralOperatorId: 7028 case UnqualifiedId::IK_ConversionFunctionId: 7029 break; 7030 7031 case UnqualifiedId::IK_ConstructorName: 7032 case UnqualifiedId::IK_ConstructorTemplateId: 7033 // C++11 inheriting constructors. 7034 Diag(Name.getLocStart(), 7035 getLangOpts().CPlusPlus11 ? 7036 diag::warn_cxx98_compat_using_decl_constructor : 7037 diag::err_using_decl_constructor) 7038 << SS.getRange(); 7039 7040 if (getLangOpts().CPlusPlus11) break; 7041 7042 return 0; 7043 7044 case UnqualifiedId::IK_DestructorName: 7045 Diag(Name.getLocStart(), diag::err_using_decl_destructor) 7046 << SS.getRange(); 7047 return 0; 7048 7049 case UnqualifiedId::IK_TemplateId: 7050 Diag(Name.getLocStart(), diag::err_using_decl_template_id) 7051 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 7052 return 0; 7053 } 7054 7055 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 7056 DeclarationName TargetName = TargetNameInfo.getName(); 7057 if (!TargetName) 7058 return 0; 7059 7060 // Warn about access declarations. 7061 if (!HasUsingKeyword) { 7062 Diag(Name.getLocStart(), 7063 getLangOpts().CPlusPlus11 ? diag::err_access_decl 7064 : diag::warn_access_decl_deprecated) 7065 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 7066 } 7067 7068 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 7069 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 7070 return 0; 7071 7072 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 7073 TargetNameInfo, AttrList, 7074 /* IsInstantiation */ false, 7075 HasTypenameKeyword, TypenameLoc); 7076 if (UD) 7077 PushOnScopeChains(UD, S, /*AddToContext*/ false); 7078 7079 return UD; 7080 } 7081 7082 /// \brief Determine whether a using declaration considers the given 7083 /// declarations as "equivalent", e.g., if they are redeclarations of 7084 /// the same entity or are both typedefs of the same type. 7085 static bool 7086 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 7087 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 7088 return true; 7089 7090 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 7091 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 7092 return Context.hasSameType(TD1->getUnderlyingType(), 7093 TD2->getUnderlyingType()); 7094 7095 return false; 7096 } 7097 7098 7099 /// Determines whether to create a using shadow decl for a particular 7100 /// decl, given the set of decls existing prior to this using lookup. 7101 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 7102 const LookupResult &Previous, 7103 UsingShadowDecl *&PrevShadow) { 7104 // Diagnose finding a decl which is not from a base class of the 7105 // current class. We do this now because there are cases where this 7106 // function will silently decide not to build a shadow decl, which 7107 // will pre-empt further diagnostics. 7108 // 7109 // We don't need to do this in C++0x because we do the check once on 7110 // the qualifier. 7111 // 7112 // FIXME: diagnose the following if we care enough: 7113 // struct A { int foo; }; 7114 // struct B : A { using A::foo; }; 7115 // template <class T> struct C : A {}; 7116 // template <class T> struct D : C<T> { using B::foo; } // <--- 7117 // This is invalid (during instantiation) in C++03 because B::foo 7118 // resolves to the using decl in B, which is not a base class of D<T>. 7119 // We can't diagnose it immediately because C<T> is an unknown 7120 // specialization. The UsingShadowDecl in D<T> then points directly 7121 // to A::foo, which will look well-formed when we instantiate. 7122 // The right solution is to not collapse the shadow-decl chain. 7123 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 7124 DeclContext *OrigDC = Orig->getDeclContext(); 7125 7126 // Handle enums and anonymous structs. 7127 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 7128 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 7129 while (OrigRec->isAnonymousStructOrUnion()) 7130 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 7131 7132 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 7133 if (OrigDC == CurContext) { 7134 Diag(Using->getLocation(), 7135 diag::err_using_decl_nested_name_specifier_is_current_class) 7136 << Using->getQualifierLoc().getSourceRange(); 7137 Diag(Orig->getLocation(), diag::note_using_decl_target); 7138 return true; 7139 } 7140 7141 Diag(Using->getQualifierLoc().getBeginLoc(), 7142 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7143 << Using->getQualifier() 7144 << cast<CXXRecordDecl>(CurContext) 7145 << Using->getQualifierLoc().getSourceRange(); 7146 Diag(Orig->getLocation(), diag::note_using_decl_target); 7147 return true; 7148 } 7149 } 7150 7151 if (Previous.empty()) return false; 7152 7153 NamedDecl *Target = Orig; 7154 if (isa<UsingShadowDecl>(Target)) 7155 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7156 7157 // If the target happens to be one of the previous declarations, we 7158 // don't have a conflict. 7159 // 7160 // FIXME: but we might be increasing its access, in which case we 7161 // should redeclare it. 7162 NamedDecl *NonTag = 0, *Tag = 0; 7163 bool FoundEquivalentDecl = false; 7164 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7165 I != E; ++I) { 7166 NamedDecl *D = (*I)->getUnderlyingDecl(); 7167 if (IsEquivalentForUsingDecl(Context, D, Target)) { 7168 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 7169 PrevShadow = Shadow; 7170 FoundEquivalentDecl = true; 7171 } 7172 7173 (isa<TagDecl>(D) ? Tag : NonTag) = D; 7174 } 7175 7176 if (FoundEquivalentDecl) 7177 return false; 7178 7179 if (FunctionDecl *FD = Target->getAsFunction()) { 7180 NamedDecl *OldDecl = 0; 7181 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 7182 case Ovl_Overload: 7183 return false; 7184 7185 case Ovl_NonFunction: 7186 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7187 break; 7188 7189 // We found a decl with the exact signature. 7190 case Ovl_Match: 7191 // If we're in a record, we want to hide the target, so we 7192 // return true (without a diagnostic) to tell the caller not to 7193 // build a shadow decl. 7194 if (CurContext->isRecord()) 7195 return true; 7196 7197 // If we're not in a record, this is an error. 7198 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7199 break; 7200 } 7201 7202 Diag(Target->getLocation(), diag::note_using_decl_target); 7203 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 7204 return true; 7205 } 7206 7207 // Target is not a function. 7208 7209 if (isa<TagDecl>(Target)) { 7210 // No conflict between a tag and a non-tag. 7211 if (!Tag) return false; 7212 7213 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7214 Diag(Target->getLocation(), diag::note_using_decl_target); 7215 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 7216 return true; 7217 } 7218 7219 // No conflict between a tag and a non-tag. 7220 if (!NonTag) return false; 7221 7222 Diag(Using->getLocation(), diag::err_using_decl_conflict); 7223 Diag(Target->getLocation(), diag::note_using_decl_target); 7224 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 7225 return true; 7226 } 7227 7228 /// Builds a shadow declaration corresponding to a 'using' declaration. 7229 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 7230 UsingDecl *UD, 7231 NamedDecl *Orig, 7232 UsingShadowDecl *PrevDecl) { 7233 7234 // If we resolved to another shadow declaration, just coalesce them. 7235 NamedDecl *Target = Orig; 7236 if (isa<UsingShadowDecl>(Target)) { 7237 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 7238 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 7239 } 7240 7241 UsingShadowDecl *Shadow 7242 = UsingShadowDecl::Create(Context, CurContext, 7243 UD->getLocation(), UD, Target); 7244 UD->addShadowDecl(Shadow); 7245 7246 Shadow->setAccess(UD->getAccess()); 7247 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 7248 Shadow->setInvalidDecl(); 7249 7250 Shadow->setPreviousDecl(PrevDecl); 7251 7252 if (S) 7253 PushOnScopeChains(Shadow, S); 7254 else 7255 CurContext->addDecl(Shadow); 7256 7257 7258 return Shadow; 7259 } 7260 7261 /// Hides a using shadow declaration. This is required by the current 7262 /// using-decl implementation when a resolvable using declaration in a 7263 /// class is followed by a declaration which would hide or override 7264 /// one or more of the using decl's targets; for example: 7265 /// 7266 /// struct Base { void foo(int); }; 7267 /// struct Derived : Base { 7268 /// using Base::foo; 7269 /// void foo(int); 7270 /// }; 7271 /// 7272 /// The governing language is C++03 [namespace.udecl]p12: 7273 /// 7274 /// When a using-declaration brings names from a base class into a 7275 /// derived class scope, member functions in the derived class 7276 /// override and/or hide member functions with the same name and 7277 /// parameter types in a base class (rather than conflicting). 7278 /// 7279 /// There are two ways to implement this: 7280 /// (1) optimistically create shadow decls when they're not hidden 7281 /// by existing declarations, or 7282 /// (2) don't create any shadow decls (or at least don't make them 7283 /// visible) until we've fully parsed/instantiated the class. 7284 /// The problem with (1) is that we might have to retroactively remove 7285 /// a shadow decl, which requires several O(n) operations because the 7286 /// decl structures are (very reasonably) not designed for removal. 7287 /// (2) avoids this but is very fiddly and phase-dependent. 7288 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 7289 if (Shadow->getDeclName().getNameKind() == 7290 DeclarationName::CXXConversionFunctionName) 7291 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 7292 7293 // Remove it from the DeclContext... 7294 Shadow->getDeclContext()->removeDecl(Shadow); 7295 7296 // ...and the scope, if applicable... 7297 if (S) { 7298 S->RemoveDecl(Shadow); 7299 IdResolver.RemoveDecl(Shadow); 7300 } 7301 7302 // ...and the using decl. 7303 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 7304 7305 // TODO: complain somehow if Shadow was used. It shouldn't 7306 // be possible for this to happen, because...? 7307 } 7308 7309 namespace { 7310 class UsingValidatorCCC : public CorrectionCandidateCallback { 7311 public: 7312 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 7313 bool RequireMember) 7314 : HasTypenameKeyword(HasTypenameKeyword), 7315 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {} 7316 7317 bool ValidateCandidate(const TypoCorrection &Candidate) override { 7318 NamedDecl *ND = Candidate.getCorrectionDecl(); 7319 7320 // Keywords are not valid here. 7321 if (!ND || isa<NamespaceDecl>(ND)) 7322 return false; 7323 7324 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) && 7325 !isa<TypeDecl>(ND)) 7326 return false; 7327 7328 // Completely unqualified names are invalid for a 'using' declaration. 7329 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 7330 return false; 7331 7332 if (isa<TypeDecl>(ND)) 7333 return HasTypenameKeyword || !IsInstantiation; 7334 7335 return !HasTypenameKeyword; 7336 } 7337 7338 private: 7339 bool HasTypenameKeyword; 7340 bool IsInstantiation; 7341 bool RequireMember; 7342 }; 7343 } // end anonymous namespace 7344 7345 /// Builds a using declaration. 7346 /// 7347 /// \param IsInstantiation - Whether this call arises from an 7348 /// instantiation of an unresolved using declaration. We treat 7349 /// the lookup differently for these declarations. 7350 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 7351 SourceLocation UsingLoc, 7352 CXXScopeSpec &SS, 7353 const DeclarationNameInfo &NameInfo, 7354 AttributeList *AttrList, 7355 bool IsInstantiation, 7356 bool HasTypenameKeyword, 7357 SourceLocation TypenameLoc) { 7358 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 7359 SourceLocation IdentLoc = NameInfo.getLoc(); 7360 assert(IdentLoc.isValid() && "Invalid TargetName location."); 7361 7362 // FIXME: We ignore attributes for now. 7363 7364 if (SS.isEmpty()) { 7365 Diag(IdentLoc, diag::err_using_requires_qualname); 7366 return 0; 7367 } 7368 7369 // Do the redeclaration lookup in the current scope. 7370 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 7371 ForRedeclaration); 7372 Previous.setHideTags(false); 7373 if (S) { 7374 LookupName(Previous, S); 7375 7376 // It is really dumb that we have to do this. 7377 LookupResult::Filter F = Previous.makeFilter(); 7378 while (F.hasNext()) { 7379 NamedDecl *D = F.next(); 7380 if (!isDeclInScope(D, CurContext, S)) 7381 F.erase(); 7382 } 7383 F.done(); 7384 } else { 7385 assert(IsInstantiation && "no scope in non-instantiation"); 7386 assert(CurContext->isRecord() && "scope not record in instantiation"); 7387 LookupQualifiedName(Previous, CurContext); 7388 } 7389 7390 // Check for invalid redeclarations. 7391 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7392 SS, IdentLoc, Previous)) 7393 return 0; 7394 7395 // Check for bad qualifiers. 7396 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 7397 return 0; 7398 7399 DeclContext *LookupContext = computeDeclContext(SS); 7400 NamedDecl *D; 7401 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7402 if (!LookupContext) { 7403 if (HasTypenameKeyword) { 7404 // FIXME: not all declaration name kinds are legal here 7405 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7406 UsingLoc, TypenameLoc, 7407 QualifierLoc, 7408 IdentLoc, NameInfo.getName()); 7409 } else { 7410 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7411 QualifierLoc, NameInfo); 7412 } 7413 } else { 7414 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 7415 NameInfo, HasTypenameKeyword); 7416 } 7417 D->setAccess(AS); 7418 CurContext->addDecl(D); 7419 7420 if (!LookupContext) return D; 7421 UsingDecl *UD = cast<UsingDecl>(D); 7422 7423 if (RequireCompleteDeclContext(SS, LookupContext)) { 7424 UD->setInvalidDecl(); 7425 return UD; 7426 } 7427 7428 // The normal rules do not apply to inheriting constructor declarations. 7429 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7430 if (CheckInheritingConstructorUsingDecl(UD)) 7431 UD->setInvalidDecl(); 7432 return UD; 7433 } 7434 7435 // Otherwise, look up the target name. 7436 7437 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7438 7439 // Unlike most lookups, we don't always want to hide tag 7440 // declarations: tag names are visible through the using declaration 7441 // even if hidden by ordinary names, *except* in a dependent context 7442 // where it's important for the sanity of two-phase lookup. 7443 if (!IsInstantiation) 7444 R.setHideTags(false); 7445 7446 // For the purposes of this lookup, we have a base object type 7447 // equal to that of the current context. 7448 if (CurContext->isRecord()) { 7449 R.setBaseObjectType( 7450 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7451 } 7452 7453 LookupQualifiedName(R, LookupContext); 7454 7455 // Try to correct typos if possible. 7456 if (R.empty()) { 7457 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, 7458 CurContext->isRecord()); 7459 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(), 7460 R.getLookupKind(), S, &SS, CCC)){ 7461 // We reject any correction for which ND would be NULL. 7462 NamedDecl *ND = Corrected.getCorrectionDecl(); 7463 R.setLookupName(Corrected.getCorrection()); 7464 R.addDecl(ND); 7465 // We reject candidates where DroppedSpecifier == true, hence the 7466 // literal '0' below. 7467 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 7468 << NameInfo.getName() << LookupContext << 0 7469 << SS.getRange()); 7470 } else { 7471 Diag(IdentLoc, diag::err_no_member) 7472 << NameInfo.getName() << LookupContext << SS.getRange(); 7473 UD->setInvalidDecl(); 7474 return UD; 7475 } 7476 } 7477 7478 if (R.isAmbiguous()) { 7479 UD->setInvalidDecl(); 7480 return UD; 7481 } 7482 7483 if (HasTypenameKeyword) { 7484 // If we asked for a typename and got a non-type decl, error out. 7485 if (!R.getAsSingle<TypeDecl>()) { 7486 Diag(IdentLoc, diag::err_using_typename_non_type); 7487 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7488 Diag((*I)->getUnderlyingDecl()->getLocation(), 7489 diag::note_using_decl_target); 7490 UD->setInvalidDecl(); 7491 return UD; 7492 } 7493 } else { 7494 // If we asked for a non-typename and we got a type, error out, 7495 // but only if this is an instantiation of an unresolved using 7496 // decl. Otherwise just silently find the type name. 7497 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7498 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7499 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7500 UD->setInvalidDecl(); 7501 return UD; 7502 } 7503 } 7504 7505 // C++0x N2914 [namespace.udecl]p6: 7506 // A using-declaration shall not name a namespace. 7507 if (R.getAsSingle<NamespaceDecl>()) { 7508 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7509 << SS.getRange(); 7510 UD->setInvalidDecl(); 7511 return UD; 7512 } 7513 7514 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7515 UsingShadowDecl *PrevDecl = 0; 7516 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 7517 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 7518 } 7519 7520 return UD; 7521 } 7522 7523 /// Additional checks for a using declaration referring to a constructor name. 7524 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7525 assert(!UD->hasTypename() && "expecting a constructor name"); 7526 7527 const Type *SourceType = UD->getQualifier()->getAsType(); 7528 assert(SourceType && 7529 "Using decl naming constructor doesn't have type in scope spec."); 7530 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7531 7532 // Check whether the named type is a direct base class. 7533 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 7534 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 7535 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 7536 BaseIt != BaseE; ++BaseIt) { 7537 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 7538 if (CanonicalSourceType == BaseType) 7539 break; 7540 if (BaseIt->getType()->isDependentType()) 7541 break; 7542 } 7543 7544 if (BaseIt == BaseE) { 7545 // Did not find SourceType in the bases. 7546 Diag(UD->getUsingLoc(), 7547 diag::err_using_decl_constructor_not_in_direct_base) 7548 << UD->getNameInfo().getSourceRange() 7549 << QualType(SourceType, 0) << TargetClass; 7550 return true; 7551 } 7552 7553 if (!CurContext->isDependentContext()) 7554 BaseIt->setInheritConstructors(); 7555 7556 return false; 7557 } 7558 7559 /// Checks that the given using declaration is not an invalid 7560 /// redeclaration. Note that this is checking only for the using decl 7561 /// itself, not for any ill-formedness among the UsingShadowDecls. 7562 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7563 bool HasTypenameKeyword, 7564 const CXXScopeSpec &SS, 7565 SourceLocation NameLoc, 7566 const LookupResult &Prev) { 7567 // C++03 [namespace.udecl]p8: 7568 // C++0x [namespace.udecl]p10: 7569 // A using-declaration is a declaration and can therefore be used 7570 // repeatedly where (and only where) multiple declarations are 7571 // allowed. 7572 // 7573 // That's in non-member contexts. 7574 if (!CurContext->getRedeclContext()->isRecord()) 7575 return false; 7576 7577 NestedNameSpecifier *Qual = SS.getScopeRep(); 7578 7579 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7580 NamedDecl *D = *I; 7581 7582 bool DTypename; 7583 NestedNameSpecifier *DQual; 7584 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7585 DTypename = UD->hasTypename(); 7586 DQual = UD->getQualifier(); 7587 } else if (UnresolvedUsingValueDecl *UD 7588 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7589 DTypename = false; 7590 DQual = UD->getQualifier(); 7591 } else if (UnresolvedUsingTypenameDecl *UD 7592 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7593 DTypename = true; 7594 DQual = UD->getQualifier(); 7595 } else continue; 7596 7597 // using decls differ if one says 'typename' and the other doesn't. 7598 // FIXME: non-dependent using decls? 7599 if (HasTypenameKeyword != DTypename) continue; 7600 7601 // using decls differ if they name different scopes (but note that 7602 // template instantiation can cause this check to trigger when it 7603 // didn't before instantiation). 7604 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7605 Context.getCanonicalNestedNameSpecifier(DQual)) 7606 continue; 7607 7608 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7609 Diag(D->getLocation(), diag::note_using_decl) << 1; 7610 return true; 7611 } 7612 7613 return false; 7614 } 7615 7616 7617 /// Checks that the given nested-name qualifier used in a using decl 7618 /// in the current context is appropriately related to the current 7619 /// scope. If an error is found, diagnoses it and returns true. 7620 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7621 const CXXScopeSpec &SS, 7622 const DeclarationNameInfo &NameInfo, 7623 SourceLocation NameLoc) { 7624 DeclContext *NamedContext = computeDeclContext(SS); 7625 7626 if (!CurContext->isRecord()) { 7627 // C++03 [namespace.udecl]p3: 7628 // C++0x [namespace.udecl]p8: 7629 // A using-declaration for a class member shall be a member-declaration. 7630 7631 // If we weren't able to compute a valid scope, it must be a 7632 // dependent class scope. 7633 if (!NamedContext || NamedContext->isRecord()) { 7634 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext); 7635 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 7636 RD = 0; 7637 7638 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7639 << SS.getRange(); 7640 7641 // If we have a complete, non-dependent source type, try to suggest a 7642 // way to get the same effect. 7643 if (!RD) 7644 return true; 7645 7646 // Find what this using-declaration was referring to. 7647 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7648 R.setHideTags(false); 7649 R.suppressDiagnostics(); 7650 LookupQualifiedName(R, RD); 7651 7652 if (R.getAsSingle<TypeDecl>()) { 7653 if (getLangOpts().CPlusPlus11) { 7654 // Convert 'using X::Y;' to 'using Y = X::Y;'. 7655 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 7656 << 0 // alias declaration 7657 << FixItHint::CreateInsertion(SS.getBeginLoc(), 7658 NameInfo.getName().getAsString() + 7659 " = "); 7660 } else { 7661 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 7662 SourceLocation InsertLoc = 7663 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 7664 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 7665 << 1 // typedef declaration 7666 << FixItHint::CreateReplacement(UsingLoc, "typedef") 7667 << FixItHint::CreateInsertion( 7668 InsertLoc, " " + NameInfo.getName().getAsString()); 7669 } 7670 } else if (R.getAsSingle<VarDecl>()) { 7671 // Don't provide a fixit outside C++11 mode; we don't want to suggest 7672 // repeating the type of the static data member here. 7673 FixItHint FixIt; 7674 if (getLangOpts().CPlusPlus11) { 7675 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 7676 FixIt = FixItHint::CreateReplacement( 7677 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 7678 } 7679 7680 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 7681 << 2 // reference declaration 7682 << FixIt; 7683 } 7684 return true; 7685 } 7686 7687 // Otherwise, everything is known to be fine. 7688 return false; 7689 } 7690 7691 // The current scope is a record. 7692 7693 // If the named context is dependent, we can't decide much. 7694 if (!NamedContext) { 7695 // FIXME: in C++0x, we can diagnose if we can prove that the 7696 // nested-name-specifier does not refer to a base class, which is 7697 // still possible in some cases. 7698 7699 // Otherwise we have to conservatively report that things might be 7700 // okay. 7701 return false; 7702 } 7703 7704 if (!NamedContext->isRecord()) { 7705 // Ideally this would point at the last name in the specifier, 7706 // but we don't have that level of source info. 7707 Diag(SS.getRange().getBegin(), 7708 diag::err_using_decl_nested_name_specifier_is_not_class) 7709 << SS.getScopeRep() << SS.getRange(); 7710 return true; 7711 } 7712 7713 if (!NamedContext->isDependentContext() && 7714 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7715 return true; 7716 7717 if (getLangOpts().CPlusPlus11) { 7718 // C++0x [namespace.udecl]p3: 7719 // In a using-declaration used as a member-declaration, the 7720 // nested-name-specifier shall name a base class of the class 7721 // being defined. 7722 7723 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7724 cast<CXXRecordDecl>(NamedContext))) { 7725 if (CurContext == NamedContext) { 7726 Diag(NameLoc, 7727 diag::err_using_decl_nested_name_specifier_is_current_class) 7728 << SS.getRange(); 7729 return true; 7730 } 7731 7732 Diag(SS.getRange().getBegin(), 7733 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7734 << SS.getScopeRep() 7735 << cast<CXXRecordDecl>(CurContext) 7736 << SS.getRange(); 7737 return true; 7738 } 7739 7740 return false; 7741 } 7742 7743 // C++03 [namespace.udecl]p4: 7744 // A using-declaration used as a member-declaration shall refer 7745 // to a member of a base class of the class being defined [etc.]. 7746 7747 // Salient point: SS doesn't have to name a base class as long as 7748 // lookup only finds members from base classes. Therefore we can 7749 // diagnose here only if we can prove that that can't happen, 7750 // i.e. if the class hierarchies provably don't intersect. 7751 7752 // TODO: it would be nice if "definitely valid" results were cached 7753 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7754 // need to be repeated. 7755 7756 struct UserData { 7757 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7758 7759 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7760 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7761 Data->Bases.insert(Base); 7762 return true; 7763 } 7764 7765 bool hasDependentBases(const CXXRecordDecl *Class) { 7766 return !Class->forallBases(collect, this); 7767 } 7768 7769 /// Returns true if the base is dependent or is one of the 7770 /// accumulated base classes. 7771 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7772 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7773 return !Data->Bases.count(Base); 7774 } 7775 7776 bool mightShareBases(const CXXRecordDecl *Class) { 7777 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7778 } 7779 }; 7780 7781 UserData Data; 7782 7783 // Returns false if we find a dependent base. 7784 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7785 return false; 7786 7787 // Returns false if the class has a dependent base or if it or one 7788 // of its bases is present in the base set of the current context. 7789 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7790 return false; 7791 7792 Diag(SS.getRange().getBegin(), 7793 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7794 << SS.getScopeRep() 7795 << cast<CXXRecordDecl>(CurContext) 7796 << SS.getRange(); 7797 7798 return true; 7799 } 7800 7801 Decl *Sema::ActOnAliasDeclaration(Scope *S, 7802 AccessSpecifier AS, 7803 MultiTemplateParamsArg TemplateParamLists, 7804 SourceLocation UsingLoc, 7805 UnqualifiedId &Name, 7806 AttributeList *AttrList, 7807 TypeResult Type) { 7808 // Skip up to the relevant declaration scope. 7809 while (S->getFlags() & Scope::TemplateParamScope) 7810 S = S->getParent(); 7811 assert((S->getFlags() & Scope::DeclScope) && 7812 "got alias-declaration outside of declaration scope"); 7813 7814 if (Type.isInvalid()) 7815 return 0; 7816 7817 bool Invalid = false; 7818 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7819 TypeSourceInfo *TInfo = 0; 7820 GetTypeFromParser(Type.get(), &TInfo); 7821 7822 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7823 return 0; 7824 7825 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7826 UPPC_DeclarationType)) { 7827 Invalid = true; 7828 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7829 TInfo->getTypeLoc().getBeginLoc()); 7830 } 7831 7832 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7833 LookupName(Previous, S); 7834 7835 // Warn about shadowing the name of a template parameter. 7836 if (Previous.isSingleResult() && 7837 Previous.getFoundDecl()->isTemplateParameter()) { 7838 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7839 Previous.clear(); 7840 } 7841 7842 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7843 "name in alias declaration must be an identifier"); 7844 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7845 Name.StartLocation, 7846 Name.Identifier, TInfo); 7847 7848 NewTD->setAccess(AS); 7849 7850 if (Invalid) 7851 NewTD->setInvalidDecl(); 7852 7853 ProcessDeclAttributeList(S, NewTD, AttrList); 7854 7855 CheckTypedefForVariablyModifiedType(S, NewTD); 7856 Invalid |= NewTD->isInvalidDecl(); 7857 7858 bool Redeclaration = false; 7859 7860 NamedDecl *NewND; 7861 if (TemplateParamLists.size()) { 7862 TypeAliasTemplateDecl *OldDecl = 0; 7863 TemplateParameterList *OldTemplateParams = 0; 7864 7865 if (TemplateParamLists.size() != 1) { 7866 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7867 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7868 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7869 } 7870 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7871 7872 // Only consider previous declarations in the same scope. 7873 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7874 /*ExplicitInstantiationOrSpecialization*/false); 7875 if (!Previous.empty()) { 7876 Redeclaration = true; 7877 7878 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7879 if (!OldDecl && !Invalid) { 7880 Diag(UsingLoc, diag::err_redefinition_different_kind) 7881 << Name.Identifier; 7882 7883 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7884 if (OldD->getLocation().isValid()) 7885 Diag(OldD->getLocation(), diag::note_previous_definition); 7886 7887 Invalid = true; 7888 } 7889 7890 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7891 if (TemplateParameterListsAreEqual(TemplateParams, 7892 OldDecl->getTemplateParameters(), 7893 /*Complain=*/true, 7894 TPL_TemplateMatch)) 7895 OldTemplateParams = OldDecl->getTemplateParameters(); 7896 else 7897 Invalid = true; 7898 7899 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7900 if (!Invalid && 7901 !Context.hasSameType(OldTD->getUnderlyingType(), 7902 NewTD->getUnderlyingType())) { 7903 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7904 // but we can't reasonably accept it. 7905 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7906 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7907 if (OldTD->getLocation().isValid()) 7908 Diag(OldTD->getLocation(), diag::note_previous_definition); 7909 Invalid = true; 7910 } 7911 } 7912 } 7913 7914 // Merge any previous default template arguments into our parameters, 7915 // and check the parameter list. 7916 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7917 TPC_TypeAliasTemplate)) 7918 return 0; 7919 7920 TypeAliasTemplateDecl *NewDecl = 7921 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7922 Name.Identifier, TemplateParams, 7923 NewTD); 7924 7925 NewDecl->setAccess(AS); 7926 7927 if (Invalid) 7928 NewDecl->setInvalidDecl(); 7929 else if (OldDecl) 7930 NewDecl->setPreviousDecl(OldDecl); 7931 7932 NewND = NewDecl; 7933 } else { 7934 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7935 NewND = NewTD; 7936 } 7937 7938 if (!Redeclaration) 7939 PushOnScopeChains(NewND, S); 7940 7941 ActOnDocumentableDecl(NewND); 7942 return NewND; 7943 } 7944 7945 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7946 SourceLocation NamespaceLoc, 7947 SourceLocation AliasLoc, 7948 IdentifierInfo *Alias, 7949 CXXScopeSpec &SS, 7950 SourceLocation IdentLoc, 7951 IdentifierInfo *Ident) { 7952 7953 // Lookup the namespace name. 7954 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7955 LookupParsedName(R, S, &SS); 7956 7957 // Check if we have a previous declaration with the same name. 7958 NamedDecl *PrevDecl 7959 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7960 ForRedeclaration); 7961 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7962 PrevDecl = 0; 7963 7964 if (PrevDecl) { 7965 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7966 // We already have an alias with the same name that points to the same 7967 // namespace, so don't create a new one. 7968 // FIXME: At some point, we'll want to create the (redundant) 7969 // declaration to maintain better source information. 7970 if (!R.isAmbiguous() && !R.empty() && 7971 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7972 return 0; 7973 } 7974 7975 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7976 diag::err_redefinition_different_kind; 7977 Diag(AliasLoc, DiagID) << Alias; 7978 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7979 return 0; 7980 } 7981 7982 if (R.isAmbiguous()) 7983 return 0; 7984 7985 if (R.empty()) { 7986 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 7987 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7988 return 0; 7989 } 7990 } 7991 7992 NamespaceAliasDecl *AliasDecl = 7993 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 7994 Alias, SS.getWithLocInContext(Context), 7995 IdentLoc, R.getFoundDecl()); 7996 7997 PushOnScopeChains(AliasDecl, S); 7998 return AliasDecl; 7999 } 8000 8001 Sema::ImplicitExceptionSpecification 8002 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8003 CXXMethodDecl *MD) { 8004 CXXRecordDecl *ClassDecl = MD->getParent(); 8005 8006 // C++ [except.spec]p14: 8007 // An implicitly declared special member function (Clause 12) shall have an 8008 // exception-specification. [...] 8009 ImplicitExceptionSpecification ExceptSpec(*this); 8010 if (ClassDecl->isInvalidDecl()) 8011 return ExceptSpec; 8012 8013 // Direct base-class constructors. 8014 for (const auto &B : ClassDecl->bases()) { 8015 if (B.isVirtual()) // Handled below. 8016 continue; 8017 8018 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8019 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8020 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8021 // If this is a deleted function, add it anyway. This might be conformant 8022 // with the standard. This might not. I'm not sure. It might not matter. 8023 if (Constructor) 8024 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8025 } 8026 } 8027 8028 // Virtual base-class constructors. 8029 for (const auto &B : ClassDecl->vbases()) { 8030 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8031 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8032 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8033 // If this is a deleted function, add it anyway. This might be conformant 8034 // with the standard. This might not. I'm not sure. It might not matter. 8035 if (Constructor) 8036 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8037 } 8038 } 8039 8040 // Field constructors. 8041 for (const auto *F : ClassDecl->fields()) { 8042 if (F->hasInClassInitializer()) { 8043 if (Expr *E = F->getInClassInitializer()) 8044 ExceptSpec.CalledExpr(E); 8045 else if (!F->isInvalidDecl()) 8046 // DR1351: 8047 // If the brace-or-equal-initializer of a non-static data member 8048 // invokes a defaulted default constructor of its class or of an 8049 // enclosing class in a potentially evaluated subexpression, the 8050 // program is ill-formed. 8051 // 8052 // This resolution is unworkable: the exception specification of the 8053 // default constructor can be needed in an unevaluated context, in 8054 // particular, in the operand of a noexcept-expression, and we can be 8055 // unable to compute an exception specification for an enclosed class. 8056 // 8057 // We do not allow an in-class initializer to require the evaluation 8058 // of the exception specification for any in-class initializer whose 8059 // definition is not lexically complete. 8060 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 8061 } else if (const RecordType *RecordTy 8062 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8063 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8064 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8065 // If this is a deleted function, add it anyway. This might be conformant 8066 // with the standard. This might not. I'm not sure. It might not matter. 8067 // In particular, the problem is that this function never gets called. It 8068 // might just be ill-formed because this function attempts to refer to 8069 // a deleted function here. 8070 if (Constructor) 8071 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8072 } 8073 } 8074 8075 return ExceptSpec; 8076 } 8077 8078 Sema::ImplicitExceptionSpecification 8079 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8080 CXXRecordDecl *ClassDecl = CD->getParent(); 8081 8082 // C++ [except.spec]p14: 8083 // An inheriting constructor [...] shall have an exception-specification. [...] 8084 ImplicitExceptionSpecification ExceptSpec(*this); 8085 if (ClassDecl->isInvalidDecl()) 8086 return ExceptSpec; 8087 8088 // Inherited constructor. 8089 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8090 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8091 // FIXME: Copying or moving the parameters could add extra exceptions to the 8092 // set, as could the default arguments for the inherited constructor. This 8093 // will be addressed when we implement the resolution of core issue 1351. 8094 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8095 8096 // Direct base-class constructors. 8097 for (const auto &B : ClassDecl->bases()) { 8098 if (B.isVirtual()) // Handled below. 8099 continue; 8100 8101 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8102 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8103 if (BaseClassDecl == InheritedDecl) 8104 continue; 8105 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8106 if (Constructor) 8107 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8108 } 8109 } 8110 8111 // Virtual base-class constructors. 8112 for (const auto &B : ClassDecl->vbases()) { 8113 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8114 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8115 if (BaseClassDecl == InheritedDecl) 8116 continue; 8117 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8118 if (Constructor) 8119 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8120 } 8121 } 8122 8123 // Field constructors. 8124 for (const auto *F : ClassDecl->fields()) { 8125 if (F->hasInClassInitializer()) { 8126 if (Expr *E = F->getInClassInitializer()) 8127 ExceptSpec.CalledExpr(E); 8128 else if (!F->isInvalidDecl()) 8129 Diag(CD->getLocation(), 8130 diag::err_in_class_initializer_references_def_ctor) << CD; 8131 } else if (const RecordType *RecordTy 8132 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8133 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8134 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8135 if (Constructor) 8136 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8137 } 8138 } 8139 8140 return ExceptSpec; 8141 } 8142 8143 namespace { 8144 /// RAII object to register a special member as being currently declared. 8145 struct DeclaringSpecialMember { 8146 Sema &S; 8147 Sema::SpecialMemberDecl D; 8148 bool WasAlreadyBeingDeclared; 8149 8150 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8151 : S(S), D(RD, CSM) { 8152 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 8153 if (WasAlreadyBeingDeclared) 8154 // This almost never happens, but if it does, ensure that our cache 8155 // doesn't contain a stale result. 8156 S.SpecialMemberCache.clear(); 8157 8158 // FIXME: Register a note to be produced if we encounter an error while 8159 // declaring the special member. 8160 } 8161 ~DeclaringSpecialMember() { 8162 if (!WasAlreadyBeingDeclared) 8163 S.SpecialMembersBeingDeclared.erase(D); 8164 } 8165 8166 /// \brief Are we already trying to declare this special member? 8167 bool isAlreadyBeingDeclared() const { 8168 return WasAlreadyBeingDeclared; 8169 } 8170 }; 8171 } 8172 8173 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8174 CXXRecordDecl *ClassDecl) { 8175 // C++ [class.ctor]p5: 8176 // A default constructor for a class X is a constructor of class X 8177 // that can be called without an argument. If there is no 8178 // user-declared constructor for class X, a default constructor is 8179 // implicitly declared. An implicitly-declared default constructor 8180 // is an inline public member of its class. 8181 assert(ClassDecl->needsImplicitDefaultConstructor() && 8182 "Should not build implicit default constructor!"); 8183 8184 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8185 if (DSM.isAlreadyBeingDeclared()) 8186 return 0; 8187 8188 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8189 CXXDefaultConstructor, 8190 false); 8191 8192 // Create the actual constructor declaration. 8193 CanQualType ClassType 8194 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8195 SourceLocation ClassLoc = ClassDecl->getLocation(); 8196 DeclarationName Name 8197 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8198 DeclarationNameInfo NameInfo(Name, ClassLoc); 8199 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8200 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 8201 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8202 Constexpr); 8203 DefaultCon->setAccess(AS_public); 8204 DefaultCon->setDefaulted(); 8205 DefaultCon->setImplicit(); 8206 8207 // Build an exception specification pointing back at this constructor. 8208 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8209 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8210 8211 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8212 // constructors is easy to compute. 8213 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8214 8215 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8216 SetDeclDeleted(DefaultCon, ClassLoc); 8217 8218 // Note that we have declared this constructor. 8219 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8220 8221 if (Scope *S = getScopeForContext(ClassDecl)) 8222 PushOnScopeChains(DefaultCon, S, false); 8223 ClassDecl->addDecl(DefaultCon); 8224 8225 return DefaultCon; 8226 } 8227 8228 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8229 CXXConstructorDecl *Constructor) { 8230 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8231 !Constructor->doesThisDeclarationHaveABody() && 8232 !Constructor->isDeleted()) && 8233 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8234 8235 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8236 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8237 8238 SynthesizedFunctionScope Scope(*this, Constructor); 8239 DiagnosticErrorTrap Trap(Diags); 8240 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8241 Trap.hasErrorOccurred()) { 8242 Diag(CurrentLocation, diag::note_member_synthesized_at) 8243 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8244 Constructor->setInvalidDecl(); 8245 return; 8246 } 8247 8248 SourceLocation Loc = Constructor->getLocation(); 8249 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8250 8251 Constructor->markUsed(Context); 8252 MarkVTableUsed(CurrentLocation, ClassDecl); 8253 8254 if (ASTMutationListener *L = getASTMutationListener()) { 8255 L->CompletedImplicitDefinition(Constructor); 8256 } 8257 8258 DiagnoseUninitializedFields(*this, Constructor); 8259 } 8260 8261 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8262 // Perform any delayed checks on exception specifications. 8263 CheckDelayedMemberExceptionSpecs(); 8264 } 8265 8266 namespace { 8267 /// Information on inheriting constructors to declare. 8268 class InheritingConstructorInfo { 8269 public: 8270 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8271 : SemaRef(SemaRef), Derived(Derived) { 8272 // Mark the constructors that we already have in the derived class. 8273 // 8274 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8275 // unless there is a user-declared constructor with the same signature in 8276 // the class where the using-declaration appears. 8277 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8278 } 8279 8280 void inheritAll(CXXRecordDecl *RD) { 8281 visitAll(RD, &InheritingConstructorInfo::inherit); 8282 } 8283 8284 private: 8285 /// Information about an inheriting constructor. 8286 struct InheritingConstructor { 8287 InheritingConstructor() 8288 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {} 8289 8290 /// If \c true, a constructor with this signature is already declared 8291 /// in the derived class. 8292 bool DeclaredInDerived; 8293 8294 /// The constructor which is inherited. 8295 const CXXConstructorDecl *BaseCtor; 8296 8297 /// The derived constructor we declared. 8298 CXXConstructorDecl *DerivedCtor; 8299 }; 8300 8301 /// Inheriting constructors with a given canonical type. There can be at 8302 /// most one such non-template constructor, and any number of templated 8303 /// constructors. 8304 struct InheritingConstructorsForType { 8305 InheritingConstructor NonTemplate; 8306 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8307 Templates; 8308 8309 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8310 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8311 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8312 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8313 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8314 false, S.TPL_TemplateMatch)) 8315 return Templates[I].second; 8316 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8317 return Templates.back().second; 8318 } 8319 8320 return NonTemplate; 8321 } 8322 }; 8323 8324 /// Get or create the inheriting constructor record for a constructor. 8325 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8326 QualType CtorType) { 8327 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8328 .getEntry(SemaRef, Ctor); 8329 } 8330 8331 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8332 8333 /// Process all constructors for a class. 8334 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8335 for (const auto *Ctor : RD->ctors()) 8336 (this->*Callback)(Ctor); 8337 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8338 I(RD->decls_begin()), E(RD->decls_end()); 8339 I != E; ++I) { 8340 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8341 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8342 (this->*Callback)(CD); 8343 } 8344 } 8345 8346 /// Note that a constructor (or constructor template) was declared in Derived. 8347 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8348 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8349 } 8350 8351 /// Inherit a single constructor. 8352 void inherit(const CXXConstructorDecl *Ctor) { 8353 const FunctionProtoType *CtorType = 8354 Ctor->getType()->castAs<FunctionProtoType>(); 8355 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes()); 8356 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8357 8358 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8359 8360 // Core issue (no number yet): the ellipsis is always discarded. 8361 if (EPI.Variadic) { 8362 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8363 SemaRef.Diag(Ctor->getLocation(), 8364 diag::note_using_decl_constructor_ellipsis); 8365 EPI.Variadic = false; 8366 } 8367 8368 // Declare a constructor for each number of parameters. 8369 // 8370 // C++11 [class.inhctor]p1: 8371 // The candidate set of inherited constructors from the class X named in 8372 // the using-declaration consists of [... modulo defects ...] for each 8373 // constructor or constructor template of X, the set of constructors or 8374 // constructor templates that results from omitting any ellipsis parameter 8375 // specification and successively omitting parameters with a default 8376 // argument from the end of the parameter-type-list 8377 unsigned MinParams = minParamsToInherit(Ctor); 8378 unsigned Params = Ctor->getNumParams(); 8379 if (Params >= MinParams) { 8380 do 8381 declareCtor(UsingLoc, Ctor, 8382 SemaRef.Context.getFunctionType( 8383 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 8384 while (Params > MinParams && 8385 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8386 } 8387 } 8388 8389 /// Find the using-declaration which specified that we should inherit the 8390 /// constructors of \p Base. 8391 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8392 // No fancy lookup required; just look for the base constructor name 8393 // directly within the derived class. 8394 ASTContext &Context = SemaRef.Context; 8395 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8396 Context.getCanonicalType(Context.getRecordType(Base))); 8397 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8398 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8399 } 8400 8401 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8402 // C++11 [class.inhctor]p3: 8403 // [F]or each constructor template in the candidate set of inherited 8404 // constructors, a constructor template is implicitly declared 8405 if (Ctor->getDescribedFunctionTemplate()) 8406 return 0; 8407 8408 // For each non-template constructor in the candidate set of inherited 8409 // constructors other than a constructor having no parameters or a 8410 // copy/move constructor having a single parameter, a constructor is 8411 // implicitly declared [...] 8412 if (Ctor->getNumParams() == 0) 8413 return 1; 8414 if (Ctor->isCopyOrMoveConstructor()) 8415 return 2; 8416 8417 // Per discussion on core reflector, never inherit a constructor which 8418 // would become a default, copy, or move constructor of Derived either. 8419 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8420 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8421 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8422 } 8423 8424 /// Declare a single inheriting constructor, inheriting the specified 8425 /// constructor, with the given type. 8426 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8427 QualType DerivedType) { 8428 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8429 8430 // C++11 [class.inhctor]p3: 8431 // ... a constructor is implicitly declared with the same constructor 8432 // characteristics unless there is a user-declared constructor with 8433 // the same signature in the class where the using-declaration appears 8434 if (Entry.DeclaredInDerived) 8435 return; 8436 8437 // C++11 [class.inhctor]p7: 8438 // If two using-declarations declare inheriting constructors with the 8439 // same signature, the program is ill-formed 8440 if (Entry.DerivedCtor) { 8441 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8442 // Only diagnose this once per constructor. 8443 if (Entry.DerivedCtor->isInvalidDecl()) 8444 return; 8445 Entry.DerivedCtor->setInvalidDecl(); 8446 8447 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8448 SemaRef.Diag(BaseCtor->getLocation(), 8449 diag::note_using_decl_constructor_conflict_current_ctor); 8450 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8451 diag::note_using_decl_constructor_conflict_previous_ctor); 8452 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8453 diag::note_using_decl_constructor_conflict_previous_using); 8454 } else { 8455 // Core issue (no number): if the same inheriting constructor is 8456 // produced by multiple base class constructors from the same base 8457 // class, the inheriting constructor is defined as deleted. 8458 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8459 } 8460 8461 return; 8462 } 8463 8464 ASTContext &Context = SemaRef.Context; 8465 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8466 Context.getCanonicalType(Context.getRecordType(Derived))); 8467 DeclarationNameInfo NameInfo(Name, UsingLoc); 8468 8469 TemplateParameterList *TemplateParams = 0; 8470 if (const FunctionTemplateDecl *FTD = 8471 BaseCtor->getDescribedFunctionTemplate()) { 8472 TemplateParams = FTD->getTemplateParameters(); 8473 // We're reusing template parameters from a different DeclContext. This 8474 // is questionable at best, but works out because the template depth in 8475 // both places is guaranteed to be 0. 8476 // FIXME: Rebuild the template parameters in the new context, and 8477 // transform the function type to refer to them. 8478 } 8479 8480 // Build type source info pointing at the using-declaration. This is 8481 // required by template instantiation. 8482 TypeSourceInfo *TInfo = 8483 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8484 FunctionProtoTypeLoc ProtoLoc = 8485 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8486 8487 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8488 Context, Derived, UsingLoc, NameInfo, DerivedType, 8489 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8490 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8491 8492 // Build an unevaluated exception specification for this constructor. 8493 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8494 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8495 EPI.ExceptionSpecType = EST_Unevaluated; 8496 EPI.ExceptionSpecDecl = DerivedCtor; 8497 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 8498 FPT->getParamTypes(), EPI)); 8499 8500 // Build the parameter declarations. 8501 SmallVector<ParmVarDecl *, 16> ParamDecls; 8502 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 8503 TypeSourceInfo *TInfo = 8504 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 8505 ParmVarDecl *PD = ParmVarDecl::Create( 8506 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0, 8507 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/0); 8508 PD->setScopeInfo(0, I); 8509 PD->setImplicit(); 8510 ParamDecls.push_back(PD); 8511 ProtoLoc.setParam(I, PD); 8512 } 8513 8514 // Set up the new constructor. 8515 DerivedCtor->setAccess(BaseCtor->getAccess()); 8516 DerivedCtor->setParams(ParamDecls); 8517 DerivedCtor->setInheritedConstructor(BaseCtor); 8518 if (BaseCtor->isDeleted()) 8519 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8520 8521 // If this is a constructor template, build the template declaration. 8522 if (TemplateParams) { 8523 FunctionTemplateDecl *DerivedTemplate = 8524 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8525 TemplateParams, DerivedCtor); 8526 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8527 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8528 Derived->addDecl(DerivedTemplate); 8529 } else { 8530 Derived->addDecl(DerivedCtor); 8531 } 8532 8533 Entry.BaseCtor = BaseCtor; 8534 Entry.DerivedCtor = DerivedCtor; 8535 } 8536 8537 Sema &SemaRef; 8538 CXXRecordDecl *Derived; 8539 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8540 MapType Map; 8541 }; 8542 } 8543 8544 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8545 // Defer declaring the inheriting constructors until the class is 8546 // instantiated. 8547 if (ClassDecl->isDependentContext()) 8548 return; 8549 8550 // Find base classes from which we might inherit constructors. 8551 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8552 for (const auto &BaseIt : ClassDecl->bases()) 8553 if (BaseIt.getInheritConstructors()) 8554 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 8555 8556 // Go no further if we're not inheriting any constructors. 8557 if (InheritedBases.empty()) 8558 return; 8559 8560 // Declare the inherited constructors. 8561 InheritingConstructorInfo ICI(*this, ClassDecl); 8562 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8563 ICI.inheritAll(InheritedBases[I]); 8564 } 8565 8566 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8567 CXXConstructorDecl *Constructor) { 8568 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8569 assert(Constructor->getInheritedConstructor() && 8570 !Constructor->doesThisDeclarationHaveABody() && 8571 !Constructor->isDeleted()); 8572 8573 SynthesizedFunctionScope Scope(*this, Constructor); 8574 DiagnosticErrorTrap Trap(Diags); 8575 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8576 Trap.hasErrorOccurred()) { 8577 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8578 << Context.getTagDeclType(ClassDecl); 8579 Constructor->setInvalidDecl(); 8580 return; 8581 } 8582 8583 SourceLocation Loc = Constructor->getLocation(); 8584 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8585 8586 Constructor->markUsed(Context); 8587 MarkVTableUsed(CurrentLocation, ClassDecl); 8588 8589 if (ASTMutationListener *L = getASTMutationListener()) { 8590 L->CompletedImplicitDefinition(Constructor); 8591 } 8592 } 8593 8594 8595 Sema::ImplicitExceptionSpecification 8596 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8597 CXXRecordDecl *ClassDecl = MD->getParent(); 8598 8599 // C++ [except.spec]p14: 8600 // An implicitly declared special member function (Clause 12) shall have 8601 // an exception-specification. 8602 ImplicitExceptionSpecification ExceptSpec(*this); 8603 if (ClassDecl->isInvalidDecl()) 8604 return ExceptSpec; 8605 8606 // Direct base-class destructors. 8607 for (const auto &B : ClassDecl->bases()) { 8608 if (B.isVirtual()) // Handled below. 8609 continue; 8610 8611 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 8612 ExceptSpec.CalledDecl(B.getLocStart(), 8613 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8614 } 8615 8616 // Virtual base-class destructors. 8617 for (const auto &B : ClassDecl->vbases()) { 8618 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 8619 ExceptSpec.CalledDecl(B.getLocStart(), 8620 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8621 } 8622 8623 // Field destructors. 8624 for (const auto *F : ClassDecl->fields()) { 8625 if (const RecordType *RecordTy 8626 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8627 ExceptSpec.CalledDecl(F->getLocation(), 8628 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8629 } 8630 8631 return ExceptSpec; 8632 } 8633 8634 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8635 // C++ [class.dtor]p2: 8636 // If a class has no user-declared destructor, a destructor is 8637 // declared implicitly. An implicitly-declared destructor is an 8638 // inline public member of its class. 8639 assert(ClassDecl->needsImplicitDestructor()); 8640 8641 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8642 if (DSM.isAlreadyBeingDeclared()) 8643 return 0; 8644 8645 // Create the actual destructor declaration. 8646 CanQualType ClassType 8647 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8648 SourceLocation ClassLoc = ClassDecl->getLocation(); 8649 DeclarationName Name 8650 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8651 DeclarationNameInfo NameInfo(Name, ClassLoc); 8652 CXXDestructorDecl *Destructor 8653 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8654 QualType(), 0, /*isInline=*/true, 8655 /*isImplicitlyDeclared=*/true); 8656 Destructor->setAccess(AS_public); 8657 Destructor->setDefaulted(); 8658 Destructor->setImplicit(); 8659 8660 // Build an exception specification pointing back at this destructor. 8661 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 8662 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8663 8664 AddOverriddenMethods(ClassDecl, Destructor); 8665 8666 // We don't need to use SpecialMemberIsTrivial here; triviality for 8667 // destructors is easy to compute. 8668 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8669 8670 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8671 SetDeclDeleted(Destructor, ClassLoc); 8672 8673 // Note that we have declared this destructor. 8674 ++ASTContext::NumImplicitDestructorsDeclared; 8675 8676 // Introduce this destructor into its scope. 8677 if (Scope *S = getScopeForContext(ClassDecl)) 8678 PushOnScopeChains(Destructor, S, false); 8679 ClassDecl->addDecl(Destructor); 8680 8681 return Destructor; 8682 } 8683 8684 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8685 CXXDestructorDecl *Destructor) { 8686 assert((Destructor->isDefaulted() && 8687 !Destructor->doesThisDeclarationHaveABody() && 8688 !Destructor->isDeleted()) && 8689 "DefineImplicitDestructor - call it for implicit default dtor"); 8690 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8691 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8692 8693 if (Destructor->isInvalidDecl()) 8694 return; 8695 8696 SynthesizedFunctionScope Scope(*this, Destructor); 8697 8698 DiagnosticErrorTrap Trap(Diags); 8699 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8700 Destructor->getParent()); 8701 8702 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8703 Diag(CurrentLocation, diag::note_member_synthesized_at) 8704 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8705 8706 Destructor->setInvalidDecl(); 8707 return; 8708 } 8709 8710 SourceLocation Loc = Destructor->getLocation(); 8711 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8712 Destructor->markUsed(Context); 8713 MarkVTableUsed(CurrentLocation, ClassDecl); 8714 8715 if (ASTMutationListener *L = getASTMutationListener()) { 8716 L->CompletedImplicitDefinition(Destructor); 8717 } 8718 } 8719 8720 /// \brief Perform any semantic analysis which needs to be delayed until all 8721 /// pending class member declarations have been parsed. 8722 void Sema::ActOnFinishCXXMemberDecls() { 8723 // If the context is an invalid C++ class, just suppress these checks. 8724 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8725 if (Record->isInvalidDecl()) { 8726 DelayedDefaultedMemberExceptionSpecs.clear(); 8727 DelayedDestructorExceptionSpecChecks.clear(); 8728 return; 8729 } 8730 } 8731 } 8732 8733 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8734 CXXDestructorDecl *Destructor) { 8735 assert(getLangOpts().CPlusPlus11 && 8736 "adjusting dtor exception specs was introduced in c++11"); 8737 8738 // C++11 [class.dtor]p3: 8739 // A declaration of a destructor that does not have an exception- 8740 // specification is implicitly considered to have the same exception- 8741 // specification as an implicit declaration. 8742 const FunctionProtoType *DtorType = Destructor->getType()-> 8743 getAs<FunctionProtoType>(); 8744 if (DtorType->hasExceptionSpec()) 8745 return; 8746 8747 // Replace the destructor's type, building off the existing one. Fortunately, 8748 // the only thing of interest in the destructor type is its extended info. 8749 // The return and arguments are fixed. 8750 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8751 EPI.ExceptionSpecType = EST_Unevaluated; 8752 EPI.ExceptionSpecDecl = Destructor; 8753 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8754 8755 // FIXME: If the destructor has a body that could throw, and the newly created 8756 // spec doesn't allow exceptions, we should emit a warning, because this 8757 // change in behavior can break conforming C++03 programs at runtime. 8758 // However, we don't have a body or an exception specification yet, so it 8759 // needs to be done somewhere else. 8760 } 8761 8762 namespace { 8763 /// \brief An abstract base class for all helper classes used in building the 8764 // copy/move operators. These classes serve as factory functions and help us 8765 // avoid using the same Expr* in the AST twice. 8766 class ExprBuilder { 8767 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8768 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8769 8770 protected: 8771 static Expr *assertNotNull(Expr *E) { 8772 assert(E && "Expression construction must not fail."); 8773 return E; 8774 } 8775 8776 public: 8777 ExprBuilder() {} 8778 virtual ~ExprBuilder() {} 8779 8780 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 8781 }; 8782 8783 class RefBuilder: public ExprBuilder { 8784 VarDecl *Var; 8785 QualType VarType; 8786 8787 public: 8788 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8789 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take()); 8790 } 8791 8792 RefBuilder(VarDecl *Var, QualType VarType) 8793 : Var(Var), VarType(VarType) {} 8794 }; 8795 8796 class ThisBuilder: public ExprBuilder { 8797 public: 8798 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8799 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>()); 8800 } 8801 }; 8802 8803 class CastBuilder: public ExprBuilder { 8804 const ExprBuilder &Builder; 8805 QualType Type; 8806 ExprValueKind Kind; 8807 const CXXCastPath &Path; 8808 8809 public: 8810 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8811 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 8812 CK_UncheckedDerivedToBase, Kind, 8813 &Path).take()); 8814 } 8815 8816 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 8817 const CXXCastPath &Path) 8818 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 8819 }; 8820 8821 class DerefBuilder: public ExprBuilder { 8822 const ExprBuilder &Builder; 8823 8824 public: 8825 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8826 return assertNotNull( 8827 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take()); 8828 } 8829 8830 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8831 }; 8832 8833 class MemberBuilder: public ExprBuilder { 8834 const ExprBuilder &Builder; 8835 QualType Type; 8836 CXXScopeSpec SS; 8837 bool IsArrow; 8838 LookupResult &MemberLookup; 8839 8840 public: 8841 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8842 return assertNotNull(S.BuildMemberReferenceExpr( 8843 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0, 8844 MemberLookup, 0).take()); 8845 } 8846 8847 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 8848 LookupResult &MemberLookup) 8849 : Builder(Builder), Type(Type), IsArrow(IsArrow), 8850 MemberLookup(MemberLookup) {} 8851 }; 8852 8853 class MoveCastBuilder: public ExprBuilder { 8854 const ExprBuilder &Builder; 8855 8856 public: 8857 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8858 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 8859 } 8860 8861 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8862 }; 8863 8864 class LvalueConvBuilder: public ExprBuilder { 8865 const ExprBuilder &Builder; 8866 8867 public: 8868 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8869 return assertNotNull( 8870 S.DefaultLvalueConversion(Builder.build(S, Loc)).take()); 8871 } 8872 8873 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8874 }; 8875 8876 class SubscriptBuilder: public ExprBuilder { 8877 const ExprBuilder &Base; 8878 const ExprBuilder &Index; 8879 8880 public: 8881 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8882 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 8883 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take()); 8884 } 8885 8886 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 8887 : Base(Base), Index(Index) {} 8888 }; 8889 8890 } // end anonymous namespace 8891 8892 /// When generating a defaulted copy or move assignment operator, if a field 8893 /// should be copied with __builtin_memcpy rather than via explicit assignments, 8894 /// do so. This optimization only applies for arrays of scalars, and for arrays 8895 /// of class type where the selected copy/move-assignment operator is trivial. 8896 static StmtResult 8897 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 8898 const ExprBuilder &ToB, const ExprBuilder &FromB) { 8899 // Compute the size of the memory buffer to be copied. 8900 QualType SizeType = S.Context.getSizeType(); 8901 llvm::APInt Size(S.Context.getTypeSize(SizeType), 8902 S.Context.getTypeSizeInChars(T).getQuantity()); 8903 8904 // Take the address of the field references for "from" and "to". We 8905 // directly construct UnaryOperators here because semantic analysis 8906 // does not permit us to take the address of an xvalue. 8907 Expr *From = FromB.build(S, Loc); 8908 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 8909 S.Context.getPointerType(From->getType()), 8910 VK_RValue, OK_Ordinary, Loc); 8911 Expr *To = ToB.build(S, Loc); 8912 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 8913 S.Context.getPointerType(To->getType()), 8914 VK_RValue, OK_Ordinary, Loc); 8915 8916 const Type *E = T->getBaseElementTypeUnsafe(); 8917 bool NeedsCollectableMemCpy = 8918 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 8919 8920 // Create a reference to the __builtin_objc_memmove_collectable function 8921 StringRef MemCpyName = NeedsCollectableMemCpy ? 8922 "__builtin_objc_memmove_collectable" : 8923 "__builtin_memcpy"; 8924 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 8925 Sema::LookupOrdinaryName); 8926 S.LookupName(R, S.TUScope, true); 8927 8928 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 8929 if (!MemCpy) 8930 // Something went horribly wrong earlier, and we will have complained 8931 // about it. 8932 return StmtError(); 8933 8934 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 8935 VK_RValue, Loc, 0); 8936 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 8937 8938 Expr *CallArgs[] = { 8939 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 8940 }; 8941 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(), 8942 Loc, CallArgs, Loc); 8943 8944 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8945 return S.Owned(Call.takeAs<Stmt>()); 8946 } 8947 8948 /// \brief Builds a statement that copies/moves the given entity from \p From to 8949 /// \c To. 8950 /// 8951 /// This routine is used to copy/move the members of a class with an 8952 /// implicitly-declared copy/move assignment operator. When the entities being 8953 /// copied are arrays, this routine builds for loops to copy them. 8954 /// 8955 /// \param S The Sema object used for type-checking. 8956 /// 8957 /// \param Loc The location where the implicit copy/move is being generated. 8958 /// 8959 /// \param T The type of the expressions being copied/moved. Both expressions 8960 /// must have this type. 8961 /// 8962 /// \param To The expression we are copying/moving to. 8963 /// 8964 /// \param From The expression we are copying/moving from. 8965 /// 8966 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 8967 /// Otherwise, it's a non-static member subobject. 8968 /// 8969 /// \param Copying Whether we're copying or moving. 8970 /// 8971 /// \param Depth Internal parameter recording the depth of the recursion. 8972 /// 8973 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 8974 /// if a memcpy should be used instead. 8975 static StmtResult 8976 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 8977 const ExprBuilder &To, const ExprBuilder &From, 8978 bool CopyingBaseSubobject, bool Copying, 8979 unsigned Depth = 0) { 8980 // C++11 [class.copy]p28: 8981 // Each subobject is assigned in the manner appropriate to its type: 8982 // 8983 // - if the subobject is of class type, as if by a call to operator= with 8984 // the subobject as the object expression and the corresponding 8985 // subobject of x as a single function argument (as if by explicit 8986 // qualification; that is, ignoring any possible virtual overriding 8987 // functions in more derived classes); 8988 // 8989 // C++03 [class.copy]p13: 8990 // - if the subobject is of class type, the copy assignment operator for 8991 // the class is used (as if by explicit qualification; that is, 8992 // ignoring any possible virtual overriding functions in more derived 8993 // classes); 8994 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 8995 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8996 8997 // Look for operator=. 8998 DeclarationName Name 8999 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9000 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9001 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9002 9003 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9004 // operator. 9005 if (!S.getLangOpts().CPlusPlus11) { 9006 LookupResult::Filter F = OpLookup.makeFilter(); 9007 while (F.hasNext()) { 9008 NamedDecl *D = F.next(); 9009 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9010 if (Method->isCopyAssignmentOperator() || 9011 (!Copying && Method->isMoveAssignmentOperator())) 9012 continue; 9013 9014 F.erase(); 9015 } 9016 F.done(); 9017 } 9018 9019 // Suppress the protected check (C++ [class.protected]) for each of the 9020 // assignment operators we found. This strange dance is required when 9021 // we're assigning via a base classes's copy-assignment operator. To 9022 // ensure that we're getting the right base class subobject (without 9023 // ambiguities), we need to cast "this" to that subobject type; to 9024 // ensure that we don't go through the virtual call mechanism, we need 9025 // to qualify the operator= name with the base class (see below). However, 9026 // this means that if the base class has a protected copy assignment 9027 // operator, the protected member access check will fail. So, we 9028 // rewrite "protected" access to "public" access in this case, since we 9029 // know by construction that we're calling from a derived class. 9030 if (CopyingBaseSubobject) { 9031 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9032 L != LEnd; ++L) { 9033 if (L.getAccess() == AS_protected) 9034 L.setAccess(AS_public); 9035 } 9036 } 9037 9038 // Create the nested-name-specifier that will be used to qualify the 9039 // reference to operator=; this is required to suppress the virtual 9040 // call mechanism. 9041 CXXScopeSpec SS; 9042 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9043 SS.MakeTrivial(S.Context, 9044 NestedNameSpecifier::Create(S.Context, 0, false, 9045 CanonicalT), 9046 Loc); 9047 9048 // Create the reference to operator=. 9049 ExprResult OpEqualRef 9050 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9051 SS, /*TemplateKWLoc=*/SourceLocation(), 9052 /*FirstQualifierInScope=*/0, 9053 OpLookup, 9054 /*TemplateArgs=*/0, 9055 /*SuppressQualifierCheck=*/true); 9056 if (OpEqualRef.isInvalid()) 9057 return StmtError(); 9058 9059 // Build the call to the assignment operator. 9060 9061 Expr *FromInst = From.build(S, Loc); 9062 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 9063 OpEqualRef.takeAs<Expr>(), 9064 Loc, FromInst, Loc); 9065 if (Call.isInvalid()) 9066 return StmtError(); 9067 9068 // If we built a call to a trivial 'operator=' while copying an array, 9069 // bail out. We'll replace the whole shebang with a memcpy. 9070 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9071 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9072 return StmtResult((Stmt*)0); 9073 9074 // Convert to an expression-statement, and clean up any produced 9075 // temporaries. 9076 return S.ActOnExprStmt(Call); 9077 } 9078 9079 // - if the subobject is of scalar type, the built-in assignment 9080 // operator is used. 9081 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9082 if (!ArrayTy) { 9083 ExprResult Assignment = S.CreateBuiltinBinOp( 9084 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9085 if (Assignment.isInvalid()) 9086 return StmtError(); 9087 return S.ActOnExprStmt(Assignment); 9088 } 9089 9090 // - if the subobject is an array, each element is assigned, in the 9091 // manner appropriate to the element type; 9092 9093 // Construct a loop over the array bounds, e.g., 9094 // 9095 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9096 // 9097 // that will copy each of the array elements. 9098 QualType SizeType = S.Context.getSizeType(); 9099 9100 // Create the iteration variable. 9101 IdentifierInfo *IterationVarName = 0; 9102 { 9103 SmallString<8> Str; 9104 llvm::raw_svector_ostream OS(Str); 9105 OS << "__i" << Depth; 9106 IterationVarName = &S.Context.Idents.get(OS.str()); 9107 } 9108 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9109 IterationVarName, SizeType, 9110 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9111 SC_None); 9112 9113 // Initialize the iteration variable to zero. 9114 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9115 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9116 9117 // Creates a reference to the iteration variable. 9118 RefBuilder IterationVarRef(IterationVar, SizeType); 9119 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9120 9121 // Create the DeclStmt that holds the iteration variable. 9122 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9123 9124 // Subscript the "from" and "to" expressions with the iteration variable. 9125 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9126 MoveCastBuilder FromIndexMove(FromIndexCopy); 9127 const ExprBuilder *FromIndex; 9128 if (Copying) 9129 FromIndex = &FromIndexCopy; 9130 else 9131 FromIndex = &FromIndexMove; 9132 9133 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9134 9135 // Build the copy/move for an individual element of the array. 9136 StmtResult Copy = 9137 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9138 ToIndex, *FromIndex, CopyingBaseSubobject, 9139 Copying, Depth + 1); 9140 // Bail out if copying fails or if we determined that we should use memcpy. 9141 if (Copy.isInvalid() || !Copy.get()) 9142 return Copy; 9143 9144 // Create the comparison against the array bound. 9145 llvm::APInt Upper 9146 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9147 Expr *Comparison 9148 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9149 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9150 BO_NE, S.Context.BoolTy, 9151 VK_RValue, OK_Ordinary, Loc, false); 9152 9153 // Create the pre-increment of the iteration variable. 9154 Expr *Increment 9155 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9156 SizeType, VK_LValue, OK_Ordinary, Loc); 9157 9158 // Construct the loop that copies all elements of this array. 9159 return S.ActOnForStmt(Loc, Loc, InitStmt, 9160 S.MakeFullExpr(Comparison), 9161 0, S.MakeFullDiscardedValueExpr(Increment), 9162 Loc, Copy.take()); 9163 } 9164 9165 static StmtResult 9166 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9167 const ExprBuilder &To, const ExprBuilder &From, 9168 bool CopyingBaseSubobject, bool Copying) { 9169 // Maybe we should use a memcpy? 9170 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9171 T.isTriviallyCopyableType(S.Context)) 9172 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9173 9174 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9175 CopyingBaseSubobject, 9176 Copying, 0)); 9177 9178 // If we ended up picking a trivial assignment operator for an array of a 9179 // non-trivially-copyable class type, just emit a memcpy. 9180 if (!Result.isInvalid() && !Result.get()) 9181 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9182 9183 return Result; 9184 } 9185 9186 Sema::ImplicitExceptionSpecification 9187 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9188 CXXRecordDecl *ClassDecl = MD->getParent(); 9189 9190 ImplicitExceptionSpecification ExceptSpec(*this); 9191 if (ClassDecl->isInvalidDecl()) 9192 return ExceptSpec; 9193 9194 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9195 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9196 unsigned ArgQuals = 9197 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9198 9199 // C++ [except.spec]p14: 9200 // An implicitly declared special member function (Clause 12) shall have an 9201 // exception-specification. [...] 9202 9203 // It is unspecified whether or not an implicit copy assignment operator 9204 // attempts to deduplicate calls to assignment operators of virtual bases are 9205 // made. As such, this exception specification is effectively unspecified. 9206 // Based on a similar decision made for constness in C++0x, we're erring on 9207 // the side of assuming such calls to be made regardless of whether they 9208 // actually happen. 9209 for (const auto &Base : ClassDecl->bases()) { 9210 if (Base.isVirtual()) 9211 continue; 9212 9213 CXXRecordDecl *BaseClassDecl 9214 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9215 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9216 ArgQuals, false, 0)) 9217 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9218 } 9219 9220 for (const auto &Base : ClassDecl->vbases()) { 9221 CXXRecordDecl *BaseClassDecl 9222 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9223 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9224 ArgQuals, false, 0)) 9225 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9226 } 9227 9228 for (const auto *Field : ClassDecl->fields()) { 9229 QualType FieldType = Context.getBaseElementType(Field->getType()); 9230 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9231 if (CXXMethodDecl *CopyAssign = 9232 LookupCopyingAssignment(FieldClassDecl, 9233 ArgQuals | FieldType.getCVRQualifiers(), 9234 false, 0)) 9235 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9236 } 9237 } 9238 9239 return ExceptSpec; 9240 } 9241 9242 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9243 // Note: The following rules are largely analoguous to the copy 9244 // constructor rules. Note that virtual bases are not taken into account 9245 // for determining the argument type of the operator. Note also that 9246 // operators taking an object instead of a reference are allowed. 9247 assert(ClassDecl->needsImplicitCopyAssignment()); 9248 9249 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9250 if (DSM.isAlreadyBeingDeclared()) 9251 return 0; 9252 9253 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9254 QualType RetType = Context.getLValueReferenceType(ArgType); 9255 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9256 if (Const) 9257 ArgType = ArgType.withConst(); 9258 ArgType = Context.getLValueReferenceType(ArgType); 9259 9260 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9261 CXXCopyAssignment, 9262 Const); 9263 9264 // An implicitly-declared copy assignment operator is an inline public 9265 // member of its class. 9266 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9267 SourceLocation ClassLoc = ClassDecl->getLocation(); 9268 DeclarationNameInfo NameInfo(Name, ClassLoc); 9269 CXXMethodDecl *CopyAssignment = 9270 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9271 /*TInfo=*/ 0, /*StorageClass=*/ SC_None, 9272 /*isInline=*/ true, Constexpr, SourceLocation()); 9273 CopyAssignment->setAccess(AS_public); 9274 CopyAssignment->setDefaulted(); 9275 CopyAssignment->setImplicit(); 9276 9277 // Build an exception specification pointing back at this member. 9278 FunctionProtoType::ExtProtoInfo EPI = 9279 getImplicitMethodEPI(*this, CopyAssignment); 9280 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9281 9282 // Add the parameter to the operator. 9283 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9284 ClassLoc, ClassLoc, /*Id=*/0, 9285 ArgType, /*TInfo=*/0, 9286 SC_None, 0); 9287 CopyAssignment->setParams(FromParam); 9288 9289 AddOverriddenMethods(ClassDecl, CopyAssignment); 9290 9291 CopyAssignment->setTrivial( 9292 ClassDecl->needsOverloadResolutionForCopyAssignment() 9293 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9294 : ClassDecl->hasTrivialCopyAssignment()); 9295 9296 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9297 SetDeclDeleted(CopyAssignment, ClassLoc); 9298 9299 // Note that we have added this copy-assignment operator. 9300 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9301 9302 if (Scope *S = getScopeForContext(ClassDecl)) 9303 PushOnScopeChains(CopyAssignment, S, false); 9304 ClassDecl->addDecl(CopyAssignment); 9305 9306 return CopyAssignment; 9307 } 9308 9309 /// Diagnose an implicit copy operation for a class which is odr-used, but 9310 /// which is deprecated because the class has a user-declared copy constructor, 9311 /// copy assignment operator, or destructor. 9312 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 9313 SourceLocation UseLoc) { 9314 assert(CopyOp->isImplicit()); 9315 9316 CXXRecordDecl *RD = CopyOp->getParent(); 9317 CXXMethodDecl *UserDeclaredOperation = 0; 9318 9319 // In Microsoft mode, assignment operations don't affect constructors and 9320 // vice versa. 9321 if (RD->hasUserDeclaredDestructor()) { 9322 UserDeclaredOperation = RD->getDestructor(); 9323 } else if (!isa<CXXConstructorDecl>(CopyOp) && 9324 RD->hasUserDeclaredCopyConstructor() && 9325 !S.getLangOpts().MSVCCompat) { 9326 // Find any user-declared copy constructor. 9327 for (auto *I : RD->ctors()) { 9328 if (I->isCopyConstructor()) { 9329 UserDeclaredOperation = I; 9330 break; 9331 } 9332 } 9333 assert(UserDeclaredOperation); 9334 } else if (isa<CXXConstructorDecl>(CopyOp) && 9335 RD->hasUserDeclaredCopyAssignment() && 9336 !S.getLangOpts().MSVCCompat) { 9337 // Find any user-declared move assignment operator. 9338 for (auto *I : RD->methods()) { 9339 if (I->isCopyAssignmentOperator()) { 9340 UserDeclaredOperation = I; 9341 break; 9342 } 9343 } 9344 assert(UserDeclaredOperation); 9345 } 9346 9347 if (UserDeclaredOperation) { 9348 S.Diag(UserDeclaredOperation->getLocation(), 9349 diag::warn_deprecated_copy_operation) 9350 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 9351 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 9352 S.Diag(UseLoc, diag::note_member_synthesized_at) 9353 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 9354 : Sema::CXXCopyAssignment) 9355 << RD; 9356 } 9357 } 9358 9359 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 9360 CXXMethodDecl *CopyAssignOperator) { 9361 assert((CopyAssignOperator->isDefaulted() && 9362 CopyAssignOperator->isOverloadedOperator() && 9363 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 9364 !CopyAssignOperator->doesThisDeclarationHaveABody() && 9365 !CopyAssignOperator->isDeleted()) && 9366 "DefineImplicitCopyAssignment called for wrong function"); 9367 9368 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 9369 9370 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 9371 CopyAssignOperator->setInvalidDecl(); 9372 return; 9373 } 9374 9375 // C++11 [class.copy]p18: 9376 // The [definition of an implicitly declared copy assignment operator] is 9377 // deprecated if the class has a user-declared copy constructor or a 9378 // user-declared destructor. 9379 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 9380 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 9381 9382 CopyAssignOperator->markUsed(Context); 9383 9384 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 9385 DiagnosticErrorTrap Trap(Diags); 9386 9387 // C++0x [class.copy]p30: 9388 // The implicitly-defined or explicitly-defaulted copy assignment operator 9389 // for a non-union class X performs memberwise copy assignment of its 9390 // subobjects. The direct base classes of X are assigned first, in the 9391 // order of their declaration in the base-specifier-list, and then the 9392 // immediate non-static data members of X are assigned, in the order in 9393 // which they were declared in the class definition. 9394 9395 // The statements that form the synthesized function body. 9396 SmallVector<Stmt*, 8> Statements; 9397 9398 // The parameter for the "other" object, which we are copying from. 9399 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 9400 Qualifiers OtherQuals = Other->getType().getQualifiers(); 9401 QualType OtherRefType = Other->getType(); 9402 if (const LValueReferenceType *OtherRef 9403 = OtherRefType->getAs<LValueReferenceType>()) { 9404 OtherRefType = OtherRef->getPointeeType(); 9405 OtherQuals = OtherRefType.getQualifiers(); 9406 } 9407 9408 // Our location for everything implicitly-generated. 9409 SourceLocation Loc = CopyAssignOperator->getLocation(); 9410 9411 // Builds a DeclRefExpr for the "other" object. 9412 RefBuilder OtherRef(Other, OtherRefType); 9413 9414 // Builds the "this" pointer. 9415 ThisBuilder This; 9416 9417 // Assign base classes. 9418 bool Invalid = false; 9419 for (auto &Base : ClassDecl->bases()) { 9420 // Form the assignment: 9421 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 9422 QualType BaseType = Base.getType().getUnqualifiedType(); 9423 if (!BaseType->isRecordType()) { 9424 Invalid = true; 9425 continue; 9426 } 9427 9428 CXXCastPath BasePath; 9429 BasePath.push_back(&Base); 9430 9431 // Construct the "from" expression, which is an implicit cast to the 9432 // appropriately-qualified base type. 9433 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 9434 VK_LValue, BasePath); 9435 9436 // Dereference "this". 9437 DerefBuilder DerefThis(This); 9438 CastBuilder To(DerefThis, 9439 Context.getCVRQualifiedType( 9440 BaseType, CopyAssignOperator->getTypeQualifiers()), 9441 VK_LValue, BasePath); 9442 9443 // Build the copy. 9444 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 9445 To, From, 9446 /*CopyingBaseSubobject=*/true, 9447 /*Copying=*/true); 9448 if (Copy.isInvalid()) { 9449 Diag(CurrentLocation, diag::note_member_synthesized_at) 9450 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9451 CopyAssignOperator->setInvalidDecl(); 9452 return; 9453 } 9454 9455 // Success! Record the copy. 9456 Statements.push_back(Copy.takeAs<Expr>()); 9457 } 9458 9459 // Assign non-static members. 9460 for (auto *Field : ClassDecl->fields()) { 9461 if (Field->isUnnamedBitfield()) 9462 continue; 9463 9464 if (Field->isInvalidDecl()) { 9465 Invalid = true; 9466 continue; 9467 } 9468 9469 // Check for members of reference type; we can't copy those. 9470 if (Field->getType()->isReferenceType()) { 9471 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9472 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9473 Diag(Field->getLocation(), diag::note_declared_at); 9474 Diag(CurrentLocation, diag::note_member_synthesized_at) 9475 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9476 Invalid = true; 9477 continue; 9478 } 9479 9480 // Check for members of const-qualified, non-class type. 9481 QualType BaseType = Context.getBaseElementType(Field->getType()); 9482 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9483 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9484 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9485 Diag(Field->getLocation(), diag::note_declared_at); 9486 Diag(CurrentLocation, diag::note_member_synthesized_at) 9487 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9488 Invalid = true; 9489 continue; 9490 } 9491 9492 // Suppress assigning zero-width bitfields. 9493 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9494 continue; 9495 9496 QualType FieldType = Field->getType().getNonReferenceType(); 9497 if (FieldType->isIncompleteArrayType()) { 9498 assert(ClassDecl->hasFlexibleArrayMember() && 9499 "Incomplete array type is not valid"); 9500 continue; 9501 } 9502 9503 // Build references to the field in the object we're copying from and to. 9504 CXXScopeSpec SS; // Intentionally empty 9505 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9506 LookupMemberName); 9507 MemberLookup.addDecl(Field); 9508 MemberLookup.resolveKind(); 9509 9510 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 9511 9512 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 9513 9514 // Build the copy of this field. 9515 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 9516 To, From, 9517 /*CopyingBaseSubobject=*/false, 9518 /*Copying=*/true); 9519 if (Copy.isInvalid()) { 9520 Diag(CurrentLocation, diag::note_member_synthesized_at) 9521 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9522 CopyAssignOperator->setInvalidDecl(); 9523 return; 9524 } 9525 9526 // Success! Record the copy. 9527 Statements.push_back(Copy.takeAs<Stmt>()); 9528 } 9529 9530 if (!Invalid) { 9531 // Add a "return *this;" 9532 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9533 9534 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9535 if (Return.isInvalid()) 9536 Invalid = true; 9537 else { 9538 Statements.push_back(Return.takeAs<Stmt>()); 9539 9540 if (Trap.hasErrorOccurred()) { 9541 Diag(CurrentLocation, diag::note_member_synthesized_at) 9542 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9543 Invalid = true; 9544 } 9545 } 9546 } 9547 9548 if (Invalid) { 9549 CopyAssignOperator->setInvalidDecl(); 9550 return; 9551 } 9552 9553 StmtResult Body; 9554 { 9555 CompoundScopeRAII CompoundScope(*this); 9556 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9557 /*isStmtExpr=*/false); 9558 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9559 } 9560 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 9561 9562 if (ASTMutationListener *L = getASTMutationListener()) { 9563 L->CompletedImplicitDefinition(CopyAssignOperator); 9564 } 9565 } 9566 9567 Sema::ImplicitExceptionSpecification 9568 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9569 CXXRecordDecl *ClassDecl = MD->getParent(); 9570 9571 ImplicitExceptionSpecification ExceptSpec(*this); 9572 if (ClassDecl->isInvalidDecl()) 9573 return ExceptSpec; 9574 9575 // C++0x [except.spec]p14: 9576 // An implicitly declared special member function (Clause 12) shall have an 9577 // exception-specification. [...] 9578 9579 // It is unspecified whether or not an implicit move assignment operator 9580 // attempts to deduplicate calls to assignment operators of virtual bases are 9581 // made. As such, this exception specification is effectively unspecified. 9582 // Based on a similar decision made for constness in C++0x, we're erring on 9583 // the side of assuming such calls to be made regardless of whether they 9584 // actually happen. 9585 // Note that a move constructor is not implicitly declared when there are 9586 // virtual bases, but it can still be user-declared and explicitly defaulted. 9587 for (const auto &Base : ClassDecl->bases()) { 9588 if (Base.isVirtual()) 9589 continue; 9590 9591 CXXRecordDecl *BaseClassDecl 9592 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9593 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9594 0, false, 0)) 9595 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 9596 } 9597 9598 for (const auto &Base : ClassDecl->vbases()) { 9599 CXXRecordDecl *BaseClassDecl 9600 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9601 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9602 0, false, 0)) 9603 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 9604 } 9605 9606 for (const auto *Field : ClassDecl->fields()) { 9607 QualType FieldType = Context.getBaseElementType(Field->getType()); 9608 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9609 if (CXXMethodDecl *MoveAssign = 9610 LookupMovingAssignment(FieldClassDecl, 9611 FieldType.getCVRQualifiers(), 9612 false, 0)) 9613 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 9614 } 9615 } 9616 9617 return ExceptSpec; 9618 } 9619 9620 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9621 assert(ClassDecl->needsImplicitMoveAssignment()); 9622 9623 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9624 if (DSM.isAlreadyBeingDeclared()) 9625 return 0; 9626 9627 // Note: The following rules are largely analoguous to the move 9628 // constructor rules. 9629 9630 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9631 QualType RetType = Context.getLValueReferenceType(ArgType); 9632 ArgType = Context.getRValueReferenceType(ArgType); 9633 9634 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9635 CXXMoveAssignment, 9636 false); 9637 9638 // An implicitly-declared move assignment operator is an inline public 9639 // member of its class. 9640 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9641 SourceLocation ClassLoc = ClassDecl->getLocation(); 9642 DeclarationNameInfo NameInfo(Name, ClassLoc); 9643 CXXMethodDecl *MoveAssignment = 9644 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9645 /*TInfo=*/0, /*StorageClass=*/SC_None, 9646 /*isInline=*/true, Constexpr, SourceLocation()); 9647 MoveAssignment->setAccess(AS_public); 9648 MoveAssignment->setDefaulted(); 9649 MoveAssignment->setImplicit(); 9650 9651 // Build an exception specification pointing back at this member. 9652 FunctionProtoType::ExtProtoInfo EPI = 9653 getImplicitMethodEPI(*this, MoveAssignment); 9654 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9655 9656 // Add the parameter to the operator. 9657 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9658 ClassLoc, ClassLoc, /*Id=*/0, 9659 ArgType, /*TInfo=*/0, 9660 SC_None, 0); 9661 MoveAssignment->setParams(FromParam); 9662 9663 AddOverriddenMethods(ClassDecl, MoveAssignment); 9664 9665 MoveAssignment->setTrivial( 9666 ClassDecl->needsOverloadResolutionForMoveAssignment() 9667 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9668 : ClassDecl->hasTrivialMoveAssignment()); 9669 9670 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9671 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 9672 SetDeclDeleted(MoveAssignment, ClassLoc); 9673 } 9674 9675 // Note that we have added this copy-assignment operator. 9676 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9677 9678 if (Scope *S = getScopeForContext(ClassDecl)) 9679 PushOnScopeChains(MoveAssignment, S, false); 9680 ClassDecl->addDecl(MoveAssignment); 9681 9682 return MoveAssignment; 9683 } 9684 9685 /// Check if we're implicitly defining a move assignment operator for a class 9686 /// with virtual bases. Such a move assignment might move-assign the virtual 9687 /// base multiple times. 9688 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 9689 SourceLocation CurrentLocation) { 9690 assert(!Class->isDependentContext() && "should not define dependent move"); 9691 9692 // Only a virtual base could get implicitly move-assigned multiple times. 9693 // Only a non-trivial move assignment can observe this. We only want to 9694 // diagnose if we implicitly define an assignment operator that assigns 9695 // two base classes, both of which move-assign the same virtual base. 9696 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 9697 Class->getNumBases() < 2) 9698 return; 9699 9700 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 9701 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 9702 VBaseMap VBases; 9703 9704 for (auto &BI : Class->bases()) { 9705 Worklist.push_back(&BI); 9706 while (!Worklist.empty()) { 9707 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 9708 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 9709 9710 // If the base has no non-trivial move assignment operators, 9711 // we don't care about moves from it. 9712 if (!Base->hasNonTrivialMoveAssignment()) 9713 continue; 9714 9715 // If there's nothing virtual here, skip it. 9716 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 9717 continue; 9718 9719 // If we're not actually going to call a move assignment for this base, 9720 // or the selected move assignment is trivial, skip it. 9721 Sema::SpecialMemberOverloadResult *SMOR = 9722 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 9723 /*ConstArg*/false, /*VolatileArg*/false, 9724 /*RValueThis*/true, /*ConstThis*/false, 9725 /*VolatileThis*/false); 9726 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 9727 !SMOR->getMethod()->isMoveAssignmentOperator()) 9728 continue; 9729 9730 if (BaseSpec->isVirtual()) { 9731 // We're going to move-assign this virtual base, and its move 9732 // assignment operator is not trivial. If this can happen for 9733 // multiple distinct direct bases of Class, diagnose it. (If it 9734 // only happens in one base, we'll diagnose it when synthesizing 9735 // that base class's move assignment operator.) 9736 CXXBaseSpecifier *&Existing = 9737 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 9738 .first->second; 9739 if (Existing && Existing != &BI) { 9740 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 9741 << Class << Base; 9742 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 9743 << (Base->getCanonicalDecl() == 9744 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 9745 << Base << Existing->getType() << Existing->getSourceRange(); 9746 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 9747 << (Base->getCanonicalDecl() == 9748 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 9749 << Base << BI.getType() << BaseSpec->getSourceRange(); 9750 9751 // Only diagnose each vbase once. 9752 Existing = 0; 9753 } 9754 } else { 9755 // Only walk over bases that have defaulted move assignment operators. 9756 // We assume that any user-provided move assignment operator handles 9757 // the multiple-moves-of-vbase case itself somehow. 9758 if (!SMOR->getMethod()->isDefaulted()) 9759 continue; 9760 9761 // We're going to move the base classes of Base. Add them to the list. 9762 for (auto &BI : Base->bases()) 9763 Worklist.push_back(&BI); 9764 } 9765 } 9766 } 9767 } 9768 9769 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 9770 CXXMethodDecl *MoveAssignOperator) { 9771 assert((MoveAssignOperator->isDefaulted() && 9772 MoveAssignOperator->isOverloadedOperator() && 9773 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 9774 !MoveAssignOperator->doesThisDeclarationHaveABody() && 9775 !MoveAssignOperator->isDeleted()) && 9776 "DefineImplicitMoveAssignment called for wrong function"); 9777 9778 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 9779 9780 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 9781 MoveAssignOperator->setInvalidDecl(); 9782 return; 9783 } 9784 9785 MoveAssignOperator->markUsed(Context); 9786 9787 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 9788 DiagnosticErrorTrap Trap(Diags); 9789 9790 // C++0x [class.copy]p28: 9791 // The implicitly-defined or move assignment operator for a non-union class 9792 // X performs memberwise move assignment of its subobjects. The direct base 9793 // classes of X are assigned first, in the order of their declaration in the 9794 // base-specifier-list, and then the immediate non-static data members of X 9795 // are assigned, in the order in which they were declared in the class 9796 // definition. 9797 9798 // Issue a warning if our implicit move assignment operator will move 9799 // from a virtual base more than once. 9800 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 9801 9802 // The statements that form the synthesized function body. 9803 SmallVector<Stmt*, 8> Statements; 9804 9805 // The parameter for the "other" object, which we are move from. 9806 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 9807 QualType OtherRefType = Other->getType()-> 9808 getAs<RValueReferenceType>()->getPointeeType(); 9809 assert(!OtherRefType.getQualifiers() && 9810 "Bad argument type of defaulted move assignment"); 9811 9812 // Our location for everything implicitly-generated. 9813 SourceLocation Loc = MoveAssignOperator->getLocation(); 9814 9815 // Builds a reference to the "other" object. 9816 RefBuilder OtherRef(Other, OtherRefType); 9817 // Cast to rvalue. 9818 MoveCastBuilder MoveOther(OtherRef); 9819 9820 // Builds the "this" pointer. 9821 ThisBuilder This; 9822 9823 // Assign base classes. 9824 bool Invalid = false; 9825 for (auto &Base : ClassDecl->bases()) { 9826 // C++11 [class.copy]p28: 9827 // It is unspecified whether subobjects representing virtual base classes 9828 // are assigned more than once by the implicitly-defined copy assignment 9829 // operator. 9830 // FIXME: Do not assign to a vbase that will be assigned by some other base 9831 // class. For a move-assignment, this can result in the vbase being moved 9832 // multiple times. 9833 9834 // Form the assignment: 9835 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 9836 QualType BaseType = Base.getType().getUnqualifiedType(); 9837 if (!BaseType->isRecordType()) { 9838 Invalid = true; 9839 continue; 9840 } 9841 9842 CXXCastPath BasePath; 9843 BasePath.push_back(&Base); 9844 9845 // Construct the "from" expression, which is an implicit cast to the 9846 // appropriately-qualified base type. 9847 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 9848 9849 // Dereference "this". 9850 DerefBuilder DerefThis(This); 9851 9852 // Implicitly cast "this" to the appropriately-qualified base type. 9853 CastBuilder To(DerefThis, 9854 Context.getCVRQualifiedType( 9855 BaseType, MoveAssignOperator->getTypeQualifiers()), 9856 VK_LValue, BasePath); 9857 9858 // Build the move. 9859 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 9860 To, From, 9861 /*CopyingBaseSubobject=*/true, 9862 /*Copying=*/false); 9863 if (Move.isInvalid()) { 9864 Diag(CurrentLocation, diag::note_member_synthesized_at) 9865 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9866 MoveAssignOperator->setInvalidDecl(); 9867 return; 9868 } 9869 9870 // Success! Record the move. 9871 Statements.push_back(Move.takeAs<Expr>()); 9872 } 9873 9874 // Assign non-static members. 9875 for (auto *Field : ClassDecl->fields()) { 9876 if (Field->isUnnamedBitfield()) 9877 continue; 9878 9879 if (Field->isInvalidDecl()) { 9880 Invalid = true; 9881 continue; 9882 } 9883 9884 // Check for members of reference type; we can't move those. 9885 if (Field->getType()->isReferenceType()) { 9886 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9887 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9888 Diag(Field->getLocation(), diag::note_declared_at); 9889 Diag(CurrentLocation, diag::note_member_synthesized_at) 9890 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9891 Invalid = true; 9892 continue; 9893 } 9894 9895 // Check for members of const-qualified, non-class type. 9896 QualType BaseType = Context.getBaseElementType(Field->getType()); 9897 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9898 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9899 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9900 Diag(Field->getLocation(), diag::note_declared_at); 9901 Diag(CurrentLocation, diag::note_member_synthesized_at) 9902 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9903 Invalid = true; 9904 continue; 9905 } 9906 9907 // Suppress assigning zero-width bitfields. 9908 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9909 continue; 9910 9911 QualType FieldType = Field->getType().getNonReferenceType(); 9912 if (FieldType->isIncompleteArrayType()) { 9913 assert(ClassDecl->hasFlexibleArrayMember() && 9914 "Incomplete array type is not valid"); 9915 continue; 9916 } 9917 9918 // Build references to the field in the object we're copying from and to. 9919 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9920 LookupMemberName); 9921 MemberLookup.addDecl(Field); 9922 MemberLookup.resolveKind(); 9923 MemberBuilder From(MoveOther, OtherRefType, 9924 /*IsArrow=*/false, MemberLookup); 9925 MemberBuilder To(This, getCurrentThisType(), 9926 /*IsArrow=*/true, MemberLookup); 9927 9928 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 9929 "Member reference with rvalue base must be rvalue except for reference " 9930 "members, which aren't allowed for move assignment."); 9931 9932 // Build the move of this field. 9933 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 9934 To, From, 9935 /*CopyingBaseSubobject=*/false, 9936 /*Copying=*/false); 9937 if (Move.isInvalid()) { 9938 Diag(CurrentLocation, diag::note_member_synthesized_at) 9939 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9940 MoveAssignOperator->setInvalidDecl(); 9941 return; 9942 } 9943 9944 // Success! Record the copy. 9945 Statements.push_back(Move.takeAs<Stmt>()); 9946 } 9947 9948 if (!Invalid) { 9949 // Add a "return *this;" 9950 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9951 9952 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9953 if (Return.isInvalid()) 9954 Invalid = true; 9955 else { 9956 Statements.push_back(Return.takeAs<Stmt>()); 9957 9958 if (Trap.hasErrorOccurred()) { 9959 Diag(CurrentLocation, diag::note_member_synthesized_at) 9960 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9961 Invalid = true; 9962 } 9963 } 9964 } 9965 9966 if (Invalid) { 9967 MoveAssignOperator->setInvalidDecl(); 9968 return; 9969 } 9970 9971 StmtResult Body; 9972 { 9973 CompoundScopeRAII CompoundScope(*this); 9974 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9975 /*isStmtExpr=*/false); 9976 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9977 } 9978 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 9979 9980 if (ASTMutationListener *L = getASTMutationListener()) { 9981 L->CompletedImplicitDefinition(MoveAssignOperator); 9982 } 9983 } 9984 9985 Sema::ImplicitExceptionSpecification 9986 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 9987 CXXRecordDecl *ClassDecl = MD->getParent(); 9988 9989 ImplicitExceptionSpecification ExceptSpec(*this); 9990 if (ClassDecl->isInvalidDecl()) 9991 return ExceptSpec; 9992 9993 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9994 assert(T->getNumParams() >= 1 && "not a copy ctor"); 9995 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9996 9997 // C++ [except.spec]p14: 9998 // An implicitly declared special member function (Clause 12) shall have an 9999 // exception-specification. [...] 10000 for (const auto &Base : ClassDecl->bases()) { 10001 // Virtual bases are handled below. 10002 if (Base.isVirtual()) 10003 continue; 10004 10005 CXXRecordDecl *BaseClassDecl 10006 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10007 if (CXXConstructorDecl *CopyConstructor = 10008 LookupCopyingConstructor(BaseClassDecl, Quals)) 10009 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10010 } 10011 for (const auto &Base : ClassDecl->vbases()) { 10012 CXXRecordDecl *BaseClassDecl 10013 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10014 if (CXXConstructorDecl *CopyConstructor = 10015 LookupCopyingConstructor(BaseClassDecl, Quals)) 10016 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10017 } 10018 for (const auto *Field : ClassDecl->fields()) { 10019 QualType FieldType = Context.getBaseElementType(Field->getType()); 10020 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10021 if (CXXConstructorDecl *CopyConstructor = 10022 LookupCopyingConstructor(FieldClassDecl, 10023 Quals | FieldType.getCVRQualifiers())) 10024 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10025 } 10026 } 10027 10028 return ExceptSpec; 10029 } 10030 10031 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10032 CXXRecordDecl *ClassDecl) { 10033 // C++ [class.copy]p4: 10034 // If the class definition does not explicitly declare a copy 10035 // constructor, one is declared implicitly. 10036 assert(ClassDecl->needsImplicitCopyConstructor()); 10037 10038 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10039 if (DSM.isAlreadyBeingDeclared()) 10040 return 0; 10041 10042 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10043 QualType ArgType = ClassType; 10044 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10045 if (Const) 10046 ArgType = ArgType.withConst(); 10047 ArgType = Context.getLValueReferenceType(ArgType); 10048 10049 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10050 CXXCopyConstructor, 10051 Const); 10052 10053 DeclarationName Name 10054 = Context.DeclarationNames.getCXXConstructorName( 10055 Context.getCanonicalType(ClassType)); 10056 SourceLocation ClassLoc = ClassDecl->getLocation(); 10057 DeclarationNameInfo NameInfo(Name, ClassLoc); 10058 10059 // An implicitly-declared copy constructor is an inline public 10060 // member of its class. 10061 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10062 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 10063 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10064 Constexpr); 10065 CopyConstructor->setAccess(AS_public); 10066 CopyConstructor->setDefaulted(); 10067 10068 // Build an exception specification pointing back at this member. 10069 FunctionProtoType::ExtProtoInfo EPI = 10070 getImplicitMethodEPI(*this, CopyConstructor); 10071 CopyConstructor->setType( 10072 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10073 10074 // Add the parameter to the constructor. 10075 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10076 ClassLoc, ClassLoc, 10077 /*IdentifierInfo=*/0, 10078 ArgType, /*TInfo=*/0, 10079 SC_None, 0); 10080 CopyConstructor->setParams(FromParam); 10081 10082 CopyConstructor->setTrivial( 10083 ClassDecl->needsOverloadResolutionForCopyConstructor() 10084 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10085 : ClassDecl->hasTrivialCopyConstructor()); 10086 10087 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10088 SetDeclDeleted(CopyConstructor, ClassLoc); 10089 10090 // Note that we have declared this constructor. 10091 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10092 10093 if (Scope *S = getScopeForContext(ClassDecl)) 10094 PushOnScopeChains(CopyConstructor, S, false); 10095 ClassDecl->addDecl(CopyConstructor); 10096 10097 return CopyConstructor; 10098 } 10099 10100 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10101 CXXConstructorDecl *CopyConstructor) { 10102 assert((CopyConstructor->isDefaulted() && 10103 CopyConstructor->isCopyConstructor() && 10104 !CopyConstructor->doesThisDeclarationHaveABody() && 10105 !CopyConstructor->isDeleted()) && 10106 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10107 10108 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10109 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10110 10111 // C++11 [class.copy]p7: 10112 // The [definition of an implicitly declared copy constructor] is 10113 // deprecated if the class has a user-declared copy assignment operator 10114 // or a user-declared destructor. 10115 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10116 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10117 10118 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10119 DiagnosticErrorTrap Trap(Diags); 10120 10121 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10122 Trap.hasErrorOccurred()) { 10123 Diag(CurrentLocation, diag::note_member_synthesized_at) 10124 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10125 CopyConstructor->setInvalidDecl(); 10126 } else { 10127 Sema::CompoundScopeRAII CompoundScope(*this); 10128 CopyConstructor->setBody(ActOnCompoundStmt( 10129 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None, 10130 /*isStmtExpr=*/ false).takeAs<Stmt>()); 10131 } 10132 10133 CopyConstructor->markUsed(Context); 10134 if (ASTMutationListener *L = getASTMutationListener()) { 10135 L->CompletedImplicitDefinition(CopyConstructor); 10136 } 10137 } 10138 10139 Sema::ImplicitExceptionSpecification 10140 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10141 CXXRecordDecl *ClassDecl = MD->getParent(); 10142 10143 // C++ [except.spec]p14: 10144 // An implicitly declared special member function (Clause 12) shall have an 10145 // exception-specification. [...] 10146 ImplicitExceptionSpecification ExceptSpec(*this); 10147 if (ClassDecl->isInvalidDecl()) 10148 return ExceptSpec; 10149 10150 // Direct base-class constructors. 10151 for (const auto &B : ClassDecl->bases()) { 10152 if (B.isVirtual()) // Handled below. 10153 continue; 10154 10155 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10156 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10157 CXXConstructorDecl *Constructor = 10158 LookupMovingConstructor(BaseClassDecl, 0); 10159 // If this is a deleted function, add it anyway. This might be conformant 10160 // with the standard. This might not. I'm not sure. It might not matter. 10161 if (Constructor) 10162 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10163 } 10164 } 10165 10166 // Virtual base-class constructors. 10167 for (const auto &B : ClassDecl->vbases()) { 10168 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10169 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10170 CXXConstructorDecl *Constructor = 10171 LookupMovingConstructor(BaseClassDecl, 0); 10172 // If this is a deleted function, add it anyway. This might be conformant 10173 // with the standard. This might not. I'm not sure. It might not matter. 10174 if (Constructor) 10175 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10176 } 10177 } 10178 10179 // Field constructors. 10180 for (const auto *F : ClassDecl->fields()) { 10181 QualType FieldType = Context.getBaseElementType(F->getType()); 10182 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10183 CXXConstructorDecl *Constructor = 10184 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10185 // If this is a deleted function, add it anyway. This might be conformant 10186 // with the standard. This might not. I'm not sure. It might not matter. 10187 // In particular, the problem is that this function never gets called. It 10188 // might just be ill-formed because this function attempts to refer to 10189 // a deleted function here. 10190 if (Constructor) 10191 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10192 } 10193 } 10194 10195 return ExceptSpec; 10196 } 10197 10198 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10199 CXXRecordDecl *ClassDecl) { 10200 assert(ClassDecl->needsImplicitMoveConstructor()); 10201 10202 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10203 if (DSM.isAlreadyBeingDeclared()) 10204 return 0; 10205 10206 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10207 QualType ArgType = Context.getRValueReferenceType(ClassType); 10208 10209 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10210 CXXMoveConstructor, 10211 false); 10212 10213 DeclarationName Name 10214 = Context.DeclarationNames.getCXXConstructorName( 10215 Context.getCanonicalType(ClassType)); 10216 SourceLocation ClassLoc = ClassDecl->getLocation(); 10217 DeclarationNameInfo NameInfo(Name, ClassLoc); 10218 10219 // C++11 [class.copy]p11: 10220 // An implicitly-declared copy/move constructor is an inline public 10221 // member of its class. 10222 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10223 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 10224 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10225 Constexpr); 10226 MoveConstructor->setAccess(AS_public); 10227 MoveConstructor->setDefaulted(); 10228 10229 // Build an exception specification pointing back at this member. 10230 FunctionProtoType::ExtProtoInfo EPI = 10231 getImplicitMethodEPI(*this, MoveConstructor); 10232 MoveConstructor->setType( 10233 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10234 10235 // Add the parameter to the constructor. 10236 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10237 ClassLoc, ClassLoc, 10238 /*IdentifierInfo=*/0, 10239 ArgType, /*TInfo=*/0, 10240 SC_None, 0); 10241 MoveConstructor->setParams(FromParam); 10242 10243 MoveConstructor->setTrivial( 10244 ClassDecl->needsOverloadResolutionForMoveConstructor() 10245 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10246 : ClassDecl->hasTrivialMoveConstructor()); 10247 10248 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10249 ClassDecl->setImplicitMoveConstructorIsDeleted(); 10250 SetDeclDeleted(MoveConstructor, ClassLoc); 10251 } 10252 10253 // Note that we have declared this constructor. 10254 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10255 10256 if (Scope *S = getScopeForContext(ClassDecl)) 10257 PushOnScopeChains(MoveConstructor, S, false); 10258 ClassDecl->addDecl(MoveConstructor); 10259 10260 return MoveConstructor; 10261 } 10262 10263 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 10264 CXXConstructorDecl *MoveConstructor) { 10265 assert((MoveConstructor->isDefaulted() && 10266 MoveConstructor->isMoveConstructor() && 10267 !MoveConstructor->doesThisDeclarationHaveABody() && 10268 !MoveConstructor->isDeleted()) && 10269 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 10270 10271 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 10272 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 10273 10274 SynthesizedFunctionScope Scope(*this, MoveConstructor); 10275 DiagnosticErrorTrap Trap(Diags); 10276 10277 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10278 Trap.hasErrorOccurred()) { 10279 Diag(CurrentLocation, diag::note_member_synthesized_at) 10280 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10281 MoveConstructor->setInvalidDecl(); 10282 } else { 10283 Sema::CompoundScopeRAII CompoundScope(*this); 10284 MoveConstructor->setBody(ActOnCompoundStmt( 10285 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None, 10286 /*isStmtExpr=*/ false).takeAs<Stmt>()); 10287 } 10288 10289 MoveConstructor->markUsed(Context); 10290 10291 if (ASTMutationListener *L = getASTMutationListener()) { 10292 L->CompletedImplicitDefinition(MoveConstructor); 10293 } 10294 } 10295 10296 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10297 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10298 } 10299 10300 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10301 SourceLocation CurrentLocation, 10302 CXXConversionDecl *Conv) { 10303 CXXRecordDecl *Lambda = Conv->getParent(); 10304 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 10305 // If we are defining a specialization of a conversion to function-ptr 10306 // cache the deduced template arguments for this specialization 10307 // so that we can use them to retrieve the corresponding call-operator 10308 // and static-invoker. 10309 const TemplateArgumentList *DeducedTemplateArgs = 0; 10310 10311 10312 // Retrieve the corresponding call-operator specialization. 10313 if (Lambda->isGenericLambda()) { 10314 assert(Conv->isFunctionTemplateSpecialization()); 10315 FunctionTemplateDecl *CallOpTemplate = 10316 CallOp->getDescribedFunctionTemplate(); 10317 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 10318 void *InsertPos = 0; 10319 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 10320 DeducedTemplateArgs->data(), 10321 DeducedTemplateArgs->size(), 10322 InsertPos); 10323 assert(CallOpSpec && 10324 "Conversion operator must have a corresponding call operator"); 10325 CallOp = cast<CXXMethodDecl>(CallOpSpec); 10326 } 10327 // Mark the call operator referenced (and add to pending instantiations 10328 // if necessary). 10329 // For both the conversion and static-invoker template specializations 10330 // we construct their body's in this function, so no need to add them 10331 // to the PendingInstantiations. 10332 MarkFunctionReferenced(CurrentLocation, CallOp); 10333 10334 SynthesizedFunctionScope Scope(*this, Conv); 10335 DiagnosticErrorTrap Trap(Diags); 10336 10337 // Retrieve the static invoker... 10338 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 10339 // ... and get the corresponding specialization for a generic lambda. 10340 if (Lambda->isGenericLambda()) { 10341 assert(DeducedTemplateArgs && 10342 "Must have deduced template arguments from Conversion Operator"); 10343 FunctionTemplateDecl *InvokeTemplate = 10344 Invoker->getDescribedFunctionTemplate(); 10345 void *InsertPos = 0; 10346 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 10347 DeducedTemplateArgs->data(), 10348 DeducedTemplateArgs->size(), 10349 InsertPos); 10350 assert(InvokeSpec && 10351 "Must have a corresponding static invoker specialization"); 10352 Invoker = cast<CXXMethodDecl>(InvokeSpec); 10353 } 10354 // Construct the body of the conversion function { return __invoke; }. 10355 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 10356 VK_LValue, Conv->getLocation()).take(); 10357 assert(FunctionRef && "Can't refer to __invoke function?"); 10358 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 10359 Conv->setBody(new (Context) CompoundStmt(Context, Return, 10360 Conv->getLocation(), 10361 Conv->getLocation())); 10362 10363 Conv->markUsed(Context); 10364 Conv->setReferenced(); 10365 10366 // Fill in the __invoke function with a dummy implementation. IR generation 10367 // will fill in the actual details. 10368 Invoker->markUsed(Context); 10369 Invoker->setReferenced(); 10370 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 10371 10372 if (ASTMutationListener *L = getASTMutationListener()) { 10373 L->CompletedImplicitDefinition(Conv); 10374 L->CompletedImplicitDefinition(Invoker); 10375 } 10376 } 10377 10378 10379 10380 void Sema::DefineImplicitLambdaToBlockPointerConversion( 10381 SourceLocation CurrentLocation, 10382 CXXConversionDecl *Conv) 10383 { 10384 assert(!Conv->getParent()->isGenericLambda()); 10385 10386 Conv->markUsed(Context); 10387 10388 SynthesizedFunctionScope Scope(*this, Conv); 10389 DiagnosticErrorTrap Trap(Diags); 10390 10391 // Copy-initialize the lambda object as needed to capture it. 10392 Expr *This = ActOnCXXThis(CurrentLocation).take(); 10393 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 10394 10395 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 10396 Conv->getLocation(), 10397 Conv, DerefThis); 10398 10399 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 10400 // behavior. Note that only the general conversion function does this 10401 // (since it's unusable otherwise); in the case where we inline the 10402 // block literal, it has block literal lifetime semantics. 10403 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 10404 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 10405 CK_CopyAndAutoreleaseBlockObject, 10406 BuildBlock.get(), 0, VK_RValue); 10407 10408 if (BuildBlock.isInvalid()) { 10409 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10410 Conv->setInvalidDecl(); 10411 return; 10412 } 10413 10414 // Create the return statement that returns the block from the conversion 10415 // function. 10416 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 10417 if (Return.isInvalid()) { 10418 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10419 Conv->setInvalidDecl(); 10420 return; 10421 } 10422 10423 // Set the body of the conversion function. 10424 Stmt *ReturnS = Return.take(); 10425 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 10426 Conv->getLocation(), 10427 Conv->getLocation())); 10428 10429 // We're done; notify the mutation listener, if any. 10430 if (ASTMutationListener *L = getASTMutationListener()) { 10431 L->CompletedImplicitDefinition(Conv); 10432 } 10433 } 10434 10435 /// \brief Determine whether the given list arguments contains exactly one 10436 /// "real" (non-default) argument. 10437 static bool hasOneRealArgument(MultiExprArg Args) { 10438 switch (Args.size()) { 10439 case 0: 10440 return false; 10441 10442 default: 10443 if (!Args[1]->isDefaultArgument()) 10444 return false; 10445 10446 // fall through 10447 case 1: 10448 return !Args[0]->isDefaultArgument(); 10449 } 10450 10451 return false; 10452 } 10453 10454 ExprResult 10455 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10456 CXXConstructorDecl *Constructor, 10457 MultiExprArg ExprArgs, 10458 bool HadMultipleCandidates, 10459 bool IsListInitialization, 10460 bool RequiresZeroInit, 10461 unsigned ConstructKind, 10462 SourceRange ParenRange) { 10463 bool Elidable = false; 10464 10465 // C++0x [class.copy]p34: 10466 // When certain criteria are met, an implementation is allowed to 10467 // omit the copy/move construction of a class object, even if the 10468 // copy/move constructor and/or destructor for the object have 10469 // side effects. [...] 10470 // - when a temporary class object that has not been bound to a 10471 // reference (12.2) would be copied/moved to a class object 10472 // with the same cv-unqualified type, the copy/move operation 10473 // can be omitted by constructing the temporary object 10474 // directly into the target of the omitted copy/move 10475 if (ConstructKind == CXXConstructExpr::CK_Complete && 10476 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10477 Expr *SubExpr = ExprArgs[0]; 10478 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10479 } 10480 10481 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10482 Elidable, ExprArgs, HadMultipleCandidates, 10483 IsListInitialization, RequiresZeroInit, 10484 ConstructKind, ParenRange); 10485 } 10486 10487 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 10488 /// including handling of its default argument expressions. 10489 ExprResult 10490 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10491 CXXConstructorDecl *Constructor, bool Elidable, 10492 MultiExprArg ExprArgs, 10493 bool HadMultipleCandidates, 10494 bool IsListInitialization, 10495 bool RequiresZeroInit, 10496 unsigned ConstructKind, 10497 SourceRange ParenRange) { 10498 MarkFunctionReferenced(ConstructLoc, Constructor); 10499 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 10500 Constructor, Elidable, ExprArgs, 10501 HadMultipleCandidates, 10502 IsListInitialization, RequiresZeroInit, 10503 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10504 ParenRange)); 10505 } 10506 10507 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10508 if (VD->isInvalidDecl()) return; 10509 10510 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10511 if (ClassDecl->isInvalidDecl()) return; 10512 if (ClassDecl->hasIrrelevantDestructor()) return; 10513 if (ClassDecl->isDependentContext()) return; 10514 10515 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10516 MarkFunctionReferenced(VD->getLocation(), Destructor); 10517 CheckDestructorAccess(VD->getLocation(), Destructor, 10518 PDiag(diag::err_access_dtor_var) 10519 << VD->getDeclName() 10520 << VD->getType()); 10521 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10522 10523 if (Destructor->isTrivial()) return; 10524 if (!VD->hasGlobalStorage()) return; 10525 10526 // Emit warning for non-trivial dtor in global scope (a real global, 10527 // class-static, function-static). 10528 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10529 10530 // TODO: this should be re-enabled for static locals by !CXAAtExit 10531 if (!VD->isStaticLocal()) 10532 Diag(VD->getLocation(), diag::warn_global_destructor); 10533 } 10534 10535 /// \brief Given a constructor and the set of arguments provided for the 10536 /// constructor, convert the arguments and add any required default arguments 10537 /// to form a proper call to this constructor. 10538 /// 10539 /// \returns true if an error occurred, false otherwise. 10540 bool 10541 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10542 MultiExprArg ArgsPtr, 10543 SourceLocation Loc, 10544 SmallVectorImpl<Expr*> &ConvertedArgs, 10545 bool AllowExplicit, 10546 bool IsListInitialization) { 10547 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10548 unsigned NumArgs = ArgsPtr.size(); 10549 Expr **Args = ArgsPtr.data(); 10550 10551 const FunctionProtoType *Proto 10552 = Constructor->getType()->getAs<FunctionProtoType>(); 10553 assert(Proto && "Constructor without a prototype?"); 10554 unsigned NumParams = Proto->getNumParams(); 10555 10556 // If too few arguments are available, we'll fill in the rest with defaults. 10557 if (NumArgs < NumParams) 10558 ConvertedArgs.reserve(NumParams); 10559 else 10560 ConvertedArgs.reserve(NumArgs); 10561 10562 VariadicCallType CallType = 10563 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10564 SmallVector<Expr *, 8> AllArgs; 10565 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10566 Proto, 0, 10567 llvm::makeArrayRef(Args, NumArgs), 10568 AllArgs, 10569 CallType, AllowExplicit, 10570 IsListInitialization); 10571 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 10572 10573 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 10574 10575 CheckConstructorCall(Constructor, 10576 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 10577 AllArgs.size()), 10578 Proto, Loc); 10579 10580 return Invalid; 10581 } 10582 10583 static inline bool 10584 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 10585 const FunctionDecl *FnDecl) { 10586 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 10587 if (isa<NamespaceDecl>(DC)) { 10588 return SemaRef.Diag(FnDecl->getLocation(), 10589 diag::err_operator_new_delete_declared_in_namespace) 10590 << FnDecl->getDeclName(); 10591 } 10592 10593 if (isa<TranslationUnitDecl>(DC) && 10594 FnDecl->getStorageClass() == SC_Static) { 10595 return SemaRef.Diag(FnDecl->getLocation(), 10596 diag::err_operator_new_delete_declared_static) 10597 << FnDecl->getDeclName(); 10598 } 10599 10600 return false; 10601 } 10602 10603 static inline bool 10604 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 10605 CanQualType ExpectedResultType, 10606 CanQualType ExpectedFirstParamType, 10607 unsigned DependentParamTypeDiag, 10608 unsigned InvalidParamTypeDiag) { 10609 QualType ResultType = 10610 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 10611 10612 // Check that the result type is not dependent. 10613 if (ResultType->isDependentType()) 10614 return SemaRef.Diag(FnDecl->getLocation(), 10615 diag::err_operator_new_delete_dependent_result_type) 10616 << FnDecl->getDeclName() << ExpectedResultType; 10617 10618 // Check that the result type is what we expect. 10619 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 10620 return SemaRef.Diag(FnDecl->getLocation(), 10621 diag::err_operator_new_delete_invalid_result_type) 10622 << FnDecl->getDeclName() << ExpectedResultType; 10623 10624 // A function template must have at least 2 parameters. 10625 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 10626 return SemaRef.Diag(FnDecl->getLocation(), 10627 diag::err_operator_new_delete_template_too_few_parameters) 10628 << FnDecl->getDeclName(); 10629 10630 // The function decl must have at least 1 parameter. 10631 if (FnDecl->getNumParams() == 0) 10632 return SemaRef.Diag(FnDecl->getLocation(), 10633 diag::err_operator_new_delete_too_few_parameters) 10634 << FnDecl->getDeclName(); 10635 10636 // Check the first parameter type is not dependent. 10637 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10638 if (FirstParamType->isDependentType()) 10639 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10640 << FnDecl->getDeclName() << ExpectedFirstParamType; 10641 10642 // Check that the first parameter type is what we expect. 10643 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10644 ExpectedFirstParamType) 10645 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10646 << FnDecl->getDeclName() << ExpectedFirstParamType; 10647 10648 return false; 10649 } 10650 10651 static bool 10652 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10653 // C++ [basic.stc.dynamic.allocation]p1: 10654 // A program is ill-formed if an allocation function is declared in a 10655 // namespace scope other than global scope or declared static in global 10656 // scope. 10657 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10658 return true; 10659 10660 CanQualType SizeTy = 10661 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10662 10663 // C++ [basic.stc.dynamic.allocation]p1: 10664 // The return type shall be void*. The first parameter shall have type 10665 // std::size_t. 10666 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10667 SizeTy, 10668 diag::err_operator_new_dependent_param_type, 10669 diag::err_operator_new_param_type)) 10670 return true; 10671 10672 // C++ [basic.stc.dynamic.allocation]p1: 10673 // The first parameter shall not have an associated default argument. 10674 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10675 return SemaRef.Diag(FnDecl->getLocation(), 10676 diag::err_operator_new_default_arg) 10677 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10678 10679 return false; 10680 } 10681 10682 static bool 10683 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10684 // C++ [basic.stc.dynamic.deallocation]p1: 10685 // A program is ill-formed if deallocation functions are declared in a 10686 // namespace scope other than global scope or declared static in global 10687 // scope. 10688 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10689 return true; 10690 10691 // C++ [basic.stc.dynamic.deallocation]p2: 10692 // Each deallocation function shall return void and its first parameter 10693 // shall be void*. 10694 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10695 SemaRef.Context.VoidPtrTy, 10696 diag::err_operator_delete_dependent_param_type, 10697 diag::err_operator_delete_param_type)) 10698 return true; 10699 10700 return false; 10701 } 10702 10703 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 10704 /// of this overloaded operator is well-formed. If so, returns false; 10705 /// otherwise, emits appropriate diagnostics and returns true. 10706 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10707 assert(FnDecl && FnDecl->isOverloadedOperator() && 10708 "Expected an overloaded operator declaration"); 10709 10710 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10711 10712 // C++ [over.oper]p5: 10713 // The allocation and deallocation functions, operator new, 10714 // operator new[], operator delete and operator delete[], are 10715 // described completely in 3.7.3. The attributes and restrictions 10716 // found in the rest of this subclause do not apply to them unless 10717 // explicitly stated in 3.7.3. 10718 if (Op == OO_Delete || Op == OO_Array_Delete) 10719 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10720 10721 if (Op == OO_New || Op == OO_Array_New) 10722 return CheckOperatorNewDeclaration(*this, FnDecl); 10723 10724 // C++ [over.oper]p6: 10725 // An operator function shall either be a non-static member 10726 // function or be a non-member function and have at least one 10727 // parameter whose type is a class, a reference to a class, an 10728 // enumeration, or a reference to an enumeration. 10729 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 10730 if (MethodDecl->isStatic()) 10731 return Diag(FnDecl->getLocation(), 10732 diag::err_operator_overload_static) << FnDecl->getDeclName(); 10733 } else { 10734 bool ClassOrEnumParam = false; 10735 for (auto Param : FnDecl->params()) { 10736 QualType ParamType = Param->getType().getNonReferenceType(); 10737 if (ParamType->isDependentType() || ParamType->isRecordType() || 10738 ParamType->isEnumeralType()) { 10739 ClassOrEnumParam = true; 10740 break; 10741 } 10742 } 10743 10744 if (!ClassOrEnumParam) 10745 return Diag(FnDecl->getLocation(), 10746 diag::err_operator_overload_needs_class_or_enum) 10747 << FnDecl->getDeclName(); 10748 } 10749 10750 // C++ [over.oper]p8: 10751 // An operator function cannot have default arguments (8.3.6), 10752 // except where explicitly stated below. 10753 // 10754 // Only the function-call operator allows default arguments 10755 // (C++ [over.call]p1). 10756 if (Op != OO_Call) { 10757 for (auto Param : FnDecl->params()) { 10758 if (Param->hasDefaultArg()) 10759 return Diag(Param->getLocation(), 10760 diag::err_operator_overload_default_arg) 10761 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 10762 } 10763 } 10764 10765 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 10766 { false, false, false } 10767 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 10768 , { Unary, Binary, MemberOnly } 10769 #include "clang/Basic/OperatorKinds.def" 10770 }; 10771 10772 bool CanBeUnaryOperator = OperatorUses[Op][0]; 10773 bool CanBeBinaryOperator = OperatorUses[Op][1]; 10774 bool MustBeMemberOperator = OperatorUses[Op][2]; 10775 10776 // C++ [over.oper]p8: 10777 // [...] Operator functions cannot have more or fewer parameters 10778 // than the number required for the corresponding operator, as 10779 // described in the rest of this subclause. 10780 unsigned NumParams = FnDecl->getNumParams() 10781 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 10782 if (Op != OO_Call && 10783 ((NumParams == 1 && !CanBeUnaryOperator) || 10784 (NumParams == 2 && !CanBeBinaryOperator) || 10785 (NumParams < 1) || (NumParams > 2))) { 10786 // We have the wrong number of parameters. 10787 unsigned ErrorKind; 10788 if (CanBeUnaryOperator && CanBeBinaryOperator) { 10789 ErrorKind = 2; // 2 -> unary or binary. 10790 } else if (CanBeUnaryOperator) { 10791 ErrorKind = 0; // 0 -> unary 10792 } else { 10793 assert(CanBeBinaryOperator && 10794 "All non-call overloaded operators are unary or binary!"); 10795 ErrorKind = 1; // 1 -> binary 10796 } 10797 10798 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 10799 << FnDecl->getDeclName() << NumParams << ErrorKind; 10800 } 10801 10802 // Overloaded operators other than operator() cannot be variadic. 10803 if (Op != OO_Call && 10804 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 10805 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 10806 << FnDecl->getDeclName(); 10807 } 10808 10809 // Some operators must be non-static member functions. 10810 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 10811 return Diag(FnDecl->getLocation(), 10812 diag::err_operator_overload_must_be_member) 10813 << FnDecl->getDeclName(); 10814 } 10815 10816 // C++ [over.inc]p1: 10817 // The user-defined function called operator++ implements the 10818 // prefix and postfix ++ operator. If this function is a member 10819 // function with no parameters, or a non-member function with one 10820 // parameter of class or enumeration type, it defines the prefix 10821 // increment operator ++ for objects of that type. If the function 10822 // is a member function with one parameter (which shall be of type 10823 // int) or a non-member function with two parameters (the second 10824 // of which shall be of type int), it defines the postfix 10825 // increment operator ++ for objects of that type. 10826 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 10827 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 10828 QualType ParamType = LastParam->getType(); 10829 10830 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 10831 !ParamType->isDependentType()) 10832 return Diag(LastParam->getLocation(), 10833 diag::err_operator_overload_post_incdec_must_be_int) 10834 << LastParam->getType() << (Op == OO_MinusMinus); 10835 } 10836 10837 return false; 10838 } 10839 10840 /// CheckLiteralOperatorDeclaration - Check whether the declaration 10841 /// of this literal operator function is well-formed. If so, returns 10842 /// false; otherwise, emits appropriate diagnostics and returns true. 10843 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 10844 if (isa<CXXMethodDecl>(FnDecl)) { 10845 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 10846 << FnDecl->getDeclName(); 10847 return true; 10848 } 10849 10850 if (FnDecl->isExternC()) { 10851 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 10852 return true; 10853 } 10854 10855 bool Valid = false; 10856 10857 // This might be the definition of a literal operator template. 10858 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 10859 // This might be a specialization of a literal operator template. 10860 if (!TpDecl) 10861 TpDecl = FnDecl->getPrimaryTemplate(); 10862 10863 // template <char...> type operator "" name() and 10864 // template <class T, T...> type operator "" name() are the only valid 10865 // template signatures, and the only valid signatures with no parameters. 10866 if (TpDecl) { 10867 if (FnDecl->param_size() == 0) { 10868 // Must have one or two template parameters 10869 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 10870 if (Params->size() == 1) { 10871 NonTypeTemplateParmDecl *PmDecl = 10872 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 10873 10874 // The template parameter must be a char parameter pack. 10875 if (PmDecl && PmDecl->isTemplateParameterPack() && 10876 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 10877 Valid = true; 10878 } else if (Params->size() == 2) { 10879 TemplateTypeParmDecl *PmType = 10880 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 10881 NonTypeTemplateParmDecl *PmArgs = 10882 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 10883 10884 // The second template parameter must be a parameter pack with the 10885 // first template parameter as its type. 10886 if (PmType && PmArgs && 10887 !PmType->isTemplateParameterPack() && 10888 PmArgs->isTemplateParameterPack()) { 10889 const TemplateTypeParmType *TArgs = 10890 PmArgs->getType()->getAs<TemplateTypeParmType>(); 10891 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 10892 TArgs->getIndex() == PmType->getIndex()) { 10893 Valid = true; 10894 if (ActiveTemplateInstantiations.empty()) 10895 Diag(FnDecl->getLocation(), 10896 diag::ext_string_literal_operator_template); 10897 } 10898 } 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 (auto Param : FnDecl->params()) { 10965 if (Param->hasDefaultArg()) { 10966 Diag(Param->getDefaultArgRange().getBegin(), 10967 diag::err_literal_operator_default_argument) 10968 << Param->getDefaultArgRange(); 10969 break; 10970 } 10971 } 10972 10973 StringRef LiteralName 10974 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 10975 if (LiteralName[0] != '_') { 10976 // C++11 [usrlit.suffix]p1: 10977 // Literal suffix identifiers that do not start with an underscore 10978 // are reserved for future standardization. 10979 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 10980 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 10981 } 10982 10983 return false; 10984 } 10985 10986 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 10987 /// linkage specification, including the language and (if present) 10988 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 10989 /// language string literal. LBraceLoc, if valid, provides the location of 10990 /// the '{' brace. Otherwise, this linkage specification does not 10991 /// have any braces. 10992 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 10993 Expr *LangStr, 10994 SourceLocation LBraceLoc) { 10995 StringLiteral *Lit = cast<StringLiteral>(LangStr); 10996 if (!Lit->isAscii()) { 10997 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 10998 << LangStr->getSourceRange(); 10999 return 0; 11000 } 11001 11002 StringRef Lang = Lit->getString(); 11003 LinkageSpecDecl::LanguageIDs Language; 11004 if (Lang == "C") 11005 Language = LinkageSpecDecl::lang_c; 11006 else if (Lang == "C++") 11007 Language = LinkageSpecDecl::lang_cxx; 11008 else { 11009 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11010 << LangStr->getSourceRange(); 11011 return 0; 11012 } 11013 11014 // FIXME: Add all the various semantics of linkage specifications 11015 11016 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11017 LangStr->getExprLoc(), Language, 11018 LBraceLoc.isValid()); 11019 CurContext->addDecl(D); 11020 PushDeclContext(S, D); 11021 return D; 11022 } 11023 11024 /// ActOnFinishLinkageSpecification - Complete the definition of 11025 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11026 /// valid, it's the position of the closing '}' brace in a linkage 11027 /// specification that uses braces. 11028 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11029 Decl *LinkageSpec, 11030 SourceLocation RBraceLoc) { 11031 if (RBraceLoc.isValid()) { 11032 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11033 LSDecl->setRBraceLoc(RBraceLoc); 11034 } 11035 PopDeclContext(); 11036 return LinkageSpec; 11037 } 11038 11039 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11040 AttributeList *AttrList, 11041 SourceLocation SemiLoc) { 11042 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11043 // Attribute declarations appertain to empty declaration so we handle 11044 // them here. 11045 if (AttrList) 11046 ProcessDeclAttributeList(S, ED, AttrList); 11047 11048 CurContext->addDecl(ED); 11049 return ED; 11050 } 11051 11052 /// \brief Perform semantic analysis for the variable declaration that 11053 /// occurs within a C++ catch clause, returning the newly-created 11054 /// variable. 11055 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11056 TypeSourceInfo *TInfo, 11057 SourceLocation StartLoc, 11058 SourceLocation Loc, 11059 IdentifierInfo *Name) { 11060 bool Invalid = false; 11061 QualType ExDeclType = TInfo->getType(); 11062 11063 // Arrays and functions decay. 11064 if (ExDeclType->isArrayType()) 11065 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11066 else if (ExDeclType->isFunctionType()) 11067 ExDeclType = Context.getPointerType(ExDeclType); 11068 11069 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11070 // The exception-declaration shall not denote a pointer or reference to an 11071 // incomplete type, other than [cv] void*. 11072 // N2844 forbids rvalue references. 11073 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11074 Diag(Loc, diag::err_catch_rvalue_ref); 11075 Invalid = true; 11076 } 11077 11078 QualType BaseType = ExDeclType; 11079 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11080 unsigned DK = diag::err_catch_incomplete; 11081 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11082 BaseType = Ptr->getPointeeType(); 11083 Mode = 1; 11084 DK = diag::err_catch_incomplete_ptr; 11085 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11086 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11087 BaseType = Ref->getPointeeType(); 11088 Mode = 2; 11089 DK = diag::err_catch_incomplete_ref; 11090 } 11091 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11092 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11093 Invalid = true; 11094 11095 if (!Invalid && !ExDeclType->isDependentType() && 11096 RequireNonAbstractType(Loc, ExDeclType, 11097 diag::err_abstract_type_in_decl, 11098 AbstractVariableType)) 11099 Invalid = true; 11100 11101 // Only the non-fragile NeXT runtime currently supports C++ catches 11102 // of ObjC types, and no runtime supports catching ObjC types by value. 11103 if (!Invalid && getLangOpts().ObjC1) { 11104 QualType T = ExDeclType; 11105 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11106 T = RT->getPointeeType(); 11107 11108 if (T->isObjCObjectType()) { 11109 Diag(Loc, diag::err_objc_object_catch); 11110 Invalid = true; 11111 } else if (T->isObjCObjectPointerType()) { 11112 // FIXME: should this be a test for macosx-fragile specifically? 11113 if (getLangOpts().ObjCRuntime.isFragile()) 11114 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11115 } 11116 } 11117 11118 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11119 ExDeclType, TInfo, SC_None); 11120 ExDecl->setExceptionVariable(true); 11121 11122 // In ARC, infer 'retaining' for variables of retainable type. 11123 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11124 Invalid = true; 11125 11126 if (!Invalid && !ExDeclType->isDependentType()) { 11127 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11128 // Insulate this from anything else we might currently be parsing. 11129 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11130 11131 // C++ [except.handle]p16: 11132 // The object declared in an exception-declaration or, if the 11133 // exception-declaration does not specify a name, a temporary (12.2) is 11134 // copy-initialized (8.5) from the exception object. [...] 11135 // The object is destroyed when the handler exits, after the destruction 11136 // of any automatic objects initialized within the handler. 11137 // 11138 // We just pretend to initialize the object with itself, then make sure 11139 // it can be destroyed later. 11140 QualType initType = ExDeclType; 11141 11142 InitializedEntity entity = 11143 InitializedEntity::InitializeVariable(ExDecl); 11144 InitializationKind initKind = 11145 InitializationKind::CreateCopy(Loc, SourceLocation()); 11146 11147 Expr *opaqueValue = 11148 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11149 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11150 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11151 if (result.isInvalid()) 11152 Invalid = true; 11153 else { 11154 // If the constructor used was non-trivial, set this as the 11155 // "initializer". 11156 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>(); 11157 if (!construct->getConstructor()->isTrivial()) { 11158 Expr *init = MaybeCreateExprWithCleanups(construct); 11159 ExDecl->setInit(init); 11160 } 11161 11162 // And make sure it's destructable. 11163 FinalizeVarWithDestructor(ExDecl, recordType); 11164 } 11165 } 11166 } 11167 11168 if (Invalid) 11169 ExDecl->setInvalidDecl(); 11170 11171 return ExDecl; 11172 } 11173 11174 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11175 /// handler. 11176 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11177 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11178 bool Invalid = D.isInvalidType(); 11179 11180 // Check for unexpanded parameter packs. 11181 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11182 UPPC_ExceptionType)) { 11183 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11184 D.getIdentifierLoc()); 11185 Invalid = true; 11186 } 11187 11188 IdentifierInfo *II = D.getIdentifier(); 11189 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11190 LookupOrdinaryName, 11191 ForRedeclaration)) { 11192 // The scope should be freshly made just for us. There is just no way 11193 // it contains any previous declaration. 11194 assert(!S->isDeclScope(PrevDecl)); 11195 if (PrevDecl->isTemplateParameter()) { 11196 // Maybe we will complain about the shadowed template parameter. 11197 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11198 PrevDecl = 0; 11199 } 11200 } 11201 11202 if (D.getCXXScopeSpec().isSet() && !Invalid) { 11203 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 11204 << D.getCXXScopeSpec().getRange(); 11205 Invalid = true; 11206 } 11207 11208 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 11209 D.getLocStart(), 11210 D.getIdentifierLoc(), 11211 D.getIdentifier()); 11212 if (Invalid) 11213 ExDecl->setInvalidDecl(); 11214 11215 // Add the exception declaration into this scope. 11216 if (II) 11217 PushOnScopeChains(ExDecl, S); 11218 else 11219 CurContext->addDecl(ExDecl); 11220 11221 ProcessDeclAttributes(S, ExDecl, D); 11222 return ExDecl; 11223 } 11224 11225 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11226 Expr *AssertExpr, 11227 Expr *AssertMessageExpr, 11228 SourceLocation RParenLoc) { 11229 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 11230 11231 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 11232 return 0; 11233 11234 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 11235 AssertMessage, RParenLoc, false); 11236 } 11237 11238 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11239 Expr *AssertExpr, 11240 StringLiteral *AssertMessage, 11241 SourceLocation RParenLoc, 11242 bool Failed) { 11243 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 11244 !Failed) { 11245 // In a static_assert-declaration, the constant-expression shall be a 11246 // constant expression that can be contextually converted to bool. 11247 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 11248 if (Converted.isInvalid()) 11249 Failed = true; 11250 11251 llvm::APSInt Cond; 11252 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 11253 diag::err_static_assert_expression_is_not_constant, 11254 /*AllowFold=*/false).isInvalid()) 11255 Failed = true; 11256 11257 if (!Failed && !Cond) { 11258 SmallString<256> MsgBuffer; 11259 llvm::raw_svector_ostream Msg(MsgBuffer); 11260 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 11261 Diag(StaticAssertLoc, diag::err_static_assert_failed) 11262 << Msg.str() << AssertExpr->getSourceRange(); 11263 Failed = true; 11264 } 11265 } 11266 11267 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 11268 AssertExpr, AssertMessage, RParenLoc, 11269 Failed); 11270 11271 CurContext->addDecl(Decl); 11272 return Decl; 11273 } 11274 11275 /// \brief Perform semantic analysis of the given friend type declaration. 11276 /// 11277 /// \returns A friend declaration that. 11278 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 11279 SourceLocation FriendLoc, 11280 TypeSourceInfo *TSInfo) { 11281 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 11282 11283 QualType T = TSInfo->getType(); 11284 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 11285 11286 // C++03 [class.friend]p2: 11287 // An elaborated-type-specifier shall be used in a friend declaration 11288 // for a class.* 11289 // 11290 // * The class-key of the elaborated-type-specifier is required. 11291 if (!ActiveTemplateInstantiations.empty()) { 11292 // Do not complain about the form of friend template types during 11293 // template instantiation; we will already have complained when the 11294 // template was declared. 11295 } else { 11296 if (!T->isElaboratedTypeSpecifier()) { 11297 // If we evaluated the type to a record type, suggest putting 11298 // a tag in front. 11299 if (const RecordType *RT = T->getAs<RecordType>()) { 11300 RecordDecl *RD = RT->getDecl(); 11301 11302 std::string InsertionText = std::string(" ") + RD->getKindName(); 11303 11304 Diag(TypeRange.getBegin(), 11305 getLangOpts().CPlusPlus11 ? 11306 diag::warn_cxx98_compat_unelaborated_friend_type : 11307 diag::ext_unelaborated_friend_type) 11308 << (unsigned) RD->getTagKind() 11309 << T 11310 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 11311 InsertionText); 11312 } else { 11313 Diag(FriendLoc, 11314 getLangOpts().CPlusPlus11 ? 11315 diag::warn_cxx98_compat_nonclass_type_friend : 11316 diag::ext_nonclass_type_friend) 11317 << T 11318 << TypeRange; 11319 } 11320 } else if (T->getAs<EnumType>()) { 11321 Diag(FriendLoc, 11322 getLangOpts().CPlusPlus11 ? 11323 diag::warn_cxx98_compat_enum_friend : 11324 diag::ext_enum_friend) 11325 << T 11326 << TypeRange; 11327 } 11328 11329 // C++11 [class.friend]p3: 11330 // A friend declaration that does not declare a function shall have one 11331 // of the following forms: 11332 // friend elaborated-type-specifier ; 11333 // friend simple-type-specifier ; 11334 // friend typename-specifier ; 11335 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 11336 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 11337 } 11338 11339 // If the type specifier in a friend declaration designates a (possibly 11340 // cv-qualified) class type, that class is declared as a friend; otherwise, 11341 // the friend declaration is ignored. 11342 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 11343 } 11344 11345 /// Handle a friend tag declaration where the scope specifier was 11346 /// templated. 11347 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 11348 unsigned TagSpec, SourceLocation TagLoc, 11349 CXXScopeSpec &SS, 11350 IdentifierInfo *Name, 11351 SourceLocation NameLoc, 11352 AttributeList *Attr, 11353 MultiTemplateParamsArg TempParamLists) { 11354 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11355 11356 bool isExplicitSpecialization = false; 11357 bool Invalid = false; 11358 11359 if (TemplateParameterList *TemplateParams = 11360 MatchTemplateParametersToScopeSpecifier( 11361 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true, 11362 isExplicitSpecialization, Invalid)) { 11363 if (TemplateParams->size() > 0) { 11364 // This is a declaration of a class template. 11365 if (Invalid) 11366 return 0; 11367 11368 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 11369 SS, Name, NameLoc, Attr, 11370 TemplateParams, AS_public, 11371 /*ModulePrivateLoc=*/SourceLocation(), 11372 TempParamLists.size() - 1, 11373 TempParamLists.data()).take(); 11374 } else { 11375 // The "template<>" header is extraneous. 11376 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11377 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11378 isExplicitSpecialization = true; 11379 } 11380 } 11381 11382 if (Invalid) return 0; 11383 11384 bool isAllExplicitSpecializations = true; 11385 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 11386 if (TempParamLists[I]->size()) { 11387 isAllExplicitSpecializations = false; 11388 break; 11389 } 11390 } 11391 11392 // FIXME: don't ignore attributes. 11393 11394 // If it's explicit specializations all the way down, just forget 11395 // about the template header and build an appropriate non-templated 11396 // friend. TODO: for source fidelity, remember the headers. 11397 if (isAllExplicitSpecializations) { 11398 if (SS.isEmpty()) { 11399 bool Owned = false; 11400 bool IsDependent = false; 11401 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 11402 Attr, AS_public, 11403 /*ModulePrivateLoc=*/SourceLocation(), 11404 MultiTemplateParamsArg(), Owned, IsDependent, 11405 /*ScopedEnumKWLoc=*/SourceLocation(), 11406 /*ScopedEnumUsesClassTag=*/false, 11407 /*UnderlyingType=*/TypeResult(), 11408 /*IsTypeSpecifier=*/false); 11409 } 11410 11411 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11412 ElaboratedTypeKeyword Keyword 11413 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11414 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 11415 *Name, NameLoc); 11416 if (T.isNull()) 11417 return 0; 11418 11419 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11420 if (isa<DependentNameType>(T)) { 11421 DependentNameTypeLoc TL = 11422 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11423 TL.setElaboratedKeywordLoc(TagLoc); 11424 TL.setQualifierLoc(QualifierLoc); 11425 TL.setNameLoc(NameLoc); 11426 } else { 11427 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11428 TL.setElaboratedKeywordLoc(TagLoc); 11429 TL.setQualifierLoc(QualifierLoc); 11430 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 11431 } 11432 11433 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11434 TSI, FriendLoc, TempParamLists); 11435 Friend->setAccess(AS_public); 11436 CurContext->addDecl(Friend); 11437 return Friend; 11438 } 11439 11440 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 11441 11442 11443 11444 // Handle the case of a templated-scope friend class. e.g. 11445 // template <class T> class A<T>::B; 11446 // FIXME: we don't support these right now. 11447 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 11448 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 11449 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11450 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 11451 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11452 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11453 TL.setElaboratedKeywordLoc(TagLoc); 11454 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11455 TL.setNameLoc(NameLoc); 11456 11457 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11458 TSI, FriendLoc, TempParamLists); 11459 Friend->setAccess(AS_public); 11460 Friend->setUnsupportedFriend(true); 11461 CurContext->addDecl(Friend); 11462 return Friend; 11463 } 11464 11465 11466 /// Handle a friend type declaration. This works in tandem with 11467 /// ActOnTag. 11468 /// 11469 /// Notes on friend class templates: 11470 /// 11471 /// We generally treat friend class declarations as if they were 11472 /// declaring a class. So, for example, the elaborated type specifier 11473 /// in a friend declaration is required to obey the restrictions of a 11474 /// class-head (i.e. no typedefs in the scope chain), template 11475 /// parameters are required to match up with simple template-ids, &c. 11476 /// However, unlike when declaring a template specialization, it's 11477 /// okay to refer to a template specialization without an empty 11478 /// template parameter declaration, e.g. 11479 /// friend class A<T>::B<unsigned>; 11480 /// We permit this as a special case; if there are any template 11481 /// parameters present at all, require proper matching, i.e. 11482 /// template <> template \<class T> friend class A<int>::B; 11483 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 11484 MultiTemplateParamsArg TempParams) { 11485 SourceLocation Loc = DS.getLocStart(); 11486 11487 assert(DS.isFriendSpecified()); 11488 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11489 11490 // Try to convert the decl specifier to a type. This works for 11491 // friend templates because ActOnTag never produces a ClassTemplateDecl 11492 // for a TUK_Friend. 11493 Declarator TheDeclarator(DS, Declarator::MemberContext); 11494 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11495 QualType T = TSI->getType(); 11496 if (TheDeclarator.isInvalidType()) 11497 return 0; 11498 11499 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11500 return 0; 11501 11502 // This is definitely an error in C++98. It's probably meant to 11503 // be forbidden in C++0x, too, but the specification is just 11504 // poorly written. 11505 // 11506 // The problem is with declarations like the following: 11507 // template <T> friend A<T>::foo; 11508 // where deciding whether a class C is a friend or not now hinges 11509 // on whether there exists an instantiation of A that causes 11510 // 'foo' to equal C. There are restrictions on class-heads 11511 // (which we declare (by fiat) elaborated friend declarations to 11512 // be) that makes this tractable. 11513 // 11514 // FIXME: handle "template <> friend class A<T>;", which 11515 // is possibly well-formed? Who even knows? 11516 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11517 Diag(Loc, diag::err_tagless_friend_type_template) 11518 << DS.getSourceRange(); 11519 return 0; 11520 } 11521 11522 // C++98 [class.friend]p1: A friend of a class is a function 11523 // or class that is not a member of the class . . . 11524 // This is fixed in DR77, which just barely didn't make the C++03 11525 // deadline. It's also a very silly restriction that seriously 11526 // affects inner classes and which nobody else seems to implement; 11527 // thus we never diagnose it, not even in -pedantic. 11528 // 11529 // But note that we could warn about it: it's always useless to 11530 // friend one of your own members (it's not, however, worthless to 11531 // friend a member of an arbitrary specialization of your template). 11532 11533 Decl *D; 11534 if (unsigned NumTempParamLists = TempParams.size()) 11535 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11536 NumTempParamLists, 11537 TempParams.data(), 11538 TSI, 11539 DS.getFriendSpecLoc()); 11540 else 11541 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11542 11543 if (!D) 11544 return 0; 11545 11546 D->setAccess(AS_public); 11547 CurContext->addDecl(D); 11548 11549 return D; 11550 } 11551 11552 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11553 MultiTemplateParamsArg TemplateParams) { 11554 const DeclSpec &DS = D.getDeclSpec(); 11555 11556 assert(DS.isFriendSpecified()); 11557 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11558 11559 SourceLocation Loc = D.getIdentifierLoc(); 11560 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11561 11562 // C++ [class.friend]p1 11563 // A friend of a class is a function or class.... 11564 // Note that this sees through typedefs, which is intended. 11565 // It *doesn't* see through dependent types, which is correct 11566 // according to [temp.arg.type]p3: 11567 // If a declaration acquires a function type through a 11568 // type dependent on a template-parameter and this causes 11569 // a declaration that does not use the syntactic form of a 11570 // function declarator to have a function type, the program 11571 // is ill-formed. 11572 if (!TInfo->getType()->isFunctionType()) { 11573 Diag(Loc, diag::err_unexpected_friend); 11574 11575 // It might be worthwhile to try to recover by creating an 11576 // appropriate declaration. 11577 return 0; 11578 } 11579 11580 // C++ [namespace.memdef]p3 11581 // - If a friend declaration in a non-local class first declares a 11582 // class or function, the friend class or function is a member 11583 // of the innermost enclosing namespace. 11584 // - The name of the friend is not found by simple name lookup 11585 // until a matching declaration is provided in that namespace 11586 // scope (either before or after the class declaration granting 11587 // friendship). 11588 // - If a friend function is called, its name may be found by the 11589 // name lookup that considers functions from namespaces and 11590 // classes associated with the types of the function arguments. 11591 // - When looking for a prior declaration of a class or a function 11592 // declared as a friend, scopes outside the innermost enclosing 11593 // namespace scope are not considered. 11594 11595 CXXScopeSpec &SS = D.getCXXScopeSpec(); 11596 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 11597 DeclarationName Name = NameInfo.getName(); 11598 assert(Name); 11599 11600 // Check for unexpanded parameter packs. 11601 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 11602 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 11603 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 11604 return 0; 11605 11606 // The context we found the declaration in, or in which we should 11607 // create the declaration. 11608 DeclContext *DC; 11609 Scope *DCScope = S; 11610 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11611 ForRedeclaration); 11612 11613 // There are five cases here. 11614 // - There's no scope specifier and we're in a local class. Only look 11615 // for functions declared in the immediately-enclosing block scope. 11616 // We recover from invalid scope qualifiers as if they just weren't there. 11617 FunctionDecl *FunctionContainingLocalClass = 0; 11618 if ((SS.isInvalid() || !SS.isSet()) && 11619 (FunctionContainingLocalClass = 11620 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 11621 // C++11 [class.friend]p11: 11622 // If a friend declaration appears in a local class and the name 11623 // specified is an unqualified name, a prior declaration is 11624 // looked up without considering scopes that are outside the 11625 // innermost enclosing non-class scope. For a friend function 11626 // declaration, if there is no prior declaration, the program is 11627 // ill-formed. 11628 11629 // Find the innermost enclosing non-class scope. This is the block 11630 // scope containing the local class definition (or for a nested class, 11631 // the outer local class). 11632 DCScope = S->getFnParent(); 11633 11634 // Look up the function name in the scope. 11635 Previous.clear(LookupLocalFriendName); 11636 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 11637 11638 if (!Previous.empty()) { 11639 // All possible previous declarations must have the same context: 11640 // either they were declared at block scope or they are members of 11641 // one of the enclosing local classes. 11642 DC = Previous.getRepresentativeDecl()->getDeclContext(); 11643 } else { 11644 // This is ill-formed, but provide the context that we would have 11645 // declared the function in, if we were permitted to, for error recovery. 11646 DC = FunctionContainingLocalClass; 11647 } 11648 adjustContextForLocalExternDecl(DC); 11649 11650 // C++ [class.friend]p6: 11651 // A function can be defined in a friend declaration of a class if and 11652 // only if the class is a non-local class (9.8), the function name is 11653 // unqualified, and the function has namespace scope. 11654 if (D.isFunctionDefinition()) { 11655 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11656 } 11657 11658 // - There's no scope specifier, in which case we just go to the 11659 // appropriate scope and look for a function or function template 11660 // there as appropriate. 11661 } else if (SS.isInvalid() || !SS.isSet()) { 11662 // C++11 [namespace.memdef]p3: 11663 // If the name in a friend declaration is neither qualified nor 11664 // a template-id and the declaration is a function or an 11665 // elaborated-type-specifier, the lookup to determine whether 11666 // the entity has been previously declared shall not consider 11667 // any scopes outside the innermost enclosing namespace. 11668 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 11669 11670 // Find the appropriate context according to the above. 11671 DC = CurContext; 11672 11673 // Skip class contexts. If someone can cite chapter and verse 11674 // for this behavior, that would be nice --- it's what GCC and 11675 // EDG do, and it seems like a reasonable intent, but the spec 11676 // really only says that checks for unqualified existing 11677 // declarations should stop at the nearest enclosing namespace, 11678 // not that they should only consider the nearest enclosing 11679 // namespace. 11680 while (DC->isRecord()) 11681 DC = DC->getParent(); 11682 11683 DeclContext *LookupDC = DC; 11684 while (LookupDC->isTransparentContext()) 11685 LookupDC = LookupDC->getParent(); 11686 11687 while (true) { 11688 LookupQualifiedName(Previous, LookupDC); 11689 11690 if (!Previous.empty()) { 11691 DC = LookupDC; 11692 break; 11693 } 11694 11695 if (isTemplateId) { 11696 if (isa<TranslationUnitDecl>(LookupDC)) break; 11697 } else { 11698 if (LookupDC->isFileContext()) break; 11699 } 11700 LookupDC = LookupDC->getParent(); 11701 } 11702 11703 DCScope = getScopeForDeclContext(S, DC); 11704 11705 // - There's a non-dependent scope specifier, in which case we 11706 // compute it and do a previous lookup there for a function 11707 // or function template. 11708 } else if (!SS.getScopeRep()->isDependent()) { 11709 DC = computeDeclContext(SS); 11710 if (!DC) return 0; 11711 11712 if (RequireCompleteDeclContext(SS, DC)) return 0; 11713 11714 LookupQualifiedName(Previous, DC); 11715 11716 // Ignore things found implicitly in the wrong scope. 11717 // TODO: better diagnostics for this case. Suggesting the right 11718 // qualified scope would be nice... 11719 LookupResult::Filter F = Previous.makeFilter(); 11720 while (F.hasNext()) { 11721 NamedDecl *D = F.next(); 11722 if (!DC->InEnclosingNamespaceSetOf( 11723 D->getDeclContext()->getRedeclContext())) 11724 F.erase(); 11725 } 11726 F.done(); 11727 11728 if (Previous.empty()) { 11729 D.setInvalidType(); 11730 Diag(Loc, diag::err_qualified_friend_not_found) 11731 << Name << TInfo->getType(); 11732 return 0; 11733 } 11734 11735 // C++ [class.friend]p1: A friend of a class is a function or 11736 // class that is not a member of the class . . . 11737 if (DC->Equals(CurContext)) 11738 Diag(DS.getFriendSpecLoc(), 11739 getLangOpts().CPlusPlus11 ? 11740 diag::warn_cxx98_compat_friend_is_member : 11741 diag::err_friend_is_member); 11742 11743 if (D.isFunctionDefinition()) { 11744 // C++ [class.friend]p6: 11745 // A function can be defined in a friend declaration of a class if and 11746 // only if the class is a non-local class (9.8), the function name is 11747 // unqualified, and the function has namespace scope. 11748 SemaDiagnosticBuilder DB 11749 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 11750 11751 DB << SS.getScopeRep(); 11752 if (DC->isFileContext()) 11753 DB << FixItHint::CreateRemoval(SS.getRange()); 11754 SS.clear(); 11755 } 11756 11757 // - There's a scope specifier that does not match any template 11758 // parameter lists, in which case we use some arbitrary context, 11759 // create a method or method template, and wait for instantiation. 11760 // - There's a scope specifier that does match some template 11761 // parameter lists, which we don't handle right now. 11762 } else { 11763 if (D.isFunctionDefinition()) { 11764 // C++ [class.friend]p6: 11765 // A function can be defined in a friend declaration of a class if and 11766 // only if the class is a non-local class (9.8), the function name is 11767 // unqualified, and the function has namespace scope. 11768 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 11769 << SS.getScopeRep(); 11770 } 11771 11772 DC = CurContext; 11773 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 11774 } 11775 11776 if (!DC->isRecord()) { 11777 // This implies that it has to be an operator or function. 11778 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 11779 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 11780 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 11781 Diag(Loc, diag::err_introducing_special_friend) << 11782 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 11783 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 11784 return 0; 11785 } 11786 } 11787 11788 // FIXME: This is an egregious hack to cope with cases where the scope stack 11789 // does not contain the declaration context, i.e., in an out-of-line 11790 // definition of a class. 11791 Scope FakeDCScope(S, Scope::DeclScope, Diags); 11792 if (!DCScope) { 11793 FakeDCScope.setEntity(DC); 11794 DCScope = &FakeDCScope; 11795 } 11796 11797 bool AddToScope = true; 11798 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 11799 TemplateParams, AddToScope); 11800 if (!ND) return 0; 11801 11802 assert(ND->getLexicalDeclContext() == CurContext); 11803 11804 // If we performed typo correction, we might have added a scope specifier 11805 // and changed the decl context. 11806 DC = ND->getDeclContext(); 11807 11808 // Add the function declaration to the appropriate lookup tables, 11809 // adjusting the redeclarations list as necessary. We don't 11810 // want to do this yet if the friending class is dependent. 11811 // 11812 // Also update the scope-based lookup if the target context's 11813 // lookup context is in lexical scope. 11814 if (!CurContext->isDependentContext()) { 11815 DC = DC->getRedeclContext(); 11816 DC->makeDeclVisibleInContext(ND); 11817 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11818 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 11819 } 11820 11821 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 11822 D.getIdentifierLoc(), ND, 11823 DS.getFriendSpecLoc()); 11824 FrD->setAccess(AS_public); 11825 CurContext->addDecl(FrD); 11826 11827 if (ND->isInvalidDecl()) { 11828 FrD->setInvalidDecl(); 11829 } else { 11830 if (DC->isRecord()) CheckFriendAccess(ND); 11831 11832 FunctionDecl *FD; 11833 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 11834 FD = FTD->getTemplatedDecl(); 11835 else 11836 FD = cast<FunctionDecl>(ND); 11837 11838 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 11839 // default argument expression, that declaration shall be a definition 11840 // and shall be the only declaration of the function or function 11841 // template in the translation unit. 11842 if (functionDeclHasDefaultArgument(FD)) { 11843 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 11844 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 11845 Diag(OldFD->getLocation(), diag::note_previous_declaration); 11846 } else if (!D.isFunctionDefinition()) 11847 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 11848 } 11849 11850 // Mark templated-scope function declarations as unsupported. 11851 if (FD->getNumTemplateParameterLists()) 11852 FrD->setUnsupportedFriend(true); 11853 } 11854 11855 return ND; 11856 } 11857 11858 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 11859 AdjustDeclIfTemplate(Dcl); 11860 11861 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 11862 if (!Fn) { 11863 Diag(DelLoc, diag::err_deleted_non_function); 11864 return; 11865 } 11866 11867 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 11868 // Don't consider the implicit declaration we generate for explicit 11869 // specializations. FIXME: Do not generate these implicit declarations. 11870 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 11871 Prev->getPreviousDecl()) && 11872 !Prev->isDefined()) { 11873 Diag(DelLoc, diag::err_deleted_decl_not_first); 11874 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 11875 Prev->isImplicit() ? diag::note_previous_implicit_declaration 11876 : diag::note_previous_declaration); 11877 } 11878 // If the declaration wasn't the first, we delete the function anyway for 11879 // recovery. 11880 Fn = Fn->getCanonicalDecl(); 11881 } 11882 11883 if (Fn->isDeleted()) 11884 return; 11885 11886 // See if we're deleting a function which is already known to override a 11887 // non-deleted virtual function. 11888 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 11889 bool IssuedDiagnostic = false; 11890 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 11891 E = MD->end_overridden_methods(); 11892 I != E; ++I) { 11893 if (!(*MD->begin_overridden_methods())->isDeleted()) { 11894 if (!IssuedDiagnostic) { 11895 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 11896 IssuedDiagnostic = true; 11897 } 11898 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 11899 } 11900 } 11901 } 11902 11903 // C++11 [basic.start.main]p3: 11904 // A program that defines main as deleted [...] is ill-formed. 11905 if (Fn->isMain()) 11906 Diag(DelLoc, diag::err_deleted_main); 11907 11908 Fn->setDeletedAsWritten(); 11909 } 11910 11911 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 11912 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 11913 11914 if (MD) { 11915 if (MD->getParent()->isDependentType()) { 11916 MD->setDefaulted(); 11917 MD->setExplicitlyDefaulted(); 11918 return; 11919 } 11920 11921 CXXSpecialMember Member = getSpecialMember(MD); 11922 if (Member == CXXInvalid) { 11923 if (!MD->isInvalidDecl()) 11924 Diag(DefaultLoc, diag::err_default_special_members); 11925 return; 11926 } 11927 11928 MD->setDefaulted(); 11929 MD->setExplicitlyDefaulted(); 11930 11931 // If this definition appears within the record, do the checking when 11932 // the record is complete. 11933 const FunctionDecl *Primary = MD; 11934 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 11935 // Find the uninstantiated declaration that actually had the '= default' 11936 // on it. 11937 Pattern->isDefined(Primary); 11938 11939 // If the method was defaulted on its first declaration, we will have 11940 // already performed the checking in CheckCompletedCXXClass. Such a 11941 // declaration doesn't trigger an implicit definition. 11942 if (Primary == Primary->getCanonicalDecl()) 11943 return; 11944 11945 CheckExplicitlyDefaultedSpecialMember(MD); 11946 11947 // The exception specification is needed because we are defining the 11948 // function. 11949 ResolveExceptionSpec(DefaultLoc, 11950 MD->getType()->castAs<FunctionProtoType>()); 11951 11952 if (MD->isInvalidDecl()) 11953 return; 11954 11955 switch (Member) { 11956 case CXXDefaultConstructor: 11957 DefineImplicitDefaultConstructor(DefaultLoc, 11958 cast<CXXConstructorDecl>(MD)); 11959 break; 11960 case CXXCopyConstructor: 11961 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 11962 break; 11963 case CXXCopyAssignment: 11964 DefineImplicitCopyAssignment(DefaultLoc, MD); 11965 break; 11966 case CXXDestructor: 11967 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 11968 break; 11969 case CXXMoveConstructor: 11970 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 11971 break; 11972 case CXXMoveAssignment: 11973 DefineImplicitMoveAssignment(DefaultLoc, MD); 11974 break; 11975 case CXXInvalid: 11976 llvm_unreachable("Invalid special member."); 11977 } 11978 } else { 11979 Diag(DefaultLoc, diag::err_default_special_members); 11980 } 11981 } 11982 11983 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 11984 for (Stmt::child_range CI = S->children(); CI; ++CI) { 11985 Stmt *SubStmt = *CI; 11986 if (!SubStmt) 11987 continue; 11988 if (isa<ReturnStmt>(SubStmt)) 11989 Self.Diag(SubStmt->getLocStart(), 11990 diag::err_return_in_constructor_handler); 11991 if (!isa<Expr>(SubStmt)) 11992 SearchForReturnInStmt(Self, SubStmt); 11993 } 11994 } 11995 11996 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 11997 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 11998 CXXCatchStmt *Handler = TryBlock->getHandler(I); 11999 SearchForReturnInStmt(*this, Handler); 12000 } 12001 } 12002 12003 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12004 const CXXMethodDecl *Old) { 12005 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12006 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12007 12008 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12009 12010 // If the calling conventions match, everything is fine 12011 if (NewCC == OldCC) 12012 return false; 12013 12014 // If the calling conventions mismatch because the new function is static, 12015 // suppress the calling convention mismatch error; the error about static 12016 // function override (err_static_overrides_virtual from 12017 // Sema::CheckFunctionDeclaration) is more clear. 12018 if (New->getStorageClass() == SC_Static) 12019 return false; 12020 12021 Diag(New->getLocation(), 12022 diag::err_conflicting_overriding_cc_attributes) 12023 << New->getDeclName() << New->getType() << Old->getType(); 12024 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12025 return true; 12026 } 12027 12028 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12029 const CXXMethodDecl *Old) { 12030 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12031 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12032 12033 if (Context.hasSameType(NewTy, OldTy) || 12034 NewTy->isDependentType() || OldTy->isDependentType()) 12035 return false; 12036 12037 // Check if the return types are covariant 12038 QualType NewClassTy, OldClassTy; 12039 12040 /// Both types must be pointers or references to classes. 12041 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12042 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12043 NewClassTy = NewPT->getPointeeType(); 12044 OldClassTy = OldPT->getPointeeType(); 12045 } 12046 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12047 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12048 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12049 NewClassTy = NewRT->getPointeeType(); 12050 OldClassTy = OldRT->getPointeeType(); 12051 } 12052 } 12053 } 12054 12055 // The return types aren't either both pointers or references to a class type. 12056 if (NewClassTy.isNull()) { 12057 Diag(New->getLocation(), 12058 diag::err_different_return_type_for_overriding_virtual_function) 12059 << New->getDeclName() << NewTy << OldTy; 12060 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12061 12062 return true; 12063 } 12064 12065 // C++ [class.virtual]p6: 12066 // If the return type of D::f differs from the return type of B::f, the 12067 // class type in the return type of D::f shall be complete at the point of 12068 // declaration of D::f or shall be the class type D. 12069 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12070 if (!RT->isBeingDefined() && 12071 RequireCompleteType(New->getLocation(), NewClassTy, 12072 diag::err_covariant_return_incomplete, 12073 New->getDeclName())) 12074 return true; 12075 } 12076 12077 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12078 // Check if the new class derives from the old class. 12079 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12080 Diag(New->getLocation(), 12081 diag::err_covariant_return_not_derived) 12082 << New->getDeclName() << NewTy << OldTy; 12083 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12084 return true; 12085 } 12086 12087 // Check if we the conversion from derived to base is valid. 12088 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 12089 diag::err_covariant_return_inaccessible_base, 12090 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12091 // FIXME: Should this point to the return type? 12092 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 12093 // FIXME: this note won't trigger for delayed access control 12094 // diagnostics, and it's impossible to get an undelayed error 12095 // here from access control during the original parse because 12096 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12097 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12098 return true; 12099 } 12100 } 12101 12102 // The qualifiers of the return types must be the same. 12103 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12104 Diag(New->getLocation(), 12105 diag::err_covariant_return_type_different_qualifications) 12106 << New->getDeclName() << NewTy << OldTy; 12107 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12108 return true; 12109 }; 12110 12111 12112 // The new class type must have the same or less qualifiers as the old type. 12113 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12114 Diag(New->getLocation(), 12115 diag::err_covariant_return_type_class_type_more_qualified) 12116 << New->getDeclName() << NewTy << OldTy; 12117 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12118 return true; 12119 }; 12120 12121 return false; 12122 } 12123 12124 /// \brief Mark the given method pure. 12125 /// 12126 /// \param Method the method to be marked pure. 12127 /// 12128 /// \param InitRange the source range that covers the "0" initializer. 12129 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12130 SourceLocation EndLoc = InitRange.getEnd(); 12131 if (EndLoc.isValid()) 12132 Method->setRangeEnd(EndLoc); 12133 12134 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12135 Method->setPure(); 12136 return false; 12137 } 12138 12139 if (!Method->isInvalidDecl()) 12140 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12141 << Method->getDeclName() << InitRange; 12142 return true; 12143 } 12144 12145 /// \brief Determine whether the given declaration is a static data member. 12146 static bool isStaticDataMember(const Decl *D) { 12147 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12148 return Var->isStaticDataMember(); 12149 12150 return false; 12151 } 12152 12153 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12154 /// an initializer for the out-of-line declaration 'Dcl'. The scope 12155 /// is a fresh scope pushed for just this purpose. 12156 /// 12157 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12158 /// static data member of class X, names should be looked up in the scope of 12159 /// class X. 12160 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12161 // If there is no declaration, there was an error parsing it. 12162 if (D == 0 || D->isInvalidDecl()) return; 12163 12164 // We will always have a nested name specifier here, but this declaration 12165 // might not be out of line if the specifier names the current namespace: 12166 // extern int n; 12167 // int ::n = 0; 12168 if (D->isOutOfLine()) 12169 EnterDeclaratorContext(S, D->getDeclContext()); 12170 12171 // If we are parsing the initializer for a static data member, push a 12172 // new expression evaluation context that is associated with this static 12173 // data member. 12174 if (isStaticDataMember(D)) 12175 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12176 } 12177 12178 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12179 /// initializer for the out-of-line declaration 'D'. 12180 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12181 // If there is no declaration, there was an error parsing it. 12182 if (D == 0 || D->isInvalidDecl()) return; 12183 12184 if (isStaticDataMember(D)) 12185 PopExpressionEvaluationContext(); 12186 12187 if (D->isOutOfLine()) 12188 ExitDeclaratorContext(S); 12189 } 12190 12191 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 12192 /// C++ if/switch/while/for statement. 12193 /// e.g: "if (int x = f()) {...}" 12194 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 12195 // C++ 6.4p2: 12196 // The declarator shall not specify a function or an array. 12197 // The type-specifier-seq shall not contain typedef and shall not declare a 12198 // new class or enumeration. 12199 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 12200 "Parser allowed 'typedef' as storage class of condition decl."); 12201 12202 Decl *Dcl = ActOnDeclarator(S, D); 12203 if (!Dcl) 12204 return true; 12205 12206 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 12207 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 12208 << D.getSourceRange(); 12209 return true; 12210 } 12211 12212 return Dcl; 12213 } 12214 12215 void Sema::LoadExternalVTableUses() { 12216 if (!ExternalSource) 12217 return; 12218 12219 SmallVector<ExternalVTableUse, 4> VTables; 12220 ExternalSource->ReadUsedVTables(VTables); 12221 SmallVector<VTableUse, 4> NewUses; 12222 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 12223 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 12224 = VTablesUsed.find(VTables[I].Record); 12225 // Even if a definition wasn't required before, it may be required now. 12226 if (Pos != VTablesUsed.end()) { 12227 if (!Pos->second && VTables[I].DefinitionRequired) 12228 Pos->second = true; 12229 continue; 12230 } 12231 12232 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 12233 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 12234 } 12235 12236 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 12237 } 12238 12239 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 12240 bool DefinitionRequired) { 12241 // Ignore any vtable uses in unevaluated operands or for classes that do 12242 // not have a vtable. 12243 if (!Class->isDynamicClass() || Class->isDependentContext() || 12244 CurContext->isDependentContext() || isUnevaluatedContext()) 12245 return; 12246 12247 // Try to insert this class into the map. 12248 LoadExternalVTableUses(); 12249 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12250 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 12251 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 12252 if (!Pos.second) { 12253 // If we already had an entry, check to see if we are promoting this vtable 12254 // to required a definition. If so, we need to reappend to the VTableUses 12255 // list, since we may have already processed the first entry. 12256 if (DefinitionRequired && !Pos.first->second) { 12257 Pos.first->second = true; 12258 } else { 12259 // Otherwise, we can early exit. 12260 return; 12261 } 12262 } else { 12263 // The Microsoft ABI requires that we perform the destructor body 12264 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 12265 // the deleting destructor is emitted with the vtable, not with the 12266 // destructor definition as in the Itanium ABI. 12267 // If it has a definition, we do the check at that point instead. 12268 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12269 Class->hasUserDeclaredDestructor() && 12270 !Class->getDestructor()->isDefined() && 12271 !Class->getDestructor()->isDeleted()) { 12272 CheckDestructor(Class->getDestructor()); 12273 } 12274 } 12275 12276 // Local classes need to have their virtual members marked 12277 // immediately. For all other classes, we mark their virtual members 12278 // at the end of the translation unit. 12279 if (Class->isLocalClass()) 12280 MarkVirtualMembersReferenced(Loc, Class); 12281 else 12282 VTableUses.push_back(std::make_pair(Class, Loc)); 12283 } 12284 12285 bool Sema::DefineUsedVTables() { 12286 LoadExternalVTableUses(); 12287 if (VTableUses.empty()) 12288 return false; 12289 12290 // Note: The VTableUses vector could grow as a result of marking 12291 // the members of a class as "used", so we check the size each 12292 // time through the loop and prefer indices (which are stable) to 12293 // iterators (which are not). 12294 bool DefinedAnything = false; 12295 for (unsigned I = 0; I != VTableUses.size(); ++I) { 12296 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 12297 if (!Class) 12298 continue; 12299 12300 SourceLocation Loc = VTableUses[I].second; 12301 12302 bool DefineVTable = true; 12303 12304 // If this class has a key function, but that key function is 12305 // defined in another translation unit, we don't need to emit the 12306 // vtable even though we're using it. 12307 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 12308 if (KeyFunction && !KeyFunction->hasBody()) { 12309 // The key function is in another translation unit. 12310 DefineVTable = false; 12311 TemplateSpecializationKind TSK = 12312 KeyFunction->getTemplateSpecializationKind(); 12313 assert(TSK != TSK_ExplicitInstantiationDefinition && 12314 TSK != TSK_ImplicitInstantiation && 12315 "Instantiations don't have key functions"); 12316 (void)TSK; 12317 } else if (!KeyFunction) { 12318 // If we have a class with no key function that is the subject 12319 // of an explicit instantiation declaration, suppress the 12320 // vtable; it will live with the explicit instantiation 12321 // definition. 12322 bool IsExplicitInstantiationDeclaration 12323 = Class->getTemplateSpecializationKind() 12324 == TSK_ExplicitInstantiationDeclaration; 12325 for (auto R : Class->redecls()) { 12326 TemplateSpecializationKind TSK 12327 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 12328 if (TSK == TSK_ExplicitInstantiationDeclaration) 12329 IsExplicitInstantiationDeclaration = true; 12330 else if (TSK == TSK_ExplicitInstantiationDefinition) { 12331 IsExplicitInstantiationDeclaration = false; 12332 break; 12333 } 12334 } 12335 12336 if (IsExplicitInstantiationDeclaration) 12337 DefineVTable = false; 12338 } 12339 12340 // The exception specifications for all virtual members may be needed even 12341 // if we are not providing an authoritative form of the vtable in this TU. 12342 // We may choose to emit it available_externally anyway. 12343 if (!DefineVTable) { 12344 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 12345 continue; 12346 } 12347 12348 // Mark all of the virtual members of this class as referenced, so 12349 // that we can build a vtable. Then, tell the AST consumer that a 12350 // vtable for this class is required. 12351 DefinedAnything = true; 12352 MarkVirtualMembersReferenced(Loc, Class); 12353 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12354 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 12355 12356 // Optionally warn if we're emitting a weak vtable. 12357 if (Class->isExternallyVisible() && 12358 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 12359 const FunctionDecl *KeyFunctionDef = 0; 12360 if (!KeyFunction || 12361 (KeyFunction->hasBody(KeyFunctionDef) && 12362 KeyFunctionDef->isInlined())) 12363 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 12364 TSK_ExplicitInstantiationDefinition 12365 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 12366 << Class; 12367 } 12368 } 12369 VTableUses.clear(); 12370 12371 return DefinedAnything; 12372 } 12373 12374 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 12375 const CXXRecordDecl *RD) { 12376 for (const auto *I : RD->methods()) 12377 if (I->isVirtual() && !I->isPure()) 12378 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 12379 } 12380 12381 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 12382 const CXXRecordDecl *RD) { 12383 // Mark all functions which will appear in RD's vtable as used. 12384 CXXFinalOverriderMap FinalOverriders; 12385 RD->getFinalOverriders(FinalOverriders); 12386 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 12387 E = FinalOverriders.end(); 12388 I != E; ++I) { 12389 for (OverridingMethods::const_iterator OI = I->second.begin(), 12390 OE = I->second.end(); 12391 OI != OE; ++OI) { 12392 assert(OI->second.size() > 0 && "no final overrider"); 12393 CXXMethodDecl *Overrider = OI->second.front().Method; 12394 12395 // C++ [basic.def.odr]p2: 12396 // [...] A virtual member function is used if it is not pure. [...] 12397 if (!Overrider->isPure()) 12398 MarkFunctionReferenced(Loc, Overrider); 12399 } 12400 } 12401 12402 // Only classes that have virtual bases need a VTT. 12403 if (RD->getNumVBases() == 0) 12404 return; 12405 12406 for (const auto &I : RD->bases()) { 12407 const CXXRecordDecl *Base = 12408 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 12409 if (Base->getNumVBases() == 0) 12410 continue; 12411 MarkVirtualMembersReferenced(Loc, Base); 12412 } 12413 } 12414 12415 /// SetIvarInitializers - This routine builds initialization ASTs for the 12416 /// Objective-C implementation whose ivars need be initialized. 12417 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 12418 if (!getLangOpts().CPlusPlus) 12419 return; 12420 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 12421 SmallVector<ObjCIvarDecl*, 8> ivars; 12422 CollectIvarsToConstructOrDestruct(OID, ivars); 12423 if (ivars.empty()) 12424 return; 12425 SmallVector<CXXCtorInitializer*, 32> AllToInit; 12426 for (unsigned i = 0; i < ivars.size(); i++) { 12427 FieldDecl *Field = ivars[i]; 12428 if (Field->isInvalidDecl()) 12429 continue; 12430 12431 CXXCtorInitializer *Member; 12432 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 12433 InitializationKind InitKind = 12434 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 12435 12436 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 12437 ExprResult MemberInit = 12438 InitSeq.Perform(*this, InitEntity, InitKind, None); 12439 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 12440 // Note, MemberInit could actually come back empty if no initialization 12441 // is required (e.g., because it would call a trivial default constructor) 12442 if (!MemberInit.get() || MemberInit.isInvalid()) 12443 continue; 12444 12445 Member = 12446 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 12447 SourceLocation(), 12448 MemberInit.takeAs<Expr>(), 12449 SourceLocation()); 12450 AllToInit.push_back(Member); 12451 12452 // Be sure that the destructor is accessible and is marked as referenced. 12453 if (const RecordType *RecordTy 12454 = Context.getBaseElementType(Field->getType()) 12455 ->getAs<RecordType>()) { 12456 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 12457 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 12458 MarkFunctionReferenced(Field->getLocation(), Destructor); 12459 CheckDestructorAccess(Field->getLocation(), Destructor, 12460 PDiag(diag::err_access_dtor_ivar) 12461 << Context.getBaseElementType(Field->getType())); 12462 } 12463 } 12464 } 12465 ObjCImplementation->setIvarInitializers(Context, 12466 AllToInit.data(), AllToInit.size()); 12467 } 12468 } 12469 12470 static 12471 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 12472 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 12473 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 12474 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 12475 Sema &S) { 12476 if (Ctor->isInvalidDecl()) 12477 return; 12478 12479 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 12480 12481 // Target may not be determinable yet, for instance if this is a dependent 12482 // call in an uninstantiated template. 12483 if (Target) { 12484 const FunctionDecl *FNTarget = 0; 12485 (void)Target->hasBody(FNTarget); 12486 Target = const_cast<CXXConstructorDecl*>( 12487 cast_or_null<CXXConstructorDecl>(FNTarget)); 12488 } 12489 12490 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 12491 // Avoid dereferencing a null pointer here. 12492 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 12493 12494 if (!Current.insert(Canonical)) 12495 return; 12496 12497 // We know that beyond here, we aren't chaining into a cycle. 12498 if (!Target || !Target->isDelegatingConstructor() || 12499 Target->isInvalidDecl() || Valid.count(TCanonical)) { 12500 Valid.insert(Current.begin(), Current.end()); 12501 Current.clear(); 12502 // We've hit a cycle. 12503 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 12504 Current.count(TCanonical)) { 12505 // If we haven't diagnosed this cycle yet, do so now. 12506 if (!Invalid.count(TCanonical)) { 12507 S.Diag((*Ctor->init_begin())->getSourceLocation(), 12508 diag::warn_delegating_ctor_cycle) 12509 << Ctor; 12510 12511 // Don't add a note for a function delegating directly to itself. 12512 if (TCanonical != Canonical) 12513 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 12514 12515 CXXConstructorDecl *C = Target; 12516 while (C->getCanonicalDecl() != Canonical) { 12517 const FunctionDecl *FNTarget = 0; 12518 (void)C->getTargetConstructor()->hasBody(FNTarget); 12519 assert(FNTarget && "Ctor cycle through bodiless function"); 12520 12521 C = const_cast<CXXConstructorDecl*>( 12522 cast<CXXConstructorDecl>(FNTarget)); 12523 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12524 } 12525 } 12526 12527 Invalid.insert(Current.begin(), Current.end()); 12528 Current.clear(); 12529 } else { 12530 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12531 } 12532 } 12533 12534 12535 void Sema::CheckDelegatingCtorCycles() { 12536 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12537 12538 for (DelegatingCtorDeclsType::iterator 12539 I = DelegatingCtorDecls.begin(ExternalSource), 12540 E = DelegatingCtorDecls.end(); 12541 I != E; ++I) 12542 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 12543 12544 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 12545 CE = Invalid.end(); 12546 CI != CE; ++CI) 12547 (*CI)->setInvalidDecl(); 12548 } 12549 12550 namespace { 12551 /// \brief AST visitor that finds references to the 'this' expression. 12552 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 12553 Sema &S; 12554 12555 public: 12556 explicit FindCXXThisExpr(Sema &S) : S(S) { } 12557 12558 bool VisitCXXThisExpr(CXXThisExpr *E) { 12559 S.Diag(E->getLocation(), diag::err_this_static_member_func) 12560 << E->isImplicit(); 12561 return false; 12562 } 12563 }; 12564 } 12565 12566 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 12567 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12568 if (!TSInfo) 12569 return false; 12570 12571 TypeLoc TL = TSInfo->getTypeLoc(); 12572 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12573 if (!ProtoTL) 12574 return false; 12575 12576 // C++11 [expr.prim.general]p3: 12577 // [The expression this] shall not appear before the optional 12578 // cv-qualifier-seq and it shall not appear within the declaration of a 12579 // static member function (although its type and value category are defined 12580 // within a static member function as they are within a non-static member 12581 // function). [ Note: this is because declaration matching does not occur 12582 // until the complete declarator is known. - end note ] 12583 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12584 FindCXXThisExpr Finder(*this); 12585 12586 // If the return type came after the cv-qualifier-seq, check it now. 12587 if (Proto->hasTrailingReturn() && 12588 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 12589 return true; 12590 12591 // Check the exception specification. 12592 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 12593 return true; 12594 12595 return checkThisInStaticMemberFunctionAttributes(Method); 12596 } 12597 12598 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 12599 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12600 if (!TSInfo) 12601 return false; 12602 12603 TypeLoc TL = TSInfo->getTypeLoc(); 12604 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12605 if (!ProtoTL) 12606 return false; 12607 12608 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12609 FindCXXThisExpr Finder(*this); 12610 12611 switch (Proto->getExceptionSpecType()) { 12612 case EST_Uninstantiated: 12613 case EST_Unevaluated: 12614 case EST_BasicNoexcept: 12615 case EST_DynamicNone: 12616 case EST_MSAny: 12617 case EST_None: 12618 break; 12619 12620 case EST_ComputedNoexcept: 12621 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 12622 return true; 12623 12624 case EST_Dynamic: 12625 for (const auto &E : Proto->exceptions()) { 12626 if (!Finder.TraverseType(E)) 12627 return true; 12628 } 12629 break; 12630 } 12631 12632 return false; 12633 } 12634 12635 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 12636 FindCXXThisExpr Finder(*this); 12637 12638 // Check attributes. 12639 for (const auto *A : Method->attrs()) { 12640 // FIXME: This should be emitted by tblgen. 12641 Expr *Arg = 0; 12642 ArrayRef<Expr *> Args; 12643 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 12644 Arg = G->getArg(); 12645 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 12646 Arg = G->getArg(); 12647 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 12648 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 12649 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 12650 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 12651 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 12652 Arg = ETLF->getSuccessValue(); 12653 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 12654 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 12655 Arg = STLF->getSuccessValue(); 12656 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 12657 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 12658 Arg = LR->getArg(); 12659 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 12660 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 12661 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 12662 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size()); 12663 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 12664 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size()); 12665 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 12666 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size()); 12667 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 12668 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size()); 12669 12670 if (Arg && !Finder.TraverseStmt(Arg)) 12671 return true; 12672 12673 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12674 if (!Finder.TraverseStmt(Args[I])) 12675 return true; 12676 } 12677 } 12678 12679 return false; 12680 } 12681 12682 void 12683 Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12684 ArrayRef<ParsedType> DynamicExceptions, 12685 ArrayRef<SourceRange> DynamicExceptionRanges, 12686 Expr *NoexceptExpr, 12687 SmallVectorImpl<QualType> &Exceptions, 12688 FunctionProtoType::ExtProtoInfo &EPI) { 12689 Exceptions.clear(); 12690 EPI.ExceptionSpecType = EST; 12691 if (EST == EST_Dynamic) { 12692 Exceptions.reserve(DynamicExceptions.size()); 12693 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12694 // FIXME: Preserve type source info. 12695 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12696 12697 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12698 collectUnexpandedParameterPacks(ET, Unexpanded); 12699 if (!Unexpanded.empty()) { 12700 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 12701 UPPC_ExceptionType, 12702 Unexpanded); 12703 continue; 12704 } 12705 12706 // Check that the type is valid for an exception spec, and 12707 // drop it if not. 12708 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 12709 Exceptions.push_back(ET); 12710 } 12711 EPI.NumExceptions = Exceptions.size(); 12712 EPI.Exceptions = Exceptions.data(); 12713 return; 12714 } 12715 12716 if (EST == EST_ComputedNoexcept) { 12717 // If an error occurred, there's no expression here. 12718 if (NoexceptExpr) { 12719 assert((NoexceptExpr->isTypeDependent() || 12720 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 12721 Context.BoolTy) && 12722 "Parser should have made sure that the expression is boolean"); 12723 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 12724 EPI.ExceptionSpecType = EST_BasicNoexcept; 12725 return; 12726 } 12727 12728 if (!NoexceptExpr->isValueDependent()) 12729 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 12730 diag::err_noexcept_needs_constant_expression, 12731 /*AllowFold*/ false).take(); 12732 EPI.NoexceptExpr = NoexceptExpr; 12733 } 12734 return; 12735 } 12736 } 12737 12738 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function 12739 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 12740 // Implicitly declared functions (e.g. copy constructors) are 12741 // __host__ __device__ 12742 if (D->isImplicit()) 12743 return CFT_HostDevice; 12744 12745 if (D->hasAttr<CUDAGlobalAttr>()) 12746 return CFT_Global; 12747 12748 if (D->hasAttr<CUDADeviceAttr>()) { 12749 if (D->hasAttr<CUDAHostAttr>()) 12750 return CFT_HostDevice; 12751 return CFT_Device; 12752 } 12753 12754 return CFT_Host; 12755 } 12756 12757 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 12758 CUDAFunctionTarget CalleeTarget) { 12759 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 12760 // Callable from the device only." 12761 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 12762 return true; 12763 12764 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 12765 // Callable from the host only." 12766 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 12767 // Callable from the host only." 12768 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 12769 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 12770 return true; 12771 12772 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 12773 return true; 12774 12775 return false; 12776 } 12777 12778 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 12779 /// 12780 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 12781 SourceLocation DeclStart, 12782 Declarator &D, Expr *BitWidth, 12783 InClassInitStyle InitStyle, 12784 AccessSpecifier AS, 12785 AttributeList *MSPropertyAttr) { 12786 IdentifierInfo *II = D.getIdentifier(); 12787 if (!II) { 12788 Diag(DeclStart, diag::err_anonymous_property); 12789 return NULL; 12790 } 12791 SourceLocation Loc = D.getIdentifierLoc(); 12792 12793 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12794 QualType T = TInfo->getType(); 12795 if (getLangOpts().CPlusPlus) { 12796 CheckExtraCXXDefaultArguments(D); 12797 12798 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12799 UPPC_DataMemberType)) { 12800 D.setInvalidType(); 12801 T = Context.IntTy; 12802 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12803 } 12804 } 12805 12806 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12807 12808 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12809 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12810 diag::err_invalid_thread) 12811 << DeclSpec::getSpecifierName(TSCS); 12812 12813 // Check to see if this name was declared as a member previously 12814 NamedDecl *PrevDecl = 0; 12815 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12816 LookupName(Previous, S); 12817 switch (Previous.getResultKind()) { 12818 case LookupResult::Found: 12819 case LookupResult::FoundUnresolvedValue: 12820 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12821 break; 12822 12823 case LookupResult::FoundOverloaded: 12824 PrevDecl = Previous.getRepresentativeDecl(); 12825 break; 12826 12827 case LookupResult::NotFound: 12828 case LookupResult::NotFoundInCurrentInstantiation: 12829 case LookupResult::Ambiguous: 12830 break; 12831 } 12832 12833 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12834 // Maybe we will complain about the shadowed template parameter. 12835 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12836 // Just pretend that we didn't see the previous declaration. 12837 PrevDecl = 0; 12838 } 12839 12840 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12841 PrevDecl = 0; 12842 12843 SourceLocation TSSL = D.getLocStart(); 12844 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 12845 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 12846 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 12847 ProcessDeclAttributes(TUScope, NewPD, D); 12848 NewPD->setAccess(AS); 12849 12850 if (NewPD->isInvalidDecl()) 12851 Record->setInvalidDecl(); 12852 12853 if (D.getDeclSpec().isModulePrivateSpecified()) 12854 NewPD->setModulePrivate(); 12855 12856 if (NewPD->isInvalidDecl() && PrevDecl) { 12857 // Don't introduce NewFD into scope; there's already something 12858 // with the same name in the same scope. 12859 } else if (II) { 12860 PushOnScopeChains(NewPD, S); 12861 } else 12862 Record->addDecl(NewPD); 12863 12864 return NewPD; 12865 } 12866