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 // If we found a local extern declaration that's not ordinarily visible, 7383 // and this declaration is being added to a non-block scope, ignore it. 7384 // We're only checking for scope conflicts here, not also for violations 7385 // of the linkage rules. 7386 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 7387 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 7388 F.erase(); 7389 } 7390 F.done(); 7391 } else { 7392 assert(IsInstantiation && "no scope in non-instantiation"); 7393 assert(CurContext->isRecord() && "scope not record in instantiation"); 7394 LookupQualifiedName(Previous, CurContext); 7395 } 7396 7397 // Check for invalid redeclarations. 7398 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 7399 SS, IdentLoc, Previous)) 7400 return 0; 7401 7402 // Check for bad qualifiers. 7403 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc)) 7404 return 0; 7405 7406 DeclContext *LookupContext = computeDeclContext(SS); 7407 NamedDecl *D; 7408 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7409 if (!LookupContext) { 7410 if (HasTypenameKeyword) { 7411 // FIXME: not all declaration name kinds are legal here 7412 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 7413 UsingLoc, TypenameLoc, 7414 QualifierLoc, 7415 IdentLoc, NameInfo.getName()); 7416 } else { 7417 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 7418 QualifierLoc, NameInfo); 7419 } 7420 } else { 7421 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 7422 NameInfo, HasTypenameKeyword); 7423 } 7424 D->setAccess(AS); 7425 CurContext->addDecl(D); 7426 7427 if (!LookupContext) return D; 7428 UsingDecl *UD = cast<UsingDecl>(D); 7429 7430 if (RequireCompleteDeclContext(SS, LookupContext)) { 7431 UD->setInvalidDecl(); 7432 return UD; 7433 } 7434 7435 // The normal rules do not apply to inheriting constructor declarations. 7436 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 7437 if (CheckInheritingConstructorUsingDecl(UD)) 7438 UD->setInvalidDecl(); 7439 return UD; 7440 } 7441 7442 // Otherwise, look up the target name. 7443 7444 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7445 7446 // Unlike most lookups, we don't always want to hide tag 7447 // declarations: tag names are visible through the using declaration 7448 // even if hidden by ordinary names, *except* in a dependent context 7449 // where it's important for the sanity of two-phase lookup. 7450 if (!IsInstantiation) 7451 R.setHideTags(false); 7452 7453 // For the purposes of this lookup, we have a base object type 7454 // equal to that of the current context. 7455 if (CurContext->isRecord()) { 7456 R.setBaseObjectType( 7457 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 7458 } 7459 7460 LookupQualifiedName(R, LookupContext); 7461 7462 // Try to correct typos if possible. 7463 if (R.empty()) { 7464 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, 7465 CurContext->isRecord()); 7466 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(), 7467 R.getLookupKind(), S, &SS, CCC)){ 7468 // We reject any correction for which ND would be NULL. 7469 NamedDecl *ND = Corrected.getCorrectionDecl(); 7470 R.setLookupName(Corrected.getCorrection()); 7471 R.addDecl(ND); 7472 // We reject candidates where DroppedSpecifier == true, hence the 7473 // literal '0' below. 7474 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 7475 << NameInfo.getName() << LookupContext << 0 7476 << SS.getRange()); 7477 } else { 7478 Diag(IdentLoc, diag::err_no_member) 7479 << NameInfo.getName() << LookupContext << SS.getRange(); 7480 UD->setInvalidDecl(); 7481 return UD; 7482 } 7483 } 7484 7485 if (R.isAmbiguous()) { 7486 UD->setInvalidDecl(); 7487 return UD; 7488 } 7489 7490 if (HasTypenameKeyword) { 7491 // If we asked for a typename and got a non-type decl, error out. 7492 if (!R.getAsSingle<TypeDecl>()) { 7493 Diag(IdentLoc, diag::err_using_typename_non_type); 7494 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 7495 Diag((*I)->getUnderlyingDecl()->getLocation(), 7496 diag::note_using_decl_target); 7497 UD->setInvalidDecl(); 7498 return UD; 7499 } 7500 } else { 7501 // If we asked for a non-typename and we got a type, error out, 7502 // but only if this is an instantiation of an unresolved using 7503 // decl. Otherwise just silently find the type name. 7504 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 7505 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 7506 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 7507 UD->setInvalidDecl(); 7508 return UD; 7509 } 7510 } 7511 7512 // C++0x N2914 [namespace.udecl]p6: 7513 // A using-declaration shall not name a namespace. 7514 if (R.getAsSingle<NamespaceDecl>()) { 7515 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 7516 << SS.getRange(); 7517 UD->setInvalidDecl(); 7518 return UD; 7519 } 7520 7521 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7522 UsingShadowDecl *PrevDecl = 0; 7523 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 7524 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 7525 } 7526 7527 return UD; 7528 } 7529 7530 /// Additional checks for a using declaration referring to a constructor name. 7531 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 7532 assert(!UD->hasTypename() && "expecting a constructor name"); 7533 7534 const Type *SourceType = UD->getQualifier()->getAsType(); 7535 assert(SourceType && 7536 "Using decl naming constructor doesn't have type in scope spec."); 7537 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 7538 7539 // Check whether the named type is a direct base class. 7540 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 7541 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 7542 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 7543 BaseIt != BaseE; ++BaseIt) { 7544 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 7545 if (CanonicalSourceType == BaseType) 7546 break; 7547 if (BaseIt->getType()->isDependentType()) 7548 break; 7549 } 7550 7551 if (BaseIt == BaseE) { 7552 // Did not find SourceType in the bases. 7553 Diag(UD->getUsingLoc(), 7554 diag::err_using_decl_constructor_not_in_direct_base) 7555 << UD->getNameInfo().getSourceRange() 7556 << QualType(SourceType, 0) << TargetClass; 7557 return true; 7558 } 7559 7560 if (!CurContext->isDependentContext()) 7561 BaseIt->setInheritConstructors(); 7562 7563 return false; 7564 } 7565 7566 /// Checks that the given using declaration is not an invalid 7567 /// redeclaration. Note that this is checking only for the using decl 7568 /// itself, not for any ill-formedness among the UsingShadowDecls. 7569 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 7570 bool HasTypenameKeyword, 7571 const CXXScopeSpec &SS, 7572 SourceLocation NameLoc, 7573 const LookupResult &Prev) { 7574 // C++03 [namespace.udecl]p8: 7575 // C++0x [namespace.udecl]p10: 7576 // A using-declaration is a declaration and can therefore be used 7577 // repeatedly where (and only where) multiple declarations are 7578 // allowed. 7579 // 7580 // That's in non-member contexts. 7581 if (!CurContext->getRedeclContext()->isRecord()) 7582 return false; 7583 7584 NestedNameSpecifier *Qual = SS.getScopeRep(); 7585 7586 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 7587 NamedDecl *D = *I; 7588 7589 bool DTypename; 7590 NestedNameSpecifier *DQual; 7591 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 7592 DTypename = UD->hasTypename(); 7593 DQual = UD->getQualifier(); 7594 } else if (UnresolvedUsingValueDecl *UD 7595 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 7596 DTypename = false; 7597 DQual = UD->getQualifier(); 7598 } else if (UnresolvedUsingTypenameDecl *UD 7599 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 7600 DTypename = true; 7601 DQual = UD->getQualifier(); 7602 } else continue; 7603 7604 // using decls differ if one says 'typename' and the other doesn't. 7605 // FIXME: non-dependent using decls? 7606 if (HasTypenameKeyword != DTypename) continue; 7607 7608 // using decls differ if they name different scopes (but note that 7609 // template instantiation can cause this check to trigger when it 7610 // didn't before instantiation). 7611 if (Context.getCanonicalNestedNameSpecifier(Qual) != 7612 Context.getCanonicalNestedNameSpecifier(DQual)) 7613 continue; 7614 7615 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 7616 Diag(D->getLocation(), diag::note_using_decl) << 1; 7617 return true; 7618 } 7619 7620 return false; 7621 } 7622 7623 7624 /// Checks that the given nested-name qualifier used in a using decl 7625 /// in the current context is appropriately related to the current 7626 /// scope. If an error is found, diagnoses it and returns true. 7627 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 7628 const CXXScopeSpec &SS, 7629 const DeclarationNameInfo &NameInfo, 7630 SourceLocation NameLoc) { 7631 DeclContext *NamedContext = computeDeclContext(SS); 7632 7633 if (!CurContext->isRecord()) { 7634 // C++03 [namespace.udecl]p3: 7635 // C++0x [namespace.udecl]p8: 7636 // A using-declaration for a class member shall be a member-declaration. 7637 7638 // If we weren't able to compute a valid scope, it must be a 7639 // dependent class scope. 7640 if (!NamedContext || NamedContext->isRecord()) { 7641 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext); 7642 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 7643 RD = 0; 7644 7645 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 7646 << SS.getRange(); 7647 7648 // If we have a complete, non-dependent source type, try to suggest a 7649 // way to get the same effect. 7650 if (!RD) 7651 return true; 7652 7653 // Find what this using-declaration was referring to. 7654 LookupResult R(*this, NameInfo, LookupOrdinaryName); 7655 R.setHideTags(false); 7656 R.suppressDiagnostics(); 7657 LookupQualifiedName(R, RD); 7658 7659 if (R.getAsSingle<TypeDecl>()) { 7660 if (getLangOpts().CPlusPlus11) { 7661 // Convert 'using X::Y;' to 'using Y = X::Y;'. 7662 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 7663 << 0 // alias declaration 7664 << FixItHint::CreateInsertion(SS.getBeginLoc(), 7665 NameInfo.getName().getAsString() + 7666 " = "); 7667 } else { 7668 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 7669 SourceLocation InsertLoc = 7670 PP.getLocForEndOfToken(NameInfo.getLocEnd()); 7671 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 7672 << 1 // typedef declaration 7673 << FixItHint::CreateReplacement(UsingLoc, "typedef") 7674 << FixItHint::CreateInsertion( 7675 InsertLoc, " " + NameInfo.getName().getAsString()); 7676 } 7677 } else if (R.getAsSingle<VarDecl>()) { 7678 // Don't provide a fixit outside C++11 mode; we don't want to suggest 7679 // repeating the type of the static data member here. 7680 FixItHint FixIt; 7681 if (getLangOpts().CPlusPlus11) { 7682 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 7683 FixIt = FixItHint::CreateReplacement( 7684 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 7685 } 7686 7687 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 7688 << 2 // reference declaration 7689 << FixIt; 7690 } 7691 return true; 7692 } 7693 7694 // Otherwise, everything is known to be fine. 7695 return false; 7696 } 7697 7698 // The current scope is a record. 7699 7700 // If the named context is dependent, we can't decide much. 7701 if (!NamedContext) { 7702 // FIXME: in C++0x, we can diagnose if we can prove that the 7703 // nested-name-specifier does not refer to a base class, which is 7704 // still possible in some cases. 7705 7706 // Otherwise we have to conservatively report that things might be 7707 // okay. 7708 return false; 7709 } 7710 7711 if (!NamedContext->isRecord()) { 7712 // Ideally this would point at the last name in the specifier, 7713 // but we don't have that level of source info. 7714 Diag(SS.getRange().getBegin(), 7715 diag::err_using_decl_nested_name_specifier_is_not_class) 7716 << SS.getScopeRep() << SS.getRange(); 7717 return true; 7718 } 7719 7720 if (!NamedContext->isDependentContext() && 7721 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 7722 return true; 7723 7724 if (getLangOpts().CPlusPlus11) { 7725 // C++0x [namespace.udecl]p3: 7726 // In a using-declaration used as a member-declaration, the 7727 // nested-name-specifier shall name a base class of the class 7728 // being defined. 7729 7730 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 7731 cast<CXXRecordDecl>(NamedContext))) { 7732 if (CurContext == NamedContext) { 7733 Diag(NameLoc, 7734 diag::err_using_decl_nested_name_specifier_is_current_class) 7735 << SS.getRange(); 7736 return true; 7737 } 7738 7739 Diag(SS.getRange().getBegin(), 7740 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7741 << SS.getScopeRep() 7742 << cast<CXXRecordDecl>(CurContext) 7743 << SS.getRange(); 7744 return true; 7745 } 7746 7747 return false; 7748 } 7749 7750 // C++03 [namespace.udecl]p4: 7751 // A using-declaration used as a member-declaration shall refer 7752 // to a member of a base class of the class being defined [etc.]. 7753 7754 // Salient point: SS doesn't have to name a base class as long as 7755 // lookup only finds members from base classes. Therefore we can 7756 // diagnose here only if we can prove that that can't happen, 7757 // i.e. if the class hierarchies provably don't intersect. 7758 7759 // TODO: it would be nice if "definitely valid" results were cached 7760 // in the UsingDecl and UsingShadowDecl so that these checks didn't 7761 // need to be repeated. 7762 7763 struct UserData { 7764 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases; 7765 7766 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 7767 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7768 Data->Bases.insert(Base); 7769 return true; 7770 } 7771 7772 bool hasDependentBases(const CXXRecordDecl *Class) { 7773 return !Class->forallBases(collect, this); 7774 } 7775 7776 /// Returns true if the base is dependent or is one of the 7777 /// accumulated base classes. 7778 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 7779 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 7780 return !Data->Bases.count(Base); 7781 } 7782 7783 bool mightShareBases(const CXXRecordDecl *Class) { 7784 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 7785 } 7786 }; 7787 7788 UserData Data; 7789 7790 // Returns false if we find a dependent base. 7791 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 7792 return false; 7793 7794 // Returns false if the class has a dependent base or if it or one 7795 // of its bases is present in the base set of the current context. 7796 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 7797 return false; 7798 7799 Diag(SS.getRange().getBegin(), 7800 diag::err_using_decl_nested_name_specifier_is_not_base_class) 7801 << SS.getScopeRep() 7802 << cast<CXXRecordDecl>(CurContext) 7803 << SS.getRange(); 7804 7805 return true; 7806 } 7807 7808 Decl *Sema::ActOnAliasDeclaration(Scope *S, 7809 AccessSpecifier AS, 7810 MultiTemplateParamsArg TemplateParamLists, 7811 SourceLocation UsingLoc, 7812 UnqualifiedId &Name, 7813 AttributeList *AttrList, 7814 TypeResult Type) { 7815 // Skip up to the relevant declaration scope. 7816 while (S->getFlags() & Scope::TemplateParamScope) 7817 S = S->getParent(); 7818 assert((S->getFlags() & Scope::DeclScope) && 7819 "got alias-declaration outside of declaration scope"); 7820 7821 if (Type.isInvalid()) 7822 return 0; 7823 7824 bool Invalid = false; 7825 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 7826 TypeSourceInfo *TInfo = 0; 7827 GetTypeFromParser(Type.get(), &TInfo); 7828 7829 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 7830 return 0; 7831 7832 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 7833 UPPC_DeclarationType)) { 7834 Invalid = true; 7835 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 7836 TInfo->getTypeLoc().getBeginLoc()); 7837 } 7838 7839 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration); 7840 LookupName(Previous, S); 7841 7842 // Warn about shadowing the name of a template parameter. 7843 if (Previous.isSingleResult() && 7844 Previous.getFoundDecl()->isTemplateParameter()) { 7845 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 7846 Previous.clear(); 7847 } 7848 7849 assert(Name.Kind == UnqualifiedId::IK_Identifier && 7850 "name in alias declaration must be an identifier"); 7851 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 7852 Name.StartLocation, 7853 Name.Identifier, TInfo); 7854 7855 NewTD->setAccess(AS); 7856 7857 if (Invalid) 7858 NewTD->setInvalidDecl(); 7859 7860 ProcessDeclAttributeList(S, NewTD, AttrList); 7861 7862 CheckTypedefForVariablyModifiedType(S, NewTD); 7863 Invalid |= NewTD->isInvalidDecl(); 7864 7865 bool Redeclaration = false; 7866 7867 NamedDecl *NewND; 7868 if (TemplateParamLists.size()) { 7869 TypeAliasTemplateDecl *OldDecl = 0; 7870 TemplateParameterList *OldTemplateParams = 0; 7871 7872 if (TemplateParamLists.size() != 1) { 7873 Diag(UsingLoc, diag::err_alias_template_extra_headers) 7874 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 7875 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 7876 } 7877 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 7878 7879 // Only consider previous declarations in the same scope. 7880 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 7881 /*ExplicitInstantiationOrSpecialization*/false); 7882 if (!Previous.empty()) { 7883 Redeclaration = true; 7884 7885 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 7886 if (!OldDecl && !Invalid) { 7887 Diag(UsingLoc, diag::err_redefinition_different_kind) 7888 << Name.Identifier; 7889 7890 NamedDecl *OldD = Previous.getRepresentativeDecl(); 7891 if (OldD->getLocation().isValid()) 7892 Diag(OldD->getLocation(), diag::note_previous_definition); 7893 7894 Invalid = true; 7895 } 7896 7897 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 7898 if (TemplateParameterListsAreEqual(TemplateParams, 7899 OldDecl->getTemplateParameters(), 7900 /*Complain=*/true, 7901 TPL_TemplateMatch)) 7902 OldTemplateParams = OldDecl->getTemplateParameters(); 7903 else 7904 Invalid = true; 7905 7906 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 7907 if (!Invalid && 7908 !Context.hasSameType(OldTD->getUnderlyingType(), 7909 NewTD->getUnderlyingType())) { 7910 // FIXME: The C++0x standard does not clearly say this is ill-formed, 7911 // but we can't reasonably accept it. 7912 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 7913 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 7914 if (OldTD->getLocation().isValid()) 7915 Diag(OldTD->getLocation(), diag::note_previous_definition); 7916 Invalid = true; 7917 } 7918 } 7919 } 7920 7921 // Merge any previous default template arguments into our parameters, 7922 // and check the parameter list. 7923 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 7924 TPC_TypeAliasTemplate)) 7925 return 0; 7926 7927 TypeAliasTemplateDecl *NewDecl = 7928 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 7929 Name.Identifier, TemplateParams, 7930 NewTD); 7931 7932 NewDecl->setAccess(AS); 7933 7934 if (Invalid) 7935 NewDecl->setInvalidDecl(); 7936 else if (OldDecl) 7937 NewDecl->setPreviousDecl(OldDecl); 7938 7939 NewND = NewDecl; 7940 } else { 7941 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 7942 NewND = NewTD; 7943 } 7944 7945 if (!Redeclaration) 7946 PushOnScopeChains(NewND, S); 7947 7948 ActOnDocumentableDecl(NewND); 7949 return NewND; 7950 } 7951 7952 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 7953 SourceLocation NamespaceLoc, 7954 SourceLocation AliasLoc, 7955 IdentifierInfo *Alias, 7956 CXXScopeSpec &SS, 7957 SourceLocation IdentLoc, 7958 IdentifierInfo *Ident) { 7959 7960 // Lookup the namespace name. 7961 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 7962 LookupParsedName(R, S, &SS); 7963 7964 // Check if we have a previous declaration with the same name. 7965 NamedDecl *PrevDecl 7966 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 7967 ForRedeclaration); 7968 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 7969 PrevDecl = 0; 7970 7971 if (PrevDecl) { 7972 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 7973 // We already have an alias with the same name that points to the same 7974 // namespace, so don't create a new one. 7975 // FIXME: At some point, we'll want to create the (redundant) 7976 // declaration to maintain better source information. 7977 if (!R.isAmbiguous() && !R.empty() && 7978 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 7979 return 0; 7980 } 7981 7982 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 7983 diag::err_redefinition_different_kind; 7984 Diag(AliasLoc, DiagID) << Alias; 7985 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 7986 return 0; 7987 } 7988 7989 if (R.isAmbiguous()) 7990 return 0; 7991 7992 if (R.empty()) { 7993 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 7994 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 7995 return 0; 7996 } 7997 } 7998 7999 NamespaceAliasDecl *AliasDecl = 8000 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 8001 Alias, SS.getWithLocInContext(Context), 8002 IdentLoc, R.getFoundDecl()); 8003 8004 PushOnScopeChains(AliasDecl, S); 8005 return AliasDecl; 8006 } 8007 8008 Sema::ImplicitExceptionSpecification 8009 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 8010 CXXMethodDecl *MD) { 8011 CXXRecordDecl *ClassDecl = MD->getParent(); 8012 8013 // C++ [except.spec]p14: 8014 // An implicitly declared special member function (Clause 12) shall have an 8015 // exception-specification. [...] 8016 ImplicitExceptionSpecification ExceptSpec(*this); 8017 if (ClassDecl->isInvalidDecl()) 8018 return ExceptSpec; 8019 8020 // Direct base-class constructors. 8021 for (const auto &B : ClassDecl->bases()) { 8022 if (B.isVirtual()) // Handled below. 8023 continue; 8024 8025 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8026 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8027 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8028 // If this is a deleted function, add it anyway. This might be conformant 8029 // with the standard. This might not. I'm not sure. It might not matter. 8030 if (Constructor) 8031 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8032 } 8033 } 8034 8035 // Virtual base-class constructors. 8036 for (const auto &B : ClassDecl->vbases()) { 8037 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8038 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8039 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8040 // If this is a deleted function, add it anyway. This might be conformant 8041 // with the standard. This might not. I'm not sure. It might not matter. 8042 if (Constructor) 8043 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8044 } 8045 } 8046 8047 // Field constructors. 8048 for (const auto *F : ClassDecl->fields()) { 8049 if (F->hasInClassInitializer()) { 8050 if (Expr *E = F->getInClassInitializer()) 8051 ExceptSpec.CalledExpr(E); 8052 else if (!F->isInvalidDecl()) 8053 // DR1351: 8054 // If the brace-or-equal-initializer of a non-static data member 8055 // invokes a defaulted default constructor of its class or of an 8056 // enclosing class in a potentially evaluated subexpression, the 8057 // program is ill-formed. 8058 // 8059 // This resolution is unworkable: the exception specification of the 8060 // default constructor can be needed in an unevaluated context, in 8061 // particular, in the operand of a noexcept-expression, and we can be 8062 // unable to compute an exception specification for an enclosed class. 8063 // 8064 // We do not allow an in-class initializer to require the evaluation 8065 // of the exception specification for any in-class initializer whose 8066 // definition is not lexically complete. 8067 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD; 8068 } else if (const RecordType *RecordTy 8069 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8070 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8071 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8072 // If this is a deleted function, add it anyway. This might be conformant 8073 // with the standard. This might not. I'm not sure. It might not matter. 8074 // In particular, the problem is that this function never gets called. It 8075 // might just be ill-formed because this function attempts to refer to 8076 // a deleted function here. 8077 if (Constructor) 8078 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8079 } 8080 } 8081 8082 return ExceptSpec; 8083 } 8084 8085 Sema::ImplicitExceptionSpecification 8086 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) { 8087 CXXRecordDecl *ClassDecl = CD->getParent(); 8088 8089 // C++ [except.spec]p14: 8090 // An inheriting constructor [...] shall have an exception-specification. [...] 8091 ImplicitExceptionSpecification ExceptSpec(*this); 8092 if (ClassDecl->isInvalidDecl()) 8093 return ExceptSpec; 8094 8095 // Inherited constructor. 8096 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor(); 8097 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent(); 8098 // FIXME: Copying or moving the parameters could add extra exceptions to the 8099 // set, as could the default arguments for the inherited constructor. This 8100 // will be addressed when we implement the resolution of core issue 1351. 8101 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD); 8102 8103 // Direct base-class constructors. 8104 for (const auto &B : ClassDecl->bases()) { 8105 if (B.isVirtual()) // Handled below. 8106 continue; 8107 8108 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8109 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8110 if (BaseClassDecl == InheritedDecl) 8111 continue; 8112 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8113 if (Constructor) 8114 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8115 } 8116 } 8117 8118 // Virtual base-class constructors. 8119 for (const auto &B : ClassDecl->vbases()) { 8120 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 8121 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 8122 if (BaseClassDecl == InheritedDecl) 8123 continue; 8124 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl); 8125 if (Constructor) 8126 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 8127 } 8128 } 8129 8130 // Field constructors. 8131 for (const auto *F : ClassDecl->fields()) { 8132 if (F->hasInClassInitializer()) { 8133 if (Expr *E = F->getInClassInitializer()) 8134 ExceptSpec.CalledExpr(E); 8135 else if (!F->isInvalidDecl()) 8136 Diag(CD->getLocation(), 8137 diag::err_in_class_initializer_references_def_ctor) << CD; 8138 } else if (const RecordType *RecordTy 8139 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 8140 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 8141 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl); 8142 if (Constructor) 8143 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 8144 } 8145 } 8146 8147 return ExceptSpec; 8148 } 8149 8150 namespace { 8151 /// RAII object to register a special member as being currently declared. 8152 struct DeclaringSpecialMember { 8153 Sema &S; 8154 Sema::SpecialMemberDecl D; 8155 bool WasAlreadyBeingDeclared; 8156 8157 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 8158 : S(S), D(RD, CSM) { 8159 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D); 8160 if (WasAlreadyBeingDeclared) 8161 // This almost never happens, but if it does, ensure that our cache 8162 // doesn't contain a stale result. 8163 S.SpecialMemberCache.clear(); 8164 8165 // FIXME: Register a note to be produced if we encounter an error while 8166 // declaring the special member. 8167 } 8168 ~DeclaringSpecialMember() { 8169 if (!WasAlreadyBeingDeclared) 8170 S.SpecialMembersBeingDeclared.erase(D); 8171 } 8172 8173 /// \brief Are we already trying to declare this special member? 8174 bool isAlreadyBeingDeclared() const { 8175 return WasAlreadyBeingDeclared; 8176 } 8177 }; 8178 } 8179 8180 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 8181 CXXRecordDecl *ClassDecl) { 8182 // C++ [class.ctor]p5: 8183 // A default constructor for a class X is a constructor of class X 8184 // that can be called without an argument. If there is no 8185 // user-declared constructor for class X, a default constructor is 8186 // implicitly declared. An implicitly-declared default constructor 8187 // is an inline public member of its class. 8188 assert(ClassDecl->needsImplicitDefaultConstructor() && 8189 "Should not build implicit default constructor!"); 8190 8191 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 8192 if (DSM.isAlreadyBeingDeclared()) 8193 return 0; 8194 8195 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 8196 CXXDefaultConstructor, 8197 false); 8198 8199 // Create the actual constructor declaration. 8200 CanQualType ClassType 8201 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8202 SourceLocation ClassLoc = ClassDecl->getLocation(); 8203 DeclarationName Name 8204 = Context.DeclarationNames.getCXXConstructorName(ClassType); 8205 DeclarationNameInfo NameInfo(Name, ClassLoc); 8206 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 8207 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0, 8208 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 8209 Constexpr); 8210 DefaultCon->setAccess(AS_public); 8211 DefaultCon->setDefaulted(); 8212 DefaultCon->setImplicit(); 8213 8214 // Build an exception specification pointing back at this constructor. 8215 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon); 8216 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8217 8218 // We don't need to use SpecialMemberIsTrivial here; triviality for default 8219 // constructors is easy to compute. 8220 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 8221 8222 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 8223 SetDeclDeleted(DefaultCon, ClassLoc); 8224 8225 // Note that we have declared this constructor. 8226 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 8227 8228 if (Scope *S = getScopeForContext(ClassDecl)) 8229 PushOnScopeChains(DefaultCon, S, false); 8230 ClassDecl->addDecl(DefaultCon); 8231 8232 return DefaultCon; 8233 } 8234 8235 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 8236 CXXConstructorDecl *Constructor) { 8237 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 8238 !Constructor->doesThisDeclarationHaveABody() && 8239 !Constructor->isDeleted()) && 8240 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 8241 8242 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8243 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 8244 8245 SynthesizedFunctionScope Scope(*this, Constructor); 8246 DiagnosticErrorTrap Trap(Diags); 8247 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8248 Trap.hasErrorOccurred()) { 8249 Diag(CurrentLocation, diag::note_member_synthesized_at) 8250 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl); 8251 Constructor->setInvalidDecl(); 8252 return; 8253 } 8254 8255 SourceLocation Loc = Constructor->getLocation(); 8256 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8257 8258 Constructor->markUsed(Context); 8259 MarkVTableUsed(CurrentLocation, ClassDecl); 8260 8261 if (ASTMutationListener *L = getASTMutationListener()) { 8262 L->CompletedImplicitDefinition(Constructor); 8263 } 8264 8265 DiagnoseUninitializedFields(*this, Constructor); 8266 } 8267 8268 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 8269 // Perform any delayed checks on exception specifications. 8270 CheckDelayedMemberExceptionSpecs(); 8271 } 8272 8273 namespace { 8274 /// Information on inheriting constructors to declare. 8275 class InheritingConstructorInfo { 8276 public: 8277 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived) 8278 : SemaRef(SemaRef), Derived(Derived) { 8279 // Mark the constructors that we already have in the derived class. 8280 // 8281 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...] 8282 // unless there is a user-declared constructor with the same signature in 8283 // the class where the using-declaration appears. 8284 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived); 8285 } 8286 8287 void inheritAll(CXXRecordDecl *RD) { 8288 visitAll(RD, &InheritingConstructorInfo::inherit); 8289 } 8290 8291 private: 8292 /// Information about an inheriting constructor. 8293 struct InheritingConstructor { 8294 InheritingConstructor() 8295 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {} 8296 8297 /// If \c true, a constructor with this signature is already declared 8298 /// in the derived class. 8299 bool DeclaredInDerived; 8300 8301 /// The constructor which is inherited. 8302 const CXXConstructorDecl *BaseCtor; 8303 8304 /// The derived constructor we declared. 8305 CXXConstructorDecl *DerivedCtor; 8306 }; 8307 8308 /// Inheriting constructors with a given canonical type. There can be at 8309 /// most one such non-template constructor, and any number of templated 8310 /// constructors. 8311 struct InheritingConstructorsForType { 8312 InheritingConstructor NonTemplate; 8313 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4> 8314 Templates; 8315 8316 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) { 8317 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) { 8318 TemplateParameterList *ParamList = FTD->getTemplateParameters(); 8319 for (unsigned I = 0, N = Templates.size(); I != N; ++I) 8320 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first, 8321 false, S.TPL_TemplateMatch)) 8322 return Templates[I].second; 8323 Templates.push_back(std::make_pair(ParamList, InheritingConstructor())); 8324 return Templates.back().second; 8325 } 8326 8327 return NonTemplate; 8328 } 8329 }; 8330 8331 /// Get or create the inheriting constructor record for a constructor. 8332 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor, 8333 QualType CtorType) { 8334 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()] 8335 .getEntry(SemaRef, Ctor); 8336 } 8337 8338 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*); 8339 8340 /// Process all constructors for a class. 8341 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) { 8342 for (const auto *Ctor : RD->ctors()) 8343 (this->*Callback)(Ctor); 8344 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 8345 I(RD->decls_begin()), E(RD->decls_end()); 8346 I != E; ++I) { 8347 const FunctionDecl *FD = (*I)->getTemplatedDecl(); 8348 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 8349 (this->*Callback)(CD); 8350 } 8351 } 8352 8353 /// Note that a constructor (or constructor template) was declared in Derived. 8354 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) { 8355 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true; 8356 } 8357 8358 /// Inherit a single constructor. 8359 void inherit(const CXXConstructorDecl *Ctor) { 8360 const FunctionProtoType *CtorType = 8361 Ctor->getType()->castAs<FunctionProtoType>(); 8362 ArrayRef<QualType> ArgTypes(CtorType->getParamTypes()); 8363 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo(); 8364 8365 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent()); 8366 8367 // Core issue (no number yet): the ellipsis is always discarded. 8368 if (EPI.Variadic) { 8369 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis); 8370 SemaRef.Diag(Ctor->getLocation(), 8371 diag::note_using_decl_constructor_ellipsis); 8372 EPI.Variadic = false; 8373 } 8374 8375 // Declare a constructor for each number of parameters. 8376 // 8377 // C++11 [class.inhctor]p1: 8378 // The candidate set of inherited constructors from the class X named in 8379 // the using-declaration consists of [... modulo defects ...] for each 8380 // constructor or constructor template of X, the set of constructors or 8381 // constructor templates that results from omitting any ellipsis parameter 8382 // specification and successively omitting parameters with a default 8383 // argument from the end of the parameter-type-list 8384 unsigned MinParams = minParamsToInherit(Ctor); 8385 unsigned Params = Ctor->getNumParams(); 8386 if (Params >= MinParams) { 8387 do 8388 declareCtor(UsingLoc, Ctor, 8389 SemaRef.Context.getFunctionType( 8390 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI)); 8391 while (Params > MinParams && 8392 Ctor->getParamDecl(--Params)->hasDefaultArg()); 8393 } 8394 } 8395 8396 /// Find the using-declaration which specified that we should inherit the 8397 /// constructors of \p Base. 8398 SourceLocation getUsingLoc(const CXXRecordDecl *Base) { 8399 // No fancy lookup required; just look for the base constructor name 8400 // directly within the derived class. 8401 ASTContext &Context = SemaRef.Context; 8402 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8403 Context.getCanonicalType(Context.getRecordType(Base))); 8404 DeclContext::lookup_const_result Decls = Derived->lookup(Name); 8405 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation(); 8406 } 8407 8408 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) { 8409 // C++11 [class.inhctor]p3: 8410 // [F]or each constructor template in the candidate set of inherited 8411 // constructors, a constructor template is implicitly declared 8412 if (Ctor->getDescribedFunctionTemplate()) 8413 return 0; 8414 8415 // For each non-template constructor in the candidate set of inherited 8416 // constructors other than a constructor having no parameters or a 8417 // copy/move constructor having a single parameter, a constructor is 8418 // implicitly declared [...] 8419 if (Ctor->getNumParams() == 0) 8420 return 1; 8421 if (Ctor->isCopyOrMoveConstructor()) 8422 return 2; 8423 8424 // Per discussion on core reflector, never inherit a constructor which 8425 // would become a default, copy, or move constructor of Derived either. 8426 const ParmVarDecl *PD = Ctor->getParamDecl(0); 8427 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>(); 8428 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1; 8429 } 8430 8431 /// Declare a single inheriting constructor, inheriting the specified 8432 /// constructor, with the given type. 8433 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor, 8434 QualType DerivedType) { 8435 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType); 8436 8437 // C++11 [class.inhctor]p3: 8438 // ... a constructor is implicitly declared with the same constructor 8439 // characteristics unless there is a user-declared constructor with 8440 // the same signature in the class where the using-declaration appears 8441 if (Entry.DeclaredInDerived) 8442 return; 8443 8444 // C++11 [class.inhctor]p7: 8445 // If two using-declarations declare inheriting constructors with the 8446 // same signature, the program is ill-formed 8447 if (Entry.DerivedCtor) { 8448 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) { 8449 // Only diagnose this once per constructor. 8450 if (Entry.DerivedCtor->isInvalidDecl()) 8451 return; 8452 Entry.DerivedCtor->setInvalidDecl(); 8453 8454 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 8455 SemaRef.Diag(BaseCtor->getLocation(), 8456 diag::note_using_decl_constructor_conflict_current_ctor); 8457 SemaRef.Diag(Entry.BaseCtor->getLocation(), 8458 diag::note_using_decl_constructor_conflict_previous_ctor); 8459 SemaRef.Diag(Entry.DerivedCtor->getLocation(), 8460 diag::note_using_decl_constructor_conflict_previous_using); 8461 } else { 8462 // Core issue (no number): if the same inheriting constructor is 8463 // produced by multiple base class constructors from the same base 8464 // class, the inheriting constructor is defined as deleted. 8465 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc); 8466 } 8467 8468 return; 8469 } 8470 8471 ASTContext &Context = SemaRef.Context; 8472 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 8473 Context.getCanonicalType(Context.getRecordType(Derived))); 8474 DeclarationNameInfo NameInfo(Name, UsingLoc); 8475 8476 TemplateParameterList *TemplateParams = 0; 8477 if (const FunctionTemplateDecl *FTD = 8478 BaseCtor->getDescribedFunctionTemplate()) { 8479 TemplateParams = FTD->getTemplateParameters(); 8480 // We're reusing template parameters from a different DeclContext. This 8481 // is questionable at best, but works out because the template depth in 8482 // both places is guaranteed to be 0. 8483 // FIXME: Rebuild the template parameters in the new context, and 8484 // transform the function type to refer to them. 8485 } 8486 8487 // Build type source info pointing at the using-declaration. This is 8488 // required by template instantiation. 8489 TypeSourceInfo *TInfo = 8490 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc); 8491 FunctionProtoTypeLoc ProtoLoc = 8492 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 8493 8494 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 8495 Context, Derived, UsingLoc, NameInfo, DerivedType, 8496 TInfo, BaseCtor->isExplicit(), /*Inline=*/true, 8497 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr()); 8498 8499 // Build an unevaluated exception specification for this constructor. 8500 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>(); 8501 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8502 EPI.ExceptionSpecType = EST_Unevaluated; 8503 EPI.ExceptionSpecDecl = DerivedCtor; 8504 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 8505 FPT->getParamTypes(), EPI)); 8506 8507 // Build the parameter declarations. 8508 SmallVector<ParmVarDecl *, 16> ParamDecls; 8509 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 8510 TypeSourceInfo *TInfo = 8511 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 8512 ParmVarDecl *PD = ParmVarDecl::Create( 8513 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0, 8514 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/0); 8515 PD->setScopeInfo(0, I); 8516 PD->setImplicit(); 8517 ParamDecls.push_back(PD); 8518 ProtoLoc.setParam(I, PD); 8519 } 8520 8521 // Set up the new constructor. 8522 DerivedCtor->setAccess(BaseCtor->getAccess()); 8523 DerivedCtor->setParams(ParamDecls); 8524 DerivedCtor->setInheritedConstructor(BaseCtor); 8525 if (BaseCtor->isDeleted()) 8526 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc); 8527 8528 // If this is a constructor template, build the template declaration. 8529 if (TemplateParams) { 8530 FunctionTemplateDecl *DerivedTemplate = 8531 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name, 8532 TemplateParams, DerivedCtor); 8533 DerivedTemplate->setAccess(BaseCtor->getAccess()); 8534 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate); 8535 Derived->addDecl(DerivedTemplate); 8536 } else { 8537 Derived->addDecl(DerivedCtor); 8538 } 8539 8540 Entry.BaseCtor = BaseCtor; 8541 Entry.DerivedCtor = DerivedCtor; 8542 } 8543 8544 Sema &SemaRef; 8545 CXXRecordDecl *Derived; 8546 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType; 8547 MapType Map; 8548 }; 8549 } 8550 8551 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) { 8552 // Defer declaring the inheriting constructors until the class is 8553 // instantiated. 8554 if (ClassDecl->isDependentContext()) 8555 return; 8556 8557 // Find base classes from which we might inherit constructors. 8558 SmallVector<CXXRecordDecl*, 4> InheritedBases; 8559 for (const auto &BaseIt : ClassDecl->bases()) 8560 if (BaseIt.getInheritConstructors()) 8561 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl()); 8562 8563 // Go no further if we're not inheriting any constructors. 8564 if (InheritedBases.empty()) 8565 return; 8566 8567 // Declare the inherited constructors. 8568 InheritingConstructorInfo ICI(*this, ClassDecl); 8569 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I) 8570 ICI.inheritAll(InheritedBases[I]); 8571 } 8572 8573 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 8574 CXXConstructorDecl *Constructor) { 8575 CXXRecordDecl *ClassDecl = Constructor->getParent(); 8576 assert(Constructor->getInheritedConstructor() && 8577 !Constructor->doesThisDeclarationHaveABody() && 8578 !Constructor->isDeleted()); 8579 8580 SynthesizedFunctionScope Scope(*this, Constructor); 8581 DiagnosticErrorTrap Trap(Diags); 8582 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) || 8583 Trap.hasErrorOccurred()) { 8584 Diag(CurrentLocation, diag::note_inhctor_synthesized_at) 8585 << Context.getTagDeclType(ClassDecl); 8586 Constructor->setInvalidDecl(); 8587 return; 8588 } 8589 8590 SourceLocation Loc = Constructor->getLocation(); 8591 Constructor->setBody(new (Context) CompoundStmt(Loc)); 8592 8593 Constructor->markUsed(Context); 8594 MarkVTableUsed(CurrentLocation, ClassDecl); 8595 8596 if (ASTMutationListener *L = getASTMutationListener()) { 8597 L->CompletedImplicitDefinition(Constructor); 8598 } 8599 } 8600 8601 8602 Sema::ImplicitExceptionSpecification 8603 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) { 8604 CXXRecordDecl *ClassDecl = MD->getParent(); 8605 8606 // C++ [except.spec]p14: 8607 // An implicitly declared special member function (Clause 12) shall have 8608 // an exception-specification. 8609 ImplicitExceptionSpecification ExceptSpec(*this); 8610 if (ClassDecl->isInvalidDecl()) 8611 return ExceptSpec; 8612 8613 // Direct base-class destructors. 8614 for (const auto &B : ClassDecl->bases()) { 8615 if (B.isVirtual()) // Handled below. 8616 continue; 8617 8618 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 8619 ExceptSpec.CalledDecl(B.getLocStart(), 8620 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8621 } 8622 8623 // Virtual base-class destructors. 8624 for (const auto &B : ClassDecl->vbases()) { 8625 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) 8626 ExceptSpec.CalledDecl(B.getLocStart(), 8627 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 8628 } 8629 8630 // Field destructors. 8631 for (const auto *F : ClassDecl->fields()) { 8632 if (const RecordType *RecordTy 8633 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 8634 ExceptSpec.CalledDecl(F->getLocation(), 8635 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 8636 } 8637 8638 return ExceptSpec; 8639 } 8640 8641 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 8642 // C++ [class.dtor]p2: 8643 // If a class has no user-declared destructor, a destructor is 8644 // declared implicitly. An implicitly-declared destructor is an 8645 // inline public member of its class. 8646 assert(ClassDecl->needsImplicitDestructor()); 8647 8648 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 8649 if (DSM.isAlreadyBeingDeclared()) 8650 return 0; 8651 8652 // Create the actual destructor declaration. 8653 CanQualType ClassType 8654 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8655 SourceLocation ClassLoc = ClassDecl->getLocation(); 8656 DeclarationName Name 8657 = Context.DeclarationNames.getCXXDestructorName(ClassType); 8658 DeclarationNameInfo NameInfo(Name, ClassLoc); 8659 CXXDestructorDecl *Destructor 8660 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 8661 QualType(), 0, /*isInline=*/true, 8662 /*isImplicitlyDeclared=*/true); 8663 Destructor->setAccess(AS_public); 8664 Destructor->setDefaulted(); 8665 Destructor->setImplicit(); 8666 8667 // Build an exception specification pointing back at this destructor. 8668 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor); 8669 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8670 8671 AddOverriddenMethods(ClassDecl, Destructor); 8672 8673 // We don't need to use SpecialMemberIsTrivial here; triviality for 8674 // destructors is easy to compute. 8675 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 8676 8677 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 8678 SetDeclDeleted(Destructor, ClassLoc); 8679 8680 // Note that we have declared this destructor. 8681 ++ASTContext::NumImplicitDestructorsDeclared; 8682 8683 // Introduce this destructor into its scope. 8684 if (Scope *S = getScopeForContext(ClassDecl)) 8685 PushOnScopeChains(Destructor, S, false); 8686 ClassDecl->addDecl(Destructor); 8687 8688 return Destructor; 8689 } 8690 8691 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 8692 CXXDestructorDecl *Destructor) { 8693 assert((Destructor->isDefaulted() && 8694 !Destructor->doesThisDeclarationHaveABody() && 8695 !Destructor->isDeleted()) && 8696 "DefineImplicitDestructor - call it for implicit default dtor"); 8697 CXXRecordDecl *ClassDecl = Destructor->getParent(); 8698 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 8699 8700 if (Destructor->isInvalidDecl()) 8701 return; 8702 8703 SynthesizedFunctionScope Scope(*this, Destructor); 8704 8705 DiagnosticErrorTrap Trap(Diags); 8706 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 8707 Destructor->getParent()); 8708 8709 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 8710 Diag(CurrentLocation, diag::note_member_synthesized_at) 8711 << CXXDestructor << Context.getTagDeclType(ClassDecl); 8712 8713 Destructor->setInvalidDecl(); 8714 return; 8715 } 8716 8717 SourceLocation Loc = Destructor->getLocation(); 8718 Destructor->setBody(new (Context) CompoundStmt(Loc)); 8719 Destructor->markUsed(Context); 8720 MarkVTableUsed(CurrentLocation, ClassDecl); 8721 8722 if (ASTMutationListener *L = getASTMutationListener()) { 8723 L->CompletedImplicitDefinition(Destructor); 8724 } 8725 } 8726 8727 /// \brief Perform any semantic analysis which needs to be delayed until all 8728 /// pending class member declarations have been parsed. 8729 void Sema::ActOnFinishCXXMemberDecls() { 8730 // If the context is an invalid C++ class, just suppress these checks. 8731 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 8732 if (Record->isInvalidDecl()) { 8733 DelayedDefaultedMemberExceptionSpecs.clear(); 8734 DelayedDestructorExceptionSpecChecks.clear(); 8735 return; 8736 } 8737 } 8738 } 8739 8740 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 8741 CXXDestructorDecl *Destructor) { 8742 assert(getLangOpts().CPlusPlus11 && 8743 "adjusting dtor exception specs was introduced in c++11"); 8744 8745 // C++11 [class.dtor]p3: 8746 // A declaration of a destructor that does not have an exception- 8747 // specification is implicitly considered to have the same exception- 8748 // specification as an implicit declaration. 8749 const FunctionProtoType *DtorType = Destructor->getType()-> 8750 getAs<FunctionProtoType>(); 8751 if (DtorType->hasExceptionSpec()) 8752 return; 8753 8754 // Replace the destructor's type, building off the existing one. Fortunately, 8755 // the only thing of interest in the destructor type is its extended info. 8756 // The return and arguments are fixed. 8757 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 8758 EPI.ExceptionSpecType = EST_Unevaluated; 8759 EPI.ExceptionSpecDecl = Destructor; 8760 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 8761 8762 // FIXME: If the destructor has a body that could throw, and the newly created 8763 // spec doesn't allow exceptions, we should emit a warning, because this 8764 // change in behavior can break conforming C++03 programs at runtime. 8765 // However, we don't have a body or an exception specification yet, so it 8766 // needs to be done somewhere else. 8767 } 8768 8769 namespace { 8770 /// \brief An abstract base class for all helper classes used in building the 8771 // copy/move operators. These classes serve as factory functions and help us 8772 // avoid using the same Expr* in the AST twice. 8773 class ExprBuilder { 8774 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8775 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION; 8776 8777 protected: 8778 static Expr *assertNotNull(Expr *E) { 8779 assert(E && "Expression construction must not fail."); 8780 return E; 8781 } 8782 8783 public: 8784 ExprBuilder() {} 8785 virtual ~ExprBuilder() {} 8786 8787 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 8788 }; 8789 8790 class RefBuilder: public ExprBuilder { 8791 VarDecl *Var; 8792 QualType VarType; 8793 8794 public: 8795 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8796 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take()); 8797 } 8798 8799 RefBuilder(VarDecl *Var, QualType VarType) 8800 : Var(Var), VarType(VarType) {} 8801 }; 8802 8803 class ThisBuilder: public ExprBuilder { 8804 public: 8805 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8806 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>()); 8807 } 8808 }; 8809 8810 class CastBuilder: public ExprBuilder { 8811 const ExprBuilder &Builder; 8812 QualType Type; 8813 ExprValueKind Kind; 8814 const CXXCastPath &Path; 8815 8816 public: 8817 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8818 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 8819 CK_UncheckedDerivedToBase, Kind, 8820 &Path).take()); 8821 } 8822 8823 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 8824 const CXXCastPath &Path) 8825 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 8826 }; 8827 8828 class DerefBuilder: public ExprBuilder { 8829 const ExprBuilder &Builder; 8830 8831 public: 8832 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8833 return assertNotNull( 8834 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take()); 8835 } 8836 8837 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8838 }; 8839 8840 class MemberBuilder: public ExprBuilder { 8841 const ExprBuilder &Builder; 8842 QualType Type; 8843 CXXScopeSpec SS; 8844 bool IsArrow; 8845 LookupResult &MemberLookup; 8846 8847 public: 8848 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8849 return assertNotNull(S.BuildMemberReferenceExpr( 8850 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0, 8851 MemberLookup, 0).take()); 8852 } 8853 8854 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 8855 LookupResult &MemberLookup) 8856 : Builder(Builder), Type(Type), IsArrow(IsArrow), 8857 MemberLookup(MemberLookup) {} 8858 }; 8859 8860 class MoveCastBuilder: public ExprBuilder { 8861 const ExprBuilder &Builder; 8862 8863 public: 8864 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8865 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 8866 } 8867 8868 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8869 }; 8870 8871 class LvalueConvBuilder: public ExprBuilder { 8872 const ExprBuilder &Builder; 8873 8874 public: 8875 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8876 return assertNotNull( 8877 S.DefaultLvalueConversion(Builder.build(S, Loc)).take()); 8878 } 8879 8880 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 8881 }; 8882 8883 class SubscriptBuilder: public ExprBuilder { 8884 const ExprBuilder &Base; 8885 const ExprBuilder &Index; 8886 8887 public: 8888 virtual Expr *build(Sema &S, SourceLocation Loc) const override { 8889 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 8890 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take()); 8891 } 8892 8893 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 8894 : Base(Base), Index(Index) {} 8895 }; 8896 8897 } // end anonymous namespace 8898 8899 /// When generating a defaulted copy or move assignment operator, if a field 8900 /// should be copied with __builtin_memcpy rather than via explicit assignments, 8901 /// do so. This optimization only applies for arrays of scalars, and for arrays 8902 /// of class type where the selected copy/move-assignment operator is trivial. 8903 static StmtResult 8904 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 8905 const ExprBuilder &ToB, const ExprBuilder &FromB) { 8906 // Compute the size of the memory buffer to be copied. 8907 QualType SizeType = S.Context.getSizeType(); 8908 llvm::APInt Size(S.Context.getTypeSize(SizeType), 8909 S.Context.getTypeSizeInChars(T).getQuantity()); 8910 8911 // Take the address of the field references for "from" and "to". We 8912 // directly construct UnaryOperators here because semantic analysis 8913 // does not permit us to take the address of an xvalue. 8914 Expr *From = FromB.build(S, Loc); 8915 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 8916 S.Context.getPointerType(From->getType()), 8917 VK_RValue, OK_Ordinary, Loc); 8918 Expr *To = ToB.build(S, Loc); 8919 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 8920 S.Context.getPointerType(To->getType()), 8921 VK_RValue, OK_Ordinary, Loc); 8922 8923 const Type *E = T->getBaseElementTypeUnsafe(); 8924 bool NeedsCollectableMemCpy = 8925 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 8926 8927 // Create a reference to the __builtin_objc_memmove_collectable function 8928 StringRef MemCpyName = NeedsCollectableMemCpy ? 8929 "__builtin_objc_memmove_collectable" : 8930 "__builtin_memcpy"; 8931 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 8932 Sema::LookupOrdinaryName); 8933 S.LookupName(R, S.TUScope, true); 8934 8935 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 8936 if (!MemCpy) 8937 // Something went horribly wrong earlier, and we will have complained 8938 // about it. 8939 return StmtError(); 8940 8941 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 8942 VK_RValue, Loc, 0); 8943 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 8944 8945 Expr *CallArgs[] = { 8946 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 8947 }; 8948 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(), 8949 Loc, CallArgs, Loc); 8950 8951 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 8952 return S.Owned(Call.takeAs<Stmt>()); 8953 } 8954 8955 /// \brief Builds a statement that copies/moves the given entity from \p From to 8956 /// \c To. 8957 /// 8958 /// This routine is used to copy/move the members of a class with an 8959 /// implicitly-declared copy/move assignment operator. When the entities being 8960 /// copied are arrays, this routine builds for loops to copy them. 8961 /// 8962 /// \param S The Sema object used for type-checking. 8963 /// 8964 /// \param Loc The location where the implicit copy/move is being generated. 8965 /// 8966 /// \param T The type of the expressions being copied/moved. Both expressions 8967 /// must have this type. 8968 /// 8969 /// \param To The expression we are copying/moving to. 8970 /// 8971 /// \param From The expression we are copying/moving from. 8972 /// 8973 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 8974 /// Otherwise, it's a non-static member subobject. 8975 /// 8976 /// \param Copying Whether we're copying or moving. 8977 /// 8978 /// \param Depth Internal parameter recording the depth of the recursion. 8979 /// 8980 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 8981 /// if a memcpy should be used instead. 8982 static StmtResult 8983 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 8984 const ExprBuilder &To, const ExprBuilder &From, 8985 bool CopyingBaseSubobject, bool Copying, 8986 unsigned Depth = 0) { 8987 // C++11 [class.copy]p28: 8988 // Each subobject is assigned in the manner appropriate to its type: 8989 // 8990 // - if the subobject is of class type, as if by a call to operator= with 8991 // the subobject as the object expression and the corresponding 8992 // subobject of x as a single function argument (as if by explicit 8993 // qualification; that is, ignoring any possible virtual overriding 8994 // functions in more derived classes); 8995 // 8996 // C++03 [class.copy]p13: 8997 // - if the subobject is of class type, the copy assignment operator for 8998 // the class is used (as if by explicit qualification; that is, 8999 // ignoring any possible virtual overriding functions in more derived 9000 // classes); 9001 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 9002 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 9003 9004 // Look for operator=. 9005 DeclarationName Name 9006 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9007 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 9008 S.LookupQualifiedName(OpLookup, ClassDecl, false); 9009 9010 // Prior to C++11, filter out any result that isn't a copy/move-assignment 9011 // operator. 9012 if (!S.getLangOpts().CPlusPlus11) { 9013 LookupResult::Filter F = OpLookup.makeFilter(); 9014 while (F.hasNext()) { 9015 NamedDecl *D = F.next(); 9016 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 9017 if (Method->isCopyAssignmentOperator() || 9018 (!Copying && Method->isMoveAssignmentOperator())) 9019 continue; 9020 9021 F.erase(); 9022 } 9023 F.done(); 9024 } 9025 9026 // Suppress the protected check (C++ [class.protected]) for each of the 9027 // assignment operators we found. This strange dance is required when 9028 // we're assigning via a base classes's copy-assignment operator. To 9029 // ensure that we're getting the right base class subobject (without 9030 // ambiguities), we need to cast "this" to that subobject type; to 9031 // ensure that we don't go through the virtual call mechanism, we need 9032 // to qualify the operator= name with the base class (see below). However, 9033 // this means that if the base class has a protected copy assignment 9034 // operator, the protected member access check will fail. So, we 9035 // rewrite "protected" access to "public" access in this case, since we 9036 // know by construction that we're calling from a derived class. 9037 if (CopyingBaseSubobject) { 9038 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 9039 L != LEnd; ++L) { 9040 if (L.getAccess() == AS_protected) 9041 L.setAccess(AS_public); 9042 } 9043 } 9044 9045 // Create the nested-name-specifier that will be used to qualify the 9046 // reference to operator=; this is required to suppress the virtual 9047 // call mechanism. 9048 CXXScopeSpec SS; 9049 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 9050 SS.MakeTrivial(S.Context, 9051 NestedNameSpecifier::Create(S.Context, 0, false, 9052 CanonicalT), 9053 Loc); 9054 9055 // Create the reference to operator=. 9056 ExprResult OpEqualRef 9057 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false, 9058 SS, /*TemplateKWLoc=*/SourceLocation(), 9059 /*FirstQualifierInScope=*/0, 9060 OpLookup, 9061 /*TemplateArgs=*/0, 9062 /*SuppressQualifierCheck=*/true); 9063 if (OpEqualRef.isInvalid()) 9064 return StmtError(); 9065 9066 // Build the call to the assignment operator. 9067 9068 Expr *FromInst = From.build(S, Loc); 9069 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 9070 OpEqualRef.takeAs<Expr>(), 9071 Loc, FromInst, Loc); 9072 if (Call.isInvalid()) 9073 return StmtError(); 9074 9075 // If we built a call to a trivial 'operator=' while copying an array, 9076 // bail out. We'll replace the whole shebang with a memcpy. 9077 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 9078 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 9079 return StmtResult((Stmt*)0); 9080 9081 // Convert to an expression-statement, and clean up any produced 9082 // temporaries. 9083 return S.ActOnExprStmt(Call); 9084 } 9085 9086 // - if the subobject is of scalar type, the built-in assignment 9087 // operator is used. 9088 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 9089 if (!ArrayTy) { 9090 ExprResult Assignment = S.CreateBuiltinBinOp( 9091 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 9092 if (Assignment.isInvalid()) 9093 return StmtError(); 9094 return S.ActOnExprStmt(Assignment); 9095 } 9096 9097 // - if the subobject is an array, each element is assigned, in the 9098 // manner appropriate to the element type; 9099 9100 // Construct a loop over the array bounds, e.g., 9101 // 9102 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 9103 // 9104 // that will copy each of the array elements. 9105 QualType SizeType = S.Context.getSizeType(); 9106 9107 // Create the iteration variable. 9108 IdentifierInfo *IterationVarName = 0; 9109 { 9110 SmallString<8> Str; 9111 llvm::raw_svector_ostream OS(Str); 9112 OS << "__i" << Depth; 9113 IterationVarName = &S.Context.Idents.get(OS.str()); 9114 } 9115 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 9116 IterationVarName, SizeType, 9117 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 9118 SC_None); 9119 9120 // Initialize the iteration variable to zero. 9121 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 9122 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 9123 9124 // Creates a reference to the iteration variable. 9125 RefBuilder IterationVarRef(IterationVar, SizeType); 9126 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 9127 9128 // Create the DeclStmt that holds the iteration variable. 9129 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 9130 9131 // Subscript the "from" and "to" expressions with the iteration variable. 9132 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 9133 MoveCastBuilder FromIndexMove(FromIndexCopy); 9134 const ExprBuilder *FromIndex; 9135 if (Copying) 9136 FromIndex = &FromIndexCopy; 9137 else 9138 FromIndex = &FromIndexMove; 9139 9140 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 9141 9142 // Build the copy/move for an individual element of the array. 9143 StmtResult Copy = 9144 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 9145 ToIndex, *FromIndex, CopyingBaseSubobject, 9146 Copying, Depth + 1); 9147 // Bail out if copying fails or if we determined that we should use memcpy. 9148 if (Copy.isInvalid() || !Copy.get()) 9149 return Copy; 9150 9151 // Create the comparison against the array bound. 9152 llvm::APInt Upper 9153 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 9154 Expr *Comparison 9155 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 9156 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 9157 BO_NE, S.Context.BoolTy, 9158 VK_RValue, OK_Ordinary, Loc, false); 9159 9160 // Create the pre-increment of the iteration variable. 9161 Expr *Increment 9162 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, 9163 SizeType, VK_LValue, OK_Ordinary, Loc); 9164 9165 // Construct the loop that copies all elements of this array. 9166 return S.ActOnForStmt(Loc, Loc, InitStmt, 9167 S.MakeFullExpr(Comparison), 9168 0, S.MakeFullDiscardedValueExpr(Increment), 9169 Loc, Copy.take()); 9170 } 9171 9172 static StmtResult 9173 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 9174 const ExprBuilder &To, const ExprBuilder &From, 9175 bool CopyingBaseSubobject, bool Copying) { 9176 // Maybe we should use a memcpy? 9177 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 9178 T.isTriviallyCopyableType(S.Context)) 9179 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9180 9181 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 9182 CopyingBaseSubobject, 9183 Copying, 0)); 9184 9185 // If we ended up picking a trivial assignment operator for an array of a 9186 // non-trivially-copyable class type, just emit a memcpy. 9187 if (!Result.isInvalid() && !Result.get()) 9188 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 9189 9190 return Result; 9191 } 9192 9193 Sema::ImplicitExceptionSpecification 9194 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) { 9195 CXXRecordDecl *ClassDecl = MD->getParent(); 9196 9197 ImplicitExceptionSpecification ExceptSpec(*this); 9198 if (ClassDecl->isInvalidDecl()) 9199 return ExceptSpec; 9200 9201 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 9202 assert(T->getNumParams() == 1 && "not a copy assignment op"); 9203 unsigned ArgQuals = 9204 T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 9205 9206 // C++ [except.spec]p14: 9207 // An implicitly declared special member function (Clause 12) shall have an 9208 // exception-specification. [...] 9209 9210 // It is unspecified whether or not an implicit copy assignment operator 9211 // attempts to deduplicate calls to assignment operators of virtual bases are 9212 // made. As such, this exception specification is effectively unspecified. 9213 // Based on a similar decision made for constness in C++0x, we're erring on 9214 // the side of assuming such calls to be made regardless of whether they 9215 // actually happen. 9216 for (const auto &Base : ClassDecl->bases()) { 9217 if (Base.isVirtual()) 9218 continue; 9219 9220 CXXRecordDecl *BaseClassDecl 9221 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9222 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9223 ArgQuals, false, 0)) 9224 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9225 } 9226 9227 for (const auto &Base : ClassDecl->vbases()) { 9228 CXXRecordDecl *BaseClassDecl 9229 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9230 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl, 9231 ArgQuals, false, 0)) 9232 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign); 9233 } 9234 9235 for (const auto *Field : ClassDecl->fields()) { 9236 QualType FieldType = Context.getBaseElementType(Field->getType()); 9237 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9238 if (CXXMethodDecl *CopyAssign = 9239 LookupCopyingAssignment(FieldClassDecl, 9240 ArgQuals | FieldType.getCVRQualifiers(), 9241 false, 0)) 9242 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign); 9243 } 9244 } 9245 9246 return ExceptSpec; 9247 } 9248 9249 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 9250 // Note: The following rules are largely analoguous to the copy 9251 // constructor rules. Note that virtual bases are not taken into account 9252 // for determining the argument type of the operator. Note also that 9253 // operators taking an object instead of a reference are allowed. 9254 assert(ClassDecl->needsImplicitCopyAssignment()); 9255 9256 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 9257 if (DSM.isAlreadyBeingDeclared()) 9258 return 0; 9259 9260 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9261 QualType RetType = Context.getLValueReferenceType(ArgType); 9262 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 9263 if (Const) 9264 ArgType = ArgType.withConst(); 9265 ArgType = Context.getLValueReferenceType(ArgType); 9266 9267 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9268 CXXCopyAssignment, 9269 Const); 9270 9271 // An implicitly-declared copy assignment operator is an inline public 9272 // member of its class. 9273 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9274 SourceLocation ClassLoc = ClassDecl->getLocation(); 9275 DeclarationNameInfo NameInfo(Name, ClassLoc); 9276 CXXMethodDecl *CopyAssignment = 9277 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9278 /*TInfo=*/ 0, /*StorageClass=*/ SC_None, 9279 /*isInline=*/ true, Constexpr, SourceLocation()); 9280 CopyAssignment->setAccess(AS_public); 9281 CopyAssignment->setDefaulted(); 9282 CopyAssignment->setImplicit(); 9283 9284 // Build an exception specification pointing back at this member. 9285 FunctionProtoType::ExtProtoInfo EPI = 9286 getImplicitMethodEPI(*this, CopyAssignment); 9287 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9288 9289 // Add the parameter to the operator. 9290 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 9291 ClassLoc, ClassLoc, /*Id=*/0, 9292 ArgType, /*TInfo=*/0, 9293 SC_None, 0); 9294 CopyAssignment->setParams(FromParam); 9295 9296 AddOverriddenMethods(ClassDecl, CopyAssignment); 9297 9298 CopyAssignment->setTrivial( 9299 ClassDecl->needsOverloadResolutionForCopyAssignment() 9300 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 9301 : ClassDecl->hasTrivialCopyAssignment()); 9302 9303 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 9304 SetDeclDeleted(CopyAssignment, ClassLoc); 9305 9306 // Note that we have added this copy-assignment operator. 9307 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 9308 9309 if (Scope *S = getScopeForContext(ClassDecl)) 9310 PushOnScopeChains(CopyAssignment, S, false); 9311 ClassDecl->addDecl(CopyAssignment); 9312 9313 return CopyAssignment; 9314 } 9315 9316 /// Diagnose an implicit copy operation for a class which is odr-used, but 9317 /// which is deprecated because the class has a user-declared copy constructor, 9318 /// copy assignment operator, or destructor. 9319 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp, 9320 SourceLocation UseLoc) { 9321 assert(CopyOp->isImplicit()); 9322 9323 CXXRecordDecl *RD = CopyOp->getParent(); 9324 CXXMethodDecl *UserDeclaredOperation = 0; 9325 9326 // In Microsoft mode, assignment operations don't affect constructors and 9327 // vice versa. 9328 if (RD->hasUserDeclaredDestructor()) { 9329 UserDeclaredOperation = RD->getDestructor(); 9330 } else if (!isa<CXXConstructorDecl>(CopyOp) && 9331 RD->hasUserDeclaredCopyConstructor() && 9332 !S.getLangOpts().MSVCCompat) { 9333 // Find any user-declared copy constructor. 9334 for (auto *I : RD->ctors()) { 9335 if (I->isCopyConstructor()) { 9336 UserDeclaredOperation = I; 9337 break; 9338 } 9339 } 9340 assert(UserDeclaredOperation); 9341 } else if (isa<CXXConstructorDecl>(CopyOp) && 9342 RD->hasUserDeclaredCopyAssignment() && 9343 !S.getLangOpts().MSVCCompat) { 9344 // Find any user-declared move assignment operator. 9345 for (auto *I : RD->methods()) { 9346 if (I->isCopyAssignmentOperator()) { 9347 UserDeclaredOperation = I; 9348 break; 9349 } 9350 } 9351 assert(UserDeclaredOperation); 9352 } 9353 9354 if (UserDeclaredOperation) { 9355 S.Diag(UserDeclaredOperation->getLocation(), 9356 diag::warn_deprecated_copy_operation) 9357 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 9358 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 9359 S.Diag(UseLoc, diag::note_member_synthesized_at) 9360 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor 9361 : Sema::CXXCopyAssignment) 9362 << RD; 9363 } 9364 } 9365 9366 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 9367 CXXMethodDecl *CopyAssignOperator) { 9368 assert((CopyAssignOperator->isDefaulted() && 9369 CopyAssignOperator->isOverloadedOperator() && 9370 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 9371 !CopyAssignOperator->doesThisDeclarationHaveABody() && 9372 !CopyAssignOperator->isDeleted()) && 9373 "DefineImplicitCopyAssignment called for wrong function"); 9374 9375 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 9376 9377 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 9378 CopyAssignOperator->setInvalidDecl(); 9379 return; 9380 } 9381 9382 // C++11 [class.copy]p18: 9383 // The [definition of an implicitly declared copy assignment operator] is 9384 // deprecated if the class has a user-declared copy constructor or a 9385 // user-declared destructor. 9386 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 9387 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation); 9388 9389 CopyAssignOperator->markUsed(Context); 9390 9391 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 9392 DiagnosticErrorTrap Trap(Diags); 9393 9394 // C++0x [class.copy]p30: 9395 // The implicitly-defined or explicitly-defaulted copy assignment operator 9396 // for a non-union class X performs memberwise copy assignment of its 9397 // subobjects. The direct base classes of X are assigned first, in the 9398 // order of their declaration in the base-specifier-list, and then the 9399 // immediate non-static data members of X are assigned, in the order in 9400 // which they were declared in the class definition. 9401 9402 // The statements that form the synthesized function body. 9403 SmallVector<Stmt*, 8> Statements; 9404 9405 // The parameter for the "other" object, which we are copying from. 9406 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 9407 Qualifiers OtherQuals = Other->getType().getQualifiers(); 9408 QualType OtherRefType = Other->getType(); 9409 if (const LValueReferenceType *OtherRef 9410 = OtherRefType->getAs<LValueReferenceType>()) { 9411 OtherRefType = OtherRef->getPointeeType(); 9412 OtherQuals = OtherRefType.getQualifiers(); 9413 } 9414 9415 // Our location for everything implicitly-generated. 9416 SourceLocation Loc = CopyAssignOperator->getLocation(); 9417 9418 // Builds a DeclRefExpr for the "other" object. 9419 RefBuilder OtherRef(Other, OtherRefType); 9420 9421 // Builds the "this" pointer. 9422 ThisBuilder This; 9423 9424 // Assign base classes. 9425 bool Invalid = false; 9426 for (auto &Base : ClassDecl->bases()) { 9427 // Form the assignment: 9428 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 9429 QualType BaseType = Base.getType().getUnqualifiedType(); 9430 if (!BaseType->isRecordType()) { 9431 Invalid = true; 9432 continue; 9433 } 9434 9435 CXXCastPath BasePath; 9436 BasePath.push_back(&Base); 9437 9438 // Construct the "from" expression, which is an implicit cast to the 9439 // appropriately-qualified base type. 9440 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 9441 VK_LValue, BasePath); 9442 9443 // Dereference "this". 9444 DerefBuilder DerefThis(This); 9445 CastBuilder To(DerefThis, 9446 Context.getCVRQualifiedType( 9447 BaseType, CopyAssignOperator->getTypeQualifiers()), 9448 VK_LValue, BasePath); 9449 9450 // Build the copy. 9451 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 9452 To, From, 9453 /*CopyingBaseSubobject=*/true, 9454 /*Copying=*/true); 9455 if (Copy.isInvalid()) { 9456 Diag(CurrentLocation, diag::note_member_synthesized_at) 9457 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9458 CopyAssignOperator->setInvalidDecl(); 9459 return; 9460 } 9461 9462 // Success! Record the copy. 9463 Statements.push_back(Copy.takeAs<Expr>()); 9464 } 9465 9466 // Assign non-static members. 9467 for (auto *Field : ClassDecl->fields()) { 9468 if (Field->isUnnamedBitfield()) 9469 continue; 9470 9471 if (Field->isInvalidDecl()) { 9472 Invalid = true; 9473 continue; 9474 } 9475 9476 // Check for members of reference type; we can't copy those. 9477 if (Field->getType()->isReferenceType()) { 9478 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9479 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9480 Diag(Field->getLocation(), diag::note_declared_at); 9481 Diag(CurrentLocation, diag::note_member_synthesized_at) 9482 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9483 Invalid = true; 9484 continue; 9485 } 9486 9487 // Check for members of const-qualified, non-class type. 9488 QualType BaseType = Context.getBaseElementType(Field->getType()); 9489 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9490 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9491 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9492 Diag(Field->getLocation(), diag::note_declared_at); 9493 Diag(CurrentLocation, diag::note_member_synthesized_at) 9494 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9495 Invalid = true; 9496 continue; 9497 } 9498 9499 // Suppress assigning zero-width bitfields. 9500 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9501 continue; 9502 9503 QualType FieldType = Field->getType().getNonReferenceType(); 9504 if (FieldType->isIncompleteArrayType()) { 9505 assert(ClassDecl->hasFlexibleArrayMember() && 9506 "Incomplete array type is not valid"); 9507 continue; 9508 } 9509 9510 // Build references to the field in the object we're copying from and to. 9511 CXXScopeSpec SS; // Intentionally empty 9512 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9513 LookupMemberName); 9514 MemberLookup.addDecl(Field); 9515 MemberLookup.resolveKind(); 9516 9517 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 9518 9519 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 9520 9521 // Build the copy of this field. 9522 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 9523 To, From, 9524 /*CopyingBaseSubobject=*/false, 9525 /*Copying=*/true); 9526 if (Copy.isInvalid()) { 9527 Diag(CurrentLocation, diag::note_member_synthesized_at) 9528 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9529 CopyAssignOperator->setInvalidDecl(); 9530 return; 9531 } 9532 9533 // Success! Record the copy. 9534 Statements.push_back(Copy.takeAs<Stmt>()); 9535 } 9536 9537 if (!Invalid) { 9538 // Add a "return *this;" 9539 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9540 9541 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9542 if (Return.isInvalid()) 9543 Invalid = true; 9544 else { 9545 Statements.push_back(Return.takeAs<Stmt>()); 9546 9547 if (Trap.hasErrorOccurred()) { 9548 Diag(CurrentLocation, diag::note_member_synthesized_at) 9549 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 9550 Invalid = true; 9551 } 9552 } 9553 } 9554 9555 if (Invalid) { 9556 CopyAssignOperator->setInvalidDecl(); 9557 return; 9558 } 9559 9560 StmtResult Body; 9561 { 9562 CompoundScopeRAII CompoundScope(*this); 9563 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9564 /*isStmtExpr=*/false); 9565 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9566 } 9567 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 9568 9569 if (ASTMutationListener *L = getASTMutationListener()) { 9570 L->CompletedImplicitDefinition(CopyAssignOperator); 9571 } 9572 } 9573 9574 Sema::ImplicitExceptionSpecification 9575 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) { 9576 CXXRecordDecl *ClassDecl = MD->getParent(); 9577 9578 ImplicitExceptionSpecification ExceptSpec(*this); 9579 if (ClassDecl->isInvalidDecl()) 9580 return ExceptSpec; 9581 9582 // C++0x [except.spec]p14: 9583 // An implicitly declared special member function (Clause 12) shall have an 9584 // exception-specification. [...] 9585 9586 // It is unspecified whether or not an implicit move assignment operator 9587 // attempts to deduplicate calls to assignment operators of virtual bases are 9588 // made. As such, this exception specification is effectively unspecified. 9589 // Based on a similar decision made for constness in C++0x, we're erring on 9590 // the side of assuming such calls to be made regardless of whether they 9591 // actually happen. 9592 // Note that a move constructor is not implicitly declared when there are 9593 // virtual bases, but it can still be user-declared and explicitly defaulted. 9594 for (const auto &Base : ClassDecl->bases()) { 9595 if (Base.isVirtual()) 9596 continue; 9597 9598 CXXRecordDecl *BaseClassDecl 9599 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9600 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9601 0, false, 0)) 9602 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 9603 } 9604 9605 for (const auto &Base : ClassDecl->vbases()) { 9606 CXXRecordDecl *BaseClassDecl 9607 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 9608 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl, 9609 0, false, 0)) 9610 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign); 9611 } 9612 9613 for (const auto *Field : ClassDecl->fields()) { 9614 QualType FieldType = Context.getBaseElementType(Field->getType()); 9615 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 9616 if (CXXMethodDecl *MoveAssign = 9617 LookupMovingAssignment(FieldClassDecl, 9618 FieldType.getCVRQualifiers(), 9619 false, 0)) 9620 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign); 9621 } 9622 } 9623 9624 return ExceptSpec; 9625 } 9626 9627 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 9628 assert(ClassDecl->needsImplicitMoveAssignment()); 9629 9630 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 9631 if (DSM.isAlreadyBeingDeclared()) 9632 return 0; 9633 9634 // Note: The following rules are largely analoguous to the move 9635 // constructor rules. 9636 9637 QualType ArgType = Context.getTypeDeclType(ClassDecl); 9638 QualType RetType = Context.getLValueReferenceType(ArgType); 9639 ArgType = Context.getRValueReferenceType(ArgType); 9640 9641 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 9642 CXXMoveAssignment, 9643 false); 9644 9645 // An implicitly-declared move assignment operator is an inline public 9646 // member of its class. 9647 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 9648 SourceLocation ClassLoc = ClassDecl->getLocation(); 9649 DeclarationNameInfo NameInfo(Name, ClassLoc); 9650 CXXMethodDecl *MoveAssignment = 9651 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(), 9652 /*TInfo=*/0, /*StorageClass=*/SC_None, 9653 /*isInline=*/true, Constexpr, SourceLocation()); 9654 MoveAssignment->setAccess(AS_public); 9655 MoveAssignment->setDefaulted(); 9656 MoveAssignment->setImplicit(); 9657 9658 // Build an exception specification pointing back at this member. 9659 FunctionProtoType::ExtProtoInfo EPI = 9660 getImplicitMethodEPI(*this, MoveAssignment); 9661 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 9662 9663 // Add the parameter to the operator. 9664 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 9665 ClassLoc, ClassLoc, /*Id=*/0, 9666 ArgType, /*TInfo=*/0, 9667 SC_None, 0); 9668 MoveAssignment->setParams(FromParam); 9669 9670 AddOverriddenMethods(ClassDecl, MoveAssignment); 9671 9672 MoveAssignment->setTrivial( 9673 ClassDecl->needsOverloadResolutionForMoveAssignment() 9674 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 9675 : ClassDecl->hasTrivialMoveAssignment()); 9676 9677 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 9678 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 9679 SetDeclDeleted(MoveAssignment, ClassLoc); 9680 } 9681 9682 // Note that we have added this copy-assignment operator. 9683 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 9684 9685 if (Scope *S = getScopeForContext(ClassDecl)) 9686 PushOnScopeChains(MoveAssignment, S, false); 9687 ClassDecl->addDecl(MoveAssignment); 9688 9689 return MoveAssignment; 9690 } 9691 9692 /// Check if we're implicitly defining a move assignment operator for a class 9693 /// with virtual bases. Such a move assignment might move-assign the virtual 9694 /// base multiple times. 9695 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 9696 SourceLocation CurrentLocation) { 9697 assert(!Class->isDependentContext() && "should not define dependent move"); 9698 9699 // Only a virtual base could get implicitly move-assigned multiple times. 9700 // Only a non-trivial move assignment can observe this. We only want to 9701 // diagnose if we implicitly define an assignment operator that assigns 9702 // two base classes, both of which move-assign the same virtual base. 9703 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 9704 Class->getNumBases() < 2) 9705 return; 9706 9707 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 9708 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 9709 VBaseMap VBases; 9710 9711 for (auto &BI : Class->bases()) { 9712 Worklist.push_back(&BI); 9713 while (!Worklist.empty()) { 9714 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 9715 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 9716 9717 // If the base has no non-trivial move assignment operators, 9718 // we don't care about moves from it. 9719 if (!Base->hasNonTrivialMoveAssignment()) 9720 continue; 9721 9722 // If there's nothing virtual here, skip it. 9723 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 9724 continue; 9725 9726 // If we're not actually going to call a move assignment for this base, 9727 // or the selected move assignment is trivial, skip it. 9728 Sema::SpecialMemberOverloadResult *SMOR = 9729 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 9730 /*ConstArg*/false, /*VolatileArg*/false, 9731 /*RValueThis*/true, /*ConstThis*/false, 9732 /*VolatileThis*/false); 9733 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() || 9734 !SMOR->getMethod()->isMoveAssignmentOperator()) 9735 continue; 9736 9737 if (BaseSpec->isVirtual()) { 9738 // We're going to move-assign this virtual base, and its move 9739 // assignment operator is not trivial. If this can happen for 9740 // multiple distinct direct bases of Class, diagnose it. (If it 9741 // only happens in one base, we'll diagnose it when synthesizing 9742 // that base class's move assignment operator.) 9743 CXXBaseSpecifier *&Existing = 9744 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 9745 .first->second; 9746 if (Existing && Existing != &BI) { 9747 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 9748 << Class << Base; 9749 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here) 9750 << (Base->getCanonicalDecl() == 9751 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 9752 << Base << Existing->getType() << Existing->getSourceRange(); 9753 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here) 9754 << (Base->getCanonicalDecl() == 9755 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 9756 << Base << BI.getType() << BaseSpec->getSourceRange(); 9757 9758 // Only diagnose each vbase once. 9759 Existing = 0; 9760 } 9761 } else { 9762 // Only walk over bases that have defaulted move assignment operators. 9763 // We assume that any user-provided move assignment operator handles 9764 // the multiple-moves-of-vbase case itself somehow. 9765 if (!SMOR->getMethod()->isDefaulted()) 9766 continue; 9767 9768 // We're going to move the base classes of Base. Add them to the list. 9769 for (auto &BI : Base->bases()) 9770 Worklist.push_back(&BI); 9771 } 9772 } 9773 } 9774 } 9775 9776 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 9777 CXXMethodDecl *MoveAssignOperator) { 9778 assert((MoveAssignOperator->isDefaulted() && 9779 MoveAssignOperator->isOverloadedOperator() && 9780 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 9781 !MoveAssignOperator->doesThisDeclarationHaveABody() && 9782 !MoveAssignOperator->isDeleted()) && 9783 "DefineImplicitMoveAssignment called for wrong function"); 9784 9785 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 9786 9787 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) { 9788 MoveAssignOperator->setInvalidDecl(); 9789 return; 9790 } 9791 9792 MoveAssignOperator->markUsed(Context); 9793 9794 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 9795 DiagnosticErrorTrap Trap(Diags); 9796 9797 // C++0x [class.copy]p28: 9798 // The implicitly-defined or move assignment operator for a non-union class 9799 // X performs memberwise move assignment of its subobjects. The direct base 9800 // classes of X are assigned first, in the order of their declaration in the 9801 // base-specifier-list, and then the immediate non-static data members of X 9802 // are assigned, in the order in which they were declared in the class 9803 // definition. 9804 9805 // Issue a warning if our implicit move assignment operator will move 9806 // from a virtual base more than once. 9807 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 9808 9809 // The statements that form the synthesized function body. 9810 SmallVector<Stmt*, 8> Statements; 9811 9812 // The parameter for the "other" object, which we are move from. 9813 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 9814 QualType OtherRefType = Other->getType()-> 9815 getAs<RValueReferenceType>()->getPointeeType(); 9816 assert(!OtherRefType.getQualifiers() && 9817 "Bad argument type of defaulted move assignment"); 9818 9819 // Our location for everything implicitly-generated. 9820 SourceLocation Loc = MoveAssignOperator->getLocation(); 9821 9822 // Builds a reference to the "other" object. 9823 RefBuilder OtherRef(Other, OtherRefType); 9824 // Cast to rvalue. 9825 MoveCastBuilder MoveOther(OtherRef); 9826 9827 // Builds the "this" pointer. 9828 ThisBuilder This; 9829 9830 // Assign base classes. 9831 bool Invalid = false; 9832 for (auto &Base : ClassDecl->bases()) { 9833 // C++11 [class.copy]p28: 9834 // It is unspecified whether subobjects representing virtual base classes 9835 // are assigned more than once by the implicitly-defined copy assignment 9836 // operator. 9837 // FIXME: Do not assign to a vbase that will be assigned by some other base 9838 // class. For a move-assignment, this can result in the vbase being moved 9839 // multiple times. 9840 9841 // Form the assignment: 9842 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 9843 QualType BaseType = Base.getType().getUnqualifiedType(); 9844 if (!BaseType->isRecordType()) { 9845 Invalid = true; 9846 continue; 9847 } 9848 9849 CXXCastPath BasePath; 9850 BasePath.push_back(&Base); 9851 9852 // Construct the "from" expression, which is an implicit cast to the 9853 // appropriately-qualified base type. 9854 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 9855 9856 // Dereference "this". 9857 DerefBuilder DerefThis(This); 9858 9859 // Implicitly cast "this" to the appropriately-qualified base type. 9860 CastBuilder To(DerefThis, 9861 Context.getCVRQualifiedType( 9862 BaseType, MoveAssignOperator->getTypeQualifiers()), 9863 VK_LValue, BasePath); 9864 9865 // Build the move. 9866 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 9867 To, From, 9868 /*CopyingBaseSubobject=*/true, 9869 /*Copying=*/false); 9870 if (Move.isInvalid()) { 9871 Diag(CurrentLocation, diag::note_member_synthesized_at) 9872 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9873 MoveAssignOperator->setInvalidDecl(); 9874 return; 9875 } 9876 9877 // Success! Record the move. 9878 Statements.push_back(Move.takeAs<Expr>()); 9879 } 9880 9881 // Assign non-static members. 9882 for (auto *Field : ClassDecl->fields()) { 9883 if (Field->isUnnamedBitfield()) 9884 continue; 9885 9886 if (Field->isInvalidDecl()) { 9887 Invalid = true; 9888 continue; 9889 } 9890 9891 // Check for members of reference type; we can't move those. 9892 if (Field->getType()->isReferenceType()) { 9893 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9894 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 9895 Diag(Field->getLocation(), diag::note_declared_at); 9896 Diag(CurrentLocation, diag::note_member_synthesized_at) 9897 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9898 Invalid = true; 9899 continue; 9900 } 9901 9902 // Check for members of const-qualified, non-class type. 9903 QualType BaseType = Context.getBaseElementType(Field->getType()); 9904 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 9905 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 9906 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 9907 Diag(Field->getLocation(), diag::note_declared_at); 9908 Diag(CurrentLocation, diag::note_member_synthesized_at) 9909 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9910 Invalid = true; 9911 continue; 9912 } 9913 9914 // Suppress assigning zero-width bitfields. 9915 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0) 9916 continue; 9917 9918 QualType FieldType = Field->getType().getNonReferenceType(); 9919 if (FieldType->isIncompleteArrayType()) { 9920 assert(ClassDecl->hasFlexibleArrayMember() && 9921 "Incomplete array type is not valid"); 9922 continue; 9923 } 9924 9925 // Build references to the field in the object we're copying from and to. 9926 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 9927 LookupMemberName); 9928 MemberLookup.addDecl(Field); 9929 MemberLookup.resolveKind(); 9930 MemberBuilder From(MoveOther, OtherRefType, 9931 /*IsArrow=*/false, MemberLookup); 9932 MemberBuilder To(This, getCurrentThisType(), 9933 /*IsArrow=*/true, MemberLookup); 9934 9935 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 9936 "Member reference with rvalue base must be rvalue except for reference " 9937 "members, which aren't allowed for move assignment."); 9938 9939 // Build the move of this field. 9940 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 9941 To, From, 9942 /*CopyingBaseSubobject=*/false, 9943 /*Copying=*/false); 9944 if (Move.isInvalid()) { 9945 Diag(CurrentLocation, diag::note_member_synthesized_at) 9946 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9947 MoveAssignOperator->setInvalidDecl(); 9948 return; 9949 } 9950 9951 // Success! Record the copy. 9952 Statements.push_back(Move.takeAs<Stmt>()); 9953 } 9954 9955 if (!Invalid) { 9956 // Add a "return *this;" 9957 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 9958 9959 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 9960 if (Return.isInvalid()) 9961 Invalid = true; 9962 else { 9963 Statements.push_back(Return.takeAs<Stmt>()); 9964 9965 if (Trap.hasErrorOccurred()) { 9966 Diag(CurrentLocation, diag::note_member_synthesized_at) 9967 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl); 9968 Invalid = true; 9969 } 9970 } 9971 } 9972 9973 if (Invalid) { 9974 MoveAssignOperator->setInvalidDecl(); 9975 return; 9976 } 9977 9978 StmtResult Body; 9979 { 9980 CompoundScopeRAII CompoundScope(*this); 9981 Body = ActOnCompoundStmt(Loc, Loc, Statements, 9982 /*isStmtExpr=*/false); 9983 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 9984 } 9985 MoveAssignOperator->setBody(Body.takeAs<Stmt>()); 9986 9987 if (ASTMutationListener *L = getASTMutationListener()) { 9988 L->CompletedImplicitDefinition(MoveAssignOperator); 9989 } 9990 } 9991 9992 Sema::ImplicitExceptionSpecification 9993 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) { 9994 CXXRecordDecl *ClassDecl = MD->getParent(); 9995 9996 ImplicitExceptionSpecification ExceptSpec(*this); 9997 if (ClassDecl->isInvalidDecl()) 9998 return ExceptSpec; 9999 10000 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>(); 10001 assert(T->getNumParams() >= 1 && "not a copy ctor"); 10002 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers(); 10003 10004 // C++ [except.spec]p14: 10005 // An implicitly declared special member function (Clause 12) shall have an 10006 // exception-specification. [...] 10007 for (const auto &Base : ClassDecl->bases()) { 10008 // Virtual bases are handled below. 10009 if (Base.isVirtual()) 10010 continue; 10011 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 &Base : ClassDecl->vbases()) { 10019 CXXRecordDecl *BaseClassDecl 10020 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 10021 if (CXXConstructorDecl *CopyConstructor = 10022 LookupCopyingConstructor(BaseClassDecl, Quals)) 10023 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor); 10024 } 10025 for (const auto *Field : ClassDecl->fields()) { 10026 QualType FieldType = Context.getBaseElementType(Field->getType()); 10027 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) { 10028 if (CXXConstructorDecl *CopyConstructor = 10029 LookupCopyingConstructor(FieldClassDecl, 10030 Quals | FieldType.getCVRQualifiers())) 10031 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor); 10032 } 10033 } 10034 10035 return ExceptSpec; 10036 } 10037 10038 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 10039 CXXRecordDecl *ClassDecl) { 10040 // C++ [class.copy]p4: 10041 // If the class definition does not explicitly declare a copy 10042 // constructor, one is declared implicitly. 10043 assert(ClassDecl->needsImplicitCopyConstructor()); 10044 10045 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 10046 if (DSM.isAlreadyBeingDeclared()) 10047 return 0; 10048 10049 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10050 QualType ArgType = ClassType; 10051 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 10052 if (Const) 10053 ArgType = ArgType.withConst(); 10054 ArgType = Context.getLValueReferenceType(ArgType); 10055 10056 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10057 CXXCopyConstructor, 10058 Const); 10059 10060 DeclarationName Name 10061 = Context.DeclarationNames.getCXXConstructorName( 10062 Context.getCanonicalType(ClassType)); 10063 SourceLocation ClassLoc = ClassDecl->getLocation(); 10064 DeclarationNameInfo NameInfo(Name, ClassLoc); 10065 10066 // An implicitly-declared copy constructor is an inline public 10067 // member of its class. 10068 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 10069 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 10070 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10071 Constexpr); 10072 CopyConstructor->setAccess(AS_public); 10073 CopyConstructor->setDefaulted(); 10074 10075 // Build an exception specification pointing back at this member. 10076 FunctionProtoType::ExtProtoInfo EPI = 10077 getImplicitMethodEPI(*this, CopyConstructor); 10078 CopyConstructor->setType( 10079 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10080 10081 // Add the parameter to the constructor. 10082 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 10083 ClassLoc, ClassLoc, 10084 /*IdentifierInfo=*/0, 10085 ArgType, /*TInfo=*/0, 10086 SC_None, 0); 10087 CopyConstructor->setParams(FromParam); 10088 10089 CopyConstructor->setTrivial( 10090 ClassDecl->needsOverloadResolutionForCopyConstructor() 10091 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 10092 : ClassDecl->hasTrivialCopyConstructor()); 10093 10094 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) 10095 SetDeclDeleted(CopyConstructor, ClassLoc); 10096 10097 // Note that we have declared this constructor. 10098 ++ASTContext::NumImplicitCopyConstructorsDeclared; 10099 10100 if (Scope *S = getScopeForContext(ClassDecl)) 10101 PushOnScopeChains(CopyConstructor, S, false); 10102 ClassDecl->addDecl(CopyConstructor); 10103 10104 return CopyConstructor; 10105 } 10106 10107 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 10108 CXXConstructorDecl *CopyConstructor) { 10109 assert((CopyConstructor->isDefaulted() && 10110 CopyConstructor->isCopyConstructor() && 10111 !CopyConstructor->doesThisDeclarationHaveABody() && 10112 !CopyConstructor->isDeleted()) && 10113 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 10114 10115 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 10116 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 10117 10118 // C++11 [class.copy]p7: 10119 // The [definition of an implicitly declared copy constructor] is 10120 // deprecated if the class has a user-declared copy assignment operator 10121 // or a user-declared destructor. 10122 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 10123 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation); 10124 10125 SynthesizedFunctionScope Scope(*this, CopyConstructor); 10126 DiagnosticErrorTrap Trap(Diags); 10127 10128 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) || 10129 Trap.hasErrorOccurred()) { 10130 Diag(CurrentLocation, diag::note_member_synthesized_at) 10131 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 10132 CopyConstructor->setInvalidDecl(); 10133 } else { 10134 Sema::CompoundScopeRAII CompoundScope(*this); 10135 CopyConstructor->setBody(ActOnCompoundStmt( 10136 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None, 10137 /*isStmtExpr=*/ false).takeAs<Stmt>()); 10138 } 10139 10140 CopyConstructor->markUsed(Context); 10141 if (ASTMutationListener *L = getASTMutationListener()) { 10142 L->CompletedImplicitDefinition(CopyConstructor); 10143 } 10144 } 10145 10146 Sema::ImplicitExceptionSpecification 10147 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) { 10148 CXXRecordDecl *ClassDecl = MD->getParent(); 10149 10150 // C++ [except.spec]p14: 10151 // An implicitly declared special member function (Clause 12) shall have an 10152 // exception-specification. [...] 10153 ImplicitExceptionSpecification ExceptSpec(*this); 10154 if (ClassDecl->isInvalidDecl()) 10155 return ExceptSpec; 10156 10157 // Direct base-class constructors. 10158 for (const auto &B : ClassDecl->bases()) { 10159 if (B.isVirtual()) // Handled below. 10160 continue; 10161 10162 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10163 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10164 CXXConstructorDecl *Constructor = 10165 LookupMovingConstructor(BaseClassDecl, 0); 10166 // If this is a deleted function, add it anyway. This might be conformant 10167 // with the standard. This might not. I'm not sure. It might not matter. 10168 if (Constructor) 10169 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10170 } 10171 } 10172 10173 // Virtual base-class constructors. 10174 for (const auto &B : ClassDecl->vbases()) { 10175 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) { 10176 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 10177 CXXConstructorDecl *Constructor = 10178 LookupMovingConstructor(BaseClassDecl, 0); 10179 // If this is a deleted function, add it anyway. This might be conformant 10180 // with the standard. This might not. I'm not sure. It might not matter. 10181 if (Constructor) 10182 ExceptSpec.CalledDecl(B.getLocStart(), Constructor); 10183 } 10184 } 10185 10186 // Field constructors. 10187 for (const auto *F : ClassDecl->fields()) { 10188 QualType FieldType = Context.getBaseElementType(F->getType()); 10189 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) { 10190 CXXConstructorDecl *Constructor = 10191 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers()); 10192 // If this is a deleted function, add it anyway. This might be conformant 10193 // with the standard. This might not. I'm not sure. It might not matter. 10194 // In particular, the problem is that this function never gets called. It 10195 // might just be ill-formed because this function attempts to refer to 10196 // a deleted function here. 10197 if (Constructor) 10198 ExceptSpec.CalledDecl(F->getLocation(), Constructor); 10199 } 10200 } 10201 10202 return ExceptSpec; 10203 } 10204 10205 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 10206 CXXRecordDecl *ClassDecl) { 10207 assert(ClassDecl->needsImplicitMoveConstructor()); 10208 10209 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 10210 if (DSM.isAlreadyBeingDeclared()) 10211 return 0; 10212 10213 QualType ClassType = Context.getTypeDeclType(ClassDecl); 10214 QualType ArgType = Context.getRValueReferenceType(ClassType); 10215 10216 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 10217 CXXMoveConstructor, 10218 false); 10219 10220 DeclarationName Name 10221 = Context.DeclarationNames.getCXXConstructorName( 10222 Context.getCanonicalType(ClassType)); 10223 SourceLocation ClassLoc = ClassDecl->getLocation(); 10224 DeclarationNameInfo NameInfo(Name, ClassLoc); 10225 10226 // C++11 [class.copy]p11: 10227 // An implicitly-declared copy/move constructor is an inline public 10228 // member of its class. 10229 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 10230 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0, 10231 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true, 10232 Constexpr); 10233 MoveConstructor->setAccess(AS_public); 10234 MoveConstructor->setDefaulted(); 10235 10236 // Build an exception specification pointing back at this member. 10237 FunctionProtoType::ExtProtoInfo EPI = 10238 getImplicitMethodEPI(*this, MoveConstructor); 10239 MoveConstructor->setType( 10240 Context.getFunctionType(Context.VoidTy, ArgType, EPI)); 10241 10242 // Add the parameter to the constructor. 10243 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 10244 ClassLoc, ClassLoc, 10245 /*IdentifierInfo=*/0, 10246 ArgType, /*TInfo=*/0, 10247 SC_None, 0); 10248 MoveConstructor->setParams(FromParam); 10249 10250 MoveConstructor->setTrivial( 10251 ClassDecl->needsOverloadResolutionForMoveConstructor() 10252 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 10253 : ClassDecl->hasTrivialMoveConstructor()); 10254 10255 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 10256 ClassDecl->setImplicitMoveConstructorIsDeleted(); 10257 SetDeclDeleted(MoveConstructor, ClassLoc); 10258 } 10259 10260 // Note that we have declared this constructor. 10261 ++ASTContext::NumImplicitMoveConstructorsDeclared; 10262 10263 if (Scope *S = getScopeForContext(ClassDecl)) 10264 PushOnScopeChains(MoveConstructor, S, false); 10265 ClassDecl->addDecl(MoveConstructor); 10266 10267 return MoveConstructor; 10268 } 10269 10270 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 10271 CXXConstructorDecl *MoveConstructor) { 10272 assert((MoveConstructor->isDefaulted() && 10273 MoveConstructor->isMoveConstructor() && 10274 !MoveConstructor->doesThisDeclarationHaveABody() && 10275 !MoveConstructor->isDeleted()) && 10276 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 10277 10278 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 10279 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 10280 10281 SynthesizedFunctionScope Scope(*this, MoveConstructor); 10282 DiagnosticErrorTrap Trap(Diags); 10283 10284 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) || 10285 Trap.hasErrorOccurred()) { 10286 Diag(CurrentLocation, diag::note_member_synthesized_at) 10287 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl); 10288 MoveConstructor->setInvalidDecl(); 10289 } else { 10290 Sema::CompoundScopeRAII CompoundScope(*this); 10291 MoveConstructor->setBody(ActOnCompoundStmt( 10292 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None, 10293 /*isStmtExpr=*/ false).takeAs<Stmt>()); 10294 } 10295 10296 MoveConstructor->markUsed(Context); 10297 10298 if (ASTMutationListener *L = getASTMutationListener()) { 10299 L->CompletedImplicitDefinition(MoveConstructor); 10300 } 10301 } 10302 10303 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 10304 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 10305 } 10306 10307 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 10308 SourceLocation CurrentLocation, 10309 CXXConversionDecl *Conv) { 10310 CXXRecordDecl *Lambda = Conv->getParent(); 10311 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 10312 // If we are defining a specialization of a conversion to function-ptr 10313 // cache the deduced template arguments for this specialization 10314 // so that we can use them to retrieve the corresponding call-operator 10315 // and static-invoker. 10316 const TemplateArgumentList *DeducedTemplateArgs = 0; 10317 10318 10319 // Retrieve the corresponding call-operator specialization. 10320 if (Lambda->isGenericLambda()) { 10321 assert(Conv->isFunctionTemplateSpecialization()); 10322 FunctionTemplateDecl *CallOpTemplate = 10323 CallOp->getDescribedFunctionTemplate(); 10324 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs(); 10325 void *InsertPos = 0; 10326 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization( 10327 DeducedTemplateArgs->data(), 10328 DeducedTemplateArgs->size(), 10329 InsertPos); 10330 assert(CallOpSpec && 10331 "Conversion operator must have a corresponding call operator"); 10332 CallOp = cast<CXXMethodDecl>(CallOpSpec); 10333 } 10334 // Mark the call operator referenced (and add to pending instantiations 10335 // if necessary). 10336 // For both the conversion and static-invoker template specializations 10337 // we construct their body's in this function, so no need to add them 10338 // to the PendingInstantiations. 10339 MarkFunctionReferenced(CurrentLocation, CallOp); 10340 10341 SynthesizedFunctionScope Scope(*this, Conv); 10342 DiagnosticErrorTrap Trap(Diags); 10343 10344 // Retrieve the static invoker... 10345 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker(); 10346 // ... and get the corresponding specialization for a generic lambda. 10347 if (Lambda->isGenericLambda()) { 10348 assert(DeducedTemplateArgs && 10349 "Must have deduced template arguments from Conversion Operator"); 10350 FunctionTemplateDecl *InvokeTemplate = 10351 Invoker->getDescribedFunctionTemplate(); 10352 void *InsertPos = 0; 10353 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization( 10354 DeducedTemplateArgs->data(), 10355 DeducedTemplateArgs->size(), 10356 InsertPos); 10357 assert(InvokeSpec && 10358 "Must have a corresponding static invoker specialization"); 10359 Invoker = cast<CXXMethodDecl>(InvokeSpec); 10360 } 10361 // Construct the body of the conversion function { return __invoke; }. 10362 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 10363 VK_LValue, Conv->getLocation()).take(); 10364 assert(FunctionRef && "Can't refer to __invoke function?"); 10365 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take(); 10366 Conv->setBody(new (Context) CompoundStmt(Context, Return, 10367 Conv->getLocation(), 10368 Conv->getLocation())); 10369 10370 Conv->markUsed(Context); 10371 Conv->setReferenced(); 10372 10373 // Fill in the __invoke function with a dummy implementation. IR generation 10374 // will fill in the actual details. 10375 Invoker->markUsed(Context); 10376 Invoker->setReferenced(); 10377 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 10378 10379 if (ASTMutationListener *L = getASTMutationListener()) { 10380 L->CompletedImplicitDefinition(Conv); 10381 L->CompletedImplicitDefinition(Invoker); 10382 } 10383 } 10384 10385 10386 10387 void Sema::DefineImplicitLambdaToBlockPointerConversion( 10388 SourceLocation CurrentLocation, 10389 CXXConversionDecl *Conv) 10390 { 10391 assert(!Conv->getParent()->isGenericLambda()); 10392 10393 Conv->markUsed(Context); 10394 10395 SynthesizedFunctionScope Scope(*this, Conv); 10396 DiagnosticErrorTrap Trap(Diags); 10397 10398 // Copy-initialize the lambda object as needed to capture it. 10399 Expr *This = ActOnCXXThis(CurrentLocation).take(); 10400 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take(); 10401 10402 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 10403 Conv->getLocation(), 10404 Conv, DerefThis); 10405 10406 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 10407 // behavior. Note that only the general conversion function does this 10408 // (since it's unusable otherwise); in the case where we inline the 10409 // block literal, it has block literal lifetime semantics. 10410 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 10411 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 10412 CK_CopyAndAutoreleaseBlockObject, 10413 BuildBlock.get(), 0, VK_RValue); 10414 10415 if (BuildBlock.isInvalid()) { 10416 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10417 Conv->setInvalidDecl(); 10418 return; 10419 } 10420 10421 // Create the return statement that returns the block from the conversion 10422 // function. 10423 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get()); 10424 if (Return.isInvalid()) { 10425 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 10426 Conv->setInvalidDecl(); 10427 return; 10428 } 10429 10430 // Set the body of the conversion function. 10431 Stmt *ReturnS = Return.take(); 10432 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS, 10433 Conv->getLocation(), 10434 Conv->getLocation())); 10435 10436 // We're done; notify the mutation listener, if any. 10437 if (ASTMutationListener *L = getASTMutationListener()) { 10438 L->CompletedImplicitDefinition(Conv); 10439 } 10440 } 10441 10442 /// \brief Determine whether the given list arguments contains exactly one 10443 /// "real" (non-default) argument. 10444 static bool hasOneRealArgument(MultiExprArg Args) { 10445 switch (Args.size()) { 10446 case 0: 10447 return false; 10448 10449 default: 10450 if (!Args[1]->isDefaultArgument()) 10451 return false; 10452 10453 // fall through 10454 case 1: 10455 return !Args[0]->isDefaultArgument(); 10456 } 10457 10458 return false; 10459 } 10460 10461 ExprResult 10462 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10463 CXXConstructorDecl *Constructor, 10464 MultiExprArg ExprArgs, 10465 bool HadMultipleCandidates, 10466 bool IsListInitialization, 10467 bool RequiresZeroInit, 10468 unsigned ConstructKind, 10469 SourceRange ParenRange) { 10470 bool Elidable = false; 10471 10472 // C++0x [class.copy]p34: 10473 // When certain criteria are met, an implementation is allowed to 10474 // omit the copy/move construction of a class object, even if the 10475 // copy/move constructor and/or destructor for the object have 10476 // side effects. [...] 10477 // - when a temporary class object that has not been bound to a 10478 // reference (12.2) would be copied/moved to a class object 10479 // with the same cv-unqualified type, the copy/move operation 10480 // can be omitted by constructing the temporary object 10481 // directly into the target of the omitted copy/move 10482 if (ConstructKind == CXXConstructExpr::CK_Complete && 10483 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 10484 Expr *SubExpr = ExprArgs[0]; 10485 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 10486 } 10487 10488 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 10489 Elidable, ExprArgs, HadMultipleCandidates, 10490 IsListInitialization, RequiresZeroInit, 10491 ConstructKind, ParenRange); 10492 } 10493 10494 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 10495 /// including handling of its default argument expressions. 10496 ExprResult 10497 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 10498 CXXConstructorDecl *Constructor, bool Elidable, 10499 MultiExprArg ExprArgs, 10500 bool HadMultipleCandidates, 10501 bool IsListInitialization, 10502 bool RequiresZeroInit, 10503 unsigned ConstructKind, 10504 SourceRange ParenRange) { 10505 MarkFunctionReferenced(ConstructLoc, Constructor); 10506 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 10507 Constructor, Elidable, ExprArgs, 10508 HadMultipleCandidates, 10509 IsListInitialization, RequiresZeroInit, 10510 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 10511 ParenRange)); 10512 } 10513 10514 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 10515 if (VD->isInvalidDecl()) return; 10516 10517 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 10518 if (ClassDecl->isInvalidDecl()) return; 10519 if (ClassDecl->hasIrrelevantDestructor()) return; 10520 if (ClassDecl->isDependentContext()) return; 10521 10522 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 10523 MarkFunctionReferenced(VD->getLocation(), Destructor); 10524 CheckDestructorAccess(VD->getLocation(), Destructor, 10525 PDiag(diag::err_access_dtor_var) 10526 << VD->getDeclName() 10527 << VD->getType()); 10528 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 10529 10530 if (Destructor->isTrivial()) return; 10531 if (!VD->hasGlobalStorage()) return; 10532 10533 // Emit warning for non-trivial dtor in global scope (a real global, 10534 // class-static, function-static). 10535 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 10536 10537 // TODO: this should be re-enabled for static locals by !CXAAtExit 10538 if (!VD->isStaticLocal()) 10539 Diag(VD->getLocation(), diag::warn_global_destructor); 10540 } 10541 10542 /// \brief Given a constructor and the set of arguments provided for the 10543 /// constructor, convert the arguments and add any required default arguments 10544 /// to form a proper call to this constructor. 10545 /// 10546 /// \returns true if an error occurred, false otherwise. 10547 bool 10548 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 10549 MultiExprArg ArgsPtr, 10550 SourceLocation Loc, 10551 SmallVectorImpl<Expr*> &ConvertedArgs, 10552 bool AllowExplicit, 10553 bool IsListInitialization) { 10554 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 10555 unsigned NumArgs = ArgsPtr.size(); 10556 Expr **Args = ArgsPtr.data(); 10557 10558 const FunctionProtoType *Proto 10559 = Constructor->getType()->getAs<FunctionProtoType>(); 10560 assert(Proto && "Constructor without a prototype?"); 10561 unsigned NumParams = Proto->getNumParams(); 10562 10563 // If too few arguments are available, we'll fill in the rest with defaults. 10564 if (NumArgs < NumParams) 10565 ConvertedArgs.reserve(NumParams); 10566 else 10567 ConvertedArgs.reserve(NumArgs); 10568 10569 VariadicCallType CallType = 10570 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 10571 SmallVector<Expr *, 8> AllArgs; 10572 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 10573 Proto, 0, 10574 llvm::makeArrayRef(Args, NumArgs), 10575 AllArgs, 10576 CallType, AllowExplicit, 10577 IsListInitialization); 10578 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 10579 10580 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 10581 10582 CheckConstructorCall(Constructor, 10583 llvm::makeArrayRef<const Expr *>(AllArgs.data(), 10584 AllArgs.size()), 10585 Proto, Loc); 10586 10587 return Invalid; 10588 } 10589 10590 static inline bool 10591 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 10592 const FunctionDecl *FnDecl) { 10593 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 10594 if (isa<NamespaceDecl>(DC)) { 10595 return SemaRef.Diag(FnDecl->getLocation(), 10596 diag::err_operator_new_delete_declared_in_namespace) 10597 << FnDecl->getDeclName(); 10598 } 10599 10600 if (isa<TranslationUnitDecl>(DC) && 10601 FnDecl->getStorageClass() == SC_Static) { 10602 return SemaRef.Diag(FnDecl->getLocation(), 10603 diag::err_operator_new_delete_declared_static) 10604 << FnDecl->getDeclName(); 10605 } 10606 10607 return false; 10608 } 10609 10610 static inline bool 10611 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 10612 CanQualType ExpectedResultType, 10613 CanQualType ExpectedFirstParamType, 10614 unsigned DependentParamTypeDiag, 10615 unsigned InvalidParamTypeDiag) { 10616 QualType ResultType = 10617 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 10618 10619 // Check that the result type is not dependent. 10620 if (ResultType->isDependentType()) 10621 return SemaRef.Diag(FnDecl->getLocation(), 10622 diag::err_operator_new_delete_dependent_result_type) 10623 << FnDecl->getDeclName() << ExpectedResultType; 10624 10625 // Check that the result type is what we expect. 10626 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 10627 return SemaRef.Diag(FnDecl->getLocation(), 10628 diag::err_operator_new_delete_invalid_result_type) 10629 << FnDecl->getDeclName() << ExpectedResultType; 10630 10631 // A function template must have at least 2 parameters. 10632 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 10633 return SemaRef.Diag(FnDecl->getLocation(), 10634 diag::err_operator_new_delete_template_too_few_parameters) 10635 << FnDecl->getDeclName(); 10636 10637 // The function decl must have at least 1 parameter. 10638 if (FnDecl->getNumParams() == 0) 10639 return SemaRef.Diag(FnDecl->getLocation(), 10640 diag::err_operator_new_delete_too_few_parameters) 10641 << FnDecl->getDeclName(); 10642 10643 // Check the first parameter type is not dependent. 10644 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 10645 if (FirstParamType->isDependentType()) 10646 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 10647 << FnDecl->getDeclName() << ExpectedFirstParamType; 10648 10649 // Check that the first parameter type is what we expect. 10650 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 10651 ExpectedFirstParamType) 10652 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 10653 << FnDecl->getDeclName() << ExpectedFirstParamType; 10654 10655 return false; 10656 } 10657 10658 static bool 10659 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 10660 // C++ [basic.stc.dynamic.allocation]p1: 10661 // A program is ill-formed if an allocation function is declared in a 10662 // namespace scope other than global scope or declared static in global 10663 // scope. 10664 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10665 return true; 10666 10667 CanQualType SizeTy = 10668 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 10669 10670 // C++ [basic.stc.dynamic.allocation]p1: 10671 // The return type shall be void*. The first parameter shall have type 10672 // std::size_t. 10673 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 10674 SizeTy, 10675 diag::err_operator_new_dependent_param_type, 10676 diag::err_operator_new_param_type)) 10677 return true; 10678 10679 // C++ [basic.stc.dynamic.allocation]p1: 10680 // The first parameter shall not have an associated default argument. 10681 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 10682 return SemaRef.Diag(FnDecl->getLocation(), 10683 diag::err_operator_new_default_arg) 10684 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 10685 10686 return false; 10687 } 10688 10689 static bool 10690 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 10691 // C++ [basic.stc.dynamic.deallocation]p1: 10692 // A program is ill-formed if deallocation functions are declared in a 10693 // namespace scope other than global scope or declared static in global 10694 // scope. 10695 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 10696 return true; 10697 10698 // C++ [basic.stc.dynamic.deallocation]p2: 10699 // Each deallocation function shall return void and its first parameter 10700 // shall be void*. 10701 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 10702 SemaRef.Context.VoidPtrTy, 10703 diag::err_operator_delete_dependent_param_type, 10704 diag::err_operator_delete_param_type)) 10705 return true; 10706 10707 return false; 10708 } 10709 10710 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 10711 /// of this overloaded operator is well-formed. If so, returns false; 10712 /// otherwise, emits appropriate diagnostics and returns true. 10713 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 10714 assert(FnDecl && FnDecl->isOverloadedOperator() && 10715 "Expected an overloaded operator declaration"); 10716 10717 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 10718 10719 // C++ [over.oper]p5: 10720 // The allocation and deallocation functions, operator new, 10721 // operator new[], operator delete and operator delete[], are 10722 // described completely in 3.7.3. The attributes and restrictions 10723 // found in the rest of this subclause do not apply to them unless 10724 // explicitly stated in 3.7.3. 10725 if (Op == OO_Delete || Op == OO_Array_Delete) 10726 return CheckOperatorDeleteDeclaration(*this, FnDecl); 10727 10728 if (Op == OO_New || Op == OO_Array_New) 10729 return CheckOperatorNewDeclaration(*this, FnDecl); 10730 10731 // C++ [over.oper]p6: 10732 // An operator function shall either be a non-static member 10733 // function or be a non-member function and have at least one 10734 // parameter whose type is a class, a reference to a class, an 10735 // enumeration, or a reference to an enumeration. 10736 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 10737 if (MethodDecl->isStatic()) 10738 return Diag(FnDecl->getLocation(), 10739 diag::err_operator_overload_static) << FnDecl->getDeclName(); 10740 } else { 10741 bool ClassOrEnumParam = false; 10742 for (auto Param : FnDecl->params()) { 10743 QualType ParamType = Param->getType().getNonReferenceType(); 10744 if (ParamType->isDependentType() || ParamType->isRecordType() || 10745 ParamType->isEnumeralType()) { 10746 ClassOrEnumParam = true; 10747 break; 10748 } 10749 } 10750 10751 if (!ClassOrEnumParam) 10752 return Diag(FnDecl->getLocation(), 10753 diag::err_operator_overload_needs_class_or_enum) 10754 << FnDecl->getDeclName(); 10755 } 10756 10757 // C++ [over.oper]p8: 10758 // An operator function cannot have default arguments (8.3.6), 10759 // except where explicitly stated below. 10760 // 10761 // Only the function-call operator allows default arguments 10762 // (C++ [over.call]p1). 10763 if (Op != OO_Call) { 10764 for (auto Param : FnDecl->params()) { 10765 if (Param->hasDefaultArg()) 10766 return Diag(Param->getLocation(), 10767 diag::err_operator_overload_default_arg) 10768 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 10769 } 10770 } 10771 10772 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 10773 { false, false, false } 10774 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 10775 , { Unary, Binary, MemberOnly } 10776 #include "clang/Basic/OperatorKinds.def" 10777 }; 10778 10779 bool CanBeUnaryOperator = OperatorUses[Op][0]; 10780 bool CanBeBinaryOperator = OperatorUses[Op][1]; 10781 bool MustBeMemberOperator = OperatorUses[Op][2]; 10782 10783 // C++ [over.oper]p8: 10784 // [...] Operator functions cannot have more or fewer parameters 10785 // than the number required for the corresponding operator, as 10786 // described in the rest of this subclause. 10787 unsigned NumParams = FnDecl->getNumParams() 10788 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 10789 if (Op != OO_Call && 10790 ((NumParams == 1 && !CanBeUnaryOperator) || 10791 (NumParams == 2 && !CanBeBinaryOperator) || 10792 (NumParams < 1) || (NumParams > 2))) { 10793 // We have the wrong number of parameters. 10794 unsigned ErrorKind; 10795 if (CanBeUnaryOperator && CanBeBinaryOperator) { 10796 ErrorKind = 2; // 2 -> unary or binary. 10797 } else if (CanBeUnaryOperator) { 10798 ErrorKind = 0; // 0 -> unary 10799 } else { 10800 assert(CanBeBinaryOperator && 10801 "All non-call overloaded operators are unary or binary!"); 10802 ErrorKind = 1; // 1 -> binary 10803 } 10804 10805 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 10806 << FnDecl->getDeclName() << NumParams << ErrorKind; 10807 } 10808 10809 // Overloaded operators other than operator() cannot be variadic. 10810 if (Op != OO_Call && 10811 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 10812 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 10813 << FnDecl->getDeclName(); 10814 } 10815 10816 // Some operators must be non-static member functions. 10817 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 10818 return Diag(FnDecl->getLocation(), 10819 diag::err_operator_overload_must_be_member) 10820 << FnDecl->getDeclName(); 10821 } 10822 10823 // C++ [over.inc]p1: 10824 // The user-defined function called operator++ implements the 10825 // prefix and postfix ++ operator. If this function is a member 10826 // function with no parameters, or a non-member function with one 10827 // parameter of class or enumeration type, it defines the prefix 10828 // increment operator ++ for objects of that type. If the function 10829 // is a member function with one parameter (which shall be of type 10830 // int) or a non-member function with two parameters (the second 10831 // of which shall be of type int), it defines the postfix 10832 // increment operator ++ for objects of that type. 10833 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 10834 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 10835 QualType ParamType = LastParam->getType(); 10836 10837 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 10838 !ParamType->isDependentType()) 10839 return Diag(LastParam->getLocation(), 10840 diag::err_operator_overload_post_incdec_must_be_int) 10841 << LastParam->getType() << (Op == OO_MinusMinus); 10842 } 10843 10844 return false; 10845 } 10846 10847 /// CheckLiteralOperatorDeclaration - Check whether the declaration 10848 /// of this literal operator function is well-formed. If so, returns 10849 /// false; otherwise, emits appropriate diagnostics and returns true. 10850 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 10851 if (isa<CXXMethodDecl>(FnDecl)) { 10852 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 10853 << FnDecl->getDeclName(); 10854 return true; 10855 } 10856 10857 if (FnDecl->isExternC()) { 10858 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 10859 return true; 10860 } 10861 10862 bool Valid = false; 10863 10864 // This might be the definition of a literal operator template. 10865 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 10866 // This might be a specialization of a literal operator template. 10867 if (!TpDecl) 10868 TpDecl = FnDecl->getPrimaryTemplate(); 10869 10870 // template <char...> type operator "" name() and 10871 // template <class T, T...> type operator "" name() are the only valid 10872 // template signatures, and the only valid signatures with no parameters. 10873 if (TpDecl) { 10874 if (FnDecl->param_size() == 0) { 10875 // Must have one or two template parameters 10876 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 10877 if (Params->size() == 1) { 10878 NonTypeTemplateParmDecl *PmDecl = 10879 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 10880 10881 // The template parameter must be a char parameter pack. 10882 if (PmDecl && PmDecl->isTemplateParameterPack() && 10883 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 10884 Valid = true; 10885 } else if (Params->size() == 2) { 10886 TemplateTypeParmDecl *PmType = 10887 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0)); 10888 NonTypeTemplateParmDecl *PmArgs = 10889 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 10890 10891 // The second template parameter must be a parameter pack with the 10892 // first template parameter as its type. 10893 if (PmType && PmArgs && 10894 !PmType->isTemplateParameterPack() && 10895 PmArgs->isTemplateParameterPack()) { 10896 const TemplateTypeParmType *TArgs = 10897 PmArgs->getType()->getAs<TemplateTypeParmType>(); 10898 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 10899 TArgs->getIndex() == PmType->getIndex()) { 10900 Valid = true; 10901 if (ActiveTemplateInstantiations.empty()) 10902 Diag(FnDecl->getLocation(), 10903 diag::ext_string_literal_operator_template); 10904 } 10905 } 10906 } 10907 } 10908 } else if (FnDecl->param_size()) { 10909 // Check the first parameter 10910 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 10911 10912 QualType T = (*Param)->getType().getUnqualifiedType(); 10913 10914 // unsigned long long int, long double, and any character type are allowed 10915 // as the only parameters. 10916 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 10917 Context.hasSameType(T, Context.LongDoubleTy) || 10918 Context.hasSameType(T, Context.CharTy) || 10919 Context.hasSameType(T, Context.WideCharTy) || 10920 Context.hasSameType(T, Context.Char16Ty) || 10921 Context.hasSameType(T, Context.Char32Ty)) { 10922 if (++Param == FnDecl->param_end()) 10923 Valid = true; 10924 goto FinishedParams; 10925 } 10926 10927 // Otherwise it must be a pointer to const; let's strip those qualifiers. 10928 const PointerType *PT = T->getAs<PointerType>(); 10929 if (!PT) 10930 goto FinishedParams; 10931 T = PT->getPointeeType(); 10932 if (!T.isConstQualified() || T.isVolatileQualified()) 10933 goto FinishedParams; 10934 T = T.getUnqualifiedType(); 10935 10936 // Move on to the second parameter; 10937 ++Param; 10938 10939 // If there is no second parameter, the first must be a const char * 10940 if (Param == FnDecl->param_end()) { 10941 if (Context.hasSameType(T, Context.CharTy)) 10942 Valid = true; 10943 goto FinishedParams; 10944 } 10945 10946 // const char *, const wchar_t*, const char16_t*, and const char32_t* 10947 // are allowed as the first parameter to a two-parameter function 10948 if (!(Context.hasSameType(T, Context.CharTy) || 10949 Context.hasSameType(T, Context.WideCharTy) || 10950 Context.hasSameType(T, Context.Char16Ty) || 10951 Context.hasSameType(T, Context.Char32Ty))) 10952 goto FinishedParams; 10953 10954 // The second and final parameter must be an std::size_t 10955 T = (*Param)->getType().getUnqualifiedType(); 10956 if (Context.hasSameType(T, Context.getSizeType()) && 10957 ++Param == FnDecl->param_end()) 10958 Valid = true; 10959 } 10960 10961 // FIXME: This diagnostic is absolutely terrible. 10962 FinishedParams: 10963 if (!Valid) { 10964 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 10965 << FnDecl->getDeclName(); 10966 return true; 10967 } 10968 10969 // A parameter-declaration-clause containing a default argument is not 10970 // equivalent to any of the permitted forms. 10971 for (auto Param : FnDecl->params()) { 10972 if (Param->hasDefaultArg()) { 10973 Diag(Param->getDefaultArgRange().getBegin(), 10974 diag::err_literal_operator_default_argument) 10975 << Param->getDefaultArgRange(); 10976 break; 10977 } 10978 } 10979 10980 StringRef LiteralName 10981 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 10982 if (LiteralName[0] != '_') { 10983 // C++11 [usrlit.suffix]p1: 10984 // Literal suffix identifiers that do not start with an underscore 10985 // are reserved for future standardization. 10986 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 10987 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 10988 } 10989 10990 return false; 10991 } 10992 10993 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 10994 /// linkage specification, including the language and (if present) 10995 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 10996 /// language string literal. LBraceLoc, if valid, provides the location of 10997 /// the '{' brace. Otherwise, this linkage specification does not 10998 /// have any braces. 10999 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 11000 Expr *LangStr, 11001 SourceLocation LBraceLoc) { 11002 StringLiteral *Lit = cast<StringLiteral>(LangStr); 11003 if (!Lit->isAscii()) { 11004 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 11005 << LangStr->getSourceRange(); 11006 return 0; 11007 } 11008 11009 StringRef Lang = Lit->getString(); 11010 LinkageSpecDecl::LanguageIDs Language; 11011 if (Lang == "C") 11012 Language = LinkageSpecDecl::lang_c; 11013 else if (Lang == "C++") 11014 Language = LinkageSpecDecl::lang_cxx; 11015 else { 11016 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 11017 << LangStr->getSourceRange(); 11018 return 0; 11019 } 11020 11021 // FIXME: Add all the various semantics of linkage specifications 11022 11023 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 11024 LangStr->getExprLoc(), Language, 11025 LBraceLoc.isValid()); 11026 CurContext->addDecl(D); 11027 PushDeclContext(S, D); 11028 return D; 11029 } 11030 11031 /// ActOnFinishLinkageSpecification - Complete the definition of 11032 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 11033 /// valid, it's the position of the closing '}' brace in a linkage 11034 /// specification that uses braces. 11035 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 11036 Decl *LinkageSpec, 11037 SourceLocation RBraceLoc) { 11038 if (RBraceLoc.isValid()) { 11039 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 11040 LSDecl->setRBraceLoc(RBraceLoc); 11041 } 11042 PopDeclContext(); 11043 return LinkageSpec; 11044 } 11045 11046 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 11047 AttributeList *AttrList, 11048 SourceLocation SemiLoc) { 11049 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 11050 // Attribute declarations appertain to empty declaration so we handle 11051 // them here. 11052 if (AttrList) 11053 ProcessDeclAttributeList(S, ED, AttrList); 11054 11055 CurContext->addDecl(ED); 11056 return ED; 11057 } 11058 11059 /// \brief Perform semantic analysis for the variable declaration that 11060 /// occurs within a C++ catch clause, returning the newly-created 11061 /// variable. 11062 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 11063 TypeSourceInfo *TInfo, 11064 SourceLocation StartLoc, 11065 SourceLocation Loc, 11066 IdentifierInfo *Name) { 11067 bool Invalid = false; 11068 QualType ExDeclType = TInfo->getType(); 11069 11070 // Arrays and functions decay. 11071 if (ExDeclType->isArrayType()) 11072 ExDeclType = Context.getArrayDecayedType(ExDeclType); 11073 else if (ExDeclType->isFunctionType()) 11074 ExDeclType = Context.getPointerType(ExDeclType); 11075 11076 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 11077 // The exception-declaration shall not denote a pointer or reference to an 11078 // incomplete type, other than [cv] void*. 11079 // N2844 forbids rvalue references. 11080 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 11081 Diag(Loc, diag::err_catch_rvalue_ref); 11082 Invalid = true; 11083 } 11084 11085 QualType BaseType = ExDeclType; 11086 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 11087 unsigned DK = diag::err_catch_incomplete; 11088 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 11089 BaseType = Ptr->getPointeeType(); 11090 Mode = 1; 11091 DK = diag::err_catch_incomplete_ptr; 11092 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 11093 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 11094 BaseType = Ref->getPointeeType(); 11095 Mode = 2; 11096 DK = diag::err_catch_incomplete_ref; 11097 } 11098 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 11099 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 11100 Invalid = true; 11101 11102 if (!Invalid && !ExDeclType->isDependentType() && 11103 RequireNonAbstractType(Loc, ExDeclType, 11104 diag::err_abstract_type_in_decl, 11105 AbstractVariableType)) 11106 Invalid = true; 11107 11108 // Only the non-fragile NeXT runtime currently supports C++ catches 11109 // of ObjC types, and no runtime supports catching ObjC types by value. 11110 if (!Invalid && getLangOpts().ObjC1) { 11111 QualType T = ExDeclType; 11112 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 11113 T = RT->getPointeeType(); 11114 11115 if (T->isObjCObjectType()) { 11116 Diag(Loc, diag::err_objc_object_catch); 11117 Invalid = true; 11118 } else if (T->isObjCObjectPointerType()) { 11119 // FIXME: should this be a test for macosx-fragile specifically? 11120 if (getLangOpts().ObjCRuntime.isFragile()) 11121 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 11122 } 11123 } 11124 11125 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 11126 ExDeclType, TInfo, SC_None); 11127 ExDecl->setExceptionVariable(true); 11128 11129 // In ARC, infer 'retaining' for variables of retainable type. 11130 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 11131 Invalid = true; 11132 11133 if (!Invalid && !ExDeclType->isDependentType()) { 11134 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 11135 // Insulate this from anything else we might currently be parsing. 11136 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 11137 11138 // C++ [except.handle]p16: 11139 // The object declared in an exception-declaration or, if the 11140 // exception-declaration does not specify a name, a temporary (12.2) is 11141 // copy-initialized (8.5) from the exception object. [...] 11142 // The object is destroyed when the handler exits, after the destruction 11143 // of any automatic objects initialized within the handler. 11144 // 11145 // We just pretend to initialize the object with itself, then make sure 11146 // it can be destroyed later. 11147 QualType initType = ExDeclType; 11148 11149 InitializedEntity entity = 11150 InitializedEntity::InitializeVariable(ExDecl); 11151 InitializationKind initKind = 11152 InitializationKind::CreateCopy(Loc, SourceLocation()); 11153 11154 Expr *opaqueValue = 11155 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 11156 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 11157 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 11158 if (result.isInvalid()) 11159 Invalid = true; 11160 else { 11161 // If the constructor used was non-trivial, set this as the 11162 // "initializer". 11163 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>(); 11164 if (!construct->getConstructor()->isTrivial()) { 11165 Expr *init = MaybeCreateExprWithCleanups(construct); 11166 ExDecl->setInit(init); 11167 } 11168 11169 // And make sure it's destructable. 11170 FinalizeVarWithDestructor(ExDecl, recordType); 11171 } 11172 } 11173 } 11174 11175 if (Invalid) 11176 ExDecl->setInvalidDecl(); 11177 11178 return ExDecl; 11179 } 11180 11181 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 11182 /// handler. 11183 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 11184 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11185 bool Invalid = D.isInvalidType(); 11186 11187 // Check for unexpanded parameter packs. 11188 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 11189 UPPC_ExceptionType)) { 11190 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11191 D.getIdentifierLoc()); 11192 Invalid = true; 11193 } 11194 11195 IdentifierInfo *II = D.getIdentifier(); 11196 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 11197 LookupOrdinaryName, 11198 ForRedeclaration)) { 11199 // The scope should be freshly made just for us. There is just no way 11200 // it contains any previous declaration. 11201 assert(!S->isDeclScope(PrevDecl)); 11202 if (PrevDecl->isTemplateParameter()) { 11203 // Maybe we will complain about the shadowed template parameter. 11204 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11205 PrevDecl = 0; 11206 } 11207 } 11208 11209 if (D.getCXXScopeSpec().isSet() && !Invalid) { 11210 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 11211 << D.getCXXScopeSpec().getRange(); 11212 Invalid = true; 11213 } 11214 11215 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 11216 D.getLocStart(), 11217 D.getIdentifierLoc(), 11218 D.getIdentifier()); 11219 if (Invalid) 11220 ExDecl->setInvalidDecl(); 11221 11222 // Add the exception declaration into this scope. 11223 if (II) 11224 PushOnScopeChains(ExDecl, S); 11225 else 11226 CurContext->addDecl(ExDecl); 11227 11228 ProcessDeclAttributes(S, ExDecl, D); 11229 return ExDecl; 11230 } 11231 11232 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11233 Expr *AssertExpr, 11234 Expr *AssertMessageExpr, 11235 SourceLocation RParenLoc) { 11236 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr); 11237 11238 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 11239 return 0; 11240 11241 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 11242 AssertMessage, RParenLoc, false); 11243 } 11244 11245 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 11246 Expr *AssertExpr, 11247 StringLiteral *AssertMessage, 11248 SourceLocation RParenLoc, 11249 bool Failed) { 11250 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 11251 !Failed) { 11252 // In a static_assert-declaration, the constant-expression shall be a 11253 // constant expression that can be contextually converted to bool. 11254 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 11255 if (Converted.isInvalid()) 11256 Failed = true; 11257 11258 llvm::APSInt Cond; 11259 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond, 11260 diag::err_static_assert_expression_is_not_constant, 11261 /*AllowFold=*/false).isInvalid()) 11262 Failed = true; 11263 11264 if (!Failed && !Cond) { 11265 SmallString<256> MsgBuffer; 11266 llvm::raw_svector_ostream Msg(MsgBuffer); 11267 AssertMessage->printPretty(Msg, 0, getPrintingPolicy()); 11268 Diag(StaticAssertLoc, diag::err_static_assert_failed) 11269 << Msg.str() << AssertExpr->getSourceRange(); 11270 Failed = true; 11271 } 11272 } 11273 11274 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 11275 AssertExpr, AssertMessage, RParenLoc, 11276 Failed); 11277 11278 CurContext->addDecl(Decl); 11279 return Decl; 11280 } 11281 11282 /// \brief Perform semantic analysis of the given friend type declaration. 11283 /// 11284 /// \returns A friend declaration that. 11285 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 11286 SourceLocation FriendLoc, 11287 TypeSourceInfo *TSInfo) { 11288 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 11289 11290 QualType T = TSInfo->getType(); 11291 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 11292 11293 // C++03 [class.friend]p2: 11294 // An elaborated-type-specifier shall be used in a friend declaration 11295 // for a class.* 11296 // 11297 // * The class-key of the elaborated-type-specifier is required. 11298 if (!ActiveTemplateInstantiations.empty()) { 11299 // Do not complain about the form of friend template types during 11300 // template instantiation; we will already have complained when the 11301 // template was declared. 11302 } else { 11303 if (!T->isElaboratedTypeSpecifier()) { 11304 // If we evaluated the type to a record type, suggest putting 11305 // a tag in front. 11306 if (const RecordType *RT = T->getAs<RecordType>()) { 11307 RecordDecl *RD = RT->getDecl(); 11308 11309 std::string InsertionText = std::string(" ") + RD->getKindName(); 11310 11311 Diag(TypeRange.getBegin(), 11312 getLangOpts().CPlusPlus11 ? 11313 diag::warn_cxx98_compat_unelaborated_friend_type : 11314 diag::ext_unelaborated_friend_type) 11315 << (unsigned) RD->getTagKind() 11316 << T 11317 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 11318 InsertionText); 11319 } else { 11320 Diag(FriendLoc, 11321 getLangOpts().CPlusPlus11 ? 11322 diag::warn_cxx98_compat_nonclass_type_friend : 11323 diag::ext_nonclass_type_friend) 11324 << T 11325 << TypeRange; 11326 } 11327 } else if (T->getAs<EnumType>()) { 11328 Diag(FriendLoc, 11329 getLangOpts().CPlusPlus11 ? 11330 diag::warn_cxx98_compat_enum_friend : 11331 diag::ext_enum_friend) 11332 << T 11333 << TypeRange; 11334 } 11335 11336 // C++11 [class.friend]p3: 11337 // A friend declaration that does not declare a function shall have one 11338 // of the following forms: 11339 // friend elaborated-type-specifier ; 11340 // friend simple-type-specifier ; 11341 // friend typename-specifier ; 11342 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 11343 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 11344 } 11345 11346 // If the type specifier in a friend declaration designates a (possibly 11347 // cv-qualified) class type, that class is declared as a friend; otherwise, 11348 // the friend declaration is ignored. 11349 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc); 11350 } 11351 11352 /// Handle a friend tag declaration where the scope specifier was 11353 /// templated. 11354 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 11355 unsigned TagSpec, SourceLocation TagLoc, 11356 CXXScopeSpec &SS, 11357 IdentifierInfo *Name, 11358 SourceLocation NameLoc, 11359 AttributeList *Attr, 11360 MultiTemplateParamsArg TempParamLists) { 11361 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11362 11363 bool isExplicitSpecialization = false; 11364 bool Invalid = false; 11365 11366 if (TemplateParameterList *TemplateParams = 11367 MatchTemplateParametersToScopeSpecifier( 11368 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true, 11369 isExplicitSpecialization, Invalid)) { 11370 if (TemplateParams->size() > 0) { 11371 // This is a declaration of a class template. 11372 if (Invalid) 11373 return 0; 11374 11375 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 11376 SS, Name, NameLoc, Attr, 11377 TemplateParams, AS_public, 11378 /*ModulePrivateLoc=*/SourceLocation(), 11379 TempParamLists.size() - 1, 11380 TempParamLists.data()).take(); 11381 } else { 11382 // The "template<>" header is extraneous. 11383 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11384 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11385 isExplicitSpecialization = true; 11386 } 11387 } 11388 11389 if (Invalid) return 0; 11390 11391 bool isAllExplicitSpecializations = true; 11392 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 11393 if (TempParamLists[I]->size()) { 11394 isAllExplicitSpecializations = false; 11395 break; 11396 } 11397 } 11398 11399 // FIXME: don't ignore attributes. 11400 11401 // If it's explicit specializations all the way down, just forget 11402 // about the template header and build an appropriate non-templated 11403 // friend. TODO: for source fidelity, remember the headers. 11404 if (isAllExplicitSpecializations) { 11405 if (SS.isEmpty()) { 11406 bool Owned = false; 11407 bool IsDependent = false; 11408 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 11409 Attr, AS_public, 11410 /*ModulePrivateLoc=*/SourceLocation(), 11411 MultiTemplateParamsArg(), Owned, IsDependent, 11412 /*ScopedEnumKWLoc=*/SourceLocation(), 11413 /*ScopedEnumUsesClassTag=*/false, 11414 /*UnderlyingType=*/TypeResult(), 11415 /*IsTypeSpecifier=*/false); 11416 } 11417 11418 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11419 ElaboratedTypeKeyword Keyword 11420 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11421 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 11422 *Name, NameLoc); 11423 if (T.isNull()) 11424 return 0; 11425 11426 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11427 if (isa<DependentNameType>(T)) { 11428 DependentNameTypeLoc TL = 11429 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11430 TL.setElaboratedKeywordLoc(TagLoc); 11431 TL.setQualifierLoc(QualifierLoc); 11432 TL.setNameLoc(NameLoc); 11433 } else { 11434 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11435 TL.setElaboratedKeywordLoc(TagLoc); 11436 TL.setQualifierLoc(QualifierLoc); 11437 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 11438 } 11439 11440 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11441 TSI, FriendLoc, TempParamLists); 11442 Friend->setAccess(AS_public); 11443 CurContext->addDecl(Friend); 11444 return Friend; 11445 } 11446 11447 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 11448 11449 11450 11451 // Handle the case of a templated-scope friend class. e.g. 11452 // template <class T> class A<T>::B; 11453 // FIXME: we don't support these right now. 11454 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 11455 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 11456 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 11457 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 11458 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 11459 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 11460 TL.setElaboratedKeywordLoc(TagLoc); 11461 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11462 TL.setNameLoc(NameLoc); 11463 11464 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 11465 TSI, FriendLoc, TempParamLists); 11466 Friend->setAccess(AS_public); 11467 Friend->setUnsupportedFriend(true); 11468 CurContext->addDecl(Friend); 11469 return Friend; 11470 } 11471 11472 11473 /// Handle a friend type declaration. This works in tandem with 11474 /// ActOnTag. 11475 /// 11476 /// Notes on friend class templates: 11477 /// 11478 /// We generally treat friend class declarations as if they were 11479 /// declaring a class. So, for example, the elaborated type specifier 11480 /// in a friend declaration is required to obey the restrictions of a 11481 /// class-head (i.e. no typedefs in the scope chain), template 11482 /// parameters are required to match up with simple template-ids, &c. 11483 /// However, unlike when declaring a template specialization, it's 11484 /// okay to refer to a template specialization without an empty 11485 /// template parameter declaration, e.g. 11486 /// friend class A<T>::B<unsigned>; 11487 /// We permit this as a special case; if there are any template 11488 /// parameters present at all, require proper matching, i.e. 11489 /// template <> template \<class T> friend class A<int>::B; 11490 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 11491 MultiTemplateParamsArg TempParams) { 11492 SourceLocation Loc = DS.getLocStart(); 11493 11494 assert(DS.isFriendSpecified()); 11495 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11496 11497 // Try to convert the decl specifier to a type. This works for 11498 // friend templates because ActOnTag never produces a ClassTemplateDecl 11499 // for a TUK_Friend. 11500 Declarator TheDeclarator(DS, Declarator::MemberContext); 11501 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 11502 QualType T = TSI->getType(); 11503 if (TheDeclarator.isInvalidType()) 11504 return 0; 11505 11506 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 11507 return 0; 11508 11509 // This is definitely an error in C++98. It's probably meant to 11510 // be forbidden in C++0x, too, but the specification is just 11511 // poorly written. 11512 // 11513 // The problem is with declarations like the following: 11514 // template <T> friend A<T>::foo; 11515 // where deciding whether a class C is a friend or not now hinges 11516 // on whether there exists an instantiation of A that causes 11517 // 'foo' to equal C. There are restrictions on class-heads 11518 // (which we declare (by fiat) elaborated friend declarations to 11519 // be) that makes this tractable. 11520 // 11521 // FIXME: handle "template <> friend class A<T>;", which 11522 // is possibly well-formed? Who even knows? 11523 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 11524 Diag(Loc, diag::err_tagless_friend_type_template) 11525 << DS.getSourceRange(); 11526 return 0; 11527 } 11528 11529 // C++98 [class.friend]p1: A friend of a class is a function 11530 // or class that is not a member of the class . . . 11531 // This is fixed in DR77, which just barely didn't make the C++03 11532 // deadline. It's also a very silly restriction that seriously 11533 // affects inner classes and which nobody else seems to implement; 11534 // thus we never diagnose it, not even in -pedantic. 11535 // 11536 // But note that we could warn about it: it's always useless to 11537 // friend one of your own members (it's not, however, worthless to 11538 // friend a member of an arbitrary specialization of your template). 11539 11540 Decl *D; 11541 if (unsigned NumTempParamLists = TempParams.size()) 11542 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 11543 NumTempParamLists, 11544 TempParams.data(), 11545 TSI, 11546 DS.getFriendSpecLoc()); 11547 else 11548 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 11549 11550 if (!D) 11551 return 0; 11552 11553 D->setAccess(AS_public); 11554 CurContext->addDecl(D); 11555 11556 return D; 11557 } 11558 11559 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 11560 MultiTemplateParamsArg TemplateParams) { 11561 const DeclSpec &DS = D.getDeclSpec(); 11562 11563 assert(DS.isFriendSpecified()); 11564 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 11565 11566 SourceLocation Loc = D.getIdentifierLoc(); 11567 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11568 11569 // C++ [class.friend]p1 11570 // A friend of a class is a function or class.... 11571 // Note that this sees through typedefs, which is intended. 11572 // It *doesn't* see through dependent types, which is correct 11573 // according to [temp.arg.type]p3: 11574 // If a declaration acquires a function type through a 11575 // type dependent on a template-parameter and this causes 11576 // a declaration that does not use the syntactic form of a 11577 // function declarator to have a function type, the program 11578 // is ill-formed. 11579 if (!TInfo->getType()->isFunctionType()) { 11580 Diag(Loc, diag::err_unexpected_friend); 11581 11582 // It might be worthwhile to try to recover by creating an 11583 // appropriate declaration. 11584 return 0; 11585 } 11586 11587 // C++ [namespace.memdef]p3 11588 // - If a friend declaration in a non-local class first declares a 11589 // class or function, the friend class or function is a member 11590 // of the innermost enclosing namespace. 11591 // - The name of the friend is not found by simple name lookup 11592 // until a matching declaration is provided in that namespace 11593 // scope (either before or after the class declaration granting 11594 // friendship). 11595 // - If a friend function is called, its name may be found by the 11596 // name lookup that considers functions from namespaces and 11597 // classes associated with the types of the function arguments. 11598 // - When looking for a prior declaration of a class or a function 11599 // declared as a friend, scopes outside the innermost enclosing 11600 // namespace scope are not considered. 11601 11602 CXXScopeSpec &SS = D.getCXXScopeSpec(); 11603 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 11604 DeclarationName Name = NameInfo.getName(); 11605 assert(Name); 11606 11607 // Check for unexpanded parameter packs. 11608 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 11609 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 11610 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 11611 return 0; 11612 11613 // The context we found the declaration in, or in which we should 11614 // create the declaration. 11615 DeclContext *DC; 11616 Scope *DCScope = S; 11617 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11618 ForRedeclaration); 11619 11620 // There are five cases here. 11621 // - There's no scope specifier and we're in a local class. Only look 11622 // for functions declared in the immediately-enclosing block scope. 11623 // We recover from invalid scope qualifiers as if they just weren't there. 11624 FunctionDecl *FunctionContainingLocalClass = 0; 11625 if ((SS.isInvalid() || !SS.isSet()) && 11626 (FunctionContainingLocalClass = 11627 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 11628 // C++11 [class.friend]p11: 11629 // If a friend declaration appears in a local class and the name 11630 // specified is an unqualified name, a prior declaration is 11631 // looked up without considering scopes that are outside the 11632 // innermost enclosing non-class scope. For a friend function 11633 // declaration, if there is no prior declaration, the program is 11634 // ill-formed. 11635 11636 // Find the innermost enclosing non-class scope. This is the block 11637 // scope containing the local class definition (or for a nested class, 11638 // the outer local class). 11639 DCScope = S->getFnParent(); 11640 11641 // Look up the function name in the scope. 11642 Previous.clear(LookupLocalFriendName); 11643 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 11644 11645 if (!Previous.empty()) { 11646 // All possible previous declarations must have the same context: 11647 // either they were declared at block scope or they are members of 11648 // one of the enclosing local classes. 11649 DC = Previous.getRepresentativeDecl()->getDeclContext(); 11650 } else { 11651 // This is ill-formed, but provide the context that we would have 11652 // declared the function in, if we were permitted to, for error recovery. 11653 DC = FunctionContainingLocalClass; 11654 } 11655 adjustContextForLocalExternDecl(DC); 11656 11657 // C++ [class.friend]p6: 11658 // A function can be defined in a friend declaration of a class if and 11659 // only if the class is a non-local class (9.8), the function name is 11660 // unqualified, and the function has namespace scope. 11661 if (D.isFunctionDefinition()) { 11662 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 11663 } 11664 11665 // - There's no scope specifier, in which case we just go to the 11666 // appropriate scope and look for a function or function template 11667 // there as appropriate. 11668 } else if (SS.isInvalid() || !SS.isSet()) { 11669 // C++11 [namespace.memdef]p3: 11670 // If the name in a friend declaration is neither qualified nor 11671 // a template-id and the declaration is a function or an 11672 // elaborated-type-specifier, the lookup to determine whether 11673 // the entity has been previously declared shall not consider 11674 // any scopes outside the innermost enclosing namespace. 11675 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 11676 11677 // Find the appropriate context according to the above. 11678 DC = CurContext; 11679 11680 // Skip class contexts. If someone can cite chapter and verse 11681 // for this behavior, that would be nice --- it's what GCC and 11682 // EDG do, and it seems like a reasonable intent, but the spec 11683 // really only says that checks for unqualified existing 11684 // declarations should stop at the nearest enclosing namespace, 11685 // not that they should only consider the nearest enclosing 11686 // namespace. 11687 while (DC->isRecord()) 11688 DC = DC->getParent(); 11689 11690 DeclContext *LookupDC = DC; 11691 while (LookupDC->isTransparentContext()) 11692 LookupDC = LookupDC->getParent(); 11693 11694 while (true) { 11695 LookupQualifiedName(Previous, LookupDC); 11696 11697 if (!Previous.empty()) { 11698 DC = LookupDC; 11699 break; 11700 } 11701 11702 if (isTemplateId) { 11703 if (isa<TranslationUnitDecl>(LookupDC)) break; 11704 } else { 11705 if (LookupDC->isFileContext()) break; 11706 } 11707 LookupDC = LookupDC->getParent(); 11708 } 11709 11710 DCScope = getScopeForDeclContext(S, DC); 11711 11712 // - There's a non-dependent scope specifier, in which case we 11713 // compute it and do a previous lookup there for a function 11714 // or function template. 11715 } else if (!SS.getScopeRep()->isDependent()) { 11716 DC = computeDeclContext(SS); 11717 if (!DC) return 0; 11718 11719 if (RequireCompleteDeclContext(SS, DC)) return 0; 11720 11721 LookupQualifiedName(Previous, DC); 11722 11723 // Ignore things found implicitly in the wrong scope. 11724 // TODO: better diagnostics for this case. Suggesting the right 11725 // qualified scope would be nice... 11726 LookupResult::Filter F = Previous.makeFilter(); 11727 while (F.hasNext()) { 11728 NamedDecl *D = F.next(); 11729 if (!DC->InEnclosingNamespaceSetOf( 11730 D->getDeclContext()->getRedeclContext())) 11731 F.erase(); 11732 } 11733 F.done(); 11734 11735 if (Previous.empty()) { 11736 D.setInvalidType(); 11737 Diag(Loc, diag::err_qualified_friend_not_found) 11738 << Name << TInfo->getType(); 11739 return 0; 11740 } 11741 11742 // C++ [class.friend]p1: A friend of a class is a function or 11743 // class that is not a member of the class . . . 11744 if (DC->Equals(CurContext)) 11745 Diag(DS.getFriendSpecLoc(), 11746 getLangOpts().CPlusPlus11 ? 11747 diag::warn_cxx98_compat_friend_is_member : 11748 diag::err_friend_is_member); 11749 11750 if (D.isFunctionDefinition()) { 11751 // C++ [class.friend]p6: 11752 // A function can be defined in a friend declaration of a class if and 11753 // only if the class is a non-local class (9.8), the function name is 11754 // unqualified, and the function has namespace scope. 11755 SemaDiagnosticBuilder DB 11756 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 11757 11758 DB << SS.getScopeRep(); 11759 if (DC->isFileContext()) 11760 DB << FixItHint::CreateRemoval(SS.getRange()); 11761 SS.clear(); 11762 } 11763 11764 // - There's a scope specifier that does not match any template 11765 // parameter lists, in which case we use some arbitrary context, 11766 // create a method or method template, and wait for instantiation. 11767 // - There's a scope specifier that does match some template 11768 // parameter lists, which we don't handle right now. 11769 } else { 11770 if (D.isFunctionDefinition()) { 11771 // C++ [class.friend]p6: 11772 // A function can be defined in a friend declaration of a class if and 11773 // only if the class is a non-local class (9.8), the function name is 11774 // unqualified, and the function has namespace scope. 11775 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 11776 << SS.getScopeRep(); 11777 } 11778 11779 DC = CurContext; 11780 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 11781 } 11782 11783 if (!DC->isRecord()) { 11784 // This implies that it has to be an operator or function. 11785 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 11786 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 11787 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 11788 Diag(Loc, diag::err_introducing_special_friend) << 11789 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 11790 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 11791 return 0; 11792 } 11793 } 11794 11795 // FIXME: This is an egregious hack to cope with cases where the scope stack 11796 // does not contain the declaration context, i.e., in an out-of-line 11797 // definition of a class. 11798 Scope FakeDCScope(S, Scope::DeclScope, Diags); 11799 if (!DCScope) { 11800 FakeDCScope.setEntity(DC); 11801 DCScope = &FakeDCScope; 11802 } 11803 11804 bool AddToScope = true; 11805 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 11806 TemplateParams, AddToScope); 11807 if (!ND) return 0; 11808 11809 assert(ND->getLexicalDeclContext() == CurContext); 11810 11811 // If we performed typo correction, we might have added a scope specifier 11812 // and changed the decl context. 11813 DC = ND->getDeclContext(); 11814 11815 // Add the function declaration to the appropriate lookup tables, 11816 // adjusting the redeclarations list as necessary. We don't 11817 // want to do this yet if the friending class is dependent. 11818 // 11819 // Also update the scope-based lookup if the target context's 11820 // lookup context is in lexical scope. 11821 if (!CurContext->isDependentContext()) { 11822 DC = DC->getRedeclContext(); 11823 DC->makeDeclVisibleInContext(ND); 11824 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11825 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 11826 } 11827 11828 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 11829 D.getIdentifierLoc(), ND, 11830 DS.getFriendSpecLoc()); 11831 FrD->setAccess(AS_public); 11832 CurContext->addDecl(FrD); 11833 11834 if (ND->isInvalidDecl()) { 11835 FrD->setInvalidDecl(); 11836 } else { 11837 if (DC->isRecord()) CheckFriendAccess(ND); 11838 11839 FunctionDecl *FD; 11840 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 11841 FD = FTD->getTemplatedDecl(); 11842 else 11843 FD = cast<FunctionDecl>(ND); 11844 11845 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 11846 // default argument expression, that declaration shall be a definition 11847 // and shall be the only declaration of the function or function 11848 // template in the translation unit. 11849 if (functionDeclHasDefaultArgument(FD)) { 11850 if (FunctionDecl *OldFD = FD->getPreviousDecl()) { 11851 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 11852 Diag(OldFD->getLocation(), diag::note_previous_declaration); 11853 } else if (!D.isFunctionDefinition()) 11854 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 11855 } 11856 11857 // Mark templated-scope function declarations as unsupported. 11858 if (FD->getNumTemplateParameterLists()) 11859 FrD->setUnsupportedFriend(true); 11860 } 11861 11862 return ND; 11863 } 11864 11865 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 11866 AdjustDeclIfTemplate(Dcl); 11867 11868 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 11869 if (!Fn) { 11870 Diag(DelLoc, diag::err_deleted_non_function); 11871 return; 11872 } 11873 11874 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 11875 // Don't consider the implicit declaration we generate for explicit 11876 // specializations. FIXME: Do not generate these implicit declarations. 11877 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 11878 Prev->getPreviousDecl()) && 11879 !Prev->isDefined()) { 11880 Diag(DelLoc, diag::err_deleted_decl_not_first); 11881 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 11882 Prev->isImplicit() ? diag::note_previous_implicit_declaration 11883 : diag::note_previous_declaration); 11884 } 11885 // If the declaration wasn't the first, we delete the function anyway for 11886 // recovery. 11887 Fn = Fn->getCanonicalDecl(); 11888 } 11889 11890 if (Fn->isDeleted()) 11891 return; 11892 11893 // See if we're deleting a function which is already known to override a 11894 // non-deleted virtual function. 11895 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 11896 bool IssuedDiagnostic = false; 11897 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 11898 E = MD->end_overridden_methods(); 11899 I != E; ++I) { 11900 if (!(*MD->begin_overridden_methods())->isDeleted()) { 11901 if (!IssuedDiagnostic) { 11902 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 11903 IssuedDiagnostic = true; 11904 } 11905 Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 11906 } 11907 } 11908 } 11909 11910 // C++11 [basic.start.main]p3: 11911 // A program that defines main as deleted [...] is ill-formed. 11912 if (Fn->isMain()) 11913 Diag(DelLoc, diag::err_deleted_main); 11914 11915 Fn->setDeletedAsWritten(); 11916 } 11917 11918 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 11919 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 11920 11921 if (MD) { 11922 if (MD->getParent()->isDependentType()) { 11923 MD->setDefaulted(); 11924 MD->setExplicitlyDefaulted(); 11925 return; 11926 } 11927 11928 CXXSpecialMember Member = getSpecialMember(MD); 11929 if (Member == CXXInvalid) { 11930 if (!MD->isInvalidDecl()) 11931 Diag(DefaultLoc, diag::err_default_special_members); 11932 return; 11933 } 11934 11935 MD->setDefaulted(); 11936 MD->setExplicitlyDefaulted(); 11937 11938 // If this definition appears within the record, do the checking when 11939 // the record is complete. 11940 const FunctionDecl *Primary = MD; 11941 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 11942 // Find the uninstantiated declaration that actually had the '= default' 11943 // on it. 11944 Pattern->isDefined(Primary); 11945 11946 // If the method was defaulted on its first declaration, we will have 11947 // already performed the checking in CheckCompletedCXXClass. Such a 11948 // declaration doesn't trigger an implicit definition. 11949 if (Primary == Primary->getCanonicalDecl()) 11950 return; 11951 11952 CheckExplicitlyDefaultedSpecialMember(MD); 11953 11954 // The exception specification is needed because we are defining the 11955 // function. 11956 ResolveExceptionSpec(DefaultLoc, 11957 MD->getType()->castAs<FunctionProtoType>()); 11958 11959 if (MD->isInvalidDecl()) 11960 return; 11961 11962 switch (Member) { 11963 case CXXDefaultConstructor: 11964 DefineImplicitDefaultConstructor(DefaultLoc, 11965 cast<CXXConstructorDecl>(MD)); 11966 break; 11967 case CXXCopyConstructor: 11968 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 11969 break; 11970 case CXXCopyAssignment: 11971 DefineImplicitCopyAssignment(DefaultLoc, MD); 11972 break; 11973 case CXXDestructor: 11974 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 11975 break; 11976 case CXXMoveConstructor: 11977 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 11978 break; 11979 case CXXMoveAssignment: 11980 DefineImplicitMoveAssignment(DefaultLoc, MD); 11981 break; 11982 case CXXInvalid: 11983 llvm_unreachable("Invalid special member."); 11984 } 11985 } else { 11986 Diag(DefaultLoc, diag::err_default_special_members); 11987 } 11988 } 11989 11990 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 11991 for (Stmt::child_range CI = S->children(); CI; ++CI) { 11992 Stmt *SubStmt = *CI; 11993 if (!SubStmt) 11994 continue; 11995 if (isa<ReturnStmt>(SubStmt)) 11996 Self.Diag(SubStmt->getLocStart(), 11997 diag::err_return_in_constructor_handler); 11998 if (!isa<Expr>(SubStmt)) 11999 SearchForReturnInStmt(Self, SubStmt); 12000 } 12001 } 12002 12003 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 12004 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 12005 CXXCatchStmt *Handler = TryBlock->getHandler(I); 12006 SearchForReturnInStmt(*this, Handler); 12007 } 12008 } 12009 12010 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 12011 const CXXMethodDecl *Old) { 12012 const FunctionType *NewFT = New->getType()->getAs<FunctionType>(); 12013 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>(); 12014 12015 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 12016 12017 // If the calling conventions match, everything is fine 12018 if (NewCC == OldCC) 12019 return false; 12020 12021 // If the calling conventions mismatch because the new function is static, 12022 // suppress the calling convention mismatch error; the error about static 12023 // function override (err_static_overrides_virtual from 12024 // Sema::CheckFunctionDeclaration) is more clear. 12025 if (New->getStorageClass() == SC_Static) 12026 return false; 12027 12028 Diag(New->getLocation(), 12029 diag::err_conflicting_overriding_cc_attributes) 12030 << New->getDeclName() << New->getType() << Old->getType(); 12031 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12032 return true; 12033 } 12034 12035 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 12036 const CXXMethodDecl *Old) { 12037 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 12038 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 12039 12040 if (Context.hasSameType(NewTy, OldTy) || 12041 NewTy->isDependentType() || OldTy->isDependentType()) 12042 return false; 12043 12044 // Check if the return types are covariant 12045 QualType NewClassTy, OldClassTy; 12046 12047 /// Both types must be pointers or references to classes. 12048 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 12049 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 12050 NewClassTy = NewPT->getPointeeType(); 12051 OldClassTy = OldPT->getPointeeType(); 12052 } 12053 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 12054 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 12055 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 12056 NewClassTy = NewRT->getPointeeType(); 12057 OldClassTy = OldRT->getPointeeType(); 12058 } 12059 } 12060 } 12061 12062 // The return types aren't either both pointers or references to a class type. 12063 if (NewClassTy.isNull()) { 12064 Diag(New->getLocation(), 12065 diag::err_different_return_type_for_overriding_virtual_function) 12066 << New->getDeclName() << NewTy << OldTy; 12067 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12068 12069 return true; 12070 } 12071 12072 // C++ [class.virtual]p6: 12073 // If the return type of D::f differs from the return type of B::f, the 12074 // class type in the return type of D::f shall be complete at the point of 12075 // declaration of D::f or shall be the class type D. 12076 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 12077 if (!RT->isBeingDefined() && 12078 RequireCompleteType(New->getLocation(), NewClassTy, 12079 diag::err_covariant_return_incomplete, 12080 New->getDeclName())) 12081 return true; 12082 } 12083 12084 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 12085 // Check if the new class derives from the old class. 12086 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 12087 Diag(New->getLocation(), 12088 diag::err_covariant_return_not_derived) 12089 << New->getDeclName() << NewTy << OldTy; 12090 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12091 return true; 12092 } 12093 12094 // Check if we the conversion from derived to base is valid. 12095 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 12096 diag::err_covariant_return_inaccessible_base, 12097 diag::err_covariant_return_ambiguous_derived_to_base_conv, 12098 // FIXME: Should this point to the return type? 12099 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 12100 // FIXME: this note won't trigger for delayed access control 12101 // diagnostics, and it's impossible to get an undelayed error 12102 // here from access control during the original parse because 12103 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 12104 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12105 return true; 12106 } 12107 } 12108 12109 // The qualifiers of the return types must be the same. 12110 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 12111 Diag(New->getLocation(), 12112 diag::err_covariant_return_type_different_qualifications) 12113 << New->getDeclName() << NewTy << OldTy; 12114 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12115 return true; 12116 }; 12117 12118 12119 // The new class type must have the same or less qualifiers as the old type. 12120 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 12121 Diag(New->getLocation(), 12122 diag::err_covariant_return_type_class_type_more_qualified) 12123 << New->getDeclName() << NewTy << OldTy; 12124 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 12125 return true; 12126 }; 12127 12128 return false; 12129 } 12130 12131 /// \brief Mark the given method pure. 12132 /// 12133 /// \param Method the method to be marked pure. 12134 /// 12135 /// \param InitRange the source range that covers the "0" initializer. 12136 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 12137 SourceLocation EndLoc = InitRange.getEnd(); 12138 if (EndLoc.isValid()) 12139 Method->setRangeEnd(EndLoc); 12140 12141 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 12142 Method->setPure(); 12143 return false; 12144 } 12145 12146 if (!Method->isInvalidDecl()) 12147 Diag(Method->getLocation(), diag::err_non_virtual_pure) 12148 << Method->getDeclName() << InitRange; 12149 return true; 12150 } 12151 12152 /// \brief Determine whether the given declaration is a static data member. 12153 static bool isStaticDataMember(const Decl *D) { 12154 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 12155 return Var->isStaticDataMember(); 12156 12157 return false; 12158 } 12159 12160 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 12161 /// an initializer for the out-of-line declaration 'Dcl'. The scope 12162 /// is a fresh scope pushed for just this purpose. 12163 /// 12164 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 12165 /// static data member of class X, names should be looked up in the scope of 12166 /// class X. 12167 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 12168 // If there is no declaration, there was an error parsing it. 12169 if (D == 0 || D->isInvalidDecl()) return; 12170 12171 // We will always have a nested name specifier here, but this declaration 12172 // might not be out of line if the specifier names the current namespace: 12173 // extern int n; 12174 // int ::n = 0; 12175 if (D->isOutOfLine()) 12176 EnterDeclaratorContext(S, D->getDeclContext()); 12177 12178 // If we are parsing the initializer for a static data member, push a 12179 // new expression evaluation context that is associated with this static 12180 // data member. 12181 if (isStaticDataMember(D)) 12182 PushExpressionEvaluationContext(PotentiallyEvaluated, D); 12183 } 12184 12185 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 12186 /// initializer for the out-of-line declaration 'D'. 12187 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 12188 // If there is no declaration, there was an error parsing it. 12189 if (D == 0 || D->isInvalidDecl()) return; 12190 12191 if (isStaticDataMember(D)) 12192 PopExpressionEvaluationContext(); 12193 12194 if (D->isOutOfLine()) 12195 ExitDeclaratorContext(S); 12196 } 12197 12198 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 12199 /// C++ if/switch/while/for statement. 12200 /// e.g: "if (int x = f()) {...}" 12201 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 12202 // C++ 6.4p2: 12203 // The declarator shall not specify a function or an array. 12204 // The type-specifier-seq shall not contain typedef and shall not declare a 12205 // new class or enumeration. 12206 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 12207 "Parser allowed 'typedef' as storage class of condition decl."); 12208 12209 Decl *Dcl = ActOnDeclarator(S, D); 12210 if (!Dcl) 12211 return true; 12212 12213 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 12214 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 12215 << D.getSourceRange(); 12216 return true; 12217 } 12218 12219 return Dcl; 12220 } 12221 12222 void Sema::LoadExternalVTableUses() { 12223 if (!ExternalSource) 12224 return; 12225 12226 SmallVector<ExternalVTableUse, 4> VTables; 12227 ExternalSource->ReadUsedVTables(VTables); 12228 SmallVector<VTableUse, 4> NewUses; 12229 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 12230 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 12231 = VTablesUsed.find(VTables[I].Record); 12232 // Even if a definition wasn't required before, it may be required now. 12233 if (Pos != VTablesUsed.end()) { 12234 if (!Pos->second && VTables[I].DefinitionRequired) 12235 Pos->second = true; 12236 continue; 12237 } 12238 12239 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 12240 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 12241 } 12242 12243 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 12244 } 12245 12246 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 12247 bool DefinitionRequired) { 12248 // Ignore any vtable uses in unevaluated operands or for classes that do 12249 // not have a vtable. 12250 if (!Class->isDynamicClass() || Class->isDependentContext() || 12251 CurContext->isDependentContext() || isUnevaluatedContext()) 12252 return; 12253 12254 // Try to insert this class into the map. 12255 LoadExternalVTableUses(); 12256 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12257 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 12258 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 12259 if (!Pos.second) { 12260 // If we already had an entry, check to see if we are promoting this vtable 12261 // to required a definition. If so, we need to reappend to the VTableUses 12262 // list, since we may have already processed the first entry. 12263 if (DefinitionRequired && !Pos.first->second) { 12264 Pos.first->second = true; 12265 } else { 12266 // Otherwise, we can early exit. 12267 return; 12268 } 12269 } else { 12270 // The Microsoft ABI requires that we perform the destructor body 12271 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 12272 // the deleting destructor is emitted with the vtable, not with the 12273 // destructor definition as in the Itanium ABI. 12274 // If it has a definition, we do the check at that point instead. 12275 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12276 Class->hasUserDeclaredDestructor() && 12277 !Class->getDestructor()->isDefined() && 12278 !Class->getDestructor()->isDeleted()) { 12279 CheckDestructor(Class->getDestructor()); 12280 } 12281 } 12282 12283 // Local classes need to have their virtual members marked 12284 // immediately. For all other classes, we mark their virtual members 12285 // at the end of the translation unit. 12286 if (Class->isLocalClass()) 12287 MarkVirtualMembersReferenced(Loc, Class); 12288 else 12289 VTableUses.push_back(std::make_pair(Class, Loc)); 12290 } 12291 12292 bool Sema::DefineUsedVTables() { 12293 LoadExternalVTableUses(); 12294 if (VTableUses.empty()) 12295 return false; 12296 12297 // Note: The VTableUses vector could grow as a result of marking 12298 // the members of a class as "used", so we check the size each 12299 // time through the loop and prefer indices (which are stable) to 12300 // iterators (which are not). 12301 bool DefinedAnything = false; 12302 for (unsigned I = 0; I != VTableUses.size(); ++I) { 12303 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 12304 if (!Class) 12305 continue; 12306 12307 SourceLocation Loc = VTableUses[I].second; 12308 12309 bool DefineVTable = true; 12310 12311 // If this class has a key function, but that key function is 12312 // defined in another translation unit, we don't need to emit the 12313 // vtable even though we're using it. 12314 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 12315 if (KeyFunction && !KeyFunction->hasBody()) { 12316 // The key function is in another translation unit. 12317 DefineVTable = false; 12318 TemplateSpecializationKind TSK = 12319 KeyFunction->getTemplateSpecializationKind(); 12320 assert(TSK != TSK_ExplicitInstantiationDefinition && 12321 TSK != TSK_ImplicitInstantiation && 12322 "Instantiations don't have key functions"); 12323 (void)TSK; 12324 } else if (!KeyFunction) { 12325 // If we have a class with no key function that is the subject 12326 // of an explicit instantiation declaration, suppress the 12327 // vtable; it will live with the explicit instantiation 12328 // definition. 12329 bool IsExplicitInstantiationDeclaration 12330 = Class->getTemplateSpecializationKind() 12331 == TSK_ExplicitInstantiationDeclaration; 12332 for (auto R : Class->redecls()) { 12333 TemplateSpecializationKind TSK 12334 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 12335 if (TSK == TSK_ExplicitInstantiationDeclaration) 12336 IsExplicitInstantiationDeclaration = true; 12337 else if (TSK == TSK_ExplicitInstantiationDefinition) { 12338 IsExplicitInstantiationDeclaration = false; 12339 break; 12340 } 12341 } 12342 12343 if (IsExplicitInstantiationDeclaration) 12344 DefineVTable = false; 12345 } 12346 12347 // The exception specifications for all virtual members may be needed even 12348 // if we are not providing an authoritative form of the vtable in this TU. 12349 // We may choose to emit it available_externally anyway. 12350 if (!DefineVTable) { 12351 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 12352 continue; 12353 } 12354 12355 // Mark all of the virtual members of this class as referenced, so 12356 // that we can build a vtable. Then, tell the AST consumer that a 12357 // vtable for this class is required. 12358 DefinedAnything = true; 12359 MarkVirtualMembersReferenced(Loc, Class); 12360 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 12361 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 12362 12363 // Optionally warn if we're emitting a weak vtable. 12364 if (Class->isExternallyVisible() && 12365 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 12366 const FunctionDecl *KeyFunctionDef = 0; 12367 if (!KeyFunction || 12368 (KeyFunction->hasBody(KeyFunctionDef) && 12369 KeyFunctionDef->isInlined())) 12370 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() == 12371 TSK_ExplicitInstantiationDefinition 12372 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 12373 << Class; 12374 } 12375 } 12376 VTableUses.clear(); 12377 12378 return DefinedAnything; 12379 } 12380 12381 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 12382 const CXXRecordDecl *RD) { 12383 for (const auto *I : RD->methods()) 12384 if (I->isVirtual() && !I->isPure()) 12385 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 12386 } 12387 12388 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 12389 const CXXRecordDecl *RD) { 12390 // Mark all functions which will appear in RD's vtable as used. 12391 CXXFinalOverriderMap FinalOverriders; 12392 RD->getFinalOverriders(FinalOverriders); 12393 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 12394 E = FinalOverriders.end(); 12395 I != E; ++I) { 12396 for (OverridingMethods::const_iterator OI = I->second.begin(), 12397 OE = I->second.end(); 12398 OI != OE; ++OI) { 12399 assert(OI->second.size() > 0 && "no final overrider"); 12400 CXXMethodDecl *Overrider = OI->second.front().Method; 12401 12402 // C++ [basic.def.odr]p2: 12403 // [...] A virtual member function is used if it is not pure. [...] 12404 if (!Overrider->isPure()) 12405 MarkFunctionReferenced(Loc, Overrider); 12406 } 12407 } 12408 12409 // Only classes that have virtual bases need a VTT. 12410 if (RD->getNumVBases() == 0) 12411 return; 12412 12413 for (const auto &I : RD->bases()) { 12414 const CXXRecordDecl *Base = 12415 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 12416 if (Base->getNumVBases() == 0) 12417 continue; 12418 MarkVirtualMembersReferenced(Loc, Base); 12419 } 12420 } 12421 12422 /// SetIvarInitializers - This routine builds initialization ASTs for the 12423 /// Objective-C implementation whose ivars need be initialized. 12424 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 12425 if (!getLangOpts().CPlusPlus) 12426 return; 12427 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 12428 SmallVector<ObjCIvarDecl*, 8> ivars; 12429 CollectIvarsToConstructOrDestruct(OID, ivars); 12430 if (ivars.empty()) 12431 return; 12432 SmallVector<CXXCtorInitializer*, 32> AllToInit; 12433 for (unsigned i = 0; i < ivars.size(); i++) { 12434 FieldDecl *Field = ivars[i]; 12435 if (Field->isInvalidDecl()) 12436 continue; 12437 12438 CXXCtorInitializer *Member; 12439 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 12440 InitializationKind InitKind = 12441 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 12442 12443 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 12444 ExprResult MemberInit = 12445 InitSeq.Perform(*this, InitEntity, InitKind, None); 12446 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 12447 // Note, MemberInit could actually come back empty if no initialization 12448 // is required (e.g., because it would call a trivial default constructor) 12449 if (!MemberInit.get() || MemberInit.isInvalid()) 12450 continue; 12451 12452 Member = 12453 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 12454 SourceLocation(), 12455 MemberInit.takeAs<Expr>(), 12456 SourceLocation()); 12457 AllToInit.push_back(Member); 12458 12459 // Be sure that the destructor is accessible and is marked as referenced. 12460 if (const RecordType *RecordTy 12461 = Context.getBaseElementType(Field->getType()) 12462 ->getAs<RecordType>()) { 12463 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 12464 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 12465 MarkFunctionReferenced(Field->getLocation(), Destructor); 12466 CheckDestructorAccess(Field->getLocation(), Destructor, 12467 PDiag(diag::err_access_dtor_ivar) 12468 << Context.getBaseElementType(Field->getType())); 12469 } 12470 } 12471 } 12472 ObjCImplementation->setIvarInitializers(Context, 12473 AllToInit.data(), AllToInit.size()); 12474 } 12475 } 12476 12477 static 12478 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 12479 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid, 12480 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid, 12481 llvm::SmallSet<CXXConstructorDecl*, 4> &Current, 12482 Sema &S) { 12483 if (Ctor->isInvalidDecl()) 12484 return; 12485 12486 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 12487 12488 // Target may not be determinable yet, for instance if this is a dependent 12489 // call in an uninstantiated template. 12490 if (Target) { 12491 const FunctionDecl *FNTarget = 0; 12492 (void)Target->hasBody(FNTarget); 12493 Target = const_cast<CXXConstructorDecl*>( 12494 cast_or_null<CXXConstructorDecl>(FNTarget)); 12495 } 12496 12497 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 12498 // Avoid dereferencing a null pointer here. 12499 *TCanonical = Target ? Target->getCanonicalDecl() : 0; 12500 12501 if (!Current.insert(Canonical)) 12502 return; 12503 12504 // We know that beyond here, we aren't chaining into a cycle. 12505 if (!Target || !Target->isDelegatingConstructor() || 12506 Target->isInvalidDecl() || Valid.count(TCanonical)) { 12507 Valid.insert(Current.begin(), Current.end()); 12508 Current.clear(); 12509 // We've hit a cycle. 12510 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 12511 Current.count(TCanonical)) { 12512 // If we haven't diagnosed this cycle yet, do so now. 12513 if (!Invalid.count(TCanonical)) { 12514 S.Diag((*Ctor->init_begin())->getSourceLocation(), 12515 diag::warn_delegating_ctor_cycle) 12516 << Ctor; 12517 12518 // Don't add a note for a function delegating directly to itself. 12519 if (TCanonical != Canonical) 12520 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 12521 12522 CXXConstructorDecl *C = Target; 12523 while (C->getCanonicalDecl() != Canonical) { 12524 const FunctionDecl *FNTarget = 0; 12525 (void)C->getTargetConstructor()->hasBody(FNTarget); 12526 assert(FNTarget && "Ctor cycle through bodiless function"); 12527 12528 C = const_cast<CXXConstructorDecl*>( 12529 cast<CXXConstructorDecl>(FNTarget)); 12530 S.Diag(C->getLocation(), diag::note_which_delegates_to); 12531 } 12532 } 12533 12534 Invalid.insert(Current.begin(), Current.end()); 12535 Current.clear(); 12536 } else { 12537 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 12538 } 12539 } 12540 12541 12542 void Sema::CheckDelegatingCtorCycles() { 12543 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 12544 12545 for (DelegatingCtorDeclsType::iterator 12546 I = DelegatingCtorDecls.begin(ExternalSource), 12547 E = DelegatingCtorDecls.end(); 12548 I != E; ++I) 12549 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 12550 12551 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(), 12552 CE = Invalid.end(); 12553 CI != CE; ++CI) 12554 (*CI)->setInvalidDecl(); 12555 } 12556 12557 namespace { 12558 /// \brief AST visitor that finds references to the 'this' expression. 12559 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 12560 Sema &S; 12561 12562 public: 12563 explicit FindCXXThisExpr(Sema &S) : S(S) { } 12564 12565 bool VisitCXXThisExpr(CXXThisExpr *E) { 12566 S.Diag(E->getLocation(), diag::err_this_static_member_func) 12567 << E->isImplicit(); 12568 return false; 12569 } 12570 }; 12571 } 12572 12573 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 12574 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12575 if (!TSInfo) 12576 return false; 12577 12578 TypeLoc TL = TSInfo->getTypeLoc(); 12579 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12580 if (!ProtoTL) 12581 return false; 12582 12583 // C++11 [expr.prim.general]p3: 12584 // [The expression this] shall not appear before the optional 12585 // cv-qualifier-seq and it shall not appear within the declaration of a 12586 // static member function (although its type and value category are defined 12587 // within a static member function as they are within a non-static member 12588 // function). [ Note: this is because declaration matching does not occur 12589 // until the complete declarator is known. - end note ] 12590 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12591 FindCXXThisExpr Finder(*this); 12592 12593 // If the return type came after the cv-qualifier-seq, check it now. 12594 if (Proto->hasTrailingReturn() && 12595 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 12596 return true; 12597 12598 // Check the exception specification. 12599 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 12600 return true; 12601 12602 return checkThisInStaticMemberFunctionAttributes(Method); 12603 } 12604 12605 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 12606 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 12607 if (!TSInfo) 12608 return false; 12609 12610 TypeLoc TL = TSInfo->getTypeLoc(); 12611 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 12612 if (!ProtoTL) 12613 return false; 12614 12615 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 12616 FindCXXThisExpr Finder(*this); 12617 12618 switch (Proto->getExceptionSpecType()) { 12619 case EST_Uninstantiated: 12620 case EST_Unevaluated: 12621 case EST_BasicNoexcept: 12622 case EST_DynamicNone: 12623 case EST_MSAny: 12624 case EST_None: 12625 break; 12626 12627 case EST_ComputedNoexcept: 12628 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 12629 return true; 12630 12631 case EST_Dynamic: 12632 for (const auto &E : Proto->exceptions()) { 12633 if (!Finder.TraverseType(E)) 12634 return true; 12635 } 12636 break; 12637 } 12638 12639 return false; 12640 } 12641 12642 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 12643 FindCXXThisExpr Finder(*this); 12644 12645 // Check attributes. 12646 for (const auto *A : Method->attrs()) { 12647 // FIXME: This should be emitted by tblgen. 12648 Expr *Arg = 0; 12649 ArrayRef<Expr *> Args; 12650 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 12651 Arg = G->getArg(); 12652 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 12653 Arg = G->getArg(); 12654 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 12655 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size()); 12656 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 12657 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size()); 12658 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 12659 Arg = ETLF->getSuccessValue(); 12660 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size()); 12661 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 12662 Arg = STLF->getSuccessValue(); 12663 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size()); 12664 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 12665 Arg = LR->getArg(); 12666 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 12667 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size()); 12668 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 12669 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size()); 12670 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 12671 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size()); 12672 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 12673 Args = ArrayRef<Expr *>(AC->args_begin(), AC->args_size()); 12674 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 12675 Args = ArrayRef<Expr *>(RC->args_begin(), RC->args_size()); 12676 12677 if (Arg && !Finder.TraverseStmt(Arg)) 12678 return true; 12679 12680 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 12681 if (!Finder.TraverseStmt(Args[I])) 12682 return true; 12683 } 12684 } 12685 12686 return false; 12687 } 12688 12689 void 12690 Sema::checkExceptionSpecification(ExceptionSpecificationType EST, 12691 ArrayRef<ParsedType> DynamicExceptions, 12692 ArrayRef<SourceRange> DynamicExceptionRanges, 12693 Expr *NoexceptExpr, 12694 SmallVectorImpl<QualType> &Exceptions, 12695 FunctionProtoType::ExtProtoInfo &EPI) { 12696 Exceptions.clear(); 12697 EPI.ExceptionSpecType = EST; 12698 if (EST == EST_Dynamic) { 12699 Exceptions.reserve(DynamicExceptions.size()); 12700 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 12701 // FIXME: Preserve type source info. 12702 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 12703 12704 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 12705 collectUnexpandedParameterPacks(ET, Unexpanded); 12706 if (!Unexpanded.empty()) { 12707 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(), 12708 UPPC_ExceptionType, 12709 Unexpanded); 12710 continue; 12711 } 12712 12713 // Check that the type is valid for an exception spec, and 12714 // drop it if not. 12715 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 12716 Exceptions.push_back(ET); 12717 } 12718 EPI.NumExceptions = Exceptions.size(); 12719 EPI.Exceptions = Exceptions.data(); 12720 return; 12721 } 12722 12723 if (EST == EST_ComputedNoexcept) { 12724 // If an error occurred, there's no expression here. 12725 if (NoexceptExpr) { 12726 assert((NoexceptExpr->isTypeDependent() || 12727 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 12728 Context.BoolTy) && 12729 "Parser should have made sure that the expression is boolean"); 12730 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 12731 EPI.ExceptionSpecType = EST_BasicNoexcept; 12732 return; 12733 } 12734 12735 if (!NoexceptExpr->isValueDependent()) 12736 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0, 12737 diag::err_noexcept_needs_constant_expression, 12738 /*AllowFold*/ false).take(); 12739 EPI.NoexceptExpr = NoexceptExpr; 12740 } 12741 return; 12742 } 12743 } 12744 12745 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function 12746 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) { 12747 // Implicitly declared functions (e.g. copy constructors) are 12748 // __host__ __device__ 12749 if (D->isImplicit()) 12750 return CFT_HostDevice; 12751 12752 if (D->hasAttr<CUDAGlobalAttr>()) 12753 return CFT_Global; 12754 12755 if (D->hasAttr<CUDADeviceAttr>()) { 12756 if (D->hasAttr<CUDAHostAttr>()) 12757 return CFT_HostDevice; 12758 return CFT_Device; 12759 } 12760 12761 return CFT_Host; 12762 } 12763 12764 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget, 12765 CUDAFunctionTarget CalleeTarget) { 12766 // CUDA B.1.1 "The __device__ qualifier declares a function that is... 12767 // Callable from the device only." 12768 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device) 12769 return true; 12770 12771 // CUDA B.1.2 "The __global__ qualifier declares a function that is... 12772 // Callable from the host only." 12773 // CUDA B.1.3 "The __host__ qualifier declares a function that is... 12774 // Callable from the host only." 12775 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) && 12776 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global)) 12777 return true; 12778 12779 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice) 12780 return true; 12781 12782 return false; 12783 } 12784 12785 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 12786 /// 12787 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 12788 SourceLocation DeclStart, 12789 Declarator &D, Expr *BitWidth, 12790 InClassInitStyle InitStyle, 12791 AccessSpecifier AS, 12792 AttributeList *MSPropertyAttr) { 12793 IdentifierInfo *II = D.getIdentifier(); 12794 if (!II) { 12795 Diag(DeclStart, diag::err_anonymous_property); 12796 return NULL; 12797 } 12798 SourceLocation Loc = D.getIdentifierLoc(); 12799 12800 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12801 QualType T = TInfo->getType(); 12802 if (getLangOpts().CPlusPlus) { 12803 CheckExtraCXXDefaultArguments(D); 12804 12805 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12806 UPPC_DataMemberType)) { 12807 D.setInvalidType(); 12808 T = Context.IntTy; 12809 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12810 } 12811 } 12812 12813 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12814 12815 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12816 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12817 diag::err_invalid_thread) 12818 << DeclSpec::getSpecifierName(TSCS); 12819 12820 // Check to see if this name was declared as a member previously 12821 NamedDecl *PrevDecl = 0; 12822 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12823 LookupName(Previous, S); 12824 switch (Previous.getResultKind()) { 12825 case LookupResult::Found: 12826 case LookupResult::FoundUnresolvedValue: 12827 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12828 break; 12829 12830 case LookupResult::FoundOverloaded: 12831 PrevDecl = Previous.getRepresentativeDecl(); 12832 break; 12833 12834 case LookupResult::NotFound: 12835 case LookupResult::NotFoundInCurrentInstantiation: 12836 case LookupResult::Ambiguous: 12837 break; 12838 } 12839 12840 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12841 // Maybe we will complain about the shadowed template parameter. 12842 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12843 // Just pretend that we didn't see the previous declaration. 12844 PrevDecl = 0; 12845 } 12846 12847 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12848 PrevDecl = 0; 12849 12850 SourceLocation TSSL = D.getLocStart(); 12851 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData(); 12852 MSPropertyDecl *NewPD = MSPropertyDecl::Create( 12853 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId); 12854 ProcessDeclAttributes(TUScope, NewPD, D); 12855 NewPD->setAccess(AS); 12856 12857 if (NewPD->isInvalidDecl()) 12858 Record->setInvalidDecl(); 12859 12860 if (D.getDeclSpec().isModulePrivateSpecified()) 12861 NewPD->setModulePrivate(); 12862 12863 if (NewPD->isInvalidDecl() && PrevDecl) { 12864 // Don't introduce NewFD into scope; there's already something 12865 // with the same name in the same scope. 12866 } else if (II) { 12867 PushOnScopeChains(NewPD, S); 12868 } else 12869 Record->addDecl(NewPD); 12870 12871 return NewPD; 12872 } 12873