SemaDeclCXX.cpp revision 429bb276991ff2dbc7c5b438828b9b7737cb15eb
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 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 1769 CK_UncheckedDerivedToBase, 1770 VK_LValue, &BasePath).take(); 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->isInvalidDecl()) 2463 continue; 2464 if (FieldClassDecl->hasTrivialDestructor()) 2465 continue; 2466 2467 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 2468 assert(Dtor && "No dtor found for FieldClassDecl!"); 2469 CheckDestructorAccess(Field->getLocation(), Dtor, 2470 PDiag(diag::err_access_dtor_field) 2471 << Field->getDeclName() 2472 << FieldType); 2473 2474 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2475 } 2476 2477 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 2478 2479 // Bases. 2480 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2481 E = ClassDecl->bases_end(); Base != E; ++Base) { 2482 // Bases are always records in a well-formed non-dependent class. 2483 const RecordType *RT = Base->getType()->getAs<RecordType>(); 2484 2485 // Remember direct virtual bases. 2486 if (Base->isVirtual()) 2487 DirectVirtualBases.insert(RT); 2488 2489 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2490 // If our base class is invalid, we probably can't get its dtor anyway. 2491 if (BaseClassDecl->isInvalidDecl()) 2492 continue; 2493 // Ignore trivial destructors. 2494 if (BaseClassDecl->hasTrivialDestructor()) 2495 continue; 2496 2497 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 2498 assert(Dtor && "No dtor found for BaseClassDecl!"); 2499 2500 // FIXME: caret should be on the start of the class name 2501 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor, 2502 PDiag(diag::err_access_dtor_base) 2503 << Base->getType() 2504 << Base->getSourceRange()); 2505 2506 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2507 } 2508 2509 // Virtual bases. 2510 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2511 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2512 2513 // Bases are always records in a well-formed non-dependent class. 2514 const RecordType *RT = VBase->getType()->getAs<RecordType>(); 2515 2516 // Ignore direct virtual bases. 2517 if (DirectVirtualBases.count(RT)) 2518 continue; 2519 2520 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2521 // If our base class is invalid, we probably can't get its dtor anyway. 2522 if (BaseClassDecl->isInvalidDecl()) 2523 continue; 2524 // Ignore trivial destructors. 2525 if (BaseClassDecl->hasTrivialDestructor()) 2526 continue; 2527 2528 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 2529 assert(Dtor && "No dtor found for BaseClassDecl!"); 2530 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 2531 PDiag(diag::err_access_dtor_vbase) 2532 << VBase->getType()); 2533 2534 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2535 } 2536} 2537 2538void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 2539 if (!CDtorDecl) 2540 return; 2541 2542 if (CXXConstructorDecl *Constructor 2543 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) 2544 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 2545} 2546 2547bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2548 unsigned DiagID, AbstractDiagSelID SelID) { 2549 if (SelID == -1) 2550 return RequireNonAbstractType(Loc, T, PDiag(DiagID)); 2551 else 2552 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID); 2553} 2554 2555bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2556 const PartialDiagnostic &PD) { 2557 if (!getLangOptions().CPlusPlus) 2558 return false; 2559 2560 if (const ArrayType *AT = Context.getAsArrayType(T)) 2561 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 2562 2563 if (const PointerType *PT = T->getAs<PointerType>()) { 2564 // Find the innermost pointer type. 2565 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 2566 PT = T; 2567 2568 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 2569 return RequireNonAbstractType(Loc, AT->getElementType(), PD); 2570 } 2571 2572 const RecordType *RT = T->getAs<RecordType>(); 2573 if (!RT) 2574 return false; 2575 2576 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2577 2578 // We can't answer whether something is abstract until it has a 2579 // definition. If it's currently being defined, we'll walk back 2580 // over all the declarations when we have a full definition. 2581 const CXXRecordDecl *Def = RD->getDefinition(); 2582 if (!Def || Def->isBeingDefined()) 2583 return false; 2584 2585 if (!RD->isAbstract()) 2586 return false; 2587 2588 Diag(Loc, PD) << RD->getDeclName(); 2589 DiagnoseAbstractType(RD); 2590 2591 return true; 2592} 2593 2594void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 2595 // Check if we've already emitted the list of pure virtual functions 2596 // for this class. 2597 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 2598 return; 2599 2600 CXXFinalOverriderMap FinalOverriders; 2601 RD->getFinalOverriders(FinalOverriders); 2602 2603 // Keep a set of seen pure methods so we won't diagnose the same method 2604 // more than once. 2605 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 2606 2607 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 2608 MEnd = FinalOverriders.end(); 2609 M != MEnd; 2610 ++M) { 2611 for (OverridingMethods::iterator SO = M->second.begin(), 2612 SOEnd = M->second.end(); 2613 SO != SOEnd; ++SO) { 2614 // C++ [class.abstract]p4: 2615 // A class is abstract if it contains or inherits at least one 2616 // pure virtual function for which the final overrider is pure 2617 // virtual. 2618 2619 // 2620 if (SO->second.size() != 1) 2621 continue; 2622 2623 if (!SO->second.front().Method->isPure()) 2624 continue; 2625 2626 if (!SeenPureMethods.insert(SO->second.front().Method)) 2627 continue; 2628 2629 Diag(SO->second.front().Method->getLocation(), 2630 diag::note_pure_virtual_function) 2631 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 2632 } 2633 } 2634 2635 if (!PureVirtualClassDiagSet) 2636 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 2637 PureVirtualClassDiagSet->insert(RD); 2638} 2639 2640namespace { 2641struct AbstractUsageInfo { 2642 Sema &S; 2643 CXXRecordDecl *Record; 2644 CanQualType AbstractType; 2645 bool Invalid; 2646 2647 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 2648 : S(S), Record(Record), 2649 AbstractType(S.Context.getCanonicalType( 2650 S.Context.getTypeDeclType(Record))), 2651 Invalid(false) {} 2652 2653 void DiagnoseAbstractType() { 2654 if (Invalid) return; 2655 S.DiagnoseAbstractType(Record); 2656 Invalid = true; 2657 } 2658 2659 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 2660}; 2661 2662struct CheckAbstractUsage { 2663 AbstractUsageInfo &Info; 2664 const NamedDecl *Ctx; 2665 2666 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 2667 : Info(Info), Ctx(Ctx) {} 2668 2669 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 2670 switch (TL.getTypeLocClass()) { 2671#define ABSTRACT_TYPELOC(CLASS, PARENT) 2672#define TYPELOC(CLASS, PARENT) \ 2673 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break; 2674#include "clang/AST/TypeLocNodes.def" 2675 } 2676 } 2677 2678 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2679 Visit(TL.getResultLoc(), Sema::AbstractReturnType); 2680 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 2681 if (!TL.getArg(I)) 2682 continue; 2683 2684 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo(); 2685 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 2686 } 2687 } 2688 2689 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2690 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 2691 } 2692 2693 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 2694 // Visit the type parameters from a permissive context. 2695 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 2696 TemplateArgumentLoc TAL = TL.getArgLoc(I); 2697 if (TAL.getArgument().getKind() == TemplateArgument::Type) 2698 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 2699 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 2700 // TODO: other template argument types? 2701 } 2702 } 2703 2704 // Visit pointee types from a permissive context. 2705#define CheckPolymorphic(Type) \ 2706 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 2707 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 2708 } 2709 CheckPolymorphic(PointerTypeLoc) 2710 CheckPolymorphic(ReferenceTypeLoc) 2711 CheckPolymorphic(MemberPointerTypeLoc) 2712 CheckPolymorphic(BlockPointerTypeLoc) 2713 2714 /// Handle all the types we haven't given a more specific 2715 /// implementation for above. 2716 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 2717 // Every other kind of type that we haven't called out already 2718 // that has an inner type is either (1) sugar or (2) contains that 2719 // inner type in some way as a subobject. 2720 if (TypeLoc Next = TL.getNextTypeLoc()) 2721 return Visit(Next, Sel); 2722 2723 // If there's no inner type and we're in a permissive context, 2724 // don't diagnose. 2725 if (Sel == Sema::AbstractNone) return; 2726 2727 // Check whether the type matches the abstract type. 2728 QualType T = TL.getType(); 2729 if (T->isArrayType()) { 2730 Sel = Sema::AbstractArrayType; 2731 T = Info.S.Context.getBaseElementType(T); 2732 } 2733 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 2734 if (CT != Info.AbstractType) return; 2735 2736 // It matched; do some magic. 2737 if (Sel == Sema::AbstractArrayType) { 2738 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 2739 << T << TL.getSourceRange(); 2740 } else { 2741 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 2742 << Sel << T << TL.getSourceRange(); 2743 } 2744 Info.DiagnoseAbstractType(); 2745 } 2746}; 2747 2748void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 2749 Sema::AbstractDiagSelID Sel) { 2750 CheckAbstractUsage(*this, D).Visit(TL, Sel); 2751} 2752 2753} 2754 2755/// Check for invalid uses of an abstract type in a method declaration. 2756static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 2757 CXXMethodDecl *MD) { 2758 // No need to do the check on definitions, which require that 2759 // the return/param types be complete. 2760 if (MD->isThisDeclarationADefinition()) 2761 return; 2762 2763 // For safety's sake, just ignore it if we don't have type source 2764 // information. This should never happen for non-implicit methods, 2765 // but... 2766 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 2767 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 2768} 2769 2770/// Check for invalid uses of an abstract type within a class definition. 2771static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 2772 CXXRecordDecl *RD) { 2773 for (CXXRecordDecl::decl_iterator 2774 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) { 2775 Decl *D = *I; 2776 if (D->isImplicit()) continue; 2777 2778 // Methods and method templates. 2779 if (isa<CXXMethodDecl>(D)) { 2780 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 2781 } else if (isa<FunctionTemplateDecl>(D)) { 2782 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 2783 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 2784 2785 // Fields and static variables. 2786 } else if (isa<FieldDecl>(D)) { 2787 FieldDecl *FD = cast<FieldDecl>(D); 2788 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 2789 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 2790 } else if (isa<VarDecl>(D)) { 2791 VarDecl *VD = cast<VarDecl>(D); 2792 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 2793 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 2794 2795 // Nested classes and class templates. 2796 } else if (isa<CXXRecordDecl>(D)) { 2797 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 2798 } else if (isa<ClassTemplateDecl>(D)) { 2799 CheckAbstractClassUsage(Info, 2800 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 2801 } 2802 } 2803} 2804 2805/// \brief Perform semantic checks on a class definition that has been 2806/// completing, introducing implicitly-declared members, checking for 2807/// abstract types, etc. 2808void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 2809 if (!Record) 2810 return; 2811 2812 if (Record->isAbstract() && !Record->isInvalidDecl()) { 2813 AbstractUsageInfo Info(*this, Record); 2814 CheckAbstractClassUsage(Info, Record); 2815 } 2816 2817 // If this is not an aggregate type and has no user-declared constructor, 2818 // complain about any non-static data members of reference or const scalar 2819 // type, since they will never get initializers. 2820 if (!Record->isInvalidDecl() && !Record->isDependentType() && 2821 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) { 2822 bool Complained = false; 2823 for (RecordDecl::field_iterator F = Record->field_begin(), 2824 FEnd = Record->field_end(); 2825 F != FEnd; ++F) { 2826 if (F->getType()->isReferenceType() || 2827 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 2828 if (!Complained) { 2829 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 2830 << Record->getTagKind() << Record; 2831 Complained = true; 2832 } 2833 2834 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 2835 << F->getType()->isReferenceType() 2836 << F->getDeclName(); 2837 } 2838 } 2839 } 2840 2841 if (Record->isDynamicClass() && !Record->isDependentType()) 2842 DynamicClasses.push_back(Record); 2843 2844 if (Record->getIdentifier()) { 2845 // C++ [class.mem]p13: 2846 // If T is the name of a class, then each of the following shall have a 2847 // name different from T: 2848 // - every member of every anonymous union that is a member of class T. 2849 // 2850 // C++ [class.mem]p14: 2851 // In addition, if class T has a user-declared constructor (12.1), every 2852 // non-static data member of class T shall have a name different from T. 2853 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 2854 R.first != R.second; ++R.first) { 2855 NamedDecl *D = *R.first; 2856 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) || 2857 isa<IndirectFieldDecl>(D)) { 2858 Diag(D->getLocation(), diag::err_member_name_of_class) 2859 << D->getDeclName(); 2860 break; 2861 } 2862 } 2863 } 2864 2865 // Warn if the class has virtual methods but non-virtual public destructor. 2866 if (Record->isPolymorphic() && !Record->isDependentType()) { 2867 CXXDestructorDecl *dtor = Record->getDestructor(); 2868 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) 2869 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 2870 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 2871 } 2872 2873 // See if a method overloads virtual methods in a base 2874 /// class without overriding any. 2875 if (!Record->isDependentType()) { 2876 for (CXXRecordDecl::method_iterator M = Record->method_begin(), 2877 MEnd = Record->method_end(); 2878 M != MEnd; ++M) { 2879 if (!(*M)->isStatic()) 2880 DiagnoseHiddenVirtualMethods(Record, *M); 2881 } 2882 } 2883 2884 // Declare inherited constructors. We do this eagerly here because: 2885 // - The standard requires an eager diagnostic for conflicting inherited 2886 // constructors from different classes. 2887 // - The lazy declaration of the other implicit constructors is so as to not 2888 // waste space and performance on classes that are not meant to be 2889 // instantiated (e.g. meta-functions). This doesn't apply to classes that 2890 // have inherited constructors. 2891 DeclareInheritedConstructors(Record); 2892} 2893 2894/// \brief Data used with FindHiddenVirtualMethod 2895namespace { 2896 struct FindHiddenVirtualMethodData { 2897 Sema *S; 2898 CXXMethodDecl *Method; 2899 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 2900 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2901 }; 2902} 2903 2904/// \brief Member lookup function that determines whether a given C++ 2905/// method overloads virtual methods in a base class without overriding any, 2906/// to be used with CXXRecordDecl::lookupInBases(). 2907static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier, 2908 CXXBasePath &Path, 2909 void *UserData) { 2910 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 2911 2912 FindHiddenVirtualMethodData &Data 2913 = *static_cast<FindHiddenVirtualMethodData*>(UserData); 2914 2915 DeclarationName Name = Data.Method->getDeclName(); 2916 assert(Name.getNameKind() == DeclarationName::Identifier); 2917 2918 bool foundSameNameMethod = false; 2919 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods; 2920 for (Path.Decls = BaseRecord->lookup(Name); 2921 Path.Decls.first != Path.Decls.second; 2922 ++Path.Decls.first) { 2923 NamedDecl *D = *Path.Decls.first; 2924 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 2925 MD = MD->getCanonicalDecl(); 2926 foundSameNameMethod = true; 2927 // Interested only in hidden virtual methods. 2928 if (!MD->isVirtual()) 2929 continue; 2930 // If the method we are checking overrides a method from its base 2931 // don't warn about the other overloaded methods. 2932 if (!Data.S->IsOverload(Data.Method, MD, false)) 2933 return true; 2934 // Collect the overload only if its hidden. 2935 if (!Data.OverridenAndUsingBaseMethods.count(MD)) 2936 overloadedMethods.push_back(MD); 2937 } 2938 } 2939 2940 if (foundSameNameMethod) 2941 Data.OverloadedMethods.append(overloadedMethods.begin(), 2942 overloadedMethods.end()); 2943 return foundSameNameMethod; 2944} 2945 2946/// \brief See if a method overloads virtual methods in a base class without 2947/// overriding any. 2948void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 2949 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual, 2950 MD->getLocation()) == Diagnostic::Ignored) 2951 return; 2952 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier) 2953 return; 2954 2955 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 2956 /*bool RecordPaths=*/false, 2957 /*bool DetectVirtual=*/false); 2958 FindHiddenVirtualMethodData Data; 2959 Data.Method = MD; 2960 Data.S = this; 2961 2962 // Keep the base methods that were overriden or introduced in the subclass 2963 // by 'using' in a set. A base method not in this set is hidden. 2964 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName()); 2965 res.first != res.second; ++res.first) { 2966 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first)) 2967 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 2968 E = MD->end_overridden_methods(); 2969 I != E; ++I) 2970 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl()); 2971 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first)) 2972 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl())) 2973 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl()); 2974 } 2975 2976 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) && 2977 !Data.OverloadedMethods.empty()) { 2978 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 2979 << MD << (Data.OverloadedMethods.size() > 1); 2980 2981 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) { 2982 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i]; 2983 Diag(overloadedMD->getLocation(), 2984 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 2985 } 2986 } 2987} 2988 2989void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 2990 Decl *TagDecl, 2991 SourceLocation LBrac, 2992 SourceLocation RBrac, 2993 AttributeList *AttrList) { 2994 if (!TagDecl) 2995 return; 2996 2997 AdjustDeclIfTemplate(TagDecl); 2998 2999 ActOnFields(S, RLoc, TagDecl, 3000 // strict aliasing violation! 3001 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 3002 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList); 3003 3004 CheckCompletedCXXClass( 3005 dyn_cast_or_null<CXXRecordDecl>(TagDecl)); 3006} 3007 3008namespace { 3009 /// \brief Helper class that collects exception specifications for 3010 /// implicitly-declared special member functions. 3011 class ImplicitExceptionSpecification { 3012 ASTContext &Context; 3013 // We order exception specifications thus: 3014 // noexcept is the most restrictive, but is only used in C++0x. 3015 // throw() comes next. 3016 // Then a throw(collected exceptions) 3017 // Finally no specification. 3018 // throw(...) is used instead if any called function uses it. 3019 ExceptionSpecificationType ComputedEST; 3020 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 3021 llvm::SmallVector<QualType, 4> Exceptions; 3022 3023 void ClearExceptions() { 3024 ExceptionsSeen.clear(); 3025 Exceptions.clear(); 3026 } 3027 3028 public: 3029 explicit ImplicitExceptionSpecification(ASTContext &Context) 3030 : Context(Context), ComputedEST(EST_BasicNoexcept) { 3031 if (!Context.getLangOptions().CPlusPlus0x) 3032 ComputedEST = EST_DynamicNone; 3033 } 3034 3035 /// \brief Get the computed exception specification type. 3036 ExceptionSpecificationType getExceptionSpecType() const { 3037 assert(ComputedEST != EST_ComputedNoexcept && 3038 "noexcept(expr) should not be a possible result"); 3039 return ComputedEST; 3040 } 3041 3042 /// \brief The number of exceptions in the exception specification. 3043 unsigned size() const { return Exceptions.size(); } 3044 3045 /// \brief The set of exceptions in the exception specification. 3046 const QualType *data() const { return Exceptions.data(); } 3047 3048 /// \brief Integrate another called method into the collected data. 3049 void CalledDecl(CXXMethodDecl *Method) { 3050 // If we have an MSAny spec already, don't bother. 3051 if (!Method || ComputedEST == EST_MSAny) 3052 return; 3053 3054 const FunctionProtoType *Proto 3055 = Method->getType()->getAs<FunctionProtoType>(); 3056 3057 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 3058 3059 // If this function can throw any exceptions, make a note of that. 3060 if (EST == EST_MSAny || EST == EST_None) { 3061 ClearExceptions(); 3062 ComputedEST = EST; 3063 return; 3064 } 3065 3066 // If this function has a basic noexcept, it doesn't affect the outcome. 3067 if (EST == EST_BasicNoexcept) 3068 return; 3069 3070 // If we have a throw-all spec at this point, ignore the function. 3071 if (ComputedEST == EST_None) 3072 return; 3073 3074 // If we're still at noexcept(true) and there's a nothrow() callee, 3075 // change to that specification. 3076 if (EST == EST_DynamicNone) { 3077 if (ComputedEST == EST_BasicNoexcept) 3078 ComputedEST = EST_DynamicNone; 3079 return; 3080 } 3081 3082 // Check out noexcept specs. 3083 if (EST == EST_ComputedNoexcept) { 3084 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(Context); 3085 assert(NR != FunctionProtoType::NR_NoNoexcept && 3086 "Must have noexcept result for EST_ComputedNoexcept."); 3087 assert(NR != FunctionProtoType::NR_Dependent && 3088 "Should not generate implicit declarations for dependent cases, " 3089 "and don't know how to handle them anyway."); 3090 3091 // noexcept(false) -> no spec on the new function 3092 if (NR == FunctionProtoType::NR_Throw) { 3093 ClearExceptions(); 3094 ComputedEST = EST_None; 3095 } 3096 // noexcept(true) won't change anything either. 3097 return; 3098 } 3099 3100 assert(EST == EST_Dynamic && "EST case not considered earlier."); 3101 assert(ComputedEST != EST_None && 3102 "Shouldn't collect exceptions when throw-all is guaranteed."); 3103 ComputedEST = EST_Dynamic; 3104 // Record the exceptions in this function's exception specification. 3105 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(), 3106 EEnd = Proto->exception_end(); 3107 E != EEnd; ++E) 3108 if (ExceptionsSeen.insert(Context.getCanonicalType(*E))) 3109 Exceptions.push_back(*E); 3110 } 3111 }; 3112} 3113 3114 3115/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 3116/// special functions, such as the default constructor, copy 3117/// constructor, or destructor, to the given C++ class (C++ 3118/// [special]p1). This routine can only be executed just before the 3119/// definition of the class is complete. 3120void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 3121 if (!ClassDecl->hasUserDeclaredConstructor()) 3122 ++ASTContext::NumImplicitDefaultConstructors; 3123 3124 if (!ClassDecl->hasUserDeclaredCopyConstructor()) 3125 ++ASTContext::NumImplicitCopyConstructors; 3126 3127 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 3128 ++ASTContext::NumImplicitCopyAssignmentOperators; 3129 3130 // If we have a dynamic class, then the copy assignment operator may be 3131 // virtual, so we have to declare it immediately. This ensures that, e.g., 3132 // it shows up in the right place in the vtable and that we diagnose 3133 // problems with the implicit exception specification. 3134 if (ClassDecl->isDynamicClass()) 3135 DeclareImplicitCopyAssignment(ClassDecl); 3136 } 3137 3138 if (!ClassDecl->hasUserDeclaredDestructor()) { 3139 ++ASTContext::NumImplicitDestructors; 3140 3141 // If we have a dynamic class, then the destructor may be virtual, so we 3142 // have to declare the destructor immediately. This ensures that, e.g., it 3143 // shows up in the right place in the vtable and that we diagnose problems 3144 // with the implicit exception specification. 3145 if (ClassDecl->isDynamicClass()) 3146 DeclareImplicitDestructor(ClassDecl); 3147 } 3148} 3149 3150void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 3151 if (!D) 3152 return; 3153 3154 TemplateParameterList *Params = 0; 3155 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 3156 Params = Template->getTemplateParameters(); 3157 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 3158 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 3159 Params = PartialSpec->getTemplateParameters(); 3160 else 3161 return; 3162 3163 for (TemplateParameterList::iterator Param = Params->begin(), 3164 ParamEnd = Params->end(); 3165 Param != ParamEnd; ++Param) { 3166 NamedDecl *Named = cast<NamedDecl>(*Param); 3167 if (Named->getDeclName()) { 3168 S->AddDecl(Named); 3169 IdResolver.AddDecl(Named); 3170 } 3171 } 3172} 3173 3174void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 3175 if (!RecordD) return; 3176 AdjustDeclIfTemplate(RecordD); 3177 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 3178 PushDeclContext(S, Record); 3179} 3180 3181void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 3182 if (!RecordD) return; 3183 PopDeclContext(); 3184} 3185 3186/// ActOnStartDelayedCXXMethodDeclaration - We have completed 3187/// parsing a top-level (non-nested) C++ class, and we are now 3188/// parsing those parts of the given Method declaration that could 3189/// not be parsed earlier (C++ [class.mem]p2), such as default 3190/// arguments. This action should enter the scope of the given 3191/// Method declaration as if we had just parsed the qualified method 3192/// name. However, it should not bring the parameters into scope; 3193/// that will be performed by ActOnDelayedCXXMethodParameter. 3194void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 3195} 3196 3197/// ActOnDelayedCXXMethodParameter - We've already started a delayed 3198/// C++ method declaration. We're (re-)introducing the given 3199/// function parameter into scope for use in parsing later parts of 3200/// the method declaration. For example, we could see an 3201/// ActOnParamDefaultArgument event for this parameter. 3202void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 3203 if (!ParamD) 3204 return; 3205 3206 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 3207 3208 // If this parameter has an unparsed default argument, clear it out 3209 // to make way for the parsed default argument. 3210 if (Param->hasUnparsedDefaultArg()) 3211 Param->setDefaultArg(0); 3212 3213 S->AddDecl(Param); 3214 if (Param->getDeclName()) 3215 IdResolver.AddDecl(Param); 3216} 3217 3218/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 3219/// processing the delayed method declaration for Method. The method 3220/// declaration is now considered finished. There may be a separate 3221/// ActOnStartOfFunctionDef action later (not necessarily 3222/// immediately!) for this method, if it was also defined inside the 3223/// class body. 3224void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 3225 if (!MethodD) 3226 return; 3227 3228 AdjustDeclIfTemplate(MethodD); 3229 3230 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 3231 3232 // Now that we have our default arguments, check the constructor 3233 // again. It could produce additional diagnostics or affect whether 3234 // the class has implicitly-declared destructors, among other 3235 // things. 3236 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 3237 CheckConstructor(Constructor); 3238 3239 // Check the default arguments, which we may have added. 3240 if (!Method->isInvalidDecl()) 3241 CheckCXXDefaultArguments(Method); 3242} 3243 3244/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 3245/// the well-formedness of the constructor declarator @p D with type @p 3246/// R. If there are any errors in the declarator, this routine will 3247/// emit diagnostics and set the invalid bit to true. In any case, the type 3248/// will be updated to reflect a well-formed type for the constructor and 3249/// returned. 3250QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 3251 StorageClass &SC) { 3252 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 3253 3254 // C++ [class.ctor]p3: 3255 // A constructor shall not be virtual (10.3) or static (9.4). A 3256 // constructor can be invoked for a const, volatile or const 3257 // volatile object. A constructor shall not be declared const, 3258 // volatile, or const volatile (9.3.2). 3259 if (isVirtual) { 3260 if (!D.isInvalidType()) 3261 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 3262 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 3263 << SourceRange(D.getIdentifierLoc()); 3264 D.setInvalidType(); 3265 } 3266 if (SC == SC_Static) { 3267 if (!D.isInvalidType()) 3268 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 3269 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 3270 << SourceRange(D.getIdentifierLoc()); 3271 D.setInvalidType(); 3272 SC = SC_None; 3273 } 3274 3275 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 3276 if (FTI.TypeQuals != 0) { 3277 if (FTI.TypeQuals & Qualifiers::Const) 3278 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 3279 << "const" << SourceRange(D.getIdentifierLoc()); 3280 if (FTI.TypeQuals & Qualifiers::Volatile) 3281 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 3282 << "volatile" << SourceRange(D.getIdentifierLoc()); 3283 if (FTI.TypeQuals & Qualifiers::Restrict) 3284 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 3285 << "restrict" << SourceRange(D.getIdentifierLoc()); 3286 D.setInvalidType(); 3287 } 3288 3289 // C++0x [class.ctor]p4: 3290 // A constructor shall not be declared with a ref-qualifier. 3291 if (FTI.hasRefQualifier()) { 3292 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 3293 << FTI.RefQualifierIsLValueRef 3294 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 3295 D.setInvalidType(); 3296 } 3297 3298 // Rebuild the function type "R" without any type qualifiers (in 3299 // case any of the errors above fired) and with "void" as the 3300 // return type, since constructors don't have return types. 3301 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 3302 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType()) 3303 return R; 3304 3305 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 3306 EPI.TypeQuals = 0; 3307 EPI.RefQualifier = RQ_None; 3308 3309 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 3310 Proto->getNumArgs(), EPI); 3311} 3312 3313/// CheckConstructor - Checks a fully-formed constructor for 3314/// well-formedness, issuing any diagnostics required. Returns true if 3315/// the constructor declarator is invalid. 3316void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 3317 CXXRecordDecl *ClassDecl 3318 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 3319 if (!ClassDecl) 3320 return Constructor->setInvalidDecl(); 3321 3322 // C++ [class.copy]p3: 3323 // A declaration of a constructor for a class X is ill-formed if 3324 // its first parameter is of type (optionally cv-qualified) X and 3325 // either there are no other parameters or else all other 3326 // parameters have default arguments. 3327 if (!Constructor->isInvalidDecl() && 3328 ((Constructor->getNumParams() == 1) || 3329 (Constructor->getNumParams() > 1 && 3330 Constructor->getParamDecl(1)->hasDefaultArg())) && 3331 Constructor->getTemplateSpecializationKind() 3332 != TSK_ImplicitInstantiation) { 3333 QualType ParamType = Constructor->getParamDecl(0)->getType(); 3334 QualType ClassTy = Context.getTagDeclType(ClassDecl); 3335 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 3336 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 3337 const char *ConstRef 3338 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 3339 : " const &"; 3340 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 3341 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 3342 3343 // FIXME: Rather that making the constructor invalid, we should endeavor 3344 // to fix the type. 3345 Constructor->setInvalidDecl(); 3346 } 3347 } 3348} 3349 3350/// CheckDestructor - Checks a fully-formed destructor definition for 3351/// well-formedness, issuing any diagnostics required. Returns true 3352/// on error. 3353bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 3354 CXXRecordDecl *RD = Destructor->getParent(); 3355 3356 if (Destructor->isVirtual()) { 3357 SourceLocation Loc; 3358 3359 if (!Destructor->isImplicit()) 3360 Loc = Destructor->getLocation(); 3361 else 3362 Loc = RD->getLocation(); 3363 3364 // If we have a virtual destructor, look up the deallocation function 3365 FunctionDecl *OperatorDelete = 0; 3366 DeclarationName Name = 3367 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 3368 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 3369 return true; 3370 3371 MarkDeclarationReferenced(Loc, OperatorDelete); 3372 3373 Destructor->setOperatorDelete(OperatorDelete); 3374 } 3375 3376 return false; 3377} 3378 3379static inline bool 3380FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 3381 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 3382 FTI.ArgInfo[0].Param && 3383 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()); 3384} 3385 3386/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 3387/// the well-formednes of the destructor declarator @p D with type @p 3388/// R. If there are any errors in the declarator, this routine will 3389/// emit diagnostics and set the declarator to invalid. Even if this happens, 3390/// will be updated to reflect a well-formed type for the destructor and 3391/// returned. 3392QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 3393 StorageClass& SC) { 3394 // C++ [class.dtor]p1: 3395 // [...] A typedef-name that names a class is a class-name 3396 // (7.1.3); however, a typedef-name that names a class shall not 3397 // be used as the identifier in the declarator for a destructor 3398 // declaration. 3399 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 3400 if (isa<TypedefType>(DeclaratorType)) 3401 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 3402 << DeclaratorType; 3403 3404 // C++ [class.dtor]p2: 3405 // A destructor is used to destroy objects of its class type. A 3406 // destructor takes no parameters, and no return type can be 3407 // specified for it (not even void). The address of a destructor 3408 // shall not be taken. A destructor shall not be static. A 3409 // destructor can be invoked for a const, volatile or const 3410 // volatile object. A destructor shall not be declared const, 3411 // volatile or const volatile (9.3.2). 3412 if (SC == SC_Static) { 3413 if (!D.isInvalidType()) 3414 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 3415 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 3416 << SourceRange(D.getIdentifierLoc()) 3417 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 3418 3419 SC = SC_None; 3420 } 3421 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 3422 // Destructors don't have return types, but the parser will 3423 // happily parse something like: 3424 // 3425 // class X { 3426 // float ~X(); 3427 // }; 3428 // 3429 // The return type will be eliminated later. 3430 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 3431 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 3432 << SourceRange(D.getIdentifierLoc()); 3433 } 3434 3435 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 3436 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 3437 if (FTI.TypeQuals & Qualifiers::Const) 3438 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3439 << "const" << SourceRange(D.getIdentifierLoc()); 3440 if (FTI.TypeQuals & Qualifiers::Volatile) 3441 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3442 << "volatile" << SourceRange(D.getIdentifierLoc()); 3443 if (FTI.TypeQuals & Qualifiers::Restrict) 3444 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3445 << "restrict" << SourceRange(D.getIdentifierLoc()); 3446 D.setInvalidType(); 3447 } 3448 3449 // C++0x [class.dtor]p2: 3450 // A destructor shall not be declared with a ref-qualifier. 3451 if (FTI.hasRefQualifier()) { 3452 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 3453 << FTI.RefQualifierIsLValueRef 3454 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 3455 D.setInvalidType(); 3456 } 3457 3458 // Make sure we don't have any parameters. 3459 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 3460 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 3461 3462 // Delete the parameters. 3463 FTI.freeArgs(); 3464 D.setInvalidType(); 3465 } 3466 3467 // Make sure the destructor isn't variadic. 3468 if (FTI.isVariadic) { 3469 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 3470 D.setInvalidType(); 3471 } 3472 3473 // Rebuild the function type "R" without any type qualifiers or 3474 // parameters (in case any of the errors above fired) and with 3475 // "void" as the return type, since destructors don't have return 3476 // types. 3477 if (!D.isInvalidType()) 3478 return R; 3479 3480 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 3481 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 3482 EPI.Variadic = false; 3483 EPI.TypeQuals = 0; 3484 EPI.RefQualifier = RQ_None; 3485 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 3486} 3487 3488/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 3489/// well-formednes of the conversion function declarator @p D with 3490/// type @p R. If there are any errors in the declarator, this routine 3491/// will emit diagnostics and return true. Otherwise, it will return 3492/// false. Either way, the type @p R will be updated to reflect a 3493/// well-formed type for the conversion operator. 3494void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 3495 StorageClass& SC) { 3496 // C++ [class.conv.fct]p1: 3497 // Neither parameter types nor return type can be specified. The 3498 // type of a conversion function (8.3.5) is "function taking no 3499 // parameter returning conversion-type-id." 3500 if (SC == SC_Static) { 3501 if (!D.isInvalidType()) 3502 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 3503 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 3504 << SourceRange(D.getIdentifierLoc()); 3505 D.setInvalidType(); 3506 SC = SC_None; 3507 } 3508 3509 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 3510 3511 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 3512 // Conversion functions don't have return types, but the parser will 3513 // happily parse something like: 3514 // 3515 // class X { 3516 // float operator bool(); 3517 // }; 3518 // 3519 // The return type will be changed later anyway. 3520 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 3521 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 3522 << SourceRange(D.getIdentifierLoc()); 3523 D.setInvalidType(); 3524 } 3525 3526 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 3527 3528 // Make sure we don't have any parameters. 3529 if (Proto->getNumArgs() > 0) { 3530 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 3531 3532 // Delete the parameters. 3533 D.getFunctionTypeInfo().freeArgs(); 3534 D.setInvalidType(); 3535 } else if (Proto->isVariadic()) { 3536 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 3537 D.setInvalidType(); 3538 } 3539 3540 // Diagnose "&operator bool()" and other such nonsense. This 3541 // is actually a gcc extension which we don't support. 3542 if (Proto->getResultType() != ConvType) { 3543 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 3544 << Proto->getResultType(); 3545 D.setInvalidType(); 3546 ConvType = Proto->getResultType(); 3547 } 3548 3549 // C++ [class.conv.fct]p4: 3550 // The conversion-type-id shall not represent a function type nor 3551 // an array type. 3552 if (ConvType->isArrayType()) { 3553 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 3554 ConvType = Context.getPointerType(ConvType); 3555 D.setInvalidType(); 3556 } else if (ConvType->isFunctionType()) { 3557 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 3558 ConvType = Context.getPointerType(ConvType); 3559 D.setInvalidType(); 3560 } 3561 3562 // Rebuild the function type "R" without any parameters (in case any 3563 // of the errors above fired) and with the conversion type as the 3564 // return type. 3565 if (D.isInvalidType()) 3566 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo()); 3567 3568 // C++0x explicit conversion operators. 3569 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 3570 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3571 diag::warn_explicit_conversion_functions) 3572 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 3573} 3574 3575/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 3576/// the declaration of the given C++ conversion function. This routine 3577/// is responsible for recording the conversion function in the C++ 3578/// class, if possible. 3579Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 3580 assert(Conversion && "Expected to receive a conversion function declaration"); 3581 3582 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 3583 3584 // Make sure we aren't redeclaring the conversion function. 3585 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 3586 3587 // C++ [class.conv.fct]p1: 3588 // [...] A conversion function is never used to convert a 3589 // (possibly cv-qualified) object to the (possibly cv-qualified) 3590 // same object type (or a reference to it), to a (possibly 3591 // cv-qualified) base class of that type (or a reference to it), 3592 // or to (possibly cv-qualified) void. 3593 // FIXME: Suppress this warning if the conversion function ends up being a 3594 // virtual function that overrides a virtual function in a base class. 3595 QualType ClassType 3596 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 3597 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 3598 ConvType = ConvTypeRef->getPointeeType(); 3599 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 3600 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 3601 /* Suppress diagnostics for instantiations. */; 3602 else if (ConvType->isRecordType()) { 3603 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 3604 if (ConvType == ClassType) 3605 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 3606 << ClassType; 3607 else if (IsDerivedFrom(ClassType, ConvType)) 3608 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 3609 << ClassType << ConvType; 3610 } else if (ConvType->isVoidType()) { 3611 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 3612 << ClassType << ConvType; 3613 } 3614 3615 if (FunctionTemplateDecl *ConversionTemplate 3616 = Conversion->getDescribedFunctionTemplate()) 3617 return ConversionTemplate; 3618 3619 return Conversion; 3620} 3621 3622//===----------------------------------------------------------------------===// 3623// Namespace Handling 3624//===----------------------------------------------------------------------===// 3625 3626 3627 3628/// ActOnStartNamespaceDef - This is called at the start of a namespace 3629/// definition. 3630Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 3631 SourceLocation InlineLoc, 3632 SourceLocation NamespaceLoc, 3633 SourceLocation IdentLoc, 3634 IdentifierInfo *II, 3635 SourceLocation LBrace, 3636 AttributeList *AttrList) { 3637 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 3638 // For anonymous namespace, take the location of the left brace. 3639 SourceLocation Loc = II ? IdentLoc : LBrace; 3640 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, 3641 StartLoc, Loc, II); 3642 Namespc->setInline(InlineLoc.isValid()); 3643 3644 Scope *DeclRegionScope = NamespcScope->getParent(); 3645 3646 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 3647 3648 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 3649 PushNamespaceVisibilityAttr(Attr); 3650 3651 if (II) { 3652 // C++ [namespace.def]p2: 3653 // The identifier in an original-namespace-definition shall not 3654 // have been previously defined in the declarative region in 3655 // which the original-namespace-definition appears. The 3656 // identifier in an original-namespace-definition is the name of 3657 // the namespace. Subsequently in that declarative region, it is 3658 // treated as an original-namespace-name. 3659 // 3660 // Since namespace names are unique in their scope, and we don't 3661 // look through using directives, just 3662 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II); 3663 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first; 3664 3665 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 3666 // This is an extended namespace definition. 3667 if (Namespc->isInline() != OrigNS->isInline()) { 3668 // inline-ness must match 3669 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch) 3670 << Namespc->isInline(); 3671 Diag(OrigNS->getLocation(), diag::note_previous_definition); 3672 Namespc->setInvalidDecl(); 3673 // Recover by ignoring the new namespace's inline status. 3674 Namespc->setInline(OrigNS->isInline()); 3675 } 3676 3677 // Attach this namespace decl to the chain of extended namespace 3678 // definitions. 3679 OrigNS->setNextNamespace(Namespc); 3680 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 3681 3682 // Remove the previous declaration from the scope. 3683 if (DeclRegionScope->isDeclScope(OrigNS)) { 3684 IdResolver.RemoveDecl(OrigNS); 3685 DeclRegionScope->RemoveDecl(OrigNS); 3686 } 3687 } else if (PrevDecl) { 3688 // This is an invalid name redefinition. 3689 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 3690 << Namespc->getDeclName(); 3691 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3692 Namespc->setInvalidDecl(); 3693 // Continue on to push Namespc as current DeclContext and return it. 3694 } else if (II->isStr("std") && 3695 CurContext->getRedeclContext()->isTranslationUnit()) { 3696 // This is the first "real" definition of the namespace "std", so update 3697 // our cache of the "std" namespace to point at this definition. 3698 if (NamespaceDecl *StdNS = getStdNamespace()) { 3699 // We had already defined a dummy namespace "std". Link this new 3700 // namespace definition to the dummy namespace "std". 3701 StdNS->setNextNamespace(Namespc); 3702 StdNS->setLocation(IdentLoc); 3703 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace()); 3704 } 3705 3706 // Make our StdNamespace cache point at the first real definition of the 3707 // "std" namespace. 3708 StdNamespace = Namespc; 3709 } 3710 3711 PushOnScopeChains(Namespc, DeclRegionScope); 3712 } else { 3713 // Anonymous namespaces. 3714 assert(Namespc->isAnonymousNamespace()); 3715 3716 // Link the anonymous namespace into its parent. 3717 NamespaceDecl *PrevDecl; 3718 DeclContext *Parent = CurContext->getRedeclContext(); 3719 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 3720 PrevDecl = TU->getAnonymousNamespace(); 3721 TU->setAnonymousNamespace(Namespc); 3722 } else { 3723 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 3724 PrevDecl = ND->getAnonymousNamespace(); 3725 ND->setAnonymousNamespace(Namespc); 3726 } 3727 3728 // Link the anonymous namespace with its previous declaration. 3729 if (PrevDecl) { 3730 assert(PrevDecl->isAnonymousNamespace()); 3731 assert(!PrevDecl->getNextNamespace()); 3732 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace()); 3733 PrevDecl->setNextNamespace(Namespc); 3734 3735 if (Namespc->isInline() != PrevDecl->isInline()) { 3736 // inline-ness must match 3737 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch) 3738 << Namespc->isInline(); 3739 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3740 Namespc->setInvalidDecl(); 3741 // Recover by ignoring the new namespace's inline status. 3742 Namespc->setInline(PrevDecl->isInline()); 3743 } 3744 } 3745 3746 CurContext->addDecl(Namespc); 3747 3748 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 3749 // behaves as if it were replaced by 3750 // namespace unique { /* empty body */ } 3751 // using namespace unique; 3752 // namespace unique { namespace-body } 3753 // where all occurrences of 'unique' in a translation unit are 3754 // replaced by the same identifier and this identifier differs 3755 // from all other identifiers in the entire program. 3756 3757 // We just create the namespace with an empty name and then add an 3758 // implicit using declaration, just like the standard suggests. 3759 // 3760 // CodeGen enforces the "universally unique" aspect by giving all 3761 // declarations semantically contained within an anonymous 3762 // namespace internal linkage. 3763 3764 if (!PrevDecl) { 3765 UsingDirectiveDecl* UD 3766 = UsingDirectiveDecl::Create(Context, CurContext, 3767 /* 'using' */ LBrace, 3768 /* 'namespace' */ SourceLocation(), 3769 /* qualifier */ NestedNameSpecifierLoc(), 3770 /* identifier */ SourceLocation(), 3771 Namespc, 3772 /* Ancestor */ CurContext); 3773 UD->setImplicit(); 3774 CurContext->addDecl(UD); 3775 } 3776 } 3777 3778 // Although we could have an invalid decl (i.e. the namespace name is a 3779 // redefinition), push it as current DeclContext and try to continue parsing. 3780 // FIXME: We should be able to push Namespc here, so that the each DeclContext 3781 // for the namespace has the declarations that showed up in that particular 3782 // namespace definition. 3783 PushDeclContext(NamespcScope, Namespc); 3784 return Namespc; 3785} 3786 3787/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 3788/// is a namespace alias, returns the namespace it points to. 3789static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 3790 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 3791 return AD->getNamespace(); 3792 return dyn_cast_or_null<NamespaceDecl>(D); 3793} 3794 3795/// ActOnFinishNamespaceDef - This callback is called after a namespace is 3796/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 3797void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 3798 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 3799 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 3800 Namespc->setRBraceLoc(RBrace); 3801 PopDeclContext(); 3802 if (Namespc->hasAttr<VisibilityAttr>()) 3803 PopPragmaVisibility(); 3804} 3805 3806CXXRecordDecl *Sema::getStdBadAlloc() const { 3807 return cast_or_null<CXXRecordDecl>( 3808 StdBadAlloc.get(Context.getExternalSource())); 3809} 3810 3811NamespaceDecl *Sema::getStdNamespace() const { 3812 return cast_or_null<NamespaceDecl>( 3813 StdNamespace.get(Context.getExternalSource())); 3814} 3815 3816/// \brief Retrieve the special "std" namespace, which may require us to 3817/// implicitly define the namespace. 3818NamespaceDecl *Sema::getOrCreateStdNamespace() { 3819 if (!StdNamespace) { 3820 // The "std" namespace has not yet been defined, so build one implicitly. 3821 StdNamespace = NamespaceDecl::Create(Context, 3822 Context.getTranslationUnitDecl(), 3823 SourceLocation(), SourceLocation(), 3824 &PP.getIdentifierTable().get("std")); 3825 getStdNamespace()->setImplicit(true); 3826 } 3827 3828 return getStdNamespace(); 3829} 3830 3831/// \brief Determine whether a using statement is in a context where it will be 3832/// apply in all contexts. 3833static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 3834 switch (CurContext->getDeclKind()) { 3835 case Decl::TranslationUnit: 3836 return true; 3837 case Decl::LinkageSpec: 3838 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 3839 default: 3840 return false; 3841 } 3842} 3843 3844Decl *Sema::ActOnUsingDirective(Scope *S, 3845 SourceLocation UsingLoc, 3846 SourceLocation NamespcLoc, 3847 CXXScopeSpec &SS, 3848 SourceLocation IdentLoc, 3849 IdentifierInfo *NamespcName, 3850 AttributeList *AttrList) { 3851 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 3852 assert(NamespcName && "Invalid NamespcName."); 3853 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 3854 3855 // This can only happen along a recovery path. 3856 while (S->getFlags() & Scope::TemplateParamScope) 3857 S = S->getParent(); 3858 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 3859 3860 UsingDirectiveDecl *UDir = 0; 3861 NestedNameSpecifier *Qualifier = 0; 3862 if (SS.isSet()) 3863 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 3864 3865 // Lookup namespace name. 3866 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 3867 LookupParsedName(R, S, &SS); 3868 if (R.isAmbiguous()) 3869 return 0; 3870 3871 if (R.empty()) { 3872 // Allow "using namespace std;" or "using namespace ::std;" even if 3873 // "std" hasn't been defined yet, for GCC compatibility. 3874 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 3875 NamespcName->isStr("std")) { 3876 Diag(IdentLoc, diag::ext_using_undefined_std); 3877 R.addDecl(getOrCreateStdNamespace()); 3878 R.resolveKind(); 3879 } 3880 // Otherwise, attempt typo correction. 3881 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false, 3882 CTC_NoKeywords, 0)) { 3883 if (R.getAsSingle<NamespaceDecl>() || 3884 R.getAsSingle<NamespaceAliasDecl>()) { 3885 if (DeclContext *DC = computeDeclContext(SS, false)) 3886 Diag(IdentLoc, diag::err_using_directive_member_suggest) 3887 << NamespcName << DC << Corrected << SS.getRange() 3888 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 3889 else 3890 Diag(IdentLoc, diag::err_using_directive_suggest) 3891 << NamespcName << Corrected 3892 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 3893 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here) 3894 << Corrected; 3895 3896 NamespcName = Corrected.getAsIdentifierInfo(); 3897 } else { 3898 R.clear(); 3899 R.setLookupName(NamespcName); 3900 } 3901 } 3902 } 3903 3904 if (!R.empty()) { 3905 NamedDecl *Named = R.getFoundDecl(); 3906 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 3907 && "expected namespace decl"); 3908 // C++ [namespace.udir]p1: 3909 // A using-directive specifies that the names in the nominated 3910 // namespace can be used in the scope in which the 3911 // using-directive appears after the using-directive. During 3912 // unqualified name lookup (3.4.1), the names appear as if they 3913 // were declared in the nearest enclosing namespace which 3914 // contains both the using-directive and the nominated 3915 // namespace. [Note: in this context, "contains" means "contains 3916 // directly or indirectly". ] 3917 3918 // Find enclosing context containing both using-directive and 3919 // nominated namespace. 3920 NamespaceDecl *NS = getNamespaceDecl(Named); 3921 DeclContext *CommonAncestor = cast<DeclContext>(NS); 3922 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 3923 CommonAncestor = CommonAncestor->getParent(); 3924 3925 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 3926 SS.getWithLocInContext(Context), 3927 IdentLoc, Named, CommonAncestor); 3928 3929 if (IsUsingDirectiveInToplevelContext(CurContext) && 3930 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) { 3931 Diag(IdentLoc, diag::warn_using_directive_in_header); 3932 } 3933 3934 PushUsingDirective(S, UDir); 3935 } else { 3936 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 3937 } 3938 3939 // FIXME: We ignore attributes for now. 3940 return UDir; 3941} 3942 3943void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 3944 // If scope has associated entity, then using directive is at namespace 3945 // or translation unit scope. We add UsingDirectiveDecls, into 3946 // it's lookup structure. 3947 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 3948 Ctx->addDecl(UDir); 3949 else 3950 // Otherwise it is block-sope. using-directives will affect lookup 3951 // only to the end of scope. 3952 S->PushUsingDirective(UDir); 3953} 3954 3955 3956Decl *Sema::ActOnUsingDeclaration(Scope *S, 3957 AccessSpecifier AS, 3958 bool HasUsingKeyword, 3959 SourceLocation UsingLoc, 3960 CXXScopeSpec &SS, 3961 UnqualifiedId &Name, 3962 AttributeList *AttrList, 3963 bool IsTypeName, 3964 SourceLocation TypenameLoc) { 3965 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 3966 3967 switch (Name.getKind()) { 3968 case UnqualifiedId::IK_Identifier: 3969 case UnqualifiedId::IK_OperatorFunctionId: 3970 case UnqualifiedId::IK_LiteralOperatorId: 3971 case UnqualifiedId::IK_ConversionFunctionId: 3972 break; 3973 3974 case UnqualifiedId::IK_ConstructorName: 3975 case UnqualifiedId::IK_ConstructorTemplateId: 3976 // C++0x inherited constructors. 3977 if (getLangOptions().CPlusPlus0x) break; 3978 3979 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor) 3980 << SS.getRange(); 3981 return 0; 3982 3983 case UnqualifiedId::IK_DestructorName: 3984 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor) 3985 << SS.getRange(); 3986 return 0; 3987 3988 case UnqualifiedId::IK_TemplateId: 3989 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id) 3990 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 3991 return 0; 3992 } 3993 3994 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 3995 DeclarationName TargetName = TargetNameInfo.getName(); 3996 if (!TargetName) 3997 return 0; 3998 3999 // Warn about using declarations. 4000 // TODO: store that the declaration was written without 'using' and 4001 // talk about access decls instead of using decls in the 4002 // diagnostics. 4003 if (!HasUsingKeyword) { 4004 UsingLoc = Name.getSourceRange().getBegin(); 4005 4006 Diag(UsingLoc, diag::warn_access_decl_deprecated) 4007 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 4008 } 4009 4010 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 4011 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 4012 return 0; 4013 4014 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 4015 TargetNameInfo, AttrList, 4016 /* IsInstantiation */ false, 4017 IsTypeName, TypenameLoc); 4018 if (UD) 4019 PushOnScopeChains(UD, S, /*AddToContext*/ false); 4020 4021 return UD; 4022} 4023 4024/// \brief Determine whether a using declaration considers the given 4025/// declarations as "equivalent", e.g., if they are redeclarations of 4026/// the same entity or are both typedefs of the same type. 4027static bool 4028IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2, 4029 bool &SuppressRedeclaration) { 4030 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) { 4031 SuppressRedeclaration = false; 4032 return true; 4033 } 4034 4035 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1)) 4036 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) { 4037 SuppressRedeclaration = true; 4038 return Context.hasSameType(TD1->getUnderlyingType(), 4039 TD2->getUnderlyingType()); 4040 } 4041 4042 return false; 4043} 4044 4045 4046/// Determines whether to create a using shadow decl for a particular 4047/// decl, given the set of decls existing prior to this using lookup. 4048bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 4049 const LookupResult &Previous) { 4050 // Diagnose finding a decl which is not from a base class of the 4051 // current class. We do this now because there are cases where this 4052 // function will silently decide not to build a shadow decl, which 4053 // will pre-empt further diagnostics. 4054 // 4055 // We don't need to do this in C++0x because we do the check once on 4056 // the qualifier. 4057 // 4058 // FIXME: diagnose the following if we care enough: 4059 // struct A { int foo; }; 4060 // struct B : A { using A::foo; }; 4061 // template <class T> struct C : A {}; 4062 // template <class T> struct D : C<T> { using B::foo; } // <--- 4063 // This is invalid (during instantiation) in C++03 because B::foo 4064 // resolves to the using decl in B, which is not a base class of D<T>. 4065 // We can't diagnose it immediately because C<T> is an unknown 4066 // specialization. The UsingShadowDecl in D<T> then points directly 4067 // to A::foo, which will look well-formed when we instantiate. 4068 // The right solution is to not collapse the shadow-decl chain. 4069 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) { 4070 DeclContext *OrigDC = Orig->getDeclContext(); 4071 4072 // Handle enums and anonymous structs. 4073 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 4074 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 4075 while (OrigRec->isAnonymousStructOrUnion()) 4076 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 4077 4078 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 4079 if (OrigDC == CurContext) { 4080 Diag(Using->getLocation(), 4081 diag::err_using_decl_nested_name_specifier_is_current_class) 4082 << Using->getQualifierLoc().getSourceRange(); 4083 Diag(Orig->getLocation(), diag::note_using_decl_target); 4084 return true; 4085 } 4086 4087 Diag(Using->getQualifierLoc().getBeginLoc(), 4088 diag::err_using_decl_nested_name_specifier_is_not_base_class) 4089 << Using->getQualifier() 4090 << cast<CXXRecordDecl>(CurContext) 4091 << Using->getQualifierLoc().getSourceRange(); 4092 Diag(Orig->getLocation(), diag::note_using_decl_target); 4093 return true; 4094 } 4095 } 4096 4097 if (Previous.empty()) return false; 4098 4099 NamedDecl *Target = Orig; 4100 if (isa<UsingShadowDecl>(Target)) 4101 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 4102 4103 // If the target happens to be one of the previous declarations, we 4104 // don't have a conflict. 4105 // 4106 // FIXME: but we might be increasing its access, in which case we 4107 // should redeclare it. 4108 NamedDecl *NonTag = 0, *Tag = 0; 4109 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 4110 I != E; ++I) { 4111 NamedDecl *D = (*I)->getUnderlyingDecl(); 4112 bool Result; 4113 if (IsEquivalentForUsingDecl(Context, D, Target, Result)) 4114 return Result; 4115 4116 (isa<TagDecl>(D) ? Tag : NonTag) = D; 4117 } 4118 4119 if (Target->isFunctionOrFunctionTemplate()) { 4120 FunctionDecl *FD; 4121 if (isa<FunctionTemplateDecl>(Target)) 4122 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 4123 else 4124 FD = cast<FunctionDecl>(Target); 4125 4126 NamedDecl *OldDecl = 0; 4127 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) { 4128 case Ovl_Overload: 4129 return false; 4130 4131 case Ovl_NonFunction: 4132 Diag(Using->getLocation(), diag::err_using_decl_conflict); 4133 break; 4134 4135 // We found a decl with the exact signature. 4136 case Ovl_Match: 4137 // If we're in a record, we want to hide the target, so we 4138 // return true (without a diagnostic) to tell the caller not to 4139 // build a shadow decl. 4140 if (CurContext->isRecord()) 4141 return true; 4142 4143 // If we're not in a record, this is an error. 4144 Diag(Using->getLocation(), diag::err_using_decl_conflict); 4145 break; 4146 } 4147 4148 Diag(Target->getLocation(), diag::note_using_decl_target); 4149 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 4150 return true; 4151 } 4152 4153 // Target is not a function. 4154 4155 if (isa<TagDecl>(Target)) { 4156 // No conflict between a tag and a non-tag. 4157 if (!Tag) return false; 4158 4159 Diag(Using->getLocation(), diag::err_using_decl_conflict); 4160 Diag(Target->getLocation(), diag::note_using_decl_target); 4161 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 4162 return true; 4163 } 4164 4165 // No conflict between a tag and a non-tag. 4166 if (!NonTag) return false; 4167 4168 Diag(Using->getLocation(), diag::err_using_decl_conflict); 4169 Diag(Target->getLocation(), diag::note_using_decl_target); 4170 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 4171 return true; 4172} 4173 4174/// Builds a shadow declaration corresponding to a 'using' declaration. 4175UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 4176 UsingDecl *UD, 4177 NamedDecl *Orig) { 4178 4179 // If we resolved to another shadow declaration, just coalesce them. 4180 NamedDecl *Target = Orig; 4181 if (isa<UsingShadowDecl>(Target)) { 4182 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 4183 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 4184 } 4185 4186 UsingShadowDecl *Shadow 4187 = UsingShadowDecl::Create(Context, CurContext, 4188 UD->getLocation(), UD, Target); 4189 UD->addShadowDecl(Shadow); 4190 4191 Shadow->setAccess(UD->getAccess()); 4192 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 4193 Shadow->setInvalidDecl(); 4194 4195 if (S) 4196 PushOnScopeChains(Shadow, S); 4197 else 4198 CurContext->addDecl(Shadow); 4199 4200 4201 return Shadow; 4202} 4203 4204/// Hides a using shadow declaration. This is required by the current 4205/// using-decl implementation when a resolvable using declaration in a 4206/// class is followed by a declaration which would hide or override 4207/// one or more of the using decl's targets; for example: 4208/// 4209/// struct Base { void foo(int); }; 4210/// struct Derived : Base { 4211/// using Base::foo; 4212/// void foo(int); 4213/// }; 4214/// 4215/// The governing language is C++03 [namespace.udecl]p12: 4216/// 4217/// When a using-declaration brings names from a base class into a 4218/// derived class scope, member functions in the derived class 4219/// override and/or hide member functions with the same name and 4220/// parameter types in a base class (rather than conflicting). 4221/// 4222/// There are two ways to implement this: 4223/// (1) optimistically create shadow decls when they're not hidden 4224/// by existing declarations, or 4225/// (2) don't create any shadow decls (or at least don't make them 4226/// visible) until we've fully parsed/instantiated the class. 4227/// The problem with (1) is that we might have to retroactively remove 4228/// a shadow decl, which requires several O(n) operations because the 4229/// decl structures are (very reasonably) not designed for removal. 4230/// (2) avoids this but is very fiddly and phase-dependent. 4231void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 4232 if (Shadow->getDeclName().getNameKind() == 4233 DeclarationName::CXXConversionFunctionName) 4234 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 4235 4236 // Remove it from the DeclContext... 4237 Shadow->getDeclContext()->removeDecl(Shadow); 4238 4239 // ...and the scope, if applicable... 4240 if (S) { 4241 S->RemoveDecl(Shadow); 4242 IdResolver.RemoveDecl(Shadow); 4243 } 4244 4245 // ...and the using decl. 4246 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 4247 4248 // TODO: complain somehow if Shadow was used. It shouldn't 4249 // be possible for this to happen, because...? 4250} 4251 4252/// Builds a using declaration. 4253/// 4254/// \param IsInstantiation - Whether this call arises from an 4255/// instantiation of an unresolved using declaration. We treat 4256/// the lookup differently for these declarations. 4257NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 4258 SourceLocation UsingLoc, 4259 CXXScopeSpec &SS, 4260 const DeclarationNameInfo &NameInfo, 4261 AttributeList *AttrList, 4262 bool IsInstantiation, 4263 bool IsTypeName, 4264 SourceLocation TypenameLoc) { 4265 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 4266 SourceLocation IdentLoc = NameInfo.getLoc(); 4267 assert(IdentLoc.isValid() && "Invalid TargetName location."); 4268 4269 // FIXME: We ignore attributes for now. 4270 4271 if (SS.isEmpty()) { 4272 Diag(IdentLoc, diag::err_using_requires_qualname); 4273 return 0; 4274 } 4275 4276 // Do the redeclaration lookup in the current scope. 4277 LookupResult Previous(*this, NameInfo, LookupUsingDeclName, 4278 ForRedeclaration); 4279 Previous.setHideTags(false); 4280 if (S) { 4281 LookupName(Previous, S); 4282 4283 // It is really dumb that we have to do this. 4284 LookupResult::Filter F = Previous.makeFilter(); 4285 while (F.hasNext()) { 4286 NamedDecl *D = F.next(); 4287 if (!isDeclInScope(D, CurContext, S)) 4288 F.erase(); 4289 } 4290 F.done(); 4291 } else { 4292 assert(IsInstantiation && "no scope in non-instantiation"); 4293 assert(CurContext->isRecord() && "scope not record in instantiation"); 4294 LookupQualifiedName(Previous, CurContext); 4295 } 4296 4297 // Check for invalid redeclarations. 4298 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 4299 return 0; 4300 4301 // Check for bad qualifiers. 4302 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 4303 return 0; 4304 4305 DeclContext *LookupContext = computeDeclContext(SS); 4306 NamedDecl *D; 4307 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 4308 if (!LookupContext) { 4309 if (IsTypeName) { 4310 // FIXME: not all declaration name kinds are legal here 4311 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 4312 UsingLoc, TypenameLoc, 4313 QualifierLoc, 4314 IdentLoc, NameInfo.getName()); 4315 } else { 4316 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 4317 QualifierLoc, NameInfo); 4318 } 4319 } else { 4320 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 4321 NameInfo, IsTypeName); 4322 } 4323 D->setAccess(AS); 4324 CurContext->addDecl(D); 4325 4326 if (!LookupContext) return D; 4327 UsingDecl *UD = cast<UsingDecl>(D); 4328 4329 if (RequireCompleteDeclContext(SS, LookupContext)) { 4330 UD->setInvalidDecl(); 4331 return UD; 4332 } 4333 4334 // Constructor inheriting using decls get special treatment. 4335 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 4336 if (CheckInheritedConstructorUsingDecl(UD)) 4337 UD->setInvalidDecl(); 4338 return UD; 4339 } 4340 4341 // Otherwise, look up the target name. 4342 4343 LookupResult R(*this, NameInfo, LookupOrdinaryName); 4344 4345 // Unlike most lookups, we don't always want to hide tag 4346 // declarations: tag names are visible through the using declaration 4347 // even if hidden by ordinary names, *except* in a dependent context 4348 // where it's important for the sanity of two-phase lookup. 4349 if (!IsInstantiation) 4350 R.setHideTags(false); 4351 4352 LookupQualifiedName(R, LookupContext); 4353 4354 if (R.empty()) { 4355 Diag(IdentLoc, diag::err_no_member) 4356 << NameInfo.getName() << LookupContext << SS.getRange(); 4357 UD->setInvalidDecl(); 4358 return UD; 4359 } 4360 4361 if (R.isAmbiguous()) { 4362 UD->setInvalidDecl(); 4363 return UD; 4364 } 4365 4366 if (IsTypeName) { 4367 // If we asked for a typename and got a non-type decl, error out. 4368 if (!R.getAsSingle<TypeDecl>()) { 4369 Diag(IdentLoc, diag::err_using_typename_non_type); 4370 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 4371 Diag((*I)->getUnderlyingDecl()->getLocation(), 4372 diag::note_using_decl_target); 4373 UD->setInvalidDecl(); 4374 return UD; 4375 } 4376 } else { 4377 // If we asked for a non-typename and we got a type, error out, 4378 // but only if this is an instantiation of an unresolved using 4379 // decl. Otherwise just silently find the type name. 4380 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 4381 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 4382 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 4383 UD->setInvalidDecl(); 4384 return UD; 4385 } 4386 } 4387 4388 // C++0x N2914 [namespace.udecl]p6: 4389 // A using-declaration shall not name a namespace. 4390 if (R.getAsSingle<NamespaceDecl>()) { 4391 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 4392 << SS.getRange(); 4393 UD->setInvalidDecl(); 4394 return UD; 4395 } 4396 4397 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 4398 if (!CheckUsingShadowDecl(UD, *I, Previous)) 4399 BuildUsingShadowDecl(S, UD, *I); 4400 } 4401 4402 return UD; 4403} 4404 4405/// Additional checks for a using declaration referring to a constructor name. 4406bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) { 4407 if (UD->isTypeName()) { 4408 // FIXME: Cannot specify typename when specifying constructor 4409 return true; 4410 } 4411 4412 const Type *SourceType = UD->getQualifier()->getAsType(); 4413 assert(SourceType && 4414 "Using decl naming constructor doesn't have type in scope spec."); 4415 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 4416 4417 // Check whether the named type is a direct base class. 4418 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified(); 4419 CXXRecordDecl::base_class_iterator BaseIt, BaseE; 4420 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end(); 4421 BaseIt != BaseE; ++BaseIt) { 4422 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified(); 4423 if (CanonicalSourceType == BaseType) 4424 break; 4425 } 4426 4427 if (BaseIt == BaseE) { 4428 // Did not find SourceType in the bases. 4429 Diag(UD->getUsingLocation(), 4430 diag::err_using_decl_constructor_not_in_direct_base) 4431 << UD->getNameInfo().getSourceRange() 4432 << QualType(SourceType, 0) << TargetClass; 4433 return true; 4434 } 4435 4436 BaseIt->setInheritConstructors(); 4437 4438 return false; 4439} 4440 4441/// Checks that the given using declaration is not an invalid 4442/// redeclaration. Note that this is checking only for the using decl 4443/// itself, not for any ill-formedness among the UsingShadowDecls. 4444bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 4445 bool isTypeName, 4446 const CXXScopeSpec &SS, 4447 SourceLocation NameLoc, 4448 const LookupResult &Prev) { 4449 // C++03 [namespace.udecl]p8: 4450 // C++0x [namespace.udecl]p10: 4451 // A using-declaration is a declaration and can therefore be used 4452 // repeatedly where (and only where) multiple declarations are 4453 // allowed. 4454 // 4455 // That's in non-member contexts. 4456 if (!CurContext->getRedeclContext()->isRecord()) 4457 return false; 4458 4459 NestedNameSpecifier *Qual 4460 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 4461 4462 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 4463 NamedDecl *D = *I; 4464 4465 bool DTypename; 4466 NestedNameSpecifier *DQual; 4467 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 4468 DTypename = UD->isTypeName(); 4469 DQual = UD->getQualifier(); 4470 } else if (UnresolvedUsingValueDecl *UD 4471 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 4472 DTypename = false; 4473 DQual = UD->getQualifier(); 4474 } else if (UnresolvedUsingTypenameDecl *UD 4475 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 4476 DTypename = true; 4477 DQual = UD->getQualifier(); 4478 } else continue; 4479 4480 // using decls differ if one says 'typename' and the other doesn't. 4481 // FIXME: non-dependent using decls? 4482 if (isTypeName != DTypename) continue; 4483 4484 // using decls differ if they name different scopes (but note that 4485 // template instantiation can cause this check to trigger when it 4486 // didn't before instantiation). 4487 if (Context.getCanonicalNestedNameSpecifier(Qual) != 4488 Context.getCanonicalNestedNameSpecifier(DQual)) 4489 continue; 4490 4491 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 4492 Diag(D->getLocation(), diag::note_using_decl) << 1; 4493 return true; 4494 } 4495 4496 return false; 4497} 4498 4499 4500/// Checks that the given nested-name qualifier used in a using decl 4501/// in the current context is appropriately related to the current 4502/// scope. If an error is found, diagnoses it and returns true. 4503bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 4504 const CXXScopeSpec &SS, 4505 SourceLocation NameLoc) { 4506 DeclContext *NamedContext = computeDeclContext(SS); 4507 4508 if (!CurContext->isRecord()) { 4509 // C++03 [namespace.udecl]p3: 4510 // C++0x [namespace.udecl]p8: 4511 // A using-declaration for a class member shall be a member-declaration. 4512 4513 // If we weren't able to compute a valid scope, it must be a 4514 // dependent class scope. 4515 if (!NamedContext || NamedContext->isRecord()) { 4516 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 4517 << SS.getRange(); 4518 return true; 4519 } 4520 4521 // Otherwise, everything is known to be fine. 4522 return false; 4523 } 4524 4525 // The current scope is a record. 4526 4527 // If the named context is dependent, we can't decide much. 4528 if (!NamedContext) { 4529 // FIXME: in C++0x, we can diagnose if we can prove that the 4530 // nested-name-specifier does not refer to a base class, which is 4531 // still possible in some cases. 4532 4533 // Otherwise we have to conservatively report that things might be 4534 // okay. 4535 return false; 4536 } 4537 4538 if (!NamedContext->isRecord()) { 4539 // Ideally this would point at the last name in the specifier, 4540 // but we don't have that level of source info. 4541 Diag(SS.getRange().getBegin(), 4542 diag::err_using_decl_nested_name_specifier_is_not_class) 4543 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 4544 return true; 4545 } 4546 4547 if (!NamedContext->isDependentContext() && 4548 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 4549 return true; 4550 4551 if (getLangOptions().CPlusPlus0x) { 4552 // C++0x [namespace.udecl]p3: 4553 // In a using-declaration used as a member-declaration, the 4554 // nested-name-specifier shall name a base class of the class 4555 // being defined. 4556 4557 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 4558 cast<CXXRecordDecl>(NamedContext))) { 4559 if (CurContext == NamedContext) { 4560 Diag(NameLoc, 4561 diag::err_using_decl_nested_name_specifier_is_current_class) 4562 << SS.getRange(); 4563 return true; 4564 } 4565 4566 Diag(SS.getRange().getBegin(), 4567 diag::err_using_decl_nested_name_specifier_is_not_base_class) 4568 << (NestedNameSpecifier*) SS.getScopeRep() 4569 << cast<CXXRecordDecl>(CurContext) 4570 << SS.getRange(); 4571 return true; 4572 } 4573 4574 return false; 4575 } 4576 4577 // C++03 [namespace.udecl]p4: 4578 // A using-declaration used as a member-declaration shall refer 4579 // to a member of a base class of the class being defined [etc.]. 4580 4581 // Salient point: SS doesn't have to name a base class as long as 4582 // lookup only finds members from base classes. Therefore we can 4583 // diagnose here only if we can prove that that can't happen, 4584 // i.e. if the class hierarchies provably don't intersect. 4585 4586 // TODO: it would be nice if "definitely valid" results were cached 4587 // in the UsingDecl and UsingShadowDecl so that these checks didn't 4588 // need to be repeated. 4589 4590 struct UserData { 4591 llvm::DenseSet<const CXXRecordDecl*> Bases; 4592 4593 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 4594 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 4595 Data->Bases.insert(Base); 4596 return true; 4597 } 4598 4599 bool hasDependentBases(const CXXRecordDecl *Class) { 4600 return !Class->forallBases(collect, this); 4601 } 4602 4603 /// Returns true if the base is dependent or is one of the 4604 /// accumulated base classes. 4605 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 4606 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 4607 return !Data->Bases.count(Base); 4608 } 4609 4610 bool mightShareBases(const CXXRecordDecl *Class) { 4611 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 4612 } 4613 }; 4614 4615 UserData Data; 4616 4617 // Returns false if we find a dependent base. 4618 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 4619 return false; 4620 4621 // Returns false if the class has a dependent base or if it or one 4622 // of its bases is present in the base set of the current context. 4623 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 4624 return false; 4625 4626 Diag(SS.getRange().getBegin(), 4627 diag::err_using_decl_nested_name_specifier_is_not_base_class) 4628 << (NestedNameSpecifier*) SS.getScopeRep() 4629 << cast<CXXRecordDecl>(CurContext) 4630 << SS.getRange(); 4631 4632 return true; 4633} 4634 4635Decl *Sema::ActOnNamespaceAliasDef(Scope *S, 4636 SourceLocation NamespaceLoc, 4637 SourceLocation AliasLoc, 4638 IdentifierInfo *Alias, 4639 CXXScopeSpec &SS, 4640 SourceLocation IdentLoc, 4641 IdentifierInfo *Ident) { 4642 4643 // Lookup the namespace name. 4644 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 4645 LookupParsedName(R, S, &SS); 4646 4647 // Check if we have a previous declaration with the same name. 4648 NamedDecl *PrevDecl 4649 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 4650 ForRedeclaration); 4651 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 4652 PrevDecl = 0; 4653 4654 if (PrevDecl) { 4655 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 4656 // We already have an alias with the same name that points to the same 4657 // namespace, so don't create a new one. 4658 // FIXME: At some point, we'll want to create the (redundant) 4659 // declaration to maintain better source information. 4660 if (!R.isAmbiguous() && !R.empty() && 4661 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 4662 return 0; 4663 } 4664 4665 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 4666 diag::err_redefinition_different_kind; 4667 Diag(AliasLoc, DiagID) << Alias; 4668 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 4669 return 0; 4670 } 4671 4672 if (R.isAmbiguous()) 4673 return 0; 4674 4675 if (R.empty()) { 4676 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false, 4677 CTC_NoKeywords, 0)) { 4678 if (R.getAsSingle<NamespaceDecl>() || 4679 R.getAsSingle<NamespaceAliasDecl>()) { 4680 if (DeclContext *DC = computeDeclContext(SS, false)) 4681 Diag(IdentLoc, diag::err_using_directive_member_suggest) 4682 << Ident << DC << Corrected << SS.getRange() 4683 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 4684 else 4685 Diag(IdentLoc, diag::err_using_directive_suggest) 4686 << Ident << Corrected 4687 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString()); 4688 4689 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here) 4690 << Corrected; 4691 4692 Ident = Corrected.getAsIdentifierInfo(); 4693 } else { 4694 R.clear(); 4695 R.setLookupName(Ident); 4696 } 4697 } 4698 4699 if (R.empty()) { 4700 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 4701 return 0; 4702 } 4703 } 4704 4705 NamespaceAliasDecl *AliasDecl = 4706 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 4707 Alias, SS.getWithLocInContext(Context), 4708 IdentLoc, R.getFoundDecl()); 4709 4710 PushOnScopeChains(AliasDecl, S); 4711 return AliasDecl; 4712} 4713 4714namespace { 4715 /// \brief Scoped object used to handle the state changes required in Sema 4716 /// to implicitly define the body of a C++ member function; 4717 class ImplicitlyDefinedFunctionScope { 4718 Sema &S; 4719 Sema::ContextRAII SavedContext; 4720 4721 public: 4722 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method) 4723 : S(S), SavedContext(S, Method) 4724 { 4725 S.PushFunctionScope(); 4726 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 4727 } 4728 4729 ~ImplicitlyDefinedFunctionScope() { 4730 S.PopExpressionEvaluationContext(); 4731 S.PopFunctionOrBlockScope(); 4732 } 4733 }; 4734} 4735 4736static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self, 4737 CXXRecordDecl *D) { 4738 ASTContext &Context = Self.Context; 4739 QualType ClassType = Context.getTypeDeclType(D); 4740 DeclarationName ConstructorName 4741 = Context.DeclarationNames.getCXXConstructorName( 4742 Context.getCanonicalType(ClassType.getUnqualifiedType())); 4743 4744 DeclContext::lookup_const_iterator Con, ConEnd; 4745 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName); 4746 Con != ConEnd; ++Con) { 4747 // FIXME: In C++0x, a constructor template can be a default constructor. 4748 if (isa<FunctionTemplateDecl>(*Con)) 4749 continue; 4750 4751 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 4752 if (Constructor->isDefaultConstructor()) 4753 return Constructor; 4754 } 4755 return 0; 4756} 4757 4758CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 4759 CXXRecordDecl *ClassDecl) { 4760 // C++ [class.ctor]p5: 4761 // A default constructor for a class X is a constructor of class X 4762 // that can be called without an argument. If there is no 4763 // user-declared constructor for class X, a default constructor is 4764 // implicitly declared. An implicitly-declared default constructor 4765 // is an inline public member of its class. 4766 assert(!ClassDecl->hasUserDeclaredConstructor() && 4767 "Should not build implicit default constructor!"); 4768 4769 // C++ [except.spec]p14: 4770 // An implicitly declared special member function (Clause 12) shall have an 4771 // exception-specification. [...] 4772 ImplicitExceptionSpecification ExceptSpec(Context); 4773 4774 // Direct base-class constructors. 4775 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 4776 BEnd = ClassDecl->bases_end(); 4777 B != BEnd; ++B) { 4778 if (B->isVirtual()) // Handled below. 4779 continue; 4780 4781 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 4782 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4783 if (!BaseClassDecl->hasDeclaredDefaultConstructor()) 4784 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl)); 4785 else if (CXXConstructorDecl *Constructor 4786 = getDefaultConstructorUnsafe(*this, BaseClassDecl)) 4787 ExceptSpec.CalledDecl(Constructor); 4788 } 4789 } 4790 4791 // Virtual base-class constructors. 4792 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 4793 BEnd = ClassDecl->vbases_end(); 4794 B != BEnd; ++B) { 4795 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) { 4796 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 4797 if (!BaseClassDecl->hasDeclaredDefaultConstructor()) 4798 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl)); 4799 else if (CXXConstructorDecl *Constructor 4800 = getDefaultConstructorUnsafe(*this, BaseClassDecl)) 4801 ExceptSpec.CalledDecl(Constructor); 4802 } 4803 } 4804 4805 // Field constructors. 4806 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 4807 FEnd = ClassDecl->field_end(); 4808 F != FEnd; ++F) { 4809 if (const RecordType *RecordTy 4810 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) { 4811 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4812 if (!FieldClassDecl->hasDeclaredDefaultConstructor()) 4813 ExceptSpec.CalledDecl( 4814 DeclareImplicitDefaultConstructor(FieldClassDecl)); 4815 else if (CXXConstructorDecl *Constructor 4816 = getDefaultConstructorUnsafe(*this, FieldClassDecl)) 4817 ExceptSpec.CalledDecl(Constructor); 4818 } 4819 } 4820 4821 FunctionProtoType::ExtProtoInfo EPI; 4822 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType(); 4823 EPI.NumExceptions = ExceptSpec.size(); 4824 EPI.Exceptions = ExceptSpec.data(); 4825 4826 // Create the actual constructor declaration. 4827 CanQualType ClassType 4828 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 4829 SourceLocation ClassLoc = ClassDecl->getLocation(); 4830 DeclarationName Name 4831 = Context.DeclarationNames.getCXXConstructorName(ClassType); 4832 DeclarationNameInfo NameInfo(Name, ClassLoc); 4833 CXXConstructorDecl *DefaultCon 4834 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 4835 Context.getFunctionType(Context.VoidTy, 4836 0, 0, EPI), 4837 /*TInfo=*/0, 4838 /*isExplicit=*/false, 4839 /*isInline=*/true, 4840 /*isImplicitlyDeclared=*/true); 4841 DefaultCon->setAccess(AS_public); 4842 DefaultCon->setImplicit(); 4843 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor()); 4844 4845 // Note that we have declared this constructor. 4846 ++ASTContext::NumImplicitDefaultConstructorsDeclared; 4847 4848 if (Scope *S = getScopeForContext(ClassDecl)) 4849 PushOnScopeChains(DefaultCon, S, false); 4850 ClassDecl->addDecl(DefaultCon); 4851 4852 return DefaultCon; 4853} 4854 4855void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 4856 CXXConstructorDecl *Constructor) { 4857 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() && 4858 !Constructor->isUsed(false)) && 4859 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 4860 4861 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4862 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 4863 4864 ImplicitlyDefinedFunctionScope Scope(*this, Constructor); 4865 DiagnosticErrorTrap Trap(Diags); 4866 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) || 4867 Trap.hasErrorOccurred()) { 4868 Diag(CurrentLocation, diag::note_member_synthesized_at) 4869 << CXXConstructor << Context.getTagDeclType(ClassDecl); 4870 Constructor->setInvalidDecl(); 4871 return; 4872 } 4873 4874 SourceLocation Loc = Constructor->getLocation(); 4875 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 4876 4877 Constructor->setUsed(); 4878 MarkVTableUsed(CurrentLocation, ClassDecl); 4879} 4880 4881void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) { 4882 // We start with an initial pass over the base classes to collect those that 4883 // inherit constructors from. If there are none, we can forgo all further 4884 // processing. 4885 typedef llvm::SmallVector<const RecordType *, 4> BasesVector; 4886 BasesVector BasesToInheritFrom; 4887 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(), 4888 BaseE = ClassDecl->bases_end(); 4889 BaseIt != BaseE; ++BaseIt) { 4890 if (BaseIt->getInheritConstructors()) { 4891 QualType Base = BaseIt->getType(); 4892 if (Base->isDependentType()) { 4893 // If we inherit constructors from anything that is dependent, just 4894 // abort processing altogether. We'll get another chance for the 4895 // instantiations. 4896 return; 4897 } 4898 BasesToInheritFrom.push_back(Base->castAs<RecordType>()); 4899 } 4900 } 4901 if (BasesToInheritFrom.empty()) 4902 return; 4903 4904 // Now collect the constructors that we already have in the current class. 4905 // Those take precedence over inherited constructors. 4906 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...] 4907 // unless there is a user-declared constructor with the same signature in 4908 // the class where the using-declaration appears. 4909 llvm::SmallSet<const Type *, 8> ExistingConstructors; 4910 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(), 4911 CtorE = ClassDecl->ctor_end(); 4912 CtorIt != CtorE; ++CtorIt) { 4913 ExistingConstructors.insert( 4914 Context.getCanonicalType(CtorIt->getType()).getTypePtr()); 4915 } 4916 4917 Scope *S = getScopeForContext(ClassDecl); 4918 DeclarationName CreatedCtorName = 4919 Context.DeclarationNames.getCXXConstructorName( 4920 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified()); 4921 4922 // Now comes the true work. 4923 // First, we keep a map from constructor types to the base that introduced 4924 // them. Needed for finding conflicting constructors. We also keep the 4925 // actually inserted declarations in there, for pretty diagnostics. 4926 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo; 4927 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap; 4928 ConstructorToSourceMap InheritedConstructors; 4929 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(), 4930 BaseE = BasesToInheritFrom.end(); 4931 BaseIt != BaseE; ++BaseIt) { 4932 const RecordType *Base = *BaseIt; 4933 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified(); 4934 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl()); 4935 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(), 4936 CtorE = BaseDecl->ctor_end(); 4937 CtorIt != CtorE; ++CtorIt) { 4938 // Find the using declaration for inheriting this base's constructors. 4939 DeclarationName Name = 4940 Context.DeclarationNames.getCXXConstructorName(CanonicalBase); 4941 UsingDecl *UD = dyn_cast_or_null<UsingDecl>( 4942 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName)); 4943 SourceLocation UsingLoc = UD ? UD->getLocation() : 4944 ClassDecl->getLocation(); 4945 4946 // C++0x [class.inhctor]p1: The candidate set of inherited constructors 4947 // from the class X named in the using-declaration consists of actual 4948 // constructors and notional constructors that result from the 4949 // transformation of defaulted parameters as follows: 4950 // - all non-template default constructors of X, and 4951 // - for each non-template constructor of X that has at least one 4952 // parameter with a default argument, the set of constructors that 4953 // results from omitting any ellipsis parameter specification and 4954 // successively omitting parameters with a default argument from the 4955 // end of the parameter-type-list. 4956 CXXConstructorDecl *BaseCtor = *CtorIt; 4957 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor(); 4958 const FunctionProtoType *BaseCtorType = 4959 BaseCtor->getType()->getAs<FunctionProtoType>(); 4960 4961 for (unsigned params = BaseCtor->getMinRequiredArguments(), 4962 maxParams = BaseCtor->getNumParams(); 4963 params <= maxParams; ++params) { 4964 // Skip default constructors. They're never inherited. 4965 if (params == 0) 4966 continue; 4967 // Skip copy and move constructors for the same reason. 4968 if (CanBeCopyOrMove && params == 1) 4969 continue; 4970 4971 // Build up a function type for this particular constructor. 4972 // FIXME: The working paper does not consider that the exception spec 4973 // for the inheriting constructor might be larger than that of the 4974 // source. This code doesn't yet, either. 4975 const Type *NewCtorType; 4976 if (params == maxParams) 4977 NewCtorType = BaseCtorType; 4978 else { 4979 llvm::SmallVector<QualType, 16> Args; 4980 for (unsigned i = 0; i < params; ++i) { 4981 Args.push_back(BaseCtorType->getArgType(i)); 4982 } 4983 FunctionProtoType::ExtProtoInfo ExtInfo = 4984 BaseCtorType->getExtProtoInfo(); 4985 ExtInfo.Variadic = false; 4986 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(), 4987 Args.data(), params, ExtInfo) 4988 .getTypePtr(); 4989 } 4990 const Type *CanonicalNewCtorType = 4991 Context.getCanonicalType(NewCtorType); 4992 4993 // Now that we have the type, first check if the class already has a 4994 // constructor with this signature. 4995 if (ExistingConstructors.count(CanonicalNewCtorType)) 4996 continue; 4997 4998 // Then we check if we have already declared an inherited constructor 4999 // with this signature. 5000 std::pair<ConstructorToSourceMap::iterator, bool> result = 5001 InheritedConstructors.insert(std::make_pair( 5002 CanonicalNewCtorType, 5003 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0))); 5004 if (!result.second) { 5005 // Already in the map. If it came from a different class, that's an 5006 // error. Not if it's from the same. 5007 CanQualType PreviousBase = result.first->second.first; 5008 if (CanonicalBase != PreviousBase) { 5009 const CXXConstructorDecl *PrevCtor = result.first->second.second; 5010 const CXXConstructorDecl *PrevBaseCtor = 5011 PrevCtor->getInheritedConstructor(); 5012 assert(PrevBaseCtor && "Conflicting constructor was not inherited"); 5013 5014 Diag(UsingLoc, diag::err_using_decl_constructor_conflict); 5015 Diag(BaseCtor->getLocation(), 5016 diag::note_using_decl_constructor_conflict_current_ctor); 5017 Diag(PrevBaseCtor->getLocation(), 5018 diag::note_using_decl_constructor_conflict_previous_ctor); 5019 Diag(PrevCtor->getLocation(), 5020 diag::note_using_decl_constructor_conflict_previous_using); 5021 } 5022 continue; 5023 } 5024 5025 // OK, we're there, now add the constructor. 5026 // C++0x [class.inhctor]p8: [...] that would be performed by a 5027 // user-writtern inline constructor [...] 5028 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc); 5029 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create( 5030 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0), 5031 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true, 5032 /*ImplicitlyDeclared=*/true); 5033 NewCtor->setAccess(BaseCtor->getAccess()); 5034 5035 // Build up the parameter decls and add them. 5036 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls; 5037 for (unsigned i = 0; i < params; ++i) { 5038 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor, 5039 UsingLoc, UsingLoc, 5040 /*IdentifierInfo=*/0, 5041 BaseCtorType->getArgType(i), 5042 /*TInfo=*/0, SC_None, 5043 SC_None, /*DefaultArg=*/0)); 5044 } 5045 NewCtor->setParams(ParamDecls.data(), ParamDecls.size()); 5046 NewCtor->setInheritedConstructor(BaseCtor); 5047 5048 PushOnScopeChains(NewCtor, S, false); 5049 ClassDecl->addDecl(NewCtor); 5050 result.first->second.second = NewCtor; 5051 } 5052 } 5053 } 5054} 5055 5056CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 5057 // C++ [class.dtor]p2: 5058 // If a class has no user-declared destructor, a destructor is 5059 // declared implicitly. An implicitly-declared destructor is an 5060 // inline public member of its class. 5061 5062 // C++ [except.spec]p14: 5063 // An implicitly declared special member function (Clause 12) shall have 5064 // an exception-specification. 5065 ImplicitExceptionSpecification ExceptSpec(Context); 5066 5067 // Direct base-class destructors. 5068 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(), 5069 BEnd = ClassDecl->bases_end(); 5070 B != BEnd; ++B) { 5071 if (B->isVirtual()) // Handled below. 5072 continue; 5073 5074 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 5075 ExceptSpec.CalledDecl( 5076 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 5077 } 5078 5079 // Virtual base-class destructors. 5080 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(), 5081 BEnd = ClassDecl->vbases_end(); 5082 B != BEnd; ++B) { 5083 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) 5084 ExceptSpec.CalledDecl( 5085 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl()))); 5086 } 5087 5088 // Field destructors. 5089 for (RecordDecl::field_iterator F = ClassDecl->field_begin(), 5090 FEnd = ClassDecl->field_end(); 5091 F != FEnd; ++F) { 5092 if (const RecordType *RecordTy 5093 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) 5094 ExceptSpec.CalledDecl( 5095 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl()))); 5096 } 5097 5098 // Create the actual destructor declaration. 5099 FunctionProtoType::ExtProtoInfo EPI; 5100 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType(); 5101 EPI.NumExceptions = ExceptSpec.size(); 5102 EPI.Exceptions = ExceptSpec.data(); 5103 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI); 5104 5105 CanQualType ClassType 5106 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 5107 SourceLocation ClassLoc = ClassDecl->getLocation(); 5108 DeclarationName Name 5109 = Context.DeclarationNames.getCXXDestructorName(ClassType); 5110 DeclarationNameInfo NameInfo(Name, ClassLoc); 5111 CXXDestructorDecl *Destructor 5112 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0, 5113 /*isInline=*/true, 5114 /*isImplicitlyDeclared=*/true); 5115 Destructor->setAccess(AS_public); 5116 Destructor->setImplicit(); 5117 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 5118 5119 // Note that we have declared this destructor. 5120 ++ASTContext::NumImplicitDestructorsDeclared; 5121 5122 // Introduce this destructor into its scope. 5123 if (Scope *S = getScopeForContext(ClassDecl)) 5124 PushOnScopeChains(Destructor, S, false); 5125 ClassDecl->addDecl(Destructor); 5126 5127 // This could be uniqued if it ever proves significant. 5128 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty)); 5129 5130 AddOverriddenMethods(ClassDecl, Destructor); 5131 5132 return Destructor; 5133} 5134 5135void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 5136 CXXDestructorDecl *Destructor) { 5137 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) && 5138 "DefineImplicitDestructor - call it for implicit default dtor"); 5139 CXXRecordDecl *ClassDecl = Destructor->getParent(); 5140 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 5141 5142 if (Destructor->isInvalidDecl()) 5143 return; 5144 5145 ImplicitlyDefinedFunctionScope Scope(*this, Destructor); 5146 5147 DiagnosticErrorTrap Trap(Diags); 5148 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 5149 Destructor->getParent()); 5150 5151 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 5152 Diag(CurrentLocation, diag::note_member_synthesized_at) 5153 << CXXDestructor << Context.getTagDeclType(ClassDecl); 5154 5155 Destructor->setInvalidDecl(); 5156 return; 5157 } 5158 5159 SourceLocation Loc = Destructor->getLocation(); 5160 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc)); 5161 5162 Destructor->setUsed(); 5163 MarkVTableUsed(CurrentLocation, ClassDecl); 5164} 5165 5166/// \brief Builds a statement that copies the given entity from \p From to 5167/// \c To. 5168/// 5169/// This routine is used to copy the members of a class with an 5170/// implicitly-declared copy assignment operator. When the entities being 5171/// copied are arrays, this routine builds for loops to copy them. 5172/// 5173/// \param S The Sema object used for type-checking. 5174/// 5175/// \param Loc The location where the implicit copy is being generated. 5176/// 5177/// \param T The type of the expressions being copied. Both expressions must 5178/// have this type. 5179/// 5180/// \param To The expression we are copying to. 5181/// 5182/// \param From The expression we are copying from. 5183/// 5184/// \param CopyingBaseSubobject Whether we're copying a base subobject. 5185/// Otherwise, it's a non-static member subobject. 5186/// 5187/// \param Depth Internal parameter recording the depth of the recursion. 5188/// 5189/// \returns A statement or a loop that copies the expressions. 5190static StmtResult 5191BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 5192 Expr *To, Expr *From, 5193 bool CopyingBaseSubobject, unsigned Depth = 0) { 5194 // C++0x [class.copy]p30: 5195 // Each subobject is assigned in the manner appropriate to its type: 5196 // 5197 // - if the subobject is of class type, the copy assignment operator 5198 // for the class is used (as if by explicit qualification; that is, 5199 // ignoring any possible virtual overriding functions in more derived 5200 // classes); 5201 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 5202 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 5203 5204 // Look for operator=. 5205 DeclarationName Name 5206 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 5207 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 5208 S.LookupQualifiedName(OpLookup, ClassDecl, false); 5209 5210 // Filter out any result that isn't a copy-assignment operator. 5211 LookupResult::Filter F = OpLookup.makeFilter(); 5212 while (F.hasNext()) { 5213 NamedDecl *D = F.next(); 5214 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 5215 if (Method->isCopyAssignmentOperator()) 5216 continue; 5217 5218 F.erase(); 5219 } 5220 F.done(); 5221 5222 // Suppress the protected check (C++ [class.protected]) for each of the 5223 // assignment operators we found. This strange dance is required when 5224 // we're assigning via a base classes's copy-assignment operator. To 5225 // ensure that we're getting the right base class subobject (without 5226 // ambiguities), we need to cast "this" to that subobject type; to 5227 // ensure that we don't go through the virtual call mechanism, we need 5228 // to qualify the operator= name with the base class (see below). However, 5229 // this means that if the base class has a protected copy assignment 5230 // operator, the protected member access check will fail. So, we 5231 // rewrite "protected" access to "public" access in this case, since we 5232 // know by construction that we're calling from a derived class. 5233 if (CopyingBaseSubobject) { 5234 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 5235 L != LEnd; ++L) { 5236 if (L.getAccess() == AS_protected) 5237 L.setAccess(AS_public); 5238 } 5239 } 5240 5241 // Create the nested-name-specifier that will be used to qualify the 5242 // reference to operator=; this is required to suppress the virtual 5243 // call mechanism. 5244 CXXScopeSpec SS; 5245 SS.MakeTrivial(S.Context, 5246 NestedNameSpecifier::Create(S.Context, 0, false, 5247 T.getTypePtr()), 5248 Loc); 5249 5250 // Create the reference to operator=. 5251 ExprResult OpEqualRef 5252 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS, 5253 /*FirstQualifierInScope=*/0, OpLookup, 5254 /*TemplateArgs=*/0, 5255 /*SuppressQualifierCheck=*/true); 5256 if (OpEqualRef.isInvalid()) 5257 return StmtError(); 5258 5259 // Build the call to the assignment operator. 5260 5261 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 5262 OpEqualRef.takeAs<Expr>(), 5263 Loc, &From, 1, Loc); 5264 if (Call.isInvalid()) 5265 return StmtError(); 5266 5267 return S.Owned(Call.takeAs<Stmt>()); 5268 } 5269 5270 // - if the subobject is of scalar type, the built-in assignment 5271 // operator is used. 5272 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 5273 if (!ArrayTy) { 5274 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From); 5275 if (Assignment.isInvalid()) 5276 return StmtError(); 5277 5278 return S.Owned(Assignment.takeAs<Stmt>()); 5279 } 5280 5281 // - if the subobject is an array, each element is assigned, in the 5282 // manner appropriate to the element type; 5283 5284 // Construct a loop over the array bounds, e.g., 5285 // 5286 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 5287 // 5288 // that will copy each of the array elements. 5289 QualType SizeType = S.Context.getSizeType(); 5290 5291 // Create the iteration variable. 5292 IdentifierInfo *IterationVarName = 0; 5293 { 5294 llvm::SmallString<8> Str; 5295 llvm::raw_svector_ostream OS(Str); 5296 OS << "__i" << Depth; 5297 IterationVarName = &S.Context.Idents.get(OS.str()); 5298 } 5299 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 5300 IterationVarName, SizeType, 5301 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 5302 SC_None, SC_None); 5303 5304 // Initialize the iteration variable to zero. 5305 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 5306 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 5307 5308 // Create a reference to the iteration variable; we'll use this several 5309 // times throughout. 5310 Expr *IterationVarRef 5311 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take(); 5312 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 5313 5314 // Create the DeclStmt that holds the iteration variable. 5315 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 5316 5317 // Create the comparison against the array bound. 5318 llvm::APInt Upper 5319 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 5320 Expr *Comparison 5321 = new (S.Context) BinaryOperator(IterationVarRef, 5322 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 5323 BO_NE, S.Context.BoolTy, 5324 VK_RValue, OK_Ordinary, Loc); 5325 5326 // Create the pre-increment of the iteration variable. 5327 Expr *Increment 5328 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType, 5329 VK_LValue, OK_Ordinary, Loc); 5330 5331 // Subscript the "from" and "to" expressions with the iteration variable. 5332 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc, 5333 IterationVarRef, Loc)); 5334 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc, 5335 IterationVarRef, Loc)); 5336 5337 // Build the copy for an individual element of the array. 5338 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(), 5339 To, From, CopyingBaseSubobject, 5340 Depth + 1); 5341 if (Copy.isInvalid()) 5342 return StmtError(); 5343 5344 // Construct the loop that copies all elements of this array. 5345 return S.ActOnForStmt(Loc, Loc, InitStmt, 5346 S.MakeFullExpr(Comparison), 5347 0, S.MakeFullExpr(Increment), 5348 Loc, Copy.take()); 5349} 5350 5351/// \brief Determine whether the given class has a copy assignment operator 5352/// that accepts a const-qualified argument. 5353static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) { 5354 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass); 5355 5356 if (!Class->hasDeclaredCopyAssignment()) 5357 S.DeclareImplicitCopyAssignment(Class); 5358 5359 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)); 5360 DeclarationName OpName 5361 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 5362 5363 DeclContext::lookup_const_iterator Op, OpEnd; 5364 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) { 5365 // C++ [class.copy]p9: 5366 // A user-declared copy assignment operator is a non-static non-template 5367 // member function of class X with exactly one parameter of type X, X&, 5368 // const X&, volatile X& or const volatile X&. 5369 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op); 5370 if (!Method) 5371 continue; 5372 5373 if (Method->isStatic()) 5374 continue; 5375 if (Method->getPrimaryTemplate()) 5376 continue; 5377 const FunctionProtoType *FnType = 5378 Method->getType()->getAs<FunctionProtoType>(); 5379 assert(FnType && "Overloaded operator has no prototype."); 5380 // Don't assert on this; an invalid decl might have been left in the AST. 5381 if (FnType->getNumArgs() != 1 || FnType->isVariadic()) 5382 continue; 5383 bool AcceptsConst = true; 5384 QualType ArgType = FnType->getArgType(0); 5385 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){ 5386 ArgType = Ref->getPointeeType(); 5387 // Is it a non-const lvalue reference? 5388 if (!ArgType.isConstQualified()) 5389 AcceptsConst = false; 5390 } 5391 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType)) 5392 continue; 5393 5394 // We have a single argument of type cv X or cv X&, i.e. we've found the 5395 // copy assignment operator. Return whether it accepts const arguments. 5396 return AcceptsConst; 5397 } 5398 assert(Class->isInvalidDecl() && 5399 "No copy assignment operator declared in valid code."); 5400 return false; 5401} 5402 5403CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 5404 // Note: The following rules are largely analoguous to the copy 5405 // constructor rules. Note that virtual bases are not taken into account 5406 // for determining the argument type of the operator. Note also that 5407 // operators taking an object instead of a reference are allowed. 5408 5409 5410 // C++ [class.copy]p10: 5411 // If the class definition does not explicitly declare a copy 5412 // assignment operator, one is declared implicitly. 5413 // The implicitly-defined copy assignment operator for a class X 5414 // will have the form 5415 // 5416 // X& X::operator=(const X&) 5417 // 5418 // if 5419 bool HasConstCopyAssignment = true; 5420 5421 // -- each direct base class B of X has a copy assignment operator 5422 // whose parameter is of type const B&, const volatile B& or B, 5423 // and 5424 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5425 BaseEnd = ClassDecl->bases_end(); 5426 HasConstCopyAssignment && Base != BaseEnd; ++Base) { 5427 assert(!Base->getType()->isDependentType() && 5428 "Cannot generate implicit members for class with dependent bases."); 5429 const CXXRecordDecl *BaseClassDecl 5430 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5431 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl); 5432 } 5433 5434 // -- for all the nonstatic data members of X that are of a class 5435 // type M (or array thereof), each such class type has a copy 5436 // assignment operator whose parameter is of type const M&, 5437 // const volatile M& or M. 5438 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 5439 FieldEnd = ClassDecl->field_end(); 5440 HasConstCopyAssignment && Field != FieldEnd; 5441 ++Field) { 5442 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 5443 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 5444 const CXXRecordDecl *FieldClassDecl 5445 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 5446 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl); 5447 } 5448 } 5449 5450 // Otherwise, the implicitly declared copy assignment operator will 5451 // have the form 5452 // 5453 // X& X::operator=(X&) 5454 QualType ArgType = Context.getTypeDeclType(ClassDecl); 5455 QualType RetType = Context.getLValueReferenceType(ArgType); 5456 if (HasConstCopyAssignment) 5457 ArgType = ArgType.withConst(); 5458 ArgType = Context.getLValueReferenceType(ArgType); 5459 5460 // C++ [except.spec]p14: 5461 // An implicitly declared special member function (Clause 12) shall have an 5462 // exception-specification. [...] 5463 ImplicitExceptionSpecification ExceptSpec(Context); 5464 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5465 BaseEnd = ClassDecl->bases_end(); 5466 Base != BaseEnd; ++Base) { 5467 CXXRecordDecl *BaseClassDecl 5468 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5469 5470 if (!BaseClassDecl->hasDeclaredCopyAssignment()) 5471 DeclareImplicitCopyAssignment(BaseClassDecl); 5472 5473 if (CXXMethodDecl *CopyAssign 5474 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment)) 5475 ExceptSpec.CalledDecl(CopyAssign); 5476 } 5477 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 5478 FieldEnd = ClassDecl->field_end(); 5479 Field != FieldEnd; 5480 ++Field) { 5481 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 5482 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 5483 CXXRecordDecl *FieldClassDecl 5484 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 5485 5486 if (!FieldClassDecl->hasDeclaredCopyAssignment()) 5487 DeclareImplicitCopyAssignment(FieldClassDecl); 5488 5489 if (CXXMethodDecl *CopyAssign 5490 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment)) 5491 ExceptSpec.CalledDecl(CopyAssign); 5492 } 5493 } 5494 5495 // An implicitly-declared copy assignment operator is an inline public 5496 // member of its class. 5497 FunctionProtoType::ExtProtoInfo EPI; 5498 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType(); 5499 EPI.NumExceptions = ExceptSpec.size(); 5500 EPI.Exceptions = ExceptSpec.data(); 5501 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 5502 SourceLocation ClassLoc = ClassDecl->getLocation(); 5503 DeclarationNameInfo NameInfo(Name, ClassLoc); 5504 CXXMethodDecl *CopyAssignment 5505 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 5506 Context.getFunctionType(RetType, &ArgType, 1, EPI), 5507 /*TInfo=*/0, /*isStatic=*/false, 5508 /*StorageClassAsWritten=*/SC_None, 5509 /*isInline=*/true, 5510 SourceLocation()); 5511 CopyAssignment->setAccess(AS_public); 5512 CopyAssignment->setImplicit(); 5513 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 5514 5515 // Add the parameter to the operator. 5516 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 5517 ClassLoc, ClassLoc, /*Id=*/0, 5518 ArgType, /*TInfo=*/0, 5519 SC_None, 5520 SC_None, 0); 5521 CopyAssignment->setParams(&FromParam, 1); 5522 5523 // Note that we have added this copy-assignment operator. 5524 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 5525 5526 if (Scope *S = getScopeForContext(ClassDecl)) 5527 PushOnScopeChains(CopyAssignment, S, false); 5528 ClassDecl->addDecl(CopyAssignment); 5529 5530 AddOverriddenMethods(ClassDecl, CopyAssignment); 5531 return CopyAssignment; 5532} 5533 5534void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 5535 CXXMethodDecl *CopyAssignOperator) { 5536 assert((CopyAssignOperator->isImplicit() && 5537 CopyAssignOperator->isOverloadedOperator() && 5538 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 5539 !CopyAssignOperator->isUsed(false)) && 5540 "DefineImplicitCopyAssignment called for wrong function"); 5541 5542 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 5543 5544 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 5545 CopyAssignOperator->setInvalidDecl(); 5546 return; 5547 } 5548 5549 CopyAssignOperator->setUsed(); 5550 5551 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator); 5552 DiagnosticErrorTrap Trap(Diags); 5553 5554 // C++0x [class.copy]p30: 5555 // The implicitly-defined or explicitly-defaulted copy assignment operator 5556 // for a non-union class X performs memberwise copy assignment of its 5557 // subobjects. The direct base classes of X are assigned first, in the 5558 // order of their declaration in the base-specifier-list, and then the 5559 // immediate non-static data members of X are assigned, in the order in 5560 // which they were declared in the class definition. 5561 5562 // The statements that form the synthesized function body. 5563 ASTOwningVector<Stmt*> Statements(*this); 5564 5565 // The parameter for the "other" object, which we are copying from. 5566 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 5567 Qualifiers OtherQuals = Other->getType().getQualifiers(); 5568 QualType OtherRefType = Other->getType(); 5569 if (const LValueReferenceType *OtherRef 5570 = OtherRefType->getAs<LValueReferenceType>()) { 5571 OtherRefType = OtherRef->getPointeeType(); 5572 OtherQuals = OtherRefType.getQualifiers(); 5573 } 5574 5575 // Our location for everything implicitly-generated. 5576 SourceLocation Loc = CopyAssignOperator->getLocation(); 5577 5578 // Construct a reference to the "other" object. We'll be using this 5579 // throughout the generated ASTs. 5580 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take(); 5581 assert(OtherRef && "Reference to parameter cannot fail!"); 5582 5583 // Construct the "this" pointer. We'll be using this throughout the generated 5584 // ASTs. 5585 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 5586 assert(This && "Reference to this cannot fail!"); 5587 5588 // Assign base classes. 5589 bool Invalid = false; 5590 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5591 E = ClassDecl->bases_end(); Base != E; ++Base) { 5592 // Form the assignment: 5593 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 5594 QualType BaseType = Base->getType().getUnqualifiedType(); 5595 if (!BaseType->isRecordType()) { 5596 Invalid = true; 5597 continue; 5598 } 5599 5600 CXXCastPath BasePath; 5601 BasePath.push_back(Base); 5602 5603 // Construct the "from" expression, which is an implicit cast to the 5604 // appropriately-qualified base type. 5605 Expr *From = OtherRef; 5606 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 5607 CK_UncheckedDerivedToBase, 5608 VK_LValue, &BasePath).take(); 5609 5610 // Dereference "this". 5611 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 5612 5613 // Implicitly cast "this" to the appropriately-qualified base type. 5614 To = ImpCastExprToType(To.take(), 5615 Context.getCVRQualifiedType(BaseType, 5616 CopyAssignOperator->getTypeQualifiers()), 5617 CK_UncheckedDerivedToBase, 5618 VK_LValue, &BasePath); 5619 5620 // Build the copy. 5621 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType, 5622 To.get(), From, 5623 /*CopyingBaseSubobject=*/true); 5624 if (Copy.isInvalid()) { 5625 Diag(CurrentLocation, diag::note_member_synthesized_at) 5626 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5627 CopyAssignOperator->setInvalidDecl(); 5628 return; 5629 } 5630 5631 // Success! Record the copy. 5632 Statements.push_back(Copy.takeAs<Expr>()); 5633 } 5634 5635 // \brief Reference to the __builtin_memcpy function. 5636 Expr *BuiltinMemCpyRef = 0; 5637 // \brief Reference to the __builtin_objc_memmove_collectable function. 5638 Expr *CollectableMemCpyRef = 0; 5639 5640 // Assign non-static members. 5641 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 5642 FieldEnd = ClassDecl->field_end(); 5643 Field != FieldEnd; ++Field) { 5644 // Check for members of reference type; we can't copy those. 5645 if (Field->getType()->isReferenceType()) { 5646 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 5647 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 5648 Diag(Field->getLocation(), diag::note_declared_at); 5649 Diag(CurrentLocation, diag::note_member_synthesized_at) 5650 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5651 Invalid = true; 5652 continue; 5653 } 5654 5655 // Check for members of const-qualified, non-class type. 5656 QualType BaseType = Context.getBaseElementType(Field->getType()); 5657 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 5658 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 5659 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 5660 Diag(Field->getLocation(), diag::note_declared_at); 5661 Diag(CurrentLocation, diag::note_member_synthesized_at) 5662 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5663 Invalid = true; 5664 continue; 5665 } 5666 5667 QualType FieldType = Field->getType().getNonReferenceType(); 5668 if (FieldType->isIncompleteArrayType()) { 5669 assert(ClassDecl->hasFlexibleArrayMember() && 5670 "Incomplete array type is not valid"); 5671 continue; 5672 } 5673 5674 // Build references to the field in the object we're copying from and to. 5675 CXXScopeSpec SS; // Intentionally empty 5676 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 5677 LookupMemberName); 5678 MemberLookup.addDecl(*Field); 5679 MemberLookup.resolveKind(); 5680 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType, 5681 Loc, /*IsArrow=*/false, 5682 SS, 0, MemberLookup, 0); 5683 ExprResult To = BuildMemberReferenceExpr(This, This->getType(), 5684 Loc, /*IsArrow=*/true, 5685 SS, 0, MemberLookup, 0); 5686 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 5687 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 5688 5689 // If the field should be copied with __builtin_memcpy rather than via 5690 // explicit assignments, do so. This optimization only applies for arrays 5691 // of scalars and arrays of class type with trivial copy-assignment 5692 // operators. 5693 if (FieldType->isArrayType() && 5694 (!BaseType->isRecordType() || 5695 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()) 5696 ->hasTrivialCopyAssignment())) { 5697 // Compute the size of the memory buffer to be copied. 5698 QualType SizeType = Context.getSizeType(); 5699 llvm::APInt Size(Context.getTypeSize(SizeType), 5700 Context.getTypeSizeInChars(BaseType).getQuantity()); 5701 for (const ConstantArrayType *Array 5702 = Context.getAsConstantArrayType(FieldType); 5703 Array; 5704 Array = Context.getAsConstantArrayType(Array->getElementType())) { 5705 llvm::APInt ArraySize 5706 = Array->getSize().zextOrTrunc(Size.getBitWidth()); 5707 Size *= ArraySize; 5708 } 5709 5710 // Take the address of the field references for "from" and "to". 5711 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get()); 5712 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get()); 5713 5714 bool NeedsCollectableMemCpy = 5715 (BaseType->isRecordType() && 5716 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()); 5717 5718 if (NeedsCollectableMemCpy) { 5719 if (!CollectableMemCpyRef) { 5720 // Create a reference to the __builtin_objc_memmove_collectable function. 5721 LookupResult R(*this, 5722 &Context.Idents.get("__builtin_objc_memmove_collectable"), 5723 Loc, LookupOrdinaryName); 5724 LookupName(R, TUScope, true); 5725 5726 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>(); 5727 if (!CollectableMemCpy) { 5728 // Something went horribly wrong earlier, and we will have 5729 // complained about it. 5730 Invalid = true; 5731 continue; 5732 } 5733 5734 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy, 5735 CollectableMemCpy->getType(), 5736 VK_LValue, Loc, 0).take(); 5737 assert(CollectableMemCpyRef && "Builtin reference cannot fail"); 5738 } 5739 } 5740 // Create a reference to the __builtin_memcpy builtin function. 5741 else if (!BuiltinMemCpyRef) { 5742 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 5743 LookupOrdinaryName); 5744 LookupName(R, TUScope, true); 5745 5746 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 5747 if (!BuiltinMemCpy) { 5748 // Something went horribly wrong earlier, and we will have complained 5749 // about it. 5750 Invalid = true; 5751 continue; 5752 } 5753 5754 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 5755 BuiltinMemCpy->getType(), 5756 VK_LValue, Loc, 0).take(); 5757 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 5758 } 5759 5760 ASTOwningVector<Expr*> CallArgs(*this); 5761 CallArgs.push_back(To.takeAs<Expr>()); 5762 CallArgs.push_back(From.takeAs<Expr>()); 5763 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc)); 5764 ExprResult Call = ExprError(); 5765 if (NeedsCollectableMemCpy) 5766 Call = ActOnCallExpr(/*Scope=*/0, 5767 CollectableMemCpyRef, 5768 Loc, move_arg(CallArgs), 5769 Loc); 5770 else 5771 Call = ActOnCallExpr(/*Scope=*/0, 5772 BuiltinMemCpyRef, 5773 Loc, move_arg(CallArgs), 5774 Loc); 5775 5776 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 5777 Statements.push_back(Call.takeAs<Expr>()); 5778 continue; 5779 } 5780 5781 // Build the copy of this field. 5782 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType, 5783 To.get(), From.get(), 5784 /*CopyingBaseSubobject=*/false); 5785 if (Copy.isInvalid()) { 5786 Diag(CurrentLocation, diag::note_member_synthesized_at) 5787 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5788 CopyAssignOperator->setInvalidDecl(); 5789 return; 5790 } 5791 5792 // Success! Record the copy. 5793 Statements.push_back(Copy.takeAs<Stmt>()); 5794 } 5795 5796 if (!Invalid) { 5797 // Add a "return *this;" 5798 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This); 5799 5800 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get()); 5801 if (Return.isInvalid()) 5802 Invalid = true; 5803 else { 5804 Statements.push_back(Return.takeAs<Stmt>()); 5805 5806 if (Trap.hasErrorOccurred()) { 5807 Diag(CurrentLocation, diag::note_member_synthesized_at) 5808 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 5809 Invalid = true; 5810 } 5811 } 5812 } 5813 5814 if (Invalid) { 5815 CopyAssignOperator->setInvalidDecl(); 5816 return; 5817 } 5818 5819 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 5820 /*isStmtExpr=*/false); 5821 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 5822 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 5823} 5824 5825CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 5826 CXXRecordDecl *ClassDecl) { 5827 // C++ [class.copy]p4: 5828 // If the class definition does not explicitly declare a copy 5829 // constructor, one is declared implicitly. 5830 5831 // C++ [class.copy]p5: 5832 // The implicitly-declared copy constructor for a class X will 5833 // have the form 5834 // 5835 // X::X(const X&) 5836 // 5837 // if 5838 bool HasConstCopyConstructor = true; 5839 5840 // -- each direct or virtual base class B of X has a copy 5841 // constructor whose first parameter is of type const B& or 5842 // const volatile B&, and 5843 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5844 BaseEnd = ClassDecl->bases_end(); 5845 HasConstCopyConstructor && Base != BaseEnd; 5846 ++Base) { 5847 // Virtual bases are handled below. 5848 if (Base->isVirtual()) 5849 continue; 5850 5851 CXXRecordDecl *BaseClassDecl 5852 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5853 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 5854 DeclareImplicitCopyConstructor(BaseClassDecl); 5855 5856 HasConstCopyConstructor 5857 = BaseClassDecl->hasConstCopyConstructor(Context); 5858 } 5859 5860 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 5861 BaseEnd = ClassDecl->vbases_end(); 5862 HasConstCopyConstructor && Base != BaseEnd; 5863 ++Base) { 5864 CXXRecordDecl *BaseClassDecl 5865 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5866 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 5867 DeclareImplicitCopyConstructor(BaseClassDecl); 5868 5869 HasConstCopyConstructor 5870 = BaseClassDecl->hasConstCopyConstructor(Context); 5871 } 5872 5873 // -- for all the nonstatic data members of X that are of a 5874 // class type M (or array thereof), each such class type 5875 // has a copy constructor whose first parameter is of type 5876 // const M& or const volatile M&. 5877 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 5878 FieldEnd = ClassDecl->field_end(); 5879 HasConstCopyConstructor && Field != FieldEnd; 5880 ++Field) { 5881 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 5882 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 5883 CXXRecordDecl *FieldClassDecl 5884 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 5885 if (!FieldClassDecl->hasDeclaredCopyConstructor()) 5886 DeclareImplicitCopyConstructor(FieldClassDecl); 5887 5888 HasConstCopyConstructor 5889 = FieldClassDecl->hasConstCopyConstructor(Context); 5890 } 5891 } 5892 5893 // Otherwise, the implicitly declared copy constructor will have 5894 // the form 5895 // 5896 // X::X(X&) 5897 QualType ClassType = Context.getTypeDeclType(ClassDecl); 5898 QualType ArgType = ClassType; 5899 if (HasConstCopyConstructor) 5900 ArgType = ArgType.withConst(); 5901 ArgType = Context.getLValueReferenceType(ArgType); 5902 5903 // C++ [except.spec]p14: 5904 // An implicitly declared special member function (Clause 12) shall have an 5905 // exception-specification. [...] 5906 ImplicitExceptionSpecification ExceptSpec(Context); 5907 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0; 5908 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 5909 BaseEnd = ClassDecl->bases_end(); 5910 Base != BaseEnd; 5911 ++Base) { 5912 // Virtual bases are handled below. 5913 if (Base->isVirtual()) 5914 continue; 5915 5916 CXXRecordDecl *BaseClassDecl 5917 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5918 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 5919 DeclareImplicitCopyConstructor(BaseClassDecl); 5920 5921 if (CXXConstructorDecl *CopyConstructor 5922 = BaseClassDecl->getCopyConstructor(Context, Quals)) 5923 ExceptSpec.CalledDecl(CopyConstructor); 5924 } 5925 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 5926 BaseEnd = ClassDecl->vbases_end(); 5927 Base != BaseEnd; 5928 ++Base) { 5929 CXXRecordDecl *BaseClassDecl 5930 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 5931 if (!BaseClassDecl->hasDeclaredCopyConstructor()) 5932 DeclareImplicitCopyConstructor(BaseClassDecl); 5933 5934 if (CXXConstructorDecl *CopyConstructor 5935 = BaseClassDecl->getCopyConstructor(Context, Quals)) 5936 ExceptSpec.CalledDecl(CopyConstructor); 5937 } 5938 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 5939 FieldEnd = ClassDecl->field_end(); 5940 Field != FieldEnd; 5941 ++Field) { 5942 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 5943 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 5944 CXXRecordDecl *FieldClassDecl 5945 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 5946 if (!FieldClassDecl->hasDeclaredCopyConstructor()) 5947 DeclareImplicitCopyConstructor(FieldClassDecl); 5948 5949 if (CXXConstructorDecl *CopyConstructor 5950 = FieldClassDecl->getCopyConstructor(Context, Quals)) 5951 ExceptSpec.CalledDecl(CopyConstructor); 5952 } 5953 } 5954 5955 // An implicitly-declared copy constructor is an inline public 5956 // member of its class. 5957 FunctionProtoType::ExtProtoInfo EPI; 5958 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType(); 5959 EPI.NumExceptions = ExceptSpec.size(); 5960 EPI.Exceptions = ExceptSpec.data(); 5961 DeclarationName Name 5962 = Context.DeclarationNames.getCXXConstructorName( 5963 Context.getCanonicalType(ClassType)); 5964 SourceLocation ClassLoc = ClassDecl->getLocation(); 5965 DeclarationNameInfo NameInfo(Name, ClassLoc); 5966 CXXConstructorDecl *CopyConstructor 5967 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 5968 Context.getFunctionType(Context.VoidTy, 5969 &ArgType, 1, EPI), 5970 /*TInfo=*/0, 5971 /*isExplicit=*/false, 5972 /*isInline=*/true, 5973 /*isImplicitlyDeclared=*/true); 5974 CopyConstructor->setAccess(AS_public); 5975 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 5976 5977 // Note that we have declared this constructor. 5978 ++ASTContext::NumImplicitCopyConstructorsDeclared; 5979 5980 // Add the parameter to the constructor. 5981 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 5982 ClassLoc, ClassLoc, 5983 /*IdentifierInfo=*/0, 5984 ArgType, /*TInfo=*/0, 5985 SC_None, 5986 SC_None, 0); 5987 CopyConstructor->setParams(&FromParam, 1); 5988 if (Scope *S = getScopeForContext(ClassDecl)) 5989 PushOnScopeChains(CopyConstructor, S, false); 5990 ClassDecl->addDecl(CopyConstructor); 5991 5992 return CopyConstructor; 5993} 5994 5995void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 5996 CXXConstructorDecl *CopyConstructor, 5997 unsigned TypeQuals) { 5998 assert((CopyConstructor->isImplicit() && 5999 CopyConstructor->isCopyConstructor(TypeQuals) && 6000 !CopyConstructor->isUsed(false)) && 6001 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 6002 6003 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 6004 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 6005 6006 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor); 6007 DiagnosticErrorTrap Trap(Diags); 6008 6009 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) || 6010 Trap.hasErrorOccurred()) { 6011 Diag(CurrentLocation, diag::note_member_synthesized_at) 6012 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 6013 CopyConstructor->setInvalidDecl(); 6014 } else { 6015 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 6016 CopyConstructor->getLocation(), 6017 MultiStmtArg(*this, 0, 0), 6018 /*isStmtExpr=*/false) 6019 .takeAs<Stmt>()); 6020 } 6021 6022 CopyConstructor->setUsed(); 6023} 6024 6025ExprResult 6026Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 6027 CXXConstructorDecl *Constructor, 6028 MultiExprArg ExprArgs, 6029 bool RequiresZeroInit, 6030 unsigned ConstructKind, 6031 SourceRange ParenRange) { 6032 bool Elidable = false; 6033 6034 // C++0x [class.copy]p34: 6035 // When certain criteria are met, an implementation is allowed to 6036 // omit the copy/move construction of a class object, even if the 6037 // copy/move constructor and/or destructor for the object have 6038 // side effects. [...] 6039 // - when a temporary class object that has not been bound to a 6040 // reference (12.2) would be copied/moved to a class object 6041 // with the same cv-unqualified type, the copy/move operation 6042 // can be omitted by constructing the temporary object 6043 // directly into the target of the omitted copy/move 6044 if (ConstructKind == CXXConstructExpr::CK_Complete && 6045 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) { 6046 Expr *SubExpr = ((Expr **)ExprArgs.get())[0]; 6047 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent()); 6048 } 6049 6050 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 6051 Elidable, move(ExprArgs), RequiresZeroInit, 6052 ConstructKind, ParenRange); 6053} 6054 6055/// BuildCXXConstructExpr - Creates a complete call to a constructor, 6056/// including handling of its default argument expressions. 6057ExprResult 6058Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 6059 CXXConstructorDecl *Constructor, bool Elidable, 6060 MultiExprArg ExprArgs, 6061 bool RequiresZeroInit, 6062 unsigned ConstructKind, 6063 SourceRange ParenRange) { 6064 unsigned NumExprs = ExprArgs.size(); 6065 Expr **Exprs = (Expr **)ExprArgs.release(); 6066 6067 for (specific_attr_iterator<NonNullAttr> 6068 i = Constructor->specific_attr_begin<NonNullAttr>(), 6069 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) { 6070 const NonNullAttr *NonNull = *i; 6071 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc); 6072 } 6073 6074 MarkDeclarationReferenced(ConstructLoc, Constructor); 6075 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 6076 Constructor, Elidable, Exprs, NumExprs, 6077 RequiresZeroInit, 6078 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 6079 ParenRange)); 6080} 6081 6082bool Sema::InitializeVarWithConstructor(VarDecl *VD, 6083 CXXConstructorDecl *Constructor, 6084 MultiExprArg Exprs) { 6085 // FIXME: Provide the correct paren SourceRange when available. 6086 ExprResult TempResult = 6087 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 6088 move(Exprs), false, CXXConstructExpr::CK_Complete, 6089 SourceRange()); 6090 if (TempResult.isInvalid()) 6091 return true; 6092 6093 Expr *Temp = TempResult.takeAs<Expr>(); 6094 CheckImplicitConversions(Temp, VD->getLocation()); 6095 MarkDeclarationReferenced(VD->getLocation(), Constructor); 6096 Temp = MaybeCreateExprWithCleanups(Temp); 6097 VD->setInit(Temp); 6098 6099 return false; 6100} 6101 6102void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 6103 if (VD->isInvalidDecl()) return; 6104 6105 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 6106 if (ClassDecl->isInvalidDecl()) return; 6107 if (ClassDecl->hasTrivialDestructor()) return; 6108 if (ClassDecl->isDependentContext()) return; 6109 6110 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 6111 MarkDeclarationReferenced(VD->getLocation(), Destructor); 6112 CheckDestructorAccess(VD->getLocation(), Destructor, 6113 PDiag(diag::err_access_dtor_var) 6114 << VD->getDeclName() 6115 << VD->getType()); 6116 6117 if (!VD->hasGlobalStorage()) return; 6118 6119 // Emit warning for non-trivial dtor in global scope (a real global, 6120 // class-static, function-static). 6121 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 6122 6123 // TODO: this should be re-enabled for static locals by !CXAAtExit 6124 if (!VD->isStaticLocal()) 6125 Diag(VD->getLocation(), diag::warn_global_destructor); 6126} 6127 6128/// AddCXXDirectInitializerToDecl - This action is called immediately after 6129/// ActOnDeclarator, when a C++ direct initializer is present. 6130/// e.g: "int x(1);" 6131void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl, 6132 SourceLocation LParenLoc, 6133 MultiExprArg Exprs, 6134 SourceLocation RParenLoc, 6135 bool TypeMayContainAuto) { 6136 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions"); 6137 6138 // If there is no declaration, there was an error parsing it. Just ignore 6139 // the initializer. 6140 if (RealDecl == 0) 6141 return; 6142 6143 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 6144 if (!VDecl) { 6145 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 6146 RealDecl->setInvalidDecl(); 6147 return; 6148 } 6149 6150 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 6151 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) { 6152 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed 6153 if (Exprs.size() > 1) { 6154 Diag(Exprs.get()[1]->getSourceRange().getBegin(), 6155 diag::err_auto_var_init_multiple_expressions) 6156 << VDecl->getDeclName() << VDecl->getType() 6157 << VDecl->getSourceRange(); 6158 RealDecl->setInvalidDecl(); 6159 return; 6160 } 6161 6162 Expr *Init = Exprs.get()[0]; 6163 TypeSourceInfo *DeducedType = 0; 6164 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType)) 6165 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure) 6166 << VDecl->getDeclName() << VDecl->getType() << Init->getType() 6167 << Init->getSourceRange(); 6168 if (!DeducedType) { 6169 RealDecl->setInvalidDecl(); 6170 return; 6171 } 6172 VDecl->setTypeSourceInfo(DeducedType); 6173 VDecl->setType(DeducedType->getType()); 6174 6175 // If this is a redeclaration, check that the type we just deduced matches 6176 // the previously declared type. 6177 if (VarDecl *Old = VDecl->getPreviousDeclaration()) 6178 MergeVarDeclTypes(VDecl, Old); 6179 } 6180 6181 // We will represent direct-initialization similarly to copy-initialization: 6182 // int x(1); -as-> int x = 1; 6183 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 6184 // 6185 // Clients that want to distinguish between the two forms, can check for 6186 // direct initializer using VarDecl::hasCXXDirectInitializer(). 6187 // A major benefit is that clients that don't particularly care about which 6188 // exactly form was it (like the CodeGen) can handle both cases without 6189 // special case code. 6190 6191 // C++ 8.5p11: 6192 // The form of initialization (using parentheses or '=') is generally 6193 // insignificant, but does matter when the entity being initialized has a 6194 // class type. 6195 6196 if (!VDecl->getType()->isDependentType() && 6197 RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 6198 diag::err_typecheck_decl_incomplete_type)) { 6199 VDecl->setInvalidDecl(); 6200 return; 6201 } 6202 6203 // The variable can not have an abstract class type. 6204 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 6205 diag::err_abstract_type_in_decl, 6206 AbstractVariableType)) 6207 VDecl->setInvalidDecl(); 6208 6209 const VarDecl *Def; 6210 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 6211 Diag(VDecl->getLocation(), diag::err_redefinition) 6212 << VDecl->getDeclName(); 6213 Diag(Def->getLocation(), diag::note_previous_definition); 6214 VDecl->setInvalidDecl(); 6215 return; 6216 } 6217 6218 // C++ [class.static.data]p4 6219 // If a static data member is of const integral or const 6220 // enumeration type, its declaration in the class definition can 6221 // specify a constant-initializer which shall be an integral 6222 // constant expression (5.19). In that case, the member can appear 6223 // in integral constant expressions. The member shall still be 6224 // defined in a namespace scope if it is used in the program and the 6225 // namespace scope definition shall not contain an initializer. 6226 // 6227 // We already performed a redefinition check above, but for static 6228 // data members we also need to check whether there was an in-class 6229 // declaration with an initializer. 6230 const VarDecl* PrevInit = 0; 6231 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 6232 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName(); 6233 Diag(PrevInit->getLocation(), diag::note_previous_definition); 6234 return; 6235 } 6236 6237 bool IsDependent = false; 6238 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) { 6239 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) { 6240 VDecl->setInvalidDecl(); 6241 return; 6242 } 6243 6244 if (Exprs.get()[I]->isTypeDependent()) 6245 IsDependent = true; 6246 } 6247 6248 // If either the declaration has a dependent type or if any of the 6249 // expressions is type-dependent, we represent the initialization 6250 // via a ParenListExpr for later use during template instantiation. 6251 if (VDecl->getType()->isDependentType() || IsDependent) { 6252 // Let clients know that initialization was done with a direct initializer. 6253 VDecl->setCXXDirectInitializer(true); 6254 6255 // Store the initialization expressions as a ParenListExpr. 6256 unsigned NumExprs = Exprs.size(); 6257 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc, 6258 (Expr **)Exprs.release(), 6259 NumExprs, RParenLoc)); 6260 return; 6261 } 6262 6263 // Capture the variable that is being initialized and the style of 6264 // initialization. 6265 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 6266 6267 // FIXME: Poor source location information. 6268 InitializationKind Kind 6269 = InitializationKind::CreateDirect(VDecl->getLocation(), 6270 LParenLoc, RParenLoc); 6271 6272 InitializationSequence InitSeq(*this, Entity, Kind, 6273 Exprs.get(), Exprs.size()); 6274 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs)); 6275 if (Result.isInvalid()) { 6276 VDecl->setInvalidDecl(); 6277 return; 6278 } 6279 6280 CheckImplicitConversions(Result.get(), LParenLoc); 6281 6282 Result = MaybeCreateExprWithCleanups(Result); 6283 VDecl->setInit(Result.takeAs<Expr>()); 6284 VDecl->setCXXDirectInitializer(true); 6285 6286 CheckCompleteVariableDeclaration(VDecl); 6287} 6288 6289/// \brief Given a constructor and the set of arguments provided for the 6290/// constructor, convert the arguments and add any required default arguments 6291/// to form a proper call to this constructor. 6292/// 6293/// \returns true if an error occurred, false otherwise. 6294bool 6295Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 6296 MultiExprArg ArgsPtr, 6297 SourceLocation Loc, 6298 ASTOwningVector<Expr*> &ConvertedArgs) { 6299 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 6300 unsigned NumArgs = ArgsPtr.size(); 6301 Expr **Args = (Expr **)ArgsPtr.get(); 6302 6303 const FunctionProtoType *Proto 6304 = Constructor->getType()->getAs<FunctionProtoType>(); 6305 assert(Proto && "Constructor without a prototype?"); 6306 unsigned NumArgsInProto = Proto->getNumArgs(); 6307 6308 // If too few arguments are available, we'll fill in the rest with defaults. 6309 if (NumArgs < NumArgsInProto) 6310 ConvertedArgs.reserve(NumArgsInProto); 6311 else 6312 ConvertedArgs.reserve(NumArgs); 6313 6314 VariadicCallType CallType = 6315 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 6316 llvm::SmallVector<Expr *, 8> AllArgs; 6317 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 6318 Proto, 0, Args, NumArgs, AllArgs, 6319 CallType); 6320 for (unsigned i =0, size = AllArgs.size(); i < size; i++) 6321 ConvertedArgs.push_back(AllArgs[i]); 6322 return Invalid; 6323} 6324 6325static inline bool 6326CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 6327 const FunctionDecl *FnDecl) { 6328 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 6329 if (isa<NamespaceDecl>(DC)) { 6330 return SemaRef.Diag(FnDecl->getLocation(), 6331 diag::err_operator_new_delete_declared_in_namespace) 6332 << FnDecl->getDeclName(); 6333 } 6334 6335 if (isa<TranslationUnitDecl>(DC) && 6336 FnDecl->getStorageClass() == SC_Static) { 6337 return SemaRef.Diag(FnDecl->getLocation(), 6338 diag::err_operator_new_delete_declared_static) 6339 << FnDecl->getDeclName(); 6340 } 6341 6342 return false; 6343} 6344 6345static inline bool 6346CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 6347 CanQualType ExpectedResultType, 6348 CanQualType ExpectedFirstParamType, 6349 unsigned DependentParamTypeDiag, 6350 unsigned InvalidParamTypeDiag) { 6351 QualType ResultType = 6352 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 6353 6354 // Check that the result type is not dependent. 6355 if (ResultType->isDependentType()) 6356 return SemaRef.Diag(FnDecl->getLocation(), 6357 diag::err_operator_new_delete_dependent_result_type) 6358 << FnDecl->getDeclName() << ExpectedResultType; 6359 6360 // Check that the result type is what we expect. 6361 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 6362 return SemaRef.Diag(FnDecl->getLocation(), 6363 diag::err_operator_new_delete_invalid_result_type) 6364 << FnDecl->getDeclName() << ExpectedResultType; 6365 6366 // A function template must have at least 2 parameters. 6367 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 6368 return SemaRef.Diag(FnDecl->getLocation(), 6369 diag::err_operator_new_delete_template_too_few_parameters) 6370 << FnDecl->getDeclName(); 6371 6372 // The function decl must have at least 1 parameter. 6373 if (FnDecl->getNumParams() == 0) 6374 return SemaRef.Diag(FnDecl->getLocation(), 6375 diag::err_operator_new_delete_too_few_parameters) 6376 << FnDecl->getDeclName(); 6377 6378 // Check the the first parameter type is not dependent. 6379 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 6380 if (FirstParamType->isDependentType()) 6381 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 6382 << FnDecl->getDeclName() << ExpectedFirstParamType; 6383 6384 // Check that the first parameter type is what we expect. 6385 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 6386 ExpectedFirstParamType) 6387 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 6388 << FnDecl->getDeclName() << ExpectedFirstParamType; 6389 6390 return false; 6391} 6392 6393static bool 6394CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 6395 // C++ [basic.stc.dynamic.allocation]p1: 6396 // A program is ill-formed if an allocation function is declared in a 6397 // namespace scope other than global scope or declared static in global 6398 // scope. 6399 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 6400 return true; 6401 6402 CanQualType SizeTy = 6403 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 6404 6405 // C++ [basic.stc.dynamic.allocation]p1: 6406 // The return type shall be void*. The first parameter shall have type 6407 // std::size_t. 6408 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 6409 SizeTy, 6410 diag::err_operator_new_dependent_param_type, 6411 diag::err_operator_new_param_type)) 6412 return true; 6413 6414 // C++ [basic.stc.dynamic.allocation]p1: 6415 // The first parameter shall not have an associated default argument. 6416 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 6417 return SemaRef.Diag(FnDecl->getLocation(), 6418 diag::err_operator_new_default_arg) 6419 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 6420 6421 return false; 6422} 6423 6424static bool 6425CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 6426 // C++ [basic.stc.dynamic.deallocation]p1: 6427 // A program is ill-formed if deallocation functions are declared in a 6428 // namespace scope other than global scope or declared static in global 6429 // scope. 6430 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 6431 return true; 6432 6433 // C++ [basic.stc.dynamic.deallocation]p2: 6434 // Each deallocation function shall return void and its first parameter 6435 // shall be void*. 6436 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 6437 SemaRef.Context.VoidPtrTy, 6438 diag::err_operator_delete_dependent_param_type, 6439 diag::err_operator_delete_param_type)) 6440 return true; 6441 6442 return false; 6443} 6444 6445/// CheckOverloadedOperatorDeclaration - Check whether the declaration 6446/// of this overloaded operator is well-formed. If so, returns false; 6447/// otherwise, emits appropriate diagnostics and returns true. 6448bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 6449 assert(FnDecl && FnDecl->isOverloadedOperator() && 6450 "Expected an overloaded operator declaration"); 6451 6452 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 6453 6454 // C++ [over.oper]p5: 6455 // The allocation and deallocation functions, operator new, 6456 // operator new[], operator delete and operator delete[], are 6457 // described completely in 3.7.3. The attributes and restrictions 6458 // found in the rest of this subclause do not apply to them unless 6459 // explicitly stated in 3.7.3. 6460 if (Op == OO_Delete || Op == OO_Array_Delete) 6461 return CheckOperatorDeleteDeclaration(*this, FnDecl); 6462 6463 if (Op == OO_New || Op == OO_Array_New) 6464 return CheckOperatorNewDeclaration(*this, FnDecl); 6465 6466 // C++ [over.oper]p6: 6467 // An operator function shall either be a non-static member 6468 // function or be a non-member function and have at least one 6469 // parameter whose type is a class, a reference to a class, an 6470 // enumeration, or a reference to an enumeration. 6471 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 6472 if (MethodDecl->isStatic()) 6473 return Diag(FnDecl->getLocation(), 6474 diag::err_operator_overload_static) << FnDecl->getDeclName(); 6475 } else { 6476 bool ClassOrEnumParam = false; 6477 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 6478 ParamEnd = FnDecl->param_end(); 6479 Param != ParamEnd; ++Param) { 6480 QualType ParamType = (*Param)->getType().getNonReferenceType(); 6481 if (ParamType->isDependentType() || ParamType->isRecordType() || 6482 ParamType->isEnumeralType()) { 6483 ClassOrEnumParam = true; 6484 break; 6485 } 6486 } 6487 6488 if (!ClassOrEnumParam) 6489 return Diag(FnDecl->getLocation(), 6490 diag::err_operator_overload_needs_class_or_enum) 6491 << FnDecl->getDeclName(); 6492 } 6493 6494 // C++ [over.oper]p8: 6495 // An operator function cannot have default arguments (8.3.6), 6496 // except where explicitly stated below. 6497 // 6498 // Only the function-call operator allows default arguments 6499 // (C++ [over.call]p1). 6500 if (Op != OO_Call) { 6501 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 6502 Param != FnDecl->param_end(); ++Param) { 6503 if ((*Param)->hasDefaultArg()) 6504 return Diag((*Param)->getLocation(), 6505 diag::err_operator_overload_default_arg) 6506 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 6507 } 6508 } 6509 6510 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 6511 { false, false, false } 6512#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 6513 , { Unary, Binary, MemberOnly } 6514#include "clang/Basic/OperatorKinds.def" 6515 }; 6516 6517 bool CanBeUnaryOperator = OperatorUses[Op][0]; 6518 bool CanBeBinaryOperator = OperatorUses[Op][1]; 6519 bool MustBeMemberOperator = OperatorUses[Op][2]; 6520 6521 // C++ [over.oper]p8: 6522 // [...] Operator functions cannot have more or fewer parameters 6523 // than the number required for the corresponding operator, as 6524 // described in the rest of this subclause. 6525 unsigned NumParams = FnDecl->getNumParams() 6526 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 6527 if (Op != OO_Call && 6528 ((NumParams == 1 && !CanBeUnaryOperator) || 6529 (NumParams == 2 && !CanBeBinaryOperator) || 6530 (NumParams < 1) || (NumParams > 2))) { 6531 // We have the wrong number of parameters. 6532 unsigned ErrorKind; 6533 if (CanBeUnaryOperator && CanBeBinaryOperator) { 6534 ErrorKind = 2; // 2 -> unary or binary. 6535 } else if (CanBeUnaryOperator) { 6536 ErrorKind = 0; // 0 -> unary 6537 } else { 6538 assert(CanBeBinaryOperator && 6539 "All non-call overloaded operators are unary or binary!"); 6540 ErrorKind = 1; // 1 -> binary 6541 } 6542 6543 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 6544 << FnDecl->getDeclName() << NumParams << ErrorKind; 6545 } 6546 6547 // Overloaded operators other than operator() cannot be variadic. 6548 if (Op != OO_Call && 6549 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 6550 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 6551 << FnDecl->getDeclName(); 6552 } 6553 6554 // Some operators must be non-static member functions. 6555 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 6556 return Diag(FnDecl->getLocation(), 6557 diag::err_operator_overload_must_be_member) 6558 << FnDecl->getDeclName(); 6559 } 6560 6561 // C++ [over.inc]p1: 6562 // The user-defined function called operator++ implements the 6563 // prefix and postfix ++ operator. If this function is a member 6564 // function with no parameters, or a non-member function with one 6565 // parameter of class or enumeration type, it defines the prefix 6566 // increment operator ++ for objects of that type. If the function 6567 // is a member function with one parameter (which shall be of type 6568 // int) or a non-member function with two parameters (the second 6569 // of which shall be of type int), it defines the postfix 6570 // increment operator ++ for objects of that type. 6571 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 6572 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 6573 bool ParamIsInt = false; 6574 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 6575 ParamIsInt = BT->getKind() == BuiltinType::Int; 6576 6577 if (!ParamIsInt) 6578 return Diag(LastParam->getLocation(), 6579 diag::err_operator_overload_post_incdec_must_be_int) 6580 << LastParam->getType() << (Op == OO_MinusMinus); 6581 } 6582 6583 return false; 6584} 6585 6586/// CheckLiteralOperatorDeclaration - Check whether the declaration 6587/// of this literal operator function is well-formed. If so, returns 6588/// false; otherwise, emits appropriate diagnostics and returns true. 6589bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 6590 DeclContext *DC = FnDecl->getDeclContext(); 6591 Decl::Kind Kind = DC->getDeclKind(); 6592 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace && 6593 Kind != Decl::LinkageSpec) { 6594 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 6595 << FnDecl->getDeclName(); 6596 return true; 6597 } 6598 6599 bool Valid = false; 6600 6601 // template <char...> type operator "" name() is the only valid template 6602 // signature, and the only valid signature with no parameters. 6603 if (FnDecl->param_size() == 0) { 6604 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) { 6605 // Must have only one template parameter 6606 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 6607 if (Params->size() == 1) { 6608 NonTypeTemplateParmDecl *PmDecl = 6609 cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 6610 6611 // The template parameter must be a char parameter pack. 6612 if (PmDecl && PmDecl->isTemplateParameterPack() && 6613 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 6614 Valid = true; 6615 } 6616 } 6617 } else { 6618 // Check the first parameter 6619 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 6620 6621 QualType T = (*Param)->getType(); 6622 6623 // unsigned long long int, long double, and any character type are allowed 6624 // as the only parameters. 6625 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 6626 Context.hasSameType(T, Context.LongDoubleTy) || 6627 Context.hasSameType(T, Context.CharTy) || 6628 Context.hasSameType(T, Context.WCharTy) || 6629 Context.hasSameType(T, Context.Char16Ty) || 6630 Context.hasSameType(T, Context.Char32Ty)) { 6631 if (++Param == FnDecl->param_end()) 6632 Valid = true; 6633 goto FinishedParams; 6634 } 6635 6636 // Otherwise it must be a pointer to const; let's strip those qualifiers. 6637 const PointerType *PT = T->getAs<PointerType>(); 6638 if (!PT) 6639 goto FinishedParams; 6640 T = PT->getPointeeType(); 6641 if (!T.isConstQualified()) 6642 goto FinishedParams; 6643 T = T.getUnqualifiedType(); 6644 6645 // Move on to the second parameter; 6646 ++Param; 6647 6648 // If there is no second parameter, the first must be a const char * 6649 if (Param == FnDecl->param_end()) { 6650 if (Context.hasSameType(T, Context.CharTy)) 6651 Valid = true; 6652 goto FinishedParams; 6653 } 6654 6655 // const char *, const wchar_t*, const char16_t*, and const char32_t* 6656 // are allowed as the first parameter to a two-parameter function 6657 if (!(Context.hasSameType(T, Context.CharTy) || 6658 Context.hasSameType(T, Context.WCharTy) || 6659 Context.hasSameType(T, Context.Char16Ty) || 6660 Context.hasSameType(T, Context.Char32Ty))) 6661 goto FinishedParams; 6662 6663 // The second and final parameter must be an std::size_t 6664 T = (*Param)->getType().getUnqualifiedType(); 6665 if (Context.hasSameType(T, Context.getSizeType()) && 6666 ++Param == FnDecl->param_end()) 6667 Valid = true; 6668 } 6669 6670 // FIXME: This diagnostic is absolutely terrible. 6671FinishedParams: 6672 if (!Valid) { 6673 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 6674 << FnDecl->getDeclName(); 6675 return true; 6676 } 6677 6678 return false; 6679} 6680 6681/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 6682/// linkage specification, including the language and (if present) 6683/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 6684/// the location of the language string literal, which is provided 6685/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 6686/// the '{' brace. Otherwise, this linkage specification does not 6687/// have any braces. 6688Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 6689 SourceLocation LangLoc, 6690 llvm::StringRef Lang, 6691 SourceLocation LBraceLoc) { 6692 LinkageSpecDecl::LanguageIDs Language; 6693 if (Lang == "\"C\"") 6694 Language = LinkageSpecDecl::lang_c; 6695 else if (Lang == "\"C++\"") 6696 Language = LinkageSpecDecl::lang_cxx; 6697 else { 6698 Diag(LangLoc, diag::err_bad_language); 6699 return 0; 6700 } 6701 6702 // FIXME: Add all the various semantics of linkage specifications 6703 6704 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 6705 ExternLoc, LangLoc, Language); 6706 CurContext->addDecl(D); 6707 PushDeclContext(S, D); 6708 return D; 6709} 6710 6711/// ActOnFinishLinkageSpecification - Complete the definition of 6712/// the C++ linkage specification LinkageSpec. If RBraceLoc is 6713/// valid, it's the position of the closing '}' brace in a linkage 6714/// specification that uses braces. 6715Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 6716 Decl *LinkageSpec, 6717 SourceLocation RBraceLoc) { 6718 if (LinkageSpec) { 6719 if (RBraceLoc.isValid()) { 6720 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 6721 LSDecl->setRBraceLoc(RBraceLoc); 6722 } 6723 PopDeclContext(); 6724 } 6725 return LinkageSpec; 6726} 6727 6728/// \brief Perform semantic analysis for the variable declaration that 6729/// occurs within a C++ catch clause, returning the newly-created 6730/// variable. 6731VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 6732 TypeSourceInfo *TInfo, 6733 SourceLocation StartLoc, 6734 SourceLocation Loc, 6735 IdentifierInfo *Name) { 6736 bool Invalid = false; 6737 QualType ExDeclType = TInfo->getType(); 6738 6739 // Arrays and functions decay. 6740 if (ExDeclType->isArrayType()) 6741 ExDeclType = Context.getArrayDecayedType(ExDeclType); 6742 else if (ExDeclType->isFunctionType()) 6743 ExDeclType = Context.getPointerType(ExDeclType); 6744 6745 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 6746 // The exception-declaration shall not denote a pointer or reference to an 6747 // incomplete type, other than [cv] void*. 6748 // N2844 forbids rvalue references. 6749 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 6750 Diag(Loc, diag::err_catch_rvalue_ref); 6751 Invalid = true; 6752 } 6753 6754 // GCC allows catching pointers and references to incomplete types 6755 // as an extension; so do we, but we warn by default. 6756 6757 QualType BaseType = ExDeclType; 6758 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 6759 unsigned DK = diag::err_catch_incomplete; 6760 bool IncompleteCatchIsInvalid = true; 6761 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 6762 BaseType = Ptr->getPointeeType(); 6763 Mode = 1; 6764 DK = diag::ext_catch_incomplete_ptr; 6765 IncompleteCatchIsInvalid = false; 6766 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 6767 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 6768 BaseType = Ref->getPointeeType(); 6769 Mode = 2; 6770 DK = diag::ext_catch_incomplete_ref; 6771 IncompleteCatchIsInvalid = false; 6772 } 6773 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 6774 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) && 6775 IncompleteCatchIsInvalid) 6776 Invalid = true; 6777 6778 if (!Invalid && !ExDeclType->isDependentType() && 6779 RequireNonAbstractType(Loc, ExDeclType, 6780 diag::err_abstract_type_in_decl, 6781 AbstractVariableType)) 6782 Invalid = true; 6783 6784 // Only the non-fragile NeXT runtime currently supports C++ catches 6785 // of ObjC types, and no runtime supports catching ObjC types by value. 6786 if (!Invalid && getLangOptions().ObjC1) { 6787 QualType T = ExDeclType; 6788 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 6789 T = RT->getPointeeType(); 6790 6791 if (T->isObjCObjectType()) { 6792 Diag(Loc, diag::err_objc_object_catch); 6793 Invalid = true; 6794 } else if (T->isObjCObjectPointerType()) { 6795 if (!getLangOptions().ObjCNonFragileABI) { 6796 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile); 6797 Invalid = true; 6798 } 6799 } 6800 } 6801 6802 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 6803 ExDeclType, TInfo, SC_None, SC_None); 6804 ExDecl->setExceptionVariable(true); 6805 6806 if (!Invalid) { 6807 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 6808 // C++ [except.handle]p16: 6809 // The object declared in an exception-declaration or, if the 6810 // exception-declaration does not specify a name, a temporary (12.2) is 6811 // copy-initialized (8.5) from the exception object. [...] 6812 // The object is destroyed when the handler exits, after the destruction 6813 // of any automatic objects initialized within the handler. 6814 // 6815 // We just pretend to initialize the object with itself, then make sure 6816 // it can be destroyed later. 6817 QualType initType = ExDeclType; 6818 6819 InitializedEntity entity = 6820 InitializedEntity::InitializeVariable(ExDecl); 6821 InitializationKind initKind = 6822 InitializationKind::CreateCopy(Loc, SourceLocation()); 6823 6824 Expr *opaqueValue = 6825 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 6826 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1); 6827 ExprResult result = sequence.Perform(*this, entity, initKind, 6828 MultiExprArg(&opaqueValue, 1)); 6829 if (result.isInvalid()) 6830 Invalid = true; 6831 else { 6832 // If the constructor used was non-trivial, set this as the 6833 // "initializer". 6834 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take()); 6835 if (!construct->getConstructor()->isTrivial()) { 6836 Expr *init = MaybeCreateExprWithCleanups(construct); 6837 ExDecl->setInit(init); 6838 } 6839 6840 // And make sure it's destructable. 6841 FinalizeVarWithDestructor(ExDecl, recordType); 6842 } 6843 } 6844 } 6845 6846 if (Invalid) 6847 ExDecl->setInvalidDecl(); 6848 6849 return ExDecl; 6850} 6851 6852/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 6853/// handler. 6854Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 6855 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6856 bool Invalid = D.isInvalidType(); 6857 6858 // Check for unexpanded parameter packs. 6859 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 6860 UPPC_ExceptionType)) { 6861 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 6862 D.getIdentifierLoc()); 6863 Invalid = true; 6864 } 6865 6866 IdentifierInfo *II = D.getIdentifier(); 6867 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 6868 LookupOrdinaryName, 6869 ForRedeclaration)) { 6870 // The scope should be freshly made just for us. There is just no way 6871 // it contains any previous declaration. 6872 assert(!S->isDeclScope(PrevDecl)); 6873 if (PrevDecl->isTemplateParameter()) { 6874 // Maybe we will complain about the shadowed template parameter. 6875 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 6876 } 6877 } 6878 6879 if (D.getCXXScopeSpec().isSet() && !Invalid) { 6880 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 6881 << D.getCXXScopeSpec().getRange(); 6882 Invalid = true; 6883 } 6884 6885 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo, 6886 D.getSourceRange().getBegin(), 6887 D.getIdentifierLoc(), 6888 D.getIdentifier()); 6889 if (Invalid) 6890 ExDecl->setInvalidDecl(); 6891 6892 // Add the exception declaration into this scope. 6893 if (II) 6894 PushOnScopeChains(ExDecl, S); 6895 else 6896 CurContext->addDecl(ExDecl); 6897 6898 ProcessDeclAttributes(S, ExDecl, D); 6899 return ExDecl; 6900} 6901 6902Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 6903 Expr *AssertExpr, 6904 Expr *AssertMessageExpr_, 6905 SourceLocation RParenLoc) { 6906 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_); 6907 6908 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 6909 llvm::APSInt Value(32); 6910 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 6911 Diag(StaticAssertLoc, 6912 diag::err_static_assert_expression_is_not_constant) << 6913 AssertExpr->getSourceRange(); 6914 return 0; 6915 } 6916 6917 if (Value == 0) { 6918 Diag(StaticAssertLoc, diag::err_static_assert_failed) 6919 << AssertMessage->getString() << AssertExpr->getSourceRange(); 6920 } 6921 } 6922 6923 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 6924 return 0; 6925 6926 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 6927 AssertExpr, AssertMessage, RParenLoc); 6928 6929 CurContext->addDecl(Decl); 6930 return Decl; 6931} 6932 6933/// \brief Perform semantic analysis of the given friend type declaration. 6934/// 6935/// \returns A friend declaration that. 6936FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc, 6937 TypeSourceInfo *TSInfo) { 6938 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 6939 6940 QualType T = TSInfo->getType(); 6941 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 6942 6943 if (!getLangOptions().CPlusPlus0x) { 6944 // C++03 [class.friend]p2: 6945 // An elaborated-type-specifier shall be used in a friend declaration 6946 // for a class.* 6947 // 6948 // * The class-key of the elaborated-type-specifier is required. 6949 if (!ActiveTemplateInstantiations.empty()) { 6950 // Do not complain about the form of friend template types during 6951 // template instantiation; we will already have complained when the 6952 // template was declared. 6953 } else if (!T->isElaboratedTypeSpecifier()) { 6954 // If we evaluated the type to a record type, suggest putting 6955 // a tag in front. 6956 if (const RecordType *RT = T->getAs<RecordType>()) { 6957 RecordDecl *RD = RT->getDecl(); 6958 6959 std::string InsertionText = std::string(" ") + RD->getKindName(); 6960 6961 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type) 6962 << (unsigned) RD->getTagKind() 6963 << T 6964 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 6965 InsertionText); 6966 } else { 6967 Diag(FriendLoc, diag::ext_nonclass_type_friend) 6968 << T 6969 << SourceRange(FriendLoc, TypeRange.getEnd()); 6970 } 6971 } else if (T->getAs<EnumType>()) { 6972 Diag(FriendLoc, diag::ext_enum_friend) 6973 << T 6974 << SourceRange(FriendLoc, TypeRange.getEnd()); 6975 } 6976 } 6977 6978 // C++0x [class.friend]p3: 6979 // If the type specifier in a friend declaration designates a (possibly 6980 // cv-qualified) class type, that class is declared as a friend; otherwise, 6981 // the friend declaration is ignored. 6982 6983 // FIXME: C++0x has some syntactic restrictions on friend type declarations 6984 // in [class.friend]p3 that we do not implement. 6985 6986 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc); 6987} 6988 6989/// Handle a friend tag declaration where the scope specifier was 6990/// templated. 6991Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 6992 unsigned TagSpec, SourceLocation TagLoc, 6993 CXXScopeSpec &SS, 6994 IdentifierInfo *Name, SourceLocation NameLoc, 6995 AttributeList *Attr, 6996 MultiTemplateParamsArg TempParamLists) { 6997 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 6998 6999 bool isExplicitSpecialization = false; 7000 bool Invalid = false; 7001 7002 if (TemplateParameterList *TemplateParams 7003 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS, 7004 TempParamLists.get(), 7005 TempParamLists.size(), 7006 /*friend*/ true, 7007 isExplicitSpecialization, 7008 Invalid)) { 7009 if (TemplateParams->size() > 0) { 7010 // This is a declaration of a class template. 7011 if (Invalid) 7012 return 0; 7013 7014 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, 7015 SS, Name, NameLoc, Attr, 7016 TemplateParams, AS_public, 7017 TempParamLists.size() - 1, 7018 (TemplateParameterList**) TempParamLists.release()).take(); 7019 } else { 7020 // The "template<>" header is extraneous. 7021 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 7022 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 7023 isExplicitSpecialization = true; 7024 } 7025 } 7026 7027 if (Invalid) return 0; 7028 7029 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 7030 7031 bool isAllExplicitSpecializations = true; 7032 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 7033 if (TempParamLists.get()[I]->size()) { 7034 isAllExplicitSpecializations = false; 7035 break; 7036 } 7037 } 7038 7039 // FIXME: don't ignore attributes. 7040 7041 // If it's explicit specializations all the way down, just forget 7042 // about the template header and build an appropriate non-templated 7043 // friend. TODO: for source fidelity, remember the headers. 7044 if (isAllExplicitSpecializations) { 7045 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 7046 ElaboratedTypeKeyword Keyword 7047 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 7048 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 7049 *Name, NameLoc); 7050 if (T.isNull()) 7051 return 0; 7052 7053 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 7054 if (isa<DependentNameType>(T)) { 7055 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 7056 TL.setKeywordLoc(TagLoc); 7057 TL.setQualifierLoc(QualifierLoc); 7058 TL.setNameLoc(NameLoc); 7059 } else { 7060 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 7061 TL.setKeywordLoc(TagLoc); 7062 TL.setQualifierLoc(QualifierLoc); 7063 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc); 7064 } 7065 7066 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 7067 TSI, FriendLoc); 7068 Friend->setAccess(AS_public); 7069 CurContext->addDecl(Friend); 7070 return Friend; 7071 } 7072 7073 // Handle the case of a templated-scope friend class. e.g. 7074 // template <class T> class A<T>::B; 7075 // FIXME: we don't support these right now. 7076 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 7077 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 7078 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 7079 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 7080 TL.setKeywordLoc(TagLoc); 7081 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 7082 TL.setNameLoc(NameLoc); 7083 7084 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 7085 TSI, FriendLoc); 7086 Friend->setAccess(AS_public); 7087 Friend->setUnsupportedFriend(true); 7088 CurContext->addDecl(Friend); 7089 return Friend; 7090} 7091 7092 7093/// Handle a friend type declaration. This works in tandem with 7094/// ActOnTag. 7095/// 7096/// Notes on friend class templates: 7097/// 7098/// We generally treat friend class declarations as if they were 7099/// declaring a class. So, for example, the elaborated type specifier 7100/// in a friend declaration is required to obey the restrictions of a 7101/// class-head (i.e. no typedefs in the scope chain), template 7102/// parameters are required to match up with simple template-ids, &c. 7103/// However, unlike when declaring a template specialization, it's 7104/// okay to refer to a template specialization without an empty 7105/// template parameter declaration, e.g. 7106/// friend class A<T>::B<unsigned>; 7107/// We permit this as a special case; if there are any template 7108/// parameters present at all, require proper matching, i.e. 7109/// template <> template <class T> friend class A<int>::B; 7110Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 7111 MultiTemplateParamsArg TempParams) { 7112 SourceLocation Loc = DS.getSourceRange().getBegin(); 7113 7114 assert(DS.isFriendSpecified()); 7115 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 7116 7117 // Try to convert the decl specifier to a type. This works for 7118 // friend templates because ActOnTag never produces a ClassTemplateDecl 7119 // for a TUK_Friend. 7120 Declarator TheDeclarator(DS, Declarator::MemberContext); 7121 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 7122 QualType T = TSI->getType(); 7123 if (TheDeclarator.isInvalidType()) 7124 return 0; 7125 7126 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 7127 return 0; 7128 7129 // This is definitely an error in C++98. It's probably meant to 7130 // be forbidden in C++0x, too, but the specification is just 7131 // poorly written. 7132 // 7133 // The problem is with declarations like the following: 7134 // template <T> friend A<T>::foo; 7135 // where deciding whether a class C is a friend or not now hinges 7136 // on whether there exists an instantiation of A that causes 7137 // 'foo' to equal C. There are restrictions on class-heads 7138 // (which we declare (by fiat) elaborated friend declarations to 7139 // be) that makes this tractable. 7140 // 7141 // FIXME: handle "template <> friend class A<T>;", which 7142 // is possibly well-formed? Who even knows? 7143 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 7144 Diag(Loc, diag::err_tagless_friend_type_template) 7145 << DS.getSourceRange(); 7146 return 0; 7147 } 7148 7149 // C++98 [class.friend]p1: A friend of a class is a function 7150 // or class that is not a member of the class . . . 7151 // This is fixed in DR77, which just barely didn't make the C++03 7152 // deadline. It's also a very silly restriction that seriously 7153 // affects inner classes and which nobody else seems to implement; 7154 // thus we never diagnose it, not even in -pedantic. 7155 // 7156 // But note that we could warn about it: it's always useless to 7157 // friend one of your own members (it's not, however, worthless to 7158 // friend a member of an arbitrary specialization of your template). 7159 7160 Decl *D; 7161 if (unsigned NumTempParamLists = TempParams.size()) 7162 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 7163 NumTempParamLists, 7164 TempParams.release(), 7165 TSI, 7166 DS.getFriendSpecLoc()); 7167 else 7168 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI); 7169 7170 if (!D) 7171 return 0; 7172 7173 D->setAccess(AS_public); 7174 CurContext->addDecl(D); 7175 7176 return D; 7177} 7178 7179Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition, 7180 MultiTemplateParamsArg TemplateParams) { 7181 const DeclSpec &DS = D.getDeclSpec(); 7182 7183 assert(DS.isFriendSpecified()); 7184 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 7185 7186 SourceLocation Loc = D.getIdentifierLoc(); 7187 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 7188 QualType T = TInfo->getType(); 7189 7190 // C++ [class.friend]p1 7191 // A friend of a class is a function or class.... 7192 // Note that this sees through typedefs, which is intended. 7193 // It *doesn't* see through dependent types, which is correct 7194 // according to [temp.arg.type]p3: 7195 // If a declaration acquires a function type through a 7196 // type dependent on a template-parameter and this causes 7197 // a declaration that does not use the syntactic form of a 7198 // function declarator to have a function type, the program 7199 // is ill-formed. 7200 if (!T->isFunctionType()) { 7201 Diag(Loc, diag::err_unexpected_friend); 7202 7203 // It might be worthwhile to try to recover by creating an 7204 // appropriate declaration. 7205 return 0; 7206 } 7207 7208 // C++ [namespace.memdef]p3 7209 // - If a friend declaration in a non-local class first declares a 7210 // class or function, the friend class or function is a member 7211 // of the innermost enclosing namespace. 7212 // - The name of the friend is not found by simple name lookup 7213 // until a matching declaration is provided in that namespace 7214 // scope (either before or after the class declaration granting 7215 // friendship). 7216 // - If a friend function is called, its name may be found by the 7217 // name lookup that considers functions from namespaces and 7218 // classes associated with the types of the function arguments. 7219 // - When looking for a prior declaration of a class or a function 7220 // declared as a friend, scopes outside the innermost enclosing 7221 // namespace scope are not considered. 7222 7223 CXXScopeSpec &SS = D.getCXXScopeSpec(); 7224 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7225 DeclarationName Name = NameInfo.getName(); 7226 assert(Name); 7227 7228 // Check for unexpanded parameter packs. 7229 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 7230 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 7231 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 7232 return 0; 7233 7234 // The context we found the declaration in, or in which we should 7235 // create the declaration. 7236 DeclContext *DC; 7237 Scope *DCScope = S; 7238 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 7239 ForRedeclaration); 7240 7241 // FIXME: there are different rules in local classes 7242 7243 // There are four cases here. 7244 // - There's no scope specifier, in which case we just go to the 7245 // appropriate scope and look for a function or function template 7246 // there as appropriate. 7247 // Recover from invalid scope qualifiers as if they just weren't there. 7248 if (SS.isInvalid() || !SS.isSet()) { 7249 // C++0x [namespace.memdef]p3: 7250 // If the name in a friend declaration is neither qualified nor 7251 // a template-id and the declaration is a function or an 7252 // elaborated-type-specifier, the lookup to determine whether 7253 // the entity has been previously declared shall not consider 7254 // any scopes outside the innermost enclosing namespace. 7255 // C++0x [class.friend]p11: 7256 // If a friend declaration appears in a local class and the name 7257 // specified is an unqualified name, a prior declaration is 7258 // looked up without considering scopes that are outside the 7259 // innermost enclosing non-class scope. For a friend function 7260 // declaration, if there is no prior declaration, the program is 7261 // ill-formed. 7262 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass(); 7263 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId; 7264 7265 // Find the appropriate context according to the above. 7266 DC = CurContext; 7267 while (true) { 7268 // Skip class contexts. If someone can cite chapter and verse 7269 // for this behavior, that would be nice --- it's what GCC and 7270 // EDG do, and it seems like a reasonable intent, but the spec 7271 // really only says that checks for unqualified existing 7272 // declarations should stop at the nearest enclosing namespace, 7273 // not that they should only consider the nearest enclosing 7274 // namespace. 7275 while (DC->isRecord()) 7276 DC = DC->getParent(); 7277 7278 LookupQualifiedName(Previous, DC); 7279 7280 // TODO: decide what we think about using declarations. 7281 if (isLocal || !Previous.empty()) 7282 break; 7283 7284 if (isTemplateId) { 7285 if (isa<TranslationUnitDecl>(DC)) break; 7286 } else { 7287 if (DC->isFileContext()) break; 7288 } 7289 DC = DC->getParent(); 7290 } 7291 7292 // C++ [class.friend]p1: A friend of a class is a function or 7293 // class that is not a member of the class . . . 7294 // C++0x changes this for both friend types and functions. 7295 // Most C++ 98 compilers do seem to give an error here, so 7296 // we do, too. 7297 if (!Previous.empty() && DC->Equals(CurContext) 7298 && !getLangOptions().CPlusPlus0x) 7299 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 7300 7301 DCScope = getScopeForDeclContext(S, DC); 7302 7303 // - There's a non-dependent scope specifier, in which case we 7304 // compute it and do a previous lookup there for a function 7305 // or function template. 7306 } else if (!SS.getScopeRep()->isDependent()) { 7307 DC = computeDeclContext(SS); 7308 if (!DC) return 0; 7309 7310 if (RequireCompleteDeclContext(SS, DC)) return 0; 7311 7312 LookupQualifiedName(Previous, DC); 7313 7314 // Ignore things found implicitly in the wrong scope. 7315 // TODO: better diagnostics for this case. Suggesting the right 7316 // qualified scope would be nice... 7317 LookupResult::Filter F = Previous.makeFilter(); 7318 while (F.hasNext()) { 7319 NamedDecl *D = F.next(); 7320 if (!DC->InEnclosingNamespaceSetOf( 7321 D->getDeclContext()->getRedeclContext())) 7322 F.erase(); 7323 } 7324 F.done(); 7325 7326 if (Previous.empty()) { 7327 D.setInvalidType(); 7328 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 7329 return 0; 7330 } 7331 7332 // C++ [class.friend]p1: A friend of a class is a function or 7333 // class that is not a member of the class . . . 7334 if (DC->Equals(CurContext)) 7335 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 7336 7337 // - There's a scope specifier that does not match any template 7338 // parameter lists, in which case we use some arbitrary context, 7339 // create a method or method template, and wait for instantiation. 7340 // - There's a scope specifier that does match some template 7341 // parameter lists, which we don't handle right now. 7342 } else { 7343 DC = CurContext; 7344 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 7345 } 7346 7347 if (!DC->isRecord()) { 7348 // This implies that it has to be an operator or function. 7349 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 7350 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 7351 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 7352 Diag(Loc, diag::err_introducing_special_friend) << 7353 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 7354 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 7355 return 0; 7356 } 7357 } 7358 7359 bool Redeclaration = false; 7360 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous, 7361 move(TemplateParams), 7362 IsDefinition, 7363 Redeclaration); 7364 if (!ND) return 0; 7365 7366 assert(ND->getDeclContext() == DC); 7367 assert(ND->getLexicalDeclContext() == CurContext); 7368 7369 // Add the function declaration to the appropriate lookup tables, 7370 // adjusting the redeclarations list as necessary. We don't 7371 // want to do this yet if the friending class is dependent. 7372 // 7373 // Also update the scope-based lookup if the target context's 7374 // lookup context is in lexical scope. 7375 if (!CurContext->isDependentContext()) { 7376 DC = DC->getRedeclContext(); 7377 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 7378 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 7379 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 7380 } 7381 7382 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 7383 D.getIdentifierLoc(), ND, 7384 DS.getFriendSpecLoc()); 7385 FrD->setAccess(AS_public); 7386 CurContext->addDecl(FrD); 7387 7388 if (ND->isInvalidDecl()) 7389 FrD->setInvalidDecl(); 7390 else { 7391 FunctionDecl *FD; 7392 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 7393 FD = FTD->getTemplatedDecl(); 7394 else 7395 FD = cast<FunctionDecl>(ND); 7396 7397 // Mark templated-scope function declarations as unsupported. 7398 if (FD->getNumTemplateParameterLists()) 7399 FrD->setUnsupportedFriend(true); 7400 } 7401 7402 return ND; 7403} 7404 7405void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 7406 AdjustDeclIfTemplate(Dcl); 7407 7408 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 7409 if (!Fn) { 7410 Diag(DelLoc, diag::err_deleted_non_function); 7411 return; 7412 } 7413 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 7414 Diag(DelLoc, diag::err_deleted_decl_not_first); 7415 Diag(Prev->getLocation(), diag::note_previous_declaration); 7416 // If the declaration wasn't the first, we delete the function anyway for 7417 // recovery. 7418 } 7419 Fn->setDeleted(); 7420} 7421 7422static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 7423 for (Stmt::child_range CI = S->children(); CI; ++CI) { 7424 Stmt *SubStmt = *CI; 7425 if (!SubStmt) 7426 continue; 7427 if (isa<ReturnStmt>(SubStmt)) 7428 Self.Diag(SubStmt->getSourceRange().getBegin(), 7429 diag::err_return_in_constructor_handler); 7430 if (!isa<Expr>(SubStmt)) 7431 SearchForReturnInStmt(Self, SubStmt); 7432 } 7433} 7434 7435void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 7436 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 7437 CXXCatchStmt *Handler = TryBlock->getHandler(I); 7438 SearchForReturnInStmt(*this, Handler); 7439 } 7440} 7441 7442bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 7443 const CXXMethodDecl *Old) { 7444 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 7445 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 7446 7447 if (Context.hasSameType(NewTy, OldTy) || 7448 NewTy->isDependentType() || OldTy->isDependentType()) 7449 return false; 7450 7451 // Check if the return types are covariant 7452 QualType NewClassTy, OldClassTy; 7453 7454 /// Both types must be pointers or references to classes. 7455 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 7456 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 7457 NewClassTy = NewPT->getPointeeType(); 7458 OldClassTy = OldPT->getPointeeType(); 7459 } 7460 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 7461 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 7462 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 7463 NewClassTy = NewRT->getPointeeType(); 7464 OldClassTy = OldRT->getPointeeType(); 7465 } 7466 } 7467 } 7468 7469 // The return types aren't either both pointers or references to a class type. 7470 if (NewClassTy.isNull()) { 7471 Diag(New->getLocation(), 7472 diag::err_different_return_type_for_overriding_virtual_function) 7473 << New->getDeclName() << NewTy << OldTy; 7474 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 7475 7476 return true; 7477 } 7478 7479 // C++ [class.virtual]p6: 7480 // If the return type of D::f differs from the return type of B::f, the 7481 // class type in the return type of D::f shall be complete at the point of 7482 // declaration of D::f or shall be the class type D. 7483 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 7484 if (!RT->isBeingDefined() && 7485 RequireCompleteType(New->getLocation(), NewClassTy, 7486 PDiag(diag::err_covariant_return_incomplete) 7487 << New->getDeclName())) 7488 return true; 7489 } 7490 7491 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 7492 // Check if the new class derives from the old class. 7493 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 7494 Diag(New->getLocation(), 7495 diag::err_covariant_return_not_derived) 7496 << New->getDeclName() << NewTy << OldTy; 7497 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 7498 return true; 7499 } 7500 7501 // Check if we the conversion from derived to base is valid. 7502 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 7503 diag::err_covariant_return_inaccessible_base, 7504 diag::err_covariant_return_ambiguous_derived_to_base_conv, 7505 // FIXME: Should this point to the return type? 7506 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 7507 // FIXME: this note won't trigger for delayed access control 7508 // diagnostics, and it's impossible to get an undelayed error 7509 // here from access control during the original parse because 7510 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 7511 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 7512 return true; 7513 } 7514 } 7515 7516 // The qualifiers of the return types must be the same. 7517 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 7518 Diag(New->getLocation(), 7519 diag::err_covariant_return_type_different_qualifications) 7520 << New->getDeclName() << NewTy << OldTy; 7521 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 7522 return true; 7523 }; 7524 7525 7526 // The new class type must have the same or less qualifiers as the old type. 7527 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 7528 Diag(New->getLocation(), 7529 diag::err_covariant_return_type_class_type_more_qualified) 7530 << New->getDeclName() << NewTy << OldTy; 7531 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 7532 return true; 7533 }; 7534 7535 return false; 7536} 7537 7538/// \brief Mark the given method pure. 7539/// 7540/// \param Method the method to be marked pure. 7541/// 7542/// \param InitRange the source range that covers the "0" initializer. 7543bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 7544 SourceLocation EndLoc = InitRange.getEnd(); 7545 if (EndLoc.isValid()) 7546 Method->setRangeEnd(EndLoc); 7547 7548 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 7549 Method->setPure(); 7550 return false; 7551 } 7552 7553 if (!Method->isInvalidDecl()) 7554 Diag(Method->getLocation(), diag::err_non_virtual_pure) 7555 << Method->getDeclName() << InitRange; 7556 return true; 7557} 7558 7559/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 7560/// an initializer for the out-of-line declaration 'Dcl'. The scope 7561/// is a fresh scope pushed for just this purpose. 7562/// 7563/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 7564/// static data member of class X, names should be looked up in the scope of 7565/// class X. 7566void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 7567 // If there is no declaration, there was an error parsing it. 7568 if (D == 0) return; 7569 7570 // We should only get called for declarations with scope specifiers, like: 7571 // int foo::bar; 7572 assert(D->isOutOfLine()); 7573 EnterDeclaratorContext(S, D->getDeclContext()); 7574} 7575 7576/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 7577/// initializer for the out-of-line declaration 'D'. 7578void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 7579 // If there is no declaration, there was an error parsing it. 7580 if (D == 0) return; 7581 7582 assert(D->isOutOfLine()); 7583 ExitDeclaratorContext(S); 7584} 7585 7586/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 7587/// C++ if/switch/while/for statement. 7588/// e.g: "if (int x = f()) {...}" 7589DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 7590 // C++ 6.4p2: 7591 // The declarator shall not specify a function or an array. 7592 // The type-specifier-seq shall not contain typedef and shall not declare a 7593 // new class or enumeration. 7594 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 7595 "Parser allowed 'typedef' as storage class of condition decl."); 7596 7597 TagDecl *OwnedTag = 0; 7598 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag); 7599 QualType Ty = TInfo->getType(); 7600 7601 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 7602 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 7603 // would be created and CXXConditionDeclExpr wants a VarDecl. 7604 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type) 7605 << D.getSourceRange(); 7606 return DeclResult(); 7607 } else if (OwnedTag && OwnedTag->isDefinition()) { 7608 // The type-specifier-seq shall not declare a new class or enumeration. 7609 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition); 7610 } 7611 7612 Decl *Dcl = ActOnDeclarator(S, D); 7613 if (!Dcl) 7614 return DeclResult(); 7615 7616 return Dcl; 7617} 7618 7619void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 7620 bool DefinitionRequired) { 7621 // Ignore any vtable uses in unevaluated operands or for classes that do 7622 // not have a vtable. 7623 if (!Class->isDynamicClass() || Class->isDependentContext() || 7624 CurContext->isDependentContext() || 7625 ExprEvalContexts.back().Context == Unevaluated) 7626 return; 7627 7628 // Try to insert this class into the map. 7629 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 7630 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 7631 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 7632 if (!Pos.second) { 7633 // If we already had an entry, check to see if we are promoting this vtable 7634 // to required a definition. If so, we need to reappend to the VTableUses 7635 // list, since we may have already processed the first entry. 7636 if (DefinitionRequired && !Pos.first->second) { 7637 Pos.first->second = true; 7638 } else { 7639 // Otherwise, we can early exit. 7640 return; 7641 } 7642 } 7643 7644 // Local classes need to have their virtual members marked 7645 // immediately. For all other classes, we mark their virtual members 7646 // at the end of the translation unit. 7647 if (Class->isLocalClass()) 7648 MarkVirtualMembersReferenced(Loc, Class); 7649 else 7650 VTableUses.push_back(std::make_pair(Class, Loc)); 7651} 7652 7653bool Sema::DefineUsedVTables() { 7654 if (VTableUses.empty()) 7655 return false; 7656 7657 // Note: The VTableUses vector could grow as a result of marking 7658 // the members of a class as "used", so we check the size each 7659 // time through the loop and prefer indices (with are stable) to 7660 // iterators (which are not). 7661 for (unsigned I = 0; I != VTableUses.size(); ++I) { 7662 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 7663 if (!Class) 7664 continue; 7665 7666 SourceLocation Loc = VTableUses[I].second; 7667 7668 // If this class has a key function, but that key function is 7669 // defined in another translation unit, we don't need to emit the 7670 // vtable even though we're using it. 7671 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class); 7672 if (KeyFunction && !KeyFunction->hasBody()) { 7673 switch (KeyFunction->getTemplateSpecializationKind()) { 7674 case TSK_Undeclared: 7675 case TSK_ExplicitSpecialization: 7676 case TSK_ExplicitInstantiationDeclaration: 7677 // The key function is in another translation unit. 7678 continue; 7679 7680 case TSK_ExplicitInstantiationDefinition: 7681 case TSK_ImplicitInstantiation: 7682 // We will be instantiating the key function. 7683 break; 7684 } 7685 } else if (!KeyFunction) { 7686 // If we have a class with no key function that is the subject 7687 // of an explicit instantiation declaration, suppress the 7688 // vtable; it will live with the explicit instantiation 7689 // definition. 7690 bool IsExplicitInstantiationDeclaration 7691 = Class->getTemplateSpecializationKind() 7692 == TSK_ExplicitInstantiationDeclaration; 7693 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 7694 REnd = Class->redecls_end(); 7695 R != REnd; ++R) { 7696 TemplateSpecializationKind TSK 7697 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 7698 if (TSK == TSK_ExplicitInstantiationDeclaration) 7699 IsExplicitInstantiationDeclaration = true; 7700 else if (TSK == TSK_ExplicitInstantiationDefinition) { 7701 IsExplicitInstantiationDeclaration = false; 7702 break; 7703 } 7704 } 7705 7706 if (IsExplicitInstantiationDeclaration) 7707 continue; 7708 } 7709 7710 // Mark all of the virtual members of this class as referenced, so 7711 // that we can build a vtable. Then, tell the AST consumer that a 7712 // vtable for this class is required. 7713 MarkVirtualMembersReferenced(Loc, Class); 7714 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 7715 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 7716 7717 // Optionally warn if we're emitting a weak vtable. 7718 if (Class->getLinkage() == ExternalLinkage && 7719 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 7720 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined())) 7721 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; 7722 } 7723 } 7724 VTableUses.clear(); 7725 7726 return true; 7727} 7728 7729void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 7730 const CXXRecordDecl *RD) { 7731 for (CXXRecordDecl::method_iterator i = RD->method_begin(), 7732 e = RD->method_end(); i != e; ++i) { 7733 CXXMethodDecl *MD = *i; 7734 7735 // C++ [basic.def.odr]p2: 7736 // [...] A virtual member function is used if it is not pure. [...] 7737 if (MD->isVirtual() && !MD->isPure()) 7738 MarkDeclarationReferenced(Loc, MD); 7739 } 7740 7741 // Only classes that have virtual bases need a VTT. 7742 if (RD->getNumVBases() == 0) 7743 return; 7744 7745 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 7746 e = RD->bases_end(); i != e; ++i) { 7747 const CXXRecordDecl *Base = 7748 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 7749 if (Base->getNumVBases() == 0) 7750 continue; 7751 MarkVirtualMembersReferenced(Loc, Base); 7752 } 7753} 7754 7755/// SetIvarInitializers - This routine builds initialization ASTs for the 7756/// Objective-C implementation whose ivars need be initialized. 7757void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 7758 if (!getLangOptions().CPlusPlus) 7759 return; 7760 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 7761 llvm::SmallVector<ObjCIvarDecl*, 8> ivars; 7762 CollectIvarsToConstructOrDestruct(OID, ivars); 7763 if (ivars.empty()) 7764 return; 7765 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit; 7766 for (unsigned i = 0; i < ivars.size(); i++) { 7767 FieldDecl *Field = ivars[i]; 7768 if (Field->isInvalidDecl()) 7769 continue; 7770 7771 CXXCtorInitializer *Member; 7772 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 7773 InitializationKind InitKind = 7774 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 7775 7776 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 7777 ExprResult MemberInit = 7778 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg()); 7779 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 7780 // Note, MemberInit could actually come back empty if no initialization 7781 // is required (e.g., because it would call a trivial default constructor) 7782 if (!MemberInit.get() || MemberInit.isInvalid()) 7783 continue; 7784 7785 Member = 7786 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 7787 SourceLocation(), 7788 MemberInit.takeAs<Expr>(), 7789 SourceLocation()); 7790 AllToInit.push_back(Member); 7791 7792 // Be sure that the destructor is accessible and is marked as referenced. 7793 if (const RecordType *RecordTy 7794 = Context.getBaseElementType(Field->getType()) 7795 ->getAs<RecordType>()) { 7796 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 7797 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 7798 MarkDeclarationReferenced(Field->getLocation(), Destructor); 7799 CheckDestructorAccess(Field->getLocation(), Destructor, 7800 PDiag(diag::err_access_dtor_ivar) 7801 << Context.getBaseElementType(Field->getType())); 7802 } 7803 } 7804 } 7805 ObjCImplementation->setIvarInitializers(Context, 7806 AllToInit.data(), AllToInit.size()); 7807 } 7808} 7809