SemaDeclCXX.cpp revision 3cc0dda41d0513ceb56c12f37000a888a88d03c9
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 "Sema.h" 15#include "SemaInit.h" 16#include "Lookup.h" 17#include "clang/AST/ASTConsumer.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/CharUnits.h" 20#include "clang/AST/CXXInheritance.h" 21#include "clang/AST/DeclVisitor.h" 22#include "clang/AST/RecordLayout.h" 23#include "clang/AST/StmtVisitor.h" 24#include "clang/AST/TypeLoc.h" 25#include "clang/AST/TypeOrdering.h" 26#include "clang/Parse/DeclSpec.h" 27#include "clang/Parse/Template.h" 28#include "clang/Basic/PartialDiagnostic.h" 29#include "clang/Lex/Preprocessor.h" 30#include "llvm/ADT/STLExtras.h" 31#include <map> 32#include <set> 33 34using namespace clang; 35 36//===----------------------------------------------------------------------===// 37// CheckDefaultArgumentVisitor 38//===----------------------------------------------------------------------===// 39 40namespace { 41 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 42 /// the default argument of a parameter to determine whether it 43 /// contains any ill-formed subexpressions. For example, this will 44 /// diagnose the use of local variables or parameters within the 45 /// default argument expression. 46 class CheckDefaultArgumentVisitor 47 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 48 Expr *DefaultArg; 49 Sema *S; 50 51 public: 52 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 53 : DefaultArg(defarg), S(s) {} 54 55 bool VisitExpr(Expr *Node); 56 bool VisitDeclRefExpr(DeclRefExpr *DRE); 57 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 58 }; 59 60 /// VisitExpr - Visit all of the children of this expression. 61 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 62 bool IsInvalid = false; 63 for (Stmt::child_iterator I = Node->child_begin(), 64 E = Node->child_end(); I != E; ++I) 65 IsInvalid |= Visit(*I); 66 return IsInvalid; 67 } 68 69 /// VisitDeclRefExpr - Visit a reference to a declaration, to 70 /// determine whether this declaration can be used in the default 71 /// argument expression. 72 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 73 NamedDecl *Decl = DRE->getDecl(); 74 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 75 // C++ [dcl.fct.default]p9 76 // Default arguments are evaluated each time the function is 77 // called. The order of evaluation of function arguments is 78 // unspecified. Consequently, parameters of a function shall not 79 // be used in default argument expressions, even if they are not 80 // evaluated. Parameters of a function declared before a default 81 // argument expression are in scope and can hide namespace and 82 // class member names. 83 return S->Diag(DRE->getSourceRange().getBegin(), 84 diag::err_param_default_argument_references_param) 85 << Param->getDeclName() << DefaultArg->getSourceRange(); 86 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 87 // C++ [dcl.fct.default]p7 88 // Local variables shall not be used in default argument 89 // expressions. 90 if (VDecl->isBlockVarDecl()) 91 return S->Diag(DRE->getSourceRange().getBegin(), 92 diag::err_param_default_argument_references_local) 93 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 94 } 95 96 return false; 97 } 98 99 /// VisitCXXThisExpr - Visit a C++ "this" expression. 100 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 101 // C++ [dcl.fct.default]p8: 102 // The keyword this shall not be used in a default argument of a 103 // member function. 104 return S->Diag(ThisE->getSourceRange().getBegin(), 105 diag::err_param_default_argument_references_this) 106 << ThisE->getSourceRange(); 107 } 108} 109 110bool 111Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg, 112 SourceLocation EqualLoc) { 113 if (RequireCompleteType(Param->getLocation(), Param->getType(), 114 diag::err_typecheck_decl_incomplete_type)) { 115 Param->setInvalidDecl(); 116 return true; 117 } 118 119 Expr *Arg = (Expr *)DefaultArg.get(); 120 121 // C++ [dcl.fct.default]p5 122 // A default argument expression is implicitly converted (clause 123 // 4) to the parameter type. The default argument expression has 124 // the same semantic constraints as the initializer expression in 125 // a declaration of a variable of the parameter type, using the 126 // copy-initialization semantics (8.5). 127 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param); 128 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 129 EqualLoc); 130 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1); 131 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 132 MultiExprArg(*this, (void**)&Arg, 1)); 133 if (Result.isInvalid()) 134 return true; 135 Arg = Result.takeAs<Expr>(); 136 137 Arg = MaybeCreateCXXExprWithTemporaries(Arg); 138 139 // Okay: add the default argument to the parameter 140 Param->setDefaultArg(Arg); 141 142 DefaultArg.release(); 143 144 return false; 145} 146 147/// ActOnParamDefaultArgument - Check whether the default argument 148/// provided for a function parameter is well-formed. If so, attach it 149/// to the parameter declaration. 150void 151Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc, 152 ExprArg defarg) { 153 if (!param || !defarg.get()) 154 return; 155 156 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 157 UnparsedDefaultArgLocs.erase(Param); 158 159 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>()); 160 161 // Default arguments are only permitted in C++ 162 if (!getLangOptions().CPlusPlus) { 163 Diag(EqualLoc, diag::err_param_default_argument) 164 << DefaultArg->getSourceRange(); 165 Param->setInvalidDecl(); 166 return; 167 } 168 169 // Check that the default argument is well-formed 170 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 171 if (DefaultArgChecker.Visit(DefaultArg.get())) { 172 Param->setInvalidDecl(); 173 return; 174 } 175 176 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc); 177} 178 179/// ActOnParamUnparsedDefaultArgument - We've seen a default 180/// argument for a function parameter, but we can't parse it yet 181/// because we're inside a class definition. Note that this default 182/// argument will be parsed later. 183void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param, 184 SourceLocation EqualLoc, 185 SourceLocation ArgLoc) { 186 if (!param) 187 return; 188 189 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 190 if (Param) 191 Param->setUnparsedDefaultArg(); 192 193 UnparsedDefaultArgLocs[Param] = ArgLoc; 194} 195 196/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 197/// the default argument for the parameter param failed. 198void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) { 199 if (!param) 200 return; 201 202 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 203 204 Param->setInvalidDecl(); 205 206 UnparsedDefaultArgLocs.erase(Param); 207} 208 209/// CheckExtraCXXDefaultArguments - Check for any extra default 210/// arguments in the declarator, which is not a function declaration 211/// or definition and therefore is not permitted to have default 212/// arguments. This routine should be invoked for every declarator 213/// that is not a function declaration or definition. 214void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 215 // C++ [dcl.fct.default]p3 216 // A default argument expression shall be specified only in the 217 // parameter-declaration-clause of a function declaration or in a 218 // template-parameter (14.1). It shall not be specified for a 219 // parameter pack. If it is specified in a 220 // parameter-declaration-clause, it shall not occur within a 221 // declarator or abstract-declarator of a parameter-declaration. 222 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 223 DeclaratorChunk &chunk = D.getTypeObject(i); 224 if (chunk.Kind == DeclaratorChunk::Function) { 225 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 226 ParmVarDecl *Param = 227 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>()); 228 if (Param->hasUnparsedDefaultArg()) { 229 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 230 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 231 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 232 delete Toks; 233 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 234 } else if (Param->getDefaultArg()) { 235 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 236 << Param->getDefaultArg()->getSourceRange(); 237 Param->setDefaultArg(0); 238 } 239 } 240 } 241 } 242} 243 244// MergeCXXFunctionDecl - Merge two declarations of the same C++ 245// function, once we already know that they have the same 246// type. Subroutine of MergeFunctionDecl. Returns true if there was an 247// error, false otherwise. 248bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 249 bool Invalid = false; 250 251 // C++ [dcl.fct.default]p4: 252 // For non-template functions, default arguments can be added in 253 // later declarations of a function in the same 254 // scope. Declarations in different scopes have completely 255 // distinct sets of default arguments. That is, declarations in 256 // inner scopes do not acquire default arguments from 257 // declarations in outer scopes, and vice versa. In a given 258 // function declaration, all parameters subsequent to a 259 // parameter with a default argument shall have default 260 // arguments supplied in this or previous declarations. A 261 // default argument shall not be redefined by a later 262 // declaration (not even to the same value). 263 // 264 // C++ [dcl.fct.default]p6: 265 // Except for member functions of class templates, the default arguments 266 // in a member function definition that appears outside of the class 267 // definition are added to the set of default arguments provided by the 268 // member function declaration in the class definition. 269 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 270 ParmVarDecl *OldParam = Old->getParamDecl(p); 271 ParmVarDecl *NewParam = New->getParamDecl(p); 272 273 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) { 274 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 275 // hint here. Alternatively, we could walk the type-source information 276 // for NewParam to find the last source location in the type... but it 277 // isn't worth the effort right now. This is the kind of test case that 278 // is hard to get right: 279 280 // int f(int); 281 // void g(int (*fp)(int) = f); 282 // void g(int (*fp)(int) = &f); 283 Diag(NewParam->getLocation(), 284 diag::err_param_default_argument_redefinition) 285 << NewParam->getDefaultArgRange(); 286 287 // Look for the function declaration where the default argument was 288 // actually written, which may be a declaration prior to Old. 289 for (FunctionDecl *Older = Old->getPreviousDeclaration(); 290 Older; Older = Older->getPreviousDeclaration()) { 291 if (!Older->getParamDecl(p)->hasDefaultArg()) 292 break; 293 294 OldParam = Older->getParamDecl(p); 295 } 296 297 Diag(OldParam->getLocation(), diag::note_previous_definition) 298 << OldParam->getDefaultArgRange(); 299 Invalid = true; 300 } else if (OldParam->hasDefaultArg()) { 301 // Merge the old default argument into the new parameter. 302 // It's important to use getInit() here; getDefaultArg() 303 // strips off any top-level CXXExprWithTemporaries. 304 NewParam->setHasInheritedDefaultArg(); 305 if (OldParam->hasUninstantiatedDefaultArg()) 306 NewParam->setUninstantiatedDefaultArg( 307 OldParam->getUninstantiatedDefaultArg()); 308 else 309 NewParam->setDefaultArg(OldParam->getInit()); 310 } else if (NewParam->hasDefaultArg()) { 311 if (New->getDescribedFunctionTemplate()) { 312 // Paragraph 4, quoted above, only applies to non-template functions. 313 Diag(NewParam->getLocation(), 314 diag::err_param_default_argument_template_redecl) 315 << NewParam->getDefaultArgRange(); 316 Diag(Old->getLocation(), diag::note_template_prev_declaration) 317 << false; 318 } else if (New->getTemplateSpecializationKind() 319 != TSK_ImplicitInstantiation && 320 New->getTemplateSpecializationKind() != TSK_Undeclared) { 321 // C++ [temp.expr.spec]p21: 322 // Default function arguments shall not be specified in a declaration 323 // or a definition for one of the following explicit specializations: 324 // - the explicit specialization of a function template; 325 // - the explicit specialization of a member function template; 326 // - the explicit specialization of a member function of a class 327 // template where the class template specialization to which the 328 // member function specialization belongs is implicitly 329 // instantiated. 330 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 331 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 332 << New->getDeclName() 333 << NewParam->getDefaultArgRange(); 334 } else if (New->getDeclContext()->isDependentContext()) { 335 // C++ [dcl.fct.default]p6 (DR217): 336 // Default arguments for a member function of a class template shall 337 // be specified on the initial declaration of the member function 338 // within the class template. 339 // 340 // Reading the tea leaves a bit in DR217 and its reference to DR205 341 // leads me to the conclusion that one cannot add default function 342 // arguments for an out-of-line definition of a member function of a 343 // dependent type. 344 int WhichKind = 2; 345 if (CXXRecordDecl *Record 346 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 347 if (Record->getDescribedClassTemplate()) 348 WhichKind = 0; 349 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 350 WhichKind = 1; 351 else 352 WhichKind = 2; 353 } 354 355 Diag(NewParam->getLocation(), 356 diag::err_param_default_argument_member_template_redecl) 357 << WhichKind 358 << NewParam->getDefaultArgRange(); 359 } 360 } 361 } 362 363 if (CheckEquivalentExceptionSpec(Old, New)) 364 Invalid = true; 365 366 return Invalid; 367} 368 369/// CheckCXXDefaultArguments - Verify that the default arguments for a 370/// function declaration are well-formed according to C++ 371/// [dcl.fct.default]. 372void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 373 unsigned NumParams = FD->getNumParams(); 374 unsigned p; 375 376 // Find first parameter with a default argument 377 for (p = 0; p < NumParams; ++p) { 378 ParmVarDecl *Param = FD->getParamDecl(p); 379 if (Param->hasDefaultArg()) 380 break; 381 } 382 383 // C++ [dcl.fct.default]p4: 384 // In a given function declaration, all parameters 385 // subsequent to a parameter with a default argument shall 386 // have default arguments supplied in this or previous 387 // declarations. A default argument shall not be redefined 388 // by a later declaration (not even to the same value). 389 unsigned LastMissingDefaultArg = 0; 390 for (; p < NumParams; ++p) { 391 ParmVarDecl *Param = FD->getParamDecl(p); 392 if (!Param->hasDefaultArg()) { 393 if (Param->isInvalidDecl()) 394 /* We already complained about this parameter. */; 395 else if (Param->getIdentifier()) 396 Diag(Param->getLocation(), 397 diag::err_param_default_argument_missing_name) 398 << Param->getIdentifier(); 399 else 400 Diag(Param->getLocation(), 401 diag::err_param_default_argument_missing); 402 403 LastMissingDefaultArg = p; 404 } 405 } 406 407 if (LastMissingDefaultArg > 0) { 408 // Some default arguments were missing. Clear out all of the 409 // default arguments up to (and including) the last missing 410 // default argument, so that we leave the function parameters 411 // in a semantically valid state. 412 for (p = 0; p <= LastMissingDefaultArg; ++p) { 413 ParmVarDecl *Param = FD->getParamDecl(p); 414 if (Param->hasDefaultArg()) { 415 if (!Param->hasUnparsedDefaultArg()) 416 Param->getDefaultArg()->Destroy(Context); 417 Param->setDefaultArg(0); 418 } 419 } 420 } 421} 422 423/// isCurrentClassName - Determine whether the identifier II is the 424/// name of the class type currently being defined. In the case of 425/// nested classes, this will only return true if II is the name of 426/// the innermost class. 427bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 428 const CXXScopeSpec *SS) { 429 assert(getLangOptions().CPlusPlus && "No class names in C!"); 430 431 CXXRecordDecl *CurDecl; 432 if (SS && SS->isSet() && !SS->isInvalid()) { 433 DeclContext *DC = computeDeclContext(*SS, true); 434 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 435 } else 436 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 437 438 if (CurDecl && CurDecl->getIdentifier()) 439 return &II == CurDecl->getIdentifier(); 440 else 441 return false; 442} 443 444/// \brief Check the validity of a C++ base class specifier. 445/// 446/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 447/// and returns NULL otherwise. 448CXXBaseSpecifier * 449Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 450 SourceRange SpecifierRange, 451 bool Virtual, AccessSpecifier Access, 452 QualType BaseType, 453 SourceLocation BaseLoc) { 454 // C++ [class.union]p1: 455 // A union shall not have base classes. 456 if (Class->isUnion()) { 457 Diag(Class->getLocation(), diag::err_base_clause_on_union) 458 << SpecifierRange; 459 return 0; 460 } 461 462 if (BaseType->isDependentType()) 463 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 464 Class->getTagKind() == TTK_Class, 465 Access, BaseType); 466 467 // Base specifiers must be record types. 468 if (!BaseType->isRecordType()) { 469 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 470 return 0; 471 } 472 473 // C++ [class.union]p1: 474 // A union shall not be used as a base class. 475 if (BaseType->isUnionType()) { 476 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 477 return 0; 478 } 479 480 // C++ [class.derived]p2: 481 // The class-name in a base-specifier shall not be an incompletely 482 // defined class. 483 if (RequireCompleteType(BaseLoc, BaseType, 484 PDiag(diag::err_incomplete_base_class) 485 << SpecifierRange)) 486 return 0; 487 488 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 489 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 490 assert(BaseDecl && "Record type has no declaration"); 491 BaseDecl = BaseDecl->getDefinition(); 492 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 493 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 494 assert(CXXBaseDecl && "Base type is not a C++ type"); 495 496 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases. 497 if (CXXBaseDecl->hasAttr<FinalAttr>()) { 498 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString(); 499 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl) 500 << BaseType; 501 return 0; 502 } 503 504 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual); 505 506 // Create the base specifier. 507 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 508 Class->getTagKind() == TTK_Class, 509 Access, BaseType); 510} 511 512void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class, 513 const CXXRecordDecl *BaseClass, 514 bool BaseIsVirtual) { 515 // A class with a non-empty base class is not empty. 516 // FIXME: Standard ref? 517 if (!BaseClass->isEmpty()) 518 Class->setEmpty(false); 519 520 // C++ [class.virtual]p1: 521 // A class that [...] inherits a virtual function is called a polymorphic 522 // class. 523 if (BaseClass->isPolymorphic()) 524 Class->setPolymorphic(true); 525 526 // C++ [dcl.init.aggr]p1: 527 // An aggregate is [...] a class with [...] no base classes [...]. 528 Class->setAggregate(false); 529 530 // C++ [class]p4: 531 // A POD-struct is an aggregate class... 532 Class->setPOD(false); 533 534 if (BaseIsVirtual) { 535 // C++ [class.ctor]p5: 536 // A constructor is trivial if its class has no virtual base classes. 537 Class->setHasTrivialConstructor(false); 538 539 // C++ [class.copy]p6: 540 // A copy constructor is trivial if its class has no virtual base classes. 541 Class->setHasTrivialCopyConstructor(false); 542 543 // C++ [class.copy]p11: 544 // A copy assignment operator is trivial if its class has no virtual 545 // base classes. 546 Class->setHasTrivialCopyAssignment(false); 547 548 // C++0x [meta.unary.prop] is_empty: 549 // T is a class type, but not a union type, with ... no virtual base 550 // classes 551 Class->setEmpty(false); 552 } else { 553 // C++ [class.ctor]p5: 554 // A constructor is trivial if all the direct base classes of its 555 // class have trivial constructors. 556 if (!BaseClass->hasTrivialConstructor()) 557 Class->setHasTrivialConstructor(false); 558 559 // C++ [class.copy]p6: 560 // A copy constructor is trivial if all the direct base classes of its 561 // class have trivial copy constructors. 562 if (!BaseClass->hasTrivialCopyConstructor()) 563 Class->setHasTrivialCopyConstructor(false); 564 565 // C++ [class.copy]p11: 566 // A copy assignment operator is trivial if all the direct base classes 567 // of its class have trivial copy assignment operators. 568 if (!BaseClass->hasTrivialCopyAssignment()) 569 Class->setHasTrivialCopyAssignment(false); 570 } 571 572 // C++ [class.ctor]p3: 573 // A destructor is trivial if all the direct base classes of its class 574 // have trivial destructors. 575 if (!BaseClass->hasTrivialDestructor()) 576 Class->setHasTrivialDestructor(false); 577} 578 579/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 580/// one entry in the base class list of a class specifier, for 581/// example: 582/// class foo : public bar, virtual private baz { 583/// 'public bar' and 'virtual private baz' are each base-specifiers. 584Sema::BaseResult 585Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange, 586 bool Virtual, AccessSpecifier Access, 587 TypeTy *basetype, SourceLocation BaseLoc) { 588 if (!classdecl) 589 return true; 590 591 AdjustDeclIfTemplate(classdecl); 592 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>()); 593 if (!Class) 594 return true; 595 596 QualType BaseType = GetTypeFromParser(basetype); 597 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 598 Virtual, Access, 599 BaseType, BaseLoc)) 600 return BaseSpec; 601 602 return true; 603} 604 605/// \brief Performs the actual work of attaching the given base class 606/// specifiers to a C++ class. 607bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 608 unsigned NumBases) { 609 if (NumBases == 0) 610 return false; 611 612 // Used to keep track of which base types we have already seen, so 613 // that we can properly diagnose redundant direct base types. Note 614 // that the key is always the unqualified canonical type of the base 615 // class. 616 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 617 618 // Copy non-redundant base specifiers into permanent storage. 619 unsigned NumGoodBases = 0; 620 bool Invalid = false; 621 for (unsigned idx = 0; idx < NumBases; ++idx) { 622 QualType NewBaseType 623 = Context.getCanonicalType(Bases[idx]->getType()); 624 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 625 if (!Class->hasObjectMember()) { 626 if (const RecordType *FDTTy = 627 NewBaseType.getTypePtr()->getAs<RecordType>()) 628 if (FDTTy->getDecl()->hasObjectMember()) 629 Class->setHasObjectMember(true); 630 } 631 632 if (KnownBaseTypes[NewBaseType]) { 633 // C++ [class.mi]p3: 634 // A class shall not be specified as a direct base class of a 635 // derived class more than once. 636 Diag(Bases[idx]->getSourceRange().getBegin(), 637 diag::err_duplicate_base_class) 638 << KnownBaseTypes[NewBaseType]->getType() 639 << Bases[idx]->getSourceRange(); 640 641 // Delete the duplicate base class specifier; we're going to 642 // overwrite its pointer later. 643 Context.Deallocate(Bases[idx]); 644 645 Invalid = true; 646 } else { 647 // Okay, add this new base class. 648 KnownBaseTypes[NewBaseType] = Bases[idx]; 649 Bases[NumGoodBases++] = Bases[idx]; 650 } 651 } 652 653 // Attach the remaining base class specifiers to the derived class. 654 Class->setBases(Bases, NumGoodBases); 655 656 // Delete the remaining (good) base class specifiers, since their 657 // data has been copied into the CXXRecordDecl. 658 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 659 Context.Deallocate(Bases[idx]); 660 661 return Invalid; 662} 663 664/// ActOnBaseSpecifiers - Attach the given base specifiers to the 665/// class, after checking whether there are any duplicate base 666/// classes. 667void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases, 668 unsigned NumBases) { 669 if (!ClassDecl || !Bases || !NumBases) 670 return; 671 672 AdjustDeclIfTemplate(ClassDecl); 673 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()), 674 (CXXBaseSpecifier**)(Bases), NumBases); 675} 676 677static CXXRecordDecl *GetClassForType(QualType T) { 678 if (const RecordType *RT = T->getAs<RecordType>()) 679 return cast<CXXRecordDecl>(RT->getDecl()); 680 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>()) 681 return ICT->getDecl(); 682 else 683 return 0; 684} 685 686/// \brief Determine whether the type \p Derived is a C++ class that is 687/// derived from the type \p Base. 688bool Sema::IsDerivedFrom(QualType Derived, QualType Base) { 689 if (!getLangOptions().CPlusPlus) 690 return false; 691 692 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 693 if (!DerivedRD) 694 return false; 695 696 CXXRecordDecl *BaseRD = GetClassForType(Base); 697 if (!BaseRD) 698 return false; 699 700 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this. 701 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD); 702} 703 704/// \brief Determine whether the type \p Derived is a C++ class that is 705/// derived from the type \p Base. 706bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) { 707 if (!getLangOptions().CPlusPlus) 708 return false; 709 710 CXXRecordDecl *DerivedRD = GetClassForType(Derived); 711 if (!DerivedRD) 712 return false; 713 714 CXXRecordDecl *BaseRD = GetClassForType(Base); 715 if (!BaseRD) 716 return false; 717 718 return DerivedRD->isDerivedFrom(BaseRD, Paths); 719} 720 721void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 722 CXXBaseSpecifierArray &BasePathArray) { 723 assert(BasePathArray.empty() && "Base path array must be empty!"); 724 assert(Paths.isRecordingPaths() && "Must record paths!"); 725 726 const CXXBasePath &Path = Paths.front(); 727 728 // We first go backward and check if we have a virtual base. 729 // FIXME: It would be better if CXXBasePath had the base specifier for 730 // the nearest virtual base. 731 unsigned Start = 0; 732 for (unsigned I = Path.size(); I != 0; --I) { 733 if (Path[I - 1].Base->isVirtual()) { 734 Start = I - 1; 735 break; 736 } 737 } 738 739 // Now add all bases. 740 for (unsigned I = Start, E = Path.size(); I != E; ++I) 741 BasePathArray.push_back(Path[I].Base); 742} 743 744/// \brief Determine whether the given base path includes a virtual 745/// base class. 746bool Sema::BasePathInvolvesVirtualBase(const CXXBaseSpecifierArray &BasePath) { 747 for (CXXBaseSpecifierArray::iterator B = BasePath.begin(), 748 BEnd = BasePath.end(); 749 B != BEnd; ++B) 750 if ((*B)->isVirtual()) 751 return true; 752 753 return false; 754} 755 756/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 757/// conversion (where Derived and Base are class types) is 758/// well-formed, meaning that the conversion is unambiguous (and 759/// that all of the base classes are accessible). Returns true 760/// and emits a diagnostic if the code is ill-formed, returns false 761/// otherwise. Loc is the location where this routine should point to 762/// if there is an error, and Range is the source range to highlight 763/// if there is an error. 764bool 765Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 766 unsigned InaccessibleBaseID, 767 unsigned AmbigiousBaseConvID, 768 SourceLocation Loc, SourceRange Range, 769 DeclarationName Name, 770 CXXBaseSpecifierArray *BasePath) { 771 // First, determine whether the path from Derived to Base is 772 // ambiguous. This is slightly more expensive than checking whether 773 // the Derived to Base conversion exists, because here we need to 774 // explore multiple paths to determine if there is an ambiguity. 775 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 776 /*DetectVirtual=*/false); 777 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths); 778 assert(DerivationOkay && 779 "Can only be used with a derived-to-base conversion"); 780 (void)DerivationOkay; 781 782 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) { 783 if (InaccessibleBaseID) { 784 // Check that the base class can be accessed. 785 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(), 786 InaccessibleBaseID)) { 787 case AR_inaccessible: 788 return true; 789 case AR_accessible: 790 case AR_dependent: 791 case AR_delayed: 792 break; 793 } 794 } 795 796 // Build a base path if necessary. 797 if (BasePath) 798 BuildBasePathArray(Paths, *BasePath); 799 return false; 800 } 801 802 // We know that the derived-to-base conversion is ambiguous, and 803 // we're going to produce a diagnostic. Perform the derived-to-base 804 // search just one more time to compute all of the possible paths so 805 // that we can print them out. This is more expensive than any of 806 // the previous derived-to-base checks we've done, but at this point 807 // performance isn't as much of an issue. 808 Paths.clear(); 809 Paths.setRecordingPaths(true); 810 bool StillOkay = IsDerivedFrom(Derived, Base, Paths); 811 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 812 (void)StillOkay; 813 814 // Build up a textual representation of the ambiguous paths, e.g., 815 // D -> B -> A, that will be used to illustrate the ambiguous 816 // conversions in the diagnostic. We only print one of the paths 817 // to each base class subobject. 818 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 819 820 Diag(Loc, AmbigiousBaseConvID) 821 << Derived << Base << PathDisplayStr << Range << Name; 822 return true; 823} 824 825bool 826Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 827 SourceLocation Loc, SourceRange Range, 828 CXXBaseSpecifierArray *BasePath, 829 bool IgnoreAccess) { 830 return CheckDerivedToBaseConversion(Derived, Base, 831 IgnoreAccess ? 0 832 : diag::err_upcast_to_inaccessible_base, 833 diag::err_ambiguous_derived_to_base_conv, 834 Loc, Range, DeclarationName(), 835 BasePath); 836} 837 838 839/// @brief Builds a string representing ambiguous paths from a 840/// specific derived class to different subobjects of the same base 841/// class. 842/// 843/// This function builds a string that can be used in error messages 844/// to show the different paths that one can take through the 845/// inheritance hierarchy to go from the derived class to different 846/// subobjects of a base class. The result looks something like this: 847/// @code 848/// struct D -> struct B -> struct A 849/// struct D -> struct C -> struct A 850/// @endcode 851std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 852 std::string PathDisplayStr; 853 std::set<unsigned> DisplayedPaths; 854 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 855 Path != Paths.end(); ++Path) { 856 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 857 // We haven't displayed a path to this particular base 858 // class subobject yet. 859 PathDisplayStr += "\n "; 860 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 861 for (CXXBasePath::const_iterator Element = Path->begin(); 862 Element != Path->end(); ++Element) 863 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 864 } 865 } 866 867 return PathDisplayStr; 868} 869 870//===----------------------------------------------------------------------===// 871// C++ class member Handling 872//===----------------------------------------------------------------------===// 873 874/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 875/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 876/// bitfield width if there is one and 'InitExpr' specifies the initializer if 877/// any. 878Sema::DeclPtrTy 879Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 880 MultiTemplateParamsArg TemplateParameterLists, 881 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition, 882 bool Deleted) { 883 const DeclSpec &DS = D.getDeclSpec(); 884 DeclarationName Name = GetNameForDeclarator(D); 885 Expr *BitWidth = static_cast<Expr*>(BW); 886 Expr *Init = static_cast<Expr*>(InitExpr); 887 SourceLocation Loc = D.getIdentifierLoc(); 888 889 assert(isa<CXXRecordDecl>(CurContext)); 890 assert(!DS.isFriendSpecified()); 891 892 bool isFunc = false; 893 if (D.isFunctionDeclarator()) 894 isFunc = true; 895 else if (D.getNumTypeObjects() == 0 && 896 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) { 897 QualType TDType = GetTypeFromParser(DS.getTypeRep()); 898 isFunc = TDType->isFunctionType(); 899 } 900 901 // C++ 9.2p6: A member shall not be declared to have automatic storage 902 // duration (auto, register) or with the extern storage-class-specifier. 903 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 904 // data members and cannot be applied to names declared const or static, 905 // and cannot be applied to reference members. 906 switch (DS.getStorageClassSpec()) { 907 case DeclSpec::SCS_unspecified: 908 case DeclSpec::SCS_typedef: 909 case DeclSpec::SCS_static: 910 // FALL THROUGH. 911 break; 912 case DeclSpec::SCS_mutable: 913 if (isFunc) { 914 if (DS.getStorageClassSpecLoc().isValid()) 915 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 916 else 917 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 918 919 // FIXME: It would be nicer if the keyword was ignored only for this 920 // declarator. Otherwise we could get follow-up errors. 921 D.getMutableDeclSpec().ClearStorageClassSpecs(); 922 } 923 break; 924 default: 925 if (DS.getStorageClassSpecLoc().isValid()) 926 Diag(DS.getStorageClassSpecLoc(), 927 diag::err_storageclass_invalid_for_member); 928 else 929 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 930 D.getMutableDeclSpec().ClearStorageClassSpecs(); 931 } 932 933 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 934 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 935 !isFunc); 936 937 Decl *Member; 938 if (isInstField) { 939 // FIXME: Check for template parameters! 940 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 941 AS); 942 assert(Member && "HandleField never returns null"); 943 } else { 944 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition) 945 .getAs<Decl>(); 946 if (!Member) { 947 if (BitWidth) DeleteExpr(BitWidth); 948 return DeclPtrTy(); 949 } 950 951 // Non-instance-fields can't have a bitfield. 952 if (BitWidth) { 953 if (Member->isInvalidDecl()) { 954 // don't emit another diagnostic. 955 } else if (isa<VarDecl>(Member)) { 956 // C++ 9.6p3: A bit-field shall not be a static member. 957 // "static member 'A' cannot be a bit-field" 958 Diag(Loc, diag::err_static_not_bitfield) 959 << Name << BitWidth->getSourceRange(); 960 } else if (isa<TypedefDecl>(Member)) { 961 // "typedef member 'x' cannot be a bit-field" 962 Diag(Loc, diag::err_typedef_not_bitfield) 963 << Name << BitWidth->getSourceRange(); 964 } else { 965 // A function typedef ("typedef int f(); f a;"). 966 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 967 Diag(Loc, diag::err_not_integral_type_bitfield) 968 << Name << cast<ValueDecl>(Member)->getType() 969 << BitWidth->getSourceRange(); 970 } 971 972 DeleteExpr(BitWidth); 973 BitWidth = 0; 974 Member->setInvalidDecl(); 975 } 976 977 Member->setAccess(AS); 978 979 // If we have declared a member function template, set the access of the 980 // templated declaration as well. 981 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 982 FunTmpl->getTemplatedDecl()->setAccess(AS); 983 } 984 985 assert((Name || isInstField) && "No identifier for non-field ?"); 986 987 if (Init) 988 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false); 989 if (Deleted) // FIXME: Source location is not very good. 990 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin()); 991 992 if (isInstField) { 993 FieldCollector->Add(cast<FieldDecl>(Member)); 994 return DeclPtrTy(); 995 } 996 return DeclPtrTy::make(Member); 997} 998 999/// \brief Find the direct and/or virtual base specifiers that 1000/// correspond to the given base type, for use in base initialization 1001/// within a constructor. 1002static bool FindBaseInitializer(Sema &SemaRef, 1003 CXXRecordDecl *ClassDecl, 1004 QualType BaseType, 1005 const CXXBaseSpecifier *&DirectBaseSpec, 1006 const CXXBaseSpecifier *&VirtualBaseSpec) { 1007 // First, check for a direct base class. 1008 DirectBaseSpec = 0; 1009 for (CXXRecordDecl::base_class_const_iterator Base 1010 = ClassDecl->bases_begin(); 1011 Base != ClassDecl->bases_end(); ++Base) { 1012 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) { 1013 // We found a direct base of this type. That's what we're 1014 // initializing. 1015 DirectBaseSpec = &*Base; 1016 break; 1017 } 1018 } 1019 1020 // Check for a virtual base class. 1021 // FIXME: We might be able to short-circuit this if we know in advance that 1022 // there are no virtual bases. 1023 VirtualBaseSpec = 0; 1024 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 1025 // We haven't found a base yet; search the class hierarchy for a 1026 // virtual base class. 1027 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 1028 /*DetectVirtual=*/false); 1029 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 1030 BaseType, Paths)) { 1031 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 1032 Path != Paths.end(); ++Path) { 1033 if (Path->back().Base->isVirtual()) { 1034 VirtualBaseSpec = Path->back().Base; 1035 break; 1036 } 1037 } 1038 } 1039 } 1040 1041 return DirectBaseSpec || VirtualBaseSpec; 1042} 1043 1044/// ActOnMemInitializer - Handle a C++ member initializer. 1045Sema::MemInitResult 1046Sema::ActOnMemInitializer(DeclPtrTy ConstructorD, 1047 Scope *S, 1048 CXXScopeSpec &SS, 1049 IdentifierInfo *MemberOrBase, 1050 TypeTy *TemplateTypeTy, 1051 SourceLocation IdLoc, 1052 SourceLocation LParenLoc, 1053 ExprTy **Args, unsigned NumArgs, 1054 SourceLocation *CommaLocs, 1055 SourceLocation RParenLoc) { 1056 if (!ConstructorD) 1057 return true; 1058 1059 AdjustDeclIfTemplate(ConstructorD); 1060 1061 CXXConstructorDecl *Constructor 1062 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>()); 1063 if (!Constructor) { 1064 // The user wrote a constructor initializer on a function that is 1065 // not a C++ constructor. Ignore the error for now, because we may 1066 // have more member initializers coming; we'll diagnose it just 1067 // once in ActOnMemInitializers. 1068 return true; 1069 } 1070 1071 CXXRecordDecl *ClassDecl = Constructor->getParent(); 1072 1073 // C++ [class.base.init]p2: 1074 // Names in a mem-initializer-id are looked up in the scope of the 1075 // constructor’s class and, if not found in that scope, are looked 1076 // up in the scope containing the constructor’s 1077 // definition. [Note: if the constructor’s class contains a member 1078 // with the same name as a direct or virtual base class of the 1079 // class, a mem-initializer-id naming the member or base class and 1080 // composed of a single identifier refers to the class member. A 1081 // mem-initializer-id for the hidden base class may be specified 1082 // using a qualified name. ] 1083 if (!SS.getScopeRep() && !TemplateTypeTy) { 1084 // Look for a member, first. 1085 FieldDecl *Member = 0; 1086 DeclContext::lookup_result Result 1087 = ClassDecl->lookup(MemberOrBase); 1088 if (Result.first != Result.second) 1089 Member = dyn_cast<FieldDecl>(*Result.first); 1090 1091 // FIXME: Handle members of an anonymous union. 1092 1093 if (Member) 1094 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1095 LParenLoc, RParenLoc); 1096 } 1097 // It didn't name a member, so see if it names a class. 1098 QualType BaseType; 1099 TypeSourceInfo *TInfo = 0; 1100 1101 if (TemplateTypeTy) { 1102 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 1103 } else { 1104 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 1105 LookupParsedName(R, S, &SS); 1106 1107 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 1108 if (!TyD) { 1109 if (R.isAmbiguous()) return true; 1110 1111 // We don't want access-control diagnostics here. 1112 R.suppressDiagnostics(); 1113 1114 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 1115 bool NotUnknownSpecialization = false; 1116 DeclContext *DC = computeDeclContext(SS, false); 1117 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 1118 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 1119 1120 if (!NotUnknownSpecialization) { 1121 // When the scope specifier can refer to a member of an unknown 1122 // specialization, we take it as a type name. 1123 BaseType = CheckTypenameType(ETK_None, 1124 (NestedNameSpecifier *)SS.getScopeRep(), 1125 *MemberOrBase, SourceLocation(), 1126 SS.getRange(), IdLoc); 1127 if (BaseType.isNull()) 1128 return true; 1129 1130 R.clear(); 1131 } 1132 } 1133 1134 // If no results were found, try to correct typos. 1135 if (R.empty() && BaseType.isNull() && 1136 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) && 1137 R.isSingleResult()) { 1138 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) { 1139 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) { 1140 // We have found a non-static data member with a similar 1141 // name to what was typed; complain and initialize that 1142 // member. 1143 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1144 << MemberOrBase << true << R.getLookupName() 1145 << FixItHint::CreateReplacement(R.getNameLoc(), 1146 R.getLookupName().getAsString()); 1147 Diag(Member->getLocation(), diag::note_previous_decl) 1148 << Member->getDeclName(); 1149 1150 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 1151 LParenLoc, RParenLoc); 1152 } 1153 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) { 1154 const CXXBaseSpecifier *DirectBaseSpec; 1155 const CXXBaseSpecifier *VirtualBaseSpec; 1156 if (FindBaseInitializer(*this, ClassDecl, 1157 Context.getTypeDeclType(Type), 1158 DirectBaseSpec, VirtualBaseSpec)) { 1159 // We have found a direct or virtual base class with a 1160 // similar name to what was typed; complain and initialize 1161 // that base class. 1162 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest) 1163 << MemberOrBase << false << R.getLookupName() 1164 << FixItHint::CreateReplacement(R.getNameLoc(), 1165 R.getLookupName().getAsString()); 1166 1167 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec 1168 : VirtualBaseSpec; 1169 Diag(BaseSpec->getSourceRange().getBegin(), 1170 diag::note_base_class_specified_here) 1171 << BaseSpec->getType() 1172 << BaseSpec->getSourceRange(); 1173 1174 TyD = Type; 1175 } 1176 } 1177 } 1178 1179 if (!TyD && BaseType.isNull()) { 1180 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 1181 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 1182 return true; 1183 } 1184 } 1185 1186 if (BaseType.isNull()) { 1187 BaseType = Context.getTypeDeclType(TyD); 1188 if (SS.isSet()) { 1189 NestedNameSpecifier *Qualifier = 1190 static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1191 1192 // FIXME: preserve source range information 1193 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType); 1194 } 1195 } 1196 } 1197 1198 if (!TInfo) 1199 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 1200 1201 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs, 1202 LParenLoc, RParenLoc, ClassDecl); 1203} 1204 1205/// Checks an initializer expression for use of uninitialized fields, such as 1206/// containing the field that is being initialized. Returns true if there is an 1207/// uninitialized field was used an updates the SourceLocation parameter; false 1208/// otherwise. 1209static bool InitExprContainsUninitializedFields(const Stmt* S, 1210 const FieldDecl* LhsField, 1211 SourceLocation* L) { 1212 const MemberExpr* ME = dyn_cast<MemberExpr>(S); 1213 if (ME) { 1214 const NamedDecl* RhsField = ME->getMemberDecl(); 1215 if (RhsField == LhsField) { 1216 // Initializing a field with itself. Throw a warning. 1217 // But wait; there are exceptions! 1218 // Exception #1: The field may not belong to this record. 1219 // e.g. Foo(const Foo& rhs) : A(rhs.A) {} 1220 const Expr* base = ME->getBase(); 1221 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) { 1222 // Even though the field matches, it does not belong to this record. 1223 return false; 1224 } 1225 // None of the exceptions triggered; return true to indicate an 1226 // uninitialized field was used. 1227 *L = ME->getMemberLoc(); 1228 return true; 1229 } 1230 } 1231 bool found = false; 1232 for (Stmt::const_child_iterator it = S->child_begin(); 1233 it != S->child_end() && found == false; 1234 ++it) { 1235 if (isa<CallExpr>(S)) { 1236 // Do not descend into function calls or constructors, as the use 1237 // of an uninitialized field may be valid. One would have to inspect 1238 // the contents of the function/ctor to determine if it is safe or not. 1239 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers 1240 // may be safe, depending on what the function/ctor does. 1241 continue; 1242 } 1243 found = InitExprContainsUninitializedFields(*it, LhsField, L); 1244 } 1245 return found; 1246} 1247 1248Sema::MemInitResult 1249Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args, 1250 unsigned NumArgs, SourceLocation IdLoc, 1251 SourceLocation LParenLoc, 1252 SourceLocation RParenLoc) { 1253 // Diagnose value-uses of fields to initialize themselves, e.g. 1254 // foo(foo) 1255 // where foo is not also a parameter to the constructor. 1256 // TODO: implement -Wuninitialized and fold this into that framework. 1257 for (unsigned i = 0; i < NumArgs; ++i) { 1258 SourceLocation L; 1259 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) { 1260 // FIXME: Return true in the case when other fields are used before being 1261 // uninitialized. For example, let this field be the i'th field. When 1262 // initializing the i'th field, throw a warning if any of the >= i'th 1263 // fields are used, as they are not yet initialized. 1264 // Right now we are only handling the case where the i'th field uses 1265 // itself in its initializer. 1266 Diag(L, diag::warn_field_is_uninit); 1267 } 1268 } 1269 1270 bool HasDependentArg = false; 1271 for (unsigned i = 0; i < NumArgs; i++) 1272 HasDependentArg |= Args[i]->isTypeDependent(); 1273 1274 QualType FieldType = Member->getType(); 1275 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 1276 FieldType = Array->getElementType(); 1277 if (FieldType->isDependentType() || HasDependentArg) { 1278 // Can't check initialization for a member of dependent type or when 1279 // any of the arguments are type-dependent expressions. 1280 OwningExprResult Init 1281 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1282 RParenLoc)); 1283 1284 // Erase any temporaries within this evaluation context; we're not 1285 // going to track them in the AST, since we'll be rebuilding the 1286 // ASTs during template instantiation. 1287 ExprTemporaries.erase( 1288 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1289 ExprTemporaries.end()); 1290 1291 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 1292 LParenLoc, 1293 Init.takeAs<Expr>(), 1294 RParenLoc); 1295 1296 } 1297 1298 if (Member->isInvalidDecl()) 1299 return true; 1300 1301 // Initialize the member. 1302 InitializedEntity MemberEntity = 1303 InitializedEntity::InitializeMember(Member, 0); 1304 InitializationKind Kind = 1305 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc); 1306 1307 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs); 1308 1309 OwningExprResult MemberInit = 1310 InitSeq.Perform(*this, MemberEntity, Kind, 1311 MultiExprArg(*this, (void**)Args, NumArgs), 0); 1312 if (MemberInit.isInvalid()) 1313 return true; 1314 1315 // C++0x [class.base.init]p7: 1316 // The initialization of each base and member constitutes a 1317 // full-expression. 1318 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit)); 1319 if (MemberInit.isInvalid()) 1320 return true; 1321 1322 // If we are in a dependent context, template instantiation will 1323 // perform this type-checking again. Just save the arguments that we 1324 // received in a ParenListExpr. 1325 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1326 // of the information that we have about the member 1327 // initializer. However, deconstructing the ASTs is a dicey process, 1328 // and this approach is far more likely to get the corner cases right. 1329 if (CurContext->isDependentContext()) { 1330 // Bump the reference count of all of the arguments. 1331 for (unsigned I = 0; I != NumArgs; ++I) 1332 Args[I]->Retain(); 1333 1334 OwningExprResult Init 1335 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1336 RParenLoc)); 1337 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 1338 LParenLoc, 1339 Init.takeAs<Expr>(), 1340 RParenLoc); 1341 } 1342 1343 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc, 1344 LParenLoc, 1345 MemberInit.takeAs<Expr>(), 1346 RParenLoc); 1347} 1348 1349Sema::MemInitResult 1350Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 1351 Expr **Args, unsigned NumArgs, 1352 SourceLocation LParenLoc, SourceLocation RParenLoc, 1353 CXXRecordDecl *ClassDecl) { 1354 bool HasDependentArg = false; 1355 for (unsigned i = 0; i < NumArgs; i++) 1356 HasDependentArg |= Args[i]->isTypeDependent(); 1357 1358 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 1359 if (BaseType->isDependentType() || HasDependentArg) { 1360 // Can't check initialization for a base of dependent type or when 1361 // any of the arguments are type-dependent expressions. 1362 OwningExprResult BaseInit 1363 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1364 RParenLoc)); 1365 1366 // Erase any temporaries within this evaluation context; we're not 1367 // going to track them in the AST, since we'll be rebuilding the 1368 // ASTs during template instantiation. 1369 ExprTemporaries.erase( 1370 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries, 1371 ExprTemporaries.end()); 1372 1373 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1374 /*IsVirtual=*/false, 1375 LParenLoc, 1376 BaseInit.takeAs<Expr>(), 1377 RParenLoc); 1378 } 1379 1380 if (!BaseType->isRecordType()) 1381 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 1382 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1383 1384 // C++ [class.base.init]p2: 1385 // [...] Unless the mem-initializer-id names a nonstatic data 1386 // member of the constructor’s class or a direct or virtual base 1387 // of that class, the mem-initializer is ill-formed. A 1388 // mem-initializer-list can initialize a base class using any 1389 // name that denotes that base class type. 1390 1391 // Check for direct and virtual base classes. 1392 const CXXBaseSpecifier *DirectBaseSpec = 0; 1393 const CXXBaseSpecifier *VirtualBaseSpec = 0; 1394 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 1395 VirtualBaseSpec); 1396 1397 // C++ [base.class.init]p2: 1398 // If a mem-initializer-id is ambiguous because it designates both 1399 // a direct non-virtual base class and an inherited virtual base 1400 // class, the mem-initializer is ill-formed. 1401 if (DirectBaseSpec && VirtualBaseSpec) 1402 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 1403 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1404 // C++ [base.class.init]p2: 1405 // Unless the mem-initializer-id names a nonstatic data membeer of the 1406 // constructor's class ot a direst or virtual base of that class, the 1407 // mem-initializer is ill-formed. 1408 if (!DirectBaseSpec && !VirtualBaseSpec) 1409 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 1410 << BaseType << Context.getTypeDeclType(ClassDecl) 1411 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 1412 1413 CXXBaseSpecifier *BaseSpec 1414 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec); 1415 if (!BaseSpec) 1416 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec); 1417 1418 // Initialize the base. 1419 InitializedEntity BaseEntity = 1420 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 1421 InitializationKind Kind = 1422 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc); 1423 1424 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs); 1425 1426 OwningExprResult BaseInit = 1427 InitSeq.Perform(*this, BaseEntity, Kind, 1428 MultiExprArg(*this, (void**)Args, NumArgs), 0); 1429 if (BaseInit.isInvalid()) 1430 return true; 1431 1432 // C++0x [class.base.init]p7: 1433 // The initialization of each base and member constitutes a 1434 // full-expression. 1435 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit)); 1436 if (BaseInit.isInvalid()) 1437 return true; 1438 1439 // If we are in a dependent context, template instantiation will 1440 // perform this type-checking again. Just save the arguments that we 1441 // received in a ParenListExpr. 1442 // FIXME: This isn't quite ideal, since our ASTs don't capture all 1443 // of the information that we have about the base 1444 // initializer. However, deconstructing the ASTs is a dicey process, 1445 // and this approach is far more likely to get the corner cases right. 1446 if (CurContext->isDependentContext()) { 1447 // Bump the reference count of all of the arguments. 1448 for (unsigned I = 0; I != NumArgs; ++I) 1449 Args[I]->Retain(); 1450 1451 OwningExprResult Init 1452 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs, 1453 RParenLoc)); 1454 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1455 BaseSpec->isVirtual(), 1456 LParenLoc, 1457 Init.takeAs<Expr>(), 1458 RParenLoc); 1459 } 1460 1461 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo, 1462 BaseSpec->isVirtual(), 1463 LParenLoc, 1464 BaseInit.takeAs<Expr>(), 1465 RParenLoc); 1466} 1467 1468/// ImplicitInitializerKind - How an implicit base or member initializer should 1469/// initialize its base or member. 1470enum ImplicitInitializerKind { 1471 IIK_Default, 1472 IIK_Copy, 1473 IIK_Move 1474}; 1475 1476static bool 1477BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 1478 ImplicitInitializerKind ImplicitInitKind, 1479 CXXBaseSpecifier *BaseSpec, 1480 bool IsInheritedVirtualBase, 1481 CXXBaseOrMemberInitializer *&CXXBaseInit) { 1482 InitializedEntity InitEntity 1483 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 1484 IsInheritedVirtualBase); 1485 1486 Sema::OwningExprResult BaseInit(SemaRef); 1487 1488 switch (ImplicitInitKind) { 1489 case IIK_Default: { 1490 InitializationKind InitKind 1491 = InitializationKind::CreateDefault(Constructor->getLocation()); 1492 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 1493 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 1494 Sema::MultiExprArg(SemaRef, 0, 0)); 1495 break; 1496 } 1497 1498 case IIK_Copy: { 1499 ParmVarDecl *Param = Constructor->getParamDecl(0); 1500 QualType ParamType = Param->getType().getNonReferenceType(); 1501 1502 Expr *CopyCtorArg = 1503 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param, 1504 Constructor->getLocation(), ParamType, 0); 1505 1506 // Cast to the base class to avoid ambiguities. 1507 QualType ArgTy = 1508 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 1509 ParamType.getQualifiers()); 1510 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 1511 CastExpr::CK_UncheckedDerivedToBase, 1512 /*isLvalue=*/true, 1513 CXXBaseSpecifierArray(BaseSpec)); 1514 1515 InitializationKind InitKind 1516 = InitializationKind::CreateDirect(Constructor->getLocation(), 1517 SourceLocation(), SourceLocation()); 1518 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 1519 &CopyCtorArg, 1); 1520 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, 1521 Sema::MultiExprArg(SemaRef, 1522 (void**)&CopyCtorArg, 1)); 1523 break; 1524 } 1525 1526 case IIK_Move: 1527 assert(false && "Unhandled initializer kind!"); 1528 } 1529 1530 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit)); 1531 if (BaseInit.isInvalid()) 1532 return true; 1533 1534 CXXBaseInit = 1535 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context, 1536 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 1537 SourceLocation()), 1538 BaseSpec->isVirtual(), 1539 SourceLocation(), 1540 BaseInit.takeAs<Expr>(), 1541 SourceLocation()); 1542 1543 return false; 1544} 1545 1546static bool 1547BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 1548 ImplicitInitializerKind ImplicitInitKind, 1549 FieldDecl *Field, 1550 CXXBaseOrMemberInitializer *&CXXMemberInit) { 1551 if (Field->isInvalidDecl()) 1552 return true; 1553 1554 if (ImplicitInitKind == IIK_Copy) { 1555 SourceLocation Loc = Constructor->getLocation(); 1556 ParmVarDecl *Param = Constructor->getParamDecl(0); 1557 QualType ParamType = Param->getType().getNonReferenceType(); 1558 1559 Expr *MemberExprBase = 1560 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param, 1561 Loc, ParamType, 0); 1562 1563 // Build a reference to this field within the parameter. 1564 CXXScopeSpec SS; 1565 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 1566 Sema::LookupMemberName); 1567 MemberLookup.addDecl(Field, AS_public); 1568 MemberLookup.resolveKind(); 1569 Sema::OwningExprResult CopyCtorArg 1570 = SemaRef.BuildMemberReferenceExpr(SemaRef.Owned(MemberExprBase), 1571 ParamType, Loc, 1572 /*IsArrow=*/false, 1573 SS, 1574 /*FirstQualifierInScope=*/0, 1575 MemberLookup, 1576 /*TemplateArgs=*/0); 1577 if (CopyCtorArg.isInvalid()) 1578 return true; 1579 1580 // When the field we are copying is an array, create index variables for 1581 // each dimension of the array. We use these index variables to subscript 1582 // the source array, and other clients (e.g., CodeGen) will perform the 1583 // necessary iteration with these index variables. 1584 llvm::SmallVector<VarDecl *, 4> IndexVariables; 1585 QualType BaseType = Field->getType(); 1586 QualType SizeType = SemaRef.Context.getSizeType(); 1587 while (const ConstantArrayType *Array 1588 = SemaRef.Context.getAsConstantArrayType(BaseType)) { 1589 // Create the iteration variable for this array index. 1590 IdentifierInfo *IterationVarName = 0; 1591 { 1592 llvm::SmallString<8> Str; 1593 llvm::raw_svector_ostream OS(Str); 1594 OS << "__i" << IndexVariables.size(); 1595 IterationVarName = &SemaRef.Context.Idents.get(OS.str()); 1596 } 1597 VarDecl *IterationVar 1598 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, 1599 IterationVarName, SizeType, 1600 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc), 1601 VarDecl::None, VarDecl::None); 1602 IndexVariables.push_back(IterationVar); 1603 1604 // Create a reference to the iteration variable. 1605 Sema::OwningExprResult IterationVarRef 1606 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc); 1607 assert(!IterationVarRef.isInvalid() && 1608 "Reference to invented variable cannot fail!"); 1609 1610 // Subscript the array with this iteration variable. 1611 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(move(CopyCtorArg), 1612 Loc, 1613 move(IterationVarRef), 1614 Loc); 1615 if (CopyCtorArg.isInvalid()) 1616 return true; 1617 1618 BaseType = Array->getElementType(); 1619 } 1620 1621 // Construct the entity that we will be initializing. For an array, this 1622 // will be first element in the array, which may require several levels 1623 // of array-subscript entities. 1624 llvm::SmallVector<InitializedEntity, 4> Entities; 1625 Entities.reserve(1 + IndexVariables.size()); 1626 Entities.push_back(InitializedEntity::InitializeMember(Field)); 1627 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 1628 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context, 1629 0, 1630 Entities.back())); 1631 1632 // Direct-initialize to use the copy constructor. 1633 InitializationKind InitKind = 1634 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 1635 1636 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>(); 1637 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, 1638 &CopyCtorArgE, 1); 1639 1640 Sema::OwningExprResult MemberInit 1641 = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 1642 Sema::MultiExprArg(SemaRef, (void**)&CopyCtorArgE, 1)); 1643 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit)); 1644 if (MemberInit.isInvalid()) 1645 return true; 1646 1647 CXXMemberInit 1648 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc, 1649 MemberInit.takeAs<Expr>(), Loc, 1650 IndexVariables.data(), 1651 IndexVariables.size()); 1652 return false; 1653 } 1654 1655 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!"); 1656 1657 QualType FieldBaseElementType = 1658 SemaRef.Context.getBaseElementType(Field->getType()); 1659 1660 if (FieldBaseElementType->isRecordType()) { 1661 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 1662 InitializationKind InitKind = 1663 InitializationKind::CreateDefault(Constructor->getLocation()); 1664 1665 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0); 1666 Sema::OwningExprResult MemberInit = 1667 InitSeq.Perform(SemaRef, InitEntity, InitKind, 1668 Sema::MultiExprArg(SemaRef, 0, 0)); 1669 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit)); 1670 if (MemberInit.isInvalid()) 1671 return true; 1672 1673 CXXMemberInit = 1674 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context, 1675 Field, SourceLocation(), 1676 SourceLocation(), 1677 MemberInit.takeAs<Expr>(), 1678 SourceLocation()); 1679 return false; 1680 } 1681 1682 if (FieldBaseElementType->isReferenceType()) { 1683 SemaRef.Diag(Constructor->getLocation(), 1684 diag::err_uninitialized_member_in_ctor) 1685 << (int)Constructor->isImplicit() 1686 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 1687 << 0 << Field->getDeclName(); 1688 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 1689 return true; 1690 } 1691 1692 if (FieldBaseElementType.isConstQualified()) { 1693 SemaRef.Diag(Constructor->getLocation(), 1694 diag::err_uninitialized_member_in_ctor) 1695 << (int)Constructor->isImplicit() 1696 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 1697 << 1 << Field->getDeclName(); 1698 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 1699 return true; 1700 } 1701 1702 // Nothing to initialize. 1703 CXXMemberInit = 0; 1704 return false; 1705} 1706 1707namespace { 1708struct BaseAndFieldInfo { 1709 Sema &S; 1710 CXXConstructorDecl *Ctor; 1711 bool AnyErrorsInInits; 1712 ImplicitInitializerKind IIK; 1713 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields; 1714 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit; 1715 1716 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 1717 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 1718 // FIXME: Handle implicit move constructors. 1719 if (Ctor->isImplicit() && Ctor->isCopyConstructor()) 1720 IIK = IIK_Copy; 1721 else 1722 IIK = IIK_Default; 1723 } 1724}; 1725} 1726 1727static bool CollectFieldInitializer(BaseAndFieldInfo &Info, 1728 FieldDecl *Top, FieldDecl *Field) { 1729 1730 // Overwhelmingly common case: we have a direct initializer for this field. 1731 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) { 1732 Info.AllToInit.push_back(Init); 1733 1734 if (Field != Top) { 1735 Init->setMember(Top); 1736 Init->setAnonUnionMember(Field); 1737 } 1738 return false; 1739 } 1740 1741 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) { 1742 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>(); 1743 assert(FieldClassType && "anonymous struct/union without record type"); 1744 1745 // Walk through the members, tying in any initializers for fields 1746 // we find. The earlier semantic checks should prevent redundant 1747 // initialization of union members, given the requirement that 1748 // union members never have non-trivial default constructors. 1749 1750 // TODO: in C++0x, it might be legal to have union members with 1751 // non-trivial default constructors in unions. Revise this 1752 // implementation then with the appropriate semantics. 1753 CXXRecordDecl *FieldClassDecl 1754 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1755 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 1756 EA = FieldClassDecl->field_end(); FA != EA; FA++) 1757 if (CollectFieldInitializer(Info, Top, *FA)) 1758 return true; 1759 } 1760 1761 // Don't try to build an implicit initializer if there were semantic 1762 // errors in any of the initializers (and therefore we might be 1763 // missing some that the user actually wrote). 1764 if (Info.AnyErrorsInInits) 1765 return false; 1766 1767 CXXBaseOrMemberInitializer *Init = 0; 1768 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init)) 1769 return true; 1770 1771 // If the member doesn't need to be initialized, Init will still be null. 1772 if (!Init) return false; 1773 1774 Info.AllToInit.push_back(Init); 1775 if (Top != Field) { 1776 Init->setMember(Top); 1777 Init->setAnonUnionMember(Field); 1778 } 1779 return false; 1780} 1781 1782bool 1783Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor, 1784 CXXBaseOrMemberInitializer **Initializers, 1785 unsigned NumInitializers, 1786 bool AnyErrors) { 1787 if (Constructor->getDeclContext()->isDependentContext()) { 1788 // Just store the initializers as written, they will be checked during 1789 // instantiation. 1790 if (NumInitializers > 0) { 1791 Constructor->setNumBaseOrMemberInitializers(NumInitializers); 1792 CXXBaseOrMemberInitializer **baseOrMemberInitializers = 1793 new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 1794 memcpy(baseOrMemberInitializers, Initializers, 1795 NumInitializers * sizeof(CXXBaseOrMemberInitializer*)); 1796 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 1797 } 1798 1799 return false; 1800 } 1801 1802 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 1803 1804 // We need to build the initializer AST according to order of construction 1805 // and not what user specified in the Initializers list. 1806 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 1807 if (!ClassDecl) 1808 return true; 1809 1810 bool HadError = false; 1811 1812 for (unsigned i = 0; i < NumInitializers; i++) { 1813 CXXBaseOrMemberInitializer *Member = Initializers[i]; 1814 1815 if (Member->isBaseInitializer()) 1816 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 1817 else 1818 Info.AllBaseFields[Member->getMember()] = Member; 1819 } 1820 1821 // Keep track of the direct virtual bases. 1822 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 1823 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(), 1824 E = ClassDecl->bases_end(); I != E; ++I) { 1825 if (I->isVirtual()) 1826 DirectVBases.insert(I); 1827 } 1828 1829 // Push virtual bases before others. 1830 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 1831 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 1832 1833 if (CXXBaseOrMemberInitializer *Value 1834 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 1835 Info.AllToInit.push_back(Value); 1836 } else if (!AnyErrors) { 1837 bool IsInheritedVirtualBase = !DirectVBases.count(VBase); 1838 CXXBaseOrMemberInitializer *CXXBaseInit; 1839 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 1840 VBase, IsInheritedVirtualBase, 1841 CXXBaseInit)) { 1842 HadError = true; 1843 continue; 1844 } 1845 1846 Info.AllToInit.push_back(CXXBaseInit); 1847 } 1848 } 1849 1850 // Non-virtual bases. 1851 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 1852 E = ClassDecl->bases_end(); Base != E; ++Base) { 1853 // Virtuals are in the virtual base list and already constructed. 1854 if (Base->isVirtual()) 1855 continue; 1856 1857 if (CXXBaseOrMemberInitializer *Value 1858 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 1859 Info.AllToInit.push_back(Value); 1860 } else if (!AnyErrors) { 1861 CXXBaseOrMemberInitializer *CXXBaseInit; 1862 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 1863 Base, /*IsInheritedVirtualBase=*/false, 1864 CXXBaseInit)) { 1865 HadError = true; 1866 continue; 1867 } 1868 1869 Info.AllToInit.push_back(CXXBaseInit); 1870 } 1871 } 1872 1873 // Fields. 1874 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1875 E = ClassDecl->field_end(); Field != E; ++Field) { 1876 if ((*Field)->getType()->isIncompleteArrayType()) { 1877 assert(ClassDecl->hasFlexibleArrayMember() && 1878 "Incomplete array type is not valid"); 1879 continue; 1880 } 1881 if (CollectFieldInitializer(Info, *Field, *Field)) 1882 HadError = true; 1883 } 1884 1885 NumInitializers = Info.AllToInit.size(); 1886 if (NumInitializers > 0) { 1887 Constructor->setNumBaseOrMemberInitializers(NumInitializers); 1888 CXXBaseOrMemberInitializer **baseOrMemberInitializers = 1889 new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 1890 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 1891 NumInitializers * sizeof(CXXBaseOrMemberInitializer*)); 1892 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 1893 1894 // Constructors implicitly reference the base and member 1895 // destructors. 1896 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 1897 Constructor->getParent()); 1898 } 1899 1900 return HadError; 1901} 1902 1903static void *GetKeyForTopLevelField(FieldDecl *Field) { 1904 // For anonymous unions, use the class declaration as the key. 1905 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 1906 if (RT->getDecl()->isAnonymousStructOrUnion()) 1907 return static_cast<void *>(RT->getDecl()); 1908 } 1909 return static_cast<void *>(Field); 1910} 1911 1912static void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 1913 return Context.getCanonicalType(BaseType).getTypePtr(); 1914} 1915 1916static void *GetKeyForMember(ASTContext &Context, 1917 CXXBaseOrMemberInitializer *Member, 1918 bool MemberMaybeAnon = false) { 1919 if (!Member->isMemberInitializer()) 1920 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 1921 1922 // For fields injected into the class via declaration of an anonymous union, 1923 // use its anonymous union class declaration as the unique key. 1924 FieldDecl *Field = Member->getMember(); 1925 1926 // After SetBaseOrMemberInitializers call, Field is the anonymous union 1927 // data member of the class. Data member used in the initializer list is 1928 // in AnonUnionMember field. 1929 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion()) 1930 Field = Member->getAnonUnionMember(); 1931 1932 // If the field is a member of an anonymous struct or union, our key 1933 // is the anonymous record decl that's a direct child of the class. 1934 RecordDecl *RD = Field->getParent(); 1935 if (RD->isAnonymousStructOrUnion()) { 1936 while (true) { 1937 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext()); 1938 if (Parent->isAnonymousStructOrUnion()) 1939 RD = Parent; 1940 else 1941 break; 1942 } 1943 1944 return static_cast<void *>(RD); 1945 } 1946 1947 return static_cast<void *>(Field); 1948} 1949 1950static void 1951DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, 1952 const CXXConstructorDecl *Constructor, 1953 CXXBaseOrMemberInitializer **Inits, 1954 unsigned NumInits) { 1955 if (Constructor->getDeclContext()->isDependentContext()) 1956 return; 1957 1958 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order) 1959 == Diagnostic::Ignored) 1960 return; 1961 1962 // Build the list of bases and members in the order that they'll 1963 // actually be initialized. The explicit initializers should be in 1964 // this same order but may be missing things. 1965 llvm::SmallVector<const void*, 32> IdealInitKeys; 1966 1967 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 1968 1969 // 1. Virtual bases. 1970 for (CXXRecordDecl::base_class_const_iterator VBase = 1971 ClassDecl->vbases_begin(), 1972 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 1973 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType())); 1974 1975 // 2. Non-virtual bases. 1976 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(), 1977 E = ClassDecl->bases_end(); Base != E; ++Base) { 1978 if (Base->isVirtual()) 1979 continue; 1980 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType())); 1981 } 1982 1983 // 3. Direct fields. 1984 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1985 E = ClassDecl->field_end(); Field != E; ++Field) 1986 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field)); 1987 1988 unsigned NumIdealInits = IdealInitKeys.size(); 1989 unsigned IdealIndex = 0; 1990 1991 CXXBaseOrMemberInitializer *PrevInit = 0; 1992 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) { 1993 CXXBaseOrMemberInitializer *Init = Inits[InitIndex]; 1994 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true); 1995 1996 // Scan forward to try to find this initializer in the idealized 1997 // initializers list. 1998 for (; IdealIndex != NumIdealInits; ++IdealIndex) 1999 if (InitKey == IdealInitKeys[IdealIndex]) 2000 break; 2001 2002 // If we didn't find this initializer, it must be because we 2003 // scanned past it on a previous iteration. That can only 2004 // happen if we're out of order; emit a warning. 2005 if (IdealIndex == NumIdealInits && PrevInit) { 2006 Sema::SemaDiagnosticBuilder D = 2007 SemaRef.Diag(PrevInit->getSourceLocation(), 2008 diag::warn_initializer_out_of_order); 2009 2010 if (PrevInit->isMemberInitializer()) 2011 D << 0 << PrevInit->getMember()->getDeclName(); 2012 else 2013 D << 1 << PrevInit->getBaseClassInfo()->getType(); 2014 2015 if (Init->isMemberInitializer()) 2016 D << 0 << Init->getMember()->getDeclName(); 2017 else 2018 D << 1 << Init->getBaseClassInfo()->getType(); 2019 2020 // Move back to the initializer's location in the ideal list. 2021 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 2022 if (InitKey == IdealInitKeys[IdealIndex]) 2023 break; 2024 2025 assert(IdealIndex != NumIdealInits && 2026 "initializer not found in initializer list"); 2027 } 2028 2029 PrevInit = Init; 2030 } 2031} 2032 2033namespace { 2034bool CheckRedundantInit(Sema &S, 2035 CXXBaseOrMemberInitializer *Init, 2036 CXXBaseOrMemberInitializer *&PrevInit) { 2037 if (!PrevInit) { 2038 PrevInit = Init; 2039 return false; 2040 } 2041 2042 if (FieldDecl *Field = Init->getMember()) 2043 S.Diag(Init->getSourceLocation(), 2044 diag::err_multiple_mem_initialization) 2045 << Field->getDeclName() 2046 << Init->getSourceRange(); 2047 else { 2048 Type *BaseClass = Init->getBaseClass(); 2049 assert(BaseClass && "neither field nor base"); 2050 S.Diag(Init->getSourceLocation(), 2051 diag::err_multiple_base_initialization) 2052 << QualType(BaseClass, 0) 2053 << Init->getSourceRange(); 2054 } 2055 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 2056 << 0 << PrevInit->getSourceRange(); 2057 2058 return true; 2059} 2060 2061typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry; 2062typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 2063 2064bool CheckRedundantUnionInit(Sema &S, 2065 CXXBaseOrMemberInitializer *Init, 2066 RedundantUnionMap &Unions) { 2067 FieldDecl *Field = Init->getMember(); 2068 RecordDecl *Parent = Field->getParent(); 2069 if (!Parent->isAnonymousStructOrUnion()) 2070 return false; 2071 2072 NamedDecl *Child = Field; 2073 do { 2074 if (Parent->isUnion()) { 2075 UnionEntry &En = Unions[Parent]; 2076 if (En.first && En.first != Child) { 2077 S.Diag(Init->getSourceLocation(), 2078 diag::err_multiple_mem_union_initialization) 2079 << Field->getDeclName() 2080 << Init->getSourceRange(); 2081 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 2082 << 0 << En.second->getSourceRange(); 2083 return true; 2084 } else if (!En.first) { 2085 En.first = Child; 2086 En.second = Init; 2087 } 2088 } 2089 2090 Child = Parent; 2091 Parent = cast<RecordDecl>(Parent->getDeclContext()); 2092 } while (Parent->isAnonymousStructOrUnion()); 2093 2094 return false; 2095} 2096} 2097 2098/// ActOnMemInitializers - Handle the member initializers for a constructor. 2099void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl, 2100 SourceLocation ColonLoc, 2101 MemInitTy **meminits, unsigned NumMemInits, 2102 bool AnyErrors) { 2103 if (!ConstructorDecl) 2104 return; 2105 2106 AdjustDeclIfTemplate(ConstructorDecl); 2107 2108 CXXConstructorDecl *Constructor 2109 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>()); 2110 2111 if (!Constructor) { 2112 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 2113 return; 2114 } 2115 2116 CXXBaseOrMemberInitializer **MemInits = 2117 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits); 2118 2119 // Mapping for the duplicate initializers check. 2120 // For member initializers, this is keyed with a FieldDecl*. 2121 // For base initializers, this is keyed with a Type*. 2122 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members; 2123 2124 // Mapping for the inconsistent anonymous-union initializers check. 2125 RedundantUnionMap MemberUnions; 2126 2127 bool HadError = false; 2128 for (unsigned i = 0; i < NumMemInits; i++) { 2129 CXXBaseOrMemberInitializer *Init = MemInits[i]; 2130 2131 // Set the source order index. 2132 Init->setSourceOrder(i); 2133 2134 if (Init->isMemberInitializer()) { 2135 FieldDecl *Field = Init->getMember(); 2136 if (CheckRedundantInit(*this, Init, Members[Field]) || 2137 CheckRedundantUnionInit(*this, Init, MemberUnions)) 2138 HadError = true; 2139 } else { 2140 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0)); 2141 if (CheckRedundantInit(*this, Init, Members[Key])) 2142 HadError = true; 2143 } 2144 } 2145 2146 if (HadError) 2147 return; 2148 2149 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits); 2150 2151 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors); 2152} 2153 2154void 2155Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 2156 CXXRecordDecl *ClassDecl) { 2157 // Ignore dependent contexts. 2158 if (ClassDecl->isDependentContext()) 2159 return; 2160 2161 // FIXME: all the access-control diagnostics are positioned on the 2162 // field/base declaration. That's probably good; that said, the 2163 // user might reasonably want to know why the destructor is being 2164 // emitted, and we currently don't say. 2165 2166 // Non-static data members. 2167 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 2168 E = ClassDecl->field_end(); I != E; ++I) { 2169 FieldDecl *Field = *I; 2170 if (Field->isInvalidDecl()) 2171 continue; 2172 QualType FieldType = Context.getBaseElementType(Field->getType()); 2173 2174 const RecordType* RT = FieldType->getAs<RecordType>(); 2175 if (!RT) 2176 continue; 2177 2178 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2179 if (FieldClassDecl->hasTrivialDestructor()) 2180 continue; 2181 2182 CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context); 2183 CheckDestructorAccess(Field->getLocation(), Dtor, 2184 PDiag(diag::err_access_dtor_field) 2185 << Field->getDeclName() 2186 << FieldType); 2187 2188 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2189 } 2190 2191 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 2192 2193 // Bases. 2194 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2195 E = ClassDecl->bases_end(); Base != E; ++Base) { 2196 // Bases are always records in a well-formed non-dependent class. 2197 const RecordType *RT = Base->getType()->getAs<RecordType>(); 2198 2199 // Remember direct virtual bases. 2200 if (Base->isVirtual()) 2201 DirectVirtualBases.insert(RT); 2202 2203 // Ignore trivial destructors. 2204 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2205 if (BaseClassDecl->hasTrivialDestructor()) 2206 continue; 2207 2208 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context); 2209 2210 // FIXME: caret should be on the start of the class name 2211 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor, 2212 PDiag(diag::err_access_dtor_base) 2213 << Base->getType() 2214 << Base->getSourceRange()); 2215 2216 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2217 } 2218 2219 // Virtual bases. 2220 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 2221 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 2222 2223 // Bases are always records in a well-formed non-dependent class. 2224 const RecordType *RT = VBase->getType()->getAs<RecordType>(); 2225 2226 // Ignore direct virtual bases. 2227 if (DirectVirtualBases.count(RT)) 2228 continue; 2229 2230 // Ignore trivial destructors. 2231 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 2232 if (BaseClassDecl->hasTrivialDestructor()) 2233 continue; 2234 2235 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context); 2236 CheckDestructorAccess(ClassDecl->getLocation(), Dtor, 2237 PDiag(diag::err_access_dtor_vbase) 2238 << VBase->getType()); 2239 2240 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor)); 2241 } 2242} 2243 2244void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) { 2245 if (!CDtorDecl) 2246 return; 2247 2248 if (CXXConstructorDecl *Constructor 2249 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>())) 2250 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false); 2251} 2252 2253bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2254 unsigned DiagID, AbstractDiagSelID SelID, 2255 const CXXRecordDecl *CurrentRD) { 2256 if (SelID == -1) 2257 return RequireNonAbstractType(Loc, T, 2258 PDiag(DiagID), CurrentRD); 2259 else 2260 return RequireNonAbstractType(Loc, T, 2261 PDiag(DiagID) << SelID, CurrentRD); 2262} 2263 2264bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 2265 const PartialDiagnostic &PD, 2266 const CXXRecordDecl *CurrentRD) { 2267 if (!getLangOptions().CPlusPlus) 2268 return false; 2269 2270 if (const ArrayType *AT = Context.getAsArrayType(T)) 2271 return RequireNonAbstractType(Loc, AT->getElementType(), PD, 2272 CurrentRD); 2273 2274 if (const PointerType *PT = T->getAs<PointerType>()) { 2275 // Find the innermost pointer type. 2276 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 2277 PT = T; 2278 2279 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 2280 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD); 2281 } 2282 2283 const RecordType *RT = T->getAs<RecordType>(); 2284 if (!RT) 2285 return false; 2286 2287 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 2288 2289 if (CurrentRD && CurrentRD != RD) 2290 return false; 2291 2292 // FIXME: is this reasonable? It matches current behavior, but.... 2293 if (!RD->getDefinition()) 2294 return false; 2295 2296 if (!RD->isAbstract()) 2297 return false; 2298 2299 Diag(Loc, PD) << RD->getDeclName(); 2300 2301 // Check if we've already emitted the list of pure virtual functions for this 2302 // class. 2303 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 2304 return true; 2305 2306 CXXFinalOverriderMap FinalOverriders; 2307 RD->getFinalOverriders(FinalOverriders); 2308 2309 // Keep a set of seen pure methods so we won't diagnose the same method 2310 // more than once. 2311 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 2312 2313 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 2314 MEnd = FinalOverriders.end(); 2315 M != MEnd; 2316 ++M) { 2317 for (OverridingMethods::iterator SO = M->second.begin(), 2318 SOEnd = M->second.end(); 2319 SO != SOEnd; ++SO) { 2320 // C++ [class.abstract]p4: 2321 // A class is abstract if it contains or inherits at least one 2322 // pure virtual function for which the final overrider is pure 2323 // virtual. 2324 2325 // 2326 if (SO->second.size() != 1) 2327 continue; 2328 2329 if (!SO->second.front().Method->isPure()) 2330 continue; 2331 2332 if (!SeenPureMethods.insert(SO->second.front().Method)) 2333 continue; 2334 2335 Diag(SO->second.front().Method->getLocation(), 2336 diag::note_pure_virtual_function) 2337 << SO->second.front().Method->getDeclName(); 2338 } 2339 } 2340 2341 if (!PureVirtualClassDiagSet) 2342 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 2343 PureVirtualClassDiagSet->insert(RD); 2344 2345 return true; 2346} 2347 2348namespace { 2349 class AbstractClassUsageDiagnoser 2350 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> { 2351 Sema &SemaRef; 2352 CXXRecordDecl *AbstractClass; 2353 2354 bool VisitDeclContext(const DeclContext *DC) { 2355 bool Invalid = false; 2356 2357 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(), 2358 E = DC->decls_end(); I != E; ++I) 2359 Invalid |= Visit(*I); 2360 2361 return Invalid; 2362 } 2363 2364 public: 2365 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac) 2366 : SemaRef(SemaRef), AbstractClass(ac) { 2367 Visit(SemaRef.Context.getTranslationUnitDecl()); 2368 } 2369 2370 bool VisitFunctionDecl(const FunctionDecl *FD) { 2371 if (FD->isThisDeclarationADefinition()) { 2372 // No need to do the check if we're in a definition, because it requires 2373 // that the return/param types are complete. 2374 // because that requires 2375 return VisitDeclContext(FD); 2376 } 2377 2378 // Check the return type. 2379 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType(); 2380 bool Invalid = 2381 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy, 2382 diag::err_abstract_type_in_decl, 2383 Sema::AbstractReturnType, 2384 AbstractClass); 2385 2386 for (FunctionDecl::param_const_iterator I = FD->param_begin(), 2387 E = FD->param_end(); I != E; ++I) { 2388 const ParmVarDecl *VD = *I; 2389 Invalid |= 2390 SemaRef.RequireNonAbstractType(VD->getLocation(), 2391 VD->getOriginalType(), 2392 diag::err_abstract_type_in_decl, 2393 Sema::AbstractParamType, 2394 AbstractClass); 2395 } 2396 2397 return Invalid; 2398 } 2399 2400 bool VisitDecl(const Decl* D) { 2401 if (const DeclContext *DC = dyn_cast<DeclContext>(D)) 2402 return VisitDeclContext(DC); 2403 2404 return false; 2405 } 2406 }; 2407} 2408 2409/// \brief Perform semantic checks on a class definition that has been 2410/// completing, introducing implicitly-declared members, checking for 2411/// abstract types, etc. 2412void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 2413 if (!Record || Record->isInvalidDecl()) 2414 return; 2415 2416 if (!Record->isDependentType()) 2417 AddImplicitlyDeclaredMembersToClass(S, Record); 2418 2419 if (Record->isInvalidDecl()) 2420 return; 2421 2422 // Set access bits correctly on the directly-declared conversions. 2423 UnresolvedSetImpl *Convs = Record->getConversionFunctions(); 2424 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I) 2425 Convs->setAccess(I, (*I)->getAccess()); 2426 2427 // Determine whether we need to check for final overriders. We do 2428 // this either when there are virtual base classes (in which case we 2429 // may end up finding multiple final overriders for a given virtual 2430 // function) or any of the base classes is abstract (in which case 2431 // we might detect that this class is abstract). 2432 bool CheckFinalOverriders = false; 2433 if (Record->isPolymorphic() && !Record->isInvalidDecl() && 2434 !Record->isDependentType()) { 2435 if (Record->getNumVBases()) 2436 CheckFinalOverriders = true; 2437 else if (!Record->isAbstract()) { 2438 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(), 2439 BEnd = Record->bases_end(); 2440 B != BEnd; ++B) { 2441 CXXRecordDecl *BaseDecl 2442 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl()); 2443 if (BaseDecl->isAbstract()) { 2444 CheckFinalOverriders = true; 2445 break; 2446 } 2447 } 2448 } 2449 } 2450 2451 if (CheckFinalOverriders) { 2452 CXXFinalOverriderMap FinalOverriders; 2453 Record->getFinalOverriders(FinalOverriders); 2454 2455 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 2456 MEnd = FinalOverriders.end(); 2457 M != MEnd; ++M) { 2458 for (OverridingMethods::iterator SO = M->second.begin(), 2459 SOEnd = M->second.end(); 2460 SO != SOEnd; ++SO) { 2461 assert(SO->second.size() > 0 && 2462 "All virtual functions have overridding virtual functions"); 2463 if (SO->second.size() == 1) { 2464 // C++ [class.abstract]p4: 2465 // A class is abstract if it contains or inherits at least one 2466 // pure virtual function for which the final overrider is pure 2467 // virtual. 2468 if (SO->second.front().Method->isPure()) 2469 Record->setAbstract(true); 2470 continue; 2471 } 2472 2473 // C++ [class.virtual]p2: 2474 // In a derived class, if a virtual member function of a base 2475 // class subobject has more than one final overrider the 2476 // program is ill-formed. 2477 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 2478 << (NamedDecl *)M->first << Record; 2479 Diag(M->first->getLocation(), diag::note_overridden_virtual_function); 2480 for (OverridingMethods::overriding_iterator OM = SO->second.begin(), 2481 OMEnd = SO->second.end(); 2482 OM != OMEnd; ++OM) 2483 Diag(OM->Method->getLocation(), diag::note_final_overrider) 2484 << (NamedDecl *)M->first << OM->Method->getParent(); 2485 2486 Record->setInvalidDecl(); 2487 } 2488 } 2489 } 2490 2491 if (Record->isAbstract() && !Record->isInvalidDecl()) 2492 (void)AbstractClassUsageDiagnoser(*this, Record); 2493 2494 // If this is not an aggregate type and has no user-declared constructor, 2495 // complain about any non-static data members of reference or const scalar 2496 // type, since they will never get initializers. 2497 if (!Record->isInvalidDecl() && !Record->isDependentType() && 2498 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) { 2499 bool Complained = false; 2500 for (RecordDecl::field_iterator F = Record->field_begin(), 2501 FEnd = Record->field_end(); 2502 F != FEnd; ++F) { 2503 if (F->getType()->isReferenceType() || 2504 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 2505 if (!Complained) { 2506 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 2507 << Record->getTagKind() << Record; 2508 Complained = true; 2509 } 2510 2511 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 2512 << F->getType()->isReferenceType() 2513 << F->getDeclName(); 2514 } 2515 } 2516 } 2517 2518 if (Record->isDynamicClass()) 2519 DynamicClasses.push_back(Record); 2520} 2521 2522void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 2523 DeclPtrTy TagDecl, 2524 SourceLocation LBrac, 2525 SourceLocation RBrac, 2526 AttributeList *AttrList) { 2527 if (!TagDecl) 2528 return; 2529 2530 AdjustDeclIfTemplate(TagDecl); 2531 2532 ActOnFields(S, RLoc, TagDecl, 2533 (DeclPtrTy*)FieldCollector->getCurFields(), 2534 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList); 2535 2536 CheckCompletedCXXClass(S, 2537 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>())); 2538} 2539 2540/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 2541/// special functions, such as the default constructor, copy 2542/// constructor, or destructor, to the given C++ class (C++ 2543/// [special]p1). This routine can only be executed just before the 2544/// definition of the class is complete. 2545/// 2546/// The scope, if provided, is the class scope. 2547void Sema::AddImplicitlyDeclaredMembersToClass(Scope *S, 2548 CXXRecordDecl *ClassDecl) { 2549 CanQualType ClassType 2550 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 2551 2552 // FIXME: Implicit declarations have exception specifications, which are 2553 // the union of the specifications of the implicitly called functions. 2554 2555 if (!ClassDecl->hasUserDeclaredConstructor()) { 2556 // C++ [class.ctor]p5: 2557 // A default constructor for a class X is a constructor of class X 2558 // that can be called without an argument. If there is no 2559 // user-declared constructor for class X, a default constructor is 2560 // implicitly declared. An implicitly-declared default constructor 2561 // is an inline public member of its class. 2562 DeclarationName Name 2563 = Context.DeclarationNames.getCXXConstructorName(ClassType); 2564 CXXConstructorDecl *DefaultCon = 2565 CXXConstructorDecl::Create(Context, ClassDecl, 2566 ClassDecl->getLocation(), Name, 2567 Context.getFunctionType(Context.VoidTy, 2568 0, 0, false, 0, 2569 /*FIXME*/false, false, 2570 0, 0, 2571 FunctionType::ExtInfo()), 2572 /*TInfo=*/0, 2573 /*isExplicit=*/false, 2574 /*isInline=*/true, 2575 /*isImplicitlyDeclared=*/true); 2576 DefaultCon->setAccess(AS_public); 2577 DefaultCon->setImplicit(); 2578 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor()); 2579 if (S) 2580 PushOnScopeChains(DefaultCon, S, true); 2581 else 2582 ClassDecl->addDecl(DefaultCon); 2583 } 2584 2585 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 2586 // C++ [class.copy]p4: 2587 // If the class definition does not explicitly declare a copy 2588 // constructor, one is declared implicitly. 2589 2590 // C++ [class.copy]p5: 2591 // The implicitly-declared copy constructor for a class X will 2592 // have the form 2593 // 2594 // X::X(const X&) 2595 // 2596 // if 2597 bool HasConstCopyConstructor = true; 2598 2599 // -- each direct or virtual base class B of X has a copy 2600 // constructor whose first parameter is of type const B& or 2601 // const volatile B&, and 2602 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2603 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 2604 const CXXRecordDecl *BaseClassDecl 2605 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2606 HasConstCopyConstructor 2607 = BaseClassDecl->hasConstCopyConstructor(Context); 2608 } 2609 2610 // -- for all the nonstatic data members of X that are of a 2611 // class type M (or array thereof), each such class type 2612 // has a copy constructor whose first parameter is of type 2613 // const M& or const volatile M&. 2614 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 2615 HasConstCopyConstructor && Field != ClassDecl->field_end(); 2616 ++Field) { 2617 QualType FieldType = (*Field)->getType(); 2618 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2619 FieldType = Array->getElementType(); 2620 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2621 const CXXRecordDecl *FieldClassDecl 2622 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2623 HasConstCopyConstructor 2624 = FieldClassDecl->hasConstCopyConstructor(Context); 2625 } 2626 } 2627 2628 // Otherwise, the implicitly declared copy constructor will have 2629 // the form 2630 // 2631 // X::X(X&) 2632 QualType ArgType = ClassType; 2633 if (HasConstCopyConstructor) 2634 ArgType = ArgType.withConst(); 2635 ArgType = Context.getLValueReferenceType(ArgType); 2636 2637 // An implicitly-declared copy constructor is an inline public 2638 // member of its class. 2639 DeclarationName Name 2640 = Context.DeclarationNames.getCXXConstructorName(ClassType); 2641 CXXConstructorDecl *CopyConstructor 2642 = CXXConstructorDecl::Create(Context, ClassDecl, 2643 ClassDecl->getLocation(), Name, 2644 Context.getFunctionType(Context.VoidTy, 2645 &ArgType, 1, 2646 false, 0, 2647 /*FIXME: hasExceptionSpec*/false, 2648 false, 0, 0, 2649 FunctionType::ExtInfo()), 2650 /*TInfo=*/0, 2651 /*isExplicit=*/false, 2652 /*isInline=*/true, 2653 /*isImplicitlyDeclared=*/true); 2654 CopyConstructor->setAccess(AS_public); 2655 CopyConstructor->setImplicit(); 2656 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 2657 2658 // Add the parameter to the constructor. 2659 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 2660 ClassDecl->getLocation(), 2661 /*IdentifierInfo=*/0, 2662 ArgType, /*TInfo=*/0, 2663 VarDecl::None, 2664 VarDecl::None, 0); 2665 CopyConstructor->setParams(&FromParam, 1); 2666 if (S) 2667 PushOnScopeChains(CopyConstructor, S, true); 2668 else 2669 ClassDecl->addDecl(CopyConstructor); 2670 } 2671 2672 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 2673 // Note: The following rules are largely analoguous to the copy 2674 // constructor rules. Note that virtual bases are not taken into account 2675 // for determining the argument type of the operator. Note also that 2676 // operators taking an object instead of a reference are allowed. 2677 // 2678 // C++ [class.copy]p10: 2679 // If the class definition does not explicitly declare a copy 2680 // assignment operator, one is declared implicitly. 2681 // The implicitly-defined copy assignment operator for a class X 2682 // will have the form 2683 // 2684 // X& X::operator=(const X&) 2685 // 2686 // if 2687 bool HasConstCopyAssignment = true; 2688 2689 // -- each direct base class B of X has a copy assignment operator 2690 // whose parameter is of type const B&, const volatile B& or B, 2691 // and 2692 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2693 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) { 2694 assert(!Base->getType()->isDependentType() && 2695 "Cannot generate implicit members for class with dependent bases."); 2696 const CXXRecordDecl *BaseClassDecl 2697 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2698 const CXXMethodDecl *MD = 0; 2699 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context, 2700 MD); 2701 } 2702 2703 // -- for all the nonstatic data members of X that are of a class 2704 // type M (or array thereof), each such class type has a copy 2705 // assignment operator whose parameter is of type const M&, 2706 // const volatile M& or M. 2707 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 2708 HasConstCopyAssignment && Field != ClassDecl->field_end(); 2709 ++Field) { 2710 QualType FieldType = (*Field)->getType(); 2711 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2712 FieldType = Array->getElementType(); 2713 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2714 const CXXRecordDecl *FieldClassDecl 2715 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2716 const CXXMethodDecl *MD = 0; 2717 HasConstCopyAssignment 2718 = FieldClassDecl->hasConstCopyAssignment(Context, MD); 2719 } 2720 } 2721 2722 // Otherwise, the implicitly declared copy assignment operator will 2723 // have the form 2724 // 2725 // X& X::operator=(X&) 2726 QualType ArgType = ClassType; 2727 QualType RetType = Context.getLValueReferenceType(ArgType); 2728 if (HasConstCopyAssignment) 2729 ArgType = ArgType.withConst(); 2730 ArgType = Context.getLValueReferenceType(ArgType); 2731 2732 // An implicitly-declared copy assignment operator is an inline public 2733 // member of its class. 2734 DeclarationName Name = 2735 Context.DeclarationNames.getCXXOperatorName(OO_Equal); 2736 CXXMethodDecl *CopyAssignment = 2737 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name, 2738 Context.getFunctionType(RetType, &ArgType, 1, 2739 false, 0, 2740 /*FIXME: hasExceptionSpec*/false, 2741 false, 0, 0, 2742 FunctionType::ExtInfo()), 2743 /*TInfo=*/0, /*isStatic=*/false, 2744 /*StorageClassAsWritten=*/FunctionDecl::None, 2745 /*isInline=*/true); 2746 CopyAssignment->setAccess(AS_public); 2747 CopyAssignment->setImplicit(); 2748 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 2749 CopyAssignment->setCopyAssignment(true); 2750 2751 // Add the parameter to the operator. 2752 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 2753 ClassDecl->getLocation(), 2754 /*Id=*/0, 2755 ArgType, /*TInfo=*/0, 2756 VarDecl::None, 2757 VarDecl::None, 0); 2758 CopyAssignment->setParams(&FromParam, 1); 2759 2760 // Don't call addedAssignmentOperator. There is no way to distinguish an 2761 // implicit from an explicit assignment operator. 2762 if (S) 2763 PushOnScopeChains(CopyAssignment, S, true); 2764 else 2765 ClassDecl->addDecl(CopyAssignment); 2766 AddOverriddenMethods(ClassDecl, CopyAssignment); 2767 } 2768 2769 if (!ClassDecl->hasUserDeclaredDestructor()) { 2770 // C++ [class.dtor]p2: 2771 // If a class has no user-declared destructor, a destructor is 2772 // declared implicitly. An implicitly-declared destructor is an 2773 // inline public member of its class. 2774 QualType Ty = Context.getFunctionType(Context.VoidTy, 2775 0, 0, false, 0, 2776 /*FIXME: hasExceptionSpec*/false, 2777 false, 0, 0, FunctionType::ExtInfo()); 2778 2779 DeclarationName Name 2780 = Context.DeclarationNames.getCXXDestructorName(ClassType); 2781 CXXDestructorDecl *Destructor 2782 = CXXDestructorDecl::Create(Context, ClassDecl, 2783 ClassDecl->getLocation(), Name, Ty, 2784 /*isInline=*/true, 2785 /*isImplicitlyDeclared=*/true); 2786 Destructor->setAccess(AS_public); 2787 Destructor->setImplicit(); 2788 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 2789 if (S) 2790 PushOnScopeChains(Destructor, S, true); 2791 else 2792 ClassDecl->addDecl(Destructor); 2793 2794 // This could be uniqued if it ever proves significant. 2795 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty)); 2796 2797 AddOverriddenMethods(ClassDecl, Destructor); 2798 } 2799} 2800 2801void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) { 2802 Decl *D = TemplateD.getAs<Decl>(); 2803 if (!D) 2804 return; 2805 2806 TemplateParameterList *Params = 0; 2807 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) 2808 Params = Template->getTemplateParameters(); 2809 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 2810 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 2811 Params = PartialSpec->getTemplateParameters(); 2812 else 2813 return; 2814 2815 for (TemplateParameterList::iterator Param = Params->begin(), 2816 ParamEnd = Params->end(); 2817 Param != ParamEnd; ++Param) { 2818 NamedDecl *Named = cast<NamedDecl>(*Param); 2819 if (Named->getDeclName()) { 2820 S->AddDecl(DeclPtrTy::make(Named)); 2821 IdResolver.AddDecl(Named); 2822 } 2823 } 2824} 2825 2826void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) { 2827 if (!RecordD) return; 2828 AdjustDeclIfTemplate(RecordD); 2829 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>()); 2830 PushDeclContext(S, Record); 2831} 2832 2833void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) { 2834 if (!RecordD) return; 2835 PopDeclContext(); 2836} 2837 2838/// ActOnStartDelayedCXXMethodDeclaration - We have completed 2839/// parsing a top-level (non-nested) C++ class, and we are now 2840/// parsing those parts of the given Method declaration that could 2841/// not be parsed earlier (C++ [class.mem]p2), such as default 2842/// arguments. This action should enter the scope of the given 2843/// Method declaration as if we had just parsed the qualified method 2844/// name. However, it should not bring the parameters into scope; 2845/// that will be performed by ActOnDelayedCXXMethodParameter. 2846void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 2847} 2848 2849/// ActOnDelayedCXXMethodParameter - We've already started a delayed 2850/// C++ method declaration. We're (re-)introducing the given 2851/// function parameter into scope for use in parsing later parts of 2852/// the method declaration. For example, we could see an 2853/// ActOnParamDefaultArgument event for this parameter. 2854void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) { 2855 if (!ParamD) 2856 return; 2857 2858 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>()); 2859 2860 // If this parameter has an unparsed default argument, clear it out 2861 // to make way for the parsed default argument. 2862 if (Param->hasUnparsedDefaultArg()) 2863 Param->setDefaultArg(0); 2864 2865 S->AddDecl(DeclPtrTy::make(Param)); 2866 if (Param->getDeclName()) 2867 IdResolver.AddDecl(Param); 2868} 2869 2870/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 2871/// processing the delayed method declaration for Method. The method 2872/// declaration is now considered finished. There may be a separate 2873/// ActOnStartOfFunctionDef action later (not necessarily 2874/// immediately!) for this method, if it was also defined inside the 2875/// class body. 2876void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 2877 if (!MethodD) 2878 return; 2879 2880 AdjustDeclIfTemplate(MethodD); 2881 2882 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 2883 2884 // Now that we have our default arguments, check the constructor 2885 // again. It could produce additional diagnostics or affect whether 2886 // the class has implicitly-declared destructors, among other 2887 // things. 2888 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 2889 CheckConstructor(Constructor); 2890 2891 // Check the default arguments, which we may have added. 2892 if (!Method->isInvalidDecl()) 2893 CheckCXXDefaultArguments(Method); 2894} 2895 2896/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 2897/// the well-formedness of the constructor declarator @p D with type @p 2898/// R. If there are any errors in the declarator, this routine will 2899/// emit diagnostics and set the invalid bit to true. In any case, the type 2900/// will be updated to reflect a well-formed type for the constructor and 2901/// returned. 2902QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 2903 FunctionDecl::StorageClass &SC) { 2904 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 2905 2906 // C++ [class.ctor]p3: 2907 // A constructor shall not be virtual (10.3) or static (9.4). A 2908 // constructor can be invoked for a const, volatile or const 2909 // volatile object. A constructor shall not be declared const, 2910 // volatile, or const volatile (9.3.2). 2911 if (isVirtual) { 2912 if (!D.isInvalidType()) 2913 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2914 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 2915 << SourceRange(D.getIdentifierLoc()); 2916 D.setInvalidType(); 2917 } 2918 if (SC == FunctionDecl::Static) { 2919 if (!D.isInvalidType()) 2920 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 2921 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2922 << SourceRange(D.getIdentifierLoc()); 2923 D.setInvalidType(); 2924 SC = FunctionDecl::None; 2925 } 2926 2927 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2928 if (FTI.TypeQuals != 0) { 2929 if (FTI.TypeQuals & Qualifiers::Const) 2930 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2931 << "const" << SourceRange(D.getIdentifierLoc()); 2932 if (FTI.TypeQuals & Qualifiers::Volatile) 2933 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2934 << "volatile" << SourceRange(D.getIdentifierLoc()); 2935 if (FTI.TypeQuals & Qualifiers::Restrict) 2936 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 2937 << "restrict" << SourceRange(D.getIdentifierLoc()); 2938 } 2939 2940 // Rebuild the function type "R" without any type qualifiers (in 2941 // case any of the errors above fired) and with "void" as the 2942 // return type, since constructors don't have return types. We 2943 // *always* have to do this, because GetTypeForDeclarator will 2944 // put in a result type of "int" when none was specified. 2945 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 2946 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 2947 Proto->getNumArgs(), 2948 Proto->isVariadic(), 0, 2949 Proto->hasExceptionSpec(), 2950 Proto->hasAnyExceptionSpec(), 2951 Proto->getNumExceptions(), 2952 Proto->exception_begin(), 2953 Proto->getExtInfo()); 2954} 2955 2956/// CheckConstructor - Checks a fully-formed constructor for 2957/// well-formedness, issuing any diagnostics required. Returns true if 2958/// the constructor declarator is invalid. 2959void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 2960 CXXRecordDecl *ClassDecl 2961 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 2962 if (!ClassDecl) 2963 return Constructor->setInvalidDecl(); 2964 2965 // C++ [class.copy]p3: 2966 // A declaration of a constructor for a class X is ill-formed if 2967 // its first parameter is of type (optionally cv-qualified) X and 2968 // either there are no other parameters or else all other 2969 // parameters have default arguments. 2970 if (!Constructor->isInvalidDecl() && 2971 ((Constructor->getNumParams() == 1) || 2972 (Constructor->getNumParams() > 1 && 2973 Constructor->getParamDecl(1)->hasDefaultArg())) && 2974 Constructor->getTemplateSpecializationKind() 2975 != TSK_ImplicitInstantiation) { 2976 QualType ParamType = Constructor->getParamDecl(0)->getType(); 2977 QualType ClassTy = Context.getTagDeclType(ClassDecl); 2978 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 2979 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 2980 const char *ConstRef 2981 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 2982 : " const &"; 2983 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 2984 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 2985 2986 // FIXME: Rather that making the constructor invalid, we should endeavor 2987 // to fix the type. 2988 Constructor->setInvalidDecl(); 2989 } 2990 } 2991 2992 // Notify the class that we've added a constructor. In principle we 2993 // don't need to do this for out-of-line declarations; in practice 2994 // we only instantiate the most recent declaration of a method, so 2995 // we have to call this for everything but friends. 2996 if (!Constructor->getFriendObjectKind()) 2997 ClassDecl->addedConstructor(Context, Constructor); 2998} 2999 3000/// CheckDestructor - Checks a fully-formed destructor for well-formedness, 3001/// issuing any diagnostics required. Returns true on error. 3002bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 3003 CXXRecordDecl *RD = Destructor->getParent(); 3004 3005 if (Destructor->isVirtual()) { 3006 SourceLocation Loc; 3007 3008 if (!Destructor->isImplicit()) 3009 Loc = Destructor->getLocation(); 3010 else 3011 Loc = RD->getLocation(); 3012 3013 // If we have a virtual destructor, look up the deallocation function 3014 FunctionDecl *OperatorDelete = 0; 3015 DeclarationName Name = 3016 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 3017 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 3018 return true; 3019 3020 Destructor->setOperatorDelete(OperatorDelete); 3021 } 3022 3023 return false; 3024} 3025 3026static inline bool 3027FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 3028 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 3029 FTI.ArgInfo[0].Param && 3030 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()); 3031} 3032 3033/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 3034/// the well-formednes of the destructor declarator @p D with type @p 3035/// R. If there are any errors in the declarator, this routine will 3036/// emit diagnostics and set the declarator to invalid. Even if this happens, 3037/// will be updated to reflect a well-formed type for the destructor and 3038/// returned. 3039QualType Sema::CheckDestructorDeclarator(Declarator &D, 3040 FunctionDecl::StorageClass& SC) { 3041 // C++ [class.dtor]p1: 3042 // [...] A typedef-name that names a class is a class-name 3043 // (7.1.3); however, a typedef-name that names a class shall not 3044 // be used as the identifier in the declarator for a destructor 3045 // declaration. 3046 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 3047 if (isa<TypedefType>(DeclaratorType)) { 3048 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 3049 << DeclaratorType; 3050 D.setInvalidType(); 3051 } 3052 3053 // C++ [class.dtor]p2: 3054 // A destructor is used to destroy objects of its class type. A 3055 // destructor takes no parameters, and no return type can be 3056 // specified for it (not even void). The address of a destructor 3057 // shall not be taken. A destructor shall not be static. A 3058 // destructor can be invoked for a const, volatile or const 3059 // volatile object. A destructor shall not be declared const, 3060 // volatile or const volatile (9.3.2). 3061 if (SC == FunctionDecl::Static) { 3062 if (!D.isInvalidType()) 3063 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 3064 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 3065 << SourceRange(D.getIdentifierLoc()); 3066 SC = FunctionDecl::None; 3067 D.setInvalidType(); 3068 } 3069 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 3070 // Destructors don't have return types, but the parser will 3071 // happily parse something like: 3072 // 3073 // class X { 3074 // float ~X(); 3075 // }; 3076 // 3077 // The return type will be eliminated later. 3078 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 3079 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 3080 << SourceRange(D.getIdentifierLoc()); 3081 } 3082 3083 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 3084 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 3085 if (FTI.TypeQuals & Qualifiers::Const) 3086 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3087 << "const" << SourceRange(D.getIdentifierLoc()); 3088 if (FTI.TypeQuals & Qualifiers::Volatile) 3089 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3090 << "volatile" << SourceRange(D.getIdentifierLoc()); 3091 if (FTI.TypeQuals & Qualifiers::Restrict) 3092 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 3093 << "restrict" << SourceRange(D.getIdentifierLoc()); 3094 D.setInvalidType(); 3095 } 3096 3097 // Make sure we don't have any parameters. 3098 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 3099 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 3100 3101 // Delete the parameters. 3102 FTI.freeArgs(); 3103 D.setInvalidType(); 3104 } 3105 3106 // Make sure the destructor isn't variadic. 3107 if (FTI.isVariadic) { 3108 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 3109 D.setInvalidType(); 3110 } 3111 3112 // Rebuild the function type "R" without any type qualifiers or 3113 // parameters (in case any of the errors above fired) and with 3114 // "void" as the return type, since destructors don't have return 3115 // types. We *always* have to do this, because GetTypeForDeclarator 3116 // will put in a result type of "int" when none was specified. 3117 // FIXME: Exceptions! 3118 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0, 3119 false, false, 0, 0, FunctionType::ExtInfo()); 3120} 3121 3122/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 3123/// well-formednes of the conversion function declarator @p D with 3124/// type @p R. If there are any errors in the declarator, this routine 3125/// will emit diagnostics and return true. Otherwise, it will return 3126/// false. Either way, the type @p R will be updated to reflect a 3127/// well-formed type for the conversion operator. 3128void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 3129 FunctionDecl::StorageClass& SC) { 3130 // C++ [class.conv.fct]p1: 3131 // Neither parameter types nor return type can be specified. The 3132 // type of a conversion function (8.3.5) is "function taking no 3133 // parameter returning conversion-type-id." 3134 if (SC == FunctionDecl::Static) { 3135 if (!D.isInvalidType()) 3136 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 3137 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 3138 << SourceRange(D.getIdentifierLoc()); 3139 D.setInvalidType(); 3140 SC = FunctionDecl::None; 3141 } 3142 3143 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId); 3144 3145 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 3146 // Conversion functions don't have return types, but the parser will 3147 // happily parse something like: 3148 // 3149 // class X { 3150 // float operator bool(); 3151 // }; 3152 // 3153 // The return type will be changed later anyway. 3154 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 3155 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 3156 << SourceRange(D.getIdentifierLoc()); 3157 D.setInvalidType(); 3158 } 3159 3160 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 3161 3162 // Make sure we don't have any parameters. 3163 if (Proto->getNumArgs() > 0) { 3164 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 3165 3166 // Delete the parameters. 3167 D.getTypeObject(0).Fun.freeArgs(); 3168 D.setInvalidType(); 3169 } else if (Proto->isVariadic()) { 3170 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 3171 D.setInvalidType(); 3172 } 3173 3174 // Diagnose "&operator bool()" and other such nonsense. This 3175 // is actually a gcc extension which we don't support. 3176 if (Proto->getResultType() != ConvType) { 3177 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 3178 << Proto->getResultType(); 3179 D.setInvalidType(); 3180 ConvType = Proto->getResultType(); 3181 } 3182 3183 // C++ [class.conv.fct]p4: 3184 // The conversion-type-id shall not represent a function type nor 3185 // an array type. 3186 if (ConvType->isArrayType()) { 3187 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 3188 ConvType = Context.getPointerType(ConvType); 3189 D.setInvalidType(); 3190 } else if (ConvType->isFunctionType()) { 3191 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 3192 ConvType = Context.getPointerType(ConvType); 3193 D.setInvalidType(); 3194 } 3195 3196 // Rebuild the function type "R" without any parameters (in case any 3197 // of the errors above fired) and with the conversion type as the 3198 // return type. 3199 if (D.isInvalidType()) { 3200 R = Context.getFunctionType(ConvType, 0, 0, false, 3201 Proto->getTypeQuals(), 3202 Proto->hasExceptionSpec(), 3203 Proto->hasAnyExceptionSpec(), 3204 Proto->getNumExceptions(), 3205 Proto->exception_begin(), 3206 Proto->getExtInfo()); 3207 } 3208 3209 // C++0x explicit conversion operators. 3210 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 3211 Diag(D.getDeclSpec().getExplicitSpecLoc(), 3212 diag::warn_explicit_conversion_functions) 3213 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 3214} 3215 3216/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 3217/// the declaration of the given C++ conversion function. This routine 3218/// is responsible for recording the conversion function in the C++ 3219/// class, if possible. 3220Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 3221 assert(Conversion && "Expected to receive a conversion function declaration"); 3222 3223 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 3224 3225 // Make sure we aren't redeclaring the conversion function. 3226 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 3227 3228 // C++ [class.conv.fct]p1: 3229 // [...] A conversion function is never used to convert a 3230 // (possibly cv-qualified) object to the (possibly cv-qualified) 3231 // same object type (or a reference to it), to a (possibly 3232 // cv-qualified) base class of that type (or a reference to it), 3233 // or to (possibly cv-qualified) void. 3234 // FIXME: Suppress this warning if the conversion function ends up being a 3235 // virtual function that overrides a virtual function in a base class. 3236 QualType ClassType 3237 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 3238 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 3239 ConvType = ConvTypeRef->getPointeeType(); 3240 if (ConvType->isRecordType()) { 3241 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 3242 if (ConvType == ClassType) 3243 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 3244 << ClassType; 3245 else if (IsDerivedFrom(ClassType, ConvType)) 3246 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 3247 << ClassType << ConvType; 3248 } else if (ConvType->isVoidType()) { 3249 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 3250 << ClassType << ConvType; 3251 } 3252 3253 if (Conversion->getPrimaryTemplate()) { 3254 // ignore specializations 3255 } else if (Conversion->getPreviousDeclaration()) { 3256 if (FunctionTemplateDecl *ConversionTemplate 3257 = Conversion->getDescribedFunctionTemplate()) { 3258 if (ClassDecl->replaceConversion( 3259 ConversionTemplate->getPreviousDeclaration(), 3260 ConversionTemplate)) 3261 return DeclPtrTy::make(ConversionTemplate); 3262 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(), 3263 Conversion)) 3264 return DeclPtrTy::make(Conversion); 3265 assert(Conversion->isInvalidDecl() && "Conversion should not get here."); 3266 } else if (FunctionTemplateDecl *ConversionTemplate 3267 = Conversion->getDescribedFunctionTemplate()) 3268 ClassDecl->addConversionFunction(ConversionTemplate); 3269 else 3270 ClassDecl->addConversionFunction(Conversion); 3271 3272 return DeclPtrTy::make(Conversion); 3273} 3274 3275//===----------------------------------------------------------------------===// 3276// Namespace Handling 3277//===----------------------------------------------------------------------===// 3278 3279/// ActOnStartNamespaceDef - This is called at the start of a namespace 3280/// definition. 3281Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 3282 SourceLocation IdentLoc, 3283 IdentifierInfo *II, 3284 SourceLocation LBrace, 3285 AttributeList *AttrList) { 3286 NamespaceDecl *Namespc = 3287 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 3288 Namespc->setLBracLoc(LBrace); 3289 3290 Scope *DeclRegionScope = NamespcScope->getParent(); 3291 3292 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 3293 3294 if (II) { 3295 // C++ [namespace.def]p2: 3296 // The identifier in an original-namespace-definition shall not have been 3297 // previously defined in the declarative region in which the 3298 // original-namespace-definition appears. The identifier in an 3299 // original-namespace-definition is the name of the namespace. Subsequently 3300 // in that declarative region, it is treated as an original-namespace-name. 3301 3302 NamedDecl *PrevDecl 3303 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName, 3304 ForRedeclaration); 3305 3306 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 3307 // This is an extended namespace definition. 3308 // Attach this namespace decl to the chain of extended namespace 3309 // definitions. 3310 OrigNS->setNextNamespace(Namespc); 3311 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 3312 3313 // Remove the previous declaration from the scope. 3314 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) { 3315 IdResolver.RemoveDecl(OrigNS); 3316 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS)); 3317 } 3318 } else if (PrevDecl) { 3319 // This is an invalid name redefinition. 3320 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 3321 << Namespc->getDeclName(); 3322 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3323 Namespc->setInvalidDecl(); 3324 // Continue on to push Namespc as current DeclContext and return it. 3325 } else if (II->isStr("std") && 3326 CurContext->getLookupContext()->isTranslationUnit()) { 3327 // This is the first "real" definition of the namespace "std", so update 3328 // our cache of the "std" namespace to point at this definition. 3329 if (StdNamespace) { 3330 // We had already defined a dummy namespace "std". Link this new 3331 // namespace definition to the dummy namespace "std". 3332 StdNamespace->setNextNamespace(Namespc); 3333 StdNamespace->setLocation(IdentLoc); 3334 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace()); 3335 } 3336 3337 // Make our StdNamespace cache point at the first real definition of the 3338 // "std" namespace. 3339 StdNamespace = Namespc; 3340 } 3341 3342 PushOnScopeChains(Namespc, DeclRegionScope); 3343 } else { 3344 // Anonymous namespaces. 3345 assert(Namespc->isAnonymousNamespace()); 3346 3347 // Link the anonymous namespace into its parent. 3348 NamespaceDecl *PrevDecl; 3349 DeclContext *Parent = CurContext->getLookupContext(); 3350 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 3351 PrevDecl = TU->getAnonymousNamespace(); 3352 TU->setAnonymousNamespace(Namespc); 3353 } else { 3354 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 3355 PrevDecl = ND->getAnonymousNamespace(); 3356 ND->setAnonymousNamespace(Namespc); 3357 } 3358 3359 // Link the anonymous namespace with its previous declaration. 3360 if (PrevDecl) { 3361 assert(PrevDecl->isAnonymousNamespace()); 3362 assert(!PrevDecl->getNextNamespace()); 3363 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace()); 3364 PrevDecl->setNextNamespace(Namespc); 3365 } 3366 3367 CurContext->addDecl(Namespc); 3368 3369 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 3370 // behaves as if it were replaced by 3371 // namespace unique { /* empty body */ } 3372 // using namespace unique; 3373 // namespace unique { namespace-body } 3374 // where all occurrences of 'unique' in a translation unit are 3375 // replaced by the same identifier and this identifier differs 3376 // from all other identifiers in the entire program. 3377 3378 // We just create the namespace with an empty name and then add an 3379 // implicit using declaration, just like the standard suggests. 3380 // 3381 // CodeGen enforces the "universally unique" aspect by giving all 3382 // declarations semantically contained within an anonymous 3383 // namespace internal linkage. 3384 3385 if (!PrevDecl) { 3386 UsingDirectiveDecl* UD 3387 = UsingDirectiveDecl::Create(Context, CurContext, 3388 /* 'using' */ LBrace, 3389 /* 'namespace' */ SourceLocation(), 3390 /* qualifier */ SourceRange(), 3391 /* NNS */ NULL, 3392 /* identifier */ SourceLocation(), 3393 Namespc, 3394 /* Ancestor */ CurContext); 3395 UD->setImplicit(); 3396 CurContext->addDecl(UD); 3397 } 3398 } 3399 3400 // Although we could have an invalid decl (i.e. the namespace name is a 3401 // redefinition), push it as current DeclContext and try to continue parsing. 3402 // FIXME: We should be able to push Namespc here, so that the each DeclContext 3403 // for the namespace has the declarations that showed up in that particular 3404 // namespace definition. 3405 PushDeclContext(NamespcScope, Namespc); 3406 return DeclPtrTy::make(Namespc); 3407} 3408 3409/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 3410/// is a namespace alias, returns the namespace it points to. 3411static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 3412 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 3413 return AD->getNamespace(); 3414 return dyn_cast_or_null<NamespaceDecl>(D); 3415} 3416 3417/// ActOnFinishNamespaceDef - This callback is called after a namespace is 3418/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 3419void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) { 3420 Decl *Dcl = D.getAs<Decl>(); 3421 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 3422 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 3423 Namespc->setRBracLoc(RBrace); 3424 PopDeclContext(); 3425} 3426 3427Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S, 3428 SourceLocation UsingLoc, 3429 SourceLocation NamespcLoc, 3430 CXXScopeSpec &SS, 3431 SourceLocation IdentLoc, 3432 IdentifierInfo *NamespcName, 3433 AttributeList *AttrList) { 3434 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 3435 assert(NamespcName && "Invalid NamespcName."); 3436 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 3437 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 3438 3439 UsingDirectiveDecl *UDir = 0; 3440 3441 // Lookup namespace name. 3442 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 3443 LookupParsedName(R, S, &SS); 3444 if (R.isAmbiguous()) 3445 return DeclPtrTy(); 3446 3447 if (!R.empty()) { 3448 NamedDecl *Named = R.getFoundDecl(); 3449 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named)) 3450 && "expected namespace decl"); 3451 // C++ [namespace.udir]p1: 3452 // A using-directive specifies that the names in the nominated 3453 // namespace can be used in the scope in which the 3454 // using-directive appears after the using-directive. During 3455 // unqualified name lookup (3.4.1), the names appear as if they 3456 // were declared in the nearest enclosing namespace which 3457 // contains both the using-directive and the nominated 3458 // namespace. [Note: in this context, "contains" means "contains 3459 // directly or indirectly". ] 3460 3461 // Find enclosing context containing both using-directive and 3462 // nominated namespace. 3463 NamespaceDecl *NS = getNamespaceDecl(Named); 3464 DeclContext *CommonAncestor = cast<DeclContext>(NS); 3465 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 3466 CommonAncestor = CommonAncestor->getParent(); 3467 3468 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 3469 SS.getRange(), 3470 (NestedNameSpecifier *)SS.getScopeRep(), 3471 IdentLoc, Named, CommonAncestor); 3472 PushUsingDirective(S, UDir); 3473 } else { 3474 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 3475 } 3476 3477 // FIXME: We ignore attributes for now. 3478 delete AttrList; 3479 return DeclPtrTy::make(UDir); 3480} 3481 3482void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 3483 // If scope has associated entity, then using directive is at namespace 3484 // or translation unit scope. We add UsingDirectiveDecls, into 3485 // it's lookup structure. 3486 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 3487 Ctx->addDecl(UDir); 3488 else 3489 // Otherwise it is block-sope. using-directives will affect lookup 3490 // only to the end of scope. 3491 S->PushUsingDirective(DeclPtrTy::make(UDir)); 3492} 3493 3494 3495Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S, 3496 AccessSpecifier AS, 3497 bool HasUsingKeyword, 3498 SourceLocation UsingLoc, 3499 CXXScopeSpec &SS, 3500 UnqualifiedId &Name, 3501 AttributeList *AttrList, 3502 bool IsTypeName, 3503 SourceLocation TypenameLoc) { 3504 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 3505 3506 switch (Name.getKind()) { 3507 case UnqualifiedId::IK_Identifier: 3508 case UnqualifiedId::IK_OperatorFunctionId: 3509 case UnqualifiedId::IK_LiteralOperatorId: 3510 case UnqualifiedId::IK_ConversionFunctionId: 3511 break; 3512 3513 case UnqualifiedId::IK_ConstructorName: 3514 case UnqualifiedId::IK_ConstructorTemplateId: 3515 // C++0x inherited constructors. 3516 if (getLangOptions().CPlusPlus0x) break; 3517 3518 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor) 3519 << SS.getRange(); 3520 return DeclPtrTy(); 3521 3522 case UnqualifiedId::IK_DestructorName: 3523 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor) 3524 << SS.getRange(); 3525 return DeclPtrTy(); 3526 3527 case UnqualifiedId::IK_TemplateId: 3528 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id) 3529 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 3530 return DeclPtrTy(); 3531 } 3532 3533 DeclarationName TargetName = GetNameFromUnqualifiedId(Name); 3534 if (!TargetName) 3535 return DeclPtrTy(); 3536 3537 // Warn about using declarations. 3538 // TODO: store that the declaration was written without 'using' and 3539 // talk about access decls instead of using decls in the 3540 // diagnostics. 3541 if (!HasUsingKeyword) { 3542 UsingLoc = Name.getSourceRange().getBegin(); 3543 3544 Diag(UsingLoc, diag::warn_access_decl_deprecated) 3545 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 3546 } 3547 3548 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS, 3549 Name.getSourceRange().getBegin(), 3550 TargetName, AttrList, 3551 /* IsInstantiation */ false, 3552 IsTypeName, TypenameLoc); 3553 if (UD) 3554 PushOnScopeChains(UD, S, /*AddToContext*/ false); 3555 3556 return DeclPtrTy::make(UD); 3557} 3558 3559/// Determines whether to create a using shadow decl for a particular 3560/// decl, given the set of decls existing prior to this using lookup. 3561bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 3562 const LookupResult &Previous) { 3563 // Diagnose finding a decl which is not from a base class of the 3564 // current class. We do this now because there are cases where this 3565 // function will silently decide not to build a shadow decl, which 3566 // will pre-empt further diagnostics. 3567 // 3568 // We don't need to do this in C++0x because we do the check once on 3569 // the qualifier. 3570 // 3571 // FIXME: diagnose the following if we care enough: 3572 // struct A { int foo; }; 3573 // struct B : A { using A::foo; }; 3574 // template <class T> struct C : A {}; 3575 // template <class T> struct D : C<T> { using B::foo; } // <--- 3576 // This is invalid (during instantiation) in C++03 because B::foo 3577 // resolves to the using decl in B, which is not a base class of D<T>. 3578 // We can't diagnose it immediately because C<T> is an unknown 3579 // specialization. The UsingShadowDecl in D<T> then points directly 3580 // to A::foo, which will look well-formed when we instantiate. 3581 // The right solution is to not collapse the shadow-decl chain. 3582 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) { 3583 DeclContext *OrigDC = Orig->getDeclContext(); 3584 3585 // Handle enums and anonymous structs. 3586 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 3587 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 3588 while (OrigRec->isAnonymousStructOrUnion()) 3589 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 3590 3591 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 3592 if (OrigDC == CurContext) { 3593 Diag(Using->getLocation(), 3594 diag::err_using_decl_nested_name_specifier_is_current_class) 3595 << Using->getNestedNameRange(); 3596 Diag(Orig->getLocation(), diag::note_using_decl_target); 3597 return true; 3598 } 3599 3600 Diag(Using->getNestedNameRange().getBegin(), 3601 diag::err_using_decl_nested_name_specifier_is_not_base_class) 3602 << Using->getTargetNestedNameDecl() 3603 << cast<CXXRecordDecl>(CurContext) 3604 << Using->getNestedNameRange(); 3605 Diag(Orig->getLocation(), diag::note_using_decl_target); 3606 return true; 3607 } 3608 } 3609 3610 if (Previous.empty()) return false; 3611 3612 NamedDecl *Target = Orig; 3613 if (isa<UsingShadowDecl>(Target)) 3614 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 3615 3616 // If the target happens to be one of the previous declarations, we 3617 // don't have a conflict. 3618 // 3619 // FIXME: but we might be increasing its access, in which case we 3620 // should redeclare it. 3621 NamedDecl *NonTag = 0, *Tag = 0; 3622 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 3623 I != E; ++I) { 3624 NamedDecl *D = (*I)->getUnderlyingDecl(); 3625 if (D->getCanonicalDecl() == Target->getCanonicalDecl()) 3626 return false; 3627 3628 (isa<TagDecl>(D) ? Tag : NonTag) = D; 3629 } 3630 3631 if (Target->isFunctionOrFunctionTemplate()) { 3632 FunctionDecl *FD; 3633 if (isa<FunctionTemplateDecl>(Target)) 3634 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl(); 3635 else 3636 FD = cast<FunctionDecl>(Target); 3637 3638 NamedDecl *OldDecl = 0; 3639 switch (CheckOverload(FD, Previous, OldDecl)) { 3640 case Ovl_Overload: 3641 return false; 3642 3643 case Ovl_NonFunction: 3644 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3645 break; 3646 3647 // We found a decl with the exact signature. 3648 case Ovl_Match: 3649 if (isa<UsingShadowDecl>(OldDecl)) { 3650 // Silently ignore the possible conflict. 3651 return false; 3652 } 3653 3654 // If we're in a record, we want to hide the target, so we 3655 // return true (without a diagnostic) to tell the caller not to 3656 // build a shadow decl. 3657 if (CurContext->isRecord()) 3658 return true; 3659 3660 // If we're not in a record, this is an error. 3661 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3662 break; 3663 } 3664 3665 Diag(Target->getLocation(), diag::note_using_decl_target); 3666 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 3667 return true; 3668 } 3669 3670 // Target is not a function. 3671 3672 if (isa<TagDecl>(Target)) { 3673 // No conflict between a tag and a non-tag. 3674 if (!Tag) return false; 3675 3676 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3677 Diag(Target->getLocation(), diag::note_using_decl_target); 3678 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 3679 return true; 3680 } 3681 3682 // No conflict between a tag and a non-tag. 3683 if (!NonTag) return false; 3684 3685 Diag(Using->getLocation(), diag::err_using_decl_conflict); 3686 Diag(Target->getLocation(), diag::note_using_decl_target); 3687 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 3688 return true; 3689} 3690 3691/// Builds a shadow declaration corresponding to a 'using' declaration. 3692UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 3693 UsingDecl *UD, 3694 NamedDecl *Orig) { 3695 3696 // If we resolved to another shadow declaration, just coalesce them. 3697 NamedDecl *Target = Orig; 3698 if (isa<UsingShadowDecl>(Target)) { 3699 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 3700 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 3701 } 3702 3703 UsingShadowDecl *Shadow 3704 = UsingShadowDecl::Create(Context, CurContext, 3705 UD->getLocation(), UD, Target); 3706 UD->addShadowDecl(Shadow); 3707 3708 if (S) 3709 PushOnScopeChains(Shadow, S); 3710 else 3711 CurContext->addDecl(Shadow); 3712 Shadow->setAccess(UD->getAccess()); 3713 3714 // Register it as a conversion if appropriate. 3715 if (Shadow->getDeclName().getNameKind() 3716 == DeclarationName::CXXConversionFunctionName) 3717 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow); 3718 3719 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 3720 Shadow->setInvalidDecl(); 3721 3722 return Shadow; 3723} 3724 3725/// Hides a using shadow declaration. This is required by the current 3726/// using-decl implementation when a resolvable using declaration in a 3727/// class is followed by a declaration which would hide or override 3728/// one or more of the using decl's targets; for example: 3729/// 3730/// struct Base { void foo(int); }; 3731/// struct Derived : Base { 3732/// using Base::foo; 3733/// void foo(int); 3734/// }; 3735/// 3736/// The governing language is C++03 [namespace.udecl]p12: 3737/// 3738/// When a using-declaration brings names from a base class into a 3739/// derived class scope, member functions in the derived class 3740/// override and/or hide member functions with the same name and 3741/// parameter types in a base class (rather than conflicting). 3742/// 3743/// There are two ways to implement this: 3744/// (1) optimistically create shadow decls when they're not hidden 3745/// by existing declarations, or 3746/// (2) don't create any shadow decls (or at least don't make them 3747/// visible) until we've fully parsed/instantiated the class. 3748/// The problem with (1) is that we might have to retroactively remove 3749/// a shadow decl, which requires several O(n) operations because the 3750/// decl structures are (very reasonably) not designed for removal. 3751/// (2) avoids this but is very fiddly and phase-dependent. 3752void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 3753 if (Shadow->getDeclName().getNameKind() == 3754 DeclarationName::CXXConversionFunctionName) 3755 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 3756 3757 // Remove it from the DeclContext... 3758 Shadow->getDeclContext()->removeDecl(Shadow); 3759 3760 // ...and the scope, if applicable... 3761 if (S) { 3762 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow))); 3763 IdResolver.RemoveDecl(Shadow); 3764 } 3765 3766 // ...and the using decl. 3767 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 3768 3769 // TODO: complain somehow if Shadow was used. It shouldn't 3770 // be possible for this to happen, because...? 3771} 3772 3773/// Builds a using declaration. 3774/// 3775/// \param IsInstantiation - Whether this call arises from an 3776/// instantiation of an unresolved using declaration. We treat 3777/// the lookup differently for these declarations. 3778NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 3779 SourceLocation UsingLoc, 3780 CXXScopeSpec &SS, 3781 SourceLocation IdentLoc, 3782 DeclarationName Name, 3783 AttributeList *AttrList, 3784 bool IsInstantiation, 3785 bool IsTypeName, 3786 SourceLocation TypenameLoc) { 3787 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 3788 assert(IdentLoc.isValid() && "Invalid TargetName location."); 3789 3790 // FIXME: We ignore attributes for now. 3791 delete AttrList; 3792 3793 if (SS.isEmpty()) { 3794 Diag(IdentLoc, diag::err_using_requires_qualname); 3795 return 0; 3796 } 3797 3798 // Do the redeclaration lookup in the current scope. 3799 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName, 3800 ForRedeclaration); 3801 Previous.setHideTags(false); 3802 if (S) { 3803 LookupName(Previous, S); 3804 3805 // It is really dumb that we have to do this. 3806 LookupResult::Filter F = Previous.makeFilter(); 3807 while (F.hasNext()) { 3808 NamedDecl *D = F.next(); 3809 if (!isDeclInScope(D, CurContext, S)) 3810 F.erase(); 3811 } 3812 F.done(); 3813 } else { 3814 assert(IsInstantiation && "no scope in non-instantiation"); 3815 assert(CurContext->isRecord() && "scope not record in instantiation"); 3816 LookupQualifiedName(Previous, CurContext); 3817 } 3818 3819 NestedNameSpecifier *NNS = 3820 static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 3821 3822 // Check for invalid redeclarations. 3823 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous)) 3824 return 0; 3825 3826 // Check for bad qualifiers. 3827 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc)) 3828 return 0; 3829 3830 DeclContext *LookupContext = computeDeclContext(SS); 3831 NamedDecl *D; 3832 if (!LookupContext) { 3833 if (IsTypeName) { 3834 // FIXME: not all declaration name kinds are legal here 3835 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 3836 UsingLoc, TypenameLoc, 3837 SS.getRange(), NNS, 3838 IdentLoc, Name); 3839 } else { 3840 D = UnresolvedUsingValueDecl::Create(Context, CurContext, 3841 UsingLoc, SS.getRange(), NNS, 3842 IdentLoc, Name); 3843 } 3844 } else { 3845 D = UsingDecl::Create(Context, CurContext, IdentLoc, 3846 SS.getRange(), UsingLoc, NNS, Name, 3847 IsTypeName); 3848 } 3849 D->setAccess(AS); 3850 CurContext->addDecl(D); 3851 3852 if (!LookupContext) return D; 3853 UsingDecl *UD = cast<UsingDecl>(D); 3854 3855 if (RequireCompleteDeclContext(SS, LookupContext)) { 3856 UD->setInvalidDecl(); 3857 return UD; 3858 } 3859 3860 // Look up the target name. 3861 3862 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName); 3863 3864 // Unlike most lookups, we don't always want to hide tag 3865 // declarations: tag names are visible through the using declaration 3866 // even if hidden by ordinary names, *except* in a dependent context 3867 // where it's important for the sanity of two-phase lookup. 3868 if (!IsInstantiation) 3869 R.setHideTags(false); 3870 3871 LookupQualifiedName(R, LookupContext); 3872 3873 if (R.empty()) { 3874 Diag(IdentLoc, diag::err_no_member) 3875 << Name << LookupContext << SS.getRange(); 3876 UD->setInvalidDecl(); 3877 return UD; 3878 } 3879 3880 if (R.isAmbiguous()) { 3881 UD->setInvalidDecl(); 3882 return UD; 3883 } 3884 3885 if (IsTypeName) { 3886 // If we asked for a typename and got a non-type decl, error out. 3887 if (!R.getAsSingle<TypeDecl>()) { 3888 Diag(IdentLoc, diag::err_using_typename_non_type); 3889 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 3890 Diag((*I)->getUnderlyingDecl()->getLocation(), 3891 diag::note_using_decl_target); 3892 UD->setInvalidDecl(); 3893 return UD; 3894 } 3895 } else { 3896 // If we asked for a non-typename and we got a type, error out, 3897 // but only if this is an instantiation of an unresolved using 3898 // decl. Otherwise just silently find the type name. 3899 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 3900 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 3901 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 3902 UD->setInvalidDecl(); 3903 return UD; 3904 } 3905 } 3906 3907 // C++0x N2914 [namespace.udecl]p6: 3908 // A using-declaration shall not name a namespace. 3909 if (R.getAsSingle<NamespaceDecl>()) { 3910 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 3911 << SS.getRange(); 3912 UD->setInvalidDecl(); 3913 return UD; 3914 } 3915 3916 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 3917 if (!CheckUsingShadowDecl(UD, *I, Previous)) 3918 BuildUsingShadowDecl(S, UD, *I); 3919 } 3920 3921 return UD; 3922} 3923 3924/// Checks that the given using declaration is not an invalid 3925/// redeclaration. Note that this is checking only for the using decl 3926/// itself, not for any ill-formedness among the UsingShadowDecls. 3927bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 3928 bool isTypeName, 3929 const CXXScopeSpec &SS, 3930 SourceLocation NameLoc, 3931 const LookupResult &Prev) { 3932 // C++03 [namespace.udecl]p8: 3933 // C++0x [namespace.udecl]p10: 3934 // A using-declaration is a declaration and can therefore be used 3935 // repeatedly where (and only where) multiple declarations are 3936 // allowed. 3937 // 3938 // That's in non-member contexts. 3939 if (!CurContext->getLookupContext()->isRecord()) 3940 return false; 3941 3942 NestedNameSpecifier *Qual 3943 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 3944 3945 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 3946 NamedDecl *D = *I; 3947 3948 bool DTypename; 3949 NestedNameSpecifier *DQual; 3950 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 3951 DTypename = UD->isTypeName(); 3952 DQual = UD->getTargetNestedNameDecl(); 3953 } else if (UnresolvedUsingValueDecl *UD 3954 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 3955 DTypename = false; 3956 DQual = UD->getTargetNestedNameSpecifier(); 3957 } else if (UnresolvedUsingTypenameDecl *UD 3958 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 3959 DTypename = true; 3960 DQual = UD->getTargetNestedNameSpecifier(); 3961 } else continue; 3962 3963 // using decls differ if one says 'typename' and the other doesn't. 3964 // FIXME: non-dependent using decls? 3965 if (isTypeName != DTypename) continue; 3966 3967 // using decls differ if they name different scopes (but note that 3968 // template instantiation can cause this check to trigger when it 3969 // didn't before instantiation). 3970 if (Context.getCanonicalNestedNameSpecifier(Qual) != 3971 Context.getCanonicalNestedNameSpecifier(DQual)) 3972 continue; 3973 3974 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 3975 Diag(D->getLocation(), diag::note_using_decl) << 1; 3976 return true; 3977 } 3978 3979 return false; 3980} 3981 3982 3983/// Checks that the given nested-name qualifier used in a using decl 3984/// in the current context is appropriately related to the current 3985/// scope. If an error is found, diagnoses it and returns true. 3986bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 3987 const CXXScopeSpec &SS, 3988 SourceLocation NameLoc) { 3989 DeclContext *NamedContext = computeDeclContext(SS); 3990 3991 if (!CurContext->isRecord()) { 3992 // C++03 [namespace.udecl]p3: 3993 // C++0x [namespace.udecl]p8: 3994 // A using-declaration for a class member shall be a member-declaration. 3995 3996 // If we weren't able to compute a valid scope, it must be a 3997 // dependent class scope. 3998 if (!NamedContext || NamedContext->isRecord()) { 3999 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 4000 << SS.getRange(); 4001 return true; 4002 } 4003 4004 // Otherwise, everything is known to be fine. 4005 return false; 4006 } 4007 4008 // The current scope is a record. 4009 4010 // If the named context is dependent, we can't decide much. 4011 if (!NamedContext) { 4012 // FIXME: in C++0x, we can diagnose if we can prove that the 4013 // nested-name-specifier does not refer to a base class, which is 4014 // still possible in some cases. 4015 4016 // Otherwise we have to conservatively report that things might be 4017 // okay. 4018 return false; 4019 } 4020 4021 if (!NamedContext->isRecord()) { 4022 // Ideally this would point at the last name in the specifier, 4023 // but we don't have that level of source info. 4024 Diag(SS.getRange().getBegin(), 4025 diag::err_using_decl_nested_name_specifier_is_not_class) 4026 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange(); 4027 return true; 4028 } 4029 4030 if (getLangOptions().CPlusPlus0x) { 4031 // C++0x [namespace.udecl]p3: 4032 // In a using-declaration used as a member-declaration, the 4033 // nested-name-specifier shall name a base class of the class 4034 // being defined. 4035 4036 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 4037 cast<CXXRecordDecl>(NamedContext))) { 4038 if (CurContext == NamedContext) { 4039 Diag(NameLoc, 4040 diag::err_using_decl_nested_name_specifier_is_current_class) 4041 << SS.getRange(); 4042 return true; 4043 } 4044 4045 Diag(SS.getRange().getBegin(), 4046 diag::err_using_decl_nested_name_specifier_is_not_base_class) 4047 << (NestedNameSpecifier*) SS.getScopeRep() 4048 << cast<CXXRecordDecl>(CurContext) 4049 << SS.getRange(); 4050 return true; 4051 } 4052 4053 return false; 4054 } 4055 4056 // C++03 [namespace.udecl]p4: 4057 // A using-declaration used as a member-declaration shall refer 4058 // to a member of a base class of the class being defined [etc.]. 4059 4060 // Salient point: SS doesn't have to name a base class as long as 4061 // lookup only finds members from base classes. Therefore we can 4062 // diagnose here only if we can prove that that can't happen, 4063 // i.e. if the class hierarchies provably don't intersect. 4064 4065 // TODO: it would be nice if "definitely valid" results were cached 4066 // in the UsingDecl and UsingShadowDecl so that these checks didn't 4067 // need to be repeated. 4068 4069 struct UserData { 4070 llvm::DenseSet<const CXXRecordDecl*> Bases; 4071 4072 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) { 4073 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 4074 Data->Bases.insert(Base); 4075 return true; 4076 } 4077 4078 bool hasDependentBases(const CXXRecordDecl *Class) { 4079 return !Class->forallBases(collect, this); 4080 } 4081 4082 /// Returns true if the base is dependent or is one of the 4083 /// accumulated base classes. 4084 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) { 4085 UserData *Data = reinterpret_cast<UserData*>(OpaqueData); 4086 return !Data->Bases.count(Base); 4087 } 4088 4089 bool mightShareBases(const CXXRecordDecl *Class) { 4090 return Bases.count(Class) || !Class->forallBases(doesNotContain, this); 4091 } 4092 }; 4093 4094 UserData Data; 4095 4096 // Returns false if we find a dependent base. 4097 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext))) 4098 return false; 4099 4100 // Returns false if the class has a dependent base or if it or one 4101 // of its bases is present in the base set of the current context. 4102 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext))) 4103 return false; 4104 4105 Diag(SS.getRange().getBegin(), 4106 diag::err_using_decl_nested_name_specifier_is_not_base_class) 4107 << (NestedNameSpecifier*) SS.getScopeRep() 4108 << cast<CXXRecordDecl>(CurContext) 4109 << SS.getRange(); 4110 4111 return true; 4112} 4113 4114Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S, 4115 SourceLocation NamespaceLoc, 4116 SourceLocation AliasLoc, 4117 IdentifierInfo *Alias, 4118 CXXScopeSpec &SS, 4119 SourceLocation IdentLoc, 4120 IdentifierInfo *Ident) { 4121 4122 // Lookup the namespace name. 4123 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 4124 LookupParsedName(R, S, &SS); 4125 4126 // Check if we have a previous declaration with the same name. 4127 NamedDecl *PrevDecl 4128 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName, 4129 ForRedeclaration); 4130 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S)) 4131 PrevDecl = 0; 4132 4133 if (PrevDecl) { 4134 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 4135 // We already have an alias with the same name that points to the same 4136 // namespace, so don't create a new one. 4137 // FIXME: At some point, we'll want to create the (redundant) 4138 // declaration to maintain better source information. 4139 if (!R.isAmbiguous() && !R.empty() && 4140 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl()))) 4141 return DeclPtrTy(); 4142 } 4143 4144 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 4145 diag::err_redefinition_different_kind; 4146 Diag(AliasLoc, DiagID) << Alias; 4147 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 4148 return DeclPtrTy(); 4149 } 4150 4151 if (R.isAmbiguous()) 4152 return DeclPtrTy(); 4153 4154 if (R.empty()) { 4155 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 4156 return DeclPtrTy(); 4157 } 4158 4159 NamespaceAliasDecl *AliasDecl = 4160 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 4161 Alias, SS.getRange(), 4162 (NestedNameSpecifier *)SS.getScopeRep(), 4163 IdentLoc, R.getFoundDecl()); 4164 4165 PushOnScopeChains(AliasDecl, S); 4166 return DeclPtrTy::make(AliasDecl); 4167} 4168 4169namespace { 4170 /// \brief Scoped object used to handle the state changes required in Sema 4171 /// to implicitly define the body of a C++ member function; 4172 class ImplicitlyDefinedFunctionScope { 4173 Sema &S; 4174 DeclContext *PreviousContext; 4175 4176 public: 4177 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method) 4178 : S(S), PreviousContext(S.CurContext) 4179 { 4180 S.CurContext = Method; 4181 S.PushFunctionScope(); 4182 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 4183 } 4184 4185 ~ImplicitlyDefinedFunctionScope() { 4186 S.PopExpressionEvaluationContext(); 4187 S.PopFunctionOrBlockScope(); 4188 S.CurContext = PreviousContext; 4189 } 4190 }; 4191} 4192 4193void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 4194 CXXConstructorDecl *Constructor) { 4195 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() && 4196 !Constructor->isUsed()) && 4197 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 4198 4199 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4200 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 4201 4202 ImplicitlyDefinedFunctionScope Scope(*this, Constructor); 4203 ErrorTrap Trap(*this); 4204 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) || 4205 Trap.hasErrorOccurred()) { 4206 Diag(CurrentLocation, diag::note_member_synthesized_at) 4207 << CXXConstructor << Context.getTagDeclType(ClassDecl); 4208 Constructor->setInvalidDecl(); 4209 } else { 4210 Constructor->setUsed(); 4211 MarkVTableUsed(CurrentLocation, ClassDecl); 4212 } 4213} 4214 4215void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 4216 CXXDestructorDecl *Destructor) { 4217 assert((Destructor->isImplicit() && !Destructor->isUsed()) && 4218 "DefineImplicitDestructor - call it for implicit default dtor"); 4219 CXXRecordDecl *ClassDecl = Destructor->getParent(); 4220 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 4221 4222 if (Destructor->isInvalidDecl()) 4223 return; 4224 4225 ImplicitlyDefinedFunctionScope Scope(*this, Destructor); 4226 4227 ErrorTrap Trap(*this); 4228 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 4229 Destructor->getParent()); 4230 4231 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) { 4232 Diag(CurrentLocation, diag::note_member_synthesized_at) 4233 << CXXDestructor << Context.getTagDeclType(ClassDecl); 4234 4235 Destructor->setInvalidDecl(); 4236 return; 4237 } 4238 4239 Destructor->setUsed(); 4240 MarkVTableUsed(CurrentLocation, ClassDecl); 4241} 4242 4243/// \brief Builds a statement that copies the given entity from \p From to 4244/// \c To. 4245/// 4246/// This routine is used to copy the members of a class with an 4247/// implicitly-declared copy assignment operator. When the entities being 4248/// copied are arrays, this routine builds for loops to copy them. 4249/// 4250/// \param S The Sema object used for type-checking. 4251/// 4252/// \param Loc The location where the implicit copy is being generated. 4253/// 4254/// \param T The type of the expressions being copied. Both expressions must 4255/// have this type. 4256/// 4257/// \param To The expression we are copying to. 4258/// 4259/// \param From The expression we are copying from. 4260/// 4261/// \param CopyingBaseSubobject Whether we're copying a base subobject. 4262/// Otherwise, it's a non-static member subobject. 4263/// 4264/// \param Depth Internal parameter recording the depth of the recursion. 4265/// 4266/// \returns A statement or a loop that copies the expressions. 4267static Sema::OwningStmtResult 4268BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 4269 Sema::OwningExprResult To, Sema::OwningExprResult From, 4270 bool CopyingBaseSubobject, unsigned Depth = 0) { 4271 typedef Sema::OwningStmtResult OwningStmtResult; 4272 typedef Sema::OwningExprResult OwningExprResult; 4273 4274 // C++0x [class.copy]p30: 4275 // Each subobject is assigned in the manner appropriate to its type: 4276 // 4277 // - if the subobject is of class type, the copy assignment operator 4278 // for the class is used (as if by explicit qualification; that is, 4279 // ignoring any possible virtual overriding functions in more derived 4280 // classes); 4281 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 4282 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 4283 4284 // Look for operator=. 4285 DeclarationName Name 4286 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 4287 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 4288 S.LookupQualifiedName(OpLookup, ClassDecl, false); 4289 4290 // Filter out any result that isn't a copy-assignment operator. 4291 LookupResult::Filter F = OpLookup.makeFilter(); 4292 while (F.hasNext()) { 4293 NamedDecl *D = F.next(); 4294 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 4295 if (Method->isCopyAssignmentOperator()) 4296 continue; 4297 4298 F.erase(); 4299 } 4300 F.done(); 4301 4302 // Suppress the protected check (C++ [class.protected]) for each of the 4303 // assignment operators we found. This strange dance is required when 4304 // we're assigning via a base classes's copy-assignment operator. To 4305 // ensure that we're getting the right base class subobject (without 4306 // ambiguities), we need to cast "this" to that subobject type; to 4307 // ensure that we don't go through the virtual call mechanism, we need 4308 // to qualify the operator= name with the base class (see below). However, 4309 // this means that if the base class has a protected copy assignment 4310 // operator, the protected member access check will fail. So, we 4311 // rewrite "protected" access to "public" access in this case, since we 4312 // know by construction that we're calling from a derived class. 4313 if (CopyingBaseSubobject) { 4314 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 4315 L != LEnd; ++L) { 4316 if (L.getAccess() == AS_protected) 4317 L.setAccess(AS_public); 4318 } 4319 } 4320 4321 // Create the nested-name-specifier that will be used to qualify the 4322 // reference to operator=; this is required to suppress the virtual 4323 // call mechanism. 4324 CXXScopeSpec SS; 4325 SS.setRange(Loc); 4326 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false, 4327 T.getTypePtr())); 4328 4329 // Create the reference to operator=. 4330 OwningExprResult OpEqualRef 4331 = S.BuildMemberReferenceExpr(move(To), T, Loc, /*isArrow=*/false, SS, 4332 /*FirstQualifierInScope=*/0, OpLookup, 4333 /*TemplateArgs=*/0, 4334 /*SuppressQualifierCheck=*/true); 4335 if (OpEqualRef.isInvalid()) 4336 return S.StmtError(); 4337 4338 // Build the call to the assignment operator. 4339 Expr *FromE = From.takeAs<Expr>(); 4340 OwningExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0, 4341 OpEqualRef.takeAs<Expr>(), 4342 Loc, &FromE, 1, 0, Loc); 4343 if (Call.isInvalid()) 4344 return S.StmtError(); 4345 4346 return S.Owned(Call.takeAs<Stmt>()); 4347 } 4348 4349 // - if the subobject is of scalar type, the built-in assignment 4350 // operator is used. 4351 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 4352 if (!ArrayTy) { 4353 OwningExprResult Assignment = S.CreateBuiltinBinOp(Loc, 4354 BinaryOperator::Assign, 4355 To.takeAs<Expr>(), 4356 From.takeAs<Expr>()); 4357 if (Assignment.isInvalid()) 4358 return S.StmtError(); 4359 4360 return S.Owned(Assignment.takeAs<Stmt>()); 4361 } 4362 4363 // - if the subobject is an array, each element is assigned, in the 4364 // manner appropriate to the element type; 4365 4366 // Construct a loop over the array bounds, e.g., 4367 // 4368 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 4369 // 4370 // that will copy each of the array elements. 4371 QualType SizeType = S.Context.getSizeType(); 4372 4373 // Create the iteration variable. 4374 IdentifierInfo *IterationVarName = 0; 4375 { 4376 llvm::SmallString<8> Str; 4377 llvm::raw_svector_ostream OS(Str); 4378 OS << "__i" << Depth; 4379 IterationVarName = &S.Context.Idents.get(OS.str()); 4380 } 4381 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, 4382 IterationVarName, SizeType, 4383 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 4384 VarDecl::None, VarDecl::None); 4385 4386 // Initialize the iteration variable to zero. 4387 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 4388 IterationVar->setInit(new (S.Context) IntegerLiteral(Zero, SizeType, Loc)); 4389 4390 // Create a reference to the iteration variable; we'll use this several 4391 // times throughout. 4392 Expr *IterationVarRef 4393 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>(); 4394 assert(IterationVarRef && "Reference to invented variable cannot fail!"); 4395 4396 // Create the DeclStmt that holds the iteration variable. 4397 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 4398 4399 // Create the comparison against the array bound. 4400 llvm::APInt Upper = ArrayTy->getSize(); 4401 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType)); 4402 OwningExprResult Comparison 4403 = S.Owned(new (S.Context) BinaryOperator(IterationVarRef->Retain(), 4404 new (S.Context) IntegerLiteral(Upper, SizeType, Loc), 4405 BinaryOperator::NE, S.Context.BoolTy, Loc)); 4406 4407 // Create the pre-increment of the iteration variable. 4408 OwningExprResult Increment 4409 = S.Owned(new (S.Context) UnaryOperator(IterationVarRef->Retain(), 4410 UnaryOperator::PreInc, 4411 SizeType, Loc)); 4412 4413 // Subscript the "from" and "to" expressions with the iteration variable. 4414 From = S.CreateBuiltinArraySubscriptExpr(move(From), Loc, 4415 S.Owned(IterationVarRef->Retain()), 4416 Loc); 4417 To = S.CreateBuiltinArraySubscriptExpr(move(To), Loc, 4418 S.Owned(IterationVarRef->Retain()), 4419 Loc); 4420 assert(!From.isInvalid() && "Builtin subscripting can't fail!"); 4421 assert(!To.isInvalid() && "Builtin subscripting can't fail!"); 4422 4423 // Build the copy for an individual element of the array. 4424 OwningStmtResult Copy = BuildSingleCopyAssign(S, Loc, 4425 ArrayTy->getElementType(), 4426 move(To), move(From), 4427 CopyingBaseSubobject, Depth+1); 4428 if (Copy.isInvalid()) { 4429 InitStmt->Destroy(S.Context); 4430 return S.StmtError(); 4431 } 4432 4433 // Construct the loop that copies all elements of this array. 4434 return S.ActOnForStmt(Loc, Loc, S.Owned(InitStmt), 4435 S.MakeFullExpr(Comparison), 4436 Sema::DeclPtrTy(), 4437 S.MakeFullExpr(Increment), 4438 Loc, move(Copy)); 4439} 4440 4441void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 4442 CXXMethodDecl *CopyAssignOperator) { 4443 assert((CopyAssignOperator->isImplicit() && 4444 CopyAssignOperator->isOverloadedOperator() && 4445 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 4446 !CopyAssignOperator->isUsed()) && 4447 "DefineImplicitCopyAssignment called for wrong function"); 4448 4449 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 4450 4451 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) { 4452 CopyAssignOperator->setInvalidDecl(); 4453 return; 4454 } 4455 4456 CopyAssignOperator->setUsed(); 4457 4458 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator); 4459 ErrorTrap Trap(*this); 4460 4461 // C++0x [class.copy]p30: 4462 // The implicitly-defined or explicitly-defaulted copy assignment operator 4463 // for a non-union class X performs memberwise copy assignment of its 4464 // subobjects. The direct base classes of X are assigned first, in the 4465 // order of their declaration in the base-specifier-list, and then the 4466 // immediate non-static data members of X are assigned, in the order in 4467 // which they were declared in the class definition. 4468 4469 // The statements that form the synthesized function body. 4470 ASTOwningVector<&ActionBase::DeleteStmt> Statements(*this); 4471 4472 // The parameter for the "other" object, which we are copying from. 4473 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 4474 Qualifiers OtherQuals = Other->getType().getQualifiers(); 4475 QualType OtherRefType = Other->getType(); 4476 if (const LValueReferenceType *OtherRef 4477 = OtherRefType->getAs<LValueReferenceType>()) { 4478 OtherRefType = OtherRef->getPointeeType(); 4479 OtherQuals = OtherRefType.getQualifiers(); 4480 } 4481 4482 // Our location for everything implicitly-generated. 4483 SourceLocation Loc = CopyAssignOperator->getLocation(); 4484 4485 // Construct a reference to the "other" object. We'll be using this 4486 // throughout the generated ASTs. 4487 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>(); 4488 assert(OtherRef && "Reference to parameter cannot fail!"); 4489 4490 // Construct the "this" pointer. We'll be using this throughout the generated 4491 // ASTs. 4492 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>(); 4493 assert(This && "Reference to this cannot fail!"); 4494 4495 // Assign base classes. 4496 bool Invalid = false; 4497 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 4498 E = ClassDecl->bases_end(); Base != E; ++Base) { 4499 // Form the assignment: 4500 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 4501 QualType BaseType = Base->getType().getUnqualifiedType(); 4502 CXXRecordDecl *BaseClassDecl = 0; 4503 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>()) 4504 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl()); 4505 else { 4506 Invalid = true; 4507 continue; 4508 } 4509 4510 // Construct the "from" expression, which is an implicit cast to the 4511 // appropriately-qualified base type. 4512 Expr *From = OtherRef->Retain(); 4513 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals), 4514 CastExpr::CK_UncheckedDerivedToBase, /*isLvalue=*/true, 4515 CXXBaseSpecifierArray(Base)); 4516 4517 // Dereference "this". 4518 OwningExprResult To = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref, 4519 Owned(This->Retain())); 4520 4521 // Implicitly cast "this" to the appropriately-qualified base type. 4522 Expr *ToE = To.takeAs<Expr>(); 4523 ImpCastExprToType(ToE, 4524 Context.getCVRQualifiedType(BaseType, 4525 CopyAssignOperator->getTypeQualifiers()), 4526 CastExpr::CK_UncheckedDerivedToBase, 4527 /*isLvalue=*/true, CXXBaseSpecifierArray(Base)); 4528 To = Owned(ToE); 4529 4530 // Build the copy. 4531 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType, 4532 move(To), Owned(From), 4533 /*CopyingBaseSubobject=*/true); 4534 if (Copy.isInvalid()) { 4535 Diag(CurrentLocation, diag::note_member_synthesized_at) 4536 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 4537 CopyAssignOperator->setInvalidDecl(); 4538 return; 4539 } 4540 4541 // Success! Record the copy. 4542 Statements.push_back(Copy.takeAs<Expr>()); 4543 } 4544 4545 // \brief Reference to the __builtin_memcpy function. 4546 Expr *BuiltinMemCpyRef = 0; 4547 4548 // Assign non-static members. 4549 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 4550 FieldEnd = ClassDecl->field_end(); 4551 Field != FieldEnd; ++Field) { 4552 // Check for members of reference type; we can't copy those. 4553 if (Field->getType()->isReferenceType()) { 4554 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 4555 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 4556 Diag(Field->getLocation(), diag::note_declared_at); 4557 Diag(CurrentLocation, diag::note_member_synthesized_at) 4558 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 4559 Invalid = true; 4560 continue; 4561 } 4562 4563 // Check for members of const-qualified, non-class type. 4564 QualType BaseType = Context.getBaseElementType(Field->getType()); 4565 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 4566 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 4567 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 4568 Diag(Field->getLocation(), diag::note_declared_at); 4569 Diag(CurrentLocation, diag::note_member_synthesized_at) 4570 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 4571 Invalid = true; 4572 continue; 4573 } 4574 4575 QualType FieldType = Field->getType().getNonReferenceType(); 4576 if (FieldType->isIncompleteArrayType()) { 4577 assert(ClassDecl->hasFlexibleArrayMember() && 4578 "Incomplete array type is not valid"); 4579 continue; 4580 } 4581 4582 // Build references to the field in the object we're copying from and to. 4583 CXXScopeSpec SS; // Intentionally empty 4584 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 4585 LookupMemberName); 4586 MemberLookup.addDecl(*Field); 4587 MemberLookup.resolveKind(); 4588 OwningExprResult From = BuildMemberReferenceExpr(Owned(OtherRef->Retain()), 4589 OtherRefType, 4590 Loc, /*IsArrow=*/false, 4591 SS, 0, MemberLookup, 0); 4592 OwningExprResult To = BuildMemberReferenceExpr(Owned(This->Retain()), 4593 This->getType(), 4594 Loc, /*IsArrow=*/true, 4595 SS, 0, MemberLookup, 0); 4596 assert(!From.isInvalid() && "Implicit field reference cannot fail"); 4597 assert(!To.isInvalid() && "Implicit field reference cannot fail"); 4598 4599 // If the field should be copied with __builtin_memcpy rather than via 4600 // explicit assignments, do so. This optimization only applies for arrays 4601 // of scalars and arrays of class type with trivial copy-assignment 4602 // operators. 4603 if (FieldType->isArrayType() && 4604 (!BaseType->isRecordType() || 4605 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()) 4606 ->hasTrivialCopyAssignment())) { 4607 // Compute the size of the memory buffer to be copied. 4608 QualType SizeType = Context.getSizeType(); 4609 llvm::APInt Size(Context.getTypeSize(SizeType), 4610 Context.getTypeSizeInChars(BaseType).getQuantity()); 4611 for (const ConstantArrayType *Array 4612 = Context.getAsConstantArrayType(FieldType); 4613 Array; 4614 Array = Context.getAsConstantArrayType(Array->getElementType())) { 4615 llvm::APInt ArraySize = Array->getSize(); 4616 ArraySize.zextOrTrunc(Size.getBitWidth()); 4617 Size *= ArraySize; 4618 } 4619 4620 // Take the address of the field references for "from" and "to". 4621 From = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(From)); 4622 To = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(To)); 4623 4624 // Create a reference to the __builtin_memcpy builtin function. 4625 if (!BuiltinMemCpyRef) { 4626 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc, 4627 LookupOrdinaryName); 4628 LookupName(R, TUScope, true); 4629 4630 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>(); 4631 if (!BuiltinMemCpy) { 4632 // Something went horribly wrong earlier, and we will have complained 4633 // about it. 4634 Invalid = true; 4635 continue; 4636 } 4637 4638 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy, 4639 BuiltinMemCpy->getType(), 4640 Loc, 0).takeAs<Expr>(); 4641 assert(BuiltinMemCpyRef && "Builtin reference cannot fail"); 4642 } 4643 4644 ASTOwningVector<&ActionBase::DeleteExpr> CallArgs(*this); 4645 CallArgs.push_back(To.takeAs<Expr>()); 4646 CallArgs.push_back(From.takeAs<Expr>()); 4647 CallArgs.push_back(new (Context) IntegerLiteral(Size, SizeType, Loc)); 4648 llvm::SmallVector<SourceLocation, 4> Commas; // FIXME: Silly 4649 Commas.push_back(Loc); 4650 Commas.push_back(Loc); 4651 OwningExprResult Call = ActOnCallExpr(/*Scope=*/0, 4652 Owned(BuiltinMemCpyRef->Retain()), 4653 Loc, move_arg(CallArgs), 4654 Commas.data(), Loc); 4655 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 4656 Statements.push_back(Call.takeAs<Expr>()); 4657 continue; 4658 } 4659 4660 // Build the copy of this field. 4661 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType, 4662 move(To), move(From), 4663 /*CopyingBaseSubobject=*/false); 4664 if (Copy.isInvalid()) { 4665 Diag(CurrentLocation, diag::note_member_synthesized_at) 4666 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 4667 CopyAssignOperator->setInvalidDecl(); 4668 return; 4669 } 4670 4671 // Success! Record the copy. 4672 Statements.push_back(Copy.takeAs<Stmt>()); 4673 } 4674 4675 if (!Invalid) { 4676 // Add a "return *this;" 4677 OwningExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref, 4678 Owned(This->Retain())); 4679 4680 OwningStmtResult Return = ActOnReturnStmt(Loc, move(ThisObj)); 4681 if (Return.isInvalid()) 4682 Invalid = true; 4683 else { 4684 Statements.push_back(Return.takeAs<Stmt>()); 4685 4686 if (Trap.hasErrorOccurred()) { 4687 Diag(CurrentLocation, diag::note_member_synthesized_at) 4688 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl); 4689 Invalid = true; 4690 } 4691 } 4692 } 4693 4694 if (Invalid) { 4695 CopyAssignOperator->setInvalidDecl(); 4696 return; 4697 } 4698 4699 OwningStmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements), 4700 /*isStmtExpr=*/false); 4701 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 4702 CopyAssignOperator->setBody(Body.takeAs<Stmt>()); 4703} 4704 4705void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 4706 CXXConstructorDecl *CopyConstructor, 4707 unsigned TypeQuals) { 4708 assert((CopyConstructor->isImplicit() && 4709 CopyConstructor->isCopyConstructor(TypeQuals) && 4710 !CopyConstructor->isUsed()) && 4711 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 4712 4713 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 4714 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 4715 4716 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor); 4717 ErrorTrap Trap(*this); 4718 4719 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) || 4720 Trap.hasErrorOccurred()) { 4721 Diag(CurrentLocation, diag::note_member_synthesized_at) 4722 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl); 4723 CopyConstructor->setInvalidDecl(); 4724 } else { 4725 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(), 4726 CopyConstructor->getLocation(), 4727 MultiStmtArg(*this, 0, 0), 4728 /*isStmtExpr=*/false) 4729 .takeAs<Stmt>()); 4730 } 4731 4732 CopyConstructor->setUsed(); 4733} 4734 4735Sema::OwningExprResult 4736Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 4737 CXXConstructorDecl *Constructor, 4738 MultiExprArg ExprArgs, 4739 bool RequiresZeroInit, 4740 CXXConstructExpr::ConstructionKind ConstructKind) { 4741 bool Elidable = false; 4742 4743 // C++0x [class.copy]p34: 4744 // When certain criteria are met, an implementation is allowed to 4745 // omit the copy/move construction of a class object, even if the 4746 // copy/move constructor and/or destructor for the object have 4747 // side effects. [...] 4748 // - when a temporary class object that has not been bound to a 4749 // reference (12.2) would be copied/moved to a class object 4750 // with the same cv-unqualified type, the copy/move operation 4751 // can be omitted by constructing the temporary object 4752 // directly into the target of the omitted copy/move 4753 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) { 4754 Expr *SubExpr = ((Expr **)ExprArgs.get())[0]; 4755 Elidable = SubExpr->isTemporaryObject() && 4756 Context.hasSameUnqualifiedType(SubExpr->getType(), 4757 Context.getTypeDeclType(Constructor->getParent())); 4758 } 4759 4760 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 4761 Elidable, move(ExprArgs), RequiresZeroInit, 4762 ConstructKind); 4763} 4764 4765/// BuildCXXConstructExpr - Creates a complete call to a constructor, 4766/// including handling of its default argument expressions. 4767Sema::OwningExprResult 4768Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 4769 CXXConstructorDecl *Constructor, bool Elidable, 4770 MultiExprArg ExprArgs, 4771 bool RequiresZeroInit, 4772 CXXConstructExpr::ConstructionKind ConstructKind) { 4773 unsigned NumExprs = ExprArgs.size(); 4774 Expr **Exprs = (Expr **)ExprArgs.release(); 4775 4776 MarkDeclarationReferenced(ConstructLoc, Constructor); 4777 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc, 4778 Constructor, Elidable, Exprs, NumExprs, 4779 RequiresZeroInit, ConstructKind)); 4780} 4781 4782bool Sema::InitializeVarWithConstructor(VarDecl *VD, 4783 CXXConstructorDecl *Constructor, 4784 MultiExprArg Exprs) { 4785 OwningExprResult TempResult = 4786 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor, 4787 move(Exprs)); 4788 if (TempResult.isInvalid()) 4789 return true; 4790 4791 Expr *Temp = TempResult.takeAs<Expr>(); 4792 MarkDeclarationReferenced(VD->getLocation(), Constructor); 4793 Temp = MaybeCreateCXXExprWithTemporaries(Temp); 4794 VD->setInit(Temp); 4795 4796 return false; 4797} 4798 4799void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 4800 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 4801 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() && 4802 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) { 4803 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context); 4804 MarkDeclarationReferenced(VD->getLocation(), Destructor); 4805 CheckDestructorAccess(VD->getLocation(), Destructor, 4806 PDiag(diag::err_access_dtor_var) 4807 << VD->getDeclName() 4808 << VD->getType()); 4809 } 4810} 4811 4812/// AddCXXDirectInitializerToDecl - This action is called immediately after 4813/// ActOnDeclarator, when a C++ direct initializer is present. 4814/// e.g: "int x(1);" 4815void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl, 4816 SourceLocation LParenLoc, 4817 MultiExprArg Exprs, 4818 SourceLocation *CommaLocs, 4819 SourceLocation RParenLoc) { 4820 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions"); 4821 Decl *RealDecl = Dcl.getAs<Decl>(); 4822 4823 // If there is no declaration, there was an error parsing it. Just ignore 4824 // the initializer. 4825 if (RealDecl == 0) 4826 return; 4827 4828 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 4829 if (!VDecl) { 4830 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 4831 RealDecl->setInvalidDecl(); 4832 return; 4833 } 4834 4835 // We will represent direct-initialization similarly to copy-initialization: 4836 // int x(1); -as-> int x = 1; 4837 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 4838 // 4839 // Clients that want to distinguish between the two forms, can check for 4840 // direct initializer using VarDecl::hasCXXDirectInitializer(). 4841 // A major benefit is that clients that don't particularly care about which 4842 // exactly form was it (like the CodeGen) can handle both cases without 4843 // special case code. 4844 4845 // C++ 8.5p11: 4846 // The form of initialization (using parentheses or '=') is generally 4847 // insignificant, but does matter when the entity being initialized has a 4848 // class type. 4849 QualType DeclInitType = VDecl->getType(); 4850 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 4851 DeclInitType = Context.getBaseElementType(Array); 4852 4853 if (!VDecl->getType()->isDependentType() && 4854 RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 4855 diag::err_typecheck_decl_incomplete_type)) { 4856 VDecl->setInvalidDecl(); 4857 return; 4858 } 4859 4860 // The variable can not have an abstract class type. 4861 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 4862 diag::err_abstract_type_in_decl, 4863 AbstractVariableType)) 4864 VDecl->setInvalidDecl(); 4865 4866 const VarDecl *Def; 4867 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 4868 Diag(VDecl->getLocation(), diag::err_redefinition) 4869 << VDecl->getDeclName(); 4870 Diag(Def->getLocation(), diag::note_previous_definition); 4871 VDecl->setInvalidDecl(); 4872 return; 4873 } 4874 4875 // If either the declaration has a dependent type or if any of the 4876 // expressions is type-dependent, we represent the initialization 4877 // via a ParenListExpr for later use during template instantiation. 4878 if (VDecl->getType()->isDependentType() || 4879 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) { 4880 // Let clients know that initialization was done with a direct initializer. 4881 VDecl->setCXXDirectInitializer(true); 4882 4883 // Store the initialization expressions as a ParenListExpr. 4884 unsigned NumExprs = Exprs.size(); 4885 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc, 4886 (Expr **)Exprs.release(), 4887 NumExprs, RParenLoc)); 4888 return; 4889 } 4890 4891 // Capture the variable that is being initialized and the style of 4892 // initialization. 4893 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 4894 4895 // FIXME: Poor source location information. 4896 InitializationKind Kind 4897 = InitializationKind::CreateDirect(VDecl->getLocation(), 4898 LParenLoc, RParenLoc); 4899 4900 InitializationSequence InitSeq(*this, Entity, Kind, 4901 (Expr**)Exprs.get(), Exprs.size()); 4902 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs)); 4903 if (Result.isInvalid()) { 4904 VDecl->setInvalidDecl(); 4905 return; 4906 } 4907 4908 Result = MaybeCreateCXXExprWithTemporaries(move(Result)); 4909 VDecl->setInit(Result.takeAs<Expr>()); 4910 VDecl->setCXXDirectInitializer(true); 4911 4912 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>()) 4913 FinalizeVarWithDestructor(VDecl, Record); 4914} 4915 4916/// \brief Given a constructor and the set of arguments provided for the 4917/// constructor, convert the arguments and add any required default arguments 4918/// to form a proper call to this constructor. 4919/// 4920/// \returns true if an error occurred, false otherwise. 4921bool 4922Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 4923 MultiExprArg ArgsPtr, 4924 SourceLocation Loc, 4925 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) { 4926 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 4927 unsigned NumArgs = ArgsPtr.size(); 4928 Expr **Args = (Expr **)ArgsPtr.get(); 4929 4930 const FunctionProtoType *Proto 4931 = Constructor->getType()->getAs<FunctionProtoType>(); 4932 assert(Proto && "Constructor without a prototype?"); 4933 unsigned NumArgsInProto = Proto->getNumArgs(); 4934 4935 // If too few arguments are available, we'll fill in the rest with defaults. 4936 if (NumArgs < NumArgsInProto) 4937 ConvertedArgs.reserve(NumArgsInProto); 4938 else 4939 ConvertedArgs.reserve(NumArgs); 4940 4941 VariadicCallType CallType = 4942 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4943 llvm::SmallVector<Expr *, 8> AllArgs; 4944 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 4945 Proto, 0, Args, NumArgs, AllArgs, 4946 CallType); 4947 for (unsigned i =0, size = AllArgs.size(); i < size; i++) 4948 ConvertedArgs.push_back(AllArgs[i]); 4949 return Invalid; 4950} 4951 4952static inline bool 4953CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 4954 const FunctionDecl *FnDecl) { 4955 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext(); 4956 if (isa<NamespaceDecl>(DC)) { 4957 return SemaRef.Diag(FnDecl->getLocation(), 4958 diag::err_operator_new_delete_declared_in_namespace) 4959 << FnDecl->getDeclName(); 4960 } 4961 4962 if (isa<TranslationUnitDecl>(DC) && 4963 FnDecl->getStorageClass() == FunctionDecl::Static) { 4964 return SemaRef.Diag(FnDecl->getLocation(), 4965 diag::err_operator_new_delete_declared_static) 4966 << FnDecl->getDeclName(); 4967 } 4968 4969 return false; 4970} 4971 4972static inline bool 4973CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 4974 CanQualType ExpectedResultType, 4975 CanQualType ExpectedFirstParamType, 4976 unsigned DependentParamTypeDiag, 4977 unsigned InvalidParamTypeDiag) { 4978 QualType ResultType = 4979 FnDecl->getType()->getAs<FunctionType>()->getResultType(); 4980 4981 // Check that the result type is not dependent. 4982 if (ResultType->isDependentType()) 4983 return SemaRef.Diag(FnDecl->getLocation(), 4984 diag::err_operator_new_delete_dependent_result_type) 4985 << FnDecl->getDeclName() << ExpectedResultType; 4986 4987 // Check that the result type is what we expect. 4988 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 4989 return SemaRef.Diag(FnDecl->getLocation(), 4990 diag::err_operator_new_delete_invalid_result_type) 4991 << FnDecl->getDeclName() << ExpectedResultType; 4992 4993 // A function template must have at least 2 parameters. 4994 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 4995 return SemaRef.Diag(FnDecl->getLocation(), 4996 diag::err_operator_new_delete_template_too_few_parameters) 4997 << FnDecl->getDeclName(); 4998 4999 // The function decl must have at least 1 parameter. 5000 if (FnDecl->getNumParams() == 0) 5001 return SemaRef.Diag(FnDecl->getLocation(), 5002 diag::err_operator_new_delete_too_few_parameters) 5003 << FnDecl->getDeclName(); 5004 5005 // Check the the first parameter type is not dependent. 5006 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 5007 if (FirstParamType->isDependentType()) 5008 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 5009 << FnDecl->getDeclName() << ExpectedFirstParamType; 5010 5011 // Check that the first parameter type is what we expect. 5012 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 5013 ExpectedFirstParamType) 5014 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 5015 << FnDecl->getDeclName() << ExpectedFirstParamType; 5016 5017 return false; 5018} 5019 5020static bool 5021CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 5022 // C++ [basic.stc.dynamic.allocation]p1: 5023 // A program is ill-formed if an allocation function is declared in a 5024 // namespace scope other than global scope or declared static in global 5025 // scope. 5026 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 5027 return true; 5028 5029 CanQualType SizeTy = 5030 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 5031 5032 // C++ [basic.stc.dynamic.allocation]p1: 5033 // The return type shall be void*. The first parameter shall have type 5034 // std::size_t. 5035 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 5036 SizeTy, 5037 diag::err_operator_new_dependent_param_type, 5038 diag::err_operator_new_param_type)) 5039 return true; 5040 5041 // C++ [basic.stc.dynamic.allocation]p1: 5042 // The first parameter shall not have an associated default argument. 5043 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 5044 return SemaRef.Diag(FnDecl->getLocation(), 5045 diag::err_operator_new_default_arg) 5046 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 5047 5048 return false; 5049} 5050 5051static bool 5052CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 5053 // C++ [basic.stc.dynamic.deallocation]p1: 5054 // A program is ill-formed if deallocation functions are declared in a 5055 // namespace scope other than global scope or declared static in global 5056 // scope. 5057 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 5058 return true; 5059 5060 // C++ [basic.stc.dynamic.deallocation]p2: 5061 // Each deallocation function shall return void and its first parameter 5062 // shall be void*. 5063 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 5064 SemaRef.Context.VoidPtrTy, 5065 diag::err_operator_delete_dependent_param_type, 5066 diag::err_operator_delete_param_type)) 5067 return true; 5068 5069 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 5070 if (FirstParamType->isDependentType()) 5071 return SemaRef.Diag(FnDecl->getLocation(), 5072 diag::err_operator_delete_dependent_param_type) 5073 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy; 5074 5075 if (SemaRef.Context.getCanonicalType(FirstParamType) != 5076 SemaRef.Context.VoidPtrTy) 5077 return SemaRef.Diag(FnDecl->getLocation(), 5078 diag::err_operator_delete_param_type) 5079 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy; 5080 5081 return false; 5082} 5083 5084/// CheckOverloadedOperatorDeclaration - Check whether the declaration 5085/// of this overloaded operator is well-formed. If so, returns false; 5086/// otherwise, emits appropriate diagnostics and returns true. 5087bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 5088 assert(FnDecl && FnDecl->isOverloadedOperator() && 5089 "Expected an overloaded operator declaration"); 5090 5091 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 5092 5093 // C++ [over.oper]p5: 5094 // The allocation and deallocation functions, operator new, 5095 // operator new[], operator delete and operator delete[], are 5096 // described completely in 3.7.3. The attributes and restrictions 5097 // found in the rest of this subclause do not apply to them unless 5098 // explicitly stated in 3.7.3. 5099 if (Op == OO_Delete || Op == OO_Array_Delete) 5100 return CheckOperatorDeleteDeclaration(*this, FnDecl); 5101 5102 if (Op == OO_New || Op == OO_Array_New) 5103 return CheckOperatorNewDeclaration(*this, FnDecl); 5104 5105 // C++ [over.oper]p6: 5106 // An operator function shall either be a non-static member 5107 // function or be a non-member function and have at least one 5108 // parameter whose type is a class, a reference to a class, an 5109 // enumeration, or a reference to an enumeration. 5110 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 5111 if (MethodDecl->isStatic()) 5112 return Diag(FnDecl->getLocation(), 5113 diag::err_operator_overload_static) << FnDecl->getDeclName(); 5114 } else { 5115 bool ClassOrEnumParam = false; 5116 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 5117 ParamEnd = FnDecl->param_end(); 5118 Param != ParamEnd; ++Param) { 5119 QualType ParamType = (*Param)->getType().getNonReferenceType(); 5120 if (ParamType->isDependentType() || ParamType->isRecordType() || 5121 ParamType->isEnumeralType()) { 5122 ClassOrEnumParam = true; 5123 break; 5124 } 5125 } 5126 5127 if (!ClassOrEnumParam) 5128 return Diag(FnDecl->getLocation(), 5129 diag::err_operator_overload_needs_class_or_enum) 5130 << FnDecl->getDeclName(); 5131 } 5132 5133 // C++ [over.oper]p8: 5134 // An operator function cannot have default arguments (8.3.6), 5135 // except where explicitly stated below. 5136 // 5137 // Only the function-call operator allows default arguments 5138 // (C++ [over.call]p1). 5139 if (Op != OO_Call) { 5140 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 5141 Param != FnDecl->param_end(); ++Param) { 5142 if ((*Param)->hasDefaultArg()) 5143 return Diag((*Param)->getLocation(), 5144 diag::err_operator_overload_default_arg) 5145 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange(); 5146 } 5147 } 5148 5149 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 5150 { false, false, false } 5151#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 5152 , { Unary, Binary, MemberOnly } 5153#include "clang/Basic/OperatorKinds.def" 5154 }; 5155 5156 bool CanBeUnaryOperator = OperatorUses[Op][0]; 5157 bool CanBeBinaryOperator = OperatorUses[Op][1]; 5158 bool MustBeMemberOperator = OperatorUses[Op][2]; 5159 5160 // C++ [over.oper]p8: 5161 // [...] Operator functions cannot have more or fewer parameters 5162 // than the number required for the corresponding operator, as 5163 // described in the rest of this subclause. 5164 unsigned NumParams = FnDecl->getNumParams() 5165 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 5166 if (Op != OO_Call && 5167 ((NumParams == 1 && !CanBeUnaryOperator) || 5168 (NumParams == 2 && !CanBeBinaryOperator) || 5169 (NumParams < 1) || (NumParams > 2))) { 5170 // We have the wrong number of parameters. 5171 unsigned ErrorKind; 5172 if (CanBeUnaryOperator && CanBeBinaryOperator) { 5173 ErrorKind = 2; // 2 -> unary or binary. 5174 } else if (CanBeUnaryOperator) { 5175 ErrorKind = 0; // 0 -> unary 5176 } else { 5177 assert(CanBeBinaryOperator && 5178 "All non-call overloaded operators are unary or binary!"); 5179 ErrorKind = 1; // 1 -> binary 5180 } 5181 5182 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 5183 << FnDecl->getDeclName() << NumParams << ErrorKind; 5184 } 5185 5186 // Overloaded operators other than operator() cannot be variadic. 5187 if (Op != OO_Call && 5188 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 5189 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 5190 << FnDecl->getDeclName(); 5191 } 5192 5193 // Some operators must be non-static member functions. 5194 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 5195 return Diag(FnDecl->getLocation(), 5196 diag::err_operator_overload_must_be_member) 5197 << FnDecl->getDeclName(); 5198 } 5199 5200 // C++ [over.inc]p1: 5201 // The user-defined function called operator++ implements the 5202 // prefix and postfix ++ operator. If this function is a member 5203 // function with no parameters, or a non-member function with one 5204 // parameter of class or enumeration type, it defines the prefix 5205 // increment operator ++ for objects of that type. If the function 5206 // is a member function with one parameter (which shall be of type 5207 // int) or a non-member function with two parameters (the second 5208 // of which shall be of type int), it defines the postfix 5209 // increment operator ++ for objects of that type. 5210 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 5211 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 5212 bool ParamIsInt = false; 5213 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>()) 5214 ParamIsInt = BT->getKind() == BuiltinType::Int; 5215 5216 if (!ParamIsInt) 5217 return Diag(LastParam->getLocation(), 5218 diag::err_operator_overload_post_incdec_must_be_int) 5219 << LastParam->getType() << (Op == OO_MinusMinus); 5220 } 5221 5222 // Notify the class if it got an assignment operator. 5223 if (Op == OO_Equal) { 5224 // Would have returned earlier otherwise. 5225 assert(isa<CXXMethodDecl>(FnDecl) && 5226 "Overloaded = not member, but not filtered."); 5227 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 5228 Method->getParent()->addedAssignmentOperator(Context, Method); 5229 } 5230 5231 return false; 5232} 5233 5234/// CheckLiteralOperatorDeclaration - Check whether the declaration 5235/// of this literal operator function is well-formed. If so, returns 5236/// false; otherwise, emits appropriate diagnostics and returns true. 5237bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 5238 DeclContext *DC = FnDecl->getDeclContext(); 5239 Decl::Kind Kind = DC->getDeclKind(); 5240 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace && 5241 Kind != Decl::LinkageSpec) { 5242 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 5243 << FnDecl->getDeclName(); 5244 return true; 5245 } 5246 5247 bool Valid = false; 5248 5249 // template <char...> type operator "" name() is the only valid template 5250 // signature, and the only valid signature with no parameters. 5251 if (FnDecl->param_size() == 0) { 5252 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) { 5253 // Must have only one template parameter 5254 TemplateParameterList *Params = TpDecl->getTemplateParameters(); 5255 if (Params->size() == 1) { 5256 NonTypeTemplateParmDecl *PmDecl = 5257 cast<NonTypeTemplateParmDecl>(Params->getParam(0)); 5258 5259 // The template parameter must be a char parameter pack. 5260 // FIXME: This test will always fail because non-type parameter packs 5261 // have not been implemented. 5262 if (PmDecl && PmDecl->isTemplateParameterPack() && 5263 Context.hasSameType(PmDecl->getType(), Context.CharTy)) 5264 Valid = true; 5265 } 5266 } 5267 } else { 5268 // Check the first parameter 5269 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 5270 5271 QualType T = (*Param)->getType(); 5272 5273 // unsigned long long int, long double, and any character type are allowed 5274 // as the only parameters. 5275 if (Context.hasSameType(T, Context.UnsignedLongLongTy) || 5276 Context.hasSameType(T, Context.LongDoubleTy) || 5277 Context.hasSameType(T, Context.CharTy) || 5278 Context.hasSameType(T, Context.WCharTy) || 5279 Context.hasSameType(T, Context.Char16Ty) || 5280 Context.hasSameType(T, Context.Char32Ty)) { 5281 if (++Param == FnDecl->param_end()) 5282 Valid = true; 5283 goto FinishedParams; 5284 } 5285 5286 // Otherwise it must be a pointer to const; let's strip those qualifiers. 5287 const PointerType *PT = T->getAs<PointerType>(); 5288 if (!PT) 5289 goto FinishedParams; 5290 T = PT->getPointeeType(); 5291 if (!T.isConstQualified()) 5292 goto FinishedParams; 5293 T = T.getUnqualifiedType(); 5294 5295 // Move on to the second parameter; 5296 ++Param; 5297 5298 // If there is no second parameter, the first must be a const char * 5299 if (Param == FnDecl->param_end()) { 5300 if (Context.hasSameType(T, Context.CharTy)) 5301 Valid = true; 5302 goto FinishedParams; 5303 } 5304 5305 // const char *, const wchar_t*, const char16_t*, and const char32_t* 5306 // are allowed as the first parameter to a two-parameter function 5307 if (!(Context.hasSameType(T, Context.CharTy) || 5308 Context.hasSameType(T, Context.WCharTy) || 5309 Context.hasSameType(T, Context.Char16Ty) || 5310 Context.hasSameType(T, Context.Char32Ty))) 5311 goto FinishedParams; 5312 5313 // The second and final parameter must be an std::size_t 5314 T = (*Param)->getType().getUnqualifiedType(); 5315 if (Context.hasSameType(T, Context.getSizeType()) && 5316 ++Param == FnDecl->param_end()) 5317 Valid = true; 5318 } 5319 5320 // FIXME: This diagnostic is absolutely terrible. 5321FinishedParams: 5322 if (!Valid) { 5323 Diag(FnDecl->getLocation(), diag::err_literal_operator_params) 5324 << FnDecl->getDeclName(); 5325 return true; 5326 } 5327 5328 return false; 5329} 5330 5331/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 5332/// linkage specification, including the language and (if present) 5333/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 5334/// the location of the language string literal, which is provided 5335/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 5336/// the '{' brace. Otherwise, this linkage specification does not 5337/// have any braces. 5338Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S, 5339 SourceLocation ExternLoc, 5340 SourceLocation LangLoc, 5341 llvm::StringRef Lang, 5342 SourceLocation LBraceLoc) { 5343 LinkageSpecDecl::LanguageIDs Language; 5344 if (Lang == "\"C\"") 5345 Language = LinkageSpecDecl::lang_c; 5346 else if (Lang == "\"C++\"") 5347 Language = LinkageSpecDecl::lang_cxx; 5348 else { 5349 Diag(LangLoc, diag::err_bad_language); 5350 return DeclPtrTy(); 5351 } 5352 5353 // FIXME: Add all the various semantics of linkage specifications 5354 5355 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 5356 LangLoc, Language, 5357 LBraceLoc.isValid()); 5358 CurContext->addDecl(D); 5359 PushDeclContext(S, D); 5360 return DeclPtrTy::make(D); 5361} 5362 5363/// ActOnFinishLinkageSpecification - Completely the definition of 5364/// the C++ linkage specification LinkageSpec. If RBraceLoc is 5365/// valid, it's the position of the closing '}' brace in a linkage 5366/// specification that uses braces. 5367Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S, 5368 DeclPtrTy LinkageSpec, 5369 SourceLocation RBraceLoc) { 5370 if (LinkageSpec) 5371 PopDeclContext(); 5372 return LinkageSpec; 5373} 5374 5375/// \brief Perform semantic analysis for the variable declaration that 5376/// occurs within a C++ catch clause, returning the newly-created 5377/// variable. 5378VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType, 5379 TypeSourceInfo *TInfo, 5380 IdentifierInfo *Name, 5381 SourceLocation Loc, 5382 SourceRange Range) { 5383 bool Invalid = false; 5384 5385 // Arrays and functions decay. 5386 if (ExDeclType->isArrayType()) 5387 ExDeclType = Context.getArrayDecayedType(ExDeclType); 5388 else if (ExDeclType->isFunctionType()) 5389 ExDeclType = Context.getPointerType(ExDeclType); 5390 5391 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 5392 // The exception-declaration shall not denote a pointer or reference to an 5393 // incomplete type, other than [cv] void*. 5394 // N2844 forbids rvalue references. 5395 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 5396 Diag(Loc, diag::err_catch_rvalue_ref) << Range; 5397 Invalid = true; 5398 } 5399 5400 // GCC allows catching pointers and references to incomplete types 5401 // as an extension; so do we, but we warn by default. 5402 5403 QualType BaseType = ExDeclType; 5404 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 5405 unsigned DK = diag::err_catch_incomplete; 5406 bool IncompleteCatchIsInvalid = true; 5407 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 5408 BaseType = Ptr->getPointeeType(); 5409 Mode = 1; 5410 DK = diag::ext_catch_incomplete_ptr; 5411 IncompleteCatchIsInvalid = false; 5412 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 5413 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 5414 BaseType = Ref->getPointeeType(); 5415 Mode = 2; 5416 DK = diag::ext_catch_incomplete_ref; 5417 IncompleteCatchIsInvalid = false; 5418 } 5419 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 5420 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) && 5421 IncompleteCatchIsInvalid) 5422 Invalid = true; 5423 5424 if (!Invalid && !ExDeclType->isDependentType() && 5425 RequireNonAbstractType(Loc, ExDeclType, 5426 diag::err_abstract_type_in_decl, 5427 AbstractVariableType)) 5428 Invalid = true; 5429 5430 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc, 5431 Name, ExDeclType, TInfo, VarDecl::None, 5432 VarDecl::None); 5433 ExDecl->setExceptionVariable(true); 5434 5435 if (!Invalid) { 5436 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) { 5437 // C++ [except.handle]p16: 5438 // The object declared in an exception-declaration or, if the 5439 // exception-declaration does not specify a name, a temporary (12.2) is 5440 // copy-initialized (8.5) from the exception object. [...] 5441 // The object is destroyed when the handler exits, after the destruction 5442 // of any automatic objects initialized within the handler. 5443 // 5444 // We just pretend to initialize the object with itself, then make sure 5445 // it can be destroyed later. 5446 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl); 5447 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl, 5448 Loc, ExDeclType, 0); 5449 InitializationKind Kind = InitializationKind::CreateCopy(Loc, 5450 SourceLocation()); 5451 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1); 5452 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, 5453 MultiExprArg(*this, (void**)&ExDeclRef, 1)); 5454 if (Result.isInvalid()) 5455 Invalid = true; 5456 else 5457 FinalizeVarWithDestructor(ExDecl, RecordTy); 5458 } 5459 } 5460 5461 if (Invalid) 5462 ExDecl->setInvalidDecl(); 5463 5464 return ExDecl; 5465} 5466 5467/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 5468/// handler. 5469Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 5470 TypeSourceInfo *TInfo = 0; 5471 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo); 5472 5473 bool Invalid = D.isInvalidType(); 5474 IdentifierInfo *II = D.getIdentifier(); 5475 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 5476 LookupOrdinaryName, 5477 ForRedeclaration)) { 5478 // The scope should be freshly made just for us. There is just no way 5479 // it contains any previous declaration. 5480 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl))); 5481 if (PrevDecl->isTemplateParameter()) { 5482 // Maybe we will complain about the shadowed template parameter. 5483 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 5484 } 5485 } 5486 5487 if (D.getCXXScopeSpec().isSet() && !Invalid) { 5488 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 5489 << D.getCXXScopeSpec().getRange(); 5490 Invalid = true; 5491 } 5492 5493 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo, 5494 D.getIdentifier(), 5495 D.getIdentifierLoc(), 5496 D.getDeclSpec().getSourceRange()); 5497 5498 if (Invalid) 5499 ExDecl->setInvalidDecl(); 5500 5501 // Add the exception declaration into this scope. 5502 if (II) 5503 PushOnScopeChains(ExDecl, S); 5504 else 5505 CurContext->addDecl(ExDecl); 5506 5507 ProcessDeclAttributes(S, ExDecl, D); 5508 return DeclPtrTy::make(ExDecl); 5509} 5510 5511Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc, 5512 ExprArg assertexpr, 5513 ExprArg assertmessageexpr) { 5514 Expr *AssertExpr = (Expr *)assertexpr.get(); 5515 StringLiteral *AssertMessage = 5516 cast<StringLiteral>((Expr *)assertmessageexpr.get()); 5517 5518 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 5519 llvm::APSInt Value(32); 5520 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 5521 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) << 5522 AssertExpr->getSourceRange(); 5523 return DeclPtrTy(); 5524 } 5525 5526 if (Value == 0) { 5527 Diag(AssertLoc, diag::err_static_assert_failed) 5528 << AssertMessage->getString() << AssertExpr->getSourceRange(); 5529 } 5530 } 5531 5532 assertexpr.release(); 5533 assertmessageexpr.release(); 5534 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc, 5535 AssertExpr, AssertMessage); 5536 5537 CurContext->addDecl(Decl); 5538 return DeclPtrTy::make(Decl); 5539} 5540 5541/// \brief Perform semantic analysis of the given friend type declaration. 5542/// 5543/// \returns A friend declaration that. 5544FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc, 5545 TypeSourceInfo *TSInfo) { 5546 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 5547 5548 QualType T = TSInfo->getType(); 5549 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 5550 5551 if (!getLangOptions().CPlusPlus0x) { 5552 // C++03 [class.friend]p2: 5553 // An elaborated-type-specifier shall be used in a friend declaration 5554 // for a class.* 5555 // 5556 // * The class-key of the elaborated-type-specifier is required. 5557 if (!ActiveTemplateInstantiations.empty()) { 5558 // Do not complain about the form of friend template types during 5559 // template instantiation; we will already have complained when the 5560 // template was declared. 5561 } else if (!T->isElaboratedTypeSpecifier()) { 5562 // If we evaluated the type to a record type, suggest putting 5563 // a tag in front. 5564 if (const RecordType *RT = T->getAs<RecordType>()) { 5565 RecordDecl *RD = RT->getDecl(); 5566 5567 std::string InsertionText = std::string(" ") + RD->getKindName(); 5568 5569 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type) 5570 << (unsigned) RD->getTagKind() 5571 << T 5572 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc), 5573 InsertionText); 5574 } else { 5575 Diag(FriendLoc, diag::ext_nonclass_type_friend) 5576 << T 5577 << SourceRange(FriendLoc, TypeRange.getEnd()); 5578 } 5579 } else if (T->getAs<EnumType>()) { 5580 Diag(FriendLoc, diag::ext_enum_friend) 5581 << T 5582 << SourceRange(FriendLoc, TypeRange.getEnd()); 5583 } 5584 } 5585 5586 // C++0x [class.friend]p3: 5587 // If the type specifier in a friend declaration designates a (possibly 5588 // cv-qualified) class type, that class is declared as a friend; otherwise, 5589 // the friend declaration is ignored. 5590 5591 // FIXME: C++0x has some syntactic restrictions on friend type declarations 5592 // in [class.friend]p3 that we do not implement. 5593 5594 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc); 5595} 5596 5597/// Handle a friend type declaration. This works in tandem with 5598/// ActOnTag. 5599/// 5600/// Notes on friend class templates: 5601/// 5602/// We generally treat friend class declarations as if they were 5603/// declaring a class. So, for example, the elaborated type specifier 5604/// in a friend declaration is required to obey the restrictions of a 5605/// class-head (i.e. no typedefs in the scope chain), template 5606/// parameters are required to match up with simple template-ids, &c. 5607/// However, unlike when declaring a template specialization, it's 5608/// okay to refer to a template specialization without an empty 5609/// template parameter declaration, e.g. 5610/// friend class A<T>::B<unsigned>; 5611/// We permit this as a special case; if there are any template 5612/// parameters present at all, require proper matching, i.e. 5613/// template <> template <class T> friend class A<int>::B; 5614Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 5615 MultiTemplateParamsArg TempParams) { 5616 SourceLocation Loc = DS.getSourceRange().getBegin(); 5617 5618 assert(DS.isFriendSpecified()); 5619 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 5620 5621 // Try to convert the decl specifier to a type. This works for 5622 // friend templates because ActOnTag never produces a ClassTemplateDecl 5623 // for a TUK_Friend. 5624 Declarator TheDeclarator(DS, Declarator::MemberContext); 5625 TypeSourceInfo *TSI; 5626 QualType T = GetTypeForDeclarator(TheDeclarator, S, &TSI); 5627 if (TheDeclarator.isInvalidType()) 5628 return DeclPtrTy(); 5629 5630 if (!TSI) 5631 TSI = Context.getTrivialTypeSourceInfo(T, DS.getSourceRange().getBegin()); 5632 5633 // This is definitely an error in C++98. It's probably meant to 5634 // be forbidden in C++0x, too, but the specification is just 5635 // poorly written. 5636 // 5637 // The problem is with declarations like the following: 5638 // template <T> friend A<T>::foo; 5639 // where deciding whether a class C is a friend or not now hinges 5640 // on whether there exists an instantiation of A that causes 5641 // 'foo' to equal C. There are restrictions on class-heads 5642 // (which we declare (by fiat) elaborated friend declarations to 5643 // be) that makes this tractable. 5644 // 5645 // FIXME: handle "template <> friend class A<T>;", which 5646 // is possibly well-formed? Who even knows? 5647 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 5648 Diag(Loc, diag::err_tagless_friend_type_template) 5649 << DS.getSourceRange(); 5650 return DeclPtrTy(); 5651 } 5652 5653 // C++98 [class.friend]p1: A friend of a class is a function 5654 // or class that is not a member of the class . . . 5655 // This is fixed in DR77, which just barely didn't make the C++03 5656 // deadline. It's also a very silly restriction that seriously 5657 // affects inner classes and which nobody else seems to implement; 5658 // thus we never diagnose it, not even in -pedantic. 5659 // 5660 // But note that we could warn about it: it's always useless to 5661 // friend one of your own members (it's not, however, worthless to 5662 // friend a member of an arbitrary specialization of your template). 5663 5664 Decl *D; 5665 if (unsigned NumTempParamLists = TempParams.size()) 5666 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 5667 NumTempParamLists, 5668 (TemplateParameterList**) TempParams.release(), 5669 TSI, 5670 DS.getFriendSpecLoc()); 5671 else 5672 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI); 5673 5674 if (!D) 5675 return DeclPtrTy(); 5676 5677 D->setAccess(AS_public); 5678 CurContext->addDecl(D); 5679 5680 return DeclPtrTy::make(D); 5681} 5682 5683Sema::DeclPtrTy 5684Sema::ActOnFriendFunctionDecl(Scope *S, 5685 Declarator &D, 5686 bool IsDefinition, 5687 MultiTemplateParamsArg TemplateParams) { 5688 const DeclSpec &DS = D.getDeclSpec(); 5689 5690 assert(DS.isFriendSpecified()); 5691 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 5692 5693 SourceLocation Loc = D.getIdentifierLoc(); 5694 TypeSourceInfo *TInfo = 0; 5695 QualType T = GetTypeForDeclarator(D, S, &TInfo); 5696 5697 // C++ [class.friend]p1 5698 // A friend of a class is a function or class.... 5699 // Note that this sees through typedefs, which is intended. 5700 // It *doesn't* see through dependent types, which is correct 5701 // according to [temp.arg.type]p3: 5702 // If a declaration acquires a function type through a 5703 // type dependent on a template-parameter and this causes 5704 // a declaration that does not use the syntactic form of a 5705 // function declarator to have a function type, the program 5706 // is ill-formed. 5707 if (!T->isFunctionType()) { 5708 Diag(Loc, diag::err_unexpected_friend); 5709 5710 // It might be worthwhile to try to recover by creating an 5711 // appropriate declaration. 5712 return DeclPtrTy(); 5713 } 5714 5715 // C++ [namespace.memdef]p3 5716 // - If a friend declaration in a non-local class first declares a 5717 // class or function, the friend class or function is a member 5718 // of the innermost enclosing namespace. 5719 // - The name of the friend is not found by simple name lookup 5720 // until a matching declaration is provided in that namespace 5721 // scope (either before or after the class declaration granting 5722 // friendship). 5723 // - If a friend function is called, its name may be found by the 5724 // name lookup that considers functions from namespaces and 5725 // classes associated with the types of the function arguments. 5726 // - When looking for a prior declaration of a class or a function 5727 // declared as a friend, scopes outside the innermost enclosing 5728 // namespace scope are not considered. 5729 5730 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec(); 5731 DeclarationName Name = GetNameForDeclarator(D); 5732 assert(Name); 5733 5734 // The context we found the declaration in, or in which we should 5735 // create the declaration. 5736 DeclContext *DC; 5737 5738 // FIXME: handle local classes 5739 5740 // Recover from invalid scope qualifiers as if they just weren't there. 5741 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName, 5742 ForRedeclaration); 5743 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) { 5744 DC = computeDeclContext(ScopeQual); 5745 5746 // FIXME: handle dependent contexts 5747 if (!DC) return DeclPtrTy(); 5748 if (RequireCompleteDeclContext(ScopeQual, DC)) return DeclPtrTy(); 5749 5750 LookupQualifiedName(Previous, DC); 5751 5752 // Ignore things found implicitly in the wrong scope. 5753 // TODO: better diagnostics for this case. Suggesting the right 5754 // qualified scope would be nice... 5755 LookupResult::Filter F = Previous.makeFilter(); 5756 while (F.hasNext()) { 5757 NamedDecl *D = F.next(); 5758 if (!D->getDeclContext()->getLookupContext()->Equals(DC)) 5759 F.erase(); 5760 } 5761 F.done(); 5762 5763 if (Previous.empty()) { 5764 D.setInvalidType(); 5765 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 5766 return DeclPtrTy(); 5767 } 5768 5769 // C++ [class.friend]p1: A friend of a class is a function or 5770 // class that is not a member of the class . . . 5771 if (DC->Equals(CurContext)) 5772 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 5773 5774 // Otherwise walk out to the nearest namespace scope looking for matches. 5775 } else { 5776 // TODO: handle local class contexts. 5777 5778 DC = CurContext; 5779 while (true) { 5780 // Skip class contexts. If someone can cite chapter and verse 5781 // for this behavior, that would be nice --- it's what GCC and 5782 // EDG do, and it seems like a reasonable intent, but the spec 5783 // really only says that checks for unqualified existing 5784 // declarations should stop at the nearest enclosing namespace, 5785 // not that they should only consider the nearest enclosing 5786 // namespace. 5787 while (DC->isRecord()) 5788 DC = DC->getParent(); 5789 5790 LookupQualifiedName(Previous, DC); 5791 5792 // TODO: decide what we think about using declarations. 5793 if (!Previous.empty()) 5794 break; 5795 5796 if (DC->isFileContext()) break; 5797 DC = DC->getParent(); 5798 } 5799 5800 // C++ [class.friend]p1: A friend of a class is a function or 5801 // class that is not a member of the class . . . 5802 // C++0x changes this for both friend types and functions. 5803 // Most C++ 98 compilers do seem to give an error here, so 5804 // we do, too. 5805 if (!Previous.empty() && DC->Equals(CurContext) 5806 && !getLangOptions().CPlusPlus0x) 5807 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 5808 } 5809 5810 if (DC->isFileContext()) { 5811 // This implies that it has to be an operator or function. 5812 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName || 5813 D.getName().getKind() == UnqualifiedId::IK_DestructorName || 5814 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) { 5815 Diag(Loc, diag::err_introducing_special_friend) << 5816 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 : 5817 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2); 5818 return DeclPtrTy(); 5819 } 5820 } 5821 5822 bool Redeclaration = false; 5823 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous, 5824 move(TemplateParams), 5825 IsDefinition, 5826 Redeclaration); 5827 if (!ND) return DeclPtrTy(); 5828 5829 assert(ND->getDeclContext() == DC); 5830 assert(ND->getLexicalDeclContext() == CurContext); 5831 5832 // Add the function declaration to the appropriate lookup tables, 5833 // adjusting the redeclarations list as necessary. We don't 5834 // want to do this yet if the friending class is dependent. 5835 // 5836 // Also update the scope-based lookup if the target context's 5837 // lookup context is in lexical scope. 5838 if (!CurContext->isDependentContext()) { 5839 DC = DC->getLookupContext(); 5840 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false); 5841 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 5842 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 5843 } 5844 5845 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 5846 D.getIdentifierLoc(), ND, 5847 DS.getFriendSpecLoc()); 5848 FrD->setAccess(AS_public); 5849 CurContext->addDecl(FrD); 5850 5851 return DeclPtrTy::make(ND); 5852} 5853 5854void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) { 5855 AdjustDeclIfTemplate(dcl); 5856 5857 Decl *Dcl = dcl.getAs<Decl>(); 5858 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 5859 if (!Fn) { 5860 Diag(DelLoc, diag::err_deleted_non_function); 5861 return; 5862 } 5863 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 5864 Diag(DelLoc, diag::err_deleted_decl_not_first); 5865 Diag(Prev->getLocation(), diag::note_previous_declaration); 5866 // If the declaration wasn't the first, we delete the function anyway for 5867 // recovery. 5868 } 5869 Fn->setDeleted(); 5870} 5871 5872static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 5873 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; 5874 ++CI) { 5875 Stmt *SubStmt = *CI; 5876 if (!SubStmt) 5877 continue; 5878 if (isa<ReturnStmt>(SubStmt)) 5879 Self.Diag(SubStmt->getSourceRange().getBegin(), 5880 diag::err_return_in_constructor_handler); 5881 if (!isa<Expr>(SubStmt)) 5882 SearchForReturnInStmt(Self, SubStmt); 5883 } 5884} 5885 5886void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 5887 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 5888 CXXCatchStmt *Handler = TryBlock->getHandler(I); 5889 SearchForReturnInStmt(*this, Handler); 5890 } 5891} 5892 5893bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 5894 const CXXMethodDecl *Old) { 5895 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType(); 5896 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType(); 5897 5898 if (Context.hasSameType(NewTy, OldTy) || 5899 NewTy->isDependentType() || OldTy->isDependentType()) 5900 return false; 5901 5902 // Check if the return types are covariant 5903 QualType NewClassTy, OldClassTy; 5904 5905 /// Both types must be pointers or references to classes. 5906 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 5907 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 5908 NewClassTy = NewPT->getPointeeType(); 5909 OldClassTy = OldPT->getPointeeType(); 5910 } 5911 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 5912 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 5913 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 5914 NewClassTy = NewRT->getPointeeType(); 5915 OldClassTy = OldRT->getPointeeType(); 5916 } 5917 } 5918 } 5919 5920 // The return types aren't either both pointers or references to a class type. 5921 if (NewClassTy.isNull()) { 5922 Diag(New->getLocation(), 5923 diag::err_different_return_type_for_overriding_virtual_function) 5924 << New->getDeclName() << NewTy << OldTy; 5925 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5926 5927 return true; 5928 } 5929 5930 // C++ [class.virtual]p6: 5931 // If the return type of D::f differs from the return type of B::f, the 5932 // class type in the return type of D::f shall be complete at the point of 5933 // declaration of D::f or shall be the class type D. 5934 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 5935 if (!RT->isBeingDefined() && 5936 RequireCompleteType(New->getLocation(), NewClassTy, 5937 PDiag(diag::err_covariant_return_incomplete) 5938 << New->getDeclName())) 5939 return true; 5940 } 5941 5942 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 5943 // Check if the new class derives from the old class. 5944 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 5945 Diag(New->getLocation(), 5946 diag::err_covariant_return_not_derived) 5947 << New->getDeclName() << NewTy << OldTy; 5948 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5949 return true; 5950 } 5951 5952 // Check if we the conversion from derived to base is valid. 5953 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 5954 diag::err_covariant_return_inaccessible_base, 5955 diag::err_covariant_return_ambiguous_derived_to_base_conv, 5956 // FIXME: Should this point to the return type? 5957 New->getLocation(), SourceRange(), New->getDeclName(), 0)) { 5958 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5959 return true; 5960 } 5961 } 5962 5963 // The qualifiers of the return types must be the same. 5964 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 5965 Diag(New->getLocation(), 5966 diag::err_covariant_return_type_different_qualifications) 5967 << New->getDeclName() << NewTy << OldTy; 5968 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5969 return true; 5970 }; 5971 5972 5973 // The new class type must have the same or less qualifiers as the old type. 5974 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 5975 Diag(New->getLocation(), 5976 diag::err_covariant_return_type_class_type_more_qualified) 5977 << New->getDeclName() << NewTy << OldTy; 5978 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5979 return true; 5980 }; 5981 5982 return false; 5983} 5984 5985bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 5986 const CXXMethodDecl *Old) 5987{ 5988 if (Old->hasAttr<FinalAttr>()) { 5989 Diag(New->getLocation(), diag::err_final_function_overridden) 5990 << New->getDeclName(); 5991 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 5992 return true; 5993 } 5994 5995 return false; 5996} 5997 5998/// \brief Mark the given method pure. 5999/// 6000/// \param Method the method to be marked pure. 6001/// 6002/// \param InitRange the source range that covers the "0" initializer. 6003bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 6004 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 6005 Method->setPure(); 6006 6007 // A class is abstract if at least one function is pure virtual. 6008 Method->getParent()->setAbstract(true); 6009 return false; 6010 } 6011 6012 if (!Method->isInvalidDecl()) 6013 Diag(Method->getLocation(), diag::err_non_virtual_pure) 6014 << Method->getDeclName() << InitRange; 6015 return true; 6016} 6017 6018/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse 6019/// an initializer for the out-of-line declaration 'Dcl'. The scope 6020/// is a fresh scope pushed for just this purpose. 6021/// 6022/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 6023/// static data member of class X, names should be looked up in the scope of 6024/// class X. 6025void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) { 6026 // If there is no declaration, there was an error parsing it. 6027 Decl *D = Dcl.getAs<Decl>(); 6028 if (D == 0) return; 6029 6030 // We should only get called for declarations with scope specifiers, like: 6031 // int foo::bar; 6032 assert(D->isOutOfLine()); 6033 EnterDeclaratorContext(S, D->getDeclContext()); 6034} 6035 6036/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 6037/// initializer for the out-of-line declaration 'Dcl'. 6038void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) { 6039 // If there is no declaration, there was an error parsing it. 6040 Decl *D = Dcl.getAs<Decl>(); 6041 if (D == 0) return; 6042 6043 assert(D->isOutOfLine()); 6044 ExitDeclaratorContext(S); 6045} 6046 6047/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 6048/// C++ if/switch/while/for statement. 6049/// e.g: "if (int x = f()) {...}" 6050Action::DeclResult 6051Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 6052 // C++ 6.4p2: 6053 // The declarator shall not specify a function or an array. 6054 // The type-specifier-seq shall not contain typedef and shall not declare a 6055 // new class or enumeration. 6056 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6057 "Parser allowed 'typedef' as storage class of condition decl."); 6058 6059 TypeSourceInfo *TInfo = 0; 6060 TagDecl *OwnedTag = 0; 6061 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag); 6062 6063 if (Ty->isFunctionType()) { // The declarator shall not specify a function... 6064 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl 6065 // would be created and CXXConditionDeclExpr wants a VarDecl. 6066 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type) 6067 << D.getSourceRange(); 6068 return DeclResult(); 6069 } else if (OwnedTag && OwnedTag->isDefinition()) { 6070 // The type-specifier-seq shall not declare a new class or enumeration. 6071 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition); 6072 } 6073 6074 DeclPtrTy Dcl = ActOnDeclarator(S, D); 6075 if (!Dcl) 6076 return DeclResult(); 6077 6078 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>()); 6079 VD->setDeclaredInCondition(true); 6080 return Dcl; 6081} 6082 6083void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 6084 bool DefinitionRequired) { 6085 // Ignore any vtable uses in unevaluated operands or for classes that do 6086 // not have a vtable. 6087 if (!Class->isDynamicClass() || Class->isDependentContext() || 6088 CurContext->isDependentContext() || 6089 ExprEvalContexts.back().Context == Unevaluated) 6090 return; 6091 6092 // Try to insert this class into the map. 6093 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 6094 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 6095 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 6096 if (!Pos.second) { 6097 // If we already had an entry, check to see if we are promoting this vtable 6098 // to required a definition. If so, we need to reappend to the VTableUses 6099 // list, since we may have already processed the first entry. 6100 if (DefinitionRequired && !Pos.first->second) { 6101 Pos.first->second = true; 6102 } else { 6103 // Otherwise, we can early exit. 6104 return; 6105 } 6106 } 6107 6108 // Local classes need to have their virtual members marked 6109 // immediately. For all other classes, we mark their virtual members 6110 // at the end of the translation unit. 6111 if (Class->isLocalClass()) 6112 MarkVirtualMembersReferenced(Loc, Class); 6113 else 6114 VTableUses.push_back(std::make_pair(Class, Loc)); 6115} 6116 6117bool Sema::DefineUsedVTables() { 6118 // If any dynamic classes have their key function defined within 6119 // this translation unit, then those vtables are considered "used" and must 6120 // be emitted. 6121 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) { 6122 if (const CXXMethodDecl *KeyFunction 6123 = Context.getKeyFunction(DynamicClasses[I])) { 6124 const FunctionDecl *Definition = 0; 6125 if (KeyFunction->getBody(Definition)) 6126 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true); 6127 } 6128 } 6129 6130 if (VTableUses.empty()) 6131 return false; 6132 6133 // Note: The VTableUses vector could grow as a result of marking 6134 // the members of a class as "used", so we check the size each 6135 // time through the loop and prefer indices (with are stable) to 6136 // iterators (which are not). 6137 for (unsigned I = 0; I != VTableUses.size(); ++I) { 6138 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 6139 if (!Class) 6140 continue; 6141 6142 SourceLocation Loc = VTableUses[I].second; 6143 6144 // If this class has a key function, but that key function is 6145 // defined in another translation unit, we don't need to emit the 6146 // vtable even though we're using it. 6147 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class); 6148 if (KeyFunction && !KeyFunction->getBody()) { 6149 switch (KeyFunction->getTemplateSpecializationKind()) { 6150 case TSK_Undeclared: 6151 case TSK_ExplicitSpecialization: 6152 case TSK_ExplicitInstantiationDeclaration: 6153 // The key function is in another translation unit. 6154 continue; 6155 6156 case TSK_ExplicitInstantiationDefinition: 6157 case TSK_ImplicitInstantiation: 6158 // We will be instantiating the key function. 6159 break; 6160 } 6161 } else if (!KeyFunction) { 6162 // If we have a class with no key function that is the subject 6163 // of an explicit instantiation declaration, suppress the 6164 // vtable; it will live with the explicit instantiation 6165 // definition. 6166 bool IsExplicitInstantiationDeclaration 6167 = Class->getTemplateSpecializationKind() 6168 == TSK_ExplicitInstantiationDeclaration; 6169 for (TagDecl::redecl_iterator R = Class->redecls_begin(), 6170 REnd = Class->redecls_end(); 6171 R != REnd; ++R) { 6172 TemplateSpecializationKind TSK 6173 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind(); 6174 if (TSK == TSK_ExplicitInstantiationDeclaration) 6175 IsExplicitInstantiationDeclaration = true; 6176 else if (TSK == TSK_ExplicitInstantiationDefinition) { 6177 IsExplicitInstantiationDeclaration = false; 6178 break; 6179 } 6180 } 6181 6182 if (IsExplicitInstantiationDeclaration) 6183 continue; 6184 } 6185 6186 // Mark all of the virtual members of this class as referenced, so 6187 // that we can build a vtable. Then, tell the AST consumer that a 6188 // vtable for this class is required. 6189 MarkVirtualMembersReferenced(Loc, Class); 6190 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl()); 6191 Consumer.HandleVTable(Class, VTablesUsed[Canonical]); 6192 6193 // Optionally warn if we're emitting a weak vtable. 6194 if (Class->getLinkage() == ExternalLinkage && 6195 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) { 6196 if (!KeyFunction || (KeyFunction->getBody() && KeyFunction->isInlined())) 6197 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; 6198 } 6199 } 6200 VTableUses.clear(); 6201 6202 return true; 6203} 6204 6205void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 6206 const CXXRecordDecl *RD) { 6207 for (CXXRecordDecl::method_iterator i = RD->method_begin(), 6208 e = RD->method_end(); i != e; ++i) { 6209 CXXMethodDecl *MD = *i; 6210 6211 // C++ [basic.def.odr]p2: 6212 // [...] A virtual member function is used if it is not pure. [...] 6213 if (MD->isVirtual() && !MD->isPure()) 6214 MarkDeclarationReferenced(Loc, MD); 6215 } 6216 6217 // Only classes that have virtual bases need a VTT. 6218 if (RD->getNumVBases() == 0) 6219 return; 6220 6221 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(), 6222 e = RD->bases_end(); i != e; ++i) { 6223 const CXXRecordDecl *Base = 6224 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl()); 6225 if (i->isVirtual()) 6226 continue; 6227 if (Base->getNumVBases() == 0) 6228 continue; 6229 MarkVirtualMembersReferenced(Loc, Base); 6230 } 6231} 6232 6233/// SetIvarInitializers - This routine builds initialization ASTs for the 6234/// Objective-C implementation whose ivars need be initialized. 6235void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 6236 if (!getLangOptions().CPlusPlus) 6237 return; 6238 if (const ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 6239 llvm::SmallVector<ObjCIvarDecl*, 8> ivars; 6240 CollectIvarsToConstructOrDestruct(OID, ivars); 6241 if (ivars.empty()) 6242 return; 6243 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit; 6244 for (unsigned i = 0; i < ivars.size(); i++) { 6245 FieldDecl *Field = ivars[i]; 6246 if (Field->isInvalidDecl()) 6247 continue; 6248 6249 CXXBaseOrMemberInitializer *Member; 6250 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 6251 InitializationKind InitKind = 6252 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 6253 6254 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0); 6255 Sema::OwningExprResult MemberInit = 6256 InitSeq.Perform(*this, InitEntity, InitKind, 6257 Sema::MultiExprArg(*this, 0, 0)); 6258 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit)); 6259 // Note, MemberInit could actually come back empty if no initialization 6260 // is required (e.g., because it would call a trivial default constructor) 6261 if (!MemberInit.get() || MemberInit.isInvalid()) 6262 continue; 6263 6264 Member = 6265 new (Context) CXXBaseOrMemberInitializer(Context, 6266 Field, SourceLocation(), 6267 SourceLocation(), 6268 MemberInit.takeAs<Expr>(), 6269 SourceLocation()); 6270 AllToInit.push_back(Member); 6271 6272 // Be sure that the destructor is accessible and is marked as referenced. 6273 if (const RecordType *RecordTy 6274 = Context.getBaseElementType(Field->getType()) 6275 ->getAs<RecordType>()) { 6276 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 6277 if (CXXDestructorDecl *Destructor 6278 = const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) { 6279 MarkDeclarationReferenced(Field->getLocation(), Destructor); 6280 CheckDestructorAccess(Field->getLocation(), Destructor, 6281 PDiag(diag::err_access_dtor_ivar) 6282 << Context.getBaseElementType(Field->getType())); 6283 } 6284 } 6285 } 6286 ObjCImplementation->setIvarInitializers(Context, 6287 AllToInit.data(), AllToInit.size()); 6288 } 6289} 6290