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