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