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