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