SemaDeclCXX.cpp revision 1d20927fd0a08c26ef0e86e26f42073fd582ff77
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for C++ declarations. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/SemaInternal.h" 15#include "clang/Sema/CXXFieldCollector.h" 16#include "clang/Sema/Scope.h" 17#include "clang/Sema/Initialization.h" 18#include "clang/Sema/Lookup.h" 19#include "clang/AST/ASTConsumer.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/CharUnits.h" 22#include "clang/AST/CXXInheritance.h" 23#include "clang/AST/DeclVisitor.h" 24#include "clang/AST/ExprCXX.h" 25#include "clang/AST/RecordLayout.h" 26#include "clang/AST/StmtVisitor.h" 27#include "clang/AST/TypeLoc.h" 28#include "clang/AST/TypeOrdering.h" 29#include "clang/Sema/DeclSpec.h" 30#include "clang/Sema/ParsedTemplate.h" 31#include "clang/Basic/PartialDiagnostic.h" 32#include "clang/Lex/Preprocessor.h" 33#include "llvm/ADT/DenseSet.h" 34#include "llvm/ADT/STLExtras.h" 35#include <map> 36#include <set> 37 38using namespace clang; 39 40//===----------------------------------------------------------------------===// 41// CheckDefaultArgumentVisitor 42//===----------------------------------------------------------------------===// 43 44namespace { 45 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 46 /// the default argument of a parameter to determine whether it 47 /// contains any ill-formed subexpressions. For example, this will 48 /// diagnose the use of local variables or parameters within the 49 /// default argument expression. 50 class CheckDefaultArgumentVisitor 51 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 52 Expr *DefaultArg; 53 Sema *S; 54 55 public: 56 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 57 : DefaultArg(defarg), S(s) {} 58 59 bool VisitExpr(Expr *Node); 60 bool VisitDeclRefExpr(DeclRefExpr *DRE); 61 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 62 }; 63 64 /// VisitExpr - Visit all of the children of this expression. 65 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 66 bool IsInvalid = false; 67 for (Stmt::child_range I = Node->children(); I; ++I) 68 IsInvalid |= Visit(*I); 69 return IsInvalid; 70 } 71 72 /// VisitDeclRefExpr - Visit a reference to a declaration, to 73 /// determine whether this declaration can be used in the default 74 /// argument expression. 75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 76 NamedDecl *Decl = DRE->getDecl(); 77 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 78 // C++ [dcl.fct.default]p9 79 // Default arguments are evaluated each time the function is 80 // called. The order of evaluation of function arguments is 81 // unspecified. Consequently, parameters of a function shall not 82 // be used in default argument expressions, even if they are not 83 // evaluated. Parameters of a function declared before a default 84 // argument expression are in scope and can hide namespace and 85 // class member names. 86 return S->Diag(DRE->getSourceRange().getBegin(), 87 diag::err_param_default_argument_references_param) 88 << Param->getDeclName() << DefaultArg->getSourceRange(); 89 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 90 // C++ [dcl.fct.default]p7 91 // Local variables shall not be used in default argument 92 // expressions. 93 if (VDecl->isLocalVarDecl()) 94 return S->Diag(DRE->getSourceRange().getBegin(), 95 diag::err_param_default_argument_references_local) 96 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 97 } 98 99 return false; 100 } 101 102 /// VisitCXXThisExpr - Visit a C++ "this" expression. 103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 104 // C++ [dcl.fct.default]p8: 105 // The keyword this shall not be used in a default argument of a 106 // member function. 107 return S->Diag(ThisE->getSourceRange().getBegin(), 108 diag::err_param_default_argument_references_this) 109 << ThisE->getSourceRange(); 110 } 111} 112 113bool 114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 115 SourceLocation EqualLoc) { 116 if (RequireCompleteType(Param->getLocation(), Param->getType(), 117 diag::err_typecheck_decl_incomplete_type)) { 118 Param->setInvalidDecl(); 119 return true; 120 } 121 122 // C++ [dcl.fct.default]p5 123 // A default argument expression is implicitly converted (clause 124 // 4) to the parameter type. The default argument expression has 125 // the same semantic constraints as the initializer expression in 126 // a declaration of a variable of the parameter type, using the 127 // copy-initialization semantics (8.5). 128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 129 Param); 130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 131 EqualLoc); 132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 134 MultiExprArg(*this, &Arg, 1)); 135 if (Result.isInvalid()) 136 return true; 137 Arg = Result.takeAs<Expr>(); 138 139 CheckImplicitConversions(Arg, EqualLoc); 140 Arg = MaybeCreateExprWithCleanups(Arg); 141 142 // Okay: add the default argument to the parameter 143 Param->setDefaultArg(Arg); 144 145 // We have already instantiated this parameter; provide each of the 146 // instantiations with the uninstantiated default argument. 147 UnparsedDefaultArgInstantiationsMap::iterator InstPos 148 = UnparsedDefaultArgInstantiations.find(Param); 149 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 150 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 151 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 152 153 // We're done tracking this parameter's instantiations. 154 UnparsedDefaultArgInstantiations.erase(InstPos); 155 } 156 157 return false; 158} 159 160/// ActOnParamDefaultArgument - Check whether the default argument 161/// provided for a function parameter is well-formed. If so, attach it 162/// to the parameter declaration. 163void 164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 165 Expr *DefaultArg) { 166 if (!param || !DefaultArg) 167 return; 168 169 ParmVarDecl *Param = cast<ParmVarDecl>(param); 170 UnparsedDefaultArgLocs.erase(Param); 171 172 // Default arguments are only permitted in C++ 173 if (!getLangOptions().CPlusPlus) { 174 Diag(EqualLoc, diag::err_param_default_argument) 175 << DefaultArg->getSourceRange(); 176 Param->setInvalidDecl(); 177 return; 178 } 179 180 // Check for unexpanded parameter packs. 181 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 182 Param->setInvalidDecl(); 183 return; 184 } 185 186 // Check that the default argument is well-formed 187 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 188 if (DefaultArgChecker.Visit(DefaultArg)) { 189 Param->setInvalidDecl(); 190 return; 191 } 192 193 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 194} 195 196/// ActOnParamUnparsedDefaultArgument - We've seen a default 197/// argument for a function parameter, but we can't parse it yet 198/// because we're inside a class definition. Note that this default 199/// argument will be parsed later. 200void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 201 SourceLocation EqualLoc, 202 SourceLocation ArgLoc) { 203 if (!param) 204 return; 205 206 ParmVarDecl *Param = cast<ParmVarDecl>(param); 207 if (Param) 208 Param->setUnparsedDefaultArg(); 209 210 UnparsedDefaultArgLocs[Param] = ArgLoc; 211} 212 213/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 214/// the default argument for the parameter param failed. 215void Sema::ActOnParamDefaultArgumentError(Decl *param) { 216 if (!param) 217 return; 218 219 ParmVarDecl *Param = cast<ParmVarDecl>(param); 220 221 Param->setInvalidDecl(); 222 223 UnparsedDefaultArgLocs.erase(Param); 224} 225 226/// CheckExtraCXXDefaultArguments - Check for any extra default 227/// arguments in the declarator, which is not a function declaration 228/// or definition and therefore is not permitted to have default 229/// arguments. This routine should be invoked for every declarator 230/// that is not a function declaration or definition. 231void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 232 // C++ [dcl.fct.default]p3 233 // A default argument expression shall be specified only in the 234 // parameter-declaration-clause of a function declaration or in a 235 // template-parameter (14.1). It shall not be specified for a 236 // parameter pack. If it is specified in a 237 // parameter-declaration-clause, it shall not occur within a 238 // declarator or abstract-declarator of a parameter-declaration. 239 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 240 DeclaratorChunk &chunk = D.getTypeObject(i); 241 if (chunk.Kind == DeclaratorChunk::Function) { 242 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 243 ParmVarDecl *Param = 244 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param); 245 if (Param->hasUnparsedDefaultArg()) { 246 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 247 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 248 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 249 delete Toks; 250 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 251 } else if (Param->getDefaultArg()) { 252 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 253 << Param->getDefaultArg()->getSourceRange(); 254 Param->setDefaultArg(0); 255 } 256 } 257 } 258 } 259} 260 261// MergeCXXFunctionDecl - Merge two declarations of the same C++ 262// function, once we already know that they have the same 263// type. Subroutine of MergeFunctionDecl. Returns true if there was an 264// error, false otherwise. 265bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 266 bool Invalid = false; 267 268 // C++ [dcl.fct.default]p4: 269 // For non-template functions, default arguments can be added in 270 // later declarations of a function in the same 271 // scope. Declarations in different scopes have completely 272 // distinct sets of default arguments. That is, declarations in 273 // inner scopes do not acquire default arguments from 274 // declarations in outer scopes, and vice versa. In a given 275 // function declaration, all parameters subsequent to a 276 // parameter with a default argument shall have default 277 // arguments supplied in this or previous declarations. A 278 // default argument shall not be redefined by a later 279 // declaration (not even to the same value). 280 // 281 // C++ [dcl.fct.default]p6: 282 // Except for member functions of class templates, the default arguments 283 // in a member function definition that appears outside of the class 284 // definition are added to the set of default arguments provided by the 285 // member function declaration in the class definition. 286 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 287 ParmVarDecl *OldParam = Old->getParamDecl(p); 288 ParmVarDecl *NewParam = New->getParamDecl(p); 289 290 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 291 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 292 // hint here. Alternatively, we could walk the type-source information 293 // for NewParam to find the last source location in the type... but it 294 // isn't worth the effort right now. This is the kind of test case that 295 // is hard to get right: 296 297 // int f(int); 298 // void g(int (*fp)(int) = f); 299 // void g(int (*fp)(int) = &f); 300 Diag(NewParam->getLocation(), 301 diag::err_param_default_argument_redefinition) 302 << NewParam->getDefaultArgRange(); 303 304 // Look for the function declaration where the default argument was 305 // actually written, which may be a declaration prior to Old. 306 for (FunctionDecl *Older = Old->getPreviousDeclaration(); 307 Older; Older = Older->getPreviousDeclaration()) { 308 if (!Older->getParamDecl(p)->hasDefaultArg()) 309 break; 310 311 OldParam = Older->getParamDecl(p); 312 } 313 314 Diag(OldParam->getLocation(), diag::note_previous_definition) 315 << OldParam->getDefaultArgRange(); 316 Invalid = true; 317 } else if (OldParam->hasDefaultArg()) { 318 // Merge the old default argument into the new parameter. 319 // It's important to use getInit() here; getDefaultArg() 320 // strips off any top-level ExprWithCleanups. 321 NewParam->setHasInheritedDefaultArg(); 322 if (OldParam->hasUninstantiatedDefaultArg()) 323 NewParam->setUninstantiatedDefaultArg( 324 OldParam->getUninstantiatedDefaultArg()); 325 else 326 NewParam->setDefaultArg(OldParam->getInit()); 327 } else if (NewParam->hasDefaultArg()) { 328 if (New->getDescribedFunctionTemplate()) { 329 // Paragraph 4, quoted above, only applies to non-template functions. 330 Diag(NewParam->getLocation(), 331 diag::err_param_default_argument_template_redecl) 332 << NewParam->getDefaultArgRange(); 333 Diag(Old->getLocation(), diag::note_template_prev_declaration) 334 << false; 335 } else if (New->getTemplateSpecializationKind() 336 != TSK_ImplicitInstantiation && 337 New->getTemplateSpecializationKind() != TSK_Undeclared) { 338 // C++ [temp.expr.spec]p21: 339 // Default function arguments shall not be specified in a declaration 340 // or a definition for one of the following explicit specializations: 341 // - the explicit specialization of a function template; 342 // - the explicit specialization of a member function template; 343 // - the explicit specialization of a member function of a class 344 // template where the class template specialization to which the 345 // member function specialization belongs is implicitly 346 // instantiated. 347 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 348 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 349 << New->getDeclName() 350 << NewParam->getDefaultArgRange(); 351 } else if (New->getDeclContext()->isDependentContext()) { 352 // C++ [dcl.fct.default]p6 (DR217): 353 // Default arguments for a member function of a class template shall 354 // be specified on the initial declaration of the member function 355 // within the class template. 356 // 357 // Reading the tea leaves a bit in DR217 and its reference to DR205 358 // leads me to the conclusion that one cannot add default function 359 // arguments for an out-of-line definition of a member function of a 360 // dependent type. 361 int WhichKind = 2; 362 if (CXXRecordDecl *Record 363 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 364 if (Record->getDescribedClassTemplate()) 365 WhichKind = 0; 366 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 367 WhichKind = 1; 368 else 369 WhichKind = 2; 370 } 371 372 Diag(NewParam->getLocation(), 373 diag::err_param_default_argument_member_template_redecl) 374 << WhichKind 375 << NewParam->getDefaultArgRange(); 376 } 377 } 378 } 379 380 if (CheckEquivalentExceptionSpec(Old, New)) 381 Invalid = true; 382 383 return Invalid; 384} 385 386/// \brief Merge the exception specifications of two variable declarations. 387/// 388/// This is called when there's a redeclaration of a VarDecl. The function 389/// checks if the redeclaration might have an exception specification and 390/// validates compatibility and merges the specs if necessary. 391void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 392 // Shortcut if exceptions are disabled. 393 if (!getLangOptions().CXXExceptions) 394 return; 395 396 assert(Context.hasSameType(New->getType(), Old->getType()) && 397 "Should only be called if types are otherwise the same."); 398 399 QualType NewType = New->getType(); 400 QualType OldType = Old->getType(); 401 402 // We're only interested in pointers and references to functions, as well 403 // as pointers to member functions. 404 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 405 NewType = R->getPointeeType(); 406 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 407 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 408 NewType = P->getPointeeType(); 409 OldType = OldType->getAs<PointerType>()->getPointeeType(); 410 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 411 NewType = M->getPointeeType(); 412 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 413 } 414 415 if (!NewType->isFunctionProtoType()) 416 return; 417 418 // There's lots of special cases for functions. For function pointers, system 419 // libraries are hopefully not as broken so that we don't need these 420 // workarounds. 421 if (CheckEquivalentExceptionSpec( 422 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 423 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 424 New->setInvalidDecl(); 425 } 426} 427 428/// CheckCXXDefaultArguments - Verify that the default arguments for a 429/// function declaration are well-formed according to C++ 430/// [dcl.fct.default]. 431void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 432 unsigned NumParams = FD->getNumParams(); 433 unsigned p; 434 435 // Find first parameter with a default argument 436 for (p = 0; p < NumParams; ++p) { 437 ParmVarDecl *Param = FD->getParamDecl(p); 438 if (Param->hasDefaultArg()) 439 break; 440 } 441 442 // C++ [dcl.fct.default]p4: 443 // In a given function declaration, all parameters 444 // subsequent to a parameter with a default argument shall 445 // have default arguments supplied in this or previous 446 // declarations. A default argument shall not be redefined 447 // by a later declaration (not even to the same value). 448 unsigned LastMissingDefaultArg = 0; 449 for (; p < NumParams; ++p) { 450 ParmVarDecl *Param = FD->getParamDecl(p); 451 if (!Param->hasDefaultArg()) { 452 if (Param->isInvalidDecl()) 453 /* We already complained about this parameter. */; 454 else if (Param->getIdentifier()) 455 Diag(Param->getLocation(), 456 diag::err_param_default_argument_missing_name) 457 << Param->getIdentifier(); 458 else 459 Diag(Param->getLocation(), 460 diag::err_param_default_argument_missing); 461 462 LastMissingDefaultArg = p; 463 } 464 } 465 466 if (LastMissingDefaultArg > 0) { 467 // Some default arguments were missing. Clear out all of the 468 // default arguments up to (and including) the last missing 469 // default argument, so that we leave the function parameters 470 // in a semantically valid state. 471 for (p = 0; p <= LastMissingDefaultArg; ++p) { 472 ParmVarDecl *Param = FD->getParamDecl(p); 473 if (Param->hasDefaultArg()) { 474 Param->setDefaultArg(0); 475 } 476 } 477 } 478} 479 480/// isCurrentClassName - Determine whether the identifier II is the 481/// name of the class type currently being defined. In the case of 482/// nested classes, this will only return true if II is the name of 483/// the innermost class. 484bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 485 const CXXScopeSpec *SS) { 486 assert(getLangOptions().CPlusPlus && "No class names in C!"); 487 488 CXXRecordDecl *CurDecl; 489 if (SS && SS->isSet() && !SS->isInvalid()) { 490 DeclContext *DC = computeDeclContext(*SS, true); 491 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 492 } else 493 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 494 495 if (CurDecl && CurDecl->getIdentifier()) 496 return &II == CurDecl->getIdentifier(); 497 else 498 return false; 499} 500 501/// \brief Check the validity of a C++ base class specifier. 502/// 503/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 504/// and returns NULL otherwise. 505CXXBaseSpecifier * 506Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 507 SourceRange SpecifierRange, 508 bool Virtual, AccessSpecifier Access, 509 TypeSourceInfo *TInfo, 510 SourceLocation EllipsisLoc) { 511 QualType BaseType = TInfo->getType(); 512 513 // C++ [class.union]p1: 514 // A union shall not have base classes. 515 if (Class->isUnion()) { 516 Diag(Class->getLocation(), diag::err_base_clause_on_union) 517 << SpecifierRange; 518 return 0; 519 } 520 521 if (EllipsisLoc.isValid() && 522 !TInfo->getType()->containsUnexpandedParameterPack()) { 523 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 524 << TInfo->getTypeLoc().getSourceRange(); 525 EllipsisLoc = SourceLocation(); 526 } 527 528 if (BaseType->isDependentType()) 529 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 530 Class->getTagKind() == TTK_Class, 531 Access, TInfo, EllipsisLoc); 532 533 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 534 535 // Base specifiers must be record types. 536 if (!BaseType->isRecordType()) { 537 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 538 return 0; 539 } 540 541 // C++ [class.union]p1: 542 // A union shall not be used as a base class. 543 if (BaseType->isUnionType()) { 544 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 545 return 0; 546 } 547 548 // C++ [class.derived]p2: 549 // The class-name in a base-specifier shall not be an incompletely 550 // defined class. 551 if (RequireCompleteType(BaseLoc, BaseType, 552 PDiag(diag::err_incomplete_base_class) 553 << SpecifierRange)) { 554 Class->setInvalidDecl(); 555 return 0; 556 } 557 558 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 559 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 560 assert(BaseDecl && "Record type has no declaration"); 561 BaseDecl = BaseDecl->getDefinition(); 562 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 563 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 564 assert(CXXBaseDecl && "Base type is not a C++ type"); 565 566 // C++ [class]p3: 567 // If a class is marked final and it appears as a base-type-specifier in 568 // base-clause, the program is ill-formed. 569 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 570 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 571 << CXXBaseDecl->getDeclName(); 572 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 573 << CXXBaseDecl->getDeclName(); 574 return 0; 575 } 576 577 if (BaseDecl->isInvalidDecl()) 578 Class->setInvalidDecl(); 579 580 // Create the base specifier. 581 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 582 Class->getTagKind() == TTK_Class, 583 Access, TInfo, EllipsisLoc); 584} 585 586/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 587/// one entry in the base class list of a class specifier, for 588/// example: 589/// class foo : public bar, virtual private baz { 590/// 'public bar' and 'virtual private baz' are each base-specifiers. 591BaseResult 592Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 593 bool Virtual, AccessSpecifier Access, 594 ParsedType basetype, SourceLocation BaseLoc, 595 SourceLocation EllipsisLoc) { 596 if (!classdecl) 597 return true; 598 599 AdjustDeclIfTemplate(classdecl); 600 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 601 if (!Class) 602 return true; 603 604 TypeSourceInfo *TInfo = 0; 605 GetTypeFromParser(basetype, &TInfo); 606 607 if (EllipsisLoc.isInvalid() && 608 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 609 UPPC_BaseType)) 610 return true; 611 612 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 613 Virtual, Access, TInfo, 614 EllipsisLoc)) 615 return BaseSpec; 616 617 return true; 618} 619 620/// \brief Performs the actual work of attaching the given base class 621/// specifiers to a C++ class. 622bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 623 unsigned NumBases) { 624 if (NumBases == 0) 625 return false; 626 627 // Used to keep track of which base types we have already seen, so 628 // that we can properly diagnose redundant direct base types. Note 629 // that the key is always the unqualified canonical type of the base 630 // class. 631 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 632 633 // Copy non-redundant base specifiers into permanent storage. 634 unsigned NumGoodBases = 0; 635 bool Invalid = false; 636 for (unsigned idx = 0; idx < NumBases; ++idx) { 637 QualType NewBaseType 638 = Context.getCanonicalType(Bases[idx]->getType()); 639 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 640 if (!Class->hasObjectMember()) { 641 if (const RecordType *FDTTy = 642 NewBaseType.getTypePtr()->getAs<RecordType>()) 643 if (FDTTy->getDecl()->hasObjectMember()) 644 Class->setHasObjectMember(true); 645 } 646 647 if (KnownBaseTypes[NewBaseType]) { 648 // C++ [class.mi]p3: 649 // A class shall not be specified as a direct base class of a 650 // derived class more than once. 651 Diag(Bases[idx]->getSourceRange().getBegin(), 652 diag::err_duplicate_base_class) 653 << KnownBaseTypes[NewBaseType]->getType() 654 << Bases[idx]->getSourceRange(); 655 656 // Delete the duplicate base class specifier; we're going to 657 // overwrite its pointer later. 658 Context.Deallocate(Bases[idx]); 659 660 Invalid = true; 661 } else { 662 // Okay, add this new base class. 663 KnownBaseTypes[NewBaseType] = Bases[idx]; 664 Bases[NumGoodBases++] = Bases[idx]; 665 } 666 } 667 668 // Attach the remaining base class specifiers to the derived class. 669 Class->setBases(Bases, NumGoodBases); 670 671 // Delete the remaining (good) base class specifiers, since their 672 // data has been copied into the CXXRecordDecl. 673 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 674 Context.Deallocate(Bases[idx]); 675 676 return Invalid; 677} 678 679/// ActOnBaseSpecifiers - Attach the given base specifiers to the 680/// class, after checking whether there are any duplicate base 681/// classes. 682void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases, 683 unsigned NumBases) { 684 if (!ClassDecl || !Bases || !NumBases) 685 return; 686 687 AdjustDeclIfTemplate(ClassDecl); 688 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), 689 (CXXBaseSpecifier**)(Bases), NumBases); 690} 691 692static CXXRecordDecl *GetClassForType(QualType T) { 693 if (const RecordType *RT = T->getAs<RecordType>()) 694 return cast<CXXRecordDecl>(RT->getDecl()); 695 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 696 return ICT->getDecl(); 697 else 698 return 0; 699} 700 701/// \brief Determine whether the type \p Derived is a C++ class that is 702/// derived from the type \p Base. 703bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 704 if (!getLangOptions().CPlusPlus) 705 return false; 706 707 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 708 if (!DerivedRD) 709 return false; 710 711 CXXRecordDecl *BaseRD = GetClassForType(Base); 712 if (!BaseRD) 713 return false; 714 715 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 716 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 717} 718 719/// \brief Determine whether the type \p Derived is a C++ class that is 720/// derived from the type \p Base. 721bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 722 if (!getLangOptions().CPlusPlus) 723 return false; 724 725 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 726 if (!DerivedRD) 727 return false; 728 729 CXXRecordDecl *BaseRD = GetClassForType(Base); 730 if (!BaseRD) 731 return false; 732 733 return DerivedRD->isDerivedFrom(BaseRD, Paths); 734} 735 736void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 737 CXXCastPath &BasePathArray) { 738 assert(BasePathArray.empty() && "Base path array must be empty!"); 739 assert(Paths.isRecordingPaths() && "Must record paths!"); 740 741 const CXXBasePath &Path = Paths.front(); 742 743 // We first go backward and check if we have a virtual base. 744 // FIXME: It would be better if CXXBasePath had the base specifier for 745 // the nearest virtual base. 746 unsigned Start = 0; 747 for (unsigned I = Path.size(); I != 0; --I) { 748 if (Path[I - 1].Base->isVirtual()) { 749 Start = I - 1; 750 break; 751 } 752 } 753 754 // Now add all bases. 755 for (unsigned I = Start, E = Path.size(); I != E; ++I) 756 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 757} 758 759/// \brief Determine whether the given base path includes a virtual 760/// base class. 761bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) { 762 for (CXXCastPath::const_iterator B = BasePath.begin(), 763 BEnd = BasePath.end(); 764 B != BEnd; ++B) 765 if ((*B)->isVirtual()) 766 return true; 767 768 return false; 769} 770 771/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 772/// conversion (where Derived and Base are class types) is 773/// well-formed, meaning that the conversion is unambiguous (and 774/// that all of the base classes are accessible). Returns true 775/// and emits a diagnostic if the code is ill-formed, returns false 776/// otherwise. Loc is the location where this routine should point to 777/// if there is an error, and Range is the source range to highlight 778/// if there is an error. 779bool 780Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 781 unsigned InaccessibleBaseID, 782 unsigned AmbigiousBaseConvID, 783 SourceLocation Loc, SourceRange Range, 784 DeclarationName Name, 785 CXXCastPath *BasePath) { 786 // First, determine whether the path from Derived to Base is 787 // ambiguous. This is slightly more expensive than checking whether 788 // the Derived to Base conversion exists, because here we need to 789 // explore multiple paths to determine if there is an ambiguity. 790 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 791 /*DetectVirtual=*/false); 792 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 793 assert(DerivationOkay && 794 "Can only be used with a derived-to-base conversion"); 795 (void)DerivationOkay; 796 797 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 798 if (InaccessibleBaseID) { 799 // Check that the base class can be accessed. 800 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 801 InaccessibleBaseID)) { 802 case AR_inaccessible: 803 return true; 804 case AR_accessible: 805 case AR_dependent: 806 case AR_delayed: 807 break; 808 } 809 } 810 811 // Build a base path if necessary. 812 if (BasePath) 813 BuildBasePathArray(Paths, *BasePath); 814 return false; 815 } 816 817 // We know that the derived-to-base conversion is ambiguous, and 818 // we're going to produce a diagnostic. Perform the derived-to-base 819 // search just one more time to compute all of the possible paths so 820 // that we can print them out. This is more expensive than any of 821 // the previous derived-to-base checks we've done, but at this point 822 // performance isn't as much of an issue. 823 Paths.clear(); 824 Paths.setRecordingPaths(true); 825 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 826 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 827 (void)StillOkay; 828 829 // Build up a textual representation of the ambiguous paths, e.g., 830 // D -> B -> A, that will be used to illustrate the ambiguous 831 // conversions in the diagnostic. We only print one of the paths 832 // to each base class subobject. 833 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 834 835 Diag(Loc, AmbigiousBaseConvID) 836 << Derived << Base << PathDisplayStr << Range << Name; 837 return true; 838} 839 840bool 841Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 842 SourceLocation Loc, SourceRange Range, 843 CXXCastPath *BasePath, 844 bool IgnoreAccess) { 845 return CheckDerivedToBaseConversion(Derived, Base, 846 IgnoreAccess ? 0 847 : diag::err_upcast_to_inaccessible_base, 848 diag::err_ambiguous_derived_to_base_conv, 849 Loc, Range, DeclarationName(), 850 BasePath); 851} 852 853 854/// @brief Builds a string representing ambiguous paths from a 855/// specific derived class to different subobjects of the same base 856/// class. 857/// 858/// This function builds a string that can be used in error messages 859/// to show the different paths that one can take through the 860/// inheritance hierarchy to go from the derived class to different 861/// subobjects of a base class. The result looks something like this: 862/// @code 863/// struct D -> struct B -> struct A 864/// struct D -> struct C -> struct A 865/// @endcode 866std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 867 std::string PathDisplayStr; 868 std::set<unsigned> DisplayedPaths; 869 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 870 Path != Paths.end(); ++Path) { 871 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 872 // We haven't displayed a path to this particular base 873 // class subobject yet. 874 PathDisplayStr += "\n "; 875 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 876 for (CXXBasePath::const_iterator Element = Path->begin(); 877 Element != Path->end(); ++Element) 878 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 879 } 880 } 881 882 return PathDisplayStr; 883} 884 885//===----------------------------------------------------------------------===// 886// C++ class member Handling 887//===----------------------------------------------------------------------===// 888 889/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 890Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access, 891 SourceLocation ASLoc, 892 SourceLocation ColonLoc) { 893 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 894 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 895 ASLoc, ColonLoc); 896 CurContext->addHiddenDecl(ASDecl); 897 return ASDecl; 898} 899 900/// CheckOverrideControl - Check C++0x override control semantics. 901void Sema::CheckOverrideControl(const Decl *D) { 902 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D); 903 if (!MD || !MD->isVirtual()) 904 return; 905 906 if (MD->isDependentContext()) 907 return; 908 909 // C++0x [class.virtual]p3: 910 // If a virtual function is marked with the virt-specifier override and does 911 // not override a member function of a base class, 912 // the program is ill-formed. 913 bool HasOverriddenMethods = 914 MD->begin_overridden_methods() != MD->end_overridden_methods(); 915 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) { 916 Diag(MD->getLocation(), 917 diag::err_function_marked_override_not_overriding) 918 << MD->getDeclName(); 919 return; 920 } 921} 922 923/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 924/// function overrides a virtual member function marked 'final', according to 925/// C++0x [class.virtual]p3. 926bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 927 const CXXMethodDecl *Old) { 928 if (!Old->hasAttr<FinalAttr>()) 929 return false; 930 931 Diag(New->getLocation(), diag::err_final_function_overridden) 932 << New->getDeclName(); 933 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 934 return true; 935} 936 937/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 938/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 939/// bitfield width if there is one and 'InitExpr' specifies the initializer if 940/// any. 941Decl * 942Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 943 MultiTemplateParamsArg TemplateParameterLists, 944 ExprTy *BW, const VirtSpecifiers &VS, 945 ExprTy *InitExpr, bool IsDefinition, 946 bool Deleted) { 947 const DeclSpec &DS = D.getDeclSpec(); 948 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 949 DeclarationName Name = NameInfo.getName(); 950 SourceLocation Loc = NameInfo.getLoc(); 951 952 // For anonymous bitfields, the location should point to the type. 953 if (Loc.isInvalid()) 954 Loc = D.getSourceRange().getBegin(); 955 956 Expr *BitWidth = static_cast<Expr*>(BW); 957 Expr *Init = static_cast<Expr*>(InitExpr); 958 959 assert(isa<CXXRecordDecl>(CurContext)); 960 assert(!DS.isFriendSpecified()); 961 962 bool isFunc = false; 963 if (D.isFunctionDeclarator()) 964 isFunc = true; 965 else if (D.getNumTypeObjects() == 0 && 966 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) { 967 QualType TDType = GetTypeFromParser(DS.getRepAsType()); 968 isFunc = TDType->isFunctionType(); 969 } 970 971 // C++ 9.2p6: A member shall not be declared to have automatic storage 972 // duration (auto, register) or with the extern storage-class-specifier. 973 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 974 // data members and cannot be applied to names declared const or static, 975 // and cannot be applied to reference members. 976 switch (DS.getStorageClassSpec()) { 977 case DeclSpec::SCS_unspecified: 978 case DeclSpec::SCS_typedef: 979 case DeclSpec::SCS_static: 980 // FALL THROUGH. 981 break; 982 case DeclSpec::SCS_mutable: 983 if (isFunc) { 984 if (DS.getStorageClassSpecLoc().isValid()) 985 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 986 else 987 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 988 989 // FIXME: It would be nicer if the keyword was ignored only for this 990 // declarator. Otherwise we could get follow-up errors. 991 D.getMutableDeclSpec().ClearStorageClassSpecs(); 992 } 993 break; 994 default: 995 if (DS.getStorageClassSpecLoc().isValid()) 996 Diag(DS.getStorageClassSpecLoc(), 997 diag::err_storageclass_invalid_for_member); 998 else 999 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 1000 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1001 } 1002 1003 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 1004 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 1005 !isFunc); 1006 1007 Decl *Member; 1008 if (isInstField) { 1009 CXXScopeSpec &SS = D.getCXXScopeSpec(); 1010 1011 1012 if (SS.isSet() && !SS.isInvalid()) { 1013 // The user provided a superfluous scope specifier inside a class 1014 // definition: 1015 // 1016 // class X { 1017 // int X::member; 1018 // }; 1019 DeclContext *DC = 0; 1020 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext)) 1021 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification) 1022 << Name << FixItHint::CreateRemoval(SS.getRange()); 1023 else 1024 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 1025 << Name << SS.getRange(); 1026 1027 SS.clear(); 1028 } 1029 1030 // FIXME: Check for template parameters! 1031 // FIXME: Check that the name is an identifier! 1032 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 1033 AS); 1034 assert(Member && "HandleField never returns null"); 1035 } else { 1036 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition); 1037 if (!Member) { 1038 return 0; 1039 } 1040 1041 // Non-instance-fields can't have a bitfield. 1042 if (BitWidth) { 1043 if (Member->isInvalidDecl()) { 1044 // don't emit another diagnostic. 1045 } else if (isa<VarDecl>(Member)) { 1046 // C++ 9.6p3: A bit-field shall not be a static member. 1047 // "static member 'A' cannot be a bit-field" 1048 Diag(Loc, diag::err_static_not_bitfield) 1049 << Name << BitWidth->getSourceRange(); 1050 } else if (isa<TypedefDecl>(Member)) { 1051 // "typedef member 'x' cannot be a bit-field" 1052 Diag(Loc, diag::err_typedef_not_bitfield) 1053 << Name << BitWidth->getSourceRange(); 1054 } else { 1055 // A function typedef ("typedef int f(); f a;"). 1056 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 1057 Diag(Loc, diag::err_not_integral_type_bitfield) 1058 << Name << cast<ValueDecl>(Member)->getType() 1059 << BitWidth->getSourceRange(); 1060 } 1061 1062 BitWidth = 0; 1063 Member->setInvalidDecl(); 1064 } 1065 1066 Member->setAccess(AS); 1067 1068 // If we have declared a member function template, set the access of the 1069 // templated declaration as well. 1070 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 1071 FunTmpl->getTemplatedDecl()->setAccess(AS); 1072 } 1073 1074 if (VS.isOverrideSpecified()) { 1075 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 1076 if (!MD || !MD->isVirtual()) { 1077 Diag(Member->getLocStart(), 1078 diag::override_keyword_only_allowed_on_virtual_member_functions) 1079 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc()); 1080 } else 1081 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context)); 1082 } 1083 if (VS.isFinalSpecified()) { 1084 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 1085 if (!MD || !MD->isVirtual()) { 1086 Diag(Member->getLocStart(), 1087 diag::override_keyword_only_allowed_on_virtual_member_functions) 1088 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc()); 1089 } else 1090 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context)); 1091 } 1092 1093 if (VS.getLastLocation().isValid()) { 1094 // Update the end location of a method that has a virt-specifiers. 1095 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 1096 MD->setRangeEnd(VS.getLastLocation()); 1097 } 1098 1099 CheckOverrideControl(Member); 1100 1101 assert((Name || isInstField) && "No identifier for non-field ?"); 1102 1103 if (Init) 1104 AddInitializerToDecl(Member, Init, false, 1105 DS.getTypeSpecType() == DeclSpec::TST_auto); 1106 if (Deleted) // FIXME: Source location is not very good. 1107 SetDeclDeleted(Member, D.getSourceRange().getBegin()); 1108 1109 FinalizeDeclaration(Member); 1110 1111 if (isInstField) 1112 FieldCollector->Add(cast<FieldDecl>(Member)); 1113 return Member; 1114} 1115 1116/// \brief Find the direct and/or virtual base specifiers that 1117/// correspond to the given base type, for use in base initialization 1118/// within a constructor. 1119static bool FindBaseInitializer(Sema &SemaRef, 1120 CXXRecordDecl *ClassDecl, 1121 QualType BaseType, 1122 const CXXBaseSpecifier *&DirectBaseSpec, 1123 const CXXBaseSpecifier *&VirtualBaseSpec) { 1124 // First, check for a direct base class. 1125 DirectBaseSpec = 0; 1126 for (CXXRecordDecl::base_class_const_iterator Base 1127 = ClassDecl->bases_begin(); 1128 Base != ClassDecl->bases_end(); ++Base) { 1129 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 1130 // We found a direct base of this type. That's what we're 1131 // initializing. 1132 DirectBaseSpec = &*Base; 1133 break; 1134 } 1135 } 1136 1137 // Check for a virtual base class. 1138 // FIXME: We might be able to short-circuit this if we know in advance that 1139 // there are no virtual bases. 1140 VirtualBaseSpec = 0; 1141 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 1142 // We haven't found a base yet; search the class hierarchy for a 1143 // virtual base class. 1144 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1145 /*DetectVirtual=*/false); 1146 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 1147 BaseType, Paths)) { 1148 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1149 Path != Paths.end(); ++Path) { 1150 if (Path->back().Base->isVirtual()) { 1151 VirtualBaseSpec = Path->back().Base; 1152 break; 1153 } 1154 } 1155 } 1156 } 1157 1158 return DirectBaseSpec || VirtualBaseSpec; 1159} 1160 1161/// ActOnMemInitializer - Handle a C++ member initializer. 1162MemInitResult 1163Sema::ActOnMemInitializer(Decl *ConstructorD, 1164 Scope *S, 1165 CXXScopeSpec &SS, 1166 IdentifierInfo *MemberOrBase, 1167 ParsedType TemplateTypeTy, 1168 SourceLocation IdLoc, 1169 SourceLocation LParenLoc, 1170 ExprTy **Args, unsigned NumArgs, 1171 SourceLocation RParenLoc, 1172 SourceLocation EllipsisLoc) { 1173 if (!ConstructorD) 1174 return true; 1175 1176 AdjustDeclIfTemplate(ConstructorD); 1177 1178 CXXConstructorDecl *Constructor 1179 = dyn_cast<CXXConstructorDecl>(ConstructorD); 1180 if (!Constructor) { 1181 // The user wrote a constructor initializer on a function that is 1182 // not a C++ constructor. Ignore the error for now, because we may 1183 // have more member initializers coming; we'll diagnose it just 1184 // once in ActOnMemInitializers. 1185 return true; 1186 } 1187 1188 CXXRecordDecl *ClassDecl = Constructor->getParent(); 1189 1190 // C++ [class.base.init]p2: 1191 // Names in a mem-initializer-id are looked up in the scope of the 1192 // constructor's class and, if not found in that scope, are looked 1193 // up in the scope containing the constructor's definition. 1194 // [Note: if the constructor's class contains a member with the 1195 // same name as a direct or virtual base class of the class, a 1196 // mem-initializer-id naming the member or base class and composed 1197 // of a single identifier refers to the class member. A 1198 // mem-initializer-id for the hidden base class may be specified 1199 // using a qualified name. ] 1200 if (!SS.getScopeRep() && !TemplateTypeTy) { 1201 // Look for a member, first. 1202 FieldDecl *Member = 0; 1203 DeclContext::lookup_result Result 1204 = ClassDecl->lookup(MemberOrBase); 1205 if (Result.first != Result.second) { 1206 Member = dyn_cast<FieldDecl>(*Result.first); 1207 1208 if (Member) { 1209 if (EllipsisLoc.isValid()) 1210 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 1211 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1212 1213 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1214 LParenLoc, RParenLoc); 1215 } 1216 1217 // Handle anonymous union case. 1218 if (IndirectFieldDecl* IndirectField 1219 = dyn_cast<IndirectFieldDecl>(*Result.first)) { 1220 if (EllipsisLoc.isValid()) 1221 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 1222 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1223 1224 return BuildMemberInitializer(IndirectField, (Expr**)Args, 1225 NumArgs, IdLoc, 1226 LParenLoc, RParenLoc); 1227 } 1228 } 1229 } 1230 // It didn't name a member, so see if it names a class. 1231 QualType BaseType; 1232 TypeSourceInfo *TInfo = 0; 1233 1234 if (TemplateTypeTy) { 1235 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 1236 } else { 1237 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 1238 LookupParsedName(R, S, &SS); 1239 1240 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 1241 if (!TyD) { 1242 if (R.isAmbiguous()) return true; 1243 1244 // We don't want access-control diagnostics here. 1245 R.suppressDiagnostics(); 1246 1247 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 1248 bool NotUnknownSpecialization = false; 1249 DeclContext *DC = computeDeclContext(SS, false); 1250 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 1251 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 1252 1253 if (!NotUnknownSpecialization) { 1254 // When the scope specifier can refer to a member of an unknown 1255 // specialization, we take it as a type name. 1256 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 1257 SS.getWithLocInContext(Context), 1258 *MemberOrBase, IdLoc); 1259 if (BaseType.isNull()) 1260 return true; 1261 1262 R.clear(); 1263 R.setLookupName(MemberOrBase); 1264 } 1265 } 1266 1267 // If no results were found, try to correct typos. 1268 if (R.empty() && BaseType.isNull() && 1269 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) && 1270 R.isSingleResult()) { 1271 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) { 1272 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) { 1273 // We have found a non-static data member with a similar 1274 // name to what was typed; complain and initialize that 1275 // member. 1276 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1277 << MemberOrBase << true << R.getLookupName() 1278 << FixItHint::CreateReplacement(R.getNameLoc(), 1279 R.getLookupName().getAsString()); 1280 Diag(Member->getLocation(), diag::note_previous_decl) 1281 << Member->getDeclName(); 1282 1283 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1284 LParenLoc, RParenLoc); 1285 } 1286 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) { 1287 const CXXBaseSpecifier *DirectBaseSpec; 1288 const CXXBaseSpecifier *VirtualBaseSpec; 1289 if (FindBaseInitializer(*this, ClassDecl, 1290 Context.getTypeDeclType(Type), 1291 DirectBaseSpec, VirtualBaseSpec)) { 1292 // We have found a direct or virtual base class with a 1293 // similar name to what was typed; complain and initialize 1294 // that base class. 1295 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1296 << MemberOrBase << false << R.getLookupName() 1297 << FixItHint::CreateReplacement(R.getNameLoc(), 1298 R.getLookupName().getAsString()); 1299 1300 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 1301 : VirtualBaseSpec; 1302 Diag(BaseSpec->getSourceRange().getBegin(), 1303 diag::note_base_class_specified_here) 1304 << BaseSpec->getType() 1305 << BaseSpec->getSourceRange(); 1306 1307 TyD = Type; 1308 } 1309 } 1310 } 1311 1312 if (!TyD && BaseType.isNull()) { 1313 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 1314 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1315 return true; 1316 } 1317 } 1318 1319 if (BaseType.isNull()) { 1320 BaseType = Context.getTypeDeclType(TyD); 1321 if (SS.isSet()) { 1322 NestedNameSpecifier *Qualifier = 1323 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1324 1325 // FIXME: preserve source range information 1326 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 1327 } 1328 } 1329 } 1330 1331 if (!TInfo) 1332 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 1333 1334 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs, 1335 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc); 1336} 1337 1338/// Checks an initializer expression for use of uninitialized fields, such as 1339/// containing the field that is being initialized. Returns true if there is an 1340/// uninitialized field was used an updates the SourceLocation parameter; false 1341/// otherwise. 1342static bool InitExprContainsUninitializedFields(const Stmt *S, 1343 const ValueDecl *LhsField, 1344 SourceLocation *L) { 1345 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField)); 1346 1347 if (isa<CallExpr>(S)) { 1348 // Do not descend into function calls or constructors, as the use 1349 // of an uninitialized field may be valid. One would have to inspect 1350 // the contents of the function/ctor to determine if it is safe or not. 1351 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers 1352 // may be safe, depending on what the function/ctor does. 1353 return false; 1354 } 1355 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) { 1356 const NamedDecl *RhsField = ME->getMemberDecl(); 1357 1358 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) { 1359 // The member expression points to a static data member. 1360 assert(VD->isStaticDataMember() && 1361 "Member points to non-static data member!"); 1362 (void)VD; 1363 return false; 1364 } 1365 1366 if (isa<EnumConstantDecl>(RhsField)) { 1367 // The member expression points to an enum. 1368 return false; 1369 } 1370 1371 if (RhsField == LhsField) { 1372 // Initializing a field with itself. Throw a warning. 1373 // But wait; there are exceptions! 1374 // Exception #1: The field may not belong to this record. 1375 // e.g. Foo(const Foo& rhs) : A(rhs.A) {} 1376 const Expr *base = ME->getBase(); 1377 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) { 1378 // Even though the field matches, it does not belong to this record. 1379 return false; 1380 } 1381 // None of the exceptions triggered; return true to indicate an 1382 // uninitialized field was used. 1383 *L = ME->getMemberLoc(); 1384 return true; 1385 } 1386 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) { 1387 // sizeof/alignof doesn't reference contents, do not warn. 1388 return false; 1389 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) { 1390 // address-of doesn't reference contents (the pointer may be dereferenced 1391 // in the same expression but it would be rare; and weird). 1392 if (UOE->getOpcode() == UO_AddrOf) 1393 return false; 1394 } 1395 for (Stmt::const_child_range it = S->children(); it; ++it) { 1396 if (!*it) { 1397 // An expression such as 'member(arg ?: "")' may trigger this. 1398 continue; 1399 } 1400 if (InitExprContainsUninitializedFields(*it, LhsField, L)) 1401 return true; 1402 } 1403 return false; 1404} 1405 1406MemInitResult 1407Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args, 1408 unsigned NumArgs, SourceLocation IdLoc, 1409 SourceLocation LParenLoc, 1410 SourceLocation RParenLoc) { 1411 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 1412 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 1413 assert((DirectMember || IndirectMember) && 1414 "Member must be a FieldDecl or IndirectFieldDecl"); 1415 1416 if (Member->isInvalidDecl()) 1417 return true; 1418 1419 // Diagnose value-uses of fields to initialize themselves, e.g. 1420 // foo(foo) 1421 // where foo is not also a parameter to the constructor. 1422 // TODO: implement -Wuninitialized and fold this into that framework. 1423 for (unsigned i = 0; i < NumArgs; ++i) { 1424 SourceLocation L; 1425 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) { 1426 // FIXME: Return true in the case when other fields are used before being 1427 // uninitialized. For example, let this field be the i'th field. When 1428 // initializing the i'th field, throw a warning if any of the >= i'th 1429 // fields are used, as they are not yet initialized. 1430 // Right now we are only handling the case where the i'th field uses 1431 // itself in its initializer. 1432 Diag(L, diag::warn_field_is_uninit); 1433 } 1434 } 1435 1436 bool HasDependentArg = false; 1437 for (unsigned i = 0; i < NumArgs; i++) 1438 HasDependentArg |= Args[i]->isTypeDependent(); 1439 1440 Expr *Init; 1441 if (Member->getType()->isDependentType() || HasDependentArg) { 1442 // Can't check initialization for a member of dependent type or when 1443 // any of the arguments are type-dependent expressions. 1444 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1445 RParenLoc); 1446 1447 // Erase any temporaries within this evaluation context; we're not 1448 // going to track them in the AST, since we'll be rebuilding the 1449 // ASTs during template instantiation. 1450 ExprTemporaries.erase( 1451 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1452 ExprTemporaries.end()); 1453 } else { 1454 // Initialize the member. 1455 InitializedEntity MemberEntity = 1456 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0) 1457 : InitializedEntity::InitializeMember(IndirectMember, 0); 1458 InitializationKind Kind = 1459 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc); 1460 1461 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 1462 1463 ExprResult MemberInit = 1464 InitSeq.Perform(*this, MemberEntity, Kind, 1465 MultiExprArg(*this, Args, NumArgs), 0); 1466 if (MemberInit.isInvalid()) 1467 return true; 1468 1469 CheckImplicitConversions(MemberInit.get(), LParenLoc); 1470 1471 // C++0x [class.base.init]p7: 1472 // The initialization of each base and member constitutes a 1473 // full-expression. 1474 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 1475 if (MemberInit.isInvalid()) 1476 return true; 1477 1478 // If we are in a dependent context, template instantiation will 1479 // perform this type-checking again. Just save the arguments that we 1480 // received in a ParenListExpr. 1481 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1482 // of the information that we have about the member 1483 // initializer. However, deconstructing the ASTs is a dicey process, 1484 // and this approach is far more likely to get the corner cases right. 1485 if (CurContext->isDependentContext()) 1486 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1487 RParenLoc); 1488 else 1489 Init = MemberInit.get(); 1490 } 1491 1492 if (DirectMember) { 1493 return new (Context) CXXCtorInitializer(Context, DirectMember, 1494 IdLoc, LParenLoc, Init, 1495 RParenLoc); 1496 } else { 1497 return new (Context) CXXCtorInitializer(Context, IndirectMember, 1498 IdLoc, LParenLoc, Init, 1499 RParenLoc); 1500 } 1501} 1502 1503MemInitResult 1504Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, 1505 Expr **Args, unsigned NumArgs, 1506 SourceLocation NameLoc, 1507 SourceLocation LParenLoc, 1508 SourceLocation RParenLoc, 1509 CXXRecordDecl *ClassDecl) { 1510 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 1511 if (!LangOpts.CPlusPlus0x) 1512 return Diag(Loc, diag::err_delegation_0x_only) 1513 << TInfo->getTypeLoc().getLocalSourceRange(); 1514 1515 // Initialize the object. 1516 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 1517 QualType(ClassDecl->getTypeForDecl(), 0)); 1518 InitializationKind Kind = 1519 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc); 1520 1521 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs); 1522 1523 ExprResult DelegationInit = 1524 InitSeq.Perform(*this, DelegationEntity, Kind, 1525 MultiExprArg(*this, Args, NumArgs), 0); 1526 if (DelegationInit.isInvalid()) 1527 return true; 1528 1529 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get()); 1530 CXXConstructorDecl *Constructor = ConExpr->getConstructor(); 1531 assert(Constructor && "Delegating constructor with no target?"); 1532 1533 CheckImplicitConversions(DelegationInit.get(), LParenLoc); 1534 1535 // C++0x [class.base.init]p7: 1536 // The initialization of each base and member constitutes a 1537 // full-expression. 1538 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit); 1539 if (DelegationInit.isInvalid()) 1540 return true; 1541 1542 // If we are in a dependent context, template instantiation will 1543 // perform this type-checking again. Just save the arguments that we 1544 // received in a ParenListExpr. 1545 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1546 // of the information that we have about the base 1547 // initializer. However, deconstructing the ASTs is a dicey process, 1548 // and this approach is far more likely to get the corner cases right. 1549 if (CurContext->isDependentContext()) { 1550 ExprResult Init 1551 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, 1552 NumArgs, RParenLoc)); 1553 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, 1554 Constructor, Init.takeAs<Expr>(), 1555 RParenLoc); 1556 } 1557 1558 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor, 1559 DelegationInit.takeAs<Expr>(), 1560 RParenLoc); 1561} 1562 1563MemInitResult 1564Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 1565 Expr **Args, unsigned NumArgs, 1566 SourceLocation LParenLoc, SourceLocation RParenLoc, 1567 CXXRecordDecl *ClassDecl, 1568 SourceLocation EllipsisLoc) { 1569 bool HasDependentArg = false; 1570 for (unsigned i = 0; i < NumArgs; i++) 1571 HasDependentArg |= Args[i]->isTypeDependent(); 1572 1573 SourceLocation BaseLoc 1574 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 1575 1576 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 1577 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 1578 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1579 1580 // C++ [class.base.init]p2: 1581 // [...] Unless the mem-initializer-id names a nonstatic data 1582 // member of the constructor's class or a direct or virtual base 1583 // of that class, the mem-initializer is ill-formed. A 1584 // mem-initializer-list can initialize a base class using any 1585 // name that denotes that base class type. 1586 bool Dependent = BaseType->isDependentType() || HasDependentArg; 1587 1588 if (EllipsisLoc.isValid()) { 1589 // This is a pack expansion. 1590 if (!BaseType->containsUnexpandedParameterPack()) { 1591 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 1592 << SourceRange(BaseLoc, RParenLoc); 1593 1594 EllipsisLoc = SourceLocation(); 1595 } 1596 } else { 1597 // Check for any unexpanded parameter packs. 1598 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 1599 return true; 1600 1601 for (unsigned I = 0; I != NumArgs; ++I) 1602 if (DiagnoseUnexpandedParameterPack(Args[I])) 1603 return true; 1604 } 1605 1606 // Check for direct and virtual base classes. 1607 const CXXBaseSpecifier *DirectBaseSpec = 0; 1608 const CXXBaseSpecifier *VirtualBaseSpec = 0; 1609 if (!Dependent) { 1610 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 1611 BaseType)) 1612 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc, 1613 LParenLoc, RParenLoc, ClassDecl); 1614 1615 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 1616 VirtualBaseSpec); 1617 1618 // C++ [base.class.init]p2: 1619 // Unless the mem-initializer-id names a nonstatic data member of the 1620 // constructor's class or a direct or virtual base of that class, the 1621 // mem-initializer is ill-formed. 1622 if (!DirectBaseSpec && !VirtualBaseSpec) { 1623 // If the class has any dependent bases, then it's possible that 1624 // one of those types will resolve to the same type as 1625 // BaseType. Therefore, just treat this as a dependent base 1626 // class initialization. FIXME: Should we try to check the 1627 // initialization anyway? It seems odd. 1628 if (ClassDecl->hasAnyDependentBases()) 1629 Dependent = true; 1630 else 1631 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 1632 << BaseType << Context.getTypeDeclType(ClassDecl) 1633 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1634 } 1635 } 1636 1637 if (Dependent) { 1638 // Can't check initialization for a base of dependent type or when 1639 // any of the arguments are type-dependent expressions. 1640 ExprResult BaseInit 1641 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1642 RParenLoc)); 1643 1644 // Erase any temporaries within this evaluation context; we're not 1645 // going to track them in the AST, since we'll be rebuilding the 1646 // ASTs during template instantiation. 1647 ExprTemporaries.erase( 1648 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1649 ExprTemporaries.end()); 1650 1651 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 1652 /*IsVirtual=*/false, 1653 LParenLoc, 1654 BaseInit.takeAs<Expr>(), 1655 RParenLoc, 1656 EllipsisLoc); 1657 } 1658 1659 // C++ [base.class.init]p2: 1660 // If a mem-initializer-id is ambiguous because it designates both 1661 // a direct non-virtual base class and an inherited virtual base 1662 // class, the mem-initializer is ill-formed. 1663 if (DirectBaseSpec && VirtualBaseSpec) 1664 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 1665 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1666 1667 CXXBaseSpecifier *BaseSpec 1668 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 1669 if (!BaseSpec) 1670 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 1671 1672 // Initialize the base. 1673 InitializedEntity BaseEntity = 1674 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 1675 InitializationKind Kind = 1676 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc); 1677 1678 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 1679 1680 ExprResult BaseInit = 1681 InitSeq.Perform(*this, BaseEntity, Kind, 1682 MultiExprArg(*this, Args, NumArgs), 0); 1683 if (BaseInit.isInvalid()) 1684 return true; 1685 1686 CheckImplicitConversions(BaseInit.get(), LParenLoc); 1687 1688 // C++0x [class.base.init]p7: 1689 // The initialization of each base and member constitutes a 1690 // full-expression. 1691 BaseInit = MaybeCreateExprWithCleanups(BaseInit); 1692 if (BaseInit.isInvalid()) 1693 return true; 1694 1695 // If we are in a dependent context, template instantiation will 1696 // perform this type-checking again. Just save the arguments that we 1697 // received in a ParenListExpr. 1698 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1699 // of the information that we have about the base 1700 // initializer. However, deconstructing the ASTs is a dicey process, 1701 // and this approach is far more likely to get the corner cases right. 1702 if (CurContext->isDependentContext()) { 1703 ExprResult Init 1704 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1705 RParenLoc)); 1706 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 1707 BaseSpec->isVirtual(), 1708 LParenLoc, 1709 Init.takeAs<Expr>(), 1710 RParenLoc, 1711 EllipsisLoc); 1712 } 1713 1714 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 1715 BaseSpec->isVirtual(), 1716 LParenLoc, 1717 BaseInit.takeAs<Expr>(), 1718 RParenLoc, 1719 EllipsisLoc); 1720} 1721 1722/// ImplicitInitializerKind - How an implicit base or member initializer should 1723/// initialize its base or member. 1724enum ImplicitInitializerKind { 1725 IIK_Default, 1726 IIK_Copy, 1727 IIK_Move 1728}; 1729 1730static bool 1731BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 1732 ImplicitInitializerKind ImplicitInitKind, 1733 CXXBaseSpecifier *BaseSpec, 1734 bool IsInheritedVirtualBase, 1735 CXXCtorInitializer *&CXXBaseInit) { 1736 InitializedEntity InitEntity 1737 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 1738 IsInheritedVirtualBase); 1739 1740 ExprResult BaseInit; 1741 1742 switch (ImplicitInitKind) { 1743 case IIK_Default: { 1744 InitializationKind InitKind 1745 = InitializationKind::CreateDefault(Constructor->getLocation()); 1746 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 1747 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 1748 MultiExprArg(SemaRef, 0, 0)); 1749 break; 1750 } 1751 1752 case IIK_Copy: { 1753 ParmVarDecl *Param = Constructor->getParamDecl(0); 1754 QualType ParamType = Param->getType().getNonReferenceType(); 1755 1756 Expr *CopyCtorArg = 1757 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param, 1758 Constructor->getLocation(), ParamType, 1759 VK_LValue, 0); 1760 1761 // Cast to the base class to avoid ambiguities. 1762 QualType ArgTy = 1763 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 1764 ParamType.getQualifiers()); 1765 1766 CXXCastPath BasePath; 1767 BasePath.push_back(BaseSpec); 1768 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 1769 CK_UncheckedDerivedToBase, 1770 VK_LValue, &BasePath); 1771 1772 InitializationKind InitKind 1773 = InitializationKind::CreateDirect(Constructor->getLocation(), 1774 SourceLocation(), SourceLocation()); 1775 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 1776 &CopyCtorArg, 1); 1777 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 1778 MultiExprArg(&CopyCtorArg, 1)); 1779 break; 1780 } 1781 1782 case IIK_Move: 1783 assert(false && "Unhandled initializer kind!"); 1784 } 1785 1786 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 1787 if (BaseInit.isInvalid()) 1788 return true; 1789 1790 CXXBaseInit = 1791 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 1792 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 1793 SourceLocation()), 1794 BaseSpec->isVirtual(), 1795 SourceLocation(), 1796 BaseInit.takeAs<Expr>(), 1797 SourceLocation(), 1798 SourceLocation()); 1799 1800 return false; 1801} 1802 1803static bool 1804BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 1805 ImplicitInitializerKind ImplicitInitKind, 1806 FieldDecl *Field, 1807 CXXCtorInitializer *&CXXMemberInit) { 1808 if (Field->isInvalidDecl()) 1809 return true; 1810 1811 SourceLocation Loc = Constructor->getLocation(); 1812 1813 if (ImplicitInitKind == IIK_Copy) { 1814 ParmVarDecl *Param = Constructor->getParamDecl(0); 1815 QualType ParamType = Param->getType().getNonReferenceType(); 1816 1817 Expr *MemberExprBase = 1818 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param, 1819 Loc, ParamType, VK_LValue, 0); 1820 1821 // Build a reference to this field within the parameter. 1822 CXXScopeSpec SS; 1823 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 1824 Sema::LookupMemberName); 1825 MemberLookup.addDecl(Field, AS_public); 1826 MemberLookup.resolveKind(); 1827 ExprResult CopyCtorArg 1828 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 1829 ParamType, Loc, 1830 /*IsArrow=*/false, 1831 SS, 1832 /*FirstQualifierInScope=*/0, 1833 MemberLookup, 1834 /*TemplateArgs=*/0); 1835 if (CopyCtorArg.isInvalid()) 1836 return true; 1837 1838 // When the field we are copying is an array, create index variables for 1839 // each dimension of the array. We use these index variables to subscript 1840 // the source array, and other clients (e.g., CodeGen) will perform the 1841 // necessary iteration with these index variables. 1842 llvm::SmallVector<VarDecl *, 4> IndexVariables; 1843 QualType BaseType = Field->getType(); 1844 QualType SizeType = SemaRef.Context.getSizeType(); 1845 while (const ConstantArrayType *Array 1846 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 1847 // Create the iteration variable for this array index. 1848 IdentifierInfo *IterationVarName = 0; 1849 { 1850 llvm::SmallString<8> Str; 1851 llvm::raw_svector_ostream OS(Str); 1852 OS << "__i" << IndexVariables.size(); 1853 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 1854 } 1855 VarDecl *IterationVar 1856 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc, 1857 IterationVarName, SizeType, 1858 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 1859 SC_None, SC_None); 1860 IndexVariables.push_back(IterationVar); 1861 1862 // Create a reference to the iteration variable. 1863 ExprResult IterationVarRef 1864 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc); 1865 assert(!IterationVarRef.isInvalid() && 1866 "Reference to invented variable cannot fail!"); 1867 1868 // Subscript the array with this iteration variable. 1869 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(), 1870 Loc, 1871 IterationVarRef.take(), 1872 Loc); 1873 if (CopyCtorArg.isInvalid()) 1874 return true; 1875 1876 BaseType = Array->getElementType(); 1877 } 1878 1879 // Construct the entity that we will be initializing. For an array, this 1880 // will be first element in the array, which may require several levels 1881 // of array-subscript entities. 1882 llvm::SmallVector<InitializedEntity, 4> Entities; 1883 Entities.reserve(1 + IndexVariables.size()); 1884 Entities.push_back(InitializedEntity::InitializeMember(Field)); 1885 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 1886 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 1887 0, 1888 Entities.back())); 1889 1890 // Direct-initialize to use the copy constructor. 1891 InitializationKind InitKind = 1892 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 1893 1894 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>(); 1895 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 1896 &CopyCtorArgE, 1); 1897 1898 ExprResult MemberInit 1899 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 1900 MultiExprArg(&CopyCtorArgE, 1)); 1901 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 1902 if (MemberInit.isInvalid()) 1903 return true; 1904 1905 CXXMemberInit 1906 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc, 1907 MemberInit.takeAs<Expr>(), Loc, 1908 IndexVariables.data(), 1909 IndexVariables.size()); 1910 return false; 1911 } 1912 1913 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!"); 1914 1915 QualType FieldBaseElementType = 1916 SemaRef.Context.getBaseElementType(Field->getType()); 1917 1918 if (FieldBaseElementType->isRecordType()) { 1919 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 1920 InitializationKind InitKind = 1921 InitializationKind::CreateDefault(Loc); 1922 1923 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 1924 ExprResult MemberInit = 1925 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg()); 1926 1927 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 1928 if (MemberInit.isInvalid()) 1929 return true; 1930 1931 CXXMemberInit = 1932 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 1933 Field, Loc, Loc, 1934 MemberInit.get(), 1935 Loc); 1936 return false; 1937 } 1938 1939 if (FieldBaseElementType->isReferenceType()) { 1940 SemaRef.Diag(Constructor->getLocation(), 1941 diag::err_uninitialized_member_in_ctor) 1942 << (int)Constructor->isImplicit() 1943 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 1944 << 0 << Field->getDeclName(); 1945 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 1946 return true; 1947 } 1948 1949 if (FieldBaseElementType.isConstQualified()) { 1950 SemaRef.Diag(Constructor->getLocation(), 1951 diag::err_uninitialized_member_in_ctor) 1952 << (int)Constructor->isImplicit() 1953 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 1954 << 1 << Field->getDeclName(); 1955 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 1956 return true; 1957 } 1958 1959 // Nothing to initialize. 1960 CXXMemberInit = 0; 1961 return false; 1962} 1963 1964namespace { 1965struct BaseAndFieldInfo { 1966 Sema &S; 1967 CXXConstructorDecl *Ctor; 1968 bool AnyErrorsInInits; 1969 ImplicitInitializerKind IIK; 1970 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 1971 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit; 1972 1973 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 1974 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 1975 // FIXME: Handle implicit move constructors. 1976 if (Ctor->isImplicit() && Ctor->isCopyConstructor()) 1977 IIK = IIK_Copy; 1978 else 1979 IIK = IIK_Default; 1980 } 1981}; 1982} 1983 1984static bool CollectFieldInitializer(BaseAndFieldInfo &Info, 1985 FieldDecl *Top, FieldDecl *Field) { 1986 1987 // Overwhelmingly common case: we have a direct initializer for this field. 1988 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) { 1989 Info.AllToInit.push_back(Init); 1990 return false; 1991 } 1992 1993 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) { 1994 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>(); 1995 assert(FieldClassType && "anonymous struct/union without record type"); 1996 CXXRecordDecl *FieldClassDecl 1997 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1998 1999 // Even though union members never have non-trivial default 2000 // constructions in C++03, we still build member initializers for aggregate 2001 // record types which can be union members, and C++0x allows non-trivial 2002 // default constructors for union members, so we ensure that only one 2003 // member is initialized for these. 2004 if (FieldClassDecl->isUnion()) { 2005 // First check for an explicit initializer for one field. 2006 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 2007 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 2008 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) { 2009 Info.AllToInit.push_back(Init); 2010 2011 // Once we've initialized a field of an anonymous union, the union 2012 // field in the class is also initialized, so exit immediately. 2013 return false; 2014 } else if ((*FA)->isAnonymousStructOrUnion()) { 2015 if (CollectFieldInitializer(Info, Top, *FA)) 2016 return true; 2017 } 2018 } 2019 2020 // Fallthrough and construct a default initializer for the union as 2021 // a whole, which can call its default constructor if such a thing exists 2022 // (C++0x perhaps). FIXME: It's not clear that this is the correct 2023 // behavior going forward with C++0x, when anonymous unions there are 2024 // finalized, we should revisit this. 2025 } else { 2026 // For structs, we simply descend through to initialize all members where 2027 // necessary. 2028 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 2029 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 2030 if (CollectFieldInitializer(Info, Top, *FA)) 2031 return true; 2032 } 2033 } 2034 } 2035 2036 // Don't try to build an implicit initializer if there were semantic 2037 // errors in any of the initializers (and therefore we might be 2038 // missing some that the user actually wrote). 2039 if (Info.AnyErrorsInInits) 2040 return false; 2041 2042 CXXCtorInitializer *Init = 0; 2043 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init)) 2044 return true; 2045 2046 if (Init) 2047 Info.AllToInit.push_back(Init); 2048 2049 return false; 2050} 2051 2052bool 2053Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, 2054 CXXCtorInitializer **Initializers, 2055 unsigned NumInitializers, 2056 bool AnyErrors) { 2057 if (Constructor->getDeclContext()->isDependentContext()) { 2058 // Just store the initializers as written, they will be checked during 2059 // instantiation. 2060 if (NumInitializers > 0) { 2061 Constructor->setNumCtorInitializers(NumInitializers); 2062 CXXCtorInitializer **baseOrMemberInitializers = 2063 new (Context) CXXCtorInitializer*[NumInitializers]; 2064 memcpy(baseOrMemberInitializers, Initializers, 2065 NumInitializers * sizeof(CXXCtorInitializer*)); 2066 Constructor->setCtorInitializers(baseOrMemberInitializers); 2067 } 2068 2069 return false; 2070 } 2071 2072 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 2073 2074 // We need to build the initializer AST according to order of construction 2075 // and not what user specified in the Initializers list. 2076 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 2077 if (!ClassDecl) 2078 return true; 2079 2080 bool HadError = false; 2081 2082 for (unsigned i = 0; i < NumInitializers; i++) { 2083 CXXCtorInitializer *Member = Initializers[i]; 2084 2085 if (Member->isBaseInitializer()) 2086 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 2087 else 2088 Info.AllBaseFields[Member->getAnyMember()] = Member; 2089 } 2090 2091 // Keep track of the direct virtual bases. 2092 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 2093 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 2094 E = ClassDecl->bases_end(); I != E; ++I) { 2095 if (I->isVirtual()) 2096 DirectVBases.insert(I); 2097 } 2098 2099 // Push virtual bases before others. 2100 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2101 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2102 2103 if (CXXCtorInitializer *Value 2104 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 2105 Info.AllToInit.push_back(Value); 2106 } else if (!AnyErrors) { 2107 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 2108 CXXCtorInitializer *CXXBaseInit; 2109 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 2110 VBase, IsInheritedVirtualBase, 2111 CXXBaseInit)) { 2112 HadError = true; 2113 continue; 2114 } 2115 2116 Info.AllToInit.push_back(CXXBaseInit); 2117 } 2118 } 2119 2120 // Non-virtual bases. 2121 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2122 E = ClassDecl->bases_end(); Base != E; ++Base) { 2123 // Virtuals are in the virtual base list and already constructed. 2124 if (Base->isVirtual()) 2125 continue; 2126 2127 if (CXXCtorInitializer *Value 2128 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 2129 Info.AllToInit.push_back(Value); 2130 } else if (!AnyErrors) { 2131 CXXCtorInitializer *CXXBaseInit; 2132 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 2133 Base, /*IsInheritedVirtualBase=*/false, 2134 CXXBaseInit)) { 2135 HadError = true; 2136 continue; 2137 } 2138 2139 Info.AllToInit.push_back(CXXBaseInit); 2140 } 2141 } 2142 2143 // Fields. 2144 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2145 E = ClassDecl->field_end(); Field != E; ++Field) { 2146 if ((*Field)->getType()->isIncompleteArrayType()) { 2147 assert(ClassDecl->hasFlexibleArrayMember() && 2148 "Incomplete array type is not valid"); 2149 continue; 2150 } 2151 if (CollectFieldInitializer(Info, *Field, *Field)) 2152 HadError = true; 2153 } 2154 2155 NumInitializers = Info.AllToInit.size(); 2156 if (NumInitializers > 0) { 2157 Constructor->setNumCtorInitializers(NumInitializers); 2158 CXXCtorInitializer **baseOrMemberInitializers = 2159 new (Context) CXXCtorInitializer*[NumInitializers]; 2160 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 2161 NumInitializers * sizeof(CXXCtorInitializer*)); 2162 Constructor->setCtorInitializers(baseOrMemberInitializers); 2163 2164 // Constructors implicitly reference the base and member 2165 // destructors. 2166 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 2167 Constructor->getParent()); 2168 } 2169 2170 return HadError; 2171} 2172 2173static void *GetKeyForTopLevelField(FieldDecl *Field) { 2174 // For anonymous unions, use the class declaration as the key. 2175 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 2176 if (RT->getDecl()->isAnonymousStructOrUnion()) 2177 return static_cast<void *>(RT->getDecl()); 2178 } 2179 return static_cast<void *>(Field); 2180} 2181 2182static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 2183 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr()); 2184} 2185 2186static void *GetKeyForMember(ASTContext &Context, 2187 CXXCtorInitializer *Member) { 2188 if (!Member->isAnyMemberInitializer()) 2189 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 2190 2191 // For fields injected into the class via declaration of an anonymous union, 2192 // use its anonymous union class declaration as the unique key. 2193 FieldDecl *Field = Member->getAnyMember(); 2194 2195 // If the field is a member of an anonymous struct or union, our key 2196 // is the anonymous record decl that's a direct child of the class. 2197 RecordDecl *RD = Field->getParent(); 2198 if (RD->isAnonymousStructOrUnion()) { 2199 while (true) { 2200 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext()); 2201 if (Parent->isAnonymousStructOrUnion()) 2202 RD = Parent; 2203 else 2204 break; 2205 } 2206 2207 return static_cast<void *>(RD); 2208 } 2209 2210 return static_cast<void *>(Field); 2211} 2212 2213static void 2214DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, 2215 const CXXConstructorDecl *Constructor, 2216 CXXCtorInitializer **Inits, 2217 unsigned NumInits) { 2218 if (Constructor->getDeclContext()->isDependentContext()) 2219 return; 2220 2221 // Don't check initializers order unless the warning is enabled at the 2222 // location of at least one initializer. 2223 bool ShouldCheckOrder = false; 2224 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 2225 CXXCtorInitializer *Init = Inits[InitIndex]; 2226 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order, 2227 Init->getSourceLocation()) 2228 != Diagnostic::Ignored) { 2229 ShouldCheckOrder = true; 2230 break; 2231 } 2232 } 2233 if (!ShouldCheckOrder) 2234 return; 2235 2236 // Build the list of bases and members in the order that they'll 2237 // actually be initialized. The explicit initializers should be in 2238 // this same order but may be missing things. 2239 llvm::SmallVector<const void*, 32> IdealInitKeys; 2240 2241 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 2242 2243 // 1. Virtual bases. 2244 for (CXXRecordDecl::base_class_const_iterator VBase = 2245 ClassDecl->vbases_begin(), 2246 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 2247 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 2248 2249 // 2. Non-virtual bases. 2250 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 2251 E = ClassDecl->bases_end(); Base != E; ++Base) { 2252 if (Base->isVirtual()) 2253 continue; 2254 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 2255 } 2256 2257 // 3. Direct fields. 2258 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2259 E = ClassDecl->field_end(); Field != E; ++Field) 2260 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field)); 2261 2262 unsigned NumIdealInits = IdealInitKeys.size(); 2263 unsigned IdealIndex = 0; 2264 2265 CXXCtorInitializer *PrevInit = 0; 2266 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 2267 CXXCtorInitializer *Init = Inits[InitIndex]; 2268 void *InitKey = GetKeyForMember(SemaRef.Context, Init); 2269 2270 // Scan forward to try to find this initializer in the idealized 2271 // initializers list. 2272 for (; IdealIndex != NumIdealInits; ++IdealIndex) 2273 if (InitKey == IdealInitKeys[IdealIndex]) 2274 break; 2275 2276 // If we didn't find this initializer, it must be because we 2277 // scanned past it on a previous iteration. That can only 2278 // happen if we're out of order; emit a warning. 2279 if (IdealIndex == NumIdealInits && PrevInit) { 2280 Sema::SemaDiagnosticBuilder D = 2281 SemaRef.Diag(PrevInit->getSourceLocation(), 2282 diag::warn_initializer_out_of_order); 2283 2284 if (PrevInit->isAnyMemberInitializer()) 2285 D << 0 << PrevInit->getAnyMember()->getDeclName(); 2286 else 2287 D << 1 << PrevInit->getBaseClassInfo()->getType(); 2288 2289 if (Init->isAnyMemberInitializer()) 2290 D << 0 << Init->getAnyMember()->getDeclName(); 2291 else 2292 D << 1 << Init->getBaseClassInfo()->getType(); 2293 2294 // Move back to the initializer's location in the ideal list. 2295 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 2296 if (InitKey == IdealInitKeys[IdealIndex]) 2297 break; 2298 2299 assert(IdealIndex != NumIdealInits && 2300 "initializer not found in initializer list"); 2301 } 2302 2303 PrevInit = Init; 2304 } 2305} 2306 2307namespace { 2308bool CheckRedundantInit(Sema &S, 2309 CXXCtorInitializer *Init, 2310 CXXCtorInitializer *&PrevInit) { 2311 if (!PrevInit) { 2312 PrevInit = Init; 2313 return false; 2314 } 2315 2316 if (FieldDecl *Field = Init->getMember()) 2317 S.Diag(Init->getSourceLocation(), 2318 diag::err_multiple_mem_initialization) 2319 << Field->getDeclName() 2320 << Init->getSourceRange(); 2321 else { 2322 const Type *BaseClass = Init->getBaseClass(); 2323 assert(BaseClass && "neither field nor base"); 2324 S.Diag(Init->getSourceLocation(), 2325 diag::err_multiple_base_initialization) 2326 << QualType(BaseClass, 0) 2327 << Init->getSourceRange(); 2328 } 2329 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 2330 << 0 << PrevInit->getSourceRange(); 2331 2332 return true; 2333} 2334 2335typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 2336typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 2337 2338bool CheckRedundantUnionInit(Sema &S, 2339 CXXCtorInitializer *Init, 2340 RedundantUnionMap &Unions) { 2341 FieldDecl *Field = Init->getAnyMember(); 2342 RecordDecl *Parent = Field->getParent(); 2343 if (!Parent->isAnonymousStructOrUnion()) 2344 return false; 2345 2346 NamedDecl *Child = Field; 2347 do { 2348 if (Parent->isUnion()) { 2349 UnionEntry &En = Unions[Parent]; 2350 if (En.first && En.first != Child) { 2351 S.Diag(Init->getSourceLocation(), 2352 diag::err_multiple_mem_union_initialization) 2353 << Field->getDeclName() 2354 << Init->getSourceRange(); 2355 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 2356 << 0 << En.second->getSourceRange(); 2357 return true; 2358 } else if (!En.first) { 2359 En.first = Child; 2360 En.second = Init; 2361 } 2362 } 2363 2364 Child = Parent; 2365 Parent = cast<RecordDecl>(Parent->getDeclContext()); 2366 } while (Parent->isAnonymousStructOrUnion()); 2367 2368 return false; 2369} 2370} 2371 2372/// ActOnMemInitializers - Handle the member initializers for a constructor. 2373void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 2374 SourceLocation ColonLoc, 2375 MemInitTy **meminits, unsigned NumMemInits, 2376 bool AnyErrors) { 2377 if (!ConstructorDecl) 2378 return; 2379 2380 AdjustDeclIfTemplate(ConstructorDecl); 2381 2382 CXXConstructorDecl *Constructor 2383 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 2384 2385 if (!Constructor) { 2386 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 2387 return; 2388 } 2389 2390 CXXCtorInitializer **MemInits = 2391 reinterpret_cast<CXXCtorInitializer **>(meminits); 2392 2393 // Mapping for the duplicate initializers check. 2394 // For member initializers, this is keyed with a FieldDecl*. 2395 // For base initializers, this is keyed with a Type*. 2396 llvm::DenseMap<void*, CXXCtorInitializer *> Members; 2397 2398 // Mapping for the inconsistent anonymous-union initializers check. 2399 RedundantUnionMap MemberUnions; 2400 2401 bool HadError = false; 2402 for (unsigned i = 0; i < NumMemInits; i++) { 2403 CXXCtorInitializer *Init = MemInits[i]; 2404 2405 // Set the source order index. 2406 Init->setSourceOrder(i); 2407 2408 if (Init->isAnyMemberInitializer()) { 2409 FieldDecl *Field = Init->getAnyMember(); 2410 if (CheckRedundantInit(*this, Init, Members[Field]) || 2411 CheckRedundantUnionInit(*this, Init, MemberUnions)) 2412 HadError = true; 2413 } else if (Init->isBaseInitializer()) { 2414 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 2415 if (CheckRedundantInit(*this, Init, Members[Key])) 2416 HadError = true; 2417 } else { 2418 assert(Init->isDelegatingInitializer()); 2419 // This must be the only initializer 2420 if (i != 0 || NumMemInits > 1) { 2421 Diag(MemInits[0]->getSourceLocation(), 2422 diag::err_delegating_initializer_alone) 2423 << MemInits[0]->getSourceRange(); 2424 HadError = true; 2425 } 2426 } 2427 } 2428 2429 if (HadError) 2430 return; 2431 2432 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits); 2433 2434 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors); 2435} 2436 2437void 2438Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 2439 CXXRecordDecl *ClassDecl) { 2440 // Ignore dependent contexts. 2441 if (ClassDecl->isDependentContext()) 2442 return; 2443 2444 // FIXME: all the access-control diagnostics are positioned on the 2445 // field/base declaration. That's probably good; that said, the 2446 // user might reasonably want to know why the destructor is being 2447 // emitted, and we currently don't say. 2448 2449 // Non-static data members. 2450 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 2451 E = ClassDecl->field_end(); I != E; ++I) { 2452 FieldDecl *Field = *I; 2453 if (Field->isInvalidDecl()) 2454 continue; 2455 QualType FieldType = Context.getBaseElementType(Field->getType()); 2456 2457 const RecordType* RT = FieldType->getAs<RecordType>(); 2458 if (!RT) 2459 continue; 2460 2461 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2462 if (FieldClassDecl->hasTrivialDestructor()) 2463 continue; 2464 2465 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 2466 CheckDestructorAccess(Field->getLocation(), Dtor, 2467 PDiag(diag::err_access_dtor_field) 2468 << Field->getDeclName() 2469 << FieldType); 2470 2471 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2472 } 2473 2474 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 2475 2476 // Bases. 2477 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2478 E = ClassDecl->bases_end(); Base != E; ++Base) { 2479 // Bases are always records in a well-formed non-dependent class. 2480 const RecordType *RT = Base->getType()->getAs<RecordType>(); 2481 2482 // Remember direct virtual bases. 2483 if (Base->isVirtual()) 2484 DirectVirtualBases.insert(RT); 2485 2486 // Ignore trivial destructors. 2487 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2488 if (BaseClassDecl->hasTrivialDestructor()) 2489 continue; 2490 2491 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 2492 2493 // FIXME: caret should be on the start of the class name 2494 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor, 2495 PDiag(diag::err_access_dtor_base) 2496 << Base->getType() 2497 << Base->getSourceRange()); 2498 2499 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2500 } 2501 2502 // Virtual bases. 2503 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2504 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2505 2506 // Bases are always records in a well-formed non-dependent class. 2507 const RecordType *RT = VBase->getType()->getAs<RecordType>(); 2508 2509 // Ignore direct virtual bases. 2510 if (DirectVirtualBases.count(RT)) 2511 continue; 2512 2513 // Ignore trivial destructors. 2514 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2515 if (BaseClassDecl->hasTrivialDestructor()) 2516 continue; 2517 2518 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 2519 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 2520 PDiag(diag::err_access_dtor_vbase) 2521 << VBase->getType()); 2522 2523 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2524 } 2525} 2526 2527void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 2528 if (!CDtorDecl) 2529 return; 2530 2531 if (CXXConstructorDecl *Constructor 2532 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 2533 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 2534} 2535 2536bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2537 unsigned DiagID, AbstractDiagSelID SelID) { 2538 if (SelID == -1) 2539 return RequireNonAbstractType(Loc, T, PDiag(DiagID)); 2540 else 2541 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID); 2542} 2543 2544bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2545 const PartialDiagnostic &PD) { 2546 if (!getLangOptions().CPlusPlus) 2547 return false; 2548 2549 if (const ArrayType *AT = Context.getAsArrayType(T)) 2550 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 2551 2552 if (const PointerType *PT = T->getAs<PointerType>()) { 2553 // Find the innermost pointer type. 2554 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 2555 PT = T; 2556 2557 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 2558 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 2559 } 2560 2561 const RecordType *RT = T->getAs<RecordType>(); 2562 if (!RT) 2563 return false; 2564 2565 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2566 2567 // We can't answer whether something is abstract until it has a 2568 // definition. If it's currently being defined, we'll walk back 2569 // over all the declarations when we have a full definition. 2570 const CXXRecordDecl *Def = RD->getDefinition(); 2571 if (!Def || Def->isBeingDefined()) 2572 return false; 2573 2574 if (!RD->isAbstract()) 2575 return false; 2576 2577 Diag(Loc, PD) << RD->getDeclName(); 2578 DiagnoseAbstractType(RD); 2579 2580 return true; 2581} 2582 2583void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 2584 // Check if we've already emitted the list of pure virtual functions 2585 // for this class. 2586 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 2587 return; 2588 2589 CXXFinalOverriderMap FinalOverriders; 2590 RD->getFinalOverriders(FinalOverriders); 2591 2592 // Keep a set of seen pure methods so we won't diagnose the same method 2593 // more than once. 2594 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 2595 2596 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 2597 MEnd = FinalOverriders.end(); 2598 M != MEnd; 2599 ++M) { 2600 for (OverridingMethods::iterator SO = M->second.begin(), 2601 SOEnd = M->second.end(); 2602 SO != SOEnd; ++SO) { 2603 // C++ [class.abstract]p4: 2604 // A class is abstract if it contains or inherits at least one 2605 // pure virtual function for which the final overrider is pure 2606 // virtual. 2607 2608 // 2609 if (SO->second.size() != 1) 2610 continue; 2611 2612 if (!SO->second.front().Method->isPure()) 2613 continue; 2614 2615 if (!SeenPureMethods.insert(SO->second.front().Method)) 2616 continue; 2617 2618 Diag(SO->second.front().Method->getLocation(), 2619 diag::note_pure_virtual_function) 2620 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 2621 } 2622 } 2623 2624 if (!PureVirtualClassDiagSet) 2625 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 2626 PureVirtualClassDiagSet->insert(RD); 2627} 2628 2629namespace { 2630struct AbstractUsageInfo { 2631 Sema &S; 2632 CXXRecordDecl *Record; 2633 CanQualType AbstractType; 2634 bool Invalid; 2635 2636 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 2637 : S(S), Record(Record), 2638 AbstractType(S.Context.getCanonicalType( 2639 S.Context.getTypeDeclType(Record))), 2640 Invalid(false) {} 2641 2642 void DiagnoseAbstractType() { 2643 if (Invalid) return; 2644 S.DiagnoseAbstractType(Record); 2645 Invalid = true; 2646 } 2647 2648 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 2649}; 2650 2651struct CheckAbstractUsage { 2652 AbstractUsageInfo &Info; 2653 const NamedDecl *Ctx; 2654 2655 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 2656 : Info(Info), Ctx(Ctx) {} 2657 2658 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 2659 switch (TL.getTypeLocClass()) { 2660#define ABSTRACT_TYPELOC(CLASS, PARENT) 2661#define TYPELOC(CLASS, PARENT) \ 2662 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break; 2663#include "clang/AST/TypeLocNodes.def" 2664 } 2665 } 2666 2667 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2668 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 2669 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 2670 if (!TL.getArg(I)) 2671 continue; 2672 2673 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 2674 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 2675 } 2676 } 2677 2678 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2679 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 2680 } 2681 2682 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2683 // Visit the type parameters from a permissive context. 2684 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 2685 TemplateArgumentLoc TAL = TL.getArgLoc(I); 2686 if (TAL.getArgument().getKind() == TemplateArgument::Type) 2687 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 2688 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 2689 // TODO: other template argument types? 2690 } 2691 } 2692 2693 // Visit pointee types from a permissive context. 2694#define CheckPolymorphic(Type) \ 2695 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 2696 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 2697 } 2698 CheckPolymorphic(PointerTypeLoc) 2699 CheckPolymorphic(ReferenceTypeLoc) 2700 CheckPolymorphic(MemberPointerTypeLoc) 2701 CheckPolymorphic(BlockPointerTypeLoc) 2702 2703 /// Handle all the types we haven't given a more specific 2704 /// implementation for above. 2705 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 2706 // Every other kind of type that we haven't called out already 2707 // that has an inner type is either (1) sugar or (2) contains that 2708 // inner type in some way as a subobject. 2709 if (TypeLoc Next = TL.getNextTypeLoc()) 2710 return Visit(Next, Sel); 2711 2712 // If there's no inner type and we're in a permissive context, 2713 // don't diagnose. 2714 if (Sel == Sema::AbstractNone) return; 2715 2716 // Check whether the type matches the abstract type. 2717 QualType T = TL.getType(); 2718 if (T->isArrayType()) { 2719 Sel = Sema::AbstractArrayType; 2720 T = Info.S.Context.getBaseElementType(T); 2721 } 2722 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 2723 if (CT != Info.AbstractType) return; 2724 2725 // It matched; do some magic. 2726 if (Sel == Sema::AbstractArrayType) { 2727 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 2728 << T << TL.getSourceRange(); 2729 } else { 2730 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 2731 << Sel << T << TL.getSourceRange(); 2732 } 2733 Info.DiagnoseAbstractType(); 2734 } 2735}; 2736 2737void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 2738 Sema::AbstractDiagSelID Sel) { 2739 CheckAbstractUsage(*this, D).Visit(TL, Sel); 2740} 2741 2742} 2743 2744/// Check for invalid uses of an abstract type in a method declaration. 2745static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 2746 CXXMethodDecl *MD) { 2747 // No need to do the check on definitions, which require that 2748 // the return/param types be complete. 2749 if (MD->isThisDeclarationADefinition()) 2750 return; 2751 2752 // For safety's sake, just ignore it if we don't have type source 2753 // information. This should never happen for non-implicit methods, 2754 // but... 2755 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 2756 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 2757} 2758 2759/// Check for invalid uses of an abstract type within a class definition. 2760static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 2761 CXXRecordDecl *RD) { 2762 for (CXXRecordDecl::decl_iterator 2763 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 2764 Decl *D = *I; 2765 if (D->isImplicit()) continue; 2766 2767 // Methods and method templates. 2768 if (isa<CXXMethodDecl>(D)) { 2769 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 2770 } else if (isa<FunctionTemplateDecl>(D)) { 2771 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 2772 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 2773 2774 // Fields and static variables. 2775 } else if (isa<FieldDecl>(D)) { 2776 FieldDecl *FD = cast<FieldDecl>(D); 2777 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 2778 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 2779 } else if (isa<VarDecl>(D)) { 2780 VarDecl *VD = cast<VarDecl>(D); 2781 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 2782 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 2783 2784 // Nested classes and class templates. 2785 } else if (isa<CXXRecordDecl>(D)) { 2786 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 2787 } else if (isa<ClassTemplateDecl>(D)) { 2788 CheckAbstractClassUsage(Info, 2789 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 2790 } 2791 } 2792} 2793 2794/// \brief Perform semantic checks on a class definition that has been 2795/// completing, introducing implicitly-declared members, checking for 2796/// abstract types, etc. 2797void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 2798 if (!Record) 2799 return; 2800 2801 if (Record->isAbstract() && !Record->isInvalidDecl()) { 2802 AbstractUsageInfo Info(*this, Record); 2803 CheckAbstractClassUsage(Info, Record); 2804 } 2805 2806 // If this is not an aggregate type and has no user-declared constructor, 2807 // complain about any non-static data members of reference or const scalar 2808 // type, since they will never get initializers. 2809 if (!Record->isInvalidDecl() && !Record->isDependentType() && 2810 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) { 2811 bool Complained = false; 2812 for (RecordDecl::field_iterator F = Record->field_begin(), 2813 FEnd = Record->field_end(); 2814 F != FEnd; ++F) { 2815 if (F->getType()->isReferenceType() || 2816 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 2817 if (!Complained) { 2818 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 2819 << Record->getTagKind() << Record; 2820 Complained = true; 2821 } 2822 2823 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 2824 << F->getType()->isReferenceType() 2825 << F->getDeclName(); 2826 } 2827 } 2828 } 2829 2830 if (Record->isDynamicClass() && !Record->isDependentType()) 2831 DynamicClasses.push_back(Record); 2832 2833 if (Record->getIdentifier()) { 2834 // C++ [class.mem]p13: 2835 // If T is the name of a class, then each of the following shall have a 2836 // name different from T: 2837 // - every member of every anonymous union that is a member of class T. 2838 // 2839 // C++ [class.mem]p14: 2840 // In addition, if class T has a user-declared constructor (12.1), every 2841 // non-static data member of class T shall have a name different from T. 2842 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 2843 R.first != R.second; ++R.first) { 2844 NamedDecl *D = *R.first; 2845 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 2846 isa<IndirectFieldDecl>(D)) { 2847 Diag(D->getLocation(), diag::err_member_name_of_class) 2848 << D->getDeclName(); 2849 break; 2850 } 2851 } 2852 } 2853 2854 // Warn if the class has virtual methods but non-virtual public destructor. 2855 if (Record->isPolymorphic() && !Record->isDependentType()) { 2856 CXXDestructorDecl *dtor = Record->getDestructor(); 2857 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 2858 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 2859 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 2860 } 2861 2862 // See if a method overloads virtual methods in a base 2863 /// class without overriding any. 2864 if (!Record->isDependentType()) { 2865 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 2866 MEnd = Record->method_end(); 2867 M != MEnd; ++M) { 2868 if (!(*M)->isStatic()) 2869 DiagnoseHiddenVirtualMethods(Record, *M); 2870 } 2871 } 2872 2873 // Declare inherited constructors. We do this eagerly here because: 2874 // - The standard requires an eager diagnostic for conflicting inherited 2875 // constructors from different classes. 2876 // - The lazy declaration of the other implicit constructors is so as to not 2877 // waste space and performance on classes that are not meant to be 2878 // instantiated (e.g. meta-functions). This doesn't apply to classes that 2879 // have inherited constructors. 2880 DeclareInheritedConstructors(Record); 2881} 2882 2883/// \brief Data used with FindHiddenVirtualMethod 2884namespace { 2885 struct FindHiddenVirtualMethodData { 2886 Sema *S; 2887 CXXMethodDecl *Method; 2888 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 2889 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2890 }; 2891} 2892 2893/// \brief Member lookup function that determines whether a given C++ 2894/// method overloads virtual methods in a base class without overriding any, 2895/// to be used with CXXRecordDecl::lookupInBases(). 2896static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 2897 CXXBasePath &Path, 2898 void *UserData) { 2899 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 2900 2901 FindHiddenVirtualMethodData &Data 2902 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 2903 2904 DeclarationName Name = Data.Method->getDeclName(); 2905 assert(Name.getNameKind() == DeclarationName::Identifier); 2906 2907 bool foundSameNameMethod = false; 2908 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods; 2909 for (Path.Decls = BaseRecord->lookup(Name); 2910 Path.Decls.first != Path.Decls.second; 2911 ++Path.Decls.first) { 2912 NamedDecl *D = *Path.Decls.first; 2913 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 2914 MD = MD->getCanonicalDecl(); 2915 foundSameNameMethod = true; 2916 // Interested only in hidden virtual methods. 2917 if (!MD->isVirtual()) 2918 continue; 2919 // If the method we are checking overrides a method from its base 2920 // don't warn about the other overloaded methods. 2921 if (!Data.S->IsOverload(Data.Method, MD, false)) 2922 return true; 2923 // Collect the overload only if its hidden. 2924 if (!Data.OverridenAndUsingBaseMethods.count(MD)) 2925 overloadedMethods.push_back(MD); 2926 } 2927 } 2928 2929 if (foundSameNameMethod) 2930 Data.OverloadedMethods.append(overloadedMethods.begin(), 2931 overloadedMethods.end()); 2932 return foundSameNameMethod; 2933} 2934 2935/// \brief See if a method overloads virtual methods in a base class without 2936/// overriding any. 2937void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 2938 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 2939 MD->getLocation()) == Diagnostic::Ignored) 2940 return; 2941 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier) 2942 return; 2943 2944 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 2945 /*bool RecordPaths=*/false, 2946 /*bool DetectVirtual=*/false); 2947 FindHiddenVirtualMethodData Data; 2948 Data.Method = MD; 2949 Data.S = this; 2950 2951 // Keep the base methods that were overriden or introduced in the subclass 2952 // by 'using' in a set. A base method not in this set is hidden. 2953 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName()); 2954 res.first != res.second; ++res.first) { 2955 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first)) 2956 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 2957 E = MD->end_overridden_methods(); 2958 I != E; ++I) 2959 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl()); 2960 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first)) 2961 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl())) 2962 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl()); 2963 } 2964 2965 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 2966 !Data.OverloadedMethods.empty()) { 2967 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 2968 << MD << (Data.OverloadedMethods.size() > 1); 2969 2970 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 2971 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 2972 Diag(overloadedMD->getLocation(), 2973 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 2974 } 2975 } 2976} 2977 2978void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 2979 Decl *TagDecl, 2980 SourceLocation LBrac, 2981 SourceLocation RBrac, 2982 AttributeList *AttrList) { 2983 if (!TagDecl) 2984 return; 2985 2986 AdjustDeclIfTemplate(TagDecl); 2987 2988 ActOnFields(S, RLoc, TagDecl, 2989 // strict aliasing violation! 2990 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 2991 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList); 2992 2993 CheckCompletedCXXClass( 2994 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 2995} 2996 2997namespace { 2998 /// \brief Helper class that collects exception specifications for 2999 /// implicitly-declared special member functions. 3000 class ImplicitExceptionSpecification { 3001 ASTContext &Context; 3002 // We order exception specifications thus: 3003 // noexcept is the most restrictive, but is only used in C++0x. 3004 // throw() comes next. 3005 // Then a throw(collected exceptions) 3006 // Finally no specification. 3007 // throw(...) is used instead if any called function uses it. 3008 ExceptionSpecificationType ComputedEST; 3009 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 3010 llvm::SmallVector<QualType, 4> Exceptions; 3011 3012 void ClearExceptions() { 3013 ExceptionsSeen.clear(); 3014 Exceptions.clear(); 3015 } 3016 3017 public: 3018 explicit ImplicitExceptionSpecification(ASTContext &Context) 3019 : Context(Context), ComputedEST(EST_BasicNoexcept) { 3020 if (!Context.getLangOptions().CPlusPlus0x) 3021 ComputedEST = EST_DynamicNone; 3022 } 3023 3024 /// \brief Get the computed exception specification type. 3025 ExceptionSpecificationType getExceptionSpecType() const { 3026 assert(ComputedEST != EST_ComputedNoexcept && 3027 "noexcept(expr) should not be a possible result"); 3028 return ComputedEST; 3029 } 3030 3031 /// \brief The number of exceptions in the exception specification. 3032 unsigned size() const { return Exceptions.size(); } 3033 3034 /// \brief The set of exceptions in the exception specification. 3035 const QualType *data() const { return Exceptions.data(); } 3036 3037 /// \brief Integrate another called method into the collected data. 3038 void CalledDecl(CXXMethodDecl *Method) { 3039 // If we have an MSAny spec already, don't bother. 3040 if (!Method || ComputedEST == EST_MSAny) 3041 return; 3042 3043 const FunctionProtoType *Proto 3044 = Method->getType()->getAs<FunctionProtoType>(); 3045 3046 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 3047 3048 // If this function can throw any exceptions, make a note of that. 3049 if (EST == EST_MSAny || EST == EST_None) { 3050 ClearExceptions(); 3051 ComputedEST = EST; 3052 return; 3053 } 3054 3055 // If this function has a basic noexcept, it doesn't affect the outcome. 3056 if (EST == EST_BasicNoexcept) 3057 return; 3058 3059 // If we have a throw-all spec at this point, ignore the function. 3060 if (ComputedEST == EST_None) 3061 return; 3062 3063 // If we're still at noexcept(true) and there's a nothrow() callee, 3064 // change to that specification. 3065 if (EST == EST_DynamicNone) { 3066 if (ComputedEST == EST_BasicNoexcept) 3067 ComputedEST = EST_DynamicNone; 3068 return; 3069 } 3070 3071 // Check out noexcept specs. 3072 if (EST == EST_ComputedNoexcept) { 3073 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(Context); 3074 assert(NR != FunctionProtoType::NR_NoNoexcept && 3075 "Must have noexcept result for EST_ComputedNoexcept."); 3076 assert(NR != FunctionProtoType::NR_Dependent && 3077 "Should not generate implicit declarations for dependent cases, " 3078 "and don't know how to handle them anyway."); 3079 3080 // noexcept(false) -> no spec on the new function 3081 if (NR == FunctionProtoType::NR_Throw) { 3082 ClearExceptions(); 3083 ComputedEST = EST_None; 3084 } 3085 // noexcept(true) won't change anything either. 3086 return; 3087 } 3088 3089 assert(EST == EST_Dynamic && "EST case not considered earlier."); 3090 assert(ComputedEST != EST_None && 3091 "Shouldn't collect exceptions when throw-all is guaranteed."); 3092 ComputedEST = EST_Dynamic; 3093 // Record the exceptions in this function's exception specification. 3094 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 3095 EEnd = Proto->exception_end(); 3096 E != EEnd; ++E) 3097 if (ExceptionsSeen.insert(Context.getCanonicalType(*E))) 3098 Exceptions.push_back(*E); 3099 } 3100 }; 3101} 3102 3103 3104/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 3105/// special functions, such as the default constructor, copy 3106/// constructor, or destructor, to the given C++ class (C++ 3107/// [special]p1). This routine can only be executed just before the 3108/// definition of the class is complete. 3109void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 3110 if (!ClassDecl->hasUserDeclaredConstructor()) 3111 ++ASTContext::NumImplicitDefaultConstructors; 3112 3113 if (!ClassDecl->hasUserDeclaredCopyConstructor()) 3114 ++ASTContext::NumImplicitCopyConstructors; 3115 3116 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 3117 ++ASTContext::NumImplicitCopyAssignmentOperators; 3118 3119 // If we have a dynamic class, then the copy assignment operator may be 3120 // virtual, so we have to declare it immediately. This ensures that, e.g., 3121 // it shows up in the right place in the vtable and that we diagnose 3122 // problems with the implicit exception specification. 3123 if (ClassDecl->isDynamicClass()) 3124 DeclareImplicitCopyAssignment(ClassDecl); 3125 } 3126 3127 if (!ClassDecl->hasUserDeclaredDestructor()) { 3128 ++ASTContext::NumImplicitDestructors; 3129 3130 // If we have a dynamic class, then the destructor may be virtual, so we 3131 // have to declare the destructor immediately. This ensures that, e.g., it 3132 // shows up in the right place in the vtable and that we diagnose problems 3133 // with the implicit exception specification. 3134 if (ClassDecl->isDynamicClass()) 3135 DeclareImplicitDestructor(ClassDecl); 3136 } 3137} 3138 3139void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 3140 if (!D) 3141 return; 3142 3143 TemplateParameterList *Params = 0; 3144 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 3145 Params = Template->getTemplateParameters(); 3146 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 3147 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 3148 Params = PartialSpec->getTemplateParameters(); 3149 else 3150 return; 3151 3152 for (TemplateParameterList::iterator Param = Params->begin(), 3153 ParamEnd = Params->end(); 3154 Param != ParamEnd; ++Param) { 3155 NamedDecl *Named = cast<NamedDecl>(*Param); 3156 if (Named->getDeclName()) { 3157 S->AddDecl(Named); 3158 IdResolver.AddDecl(Named); 3159 } 3160 } 3161} 3162 3163void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 3164 if (!RecordD) return; 3165 AdjustDeclIfTemplate(RecordD); 3166 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 3167 PushDeclContext(S, Record); 3168} 3169 3170void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 3171 if (!RecordD) return; 3172 PopDeclContext(); 3173} 3174 3175/// ActOnStartDelayedCXXMethodDeclaration - We have completed 3176/// parsing a top-level (non-nested) C++ class, and we are now 3177/// parsing those parts of the given Method declaration that could 3178/// not be parsed earlier (C++ [class.mem]p2), such as default 3179/// arguments. This action should enter the scope of the given 3180/// Method declaration as if we had just parsed the qualified method 3181/// name. However, it should not bring the parameters into scope; 3182/// that will be performed by ActOnDelayedCXXMethodParameter. 3183void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 3184} 3185 3186/// ActOnDelayedCXXMethodParameter - We've already started a delayed 3187/// C++ method declaration. We're (re-)introducing the given 3188/// function parameter into scope for use in parsing later parts of 3189/// the method declaration. For example, we could see an 3190/// ActOnParamDefaultArgument event for this parameter. 3191void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 3192 if (!ParamD) 3193 return; 3194 3195 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 3196 3197 // If this parameter has an unparsed default argument, clear it out 3198 // to make way for the parsed default argument. 3199 if (Param->hasUnparsedDefaultArg()) 3200 Param->setDefaultArg(0); 3201 3202 S->AddDecl(Param); 3203 if (Param->getDeclName()) 3204 IdResolver.AddDecl(Param); 3205} 3206 3207/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 3208/// processing the delayed method declaration for Method. The method 3209/// declaration is now considered finished. There may be a separate 3210/// ActOnStartOfFunctionDef action later (not necessarily 3211/// immediately!) for this method, if it was also defined inside the 3212/// class body. 3213void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 3214 if (!MethodD) 3215 return; 3216 3217 AdjustDeclIfTemplate(MethodD); 3218 3219 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 3220 3221 // Now that we have our default arguments, check the constructor 3222 // again. It could produce additional diagnostics or affect whether 3223 // the class has implicitly-declared destructors, among other 3224 // things. 3225 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 3226 CheckConstructor(Constructor); 3227 3228 // Check the default arguments, which we may have added. 3229 if (!Method->isInvalidDecl()) 3230 CheckCXXDefaultArguments(Method); 3231} 3232 3233/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 3234/// the well-formedness of the constructor declarator @p D with type @p 3235/// R. If there are any errors in the declarator, this routine will 3236/// emit diagnostics and set the invalid bit to true. In any case, the type 3237/// will be updated to reflect a well-formed type for the constructor and 3238/// returned. 3239QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 3240 StorageClass &SC) { 3241 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 3242 3243 // C++ [class.ctor]p3: 3244 // A constructor shall not be virtual (10.3) or static (9.4). A 3245 // constructor can be invoked for a const, volatile or const 3246 // volatile object. A constructor shall not be declared const, 3247 // volatile, or const volatile (9.3.2). 3248 if (isVirtual) { 3249 if (!D.isInvalidType()) 3250 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 3251 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 3252 << SourceRange(D.getIdentifierLoc()); 3253 D.setInvalidType(); 3254 } 3255 if (SC == SC_Static) { 3256 if (!D.isInvalidType()) 3257 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 3258 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 3259 << SourceRange(D.getIdentifierLoc()); 3260 D.setInvalidType(); 3261 SC = SC_None; 3262 } 3263 3264 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 3265 if (FTI.TypeQuals != 0) { 3266 if (FTI.TypeQuals & Qualifiers::Const) 3267 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 3268 << "const" << SourceRange(D.getIdentifierLoc()); 3269 if (FTI.TypeQuals & Qualifiers::Volatile) 3270 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 3271 << "volatile" << SourceRange(D.getIdentifierLoc()); 3272 if (FTI.TypeQuals & Qualifiers::Restrict) 3273 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 3274 << "restrict" << SourceRange(D.getIdentifierLoc()); 3275 D.setInvalidType(); 3276 } 3277 3278 // C++0x [class.ctor]p4: 3279 // A constructor shall not be declared with a ref-qualifier. 3280 if (FTI.hasRefQualifier()) { 3281 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 3282 << FTI.RefQualifierIsLValueRef 3283 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 3284 D.setInvalidType(); 3285 } 3286 3287 // Rebuild the function type "R" without any type qualifiers (in 3288 // case any of the errors above fired) and with "void" as the 3289 // return type, since constructors don't have return types. 3290 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 3291 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 3292 return R; 3293 3294 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 3295 EPI.TypeQuals = 0; 3296 EPI.RefQualifier = RQ_None; 3297 3298 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 3299 Proto->getNumArgs(), EPI); 3300} 3301 3302/// CheckConstructor - Checks a fully-formed constructor for 3303/// well-formedness, issuing any diagnostics required. Returns true if 3304/// the constructor declarator is invalid. 3305void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 3306 CXXRecordDecl *ClassDecl 3307 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 3308 if (!ClassDecl) 3309 return Constructor->setInvalidDecl(); 3310 3311 // C++ [class.copy]p3: 3312 // A declaration of a constructor for a class X is ill-formed if 3313 // its first parameter is of type (optionally cv-qualified) X and 3314 // either there are no other parameters or else all other 3315 // parameters have default arguments. 3316 if (!Constructor->isInvalidDecl() && 3317 ((Constructor->getNumParams() == 1) || 3318 (Constructor->getNumParams() > 1 && 3319 Constructor->getParamDecl(1)->hasDefaultArg())) && 3320 Constructor->getTemplateSpecializationKind() 3321 != TSK_ImplicitInstantiation) { 3322 QualType ParamType = Constructor->getParamDecl(0)->getType(); 3323 QualType ClassTy = Context.getTagDeclType(ClassDecl); 3324 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 3325 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 3326 const char *ConstRef 3327 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 3328 : " const &"; 3329 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 3330 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 3331 3332 // FIXME: Rather that making the constructor invalid, we should endeavor 3333 // to fix the type. 3334 Constructor->setInvalidDecl(); 3335 } 3336 } 3337} 3338 3339/// CheckDestructor - Checks a fully-formed destructor definition for 3340/// well-formedness, issuing any diagnostics required. Returns true 3341/// on error. 3342bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 3343 CXXRecordDecl *RD = Destructor->getParent(); 3344 3345 if (Destructor->isVirtual()) { 3346 SourceLocation Loc; 3347 3348 if (!Destructor->isImplicit()) 3349 Loc = Destructor->getLocation(); 3350 else 3351 Loc = RD->getLocation(); 3352 3353 // If we have a virtual destructor, look up the deallocation function 3354 FunctionDecl *OperatorDelete = 0; 3355 DeclarationName Name = 3356 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 3357 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 3358 return true; 3359 3360 MarkDeclarationReferenced(Loc, OperatorDelete); 3361 3362 Destructor->setOperatorDelete(OperatorDelete); 3363 } 3364 3365 return false; 3366} 3367 3368static inline bool 3369FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 3370 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 3371 FTI.ArgInfo[0].Param && 3372 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 3373} 3374 3375/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 3376/// the well-formednes of the destructor declarator @p D with type @p 3377/// R. If there are any errors in the declarator, this routine will 3378/// emit diagnostics and set the declarator to invalid. Even if this happens, 3379/// will be updated to reflect a well-formed type for the destructor and 3380/// returned. 3381QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 3382 StorageClass& SC) { 3383 // C++ [class.dtor]p1: 3384 // [...] A typedef-name that names a class is a class-name 3385 // (7.1.3); however, a typedef-name that names a class shall not 3386 // be used as the identifier in the declarator for a destructor 3387 // declaration. 3388 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 3389 if (isa<TypedefType>(DeclaratorType)) 3390 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 3391 << DeclaratorType; 3392 3393 // C++ [class.dtor]p2: 3394 // A destructor is used to destroy objects of its class type. A 3395 // destructor takes no parameters, and no return type can be 3396 // specified for it (not even void). The address of a destructor 3397 // shall not be taken. A destructor shall not be static. A 3398 // destructor can be invoked for a const, volatile or const 3399 // volatile object. A destructor shall not be declared const, 3400 // volatile or const volatile (9.3.2). 3401 if (SC == SC_Static) { 3402 if (!D.isInvalidType()) 3403 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 3404 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 3405 << SourceRange(D.getIdentifierLoc()) 3406 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 3407 3408 SC = SC_None; 3409 } 3410 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 3411 // Destructors don't have return types, but the parser will 3412 // happily parse something like: 3413 // 3414 // class X { 3415 // float ~X(); 3416 // }; 3417 // 3418 // The return type will be eliminated later. 3419 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 3420 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 3421 << SourceRange(D.getIdentifierLoc()); 3422 } 3423 3424 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 3425 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 3426 if (FTI.TypeQuals & Qualifiers::Const) 3427 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3428 << "const" << SourceRange(D.getIdentifierLoc()); 3429 if (FTI.TypeQuals & Qualifiers::Volatile) 3430 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3431 << "volatile" << SourceRange(D.getIdentifierLoc()); 3432 if (FTI.TypeQuals & Qualifiers::Restrict) 3433 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3434 << "restrict" << SourceRange(D.getIdentifierLoc()); 3435 D.setInvalidType(); 3436 } 3437 3438 // C++0x [class.dtor]p2: 3439 // A destructor shall not be declared with a ref-qualifier. 3440 if (FTI.hasRefQualifier()) { 3441 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 3442 << FTI.RefQualifierIsLValueRef 3443 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 3444 D.setInvalidType(); 3445 } 3446 3447 // Make sure we don't have any parameters. 3448 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 3449 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 3450 3451 // Delete the parameters. 3452 FTI.freeArgs(); 3453 D.setInvalidType(); 3454 } 3455 3456 // Make sure the destructor isn't variadic. 3457 if (FTI.isVariadic) { 3458 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 3459 D.setInvalidType(); 3460 } 3461 3462 // Rebuild the function type "R" without any type qualifiers or 3463 // parameters (in case any of the errors above fired) and with 3464 // "void" as the return type, since destructors don't have return 3465 // types. 3466 if (!D.isInvalidType()) 3467 return R; 3468 3469 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 3470 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 3471 EPI.Variadic = false; 3472 EPI.TypeQuals = 0; 3473 EPI.RefQualifier = RQ_None; 3474 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 3475} 3476 3477/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 3478/// well-formednes of the conversion function declarator @p D with 3479/// type @p R. If there are any errors in the declarator, this routine 3480/// will emit diagnostics and return true. Otherwise, it will return 3481/// false. Either way, the type @p R will be updated to reflect a 3482/// well-formed type for the conversion operator. 3483void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 3484 StorageClass& SC) { 3485 // C++ [class.conv.fct]p1: 3486 // Neither parameter types nor return type can be specified. The 3487 // type of a conversion function (8.3.5) is "function taking no 3488 // parameter returning conversion-type-id." 3489 if (SC == SC_Static) { 3490 if (!D.isInvalidType()) 3491 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 3492 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 3493 << SourceRange(D.getIdentifierLoc()); 3494 D.setInvalidType(); 3495 SC = SC_None; 3496 } 3497 3498 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 3499 3500 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 3501 // Conversion functions don't have return types, but the parser will 3502 // happily parse something like: 3503 // 3504 // class X { 3505 // float operator bool(); 3506 // }; 3507 // 3508 // The return type will be changed later anyway. 3509 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 3510 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 3511 << SourceRange(D.getIdentifierLoc()); 3512 D.setInvalidType(); 3513 } 3514 3515 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 3516 3517 // Make sure we don't have any parameters. 3518 if (Proto->getNumArgs() > 0) { 3519 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 3520 3521 // Delete the parameters. 3522 D.getFunctionTypeInfo().freeArgs(); 3523 D.setInvalidType(); 3524 } else if (Proto->isVariadic()) { 3525 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 3526 D.setInvalidType(); 3527 } 3528 3529 // Diagnose "&operator bool()" and other such nonsense. This 3530 // is actually a gcc extension which we don't support. 3531 if (Proto->getResultType() != ConvType) { 3532 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 3533 << Proto->getResultType(); 3534 D.setInvalidType(); 3535 ConvType = Proto->getResultType(); 3536 } 3537 3538 // C++ [class.conv.fct]p4: 3539 // The conversion-type-id shall not represent a function type nor 3540 // an array type. 3541 if (ConvType->isArrayType()) { 3542 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 3543 ConvType = Context.getPointerType(ConvType); 3544 D.setInvalidType(); 3545 } else if (ConvType->isFunctionType()) { 3546 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 3547 ConvType = Context.getPointerType(ConvType); 3548 D.setInvalidType(); 3549 } 3550 3551 // Rebuild the function type "R" without any parameters (in case any 3552 // of the errors above fired) and with the conversion type as the 3553 // return type. 3554 if (D.isInvalidType()) 3555 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo()); 3556 3557 // C++0x explicit conversion operators. 3558 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 3559 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3560 diag::warn_explicit_conversion_functions) 3561 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 3562} 3563 3564/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 3565/// the declaration of the given C++ conversion function. This routine 3566/// is responsible for recording the conversion function in the C++ 3567/// class, if possible. 3568Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 3569 assert(Conversion && "Expected to receive a conversion function declaration"); 3570 3571 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 3572 3573 // Make sure we aren't redeclaring the conversion function. 3574 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 3575 3576 // C++ [class.conv.fct]p1: 3577 // [...] A conversion function is never used to convert a 3578 // (possibly cv-qualified) object to the (possibly cv-qualified) 3579 // same object type (or a reference to it), to a (possibly 3580 // cv-qualified) base class of that type (or a reference to it), 3581 // or to (possibly cv-qualified) void. 3582 // FIXME: Suppress this warning if the conversion function ends up being a 3583 // virtual function that overrides a virtual function in a base class. 3584 QualType ClassType 3585 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 3586 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 3587 ConvType = ConvTypeRef->getPointeeType(); 3588 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 3589 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 3590 /* Suppress diagnostics for instantiations. */; 3591 else if (ConvType->isRecordType()) { 3592 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 3593 if (ConvType == ClassType) 3594 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 3595 << ClassType; 3596 else if (IsDerivedFrom(ClassType, ConvType)) 3597 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 3598 << ClassType << ConvType; 3599 } else if (ConvType->isVoidType()) { 3600 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 3601 << ClassType << ConvType; 3602 } 3603 3604 if (FunctionTemplateDecl *ConversionTemplate 3605 = Conversion->getDescribedFunctionTemplate()) 3606 return ConversionTemplate; 3607 3608 return Conversion; 3609} 3610 3611//===----------------------------------------------------------------------===// 3612// Namespace Handling 3613//===----------------------------------------------------------------------===// 3614 3615 3616 3617/// ActOnStartNamespaceDef - This is called at the start of a namespace 3618/// definition. 3619Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 3620 SourceLocation InlineLoc, 3621 SourceLocation NamespaceLoc, 3622 SourceLocation IdentLoc, 3623 IdentifierInfo *II, 3624 SourceLocation LBrace, 3625 AttributeList *AttrList) { 3626 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 3627 // For anonymous namespace, take the location of the left brace. 3628 SourceLocation Loc = II ? IdentLoc : LBrace; 3629 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, 3630 StartLoc, Loc, II); 3631 Namespc->setInline(InlineLoc.isValid()); 3632 3633 Scope *DeclRegionScope = NamespcScope->getParent(); 3634 3635 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 3636 3637 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 3638 PushNamespaceVisibilityAttr(Attr); 3639 3640 if (II) { 3641 // C++ [namespace.def]p2: 3642 // The identifier in an original-namespace-definition shall not 3643 // have been previously defined in the declarative region in 3644 // which the original-namespace-definition appears. The 3645 // identifier in an original-namespace-definition is the name of 3646 // the namespace. Subsequently in that declarative region, it is 3647 // treated as an original-namespace-name. 3648 // 3649 // Since namespace names are unique in their scope, and we don't 3650 // look through using directives, just 3651 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 3652 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first; 3653 3654 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 3655 // This is an extended namespace definition. 3656 if (Namespc->isInline() != OrigNS->isInline()) { 3657 // inline-ness must match 3658 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch) 3659 << Namespc->isInline(); 3660 Diag(OrigNS->getLocation(), diag::note_previous_definition); 3661 Namespc->setInvalidDecl(); 3662 // Recover by ignoring the new namespace's inline status. 3663 Namespc->setInline(OrigNS->isInline()); 3664 } 3665 3666 // Attach this namespace decl to the chain of extended namespace 3667 // definitions. 3668 OrigNS->setNextNamespace(Namespc); 3669 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 3670 3671 // Remove the previous declaration from the scope. 3672 if (DeclRegionScope->isDeclScope(OrigNS)) { 3673 IdResolver.RemoveDecl(OrigNS); 3674 DeclRegionScope->RemoveDecl(OrigNS); 3675 } 3676 } else if (PrevDecl) { 3677 // This is an invalid name redefinition. 3678 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 3679 << Namespc->getDeclName(); 3680 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3681 Namespc->setInvalidDecl(); 3682 // Continue on to push Namespc as current DeclContext and return it. 3683 } else if (II->isStr("std") && 3684 CurContext->getRedeclContext()->isTranslationUnit()) { 3685 // This is the first "real" definition of the namespace "std", so update 3686 // our cache of the "std" namespace to point at this definition. 3687 if (NamespaceDecl *StdNS = getStdNamespace()) { 3688 // We had already defined a dummy namespace "std". Link this new 3689 // namespace definition to the dummy namespace "std". 3690 StdNS->setNextNamespace(Namespc); 3691 StdNS->setLocation(IdentLoc); 3692 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace()); 3693 } 3694 3695 // Make our StdNamespace cache point at the first real definition of the 3696 // "std" namespace. 3697 StdNamespace = Namespc; 3698 } 3699 3700 PushOnScopeChains(Namespc, DeclRegionScope); 3701 } else { 3702 // Anonymous namespaces. 3703 assert(Namespc->isAnonymousNamespace()); 3704 3705 // Link the anonymous namespace into its parent. 3706 NamespaceDecl *PrevDecl; 3707 DeclContext *Parent = CurContext->getRedeclContext(); 3708 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 3709 PrevDecl = TU->getAnonymousNamespace(); 3710 TU->setAnonymousNamespace(Namespc); 3711 } else { 3712 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 3713 PrevDecl = ND->getAnonymousNamespace(); 3714 ND->setAnonymousNamespace(Namespc); 3715 } 3716 3717 // Link the anonymous namespace with its previous declaration. 3718 if (PrevDecl) { 3719 assert(PrevDecl->isAnonymousNamespace()); 3720 assert(!PrevDecl->getNextNamespace()); 3721 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace()); 3722 PrevDecl->setNextNamespace(Namespc); 3723 3724 if (Namespc->isInline() != PrevDecl->isInline()) { 3725 // inline-ness must match 3726 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch) 3727 << Namespc->isInline(); 3728 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3729 Namespc->setInvalidDecl(); 3730 // Recover by ignoring the new namespace's inline status. 3731 Namespc->setInline(PrevDecl->isInline()); 3732 } 3733 } 3734 3735 CurContext->addDecl(Namespc); 3736 3737 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 3738 // behaves as if it were replaced by 3739 // namespace unique { /* empty body */ } 3740 // using namespace unique; 3741 // namespace unique { namespace-body } 3742 // where all occurrences of 'unique' in a translation unit are 3743 // replaced by the same identifier and this identifier differs 3744 // from all other identifiers in the entire program. 3745 3746 // We just create the namespace with an empty name and then add an 3747 // implicit using declaration, just like the standard suggests. 3748 // 3749 // CodeGen enforces the "universally unique" aspect by giving all 3750 // declarations semantically contained within an anonymous 3751 // namespace internal linkage. 3752 3753 if (!PrevDecl) { 3754 UsingDirectiveDecl* UD 3755 = UsingDirectiveDecl::Create(Context, CurContext, 3756 /* 'using' */ LBrace, 3757 /* 'namespace' */ SourceLocation(), 3758 /* qualifier */ NestedNameSpecifierLoc(), 3759 /* identifier */ SourceLocation(), 3760 Namespc, 3761 /* Ancestor */ CurContext); 3762 UD->setImplicit(); 3763 CurContext->addDecl(UD); 3764 } 3765 } 3766 3767 // Although we could have an invalid decl (i.e. the namespace name is a 3768 // redefinition), push it as current DeclContext and try to continue parsing. 3769 // FIXME: We should be able to push Namespc here, so that the each DeclContext 3770 // for the namespace has the declarations that showed up in that particular 3771 // namespace definition. 3772 PushDeclContext(NamespcScope, Namespc); 3773 return Namespc; 3774} 3775 3776/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 3777/// is a namespace alias, returns the namespace it points to. 3778static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 3779 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 3780 return AD->getNamespace(); 3781 return dyn_cast_or_null<NamespaceDecl>(D); 3782} 3783 3784/// ActOnFinishNamespaceDef - This callback is called after a namespace is 3785/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 3786void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 3787 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 3788 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 3789 Namespc->setRBraceLoc(RBrace); 3790 PopDeclContext(); 3791 if (Namespc->hasAttr<VisibilityAttr>()) 3792 PopPragmaVisibility(); 3793} 3794 3795CXXRecordDecl *Sema::getStdBadAlloc() const { 3796 return cast_or_null<CXXRecordDecl>( 3797 StdBadAlloc.get(Context.getExternalSource())); 3798} 3799 3800NamespaceDecl *Sema::getStdNamespace() const { 3801 return cast_or_null<NamespaceDecl>( 3802 StdNamespace.get(Context.getExternalSource())); 3803} 3804 3805/// \brief Retrieve the special "std" namespace, which may require us to 3806/// implicitly define the namespace. 3807NamespaceDecl *Sema::getOrCreateStdNamespace() { 3808 if (!StdNamespace) { 3809 // The "std" namespace has not yet been defined, so build one implicitly. 3810 StdNamespace = NamespaceDecl::Create(Context, 3811 Context.getTranslationUnitDecl(), 3812 SourceLocation(), SourceLocation(), 3813 &PP.getIdentifierTable().get("std")); 3814 getStdNamespace()->setImplicit(true); 3815 } 3816 3817 return getStdNamespace(); 3818} 3819 3820Decl *Sema::ActOnUsingDirective(Scope *S, 3821 SourceLocation UsingLoc, 3822 SourceLocation NamespcLoc, 3823 CXXScopeSpec &SS, 3824 SourceLocation IdentLoc, 3825 IdentifierInfo *NamespcName, 3826 AttributeList *AttrList) { 3827 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 3828 assert(NamespcName && "Invalid NamespcName."); 3829 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 3830 3831 // This can only happen along a recovery path. 3832 while (S->getFlags() & Scope::TemplateParamScope) 3833 S = S->getParent(); 3834 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 3835 3836 UsingDirectiveDecl *UDir = 0; 3837 NestedNameSpecifier *Qualifier = 0; 3838 if (SS.isSet()) 3839 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 3840 3841 // Lookup namespace name. 3842 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 3843 LookupParsedName(R, S, &SS); 3844 if (R.isAmbiguous()) 3845 return 0; 3846 3847 if (R.empty()) { 3848 // Allow "using namespace std;" or "using namespace ::std;" even if 3849 // "std" hasn't been defined yet, for GCC compatibility. 3850 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 3851 NamespcName->isStr("std")) { 3852 Diag(IdentLoc, diag::ext_using_undefined_std); 3853 R.addDecl(getOrCreateStdNamespace()); 3854 R.resolveKind(); 3855 } 3856 // Otherwise, attempt typo correction. 3857 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false, 3858 CTC_NoKeywords, 0)) { 3859 if (R.getAsSingle<NamespaceDecl>() || 3860 R.getAsSingle<NamespaceAliasDecl>()) { 3861 if (DeclContext *DC = computeDeclContext(SS, false)) 3862 Diag(IdentLoc, diag::err_using_directive_member_suggest) 3863 << NamespcName << DC << Corrected << SS.getRange() 3864 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 3865 else 3866 Diag(IdentLoc, diag::err_using_directive_suggest) 3867 << NamespcName << Corrected 3868 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 3869 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here) 3870 << Corrected; 3871 3872 NamespcName = Corrected.getAsIdentifierInfo(); 3873 } else { 3874 R.clear(); 3875 R.setLookupName(NamespcName); 3876 } 3877 } 3878 } 3879 3880 if (!R.empty()) { 3881 NamedDecl *Named = R.getFoundDecl(); 3882 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 3883 && "expected namespace decl"); 3884 // C++ [namespace.udir]p1: 3885 // A using-directive specifies that the names in the nominated 3886 // namespace can be used in the scope in which the 3887 // using-directive appears after the using-directive. During 3888 // unqualified name lookup (3.4.1), the names appear as if they 3889 // were declared in the nearest enclosing namespace which 3890 // contains both the using-directive and the nominated 3891 // namespace. [Note: in this context, "contains" means "contains 3892 // directly or indirectly". ] 3893 3894 // Find enclosing context containing both using-directive and 3895 // nominated namespace. 3896 NamespaceDecl *NS = getNamespaceDecl(Named); 3897 DeclContext *CommonAncestor = cast<DeclContext>(NS); 3898 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 3899 CommonAncestor = CommonAncestor->getParent(); 3900 3901 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 3902 SS.getWithLocInContext(Context), 3903 IdentLoc, Named, CommonAncestor); 3904 3905 if (CurContext->getDeclKind() == Decl::TranslationUnit && 3906 !SourceMgr.isFromMainFile(IdentLoc)) { 3907 Diag(IdentLoc, diag::warn_using_directive_in_header); 3908 } 3909 3910 PushUsingDirective(S, UDir); 3911 } else { 3912 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 3913 } 3914 3915 // FIXME: We ignore attributes for now. 3916 return UDir; 3917} 3918 3919void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 3920 // If scope has associated entity, then using directive is at namespace 3921 // or translation unit scope. We add UsingDirectiveDecls, into 3922 // it's lookup structure. 3923 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 3924 Ctx->addDecl(UDir); 3925 else 3926 // Otherwise it is block-sope. using-directives will affect lookup 3927 // only to the end of scope. 3928 S->PushUsingDirective(UDir); 3929} 3930 3931 3932Decl *Sema::ActOnUsingDeclaration(Scope *S, 3933 AccessSpecifier AS, 3934 bool HasUsingKeyword, 3935 SourceLocation UsingLoc, 3936 CXXScopeSpec &SS, 3937 UnqualifiedId &Name, 3938 AttributeList *AttrList, 3939 bool IsTypeName, 3940 SourceLocation TypenameLoc) { 3941 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 3942 3943 switch (Name.getKind()) { 3944 case UnqualifiedId::IK_Identifier: 3945 case UnqualifiedId::IK_OperatorFunctionId: 3946 case UnqualifiedId::IK_LiteralOperatorId: 3947 case UnqualifiedId::IK_ConversionFunctionId: 3948 break; 3949 3950 case UnqualifiedId::IK_ConstructorName: 3951 case UnqualifiedId::IK_ConstructorTemplateId: 3952 // C++0x inherited constructors. 3953 if (getLangOptions().CPlusPlus0x) break; 3954 3955 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor) 3956 << SS.getRange(); 3957 return 0; 3958 3959 case UnqualifiedId::IK_DestructorName: 3960 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor) 3961 << SS.getRange(); 3962 return 0; 3963 3964 case UnqualifiedId::IK_TemplateId: 3965 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id) 3966 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 3967 return 0; 3968 } 3969 3970 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 3971 DeclarationName TargetName = TargetNameInfo.getName(); 3972 if (!TargetName) 3973 return 0; 3974 3975 // Warn about using declarations. 3976 // TODO: store that the declaration was written without 'using' and 3977 // talk about access decls instead of using decls in the 3978 // diagnostics. 3979 if (!HasUsingKeyword) { 3980 UsingLoc = Name.getSourceRange().getBegin(); 3981 3982 Diag(UsingLoc, diag::warn_access_decl_deprecated) 3983 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 3984 } 3985 3986 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 3987 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 3988 return 0; 3989 3990 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 3991 TargetNameInfo, AttrList, 3992 /* IsInstantiation */ false, 3993 IsTypeName, TypenameLoc); 3994 if (UD) 3995 PushOnScopeChains(UD, S, /*AddToContext*/ false); 3996 3997 return UD; 3998} 3999 4000/// \brief Determine whether a using declaration considers the given 4001/// declarations as "equivalent", e.g., if they are redeclarations of 4002/// the same entity or are both typedefs of the same type. 4003static bool 4004IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 4005 bool &SuppressRedeclaration) { 4006 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 4007 SuppressRedeclaration = false; 4008 return true; 4009 } 4010 4011 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1)) 4012 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) { 4013 SuppressRedeclaration = true; 4014 return Context.hasSameType(TD1->getUnderlyingType(), 4015 TD2->getUnderlyingType()); 4016 } 4017 4018 return false; 4019} 4020 4021 4022/// Determines whether to create a using shadow decl for a particular 4023/// decl, given the set of decls existing prior to this using lookup. 4024bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 4025 const LookupResult &Previous) { 4026 // Diagnose finding a decl which is not from a base class of the 4027 // current class. We do this now because there are cases where this 4028 // function will silently decide not to build a shadow decl, which 4029 // will pre-empt further diagnostics. 4030 // 4031 // We don't need to do this in C++0x because we do the check once on 4032 // the qualifier. 4033 // 4034 // FIXME: diagnose the following if we care enough: 4035 // struct A { int foo; }; 4036 // struct B : A { using A::foo; }; 4037 // template <class T> struct C : A {}; 4038 // template <class T> struct D : C<T> { using B::foo; } // <--- 4039 // This is invalid (during instantiation) in C++03 because B::foo 4040 // resolves to the using decl in B, which is not a base class of D<T>. 4041 // We can't diagnose it immediately because C<T> is an unknown 4042 // specialization. The UsingShadowDecl in D<T> then points directly 4043 // to A::foo, which will look well-formed when we instantiate. 4044 // The right solution is to not collapse the shadow-decl chain. 4045 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) { 4046 DeclContext *OrigDC = Orig->getDeclContext(); 4047 4048 // Handle enums and anonymous structs. 4049 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 4050 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 4051 while (OrigRec->isAnonymousStructOrUnion()) 4052 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 4053 4054 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 4055 if (OrigDC == CurContext) { 4056 Diag(Using->getLocation(), 4057 diag::err_using_decl_nested_name_specifier_is_current_class) 4058 << Using->getQualifierLoc().getSourceRange(); 4059 Diag(Orig->getLocation(), diag::note_using_decl_target); 4060 return true; 4061 } 4062 4063 Diag(Using->getQualifierLoc().getBeginLoc(), 4064 diag::err_using_decl_nested_name_specifier_is_not_base_class) 4065 << Using->getQualifier() 4066 << cast<CXXRecordDecl>(CurContext) 4067 << Using->getQualifierLoc().getSourceRange(); 4068 Diag(Orig->getLocation(), diag::note_using_decl_target); 4069 return true; 4070 } 4071 } 4072 4073 if (Previous.empty()) return false; 4074 4075 NamedDecl *Target = Orig; 4076 if (isa<UsingShadowDecl>(Target)) 4077 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 4078 4079 // If the target happens to be one of the previous declarations, we 4080 // don't have a conflict. 4081 // 4082 // FIXME: but we might be increasing its access, in which case we 4083 // should redeclare it. 4084 NamedDecl *NonTag = 0, *Tag = 0; 4085 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 4086 I != E; ++I) { 4087 NamedDecl *D = (*I)->getUnderlyingDecl(); 4088 bool Result; 4089 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 4090 return Result; 4091 4092 (isa<TagDecl>(D) ? Tag : NonTag) = D; 4093 } 4094 4095 if (Target->isFunctionOrFunctionTemplate()) { 4096 FunctionDecl *FD; 4097 if (isa<FunctionTemplateDecl>(Target)) 4098 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 4099 else 4100 FD = cast<FunctionDecl>(Target); 4101 4102 NamedDecl *OldDecl = 0; 4103 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 4104 case Ovl_Overload: 4105 return false; 4106 4107 case Ovl_NonFunction: 4108 Diag(Using->getLocation(), diag::err_using_decl_conflict); 4109 break; 4110 4111 // We found a decl with the exact signature. 4112 case Ovl_Match: 4113 // If we're in a record, we want to hide the target, so we 4114 // return true (without a diagnostic) to tell the caller not to 4115 // build a shadow decl. 4116 if (CurContext->isRecord()) 4117 return true; 4118 4119 // If we're not in a record, this is an error. 4120 Diag(Using->getLocation(), diag::err_using_decl_conflict); 4121 break; 4122 } 4123 4124 Diag(Target->getLocation(), diag::note_using_decl_target); 4125 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 4126 return true; 4127 } 4128 4129 // Target is not a function. 4130 4131 if (isa<TagDecl>(Target)) { 4132 // No conflict between a tag and a non-tag. 4133 if (!Tag) return false; 4134 4135 Diag(Using->getLocation(), diag::err_using_decl_conflict); 4136 Diag(Target->getLocation(), diag::note_using_decl_target); 4137 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 4138 return true; 4139 } 4140 4141 // No conflict between a tag and a non-tag. 4142 if (!NonTag) return false; 4143 4144 Diag(Using->getLocation(), diag::err_using_decl_conflict); 4145 Diag(Target->getLocation(), diag::note_using_decl_target); 4146 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 4147 return true; 4148} 4149 4150/// Builds a shadow declaration corresponding to a 'using' declaration. 4151UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 4152 UsingDecl *UD, 4153 NamedDecl *Orig) { 4154 4155 // If we resolved to another shadow declaration, just coalesce them. 4156 NamedDecl *Target = Orig; 4157 if (isa<UsingShadowDecl>(Target)) { 4158 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 4159 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 4160 } 4161 4162 UsingShadowDecl *Shadow 4163 = UsingShadowDecl::Create(Context, CurContext, 4164 UD->getLocation(), UD, Target); 4165 UD->addShadowDecl(Shadow); 4166 4167 Shadow->setAccess(UD->getAccess()); 4168 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 4169 Shadow->setInvalidDecl(); 4170 4171 if (S) 4172 PushOnScopeChains(Shadow, S); 4173 else 4174 CurContext->addDecl(Shadow); 4175 4176 4177 return Shadow; 4178} 4179 4180/// Hides a using shadow declaration. This is required by the current 4181/// using-decl implementation when a resolvable using declaration in a 4182/// class is followed by a declaration which would hide or override 4183/// one or more of the using decl's targets; for example: 4184/// 4185/// struct Base { void foo(int); }; 4186/// struct Derived : Base { 4187/// using Base::foo; 4188/// void foo(int); 4189/// }; 4190/// 4191/// The governing language is C++03 [namespace.udecl]p12: 4192/// 4193/// When a using-declaration brings names from a base class into a 4194/// derived class scope, member functions in the derived class 4195/// override and/or hide member functions with the same name and 4196/// parameter types in a base class (rather than conflicting). 4197/// 4198/// There are two ways to implement this: 4199/// (1) optimistically create shadow decls when they're not hidden 4200/// by existing declarations, or 4201/// (2) don't create any shadow decls (or at least don't make them 4202/// visible) until we've fully parsed/instantiated the class. 4203/// The problem with (1) is that we might have to retroactively remove 4204/// a shadow decl, which requires several O(n) operations because the 4205/// decl structures are (very reasonably) not designed for removal. 4206/// (2) avoids this but is very fiddly and phase-dependent. 4207void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 4208 if (Shadow->getDeclName().getNameKind() == 4209 DeclarationName::CXXConversionFunctionName) 4210 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 4211 4212 // Remove it from the DeclContext... 4213 Shadow->getDeclContext()->removeDecl(Shadow); 4214 4215 // ...and the scope, if applicable... 4216 if (S) { 4217 S->RemoveDecl(Shadow); 4218 IdResolver.RemoveDecl(Shadow); 4219 } 4220 4221 // ...and the using decl. 4222 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 4223 4224 // TODO: complain somehow if Shadow was used. It shouldn't 4225 // be possible for this to happen, because...? 4226} 4227 4228/// Builds a using declaration. 4229/// 4230/// \param IsInstantiation - Whether this call arises from an 4231/// instantiation of an unresolved using declaration. We treat 4232/// the lookup differently for these declarations. 4233NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 4234 SourceLocation UsingLoc, 4235 CXXScopeSpec &SS, 4236 const DeclarationNameInfo &NameInfo, 4237 AttributeList *AttrList, 4238 bool IsInstantiation, 4239 bool IsTypeName, 4240 SourceLocation TypenameLoc) { 4241 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 4242 SourceLocation IdentLoc = NameInfo.getLoc(); 4243 assert(IdentLoc.isValid() && "Invalid TargetName location."); 4244 4245 // FIXME: We ignore attributes for now. 4246 4247 if (SS.isEmpty()) { 4248 Diag(IdentLoc, diag::err_using_requires_qualname); 4249 return 0; 4250 } 4251 4252 // Do the redeclaration lookup in the current scope. 4253 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 4254 ForRedeclaration); 4255 Previous.setHideTags(false); 4256 if (S) { 4257 LookupName(Previous, S); 4258 4259 // It is really dumb that we have to do this. 4260 LookupResult::Filter F = Previous.makeFilter(); 4261 while (F.hasNext()) { 4262 NamedDecl *D = F.next(); 4263 if (!isDeclInScope(D, CurContext, S)) 4264 F.erase(); 4265 } 4266 F.done(); 4267 } else { 4268 assert(IsInstantiation && "no scope in non-instantiation"); 4269 assert(CurContext->isRecord() && "scope not record in instantiation"); 4270 LookupQualifiedName(Previous, CurContext); 4271 } 4272 4273 // Check for invalid redeclarations. 4274 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 4275 return 0; 4276 4277 // Check for bad qualifiers. 4278 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 4279 return 0; 4280 4281 DeclContext *LookupContext = computeDeclContext(SS); 4282 NamedDecl *D; 4283 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 4284 if (!LookupContext) { 4285 if (IsTypeName) { 4286 // FIXME: not all declaration name kinds are legal here 4287 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 4288 UsingLoc, TypenameLoc, 4289 QualifierLoc, 4290 IdentLoc, NameInfo.getName()); 4291 } else { 4292 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 4293 QualifierLoc, NameInfo); 4294 } 4295 } else { 4296 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 4297 NameInfo, IsTypeName); 4298 } 4299 D->setAccess(AS); 4300 CurContext->addDecl(D); 4301 4302 if (!LookupContext) return D; 4303 UsingDecl *UD = cast<UsingDecl>(D); 4304 4305 if (RequireCompleteDeclContext(SS, LookupContext)) { 4306 UD->setInvalidDecl(); 4307 return UD; 4308 } 4309 4310 // Constructor inheriting using decls get special treatment. 4311 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 4312 if (CheckInheritedConstructorUsingDecl(UD)) 4313 UD->setInvalidDecl(); 4314 return UD; 4315 } 4316 4317 // Otherwise, look up the target name. 4318 4319 LookupResult R(*this, NameInfo, LookupOrdinaryName); 4320 4321 // Unlike most lookups, we don't always want to hide tag 4322 // declarations: tag names are visible through the using declaration 4323 // even if hidden by ordinary names, *except* in a dependent context 4324 // where it's important for the sanity of two-phase lookup. 4325 if (!IsInstantiation) 4326 R.setHideTags(false); 4327 4328 LookupQualifiedName(R, LookupContext); 4329 4330 if (R.empty()) { 4331 Diag(IdentLoc, diag::err_no_member) 4332 << NameInfo.getName() << LookupContext << SS.getRange(); 4333 UD->setInvalidDecl(); 4334 return UD; 4335 } 4336 4337 if (R.isAmbiguous()) { 4338 UD->setInvalidDecl(); 4339 return UD; 4340 } 4341 4342 if (IsTypeName) { 4343 // If we asked for a typename and got a non-type decl, error out. 4344 if (!R.getAsSingle<TypeDecl>()) { 4345 Diag(IdentLoc, diag::err_using_typename_non_type); 4346 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 4347 Diag((*I)->getUnderlyingDecl()->getLocation(), 4348 diag::note_using_decl_target); 4349 UD->setInvalidDecl(); 4350 return UD; 4351 } 4352 } else { 4353 // If we asked for a non-typename and we got a type, error out, 4354 // but only if this is an instantiation of an unresolved using 4355 // decl. Otherwise just silently find the type name. 4356 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 4357 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 4358 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 4359 UD->setInvalidDecl(); 4360 return UD; 4361 } 4362 } 4363 4364 // C++0x N2914 [namespace.udecl]p6: 4365 // A using-declaration shall not name a namespace. 4366 if (R.getAsSingle<NamespaceDecl>()) { 4367 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 4368 << SS.getRange(); 4369 UD->setInvalidDecl(); 4370 return UD; 4371 } 4372 4373 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 4374 if (!CheckUsingShadowDecl(UD, *I, Previous)) 4375 BuildUsingShadowDecl(S, UD, *I); 4376 } 4377 4378 return UD; 4379} 4380 4381/// Additional checks for a using declaration referring to a constructor name. 4382bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) { 4383 if (UD->isTypeName()) { 4384 // FIXME: Cannot specify typename when specifying constructor 4385 return true; 4386 } 4387 4388 const Type *SourceType = UD->getQualifier()->getAsType(); 4389 assert(SourceType && 4390 "Using decl naming constructor doesn't have type in scope spec."); 4391 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 4392 4393 // Check whether the named type is a direct base class. 4394 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 4395 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 4396 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 4397 BaseIt != BaseE; ++BaseIt) { 4398 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 4399 if (CanonicalSourceType == BaseType) 4400 break; 4401 } 4402 4403 if (BaseIt == BaseE) { 4404 // Did not find SourceType in the bases. 4405 Diag(UD->getUsingLocation(), 4406 diag::err_using_decl_constructor_not_in_direct_base) 4407 << UD->getNameInfo().getSourceRange() 4408 << QualType(SourceType, 0) << TargetClass; 4409 return true; 4410 } 4411 4412 BaseIt->setInheritConstructors(); 4413 4414 return false; 4415} 4416 4417/// Checks that the given using declaration is not an invalid 4418/// redeclaration. Note that this is checking only for the using decl 4419/// itself, not for any ill-formedness among the UsingShadowDecls. 4420bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 4421 bool isTypeName, 4422 const CXXScopeSpec &SS, 4423 SourceLocation NameLoc, 4424 const LookupResult &Prev) { 4425 // C++03 [namespace.udecl]p8: 4426 // C++0x [namespace.udecl]p10: 4427 // A using-declaration is a declaration and can therefore be used 4428 // repeatedly where (and only where) multiple declarations are 4429 // allowed. 4430 // 4431 // That's in non-member contexts. 4432 if (!CurContext->getRedeclContext()->isRecord()) 4433 return false; 4434 4435 NestedNameSpecifier *Qual 4436 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 4437 4438 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 4439 NamedDecl *D = *I; 4440 4441 bool DTypename; 4442 NestedNameSpecifier *DQual; 4443 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 4444 DTypename = UD->isTypeName(); 4445 DQual = UD->getQualifier(); 4446 } else if (UnresolvedUsingValueDecl *UD 4447 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 4448 DTypename = false; 4449 DQual = UD->getQualifier(); 4450 } else if (UnresolvedUsingTypenameDecl *UD 4451 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 4452 DTypename = true; 4453 DQual = UD->getQualifier(); 4454 } else continue; 4455 4456 // using decls differ if one says 'typename' and the other doesn't. 4457 // FIXME: non-dependent using decls? 4458 if (isTypeName != DTypename) continue; 4459 4460 // using decls differ if they name different scopes (but note that 4461 // template instantiation can cause this check to trigger when it 4462 // didn't before instantiation). 4463 if (Context.getCanonicalNestedNameSpecifier(Qual) != 4464 Context.getCanonicalNestedNameSpecifier(DQual)) 4465 continue; 4466 4467 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 4468 Diag(D->getLocation(), diag::note_using_decl) << 1; 4469 return true; 4470 } 4471 4472 return false; 4473} 4474 4475 4476/// Checks that the given nested-name qualifier used in a using decl 4477/// in the current context is appropriately related to the current 4478/// scope. If an error is found, diagnoses it and returns true. 4479bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 4480 const CXXScopeSpec &SS, 4481 SourceLocation NameLoc) { 4482 DeclContext *NamedContext = computeDeclContext(SS); 4483 4484 if (!CurContext->isRecord()) { 4485 // C++03 [namespace.udecl]p3: 4486 // C++0x [namespace.udecl]p8: 4487 // A using-declaration for a class member shall be a member-declaration. 4488 4489 // If we weren't able to compute a valid scope, it must be a 4490 // dependent class scope. 4491 if (!NamedContext || NamedContext->isRecord()) { 4492 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 4493 << SS.getRange(); 4494 return true; 4495 } 4496 4497 // Otherwise, everything is known to be fine. 4498 return false; 4499 } 4500 4501 // The current scope is a record. 4502 4503 // If the named context is dependent, we can't decide much. 4504 if (!NamedContext) { 4505 // FIXME: in C++0x, we can diagnose if we can prove that the 4506 // nested-name-specifier does not refer to a base class, which is 4507 // still possible in some cases. 4508 4509 // Otherwise we have to conservatively report that things might be 4510 // okay. 4511 return false; 4512 } 4513 4514 if (!NamedContext->isRecord()) { 4515 // Ideally this would point at the last name in the specifier, 4516 // but we don't have that level of source info. 4517 Diag(SS.getRange().getBegin(), 4518 diag::err_using_decl_nested_name_specifier_is_not_class) 4519 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 4520 return true; 4521 } 4522 4523 if (!NamedContext->isDependentContext() && 4524 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 4525 return true; 4526 4527 if (getLangOptions().CPlusPlus0x) { 4528 // C++0x [namespace.udecl]p3: 4529 // In a using-declaration used as a member-declaration, the 4530 // nested-name-specifier shall name a base class of the class 4531 // being defined. 4532 4533 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 4534 cast<CXXRecordDecl>(NamedContext))) { 4535 if (CurContext == NamedContext) { 4536 Diag(NameLoc, 4537 diag::err_using_decl_nested_name_specifier_is_current_class) 4538 << SS.getRange(); 4539 return true; 4540 } 4541 4542 Diag(SS.getRange().getBegin(), 4543 diag::err_using_decl_nested_name_specifier_is_not_base_class) 4544 << (NestedNameSpecifier*) SS.getScopeRep() 4545 << cast<CXXRecordDecl>(CurContext) 4546 << SS.getRange(); 4547 return true; 4548 } 4549 4550 return false; 4551 } 4552 4553 // C++03 [namespace.udecl]p4: 4554 // A using-declaration used as a member-declaration shall refer 4555 // to a member of a base class of the class being defined [etc.]. 4556 4557 // Salient point: SS doesn't have to name a base class as long as 4558 // lookup only finds members from base classes. Therefore we can 4559 // diagnose here only if we can prove that that can't happen, 4560 // i.e. if the class hierarchies provably don't intersect. 4561 4562 // TODO: it would be nice if "definitely valid" results were cached 4563 // in the UsingDecl and UsingShadowDecl so that these checks didn't 4564 // need to be repeated. 4565 4566 struct UserData { 4567 llvm::DenseSet<const CXXRecordDecl*> Bases; 4568 4569 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 4570 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 4571 Data->Bases.insert(Base); 4572 return true; 4573 } 4574 4575 bool hasDependentBases(const CXXRecordDecl *Class) { 4576 return !Class->forallBases(collect, this); 4577 } 4578 4579 /// Returns true if the base is dependent or is one of the 4580 /// accumulated base classes. 4581 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 4582 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 4583 return !Data->Bases.count(Base); 4584 } 4585 4586 bool mightShareBases(const CXXRecordDecl *Class) { 4587 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 4588 } 4589 }; 4590 4591 UserData Data; 4592 4593 // Returns false if we find a dependent base. 4594 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 4595 return false; 4596 4597 // Returns false if the class has a dependent base or if it or one 4598 // of its bases is present in the base set of the current context. 4599 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 4600 return false; 4601 4602 Diag(SS.getRange().getBegin(), 4603 diag::err_using_decl_nested_name_specifier_is_not_base_class) 4604 << (NestedNameSpecifier*) SS.getScopeRep() 4605 << cast<CXXRecordDecl>(CurContext) 4606 << SS.getRange(); 4607 4608 return true; 4609} 4610 4611Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 4612 SourceLocation NamespaceLoc, 4613 SourceLocation AliasLoc, 4614 IdentifierInfo *Alias, 4615 CXXScopeSpec &SS, 4616 SourceLocation IdentLoc, 4617 IdentifierInfo *Ident) { 4618 4619 // Lookup the namespace name. 4620 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 4621 LookupParsedName(R, S, &SS); 4622 4623 // Check if we have a previous declaration with the same name. 4624 NamedDecl *PrevDecl 4625 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 4626 ForRedeclaration); 4627 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 4628 PrevDecl = 0; 4629 4630 if (PrevDecl) { 4631 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 4632 // We already have an alias with the same name that points to the same 4633 // namespace, so don't create a new one. 4634 // FIXME: At some point, we'll want to create the (redundant) 4635 // declaration to maintain better source information. 4636 if (!R.isAmbiguous() && !R.empty() && 4637 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 4638 return 0; 4639 } 4640 4641 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 4642 diag::err_redefinition_different_kind; 4643 Diag(AliasLoc, DiagID) << Alias; 4644 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 4645 return 0; 4646 } 4647 4648 if (R.isAmbiguous()) 4649 return 0; 4650 4651 if (R.empty()) { 4652 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false, 4653 CTC_NoKeywords, 0)) { 4654 if (R.getAsSingle<NamespaceDecl>() || 4655 R.getAsSingle<NamespaceAliasDecl>()) { 4656 if (DeclContext *DC = computeDeclContext(SS, false)) 4657 Diag(IdentLoc, diag::err_using_directive_member_suggest) 4658 << Ident << DC << Corrected << SS.getRange() 4659 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 4660 else 4661 Diag(IdentLoc, diag::err_using_directive_suggest) 4662 << Ident << Corrected 4663 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 4664 4665 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here) 4666 << Corrected; 4667 4668 Ident = Corrected.getAsIdentifierInfo(); 4669 } else { 4670 R.clear(); 4671 R.setLookupName(Ident); 4672 } 4673 } 4674 4675 if (R.empty()) { 4676 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 4677 return 0; 4678 } 4679 } 4680 4681 NamespaceAliasDecl *AliasDecl = 4682 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 4683 Alias, SS.getWithLocInContext(Context), 4684 IdentLoc, R.getFoundDecl()); 4685 4686 PushOnScopeChains(AliasDecl, S); 4687 return AliasDecl; 4688} 4689 4690namespace { 4691 /// \brief Scoped object used to handle the state changes required in Sema 4692 /// to implicitly define the body of a C++ member function; 4693 class ImplicitlyDefinedFunctionScope { 4694 Sema &S; 4695 Sema::ContextRAII SavedContext; 4696 4697 public: 4698 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method) 4699 : S(S), SavedContext(S, Method) 4700 { 4701 S.PushFunctionScope(); 4702 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 4703 } 4704 4705 ~ImplicitlyDefinedFunctionScope() { 4706 S.PopExpressionEvaluationContext(); 4707 S.PopFunctionOrBlockScope(); 4708 } 4709 }; 4710} 4711 4712static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self, 4713 CXXRecordDecl *D) { 4714 ASTContext &Context = Self.Context; 4715 QualType ClassType = Context.getTypeDeclType(D); 4716 DeclarationName ConstructorName 4717 = Context.DeclarationNames.getCXXConstructorName( 4718 Context.getCanonicalType(ClassType.getUnqualifiedType())); 4719 4720 DeclContext::lookup_const_iterator Con, ConEnd; 4721 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName); 4722 Con != ConEnd; ++Con) { 4723 // FIXME: In C++0x, a constructor template can be a default constructor. 4724 if (isa<FunctionTemplateDecl>(*Con)) 4725 continue; 4726 4727 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 4728 if (Constructor->isDefaultConstructor()) 4729 return Constructor; 4730 } 4731 return 0; 4732} 4733 4734CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 4735 CXXRecordDecl *ClassDecl) { 4736 // C++ [class.ctor]p5: 4737 // A default constructor for a class X is a constructor of class X 4738 // that can be called without an argument. If there is no 4739 // user-declared constructor for class X, a default constructor is 4740 // implicitly declared. An implicitly-declared default constructor 4741 // is an inline public member of its class. 4742 assert(!ClassDecl->hasUserDeclaredConstructor() && 4743 "Should not build implicit default constructor!"); 4744 4745 // C++ [except.spec]p14: 4746 // An implicitly declared special member function (Clause 12) shall have an 4747 // exception-specification. [...] 4748 ImplicitExceptionSpecification ExceptSpec(Context); 4749 4750 // Direct base-class constructors. 4751 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4752 BEnd = ClassDecl->bases_end(); 4753 B != BEnd; ++B) { 4754 if (B->isVirtual()) // Handled below. 4755 continue; 4756 4757 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 4758 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4759 if (!BaseClassDecl->hasDeclaredDefaultConstructor()) 4760 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl)); 4761 else if (CXXConstructorDecl *Constructor 4762 = getDefaultConstructorUnsafe(*this, BaseClassDecl)) 4763 ExceptSpec.CalledDecl(Constructor); 4764 } 4765 } 4766 4767 // Virtual base-class constructors. 4768 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 4769 BEnd = ClassDecl->vbases_end(); 4770 B != BEnd; ++B) { 4771 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 4772 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4773 if (!BaseClassDecl->hasDeclaredDefaultConstructor()) 4774 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl)); 4775 else if (CXXConstructorDecl *Constructor 4776 = getDefaultConstructorUnsafe(*this, BaseClassDecl)) 4777 ExceptSpec.CalledDecl(Constructor); 4778 } 4779 } 4780 4781 // Field constructors. 4782 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4783 FEnd = ClassDecl->field_end(); 4784 F != FEnd; ++F) { 4785 if (const RecordType *RecordTy 4786 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4787 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4788 if (!FieldClassDecl->hasDeclaredDefaultConstructor()) 4789 ExceptSpec.CalledDecl( 4790 DeclareImplicitDefaultConstructor(FieldClassDecl)); 4791 else if (CXXConstructorDecl *Constructor 4792 = getDefaultConstructorUnsafe(*this, FieldClassDecl)) 4793 ExceptSpec.CalledDecl(Constructor); 4794 } 4795 } 4796 4797 FunctionProtoType::ExtProtoInfo EPI; 4798 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType(); 4799 EPI.NumExceptions = ExceptSpec.size(); 4800 EPI.Exceptions = ExceptSpec.data(); 4801 4802 // Create the actual constructor declaration. 4803 CanQualType ClassType 4804 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 4805 SourceLocation ClassLoc = ClassDecl->getLocation(); 4806 DeclarationName Name 4807 = Context.DeclarationNames.getCXXConstructorName(ClassType); 4808 DeclarationNameInfo NameInfo(Name, ClassLoc); 4809 CXXConstructorDecl *DefaultCon 4810 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 4811 Context.getFunctionType(Context.VoidTy, 4812 0, 0, EPI), 4813 /*TInfo=*/0, 4814 /*isExplicit=*/false, 4815 /*isInline=*/true, 4816 /*isImplicitlyDeclared=*/true); 4817 DefaultCon->setAccess(AS_public); 4818 DefaultCon->setImplicit(); 4819 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor()); 4820 4821 // Note that we have declared this constructor. 4822 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 4823 4824 if (Scope *S = getScopeForContext(ClassDecl)) 4825 PushOnScopeChains(DefaultCon, S, false); 4826 ClassDecl->addDecl(DefaultCon); 4827 4828 return DefaultCon; 4829} 4830 4831void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 4832 CXXConstructorDecl *Constructor) { 4833 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() && 4834 !Constructor->isUsed(false)) && 4835 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 4836 4837 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4838 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 4839 4840 ImplicitlyDefinedFunctionScope Scope(*this, Constructor); 4841 DiagnosticErrorTrap Trap(Diags); 4842 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) || 4843 Trap.hasErrorOccurred()) { 4844 Diag(CurrentLocation, diag::note_member_synthesized_at) 4845 << CXXConstructor << Context.getTagDeclType(ClassDecl); 4846 Constructor->setInvalidDecl(); 4847 return; 4848 } 4849 4850 SourceLocation Loc = Constructor->getLocation(); 4851 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 4852 4853 Constructor->setUsed(); 4854 MarkVTableUsed(CurrentLocation, ClassDecl); 4855} 4856 4857void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) { 4858 // We start with an initial pass over the base classes to collect those that 4859 // inherit constructors from. If there are none, we can forgo all further 4860 // processing. 4861 typedef llvm::SmallVector<const RecordType *, 4> BasesVector; 4862 BasesVector BasesToInheritFrom; 4863 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 4864 BaseE = ClassDecl->bases_end(); 4865 BaseIt != BaseE; ++BaseIt) { 4866 if (BaseIt->getInheritConstructors()) { 4867 QualType Base = BaseIt->getType(); 4868 if (Base->isDependentType()) { 4869 // If we inherit constructors from anything that is dependent, just 4870 // abort processing altogether. We'll get another chance for the 4871 // instantiations. 4872 return; 4873 } 4874 BasesToInheritFrom.push_back(Base->castAs<RecordType>()); 4875 } 4876 } 4877 if (BasesToInheritFrom.empty()) 4878 return; 4879 4880 // Now collect the constructors that we already have in the current class. 4881 // Those take precedence over inherited constructors. 4882 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...] 4883 // unless there is a user-declared constructor with the same signature in 4884 // the class where the using-declaration appears. 4885 llvm::SmallSet<const Type *, 8> ExistingConstructors; 4886 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(), 4887 CtorE = ClassDecl->ctor_end(); 4888 CtorIt != CtorE; ++CtorIt) { 4889 ExistingConstructors.insert( 4890 Context.getCanonicalType(CtorIt->getType()).getTypePtr()); 4891 } 4892 4893 Scope *S = getScopeForContext(ClassDecl); 4894 DeclarationName CreatedCtorName = 4895 Context.DeclarationNames.getCXXConstructorName( 4896 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified()); 4897 4898 // Now comes the true work. 4899 // First, we keep a map from constructor types to the base that introduced 4900 // them. Needed for finding conflicting constructors. We also keep the 4901 // actually inserted declarations in there, for pretty diagnostics. 4902 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo; 4903 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap; 4904 ConstructorToSourceMap InheritedConstructors; 4905 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(), 4906 BaseE = BasesToInheritFrom.end(); 4907 BaseIt != BaseE; ++BaseIt) { 4908 const RecordType *Base = *BaseIt; 4909 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified(); 4910 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl()); 4911 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(), 4912 CtorE = BaseDecl->ctor_end(); 4913 CtorIt != CtorE; ++CtorIt) { 4914 // Find the using declaration for inheriting this base's constructors. 4915 DeclarationName Name = 4916 Context.DeclarationNames.getCXXConstructorName(CanonicalBase); 4917 UsingDecl *UD = dyn_cast_or_null<UsingDecl>( 4918 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName)); 4919 SourceLocation UsingLoc = UD ? UD->getLocation() : 4920 ClassDecl->getLocation(); 4921 4922 // C++0x [class.inhctor]p1: The candidate set of inherited constructors 4923 // from the class X named in the using-declaration consists of actual 4924 // constructors and notional constructors that result from the 4925 // transformation of defaulted parameters as follows: 4926 // - all non-template default constructors of X, and 4927 // - for each non-template constructor of X that has at least one 4928 // parameter with a default argument, the set of constructors that 4929 // results from omitting any ellipsis parameter specification and 4930 // successively omitting parameters with a default argument from the 4931 // end of the parameter-type-list. 4932 CXXConstructorDecl *BaseCtor = *CtorIt; 4933 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor(); 4934 const FunctionProtoType *BaseCtorType = 4935 BaseCtor->getType()->getAs<FunctionProtoType>(); 4936 4937 for (unsigned params = BaseCtor->getMinRequiredArguments(), 4938 maxParams = BaseCtor->getNumParams(); 4939 params <= maxParams; ++params) { 4940 // Skip default constructors. They're never inherited. 4941 if (params == 0) 4942 continue; 4943 // Skip copy and move constructors for the same reason. 4944 if (CanBeCopyOrMove && params == 1) 4945 continue; 4946 4947 // Build up a function type for this particular constructor. 4948 // FIXME: The working paper does not consider that the exception spec 4949 // for the inheriting constructor might be larger than that of the 4950 // source. This code doesn't yet, either. 4951 const Type *NewCtorType; 4952 if (params == maxParams) 4953 NewCtorType = BaseCtorType; 4954 else { 4955 llvm::SmallVector<QualType, 16> Args; 4956 for (unsigned i = 0; i < params; ++i) { 4957 Args.push_back(BaseCtorType->getArgType(i)); 4958 } 4959 FunctionProtoType::ExtProtoInfo ExtInfo = 4960 BaseCtorType->getExtProtoInfo(); 4961 ExtInfo.Variadic = false; 4962 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(), 4963 Args.data(), params, ExtInfo) 4964 .getTypePtr(); 4965 } 4966 const Type *CanonicalNewCtorType = 4967 Context.getCanonicalType(NewCtorType); 4968 4969 // Now that we have the type, first check if the class already has a 4970 // constructor with this signature. 4971 if (ExistingConstructors.count(CanonicalNewCtorType)) 4972 continue; 4973 4974 // Then we check if we have already declared an inherited constructor 4975 // with this signature. 4976 std::pair<ConstructorToSourceMap::iterator, bool> result = 4977 InheritedConstructors.insert(std::make_pair( 4978 CanonicalNewCtorType, 4979 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0))); 4980 if (!result.second) { 4981 // Already in the map. If it came from a different class, that's an 4982 // error. Not if it's from the same. 4983 CanQualType PreviousBase = result.first->second.first; 4984 if (CanonicalBase != PreviousBase) { 4985 const CXXConstructorDecl *PrevCtor = result.first->second.second; 4986 const CXXConstructorDecl *PrevBaseCtor = 4987 PrevCtor->getInheritedConstructor(); 4988 assert(PrevBaseCtor && "Conflicting constructor was not inherited"); 4989 4990 Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 4991 Diag(BaseCtor->getLocation(), 4992 diag::note_using_decl_constructor_conflict_current_ctor); 4993 Diag(PrevBaseCtor->getLocation(), 4994 diag::note_using_decl_constructor_conflict_previous_ctor); 4995 Diag(PrevCtor->getLocation(), 4996 diag::note_using_decl_constructor_conflict_previous_using); 4997 } 4998 continue; 4999 } 5000 5001 // OK, we're there, now add the constructor. 5002 // C++0x [class.inhctor]p8: [...] that would be performed by a 5003 // user-writtern inline constructor [...] 5004 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc); 5005 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create( 5006 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0), 5007 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true, 5008 /*ImplicitlyDeclared=*/true); 5009 NewCtor->setAccess(BaseCtor->getAccess()); 5010 5011 // Build up the parameter decls and add them. 5012 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls; 5013 for (unsigned i = 0; i < params; ++i) { 5014 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor, 5015 UsingLoc, UsingLoc, 5016 /*IdentifierInfo=*/0, 5017 BaseCtorType->getArgType(i), 5018 /*TInfo=*/0, SC_None, 5019 SC_None, /*DefaultArg=*/0)); 5020 } 5021 NewCtor->setParams(ParamDecls.data(), ParamDecls.size()); 5022 NewCtor->setInheritedConstructor(BaseCtor); 5023 5024 PushOnScopeChains(NewCtor, S, false); 5025 ClassDecl->addDecl(NewCtor); 5026 result.first->second.second = NewCtor; 5027 } 5028 } 5029 } 5030} 5031 5032CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 5033 // C++ [class.dtor]p2: 5034 // If a class has no user-declared destructor, a destructor is 5035 // declared implicitly. An implicitly-declared destructor is an 5036 // inline public member of its class. 5037 5038 // C++ [except.spec]p14: 5039 // An implicitly declared special member function (Clause 12) shall have 5040 // an exception-specification. 5041 ImplicitExceptionSpecification ExceptSpec(Context); 5042 5043 // Direct base-class destructors. 5044 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 5045 BEnd = ClassDecl->bases_end(); 5046 B != BEnd; ++B) { 5047 if (B->isVirtual()) // Handled below. 5048 continue; 5049 5050 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 5051 ExceptSpec.CalledDecl( 5052 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 5053 } 5054 5055 // Virtual base-class destructors. 5056 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 5057 BEnd = ClassDecl->vbases_end(); 5058 B != BEnd; ++B) { 5059 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 5060 ExceptSpec.CalledDecl( 5061 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 5062 } 5063 5064 // Field destructors. 5065 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 5066 FEnd = ClassDecl->field_end(); 5067 F != FEnd; ++F) { 5068 if (const RecordType *RecordTy 5069 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 5070 ExceptSpec.CalledDecl( 5071 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 5072 } 5073 5074 // Create the actual destructor declaration. 5075 FunctionProtoType::ExtProtoInfo EPI; 5076 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType(); 5077 EPI.NumExceptions = ExceptSpec.size(); 5078 EPI.Exceptions = ExceptSpec.data(); 5079 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 5080 5081 CanQualType ClassType 5082 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 5083 SourceLocation ClassLoc = ClassDecl->getLocation(); 5084 DeclarationName Name 5085 = Context.DeclarationNames.getCXXDestructorName(ClassType); 5086 DeclarationNameInfo NameInfo(Name, ClassLoc); 5087 CXXDestructorDecl *Destructor 5088 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0, 5089 /*isInline=*/true, 5090 /*isImplicitlyDeclared=*/true); 5091 Destructor->setAccess(AS_public); 5092 Destructor->setImplicit(); 5093 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 5094 5095 // Note that we have declared this destructor. 5096 ++ASTContext::NumImplicitDestructorsDeclared; 5097 5098 // Introduce this destructor into its scope. 5099 if (Scope *S = getScopeForContext(ClassDecl)) 5100 PushOnScopeChains(Destructor, S, false); 5101 ClassDecl->addDecl(Destructor); 5102 5103 // This could be uniqued if it ever proves significant. 5104 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty)); 5105 5106 AddOverriddenMethods(ClassDecl, Destructor); 5107 5108 return Destructor; 5109} 5110 5111void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 5112 CXXDestructorDecl *Destructor) { 5113 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) && 5114 "DefineImplicitDestructor - call it for implicit default dtor"); 5115 CXXRecordDecl *ClassDecl = Destructor->getParent(); 5116 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 5117 5118 if (Destructor->isInvalidDecl()) 5119 return; 5120 5121 ImplicitlyDefinedFunctionScope Scope(*this, Destructor); 5122 5123 DiagnosticErrorTrap Trap(Diags); 5124 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 5125 Destructor->getParent()); 5126 5127 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 5128 Diag(CurrentLocation, diag::note_member_synthesized_at) 5129 << CXXDestructor << Context.getTagDeclType(ClassDecl); 5130 5131 Destructor->setInvalidDecl(); 5132 return; 5133 } 5134 5135 SourceLocation Loc = Destructor->getLocation(); 5136 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 5137 5138 Destructor->setUsed(); 5139 MarkVTableUsed(CurrentLocation, ClassDecl); 5140} 5141 5142/// \brief Builds a statement that copies the given entity from \p From to 5143/// \c To. 5144/// 5145/// This routine is used to copy the members of a class with an 5146/// implicitly-declared copy assignment operator. When the entities being 5147/// copied are arrays, this routine builds for loops to copy them. 5148/// 5149/// \param S The Sema object used for type-checking. 5150/// 5151/// \param Loc The location where the implicit copy is being generated. 5152/// 5153/// \param T The type of the expressions being copied. Both expressions must 5154/// have this type. 5155/// 5156/// \param To The expression we are copying to. 5157/// 5158/// \param From The expression we are copying from. 5159/// 5160/// \param CopyingBaseSubobject Whether we're copying a base subobject. 5161/// Otherwise, it's a non-static member subobject. 5162/// 5163/// \param Depth Internal parameter recording the depth of the recursion. 5164/// 5165/// \returns A statement or a loop that copies the expressions. 5166static StmtResult 5167BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 5168 Expr *To, Expr *From, 5169 bool CopyingBaseSubobject, unsigned Depth = 0) { 5170 // C++0x [class.copy]p30: 5171 // Each subobject is assigned in the manner appropriate to its type: 5172 // 5173 // - if the subobject is of class type, the copy assignment operator 5174 // for the class is used (as if by explicit qualification; that is, 5175 // ignoring any possible virtual overriding functions in more derived 5176 // classes); 5177 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 5178 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 5179 5180 // Look for operator=. 5181 DeclarationName Name 5182 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 5183 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 5184 S.LookupQualifiedName(OpLookup, ClassDecl, false); 5185 5186 // Filter out any result that isn't a copy-assignment operator. 5187 LookupResult::Filter F = OpLookup.makeFilter(); 5188 while (F.hasNext()) { 5189 NamedDecl *D = F.next(); 5190 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 5191 if (Method->isCopyAssignmentOperator()) 5192 continue; 5193 5194 F.erase(); 5195 } 5196 F.done(); 5197 5198 // Suppress the protected check (C++ [class.protected]) for each of the 5199 // assignment operators we found. This strange dance is required when 5200 // we're assigning via a base classes's copy-assignment operator. To 5201 // ensure that we're getting the right base class subobject (without 5202 // ambiguities), we need to cast "this" to that subobject type; to 5203 // ensure that we don't go through the virtual call mechanism, we need 5204 // to qualify the operator= name with the base class (see below). However, 5205 // this means that if the base class has a protected copy assignment 5206 // operator, the protected member access check will fail. So, we 5207 // rewrite "protected" access to "public" access in this case, since we 5208 // know by construction that we're calling from a derived class. 5209 if (CopyingBaseSubobject) { 5210 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 5211 L != LEnd; ++L) { 5212 if (L.getAccess() == AS_protected) 5213 L.setAccess(AS_public); 5214 } 5215 } 5216 5217 // Create the nested-name-specifier that will be used to qualify the 5218 // reference to operator=; this is required to suppress the virtual 5219 // call mechanism. 5220 CXXScopeSpec SS; 5221 SS.MakeTrivial(S.Context, 5222 NestedNameSpecifier::Create(S.Context, 0, false, 5223 T.getTypePtr()), 5224 Loc); 5225 5226 // Create the reference to operator=. 5227 ExprResult OpEqualRef 5228 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 5229 /*FirstQualifierInScope=*/0, OpLookup, 5230 /*TemplateArgs=*/0, 5231 /*SuppressQualifierCheck=*/true); 5232 if (OpEqualRef.isInvalid()) 5233 return StmtError(); 5234 5235 // Build the call to the assignment operator. 5236 5237 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 5238 OpEqualRef.takeAs<Expr>(), 5239 Loc, &From, 1, Loc); 5240 if (Call.isInvalid()) 5241 return StmtError(); 5242 5243 return S.Owned(Call.takeAs<Stmt>()); 5244 } 5245 5246 // - if the subobject is of scalar type, the built-in assignment 5247 // operator is used. 5248 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 5249 if (!ArrayTy) { 5250 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 5251 if (Assignment.isInvalid()) 5252 return StmtError(); 5253 5254 return S.Owned(Assignment.takeAs<Stmt>()); 5255 } 5256 5257 // - if the subobject is an array, each element is assigned, in the 5258 // manner appropriate to the element type; 5259 5260 // Construct a loop over the array bounds, e.g., 5261 // 5262 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 5263 // 5264 // that will copy each of the array elements. 5265 QualType SizeType = S.Context.getSizeType(); 5266 5267 // Create the iteration variable. 5268 IdentifierInfo *IterationVarName = 0; 5269 { 5270 llvm::SmallString<8> Str; 5271 llvm::raw_svector_ostream OS(Str); 5272 OS << "__i" << Depth; 5273 IterationVarName = &S.Context.Idents.get(OS.str()); 5274 } 5275 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 5276 IterationVarName, SizeType, 5277 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 5278 SC_None, SC_None); 5279 5280 // Initialize the iteration variable to zero. 5281 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 5282 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 5283 5284 // Create a reference to the iteration variable; we'll use this several 5285 // times throughout. 5286 Expr *IterationVarRef 5287 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take(); 5288 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 5289 5290 // Create the DeclStmt that holds the iteration variable. 5291 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 5292 5293 // Create the comparison against the array bound. 5294 llvm::APInt Upper 5295 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 5296 Expr *Comparison 5297 = new (S.Context) BinaryOperator(IterationVarRef, 5298 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 5299 BO_NE, S.Context.BoolTy, 5300 VK_RValue, OK_Ordinary, Loc); 5301 5302 // Create the pre-increment of the iteration variable. 5303 Expr *Increment 5304 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 5305 VK_LValue, OK_Ordinary, Loc); 5306 5307 // Subscript the "from" and "to" expressions with the iteration variable. 5308 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 5309 IterationVarRef, Loc)); 5310 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 5311 IterationVarRef, Loc)); 5312 5313 // Build the copy for an individual element of the array. 5314 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(), 5315 To, From, CopyingBaseSubobject, 5316 Depth + 1); 5317 if (Copy.isInvalid()) 5318 return StmtError(); 5319 5320 // Construct the loop that copies all elements of this array. 5321 return S.ActOnForStmt(Loc, Loc, InitStmt, 5322 S.MakeFullExpr(Comparison), 5323 0, S.MakeFullExpr(Increment), 5324 Loc, Copy.take()); 5325} 5326 5327/// \brief Determine whether the given class has a copy assignment operator 5328/// that accepts a const-qualified argument. 5329static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) { 5330 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass); 5331 5332 if (!Class->hasDeclaredCopyAssignment()) 5333 S.DeclareImplicitCopyAssignment(Class); 5334 5335 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)); 5336 DeclarationName OpName 5337 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 5338 5339 DeclContext::lookup_const_iterator Op, OpEnd; 5340 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) { 5341 // C++ [class.copy]p9: 5342 // A user-declared copy assignment operator is a non-static non-template 5343 // member function of class X with exactly one parameter of type X, X&, 5344 // const X&, volatile X& or const volatile X&. 5345 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op); 5346 if (!Method) 5347 continue; 5348 5349 if (Method->isStatic()) 5350 continue; 5351 if (Method->getPrimaryTemplate()) 5352 continue; 5353 const FunctionProtoType *FnType = 5354 Method->getType()->getAs<FunctionProtoType>(); 5355 assert(FnType && "Overloaded operator has no prototype."); 5356 // Don't assert on this; an invalid decl might have been left in the AST. 5357 if (FnType->getNumArgs() != 1 || FnType->isVariadic()) 5358 continue; 5359 bool AcceptsConst = true; 5360 QualType ArgType = FnType->getArgType(0); 5361 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){ 5362 ArgType = Ref->getPointeeType(); 5363 // Is it a non-const lvalue reference? 5364 if (!ArgType.isConstQualified()) 5365 AcceptsConst = false; 5366 } 5367 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType)) 5368 continue; 5369 5370 // We have a single argument of type cv X or cv X&, i.e. we've found the 5371 // copy assignment operator. Return whether it accepts const arguments. 5372 return AcceptsConst; 5373 } 5374 assert(Class->isInvalidDecl() && 5375 "No copy assignment operator declared in valid code."); 5376 return false; 5377} 5378 5379CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 5380 // Note: The following rules are largely analoguous to the copy 5381 // constructor rules. Note that virtual bases are not taken into account 5382 // for determining the argument type of the operator. Note also that 5383 // operators taking an object instead of a reference are allowed. 5384 5385 5386 // C++ [class.copy]p10: 5387 // If the class definition does not explicitly declare a copy 5388 // assignment operator, one is declared implicitly. 5389 // The implicitly-defined copy assignment operator for a class X 5390 // will have the form 5391 // 5392 // X& X::operator=(const X&) 5393 // 5394 // if 5395 bool HasConstCopyAssignment = true; 5396 5397 // -- each direct base class B of X has a copy assignment operator 5398 // whose parameter is of type const B&, const volatile B& or B, 5399 // and 5400 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5401 BaseEnd = ClassDecl->bases_end(); 5402 HasConstCopyAssignment && Base != BaseEnd; ++Base) { 5403 assert(!Base->getType()->isDependentType() && 5404 "Cannot generate implicit members for class with dependent bases."); 5405 const CXXRecordDecl *BaseClassDecl 5406 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5407 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl); 5408 } 5409 5410 // -- for all the nonstatic data members of X that are of a class 5411 // type M (or array thereof), each such class type has a copy 5412 // assignment operator whose parameter is of type const M&, 5413 // const volatile M& or M. 5414 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 5415 FieldEnd = ClassDecl->field_end(); 5416 HasConstCopyAssignment && Field != FieldEnd; 5417 ++Field) { 5418 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 5419 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 5420 const CXXRecordDecl *FieldClassDecl 5421 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 5422 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl); 5423 } 5424 } 5425 5426 // Otherwise, the implicitly declared copy assignment operator will 5427 // have the form 5428 // 5429 // X& X::operator=(X&) 5430 QualType ArgType = Context.getTypeDeclType(ClassDecl); 5431 QualType RetType = Context.getLValueReferenceType(ArgType); 5432 if (HasConstCopyAssignment) 5433 ArgType = ArgType.withConst(); 5434 ArgType = Context.getLValueReferenceType(ArgType); 5435 5436 // C++ [except.spec]p14: 5437 // An implicitly declared special member function (Clause 12) shall have an 5438 // exception-specification. [...] 5439 ImplicitExceptionSpecification ExceptSpec(Context); 5440 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5441 BaseEnd = ClassDecl->bases_end(); 5442 Base != BaseEnd; ++Base) { 5443 CXXRecordDecl *BaseClassDecl 5444 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5445 5446 if (!BaseClassDecl->hasDeclaredCopyAssignment()) 5447 DeclareImplicitCopyAssignment(BaseClassDecl); 5448 5449 if (CXXMethodDecl *CopyAssign 5450 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment)) 5451 ExceptSpec.CalledDecl(CopyAssign); 5452 } 5453 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 5454 FieldEnd = ClassDecl->field_end(); 5455 Field != FieldEnd; 5456 ++Field) { 5457 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 5458 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 5459 CXXRecordDecl *FieldClassDecl 5460 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 5461 5462 if (!FieldClassDecl->hasDeclaredCopyAssignment()) 5463 DeclareImplicitCopyAssignment(FieldClassDecl); 5464 5465 if (CXXMethodDecl *CopyAssign 5466 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment)) 5467 ExceptSpec.CalledDecl(CopyAssign); 5468 } 5469 } 5470 5471 // An implicitly-declared copy assignment operator is an inline public 5472 // member of its class. 5473 FunctionProtoType::ExtProtoInfo EPI; 5474 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType(); 5475 EPI.NumExceptions = ExceptSpec.size(); 5476 EPI.Exceptions = ExceptSpec.data(); 5477 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 5478 SourceLocation ClassLoc = ClassDecl->getLocation(); 5479 DeclarationNameInfo NameInfo(Name, ClassLoc); 5480 CXXMethodDecl *CopyAssignment 5481 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 5482 Context.getFunctionType(RetType, &ArgType, 1, EPI), 5483 /*TInfo=*/0, /*isStatic=*/false, 5484 /*StorageClassAsWritten=*/SC_None, 5485 /*isInline=*/true, 5486 SourceLocation()); 5487 CopyAssignment->setAccess(AS_public); 5488 CopyAssignment->setImplicit(); 5489 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 5490 5491 // Add the parameter to the operator. 5492 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 5493 ClassLoc, ClassLoc, /*Id=*/0, 5494 ArgType, /*TInfo=*/0, 5495 SC_None, 5496 SC_None, 0); 5497 CopyAssignment->setParams(&FromParam, 1); 5498 5499 // Note that we have added this copy-assignment operator. 5500 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 5501 5502 if (Scope *S = getScopeForContext(ClassDecl)) 5503 PushOnScopeChains(CopyAssignment, S, false); 5504 ClassDecl->addDecl(CopyAssignment); 5505 5506 AddOverriddenMethods(ClassDecl, CopyAssignment); 5507 return CopyAssignment; 5508} 5509 5510void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 5511 CXXMethodDecl *CopyAssignOperator) { 5512 assert((CopyAssignOperator->isImplicit() && 5513 CopyAssignOperator->isOverloadedOperator() && 5514 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 5515 !CopyAssignOperator->isUsed(false)) && 5516 "DefineImplicitCopyAssignment called for wrong function"); 5517 5518 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 5519 5520 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 5521 CopyAssignOperator->setInvalidDecl(); 5522 return; 5523 } 5524 5525 CopyAssignOperator->setUsed(); 5526 5527 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator); 5528 DiagnosticErrorTrap Trap(Diags); 5529 5530 // C++0x [class.copy]p30: 5531 // The implicitly-defined or explicitly-defaulted copy assignment operator 5532 // for a non-union class X performs memberwise copy assignment of its 5533 // subobjects. The direct base classes of X are assigned first, in the 5534 // order of their declaration in the base-specifier-list, and then the 5535 // immediate non-static data members of X are assigned, in the order in 5536 // which they were declared in the class definition. 5537 5538 // The statements that form the synthesized function body. 5539 ASTOwningVector<Stmt*> Statements(*this); 5540 5541 // The parameter for the "other" object, which we are copying from. 5542 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 5543 Qualifiers OtherQuals = Other->getType().getQualifiers(); 5544 QualType OtherRefType = Other->getType(); 5545 if (const LValueReferenceType *OtherRef 5546 = OtherRefType->getAs<LValueReferenceType>()) { 5547 OtherRefType = OtherRef->getPointeeType(); 5548 OtherQuals = OtherRefType.getQualifiers(); 5549 } 5550 5551 // Our location for everything implicitly-generated. 5552 SourceLocation Loc = CopyAssignOperator->getLocation(); 5553 5554 // Construct a reference to the "other" object. We'll be using this 5555 // throughout the generated ASTs. 5556 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 5557 assert(OtherRef && "Reference to parameter cannot fail!"); 5558 5559 // Construct the "this" pointer. We'll be using this throughout the generated 5560 // ASTs. 5561 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 5562 assert(This && "Reference to this cannot fail!"); 5563 5564 // Assign base classes. 5565 bool Invalid = false; 5566 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5567 E = ClassDecl->bases_end(); Base != E; ++Base) { 5568 // Form the assignment: 5569 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 5570 QualType BaseType = Base->getType().getUnqualifiedType(); 5571 if (!BaseType->isRecordType()) { 5572 Invalid = true; 5573 continue; 5574 } 5575 5576 CXXCastPath BasePath; 5577 BasePath.push_back(Base); 5578 5579 // Construct the "from" expression, which is an implicit cast to the 5580 // appropriately-qualified base type. 5581 Expr *From = OtherRef; 5582 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 5583 CK_UncheckedDerivedToBase, 5584 VK_LValue, &BasePath); 5585 5586 // Dereference "this". 5587 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 5588 5589 // Implicitly cast "this" to the appropriately-qualified base type. 5590 Expr *ToE = To.takeAs<Expr>(); 5591 ImpCastExprToType(ToE, 5592 Context.getCVRQualifiedType(BaseType, 5593 CopyAssignOperator->getTypeQualifiers()), 5594 CK_UncheckedDerivedToBase, 5595 VK_LValue, &BasePath); 5596 To = Owned(ToE); 5597 5598 // Build the copy. 5599 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType, 5600 To.get(), From, 5601 /*CopyingBaseSubobject=*/true); 5602 if (Copy.isInvalid()) { 5603 Diag(CurrentLocation, diag::note_member_synthesized_at) 5604 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5605 CopyAssignOperator->setInvalidDecl(); 5606 return; 5607 } 5608 5609 // Success! Record the copy. 5610 Statements.push_back(Copy.takeAs<Expr>()); 5611 } 5612 5613 // \brief Reference to the __builtin_memcpy function. 5614 Expr *BuiltinMemCpyRef = 0; 5615 // \brief Reference to the __builtin_objc_memmove_collectable function. 5616 Expr *CollectableMemCpyRef = 0; 5617 5618 // Assign non-static members. 5619 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 5620 FieldEnd = ClassDecl->field_end(); 5621 Field != FieldEnd; ++Field) { 5622 // Check for members of reference type; we can't copy those. 5623 if (Field->getType()->isReferenceType()) { 5624 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 5625 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 5626 Diag(Field->getLocation(), diag::note_declared_at); 5627 Diag(CurrentLocation, diag::note_member_synthesized_at) 5628 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5629 Invalid = true; 5630 continue; 5631 } 5632 5633 // Check for members of const-qualified, non-class type. 5634 QualType BaseType = Context.getBaseElementType(Field->getType()); 5635 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 5636 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 5637 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 5638 Diag(Field->getLocation(), diag::note_declared_at); 5639 Diag(CurrentLocation, diag::note_member_synthesized_at) 5640 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5641 Invalid = true; 5642 continue; 5643 } 5644 5645 QualType FieldType = Field->getType().getNonReferenceType(); 5646 if (FieldType->isIncompleteArrayType()) { 5647 assert(ClassDecl->hasFlexibleArrayMember() && 5648 "Incomplete array type is not valid"); 5649 continue; 5650 } 5651 5652 // Build references to the field in the object we're copying from and to. 5653 CXXScopeSpec SS; // Intentionally empty 5654 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 5655 LookupMemberName); 5656 MemberLookup.addDecl(*Field); 5657 MemberLookup.resolveKind(); 5658 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 5659 Loc, /*IsArrow=*/false, 5660 SS, 0, MemberLookup, 0); 5661 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 5662 Loc, /*IsArrow=*/true, 5663 SS, 0, MemberLookup, 0); 5664 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 5665 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 5666 5667 // If the field should be copied with __builtin_memcpy rather than via 5668 // explicit assignments, do so. This optimization only applies for arrays 5669 // of scalars and arrays of class type with trivial copy-assignment 5670 // operators. 5671 if (FieldType->isArrayType() && 5672 (!BaseType->isRecordType() || 5673 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()) 5674 ->hasTrivialCopyAssignment())) { 5675 // Compute the size of the memory buffer to be copied. 5676 QualType SizeType = Context.getSizeType(); 5677 llvm::APInt Size(Context.getTypeSize(SizeType), 5678 Context.getTypeSizeInChars(BaseType).getQuantity()); 5679 for (const ConstantArrayType *Array 5680 = Context.getAsConstantArrayType(FieldType); 5681 Array; 5682 Array = Context.getAsConstantArrayType(Array->getElementType())) { 5683 llvm::APInt ArraySize 5684 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 5685 Size *= ArraySize; 5686 } 5687 5688 // Take the address of the field references for "from" and "to". 5689 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get()); 5690 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get()); 5691 5692 bool NeedsCollectableMemCpy = 5693 (BaseType->isRecordType() && 5694 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 5695 5696 if (NeedsCollectableMemCpy) { 5697 if (!CollectableMemCpyRef) { 5698 // Create a reference to the __builtin_objc_memmove_collectable function. 5699 LookupResult R(*this, 5700 &Context.Idents.get("__builtin_objc_memmove_collectable"), 5701 Loc, LookupOrdinaryName); 5702 LookupName(R, TUScope, true); 5703 5704 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 5705 if (!CollectableMemCpy) { 5706 // Something went horribly wrong earlier, and we will have 5707 // complained about it. 5708 Invalid = true; 5709 continue; 5710 } 5711 5712 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 5713 CollectableMemCpy->getType(), 5714 VK_LValue, Loc, 0).take(); 5715 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 5716 } 5717 } 5718 // Create a reference to the __builtin_memcpy builtin function. 5719 else if (!BuiltinMemCpyRef) { 5720 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 5721 LookupOrdinaryName); 5722 LookupName(R, TUScope, true); 5723 5724 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 5725 if (!BuiltinMemCpy) { 5726 // Something went horribly wrong earlier, and we will have complained 5727 // about it. 5728 Invalid = true; 5729 continue; 5730 } 5731 5732 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 5733 BuiltinMemCpy->getType(), 5734 VK_LValue, Loc, 0).take(); 5735 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 5736 } 5737 5738 ASTOwningVector<Expr*> CallArgs(*this); 5739 CallArgs.push_back(To.takeAs<Expr>()); 5740 CallArgs.push_back(From.takeAs<Expr>()); 5741 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 5742 ExprResult Call = ExprError(); 5743 if (NeedsCollectableMemCpy) 5744 Call = ActOnCallExpr(/*Scope=*/0, 5745 CollectableMemCpyRef, 5746 Loc, move_arg(CallArgs), 5747 Loc); 5748 else 5749 Call = ActOnCallExpr(/*Scope=*/0, 5750 BuiltinMemCpyRef, 5751 Loc, move_arg(CallArgs), 5752 Loc); 5753 5754 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 5755 Statements.push_back(Call.takeAs<Expr>()); 5756 continue; 5757 } 5758 5759 // Build the copy of this field. 5760 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType, 5761 To.get(), From.get(), 5762 /*CopyingBaseSubobject=*/false); 5763 if (Copy.isInvalid()) { 5764 Diag(CurrentLocation, diag::note_member_synthesized_at) 5765 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5766 CopyAssignOperator->setInvalidDecl(); 5767 return; 5768 } 5769 5770 // Success! Record the copy. 5771 Statements.push_back(Copy.takeAs<Stmt>()); 5772 } 5773 5774 if (!Invalid) { 5775 // Add a "return *this;" 5776 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 5777 5778 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 5779 if (Return.isInvalid()) 5780 Invalid = true; 5781 else { 5782 Statements.push_back(Return.takeAs<Stmt>()); 5783 5784 if (Trap.hasErrorOccurred()) { 5785 Diag(CurrentLocation, diag::note_member_synthesized_at) 5786 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5787 Invalid = true; 5788 } 5789 } 5790 } 5791 5792 if (Invalid) { 5793 CopyAssignOperator->setInvalidDecl(); 5794 return; 5795 } 5796 5797 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 5798 /*isStmtExpr=*/false); 5799 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 5800 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 5801} 5802 5803CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 5804 CXXRecordDecl *ClassDecl) { 5805 // C++ [class.copy]p4: 5806 // If the class definition does not explicitly declare a copy 5807 // constructor, one is declared implicitly. 5808 5809 // C++ [class.copy]p5: 5810 // The implicitly-declared copy constructor for a class X will 5811 // have the form 5812 // 5813 // X::X(const X&) 5814 // 5815 // if 5816 bool HasConstCopyConstructor = true; 5817 5818 // -- each direct or virtual base class B of X has a copy 5819 // constructor whose first parameter is of type const B& or 5820 // const volatile B&, and 5821 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5822 BaseEnd = ClassDecl->bases_end(); 5823 HasConstCopyConstructor && Base != BaseEnd; 5824 ++Base) { 5825 // Virtual bases are handled below. 5826 if (Base->isVirtual()) 5827 continue; 5828 5829 CXXRecordDecl *BaseClassDecl 5830 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5831 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 5832 DeclareImplicitCopyConstructor(BaseClassDecl); 5833 5834 HasConstCopyConstructor 5835 = BaseClassDecl->hasConstCopyConstructor(Context); 5836 } 5837 5838 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 5839 BaseEnd = ClassDecl->vbases_end(); 5840 HasConstCopyConstructor && Base != BaseEnd; 5841 ++Base) { 5842 CXXRecordDecl *BaseClassDecl 5843 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5844 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 5845 DeclareImplicitCopyConstructor(BaseClassDecl); 5846 5847 HasConstCopyConstructor 5848 = BaseClassDecl->hasConstCopyConstructor(Context); 5849 } 5850 5851 // -- for all the nonstatic data members of X that are of a 5852 // class type M (or array thereof), each such class type 5853 // has a copy constructor whose first parameter is of type 5854 // const M& or const volatile M&. 5855 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 5856 FieldEnd = ClassDecl->field_end(); 5857 HasConstCopyConstructor && Field != FieldEnd; 5858 ++Field) { 5859 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 5860 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 5861 CXXRecordDecl *FieldClassDecl 5862 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 5863 if (!FieldClassDecl->hasDeclaredCopyConstructor()) 5864 DeclareImplicitCopyConstructor(FieldClassDecl); 5865 5866 HasConstCopyConstructor 5867 = FieldClassDecl->hasConstCopyConstructor(Context); 5868 } 5869 } 5870 5871 // Otherwise, the implicitly declared copy constructor will have 5872 // the form 5873 // 5874 // X::X(X&) 5875 QualType ClassType = Context.getTypeDeclType(ClassDecl); 5876 QualType ArgType = ClassType; 5877 if (HasConstCopyConstructor) 5878 ArgType = ArgType.withConst(); 5879 ArgType = Context.getLValueReferenceType(ArgType); 5880 5881 // C++ [except.spec]p14: 5882 // An implicitly declared special member function (Clause 12) shall have an 5883 // exception-specification. [...] 5884 ImplicitExceptionSpecification ExceptSpec(Context); 5885 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0; 5886 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5887 BaseEnd = ClassDecl->bases_end(); 5888 Base != BaseEnd; 5889 ++Base) { 5890 // Virtual bases are handled below. 5891 if (Base->isVirtual()) 5892 continue; 5893 5894 CXXRecordDecl *BaseClassDecl 5895 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5896 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 5897 DeclareImplicitCopyConstructor(BaseClassDecl); 5898 5899 if (CXXConstructorDecl *CopyConstructor 5900 = BaseClassDecl->getCopyConstructor(Context, Quals)) 5901 ExceptSpec.CalledDecl(CopyConstructor); 5902 } 5903 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 5904 BaseEnd = ClassDecl->vbases_end(); 5905 Base != BaseEnd; 5906 ++Base) { 5907 CXXRecordDecl *BaseClassDecl 5908 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5909 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 5910 DeclareImplicitCopyConstructor(BaseClassDecl); 5911 5912 if (CXXConstructorDecl *CopyConstructor 5913 = BaseClassDecl->getCopyConstructor(Context, Quals)) 5914 ExceptSpec.CalledDecl(CopyConstructor); 5915 } 5916 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 5917 FieldEnd = ClassDecl->field_end(); 5918 Field != FieldEnd; 5919 ++Field) { 5920 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 5921 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 5922 CXXRecordDecl *FieldClassDecl 5923 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 5924 if (!FieldClassDecl->hasDeclaredCopyConstructor()) 5925 DeclareImplicitCopyConstructor(FieldClassDecl); 5926 5927 if (CXXConstructorDecl *CopyConstructor 5928 = FieldClassDecl->getCopyConstructor(Context, Quals)) 5929 ExceptSpec.CalledDecl(CopyConstructor); 5930 } 5931 } 5932 5933 // An implicitly-declared copy constructor is an inline public 5934 // member of its class. 5935 FunctionProtoType::ExtProtoInfo EPI; 5936 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType(); 5937 EPI.NumExceptions = ExceptSpec.size(); 5938 EPI.Exceptions = ExceptSpec.data(); 5939 DeclarationName Name 5940 = Context.DeclarationNames.getCXXConstructorName( 5941 Context.getCanonicalType(ClassType)); 5942 SourceLocation ClassLoc = ClassDecl->getLocation(); 5943 DeclarationNameInfo NameInfo(Name, ClassLoc); 5944 CXXConstructorDecl *CopyConstructor 5945 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 5946 Context.getFunctionType(Context.VoidTy, 5947 &ArgType, 1, EPI), 5948 /*TInfo=*/0, 5949 /*isExplicit=*/false, 5950 /*isInline=*/true, 5951 /*isImplicitlyDeclared=*/true); 5952 CopyConstructor->setAccess(AS_public); 5953 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 5954 5955 // Note that we have declared this constructor. 5956 ++ASTContext::NumImplicitCopyConstructorsDeclared; 5957 5958 // Add the parameter to the constructor. 5959 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 5960 ClassLoc, ClassLoc, 5961 /*IdentifierInfo=*/0, 5962 ArgType, /*TInfo=*/0, 5963 SC_None, 5964 SC_None, 0); 5965 CopyConstructor->setParams(&FromParam, 1); 5966 if (Scope *S = getScopeForContext(ClassDecl)) 5967 PushOnScopeChains(CopyConstructor, S, false); 5968 ClassDecl->addDecl(CopyConstructor); 5969 5970 return CopyConstructor; 5971} 5972 5973void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 5974 CXXConstructorDecl *CopyConstructor, 5975 unsigned TypeQuals) { 5976 assert((CopyConstructor->isImplicit() && 5977 CopyConstructor->isCopyConstructor(TypeQuals) && 5978 !CopyConstructor->isUsed(false)) && 5979 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 5980 5981 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 5982 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 5983 5984 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor); 5985 DiagnosticErrorTrap Trap(Diags); 5986 5987 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) || 5988 Trap.hasErrorOccurred()) { 5989 Diag(CurrentLocation, diag::note_member_synthesized_at) 5990 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 5991 CopyConstructor->setInvalidDecl(); 5992 } else { 5993 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 5994 CopyConstructor->getLocation(), 5995 MultiStmtArg(*this, 0, 0), 5996 /*isStmtExpr=*/false) 5997 .takeAs<Stmt>()); 5998 } 5999 6000 CopyConstructor->setUsed(); 6001} 6002 6003ExprResult 6004Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 6005 CXXConstructorDecl *Constructor, 6006 MultiExprArg ExprArgs, 6007 bool RequiresZeroInit, 6008 unsigned ConstructKind, 6009 SourceRange ParenRange) { 6010 bool Elidable = false; 6011 6012 // C++0x [class.copy]p34: 6013 // When certain criteria are met, an implementation is allowed to 6014 // omit the copy/move construction of a class object, even if the 6015 // copy/move constructor and/or destructor for the object have 6016 // side effects. [...] 6017 // - when a temporary class object that has not been bound to a 6018 // reference (12.2) would be copied/moved to a class object 6019 // with the same cv-unqualified type, the copy/move operation 6020 // can be omitted by constructing the temporary object 6021 // directly into the target of the omitted copy/move 6022 if (ConstructKind == CXXConstructExpr::CK_Complete && 6023 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) { 6024 Expr *SubExpr = ((Expr **)ExprArgs.get())[0]; 6025 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 6026 } 6027 6028 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 6029 Elidable, move(ExprArgs), RequiresZeroInit, 6030 ConstructKind, ParenRange); 6031} 6032 6033/// BuildCXXConstructExpr - Creates a complete call to a constructor, 6034/// including handling of its default argument expressions. 6035ExprResult 6036Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 6037 CXXConstructorDecl *Constructor, bool Elidable, 6038 MultiExprArg ExprArgs, 6039 bool RequiresZeroInit, 6040 unsigned ConstructKind, 6041 SourceRange ParenRange) { 6042 unsigned NumExprs = ExprArgs.size(); 6043 Expr **Exprs = (Expr **)ExprArgs.release(); 6044 6045 for (specific_attr_iterator<NonNullAttr> 6046 i = Constructor->specific_attr_begin<NonNullAttr>(), 6047 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) { 6048 const NonNullAttr *NonNull = *i; 6049 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc); 6050 } 6051 6052 MarkDeclarationReferenced(ConstructLoc, Constructor); 6053 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 6054 Constructor, Elidable, Exprs, NumExprs, 6055 RequiresZeroInit, 6056 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 6057 ParenRange)); 6058} 6059 6060bool Sema::InitializeVarWithConstructor(VarDecl *VD, 6061 CXXConstructorDecl *Constructor, 6062 MultiExprArg Exprs) { 6063 // FIXME: Provide the correct paren SourceRange when available. 6064 ExprResult TempResult = 6065 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 6066 move(Exprs), false, CXXConstructExpr::CK_Complete, 6067 SourceRange()); 6068 if (TempResult.isInvalid()) 6069 return true; 6070 6071 Expr *Temp = TempResult.takeAs<Expr>(); 6072 CheckImplicitConversions(Temp, VD->getLocation()); 6073 MarkDeclarationReferenced(VD->getLocation(), Constructor); 6074 Temp = MaybeCreateExprWithCleanups(Temp); 6075 VD->setInit(Temp); 6076 6077 return false; 6078} 6079 6080void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 6081 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 6082 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() && 6083 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) { 6084 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 6085 MarkDeclarationReferenced(VD->getLocation(), Destructor); 6086 CheckDestructorAccess(VD->getLocation(), Destructor, 6087 PDiag(diag::err_access_dtor_var) 6088 << VD->getDeclName() 6089 << VD->getType()); 6090 6091 if (!VD->isInvalidDecl() && VD->hasGlobalStorage()) { 6092 // TODO: this should be re-enabled for static locals by !CXAAtExit 6093 if (!VD->isStaticLocal()) 6094 Diag(VD->getLocation(), diag::warn_global_destructor); 6095 6096 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 6097 } 6098 } 6099} 6100 6101/// AddCXXDirectInitializerToDecl - This action is called immediately after 6102/// ActOnDeclarator, when a C++ direct initializer is present. 6103/// e.g: "int x(1);" 6104void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl, 6105 SourceLocation LParenLoc, 6106 MultiExprArg Exprs, 6107 SourceLocation RParenLoc, 6108 bool TypeMayContainAuto) { 6109 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions"); 6110 6111 // If there is no declaration, there was an error parsing it. Just ignore 6112 // the initializer. 6113 if (RealDecl == 0) 6114 return; 6115 6116 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 6117 if (!VDecl) { 6118 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 6119 RealDecl->setInvalidDecl(); 6120 return; 6121 } 6122 6123 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 6124 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) { 6125 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed 6126 if (Exprs.size() > 1) { 6127 Diag(Exprs.get()[1]->getSourceRange().getBegin(), 6128 diag::err_auto_var_init_multiple_expressions) 6129 << VDecl->getDeclName() << VDecl->getType() 6130 << VDecl->getSourceRange(); 6131 RealDecl->setInvalidDecl(); 6132 return; 6133 } 6134 6135 Expr *Init = Exprs.get()[0]; 6136 TypeSourceInfo *DeducedType = 0; 6137 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType)) 6138 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure) 6139 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 6140 << Init->getSourceRange(); 6141 if (!DeducedType) { 6142 RealDecl->setInvalidDecl(); 6143 return; 6144 } 6145 VDecl->setTypeSourceInfo(DeducedType); 6146 VDecl->setType(DeducedType->getType()); 6147 6148 // If this is a redeclaration, check that the type we just deduced matches 6149 // the previously declared type. 6150 if (VarDecl *Old = VDecl->getPreviousDeclaration()) 6151 MergeVarDeclTypes(VDecl, Old); 6152 } 6153 6154 // We will represent direct-initialization similarly to copy-initialization: 6155 // int x(1); -as-> int x = 1; 6156 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 6157 // 6158 // Clients that want to distinguish between the two forms, can check for 6159 // direct initializer using VarDecl::hasCXXDirectInitializer(). 6160 // A major benefit is that clients that don't particularly care about which 6161 // exactly form was it (like the CodeGen) can handle both cases without 6162 // special case code. 6163 6164 // C++ 8.5p11: 6165 // The form of initialization (using parentheses or '=') is generally 6166 // insignificant, but does matter when the entity being initialized has a 6167 // class type. 6168 6169 if (!VDecl->getType()->isDependentType() && 6170 RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 6171 diag::err_typecheck_decl_incomplete_type)) { 6172 VDecl->setInvalidDecl(); 6173 return; 6174 } 6175 6176 // The variable can not have an abstract class type. 6177 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 6178 diag::err_abstract_type_in_decl, 6179 AbstractVariableType)) 6180 VDecl->setInvalidDecl(); 6181 6182 const VarDecl *Def; 6183 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 6184 Diag(VDecl->getLocation(), diag::err_redefinition) 6185 << VDecl->getDeclName(); 6186 Diag(Def->getLocation(), diag::note_previous_definition); 6187 VDecl->setInvalidDecl(); 6188 return; 6189 } 6190 6191 // C++ [class.static.data]p4 6192 // If a static data member is of const integral or const 6193 // enumeration type, its declaration in the class definition can 6194 // specify a constant-initializer which shall be an integral 6195 // constant expression (5.19). In that case, the member can appear 6196 // in integral constant expressions. The member shall still be 6197 // defined in a namespace scope if it is used in the program and the 6198 // namespace scope definition shall not contain an initializer. 6199 // 6200 // We already performed a redefinition check above, but for static 6201 // data members we also need to check whether there was an in-class 6202 // declaration with an initializer. 6203 const VarDecl* PrevInit = 0; 6204 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 6205 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName(); 6206 Diag(PrevInit->getLocation(), diag::note_previous_definition); 6207 return; 6208 } 6209 6210 bool IsDependent = false; 6211 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) { 6212 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) { 6213 VDecl->setInvalidDecl(); 6214 return; 6215 } 6216 6217 if (Exprs.get()[I]->isTypeDependent()) 6218 IsDependent = true; 6219 } 6220 6221 // If either the declaration has a dependent type or if any of the 6222 // expressions is type-dependent, we represent the initialization 6223 // via a ParenListExpr for later use during template instantiation. 6224 if (VDecl->getType()->isDependentType() || IsDependent) { 6225 // Let clients know that initialization was done with a direct initializer. 6226 VDecl->setCXXDirectInitializer(true); 6227 6228 // Store the initialization expressions as a ParenListExpr. 6229 unsigned NumExprs = Exprs.size(); 6230 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc, 6231 (Expr **)Exprs.release(), 6232 NumExprs, RParenLoc)); 6233 return; 6234 } 6235 6236 // Capture the variable that is being initialized and the style of 6237 // initialization. 6238 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 6239 6240 // FIXME: Poor source location information. 6241 InitializationKind Kind 6242 = InitializationKind::CreateDirect(VDecl->getLocation(), 6243 LParenLoc, RParenLoc); 6244 6245 InitializationSequence InitSeq(*this, Entity, Kind, 6246 Exprs.get(), Exprs.size()); 6247 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs)); 6248 if (Result.isInvalid()) { 6249 VDecl->setInvalidDecl(); 6250 return; 6251 } 6252 6253 CheckImplicitConversions(Result.get(), LParenLoc); 6254 6255 Result = MaybeCreateExprWithCleanups(Result); 6256 VDecl->setInit(Result.takeAs<Expr>()); 6257 VDecl->setCXXDirectInitializer(true); 6258 6259 CheckCompleteVariableDeclaration(VDecl); 6260} 6261 6262/// \brief Given a constructor and the set of arguments provided for the 6263/// constructor, convert the arguments and add any required default arguments 6264/// to form a proper call to this constructor. 6265/// 6266/// \returns true if an error occurred, false otherwise. 6267bool 6268Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 6269 MultiExprArg ArgsPtr, 6270 SourceLocation Loc, 6271 ASTOwningVector<Expr*> &ConvertedArgs) { 6272 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 6273 unsigned NumArgs = ArgsPtr.size(); 6274 Expr **Args = (Expr **)ArgsPtr.get(); 6275 6276 const FunctionProtoType *Proto 6277 = Constructor->getType()->getAs<FunctionProtoType>(); 6278 assert(Proto && "Constructor without a prototype?"); 6279 unsigned NumArgsInProto = Proto->getNumArgs(); 6280 6281 // If too few arguments are available, we'll fill in the rest with defaults. 6282 if (NumArgs < NumArgsInProto) 6283 ConvertedArgs.reserve(NumArgsInProto); 6284 else 6285 ConvertedArgs.reserve(NumArgs); 6286 6287 VariadicCallType CallType = 6288 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 6289 llvm::SmallVector<Expr *, 8> AllArgs; 6290 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 6291 Proto, 0, Args, NumArgs, AllArgs, 6292 CallType); 6293 for (unsigned i =0, size = AllArgs.size(); i < size; i++) 6294 ConvertedArgs.push_back(AllArgs[i]); 6295 return Invalid; 6296} 6297 6298static inline bool 6299CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 6300 const FunctionDecl *FnDecl) { 6301 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 6302 if (isa<NamespaceDecl>(DC)) { 6303 return SemaRef.Diag(FnDecl->getLocation(), 6304 diag::err_operator_new_delete_declared_in_namespace) 6305 << FnDecl->getDeclName(); 6306 } 6307 6308 if (isa<TranslationUnitDecl>(DC) && 6309 FnDecl->getStorageClass() == SC_Static) { 6310 return SemaRef.Diag(FnDecl->getLocation(), 6311 diag::err_operator_new_delete_declared_static) 6312 << FnDecl->getDeclName(); 6313 } 6314 6315 return false; 6316} 6317 6318static inline bool 6319CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 6320 CanQualType ExpectedResultType, 6321 CanQualType ExpectedFirstParamType, 6322 unsigned DependentParamTypeDiag, 6323 unsigned InvalidParamTypeDiag) { 6324 QualType ResultType = 6325 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 6326 6327 // Check that the result type is not dependent. 6328 if (ResultType->isDependentType()) 6329 return SemaRef.Diag(FnDecl->getLocation(), 6330 diag::err_operator_new_delete_dependent_result_type) 6331 << FnDecl->getDeclName() << ExpectedResultType; 6332 6333 // Check that the result type is what we expect. 6334 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 6335 return SemaRef.Diag(FnDecl->getLocation(), 6336 diag::err_operator_new_delete_invalid_result_type) 6337 << FnDecl->getDeclName() << ExpectedResultType; 6338 6339 // A function template must have at least 2 parameters. 6340 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 6341 return SemaRef.Diag(FnDecl->getLocation(), 6342 diag::err_operator_new_delete_template_too_few_parameters) 6343 << FnDecl->getDeclName(); 6344 6345 // The function decl must have at least 1 parameter. 6346 if (FnDecl->getNumParams() == 0) 6347 return SemaRef.Diag(FnDecl->getLocation(), 6348 diag::err_operator_new_delete_too_few_parameters) 6349 << FnDecl->getDeclName(); 6350 6351 // Check the the first parameter type is not dependent. 6352 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 6353 if (FirstParamType->isDependentType()) 6354 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 6355 << FnDecl->getDeclName() << ExpectedFirstParamType; 6356 6357 // Check that the first parameter type is what we expect. 6358 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 6359 ExpectedFirstParamType) 6360 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 6361 << FnDecl->getDeclName() << ExpectedFirstParamType; 6362 6363 return false; 6364} 6365 6366static bool 6367CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 6368 // C++ [basic.stc.dynamic.allocation]p1: 6369 // A program is ill-formed if an allocation function is declared in a 6370 // namespace scope other than global scope or declared static in global 6371 // scope. 6372 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 6373 return true; 6374 6375 CanQualType SizeTy = 6376 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 6377 6378 // C++ [basic.stc.dynamic.allocation]p1: 6379 // The return type shall be void*. The first parameter shall have type 6380 // std::size_t. 6381 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 6382 SizeTy, 6383 diag::err_operator_new_dependent_param_type, 6384 diag::err_operator_new_param_type)) 6385 return true; 6386 6387 // C++ [basic.stc.dynamic.allocation]p1: 6388 // The first parameter shall not have an associated default argument. 6389 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 6390 return SemaRef.Diag(FnDecl->getLocation(), 6391 diag::err_operator_new_default_arg) 6392 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 6393 6394 return false; 6395} 6396 6397static bool 6398CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 6399 // C++ [basic.stc.dynamic.deallocation]p1: 6400 // A program is ill-formed if deallocation functions are declared in a 6401 // namespace scope other than global scope or declared static in global 6402 // scope. 6403 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 6404 return true; 6405 6406 // C++ [basic.stc.dynamic.deallocation]p2: 6407 // Each deallocation function shall return void and its first parameter 6408 // shall be void*. 6409 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 6410 SemaRef.Context.VoidPtrTy, 6411 diag::err_operator_delete_dependent_param_type, 6412 diag::err_operator_delete_param_type)) 6413 return true; 6414 6415 return false; 6416} 6417 6418/// CheckOverloadedOperatorDeclaration - Check whether the declaration 6419/// of this overloaded operator is well-formed. If so, returns false; 6420/// otherwise, emits appropriate diagnostics and returns true. 6421bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 6422 assert(FnDecl && FnDecl->isOverloadedOperator() && 6423 "Expected an overloaded operator declaration"); 6424 6425 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 6426 6427 // C++ [over.oper]p5: 6428 // The allocation and deallocation functions, operator new, 6429 // operator new[], operator delete and operator delete[], are 6430 // described completely in 3.7.3. The attributes and restrictions 6431 // found in the rest of this subclause do not apply to them unless 6432 // explicitly stated in 3.7.3. 6433 if (Op == OO_Delete || Op == OO_Array_Delete) 6434 return CheckOperatorDeleteDeclaration(*this, FnDecl); 6435 6436 if (Op == OO_New || Op == OO_Array_New) 6437 return CheckOperatorNewDeclaration(*this, FnDecl); 6438 6439 // C++ [over.oper]p6: 6440 // An operator function shall either be a non-static member 6441 // function or be a non-member function and have at least one 6442 // parameter whose type is a class, a reference to a class, an 6443 // enumeration, or a reference to an enumeration. 6444 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 6445 if (MethodDecl->isStatic()) 6446 return Diag(FnDecl->getLocation(), 6447 diag::err_operator_overload_static) << FnDecl->getDeclName(); 6448 } else { 6449 bool ClassOrEnumParam = false; 6450 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 6451 ParamEnd = FnDecl->param_end(); 6452 Param != ParamEnd; ++Param) { 6453 QualType ParamType = (*Param)->getType().getNonReferenceType(); 6454 if (ParamType->isDependentType() || ParamType->isRecordType() || 6455 ParamType->isEnumeralType()) { 6456 ClassOrEnumParam = true; 6457 break; 6458 } 6459 } 6460 6461 if (!ClassOrEnumParam) 6462 return Diag(FnDecl->getLocation(), 6463 diag::err_operator_overload_needs_class_or_enum) 6464 << FnDecl->getDeclName(); 6465 } 6466 6467 // C++ [over.oper]p8: 6468 // An operator function cannot have default arguments (8.3.6), 6469 // except where explicitly stated below. 6470 // 6471 // Only the function-call operator allows default arguments 6472 // (C++ [over.call]p1). 6473 if (Op != OO_Call) { 6474 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 6475 Param != FnDecl->param_end(); ++Param) { 6476 if ((*Param)->hasDefaultArg()) 6477 return Diag((*Param)->getLocation(), 6478 diag::err_operator_overload_default_arg) 6479 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 6480 } 6481 } 6482 6483 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 6484 { false, false, false } 6485#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 6486 , { Unary, Binary, MemberOnly } 6487#include "clang/Basic/OperatorKinds.def" 6488 }; 6489 6490 bool CanBeUnaryOperator = OperatorUses[Op][0]; 6491 bool CanBeBinaryOperator = OperatorUses[Op][1]; 6492 bool MustBeMemberOperator = OperatorUses[Op][2]; 6493 6494 // C++ [over.oper]p8: 6495 // [...] Operator functions cannot have more or fewer parameters 6496 // than the number required for the corresponding operator, as 6497 // described in the rest of this subclause. 6498 unsigned NumParams = FnDecl->getNumParams() 6499 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 6500 if (Op != OO_Call && 6501 ((NumParams == 1 && !CanBeUnaryOperator) || 6502 (NumParams == 2 && !CanBeBinaryOperator) || 6503 (NumParams < 1) || (NumParams > 2))) { 6504 // We have the wrong number of parameters. 6505 unsigned ErrorKind; 6506 if (CanBeUnaryOperator && CanBeBinaryOperator) { 6507 ErrorKind = 2; // 2 -> unary or binary. 6508 } else if (CanBeUnaryOperator) { 6509 ErrorKind = 0; // 0 -> unary 6510 } else { 6511 assert(CanBeBinaryOperator && 6512 "All non-call overloaded operators are unary or binary!"); 6513 ErrorKind = 1; // 1 -> binary 6514 } 6515 6516 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 6517 << FnDecl->getDeclName() << NumParams << ErrorKind; 6518 } 6519 6520 // Overloaded operators other than operator() cannot be variadic. 6521 if (Op != OO_Call && 6522 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 6523 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 6524 << FnDecl->getDeclName(); 6525 } 6526 6527 // Some operators must be non-static member functions. 6528 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 6529 return Diag(FnDecl->getLocation(), 6530 diag::err_operator_overload_must_be_member) 6531 << FnDecl->getDeclName(); 6532 } 6533 6534 // C++ [over.inc]p1: 6535 // The user-defined function called operator++ implements the 6536 // prefix and postfix ++ operator. If this function is a member 6537 // function with no parameters, or a non-member function with one 6538 // parameter of class or enumeration type, it defines the prefix 6539 // increment operator ++ for objects of that type. If the function 6540 // is a member function with one parameter (which shall be of type 6541 // int) or a non-member function with two parameters (the second 6542 // of which shall be of type int), it defines the postfix 6543 // increment operator ++ for objects of that type. 6544 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 6545 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 6546 bool ParamIsInt = false; 6547 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 6548 ParamIsInt = BT->getKind() == BuiltinType::Int; 6549 6550 if (!ParamIsInt) 6551 return Diag(LastParam->getLocation(), 6552 diag::err_operator_overload_post_incdec_must_be_int) 6553 << LastParam->getType() << (Op == OO_MinusMinus); 6554 } 6555 6556 return false; 6557} 6558 6559/// CheckLiteralOperatorDeclaration - Check whether the declaration 6560/// of this literal operator function is well-formed. If so, returns 6561/// false; otherwise, emits appropriate diagnostics and returns true. 6562bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 6563 DeclContext *DC = FnDecl->getDeclContext(); 6564 Decl::Kind Kind = DC->getDeclKind(); 6565 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace && 6566 Kind != Decl::LinkageSpec) { 6567 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 6568 << FnDecl->getDeclName(); 6569 return true; 6570 } 6571 6572 bool Valid = false; 6573 6574 // template <char...> type operator "" name() is the only valid template 6575 // signature, and the only valid signature with no parameters. 6576 if (FnDecl->param_size() == 0) { 6577 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) { 6578 // Must have only one template parameter 6579 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 6580 if (Params->size() == 1) { 6581 NonTypeTemplateParmDecl *PmDecl = 6582 cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 6583 6584 // The template parameter must be a char parameter pack. 6585 if (PmDecl && PmDecl->isTemplateParameterPack() && 6586 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 6587 Valid = true; 6588 } 6589 } 6590 } else { 6591 // Check the first parameter 6592 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 6593 6594 QualType T = (*Param)->getType(); 6595 6596 // unsigned long long int, long double, and any character type are allowed 6597 // as the only parameters. 6598 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 6599 Context.hasSameType(T, Context.LongDoubleTy) || 6600 Context.hasSameType(T, Context.CharTy) || 6601 Context.hasSameType(T, Context.WCharTy) || 6602 Context.hasSameType(T, Context.Char16Ty) || 6603 Context.hasSameType(T, Context.Char32Ty)) { 6604 if (++Param == FnDecl->param_end()) 6605 Valid = true; 6606 goto FinishedParams; 6607 } 6608 6609 // Otherwise it must be a pointer to const; let's strip those qualifiers. 6610 const PointerType *PT = T->getAs<PointerType>(); 6611 if (!PT) 6612 goto FinishedParams; 6613 T = PT->getPointeeType(); 6614 if (!T.isConstQualified()) 6615 goto FinishedParams; 6616 T = T.getUnqualifiedType(); 6617 6618 // Move on to the second parameter; 6619 ++Param; 6620 6621 // If there is no second parameter, the first must be a const char * 6622 if (Param == FnDecl->param_end()) { 6623 if (Context.hasSameType(T, Context.CharTy)) 6624 Valid = true; 6625 goto FinishedParams; 6626 } 6627 6628 // const char *, const wchar_t*, const char16_t*, and const char32_t* 6629 // are allowed as the first parameter to a two-parameter function 6630 if (!(Context.hasSameType(T, Context.CharTy) || 6631 Context.hasSameType(T, Context.WCharTy) || 6632 Context.hasSameType(T, Context.Char16Ty) || 6633 Context.hasSameType(T, Context.Char32Ty))) 6634 goto FinishedParams; 6635 6636 // The second and final parameter must be an std::size_t 6637 T = (*Param)->getType().getUnqualifiedType(); 6638 if (Context.hasSameType(T, Context.getSizeType()) && 6639 ++Param == FnDecl->param_end()) 6640 Valid = true; 6641 } 6642 6643 // FIXME: This diagnostic is absolutely terrible. 6644FinishedParams: 6645 if (!Valid) { 6646 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 6647 << FnDecl->getDeclName(); 6648 return true; 6649 } 6650 6651 return false; 6652} 6653 6654/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 6655/// linkage specification, including the language and (if present) 6656/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 6657/// the location of the language string literal, which is provided 6658/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 6659/// the '{' brace. Otherwise, this linkage specification does not 6660/// have any braces. 6661Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 6662 SourceLocation LangLoc, 6663 llvm::StringRef Lang, 6664 SourceLocation LBraceLoc) { 6665 LinkageSpecDecl::LanguageIDs Language; 6666 if (Lang == "\"C\"") 6667 Language = LinkageSpecDecl::lang_c; 6668 else if (Lang == "\"C++\"") 6669 Language = LinkageSpecDecl::lang_cxx; 6670 else { 6671 Diag(LangLoc, diag::err_bad_language); 6672 return 0; 6673 } 6674 6675 // FIXME: Add all the various semantics of linkage specifications 6676 6677 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 6678 ExternLoc, LangLoc, Language); 6679 CurContext->addDecl(D); 6680 PushDeclContext(S, D); 6681 return D; 6682} 6683 6684/// ActOnFinishLinkageSpecification - Complete the definition of 6685/// the C++ linkage specification LinkageSpec. If RBraceLoc is 6686/// valid, it's the position of the closing '}' brace in a linkage 6687/// specification that uses braces. 6688Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 6689 Decl *LinkageSpec, 6690 SourceLocation RBraceLoc) { 6691 if (LinkageSpec) { 6692 if (RBraceLoc.isValid()) { 6693 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 6694 LSDecl->setRBraceLoc(RBraceLoc); 6695 } 6696 PopDeclContext(); 6697 } 6698 return LinkageSpec; 6699} 6700 6701/// \brief Perform semantic analysis for the variable declaration that 6702/// occurs within a C++ catch clause, returning the newly-created 6703/// variable. 6704VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 6705 TypeSourceInfo *TInfo, 6706 SourceLocation StartLoc, 6707 SourceLocation Loc, 6708 IdentifierInfo *Name) { 6709 bool Invalid = false; 6710 QualType ExDeclType = TInfo->getType(); 6711 6712 // Arrays and functions decay. 6713 if (ExDeclType->isArrayType()) 6714 ExDeclType = Context.getArrayDecayedType(ExDeclType); 6715 else if (ExDeclType->isFunctionType()) 6716 ExDeclType = Context.getPointerType(ExDeclType); 6717 6718 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 6719 // The exception-declaration shall not denote a pointer or reference to an 6720 // incomplete type, other than [cv] void*. 6721 // N2844 forbids rvalue references. 6722 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 6723 Diag(Loc, diag::err_catch_rvalue_ref); 6724 Invalid = true; 6725 } 6726 6727 // GCC allows catching pointers and references to incomplete types 6728 // as an extension; so do we, but we warn by default. 6729 6730 QualType BaseType = ExDeclType; 6731 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 6732 unsigned DK = diag::err_catch_incomplete; 6733 bool IncompleteCatchIsInvalid = true; 6734 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 6735 BaseType = Ptr->getPointeeType(); 6736 Mode = 1; 6737 DK = diag::ext_catch_incomplete_ptr; 6738 IncompleteCatchIsInvalid = false; 6739 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 6740 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 6741 BaseType = Ref->getPointeeType(); 6742 Mode = 2; 6743 DK = diag::ext_catch_incomplete_ref; 6744 IncompleteCatchIsInvalid = false; 6745 } 6746 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 6747 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) && 6748 IncompleteCatchIsInvalid) 6749 Invalid = true; 6750 6751 if (!Invalid && !ExDeclType->isDependentType() && 6752 RequireNonAbstractType(Loc, ExDeclType, 6753 diag::err_abstract_type_in_decl, 6754 AbstractVariableType)) 6755 Invalid = true; 6756 6757 // Only the non-fragile NeXT runtime currently supports C++ catches 6758 // of ObjC types, and no runtime supports catching ObjC types by value. 6759 if (!Invalid && getLangOptions().ObjC1) { 6760 QualType T = ExDeclType; 6761 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 6762 T = RT->getPointeeType(); 6763 6764 if (T->isObjCObjectType()) { 6765 Diag(Loc, diag::err_objc_object_catch); 6766 Invalid = true; 6767 } else if (T->isObjCObjectPointerType()) { 6768 if (!getLangOptions().ObjCNonFragileABI) { 6769 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile); 6770 Invalid = true; 6771 } 6772 } 6773 } 6774 6775 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 6776 ExDeclType, TInfo, SC_None, SC_None); 6777 ExDecl->setExceptionVariable(true); 6778 6779 if (!Invalid) { 6780 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 6781 // C++ [except.handle]p16: 6782 // The object declared in an exception-declaration or, if the 6783 // exception-declaration does not specify a name, a temporary (12.2) is 6784 // copy-initialized (8.5) from the exception object. [...] 6785 // The object is destroyed when the handler exits, after the destruction 6786 // of any automatic objects initialized within the handler. 6787 // 6788 // We just pretend to initialize the object with itself, then make sure 6789 // it can be destroyed later. 6790 QualType initType = ExDeclType; 6791 6792 InitializedEntity entity = 6793 InitializedEntity::InitializeVariable(ExDecl); 6794 InitializationKind initKind = 6795 InitializationKind::CreateCopy(Loc, SourceLocation()); 6796 6797 Expr *opaqueValue = 6798 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 6799 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1); 6800 ExprResult result = sequence.Perform(*this, entity, initKind, 6801 MultiExprArg(&opaqueValue, 1)); 6802 if (result.isInvalid()) 6803 Invalid = true; 6804 else { 6805 // If the constructor used was non-trivial, set this as the 6806 // "initializer". 6807 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 6808 if (!construct->getConstructor()->isTrivial()) { 6809 Expr *init = MaybeCreateExprWithCleanups(construct); 6810 ExDecl->setInit(init); 6811 } 6812 6813 // And make sure it's destructable. 6814 FinalizeVarWithDestructor(ExDecl, recordType); 6815 } 6816 } 6817 } 6818 6819 if (Invalid) 6820 ExDecl->setInvalidDecl(); 6821 6822 return ExDecl; 6823} 6824 6825/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 6826/// handler. 6827Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 6828 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6829 bool Invalid = D.isInvalidType(); 6830 6831 // Check for unexpanded parameter packs. 6832 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 6833 UPPC_ExceptionType)) { 6834 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 6835 D.getIdentifierLoc()); 6836 Invalid = true; 6837 } 6838 6839 IdentifierInfo *II = D.getIdentifier(); 6840 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 6841 LookupOrdinaryName, 6842 ForRedeclaration)) { 6843 // The scope should be freshly made just for us. There is just no way 6844 // it contains any previous declaration. 6845 assert(!S->isDeclScope(PrevDecl)); 6846 if (PrevDecl->isTemplateParameter()) { 6847 // Maybe we will complain about the shadowed template parameter. 6848 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 6849 } 6850 } 6851 6852 if (D.getCXXScopeSpec().isSet() && !Invalid) { 6853 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 6854 << D.getCXXScopeSpec().getRange(); 6855 Invalid = true; 6856 } 6857 6858 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 6859 D.getSourceRange().getBegin(), 6860 D.getIdentifierLoc(), 6861 D.getIdentifier()); 6862 if (Invalid) 6863 ExDecl->setInvalidDecl(); 6864 6865 // Add the exception declaration into this scope. 6866 if (II) 6867 PushOnScopeChains(ExDecl, S); 6868 else 6869 CurContext->addDecl(ExDecl); 6870 6871 ProcessDeclAttributes(S, ExDecl, D); 6872 return ExDecl; 6873} 6874 6875Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 6876 Expr *AssertExpr, 6877 Expr *AssertMessageExpr_, 6878 SourceLocation RParenLoc) { 6879 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_); 6880 6881 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 6882 llvm::APSInt Value(32); 6883 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 6884 Diag(StaticAssertLoc, 6885 diag::err_static_assert_expression_is_not_constant) << 6886 AssertExpr->getSourceRange(); 6887 return 0; 6888 } 6889 6890 if (Value == 0) { 6891 Diag(StaticAssertLoc, diag::err_static_assert_failed) 6892 << AssertMessage->getString() << AssertExpr->getSourceRange(); 6893 } 6894 } 6895 6896 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 6897 return 0; 6898 6899 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 6900 AssertExpr, AssertMessage, RParenLoc); 6901 6902 CurContext->addDecl(Decl); 6903 return Decl; 6904} 6905 6906/// \brief Perform semantic analysis of the given friend type declaration. 6907/// 6908/// \returns A friend declaration that. 6909FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc, 6910 TypeSourceInfo *TSInfo) { 6911 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 6912 6913 QualType T = TSInfo->getType(); 6914 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 6915 6916 if (!getLangOptions().CPlusPlus0x) { 6917 // C++03 [class.friend]p2: 6918 // An elaborated-type-specifier shall be used in a friend declaration 6919 // for a class.* 6920 // 6921 // * The class-key of the elaborated-type-specifier is required. 6922 if (!ActiveTemplateInstantiations.empty()) { 6923 // Do not complain about the form of friend template types during 6924 // template instantiation; we will already have complained when the 6925 // template was declared. 6926 } else if (!T->isElaboratedTypeSpecifier()) { 6927 // If we evaluated the type to a record type, suggest putting 6928 // a tag in front. 6929 if (const RecordType *RT = T->getAs<RecordType>()) { 6930 RecordDecl *RD = RT->getDecl(); 6931 6932 std::string InsertionText = std::string(" ") + RD->getKindName(); 6933 6934 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type) 6935 << (unsigned) RD->getTagKind() 6936 << T 6937 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 6938 InsertionText); 6939 } else { 6940 Diag(FriendLoc, diag::ext_nonclass_type_friend) 6941 << T 6942 << SourceRange(FriendLoc, TypeRange.getEnd()); 6943 } 6944 } else if (T->getAs<EnumType>()) { 6945 Diag(FriendLoc, diag::ext_enum_friend) 6946 << T 6947 << SourceRange(FriendLoc, TypeRange.getEnd()); 6948 } 6949 } 6950 6951 // C++0x [class.friend]p3: 6952 // If the type specifier in a friend declaration designates a (possibly 6953 // cv-qualified) class type, that class is declared as a friend; otherwise, 6954 // the friend declaration is ignored. 6955 6956 // FIXME: C++0x has some syntactic restrictions on friend type declarations 6957 // in [class.friend]p3 that we do not implement. 6958 6959 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc); 6960} 6961 6962/// Handle a friend tag declaration where the scope specifier was 6963/// templated. 6964Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 6965 unsigned TagSpec, SourceLocation TagLoc, 6966 CXXScopeSpec &SS, 6967 IdentifierInfo *Name, SourceLocation NameLoc, 6968 AttributeList *Attr, 6969 MultiTemplateParamsArg TempParamLists) { 6970 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 6971 6972 bool isExplicitSpecialization = false; 6973 bool Invalid = false; 6974 6975 if (TemplateParameterList *TemplateParams 6976 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS, 6977 TempParamLists.get(), 6978 TempParamLists.size(), 6979 /*friend*/ true, 6980 isExplicitSpecialization, 6981 Invalid)) { 6982 if (TemplateParams->size() > 0) { 6983 // This is a declaration of a class template. 6984 if (Invalid) 6985 return 0; 6986 6987 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 6988 SS, Name, NameLoc, Attr, 6989 TemplateParams, AS_public, 6990 TempParamLists.size() - 1, 6991 (TemplateParameterList**) TempParamLists.release()).take(); 6992 } else { 6993 // The "template<>" header is extraneous. 6994 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 6995 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 6996 isExplicitSpecialization = true; 6997 } 6998 } 6999 7000 if (Invalid) return 0; 7001 7002 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 7003 7004 bool isAllExplicitSpecializations = true; 7005 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 7006 if (TempParamLists.get()[I]->size()) { 7007 isAllExplicitSpecializations = false; 7008 break; 7009 } 7010 } 7011 7012 // FIXME: don't ignore attributes. 7013 7014 // If it's explicit specializations all the way down, just forget 7015 // about the template header and build an appropriate non-templated 7016 // friend. TODO: for source fidelity, remember the headers. 7017 if (isAllExplicitSpecializations) { 7018 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7019 ElaboratedTypeKeyword Keyword 7020 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 7021 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 7022 *Name, NameLoc); 7023 if (T.isNull()) 7024 return 0; 7025 7026 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 7027 if (isa<DependentNameType>(T)) { 7028 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 7029 TL.setKeywordLoc(TagLoc); 7030 TL.setQualifierLoc(QualifierLoc); 7031 TL.setNameLoc(NameLoc); 7032 } else { 7033 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 7034 TL.setKeywordLoc(TagLoc); 7035 TL.setQualifierLoc(QualifierLoc); 7036 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc); 7037 } 7038 7039 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 7040 TSI, FriendLoc); 7041 Friend->setAccess(AS_public); 7042 CurContext->addDecl(Friend); 7043 return Friend; 7044 } 7045 7046 // Handle the case of a templated-scope friend class. e.g. 7047 // template <class T> class A<T>::B; 7048 // FIXME: we don't support these right now. 7049 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 7050 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 7051 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 7052 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 7053 TL.setKeywordLoc(TagLoc); 7054 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 7055 TL.setNameLoc(NameLoc); 7056 7057 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 7058 TSI, FriendLoc); 7059 Friend->setAccess(AS_public); 7060 Friend->setUnsupportedFriend(true); 7061 CurContext->addDecl(Friend); 7062 return Friend; 7063} 7064 7065 7066/// Handle a friend type declaration. This works in tandem with 7067/// ActOnTag. 7068/// 7069/// Notes on friend class templates: 7070/// 7071/// We generally treat friend class declarations as if they were 7072/// declaring a class. So, for example, the elaborated type specifier 7073/// in a friend declaration is required to obey the restrictions of a 7074/// class-head (i.e. no typedefs in the scope chain), template 7075/// parameters are required to match up with simple template-ids, &c. 7076/// However, unlike when declaring a template specialization, it's 7077/// okay to refer to a template specialization without an empty 7078/// template parameter declaration, e.g. 7079/// friend class A<T>::B<unsigned>; 7080/// We permit this as a special case; if there are any template 7081/// parameters present at all, require proper matching, i.e. 7082/// template <> template <class T> friend class A<int>::B; 7083Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 7084 MultiTemplateParamsArg TempParams) { 7085 SourceLocation Loc = DS.getSourceRange().getBegin(); 7086 7087 assert(DS.isFriendSpecified()); 7088 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 7089 7090 // Try to convert the decl specifier to a type. This works for 7091 // friend templates because ActOnTag never produces a ClassTemplateDecl 7092 // for a TUK_Friend. 7093 Declarator TheDeclarator(DS, Declarator::MemberContext); 7094 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 7095 QualType T = TSI->getType(); 7096 if (TheDeclarator.isInvalidType()) 7097 return 0; 7098 7099 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 7100 return 0; 7101 7102 // This is definitely an error in C++98. It's probably meant to 7103 // be forbidden in C++0x, too, but the specification is just 7104 // poorly written. 7105 // 7106 // The problem is with declarations like the following: 7107 // template <T> friend A<T>::foo; 7108 // where deciding whether a class C is a friend or not now hinges 7109 // on whether there exists an instantiation of A that causes 7110 // 'foo' to equal C. There are restrictions on class-heads 7111 // (which we declare (by fiat) elaborated friend declarations to 7112 // be) that makes this tractable. 7113 // 7114 // FIXME: handle "template <> friend class A<T>;", which 7115 // is possibly well-formed? Who even knows? 7116 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 7117 Diag(Loc, diag::err_tagless_friend_type_template) 7118 << DS.getSourceRange(); 7119 return 0; 7120 } 7121 7122 // C++98 [class.friend]p1: A friend of a class is a function 7123 // or class that is not a member of the class . . . 7124 // This is fixed in DR77, which just barely didn't make the C++03 7125 // deadline. It's also a very silly restriction that seriously 7126 // affects inner classes and which nobody else seems to implement; 7127 // thus we never diagnose it, not even in -pedantic. 7128 // 7129 // But note that we could warn about it: it's always useless to 7130 // friend one of your own members (it's not, however, worthless to 7131 // friend a member of an arbitrary specialization of your template). 7132 7133 Decl *D; 7134 if (unsigned NumTempParamLists = TempParams.size()) 7135 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 7136 NumTempParamLists, 7137 TempParams.release(), 7138 TSI, 7139 DS.getFriendSpecLoc()); 7140 else 7141 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI); 7142 7143 if (!D) 7144 return 0; 7145 7146 D->setAccess(AS_public); 7147 CurContext->addDecl(D); 7148 7149 return D; 7150} 7151 7152Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition, 7153 MultiTemplateParamsArg TemplateParams) { 7154 const DeclSpec &DS = D.getDeclSpec(); 7155 7156 assert(DS.isFriendSpecified()); 7157 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 7158 7159 SourceLocation Loc = D.getIdentifierLoc(); 7160 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 7161 QualType T = TInfo->getType(); 7162 7163 // C++ [class.friend]p1 7164 // A friend of a class is a function or class.... 7165 // Note that this sees through typedefs, which is intended. 7166 // It *doesn't* see through dependent types, which is correct 7167 // according to [temp.arg.type]p3: 7168 // If a declaration acquires a function type through a 7169 // type dependent on a template-parameter and this causes 7170 // a declaration that does not use the syntactic form of a 7171 // function declarator to have a function type, the program 7172 // is ill-formed. 7173 if (!T->isFunctionType()) { 7174 Diag(Loc, diag::err_unexpected_friend); 7175 7176 // It might be worthwhile to try to recover by creating an 7177 // appropriate declaration. 7178 return 0; 7179 } 7180 7181 // C++ [namespace.memdef]p3 7182 // - If a friend declaration in a non-local class first declares a 7183 // class or function, the friend class or function is a member 7184 // of the innermost enclosing namespace. 7185 // - The name of the friend is not found by simple name lookup 7186 // until a matching declaration is provided in that namespace 7187 // scope (either before or after the class declaration granting 7188 // friendship). 7189 // - If a friend function is called, its name may be found by the 7190 // name lookup that considers functions from namespaces and 7191 // classes associated with the types of the function arguments. 7192 // - When looking for a prior declaration of a class or a function 7193 // declared as a friend, scopes outside the innermost enclosing 7194 // namespace scope are not considered. 7195 7196 CXXScopeSpec &SS = D.getCXXScopeSpec(); 7197 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7198 DeclarationName Name = NameInfo.getName(); 7199 assert(Name); 7200 7201 // Check for unexpanded parameter packs. 7202 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 7203 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 7204 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 7205 return 0; 7206 7207 // The context we found the declaration in, or in which we should 7208 // create the declaration. 7209 DeclContext *DC; 7210 Scope *DCScope = S; 7211 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 7212 ForRedeclaration); 7213 7214 // FIXME: there are different rules in local classes 7215 7216 // There are four cases here. 7217 // - There's no scope specifier, in which case we just go to the 7218 // appropriate scope and look for a function or function template 7219 // there as appropriate. 7220 // Recover from invalid scope qualifiers as if they just weren't there. 7221 if (SS.isInvalid() || !SS.isSet()) { 7222 // C++0x [namespace.memdef]p3: 7223 // If the name in a friend declaration is neither qualified nor 7224 // a template-id and the declaration is a function or an 7225 // elaborated-type-specifier, the lookup to determine whether 7226 // the entity has been previously declared shall not consider 7227 // any scopes outside the innermost enclosing namespace. 7228 // C++0x [class.friend]p11: 7229 // If a friend declaration appears in a local class and the name 7230 // specified is an unqualified name, a prior declaration is 7231 // looked up without considering scopes that are outside the 7232 // innermost enclosing non-class scope. For a friend function 7233 // declaration, if there is no prior declaration, the program is 7234 // ill-formed. 7235 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 7236 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 7237 7238 // Find the appropriate context according to the above. 7239 DC = CurContext; 7240 while (true) { 7241 // Skip class contexts. If someone can cite chapter and verse 7242 // for this behavior, that would be nice --- it's what GCC and 7243 // EDG do, and it seems like a reasonable intent, but the spec 7244 // really only says that checks for unqualified existing 7245 // declarations should stop at the nearest enclosing namespace, 7246 // not that they should only consider the nearest enclosing 7247 // namespace. 7248 while (DC->isRecord()) 7249 DC = DC->getParent(); 7250 7251 LookupQualifiedName(Previous, DC); 7252 7253 // TODO: decide what we think about using declarations. 7254 if (isLocal || !Previous.empty()) 7255 break; 7256 7257 if (isTemplateId) { 7258 if (isa<TranslationUnitDecl>(DC)) break; 7259 } else { 7260 if (DC->isFileContext()) break; 7261 } 7262 DC = DC->getParent(); 7263 } 7264 7265 // C++ [class.friend]p1: A friend of a class is a function or 7266 // class that is not a member of the class . . . 7267 // C++0x changes this for both friend types and functions. 7268 // Most C++ 98 compilers do seem to give an error here, so 7269 // we do, too. 7270 if (!Previous.empty() && DC->Equals(CurContext) 7271 && !getLangOptions().CPlusPlus0x) 7272 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 7273 7274 DCScope = getScopeForDeclContext(S, DC); 7275 7276 // - There's a non-dependent scope specifier, in which case we 7277 // compute it and do a previous lookup there for a function 7278 // or function template. 7279 } else if (!SS.getScopeRep()->isDependent()) { 7280 DC = computeDeclContext(SS); 7281 if (!DC) return 0; 7282 7283 if (RequireCompleteDeclContext(SS, DC)) return 0; 7284 7285 LookupQualifiedName(Previous, DC); 7286 7287 // Ignore things found implicitly in the wrong scope. 7288 // TODO: better diagnostics for this case. Suggesting the right 7289 // qualified scope would be nice... 7290 LookupResult::Filter F = Previous.makeFilter(); 7291 while (F.hasNext()) { 7292 NamedDecl *D = F.next(); 7293 if (!DC->InEnclosingNamespaceSetOf( 7294 D->getDeclContext()->getRedeclContext())) 7295 F.erase(); 7296 } 7297 F.done(); 7298 7299 if (Previous.empty()) { 7300 D.setInvalidType(); 7301 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 7302 return 0; 7303 } 7304 7305 // C++ [class.friend]p1: A friend of a class is a function or 7306 // class that is not a member of the class . . . 7307 if (DC->Equals(CurContext)) 7308 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 7309 7310 // - There's a scope specifier that does not match any template 7311 // parameter lists, in which case we use some arbitrary context, 7312 // create a method or method template, and wait for instantiation. 7313 // - There's a scope specifier that does match some template 7314 // parameter lists, which we don't handle right now. 7315 } else { 7316 DC = CurContext; 7317 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 7318 } 7319 7320 if (!DC->isRecord()) { 7321 // This implies that it has to be an operator or function. 7322 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 7323 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 7324 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 7325 Diag(Loc, diag::err_introducing_special_friend) << 7326 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 7327 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 7328 return 0; 7329 } 7330 } 7331 7332 bool Redeclaration = false; 7333 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous, 7334 move(TemplateParams), 7335 IsDefinition, 7336 Redeclaration); 7337 if (!ND) return 0; 7338 7339 assert(ND->getDeclContext() == DC); 7340 assert(ND->getLexicalDeclContext() == CurContext); 7341 7342 // Add the function declaration to the appropriate lookup tables, 7343 // adjusting the redeclarations list as necessary. We don't 7344 // want to do this yet if the friending class is dependent. 7345 // 7346 // Also update the scope-based lookup if the target context's 7347 // lookup context is in lexical scope. 7348 if (!CurContext->isDependentContext()) { 7349 DC = DC->getRedeclContext(); 7350 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 7351 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 7352 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 7353 } 7354 7355 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 7356 D.getIdentifierLoc(), ND, 7357 DS.getFriendSpecLoc()); 7358 FrD->setAccess(AS_public); 7359 CurContext->addDecl(FrD); 7360 7361 if (ND->isInvalidDecl()) 7362 FrD->setInvalidDecl(); 7363 else { 7364 FunctionDecl *FD; 7365 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 7366 FD = FTD->getTemplatedDecl(); 7367 else 7368 FD = cast<FunctionDecl>(ND); 7369 7370 // Mark templated-scope function declarations as unsupported. 7371 if (FD->getNumTemplateParameterLists()) 7372 FrD->setUnsupportedFriend(true); 7373 } 7374 7375 return ND; 7376} 7377 7378void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 7379 AdjustDeclIfTemplate(Dcl); 7380 7381 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 7382 if (!Fn) { 7383 Diag(DelLoc, diag::err_deleted_non_function); 7384 return; 7385 } 7386 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 7387 Diag(DelLoc, diag::err_deleted_decl_not_first); 7388 Diag(Prev->getLocation(), diag::note_previous_declaration); 7389 // If the declaration wasn't the first, we delete the function anyway for 7390 // recovery. 7391 } 7392 Fn->setDeleted(); 7393} 7394 7395static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 7396 for (Stmt::child_range CI = S->children(); CI; ++CI) { 7397 Stmt *SubStmt = *CI; 7398 if (!SubStmt) 7399 continue; 7400 if (isa<ReturnStmt>(SubStmt)) 7401 Self.Diag(SubStmt->getSourceRange().getBegin(), 7402 diag::err_return_in_constructor_handler); 7403 if (!isa<Expr>(SubStmt)) 7404 SearchForReturnInStmt(Self, SubStmt); 7405 } 7406} 7407 7408void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 7409 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 7410 CXXCatchStmt *Handler = TryBlock->getHandler(I); 7411 SearchForReturnInStmt(*this, Handler); 7412 } 7413} 7414 7415bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 7416 const CXXMethodDecl *Old) { 7417 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 7418 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 7419 7420 if (Context.hasSameType(NewTy, OldTy) || 7421 NewTy->isDependentType() || OldTy->isDependentType()) 7422 return false; 7423 7424 // Check if the return types are covariant 7425 QualType NewClassTy, OldClassTy; 7426 7427 /// Both types must be pointers or references to classes. 7428 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 7429 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 7430 NewClassTy = NewPT->getPointeeType(); 7431 OldClassTy = OldPT->getPointeeType(); 7432 } 7433 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 7434 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 7435 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 7436 NewClassTy = NewRT->getPointeeType(); 7437 OldClassTy = OldRT->getPointeeType(); 7438 } 7439 } 7440 } 7441 7442 // The return types aren't either both pointers or references to a class type. 7443 if (NewClassTy.isNull()) { 7444 Diag(New->getLocation(), 7445 diag::err_different_return_type_for_overriding_virtual_function) 7446 << New->getDeclName() << NewTy << OldTy; 7447 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 7448 7449 return true; 7450 } 7451 7452 // C++ [class.virtual]p6: 7453 // If the return type of D::f differs from the return type of B::f, the 7454 // class type in the return type of D::f shall be complete at the point of 7455 // declaration of D::f or shall be the class type D. 7456 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 7457 if (!RT->isBeingDefined() && 7458 RequireCompleteType(New->getLocation(), NewClassTy, 7459 PDiag(diag::err_covariant_return_incomplete) 7460 << New->getDeclName())) 7461 return true; 7462 } 7463 7464 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 7465 // Check if the new class derives from the old class. 7466 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 7467 Diag(New->getLocation(), 7468 diag::err_covariant_return_not_derived) 7469 << New->getDeclName() << NewTy << OldTy; 7470 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 7471 return true; 7472 } 7473 7474 // Check if we the conversion from derived to base is valid. 7475 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 7476 diag::err_covariant_return_inaccessible_base, 7477 diag::err_covariant_return_ambiguous_derived_to_base_conv, 7478 // FIXME: Should this point to the return type? 7479 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 7480 // FIXME: this note won't trigger for delayed access control 7481 // diagnostics, and it's impossible to get an undelayed error 7482 // here from access control during the original parse because 7483 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 7484 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 7485 return true; 7486 } 7487 } 7488 7489 // The qualifiers of the return types must be the same. 7490 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 7491 Diag(New->getLocation(), 7492 diag::err_covariant_return_type_different_qualifications) 7493 << New->getDeclName() << NewTy << OldTy; 7494 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 7495 return true; 7496 }; 7497 7498 7499 // The new class type must have the same or less qualifiers as the old type. 7500 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 7501 Diag(New->getLocation(), 7502 diag::err_covariant_return_type_class_type_more_qualified) 7503 << New->getDeclName() << NewTy << OldTy; 7504 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 7505 return true; 7506 }; 7507 7508 return false; 7509} 7510 7511/// \brief Mark the given method pure. 7512/// 7513/// \param Method the method to be marked pure. 7514/// 7515/// \param InitRange the source range that covers the "0" initializer. 7516bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 7517 SourceLocation EndLoc = InitRange.getEnd(); 7518 if (EndLoc.isValid()) 7519 Method->setRangeEnd(EndLoc); 7520 7521 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 7522 Method->setPure(); 7523 return false; 7524 } 7525 7526 if (!Method->isInvalidDecl()) 7527 Diag(Method->getLocation(), diag::err_non_virtual_pure) 7528 << Method->getDeclName() << InitRange; 7529 return true; 7530} 7531 7532/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 7533/// an initializer for the out-of-line declaration 'Dcl'. The scope 7534/// is a fresh scope pushed for just this purpose. 7535/// 7536/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 7537/// static data member of class X, names should be looked up in the scope of 7538/// class X. 7539void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 7540 // If there is no declaration, there was an error parsing it. 7541 if (D == 0) return; 7542 7543 // We should only get called for declarations with scope specifiers, like: 7544 // int foo::bar; 7545 assert(D->isOutOfLine()); 7546 EnterDeclaratorContext(S, D->getDeclContext()); 7547} 7548 7549/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 7550/// initializer for the out-of-line declaration 'D'. 7551void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 7552 // If there is no declaration, there was an error parsing it. 7553 if (D == 0) return; 7554 7555 assert(D->isOutOfLine()); 7556 ExitDeclaratorContext(S); 7557} 7558 7559/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 7560/// C++ if/switch/while/for statement. 7561/// e.g: "if (int x = f()) {...}" 7562DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 7563 // C++ 6.4p2: 7564 // The declarator shall not specify a function or an array. 7565 // The type-specifier-seq shall not contain typedef and shall not declare a 7566 // new class or enumeration. 7567 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 7568 "Parser allowed 'typedef' as storage class of condition decl."); 7569 7570 TagDecl *OwnedTag = 0; 7571 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag); 7572 QualType Ty = TInfo->getType(); 7573 7574 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 7575 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 7576 // would be created and CXXConditionDeclExpr wants a VarDecl. 7577 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type) 7578 << D.getSourceRange(); 7579 return DeclResult(); 7580 } else if (OwnedTag && OwnedTag->isDefinition()) { 7581 // The type-specifier-seq shall not declare a new class or enumeration. 7582 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition); 7583 } 7584 7585 Decl *Dcl = ActOnDeclarator(S, D); 7586 if (!Dcl) 7587 return DeclResult(); 7588 7589 return Dcl; 7590} 7591 7592void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 7593 bool DefinitionRequired) { 7594 // Ignore any vtable uses in unevaluated operands or for classes that do 7595 // not have a vtable. 7596 if (!Class->isDynamicClass() || Class->isDependentContext() || 7597 CurContext->isDependentContext() || 7598 ExprEvalContexts.back().Context == Unevaluated) 7599 return; 7600 7601 // Try to insert this class into the map. 7602 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 7603 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 7604 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 7605 if (!Pos.second) { 7606 // If we already had an entry, check to see if we are promoting this vtable 7607 // to required a definition. If so, we need to reappend to the VTableUses 7608 // list, since we may have already processed the first entry. 7609 if (DefinitionRequired && !Pos.first->second) { 7610 Pos.first->second = true; 7611 } else { 7612 // Otherwise, we can early exit. 7613 return; 7614 } 7615 } 7616 7617 // Local classes need to have their virtual members marked 7618 // immediately. For all other classes, we mark their virtual members 7619 // at the end of the translation unit. 7620 if (Class->isLocalClass()) 7621 MarkVirtualMembersReferenced(Loc, Class); 7622 else 7623 VTableUses.push_back(std::make_pair(Class, Loc)); 7624} 7625 7626bool Sema::DefineUsedVTables() { 7627 if (VTableUses.empty()) 7628 return false; 7629 7630 // Note: The VTableUses vector could grow as a result of marking 7631 // the members of a class as "used", so we check the size each 7632 // time through the loop and prefer indices (with are stable) to 7633 // iterators (which are not). 7634 for (unsigned I = 0; I != VTableUses.size(); ++I) { 7635 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 7636 if (!Class) 7637 continue; 7638 7639 SourceLocation Loc = VTableUses[I].second; 7640 7641 // If this class has a key function, but that key function is 7642 // defined in another translation unit, we don't need to emit the 7643 // vtable even though we're using it. 7644 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class); 7645 if (KeyFunction && !KeyFunction->hasBody()) { 7646 switch (KeyFunction->getTemplateSpecializationKind()) { 7647 case TSK_Undeclared: 7648 case TSK_ExplicitSpecialization: 7649 case TSK_ExplicitInstantiationDeclaration: 7650 // The key function is in another translation unit. 7651 continue; 7652 7653 case TSK_ExplicitInstantiationDefinition: 7654 case TSK_ImplicitInstantiation: 7655 // We will be instantiating the key function. 7656 break; 7657 } 7658 } else if (!KeyFunction) { 7659 // If we have a class with no key function that is the subject 7660 // of an explicit instantiation declaration, suppress the 7661 // vtable; it will live with the explicit instantiation 7662 // definition. 7663 bool IsExplicitInstantiationDeclaration 7664 = Class->getTemplateSpecializationKind() 7665 == TSK_ExplicitInstantiationDeclaration; 7666 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 7667 REnd = Class->redecls_end(); 7668 R != REnd; ++R) { 7669 TemplateSpecializationKind TSK 7670 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 7671 if (TSK == TSK_ExplicitInstantiationDeclaration) 7672 IsExplicitInstantiationDeclaration = true; 7673 else if (TSK == TSK_ExplicitInstantiationDefinition) { 7674 IsExplicitInstantiationDeclaration = false; 7675 break; 7676 } 7677 } 7678 7679 if (IsExplicitInstantiationDeclaration) 7680 continue; 7681 } 7682 7683 // Mark all of the virtual members of this class as referenced, so 7684 // that we can build a vtable. Then, tell the AST consumer that a 7685 // vtable for this class is required. 7686 MarkVirtualMembersReferenced(Loc, Class); 7687 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 7688 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 7689 7690 // Optionally warn if we're emitting a weak vtable. 7691 if (Class->getLinkage() == ExternalLinkage && 7692 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 7693 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined())) 7694 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; 7695 } 7696 } 7697 VTableUses.clear(); 7698 7699 return true; 7700} 7701 7702void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 7703 const CXXRecordDecl *RD) { 7704 for (CXXRecordDecl::method_iterator i = RD->method_begin(), 7705 e = RD->method_end(); i != e; ++i) { 7706 CXXMethodDecl *MD = *i; 7707 7708 // C++ [basic.def.odr]p2: 7709 // [...] A virtual member function is used if it is not pure. [...] 7710 if (MD->isVirtual() && !MD->isPure()) 7711 MarkDeclarationReferenced(Loc, MD); 7712 } 7713 7714 // Only classes that have virtual bases need a VTT. 7715 if (RD->getNumVBases() == 0) 7716 return; 7717 7718 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 7719 e = RD->bases_end(); i != e; ++i) { 7720 const CXXRecordDecl *Base = 7721 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 7722 if (Base->getNumVBases() == 0) 7723 continue; 7724 MarkVirtualMembersReferenced(Loc, Base); 7725 } 7726} 7727 7728/// SetIvarInitializers - This routine builds initialization ASTs for the 7729/// Objective-C implementation whose ivars need be initialized. 7730void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 7731 if (!getLangOptions().CPlusPlus) 7732 return; 7733 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 7734 llvm::SmallVector<ObjCIvarDecl*, 8> ivars; 7735 CollectIvarsToConstructOrDestruct(OID, ivars); 7736 if (ivars.empty()) 7737 return; 7738 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit; 7739 for (unsigned i = 0; i < ivars.size(); i++) { 7740 FieldDecl *Field = ivars[i]; 7741 if (Field->isInvalidDecl()) 7742 continue; 7743 7744 CXXCtorInitializer *Member; 7745 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 7746 InitializationKind InitKind = 7747 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 7748 7749 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 7750 ExprResult MemberInit = 7751 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 7752 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 7753 // Note, MemberInit could actually come back empty if no initialization 7754 // is required (e.g., because it would call a trivial default constructor) 7755 if (!MemberInit.get() || MemberInit.isInvalid()) 7756 continue; 7757 7758 Member = 7759 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 7760 SourceLocation(), 7761 MemberInit.takeAs<Expr>(), 7762 SourceLocation()); 7763 AllToInit.push_back(Member); 7764 7765 // Be sure that the destructor is accessible and is marked as referenced. 7766 if (const RecordType *RecordTy 7767 = Context.getBaseElementType(Field->getType()) 7768 ->getAs<RecordType>()) { 7769 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 7770 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 7771 MarkDeclarationReferenced(Field->getLocation(), Destructor); 7772 CheckDestructorAccess(Field->getLocation(), Destructor, 7773 PDiag(diag::err_access_dtor_ivar) 7774 << Context.getBaseElementType(Field->getType())); 7775 } 7776 } 7777 } 7778 ObjCImplementation->setIvarInitializers(Context, 7779 AllToInit.data(), AllToInit.size()); 7780 } 7781} 7782