SemaDeclCXX.cpp revision 1eb4433ac451dc16f4133a88af2d002ac26c58ef
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 "SemaInherit.h" 16#include "clang/AST/ASTConsumer.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/DeclVisitor.h" 19#include "clang/AST/TypeOrdering.h" 20#include "clang/AST/StmtVisitor.h" 21#include "clang/Basic/PartialDiagnostic.h" 22#include "clang/Lex/Preprocessor.h" 23#include "clang/Parse/DeclSpec.h" 24#include "llvm/ADT/STLExtras.h" 25#include "llvm/Support/Compiler.h" 26#include <algorithm> // for std::equal 27#include <map> 28 29using namespace clang; 30 31//===----------------------------------------------------------------------===// 32// CheckDefaultArgumentVisitor 33//===----------------------------------------------------------------------===// 34 35namespace { 36 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 37 /// the default argument of a parameter to determine whether it 38 /// contains any ill-formed subexpressions. For example, this will 39 /// diagnose the use of local variables or parameters within the 40 /// default argument expression. 41 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor 42 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 43 Expr *DefaultArg; 44 Sema *S; 45 46 public: 47 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 48 : DefaultArg(defarg), S(s) {} 49 50 bool VisitExpr(Expr *Node); 51 bool VisitDeclRefExpr(DeclRefExpr *DRE); 52 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 53 }; 54 55 /// VisitExpr - Visit all of the children of this expression. 56 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 57 bool IsInvalid = false; 58 for (Stmt::child_iterator I = Node->child_begin(), 59 E = Node->child_end(); I != E; ++I) 60 IsInvalid |= Visit(*I); 61 return IsInvalid; 62 } 63 64 /// VisitDeclRefExpr - Visit a reference to a declaration, to 65 /// determine whether this declaration can be used in the default 66 /// argument expression. 67 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 68 NamedDecl *Decl = DRE->getDecl(); 69 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 70 // C++ [dcl.fct.default]p9 71 // Default arguments are evaluated each time the function is 72 // called. The order of evaluation of function arguments is 73 // unspecified. Consequently, parameters of a function shall not 74 // be used in default argument expressions, even if they are not 75 // evaluated. Parameters of a function declared before a default 76 // argument expression are in scope and can hide namespace and 77 // class member names. 78 return S->Diag(DRE->getSourceRange().getBegin(), 79 diag::err_param_default_argument_references_param) 80 << Param->getDeclName() << DefaultArg->getSourceRange(); 81 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 82 // C++ [dcl.fct.default]p7 83 // Local variables shall not be used in default argument 84 // expressions. 85 if (VDecl->isBlockVarDecl()) 86 return S->Diag(DRE->getSourceRange().getBegin(), 87 diag::err_param_default_argument_references_local) 88 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 89 } 90 91 return false; 92 } 93 94 /// VisitCXXThisExpr - Visit a C++ "this" expression. 95 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 96 // C++ [dcl.fct.default]p8: 97 // The keyword this shall not be used in a default argument of a 98 // member function. 99 return S->Diag(ThisE->getSourceRange().getBegin(), 100 diag::err_param_default_argument_references_this) 101 << ThisE->getSourceRange(); 102 } 103} 104 105bool 106Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg, 107 SourceLocation EqualLoc) { 108 QualType ParamType = Param->getType(); 109 110 if (RequireCompleteType(Param->getLocation(), Param->getType(), 111 diag::err_typecheck_decl_incomplete_type)) { 112 Param->setInvalidDecl(); 113 return true; 114 } 115 116 Expr *Arg = (Expr *)DefaultArg.get(); 117 118 // C++ [dcl.fct.default]p5 119 // A default argument expression is implicitly converted (clause 120 // 4) to the parameter type. The default argument expression has 121 // the same semantic constraints as the initializer expression in 122 // a declaration of a variable of the parameter type, using the 123 // copy-initialization semantics (8.5). 124 if (CheckInitializerTypes(Arg, ParamType, EqualLoc, 125 Param->getDeclName(), /*DirectInit=*/false)) 126 return true; 127 128 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false); 129 130 // Okay: add the default argument to the parameter 131 Param->setDefaultArg(Arg); 132 133 DefaultArg.release(); 134 135 return false; 136} 137 138/// ActOnParamDefaultArgument - Check whether the default argument 139/// provided for a function parameter is well-formed. If so, attach it 140/// to the parameter declaration. 141void 142Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc, 143 ExprArg defarg) { 144 if (!param || !defarg.get()) 145 return; 146 147 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 148 UnparsedDefaultArgLocs.erase(Param); 149 150 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>()); 151 QualType ParamType = Param->getType(); 152 153 // Default arguments are only permitted in C++ 154 if (!getLangOptions().CPlusPlus) { 155 Diag(EqualLoc, diag::err_param_default_argument) 156 << DefaultArg->getSourceRange(); 157 Param->setInvalidDecl(); 158 return; 159 } 160 161 // Check that the default argument is well-formed 162 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 163 if (DefaultArgChecker.Visit(DefaultArg.get())) { 164 Param->setInvalidDecl(); 165 return; 166 } 167 168 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc); 169} 170 171/// ActOnParamUnparsedDefaultArgument - We've seen a default 172/// argument for a function parameter, but we can't parse it yet 173/// because we're inside a class definition. Note that this default 174/// argument will be parsed later. 175void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param, 176 SourceLocation EqualLoc, 177 SourceLocation ArgLoc) { 178 if (!param) 179 return; 180 181 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 182 if (Param) 183 Param->setUnparsedDefaultArg(); 184 185 UnparsedDefaultArgLocs[Param] = ArgLoc; 186} 187 188/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 189/// the default argument for the parameter param failed. 190void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) { 191 if (!param) 192 return; 193 194 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>()); 195 196 Param->setInvalidDecl(); 197 198 UnparsedDefaultArgLocs.erase(Param); 199} 200 201/// CheckExtraCXXDefaultArguments - Check for any extra default 202/// arguments in the declarator, which is not a function declaration 203/// or definition and therefore is not permitted to have default 204/// arguments. This routine should be invoked for every declarator 205/// that is not a function declaration or definition. 206void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 207 // C++ [dcl.fct.default]p3 208 // A default argument expression shall be specified only in the 209 // parameter-declaration-clause of a function declaration or in a 210 // template-parameter (14.1). It shall not be specified for a 211 // parameter pack. If it is specified in a 212 // parameter-declaration-clause, it shall not occur within a 213 // declarator or abstract-declarator of a parameter-declaration. 214 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 215 DeclaratorChunk &chunk = D.getTypeObject(i); 216 if (chunk.Kind == DeclaratorChunk::Function) { 217 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) { 218 ParmVarDecl *Param = 219 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>()); 220 if (Param->hasUnparsedDefaultArg()) { 221 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens; 222 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 223 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation()); 224 delete Toks; 225 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0; 226 } else if (Param->getDefaultArg()) { 227 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 228 << Param->getDefaultArg()->getSourceRange(); 229 Param->setDefaultArg(0); 230 } 231 } 232 } 233 } 234} 235 236// MergeCXXFunctionDecl - Merge two declarations of the same C++ 237// function, once we already know that they have the same 238// type. Subroutine of MergeFunctionDecl. Returns true if there was an 239// error, false otherwise. 240bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 241 bool Invalid = false; 242 243 // C++ [dcl.fct.default]p4: 244 // 245 // For non-template functions, default arguments can be added in 246 // later declarations of a function in the same 247 // scope. Declarations in different scopes have completely 248 // distinct sets of default arguments. That is, declarations in 249 // inner scopes do not acquire default arguments from 250 // declarations in outer scopes, and vice versa. In a given 251 // function declaration, all parameters subsequent to a 252 // parameter with a default argument shall have default 253 // arguments supplied in this or previous declarations. A 254 // default argument shall not be redefined by a later 255 // declaration (not even to the same value). 256 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 257 ParmVarDecl *OldParam = Old->getParamDecl(p); 258 ParmVarDecl *NewParam = New->getParamDecl(p); 259 260 if (OldParam->getDefaultArg() && NewParam->getDefaultArg()) { 261 Diag(NewParam->getLocation(), 262 diag::err_param_default_argument_redefinition) 263 << NewParam->getDefaultArg()->getSourceRange(); 264 Diag(OldParam->getLocation(), diag::note_previous_definition); 265 Invalid = true; 266 } else if (OldParam->getDefaultArg()) { 267 // Merge the old default argument into the new parameter 268 NewParam->setDefaultArg(OldParam->getDefaultArg()); 269 } 270 } 271 272 if (CheckEquivalentExceptionSpec( 273 Old->getType()->getAsFunctionProtoType(), Old->getLocation(), 274 New->getType()->getAsFunctionProtoType(), New->getLocation())) { 275 Invalid = true; 276 } 277 278 return Invalid; 279} 280 281/// CheckCXXDefaultArguments - Verify that the default arguments for a 282/// function declaration are well-formed according to C++ 283/// [dcl.fct.default]. 284void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 285 unsigned NumParams = FD->getNumParams(); 286 unsigned p; 287 288 // Find first parameter with a default argument 289 for (p = 0; p < NumParams; ++p) { 290 ParmVarDecl *Param = FD->getParamDecl(p); 291 if (Param->hasDefaultArg()) 292 break; 293 } 294 295 // C++ [dcl.fct.default]p4: 296 // In a given function declaration, all parameters 297 // subsequent to a parameter with a default argument shall 298 // have default arguments supplied in this or previous 299 // declarations. A default argument shall not be redefined 300 // by a later declaration (not even to the same value). 301 unsigned LastMissingDefaultArg = 0; 302 for (; p < NumParams; ++p) { 303 ParmVarDecl *Param = FD->getParamDecl(p); 304 if (!Param->hasDefaultArg()) { 305 if (Param->isInvalidDecl()) 306 /* We already complained about this parameter. */; 307 else if (Param->getIdentifier()) 308 Diag(Param->getLocation(), 309 diag::err_param_default_argument_missing_name) 310 << Param->getIdentifier(); 311 else 312 Diag(Param->getLocation(), 313 diag::err_param_default_argument_missing); 314 315 LastMissingDefaultArg = p; 316 } 317 } 318 319 if (LastMissingDefaultArg > 0) { 320 // Some default arguments were missing. Clear out all of the 321 // default arguments up to (and including) the last missing 322 // default argument, so that we leave the function parameters 323 // in a semantically valid state. 324 for (p = 0; p <= LastMissingDefaultArg; ++p) { 325 ParmVarDecl *Param = FD->getParamDecl(p); 326 if (Param->hasDefaultArg()) { 327 if (!Param->hasUnparsedDefaultArg()) 328 Param->getDefaultArg()->Destroy(Context); 329 Param->setDefaultArg(0); 330 } 331 } 332 } 333} 334 335/// isCurrentClassName - Determine whether the identifier II is the 336/// name of the class type currently being defined. In the case of 337/// nested classes, this will only return true if II is the name of 338/// the innermost class. 339bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 340 const CXXScopeSpec *SS) { 341 CXXRecordDecl *CurDecl; 342 if (SS && SS->isSet() && !SS->isInvalid()) { 343 DeclContext *DC = computeDeclContext(*SS, true); 344 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 345 } else 346 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 347 348 if (CurDecl) 349 return &II == CurDecl->getIdentifier(); 350 else 351 return false; 352} 353 354/// \brief Check the validity of a C++ base class specifier. 355/// 356/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 357/// and returns NULL otherwise. 358CXXBaseSpecifier * 359Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 360 SourceRange SpecifierRange, 361 bool Virtual, AccessSpecifier Access, 362 QualType BaseType, 363 SourceLocation BaseLoc) { 364 // C++ [class.union]p1: 365 // A union shall not have base classes. 366 if (Class->isUnion()) { 367 Diag(Class->getLocation(), diag::err_base_clause_on_union) 368 << SpecifierRange; 369 return 0; 370 } 371 372 if (BaseType->isDependentType()) 373 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 374 Class->getTagKind() == RecordDecl::TK_class, 375 Access, BaseType); 376 377 // Base specifiers must be record types. 378 if (!BaseType->isRecordType()) { 379 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 380 return 0; 381 } 382 383 // C++ [class.union]p1: 384 // A union shall not be used as a base class. 385 if (BaseType->isUnionType()) { 386 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 387 return 0; 388 } 389 390 // C++ [class.derived]p2: 391 // The class-name in a base-specifier shall not be an incompletely 392 // defined class. 393 if (RequireCompleteType(BaseLoc, BaseType, 394 PDiag(diag::err_incomplete_base_class) 395 << SpecifierRange)) 396 return 0; 397 398 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 399 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 400 assert(BaseDecl && "Record type has no declaration"); 401 BaseDecl = BaseDecl->getDefinition(Context); 402 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 403 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 404 assert(CXXBaseDecl && "Base type is not a C++ type"); 405 if (!CXXBaseDecl->isEmpty()) 406 Class->setEmpty(false); 407 if (CXXBaseDecl->isPolymorphic()) 408 Class->setPolymorphic(true); 409 410 // C++ [dcl.init.aggr]p1: 411 // An aggregate is [...] a class with [...] no base classes [...]. 412 Class->setAggregate(false); 413 Class->setPOD(false); 414 415 if (Virtual) { 416 // C++ [class.ctor]p5: 417 // A constructor is trivial if its class has no virtual base classes. 418 Class->setHasTrivialConstructor(false); 419 420 // C++ [class.copy]p6: 421 // A copy constructor is trivial if its class has no virtual base classes. 422 Class->setHasTrivialCopyConstructor(false); 423 424 // C++ [class.copy]p11: 425 // A copy assignment operator is trivial if its class has no virtual 426 // base classes. 427 Class->setHasTrivialCopyAssignment(false); 428 429 // C++0x [meta.unary.prop] is_empty: 430 // T is a class type, but not a union type, with ... no virtual base 431 // classes 432 Class->setEmpty(false); 433 } else { 434 // C++ [class.ctor]p5: 435 // A constructor is trivial if all the direct base classes of its 436 // class have trivial constructors. 437 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor()) 438 Class->setHasTrivialConstructor(false); 439 440 // C++ [class.copy]p6: 441 // A copy constructor is trivial if all the direct base classes of its 442 // class have trivial copy constructors. 443 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor()) 444 Class->setHasTrivialCopyConstructor(false); 445 446 // C++ [class.copy]p11: 447 // A copy assignment operator is trivial if all the direct base classes 448 // of its class have trivial copy assignment operators. 449 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment()) 450 Class->setHasTrivialCopyAssignment(false); 451 } 452 453 // C++ [class.ctor]p3: 454 // A destructor is trivial if all the direct base classes of its class 455 // have trivial destructors. 456 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor()) 457 Class->setHasTrivialDestructor(false); 458 459 // Create the base specifier. 460 // FIXME: Allocate via ASTContext? 461 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 462 Class->getTagKind() == RecordDecl::TK_class, 463 Access, BaseType); 464} 465 466/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 467/// one entry in the base class list of a class specifier, for 468/// example: 469/// class foo : public bar, virtual private baz { 470/// 'public bar' and 'virtual private baz' are each base-specifiers. 471Sema::BaseResult 472Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange, 473 bool Virtual, AccessSpecifier Access, 474 TypeTy *basetype, SourceLocation BaseLoc) { 475 if (!classdecl) 476 return true; 477 478 AdjustDeclIfTemplate(classdecl); 479 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>()); 480 QualType BaseType = GetTypeFromParser(basetype); 481 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 482 Virtual, Access, 483 BaseType, BaseLoc)) 484 return BaseSpec; 485 486 return true; 487} 488 489/// \brief Performs the actual work of attaching the given base class 490/// specifiers to a C++ class. 491bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 492 unsigned NumBases) { 493 if (NumBases == 0) 494 return false; 495 496 // Used to keep track of which base types we have already seen, so 497 // that we can properly diagnose redundant direct base types. Note 498 // that the key is always the unqualified canonical type of the base 499 // class. 500 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 501 502 // Copy non-redundant base specifiers into permanent storage. 503 unsigned NumGoodBases = 0; 504 bool Invalid = false; 505 for (unsigned idx = 0; idx < NumBases; ++idx) { 506 QualType NewBaseType 507 = Context.getCanonicalType(Bases[idx]->getType()); 508 NewBaseType = NewBaseType.getUnqualifiedType(); 509 510 if (KnownBaseTypes[NewBaseType]) { 511 // C++ [class.mi]p3: 512 // A class shall not be specified as a direct base class of a 513 // derived class more than once. 514 Diag(Bases[idx]->getSourceRange().getBegin(), 515 diag::err_duplicate_base_class) 516 << KnownBaseTypes[NewBaseType]->getType() 517 << Bases[idx]->getSourceRange(); 518 519 // Delete the duplicate base class specifier; we're going to 520 // overwrite its pointer later. 521 Context.Deallocate(Bases[idx]); 522 523 Invalid = true; 524 } else { 525 // Okay, add this new base class. 526 KnownBaseTypes[NewBaseType] = Bases[idx]; 527 Bases[NumGoodBases++] = Bases[idx]; 528 } 529 } 530 531 // Attach the remaining base class specifiers to the derived class. 532 Class->setBases(Context, Bases, NumGoodBases); 533 534 // Delete the remaining (good) base class specifiers, since their 535 // data has been copied into the CXXRecordDecl. 536 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 537 Context.Deallocate(Bases[idx]); 538 539 return Invalid; 540} 541 542/// ActOnBaseSpecifiers - Attach the given base specifiers to the 543/// class, after checking whether there are any duplicate base 544/// classes. 545void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases, 546 unsigned NumBases) { 547 if (!ClassDecl || !Bases || !NumBases) 548 return; 549 550 AdjustDeclIfTemplate(ClassDecl); 551 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()), 552 (CXXBaseSpecifier**)(Bases), NumBases); 553} 554 555//===----------------------------------------------------------------------===// 556// C++ class member Handling 557//===----------------------------------------------------------------------===// 558 559/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 560/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 561/// bitfield width if there is one and 'InitExpr' specifies the initializer if 562/// any. 563Sema::DeclPtrTy 564Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 565 MultiTemplateParamsArg TemplateParameterLists, 566 ExprTy *BW, ExprTy *InitExpr, bool Deleted) { 567 const DeclSpec &DS = D.getDeclSpec(); 568 DeclarationName Name = GetNameForDeclarator(D); 569 Expr *BitWidth = static_cast<Expr*>(BW); 570 Expr *Init = static_cast<Expr*>(InitExpr); 571 SourceLocation Loc = D.getIdentifierLoc(); 572 573 bool isFunc = D.isFunctionDeclarator(); 574 575 assert(!DS.isFriendSpecified()); 576 577 // C++ 9.2p6: A member shall not be declared to have automatic storage 578 // duration (auto, register) or with the extern storage-class-specifier. 579 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 580 // data members and cannot be applied to names declared const or static, 581 // and cannot be applied to reference members. 582 switch (DS.getStorageClassSpec()) { 583 case DeclSpec::SCS_unspecified: 584 case DeclSpec::SCS_typedef: 585 case DeclSpec::SCS_static: 586 // FALL THROUGH. 587 break; 588 case DeclSpec::SCS_mutable: 589 if (isFunc) { 590 if (DS.getStorageClassSpecLoc().isValid()) 591 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 592 else 593 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 594 595 // FIXME: It would be nicer if the keyword was ignored only for this 596 // declarator. Otherwise we could get follow-up errors. 597 D.getMutableDeclSpec().ClearStorageClassSpecs(); 598 } else { 599 QualType T = GetTypeForDeclarator(D, S); 600 diag::kind err = static_cast<diag::kind>(0); 601 if (T->isReferenceType()) 602 err = diag::err_mutable_reference; 603 else if (T.isConstQualified()) 604 err = diag::err_mutable_const; 605 if (err != 0) { 606 if (DS.getStorageClassSpecLoc().isValid()) 607 Diag(DS.getStorageClassSpecLoc(), err); 608 else 609 Diag(DS.getThreadSpecLoc(), err); 610 // FIXME: It would be nicer if the keyword was ignored only for this 611 // declarator. Otherwise we could get follow-up errors. 612 D.getMutableDeclSpec().ClearStorageClassSpecs(); 613 } 614 } 615 break; 616 default: 617 if (DS.getStorageClassSpecLoc().isValid()) 618 Diag(DS.getStorageClassSpecLoc(), 619 diag::err_storageclass_invalid_for_member); 620 else 621 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 622 D.getMutableDeclSpec().ClearStorageClassSpecs(); 623 } 624 625 if (!isFunc && 626 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename && 627 D.getNumTypeObjects() == 0) { 628 // Check also for this case: 629 // 630 // typedef int f(); 631 // f a; 632 // 633 QualType TDType = GetTypeFromParser(DS.getTypeRep()); 634 isFunc = TDType->isFunctionType(); 635 } 636 637 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 638 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 639 !isFunc); 640 641 Decl *Member; 642 if (isInstField) { 643 // FIXME: Check for template parameters! 644 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth, 645 AS); 646 assert(Member && "HandleField never returns null"); 647 } else { 648 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false) 649 .getAs<Decl>(); 650 if (!Member) { 651 if (BitWidth) DeleteExpr(BitWidth); 652 return DeclPtrTy(); 653 } 654 655 // Non-instance-fields can't have a bitfield. 656 if (BitWidth) { 657 if (Member->isInvalidDecl()) { 658 // don't emit another diagnostic. 659 } else if (isa<VarDecl>(Member)) { 660 // C++ 9.6p3: A bit-field shall not be a static member. 661 // "static member 'A' cannot be a bit-field" 662 Diag(Loc, diag::err_static_not_bitfield) 663 << Name << BitWidth->getSourceRange(); 664 } else if (isa<TypedefDecl>(Member)) { 665 // "typedef member 'x' cannot be a bit-field" 666 Diag(Loc, diag::err_typedef_not_bitfield) 667 << Name << BitWidth->getSourceRange(); 668 } else { 669 // A function typedef ("typedef int f(); f a;"). 670 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 671 Diag(Loc, diag::err_not_integral_type_bitfield) 672 << Name << cast<ValueDecl>(Member)->getType() 673 << BitWidth->getSourceRange(); 674 } 675 676 DeleteExpr(BitWidth); 677 BitWidth = 0; 678 Member->setInvalidDecl(); 679 } 680 681 Member->setAccess(AS); 682 683 // If we have declared a member function template, set the access of the 684 // templated declaration as well. 685 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 686 FunTmpl->getTemplatedDecl()->setAccess(AS); 687 } 688 689 assert((Name || isInstField) && "No identifier for non-field ?"); 690 691 if (Init) 692 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false); 693 if (Deleted) // FIXME: Source location is not very good. 694 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin()); 695 696 if (isInstField) { 697 FieldCollector->Add(cast<FieldDecl>(Member)); 698 return DeclPtrTy(); 699 } 700 return DeclPtrTy::make(Member); 701} 702 703/// ActOnMemInitializer - Handle a C++ member initializer. 704Sema::MemInitResult 705Sema::ActOnMemInitializer(DeclPtrTy ConstructorD, 706 Scope *S, 707 const CXXScopeSpec &SS, 708 IdentifierInfo *MemberOrBase, 709 TypeTy *TemplateTypeTy, 710 SourceLocation IdLoc, 711 SourceLocation LParenLoc, 712 ExprTy **Args, unsigned NumArgs, 713 SourceLocation *CommaLocs, 714 SourceLocation RParenLoc) { 715 if (!ConstructorD) 716 return true; 717 718 AdjustDeclIfTemplate(ConstructorD); 719 720 CXXConstructorDecl *Constructor 721 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>()); 722 if (!Constructor) { 723 // The user wrote a constructor initializer on a function that is 724 // not a C++ constructor. Ignore the error for now, because we may 725 // have more member initializers coming; we'll diagnose it just 726 // once in ActOnMemInitializers. 727 return true; 728 } 729 730 CXXRecordDecl *ClassDecl = Constructor->getParent(); 731 732 // C++ [class.base.init]p2: 733 // Names in a mem-initializer-id are looked up in the scope of the 734 // constructor’s class and, if not found in that scope, are looked 735 // up in the scope containing the constructor’s 736 // definition. [Note: if the constructor’s class contains a member 737 // with the same name as a direct or virtual base class of the 738 // class, a mem-initializer-id naming the member or base class and 739 // composed of a single identifier refers to the class member. A 740 // mem-initializer-id for the hidden base class may be specified 741 // using a qualified name. ] 742 if (!SS.getScopeRep() && !TemplateTypeTy) { 743 // Look for a member, first. 744 FieldDecl *Member = 0; 745 DeclContext::lookup_result Result 746 = ClassDecl->lookup(MemberOrBase); 747 if (Result.first != Result.second) 748 Member = dyn_cast<FieldDecl>(*Result.first); 749 750 // FIXME: Handle members of an anonymous union. 751 752 if (Member) 753 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc, 754 RParenLoc); 755 } 756 // It didn't name a member, so see if it names a class. 757 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy 758 : getTypeName(*MemberOrBase, IdLoc, S, &SS); 759 if (!BaseTy) 760 return Diag(IdLoc, diag::err_mem_init_not_member_or_class) 761 << MemberOrBase << SourceRange(IdLoc, RParenLoc); 762 763 QualType BaseType = GetTypeFromParser(BaseTy); 764 765 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc, 766 RParenLoc, ClassDecl); 767} 768 769Sema::MemInitResult 770Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args, 771 unsigned NumArgs, SourceLocation IdLoc, 772 SourceLocation RParenLoc) { 773 bool HasDependentArg = false; 774 for (unsigned i = 0; i < NumArgs; i++) 775 HasDependentArg |= Args[i]->isTypeDependent(); 776 777 CXXConstructorDecl *C = 0; 778 QualType FieldType = Member->getType(); 779 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 780 FieldType = Array->getElementType(); 781 if (FieldType->isDependentType()) { 782 // Can't check init for dependent type. 783 } else if (FieldType->getAs<RecordType>()) { 784 if (!HasDependentArg) 785 C = PerformInitializationByConstructor( 786 FieldType, (Expr **)Args, NumArgs, IdLoc, 787 SourceRange(IdLoc, RParenLoc), Member->getDeclName(), IK_Direct); 788 } else if (NumArgs != 1 && NumArgs != 0) { 789 return Diag(IdLoc, diag::err_mem_initializer_mismatch) 790 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc); 791 } else if (!HasDependentArg) { 792 Expr *NewExp; 793 if (NumArgs == 0) { 794 if (FieldType->isReferenceType()) { 795 Diag(IdLoc, diag::err_null_intialized_reference_member) 796 << Member->getDeclName(); 797 return Diag(Member->getLocation(), diag::note_declared_at); 798 } 799 NewExp = new (Context) CXXZeroInitValueExpr(FieldType, IdLoc, RParenLoc); 800 NumArgs = 1; 801 } 802 else 803 NewExp = (Expr*)Args[0]; 804 if (PerformCopyInitialization(NewExp, FieldType, "passing")) 805 return true; 806 Args[0] = NewExp; 807 } 808 // FIXME: Perform direct initialization of the member. 809 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args, 810 NumArgs, C, IdLoc, RParenLoc); 811} 812 813Sema::MemInitResult 814Sema::BuildBaseInitializer(QualType BaseType, Expr **Args, 815 unsigned NumArgs, SourceLocation IdLoc, 816 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) { 817 bool HasDependentArg = false; 818 for (unsigned i = 0; i < NumArgs; i++) 819 HasDependentArg |= Args[i]->isTypeDependent(); 820 821 if (!BaseType->isDependentType()) { 822 if (!BaseType->isRecordType()) 823 return Diag(IdLoc, diag::err_base_init_does_not_name_class) 824 << BaseType << SourceRange(IdLoc, RParenLoc); 825 826 // C++ [class.base.init]p2: 827 // [...] Unless the mem-initializer-id names a nonstatic data 828 // member of the constructor’s class or a direct or virtual base 829 // of that class, the mem-initializer is ill-formed. A 830 // mem-initializer-list can initialize a base class using any 831 // name that denotes that base class type. 832 833 // First, check for a direct base class. 834 const CXXBaseSpecifier *DirectBaseSpec = 0; 835 for (CXXRecordDecl::base_class_const_iterator Base = 836 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) { 837 if (Context.getCanonicalType(BaseType).getUnqualifiedType() == 838 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) { 839 // We found a direct base of this type. That's what we're 840 // initializing. 841 DirectBaseSpec = &*Base; 842 break; 843 } 844 } 845 846 // Check for a virtual base class. 847 // FIXME: We might be able to short-circuit this if we know in advance that 848 // there are no virtual bases. 849 const CXXBaseSpecifier *VirtualBaseSpec = 0; 850 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 851 // We haven't found a base yet; search the class hierarchy for a 852 // virtual base class. 853 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 854 /*DetectVirtual=*/false); 855 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) { 856 for (BasePaths::paths_iterator Path = Paths.begin(); 857 Path != Paths.end(); ++Path) { 858 if (Path->back().Base->isVirtual()) { 859 VirtualBaseSpec = Path->back().Base; 860 break; 861 } 862 } 863 } 864 } 865 866 // C++ [base.class.init]p2: 867 // If a mem-initializer-id is ambiguous because it designates both 868 // a direct non-virtual base class and an inherited virtual base 869 // class, the mem-initializer is ill-formed. 870 if (DirectBaseSpec && VirtualBaseSpec) 871 return Diag(IdLoc, diag::err_base_init_direct_and_virtual) 872 << BaseType << SourceRange(IdLoc, RParenLoc); 873 // C++ [base.class.init]p2: 874 // Unless the mem-initializer-id names a nonstatic data membeer of the 875 // constructor's class ot a direst or virtual base of that class, the 876 // mem-initializer is ill-formed. 877 if (!DirectBaseSpec && !VirtualBaseSpec) 878 return Diag(IdLoc, diag::err_not_direct_base_or_virtual) 879 << BaseType << ClassDecl->getNameAsCString() 880 << SourceRange(IdLoc, RParenLoc); 881 } 882 883 CXXConstructorDecl *C = 0; 884 if (!BaseType->isDependentType() && !HasDependentArg) { 885 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( 886 Context.getCanonicalType(BaseType)); 887 C = PerformInitializationByConstructor(BaseType, (Expr **)Args, NumArgs, 888 IdLoc, SourceRange(IdLoc, RParenLoc), 889 Name, IK_Direct); 890 } 891 892 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, 893 NumArgs, C, IdLoc, RParenLoc); 894} 895 896void 897Sema::setBaseOrMemberInitializers(CXXConstructorDecl *Constructor, 898 CXXBaseOrMemberInitializer **Initializers, 899 unsigned NumInitializers, 900 llvm::SmallVectorImpl<CXXBaseSpecifier *>& Bases, 901 llvm::SmallVectorImpl<FieldDecl *>&Fields) { 902 // We need to build the initializer AST according to order of construction 903 // and not what user specified in the Initializers list. 904 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext()); 905 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit; 906 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields; 907 bool HasDependentBaseInit = false; 908 909 for (unsigned i = 0; i < NumInitializers; i++) { 910 CXXBaseOrMemberInitializer *Member = Initializers[i]; 911 if (Member->isBaseInitializer()) { 912 if (Member->getBaseClass()->isDependentType()) 913 HasDependentBaseInit = true; 914 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 915 } else { 916 AllBaseFields[Member->getMember()] = Member; 917 } 918 } 919 920 if (HasDependentBaseInit) { 921 // FIXME. This does not preserve the ordering of the initializers. 922 // Try (with -Wreorder) 923 // template<class X> struct A {}; 924 // template<class X> struct B : A<X> { 925 // B() : x1(10), A<X>() {} 926 // int x1; 927 // }; 928 // B<int> x; 929 // On seeing one dependent type, we should essentially exit this routine 930 // while preserving user-declared initializer list. When this routine is 931 // called during instantiatiation process, this routine will rebuild the 932 // oderdered initializer list correctly. 933 934 // If we have a dependent base initialization, we can't determine the 935 // association between initializers and bases; just dump the known 936 // initializers into the list, and don't try to deal with other bases. 937 for (unsigned i = 0; i < NumInitializers; i++) { 938 CXXBaseOrMemberInitializer *Member = Initializers[i]; 939 if (Member->isBaseInitializer()) 940 AllToInit.push_back(Member); 941 } 942 } else { 943 // Push virtual bases before others. 944 for (CXXRecordDecl::base_class_iterator VBase = 945 ClassDecl->vbases_begin(), 946 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 947 if (VBase->getType()->isDependentType()) 948 continue; 949 if (CXXBaseOrMemberInitializer *Value = 950 AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) { 951 CXXRecordDecl *BaseDecl = 952 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl()); 953 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null"); 954 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context)) 955 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor); 956 AllToInit.push_back(Value); 957 } 958 else { 959 CXXRecordDecl *VBaseDecl = 960 cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl()); 961 assert(VBaseDecl && "setBaseOrMemberInitializers - VBaseDecl null"); 962 CXXConstructorDecl *Ctor = VBaseDecl->getDefaultConstructor(Context); 963 if (!Ctor) 964 Bases.push_back(VBase); 965 else 966 MarkDeclarationReferenced(Constructor->getLocation(), Ctor); 967 968 CXXBaseOrMemberInitializer *Member = 969 new (Context) CXXBaseOrMemberInitializer(VBase->getType(), 0, 0, 970 Ctor, 971 SourceLocation(), 972 SourceLocation()); 973 AllToInit.push_back(Member); 974 } 975 } 976 977 for (CXXRecordDecl::base_class_iterator Base = 978 ClassDecl->bases_begin(), 979 E = ClassDecl->bases_end(); Base != E; ++Base) { 980 // Virtuals are in the virtual base list and already constructed. 981 if (Base->isVirtual()) 982 continue; 983 // Skip dependent types. 984 if (Base->getType()->isDependentType()) 985 continue; 986 if (CXXBaseOrMemberInitializer *Value = 987 AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) { 988 CXXRecordDecl *BaseDecl = 989 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 990 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null"); 991 if (CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context)) 992 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor); 993 AllToInit.push_back(Value); 994 } 995 else { 996 CXXRecordDecl *BaseDecl = 997 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 998 assert(BaseDecl && "setBaseOrMemberInitializers - BaseDecl null"); 999 CXXConstructorDecl *Ctor = BaseDecl->getDefaultConstructor(Context); 1000 if (!Ctor) 1001 Bases.push_back(Base); 1002 else 1003 MarkDeclarationReferenced(Constructor->getLocation(), Ctor); 1004 1005 CXXBaseOrMemberInitializer *Member = 1006 new (Context) CXXBaseOrMemberInitializer(Base->getType(), 0, 0, 1007 BaseDecl->getDefaultConstructor(Context), 1008 SourceLocation(), 1009 SourceLocation()); 1010 AllToInit.push_back(Member); 1011 } 1012 } 1013 } 1014 1015 // non-static data members. 1016 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1017 E = ClassDecl->field_end(); Field != E; ++Field) { 1018 if ((*Field)->isAnonymousStructOrUnion()) { 1019 if (const RecordType *FieldClassType = 1020 Field->getType()->getAs<RecordType>()) { 1021 CXXRecordDecl *FieldClassDecl 1022 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1023 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(), 1024 EA = FieldClassDecl->field_end(); FA != EA; FA++) { 1025 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) { 1026 // 'Member' is the anonymous union field and 'AnonUnionMember' is 1027 // set to the anonymous union data member used in the initializer 1028 // list. 1029 Value->setMember(*Field); 1030 Value->setAnonUnionMember(*FA); 1031 AllToInit.push_back(Value); 1032 break; 1033 } 1034 } 1035 } 1036 continue; 1037 } 1038 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) { 1039 QualType FT = (*Field)->getType(); 1040 if (const RecordType* RT = FT->getAs<RecordType>()) { 1041 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RT->getDecl()); 1042 assert(FieldRecDecl && "setBaseOrMemberInitializers - BaseDecl null"); 1043 if (CXXConstructorDecl *Ctor = 1044 FieldRecDecl->getDefaultConstructor(Context)) 1045 MarkDeclarationReferenced(Value->getSourceLocation(), Ctor); 1046 } 1047 AllToInit.push_back(Value); 1048 continue; 1049 } 1050 1051 QualType FT = Context.getBaseElementType((*Field)->getType()); 1052 if (const RecordType* RT = FT->getAs<RecordType>()) { 1053 CXXConstructorDecl *Ctor = 1054 cast<CXXRecordDecl>(RT->getDecl())->getDefaultConstructor(Context); 1055 if (!Ctor && !FT->isDependentType()) 1056 Fields.push_back(*Field); 1057 CXXBaseOrMemberInitializer *Member = 1058 new (Context) CXXBaseOrMemberInitializer((*Field), 0, 0, 1059 Ctor, 1060 SourceLocation(), 1061 SourceLocation()); 1062 AllToInit.push_back(Member); 1063 if (Ctor) 1064 MarkDeclarationReferenced(Constructor->getLocation(), Ctor); 1065 if (FT.isConstQualified() && (!Ctor || Ctor->isTrivial())) { 1066 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor) 1067 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName(); 1068 Diag((*Field)->getLocation(), diag::note_declared_at); 1069 } 1070 } 1071 else if (FT->isReferenceType()) { 1072 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor) 1073 << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getDeclName(); 1074 Diag((*Field)->getLocation(), diag::note_declared_at); 1075 } 1076 else if (FT.isConstQualified()) { 1077 Diag(Constructor->getLocation(), diag::err_unintialized_member_in_ctor) 1078 << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getDeclName(); 1079 Diag((*Field)->getLocation(), diag::note_declared_at); 1080 } 1081 } 1082 1083 NumInitializers = AllToInit.size(); 1084 if (NumInitializers > 0) { 1085 Constructor->setNumBaseOrMemberInitializers(NumInitializers); 1086 CXXBaseOrMemberInitializer **baseOrMemberInitializers = 1087 new (Context) CXXBaseOrMemberInitializer*[NumInitializers]; 1088 1089 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers); 1090 for (unsigned Idx = 0; Idx < NumInitializers; ++Idx) 1091 baseOrMemberInitializers[Idx] = AllToInit[Idx]; 1092 } 1093} 1094 1095void 1096Sema::BuildBaseOrMemberInitializers(ASTContext &C, 1097 CXXConstructorDecl *Constructor, 1098 CXXBaseOrMemberInitializer **Initializers, 1099 unsigned NumInitializers 1100 ) { 1101 llvm::SmallVector<CXXBaseSpecifier *, 4>Bases; 1102 llvm::SmallVector<FieldDecl *, 4>Members; 1103 1104 setBaseOrMemberInitializers(Constructor, 1105 Initializers, NumInitializers, Bases, Members); 1106 for (unsigned int i = 0; i < Bases.size(); i++) 1107 Diag(Bases[i]->getSourceRange().getBegin(), 1108 diag::err_missing_default_constructor) << 0 << Bases[i]->getType(); 1109 for (unsigned int i = 0; i < Members.size(); i++) 1110 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor) 1111 << 1 << Members[i]->getType(); 1112} 1113 1114static void *GetKeyForTopLevelField(FieldDecl *Field) { 1115 // For anonymous unions, use the class declaration as the key. 1116 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 1117 if (RT->getDecl()->isAnonymousStructOrUnion()) 1118 return static_cast<void *>(RT->getDecl()); 1119 } 1120 return static_cast<void *>(Field); 1121} 1122 1123static void *GetKeyForBase(QualType BaseType) { 1124 if (const RecordType *RT = BaseType->getAs<RecordType>()) 1125 return (void *)RT; 1126 1127 assert(0 && "Unexpected base type!"); 1128 return 0; 1129} 1130 1131static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member, 1132 bool MemberMaybeAnon = false) { 1133 // For fields injected into the class via declaration of an anonymous union, 1134 // use its anonymous union class declaration as the unique key. 1135 if (Member->isMemberInitializer()) { 1136 FieldDecl *Field = Member->getMember(); 1137 1138 // After BuildBaseOrMemberInitializers call, Field is the anonymous union 1139 // data member of the class. Data member used in the initializer list is 1140 // in AnonUnionMember field. 1141 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion()) 1142 Field = Member->getAnonUnionMember(); 1143 if (Field->getDeclContext()->isRecord()) { 1144 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext()); 1145 if (RD->isAnonymousStructOrUnion()) 1146 return static_cast<void *>(RD); 1147 } 1148 return static_cast<void *>(Field); 1149 } 1150 1151 return GetKeyForBase(QualType(Member->getBaseClass(), 0)); 1152} 1153 1154void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl, 1155 SourceLocation ColonLoc, 1156 MemInitTy **MemInits, unsigned NumMemInits) { 1157 if (!ConstructorDecl) 1158 return; 1159 1160 AdjustDeclIfTemplate(ConstructorDecl); 1161 1162 CXXConstructorDecl *Constructor 1163 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>()); 1164 1165 if (!Constructor) { 1166 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 1167 return; 1168 } 1169 1170 if (!Constructor->isDependentContext()) { 1171 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members; 1172 bool err = false; 1173 for (unsigned i = 0; i < NumMemInits; i++) { 1174 CXXBaseOrMemberInitializer *Member = 1175 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]); 1176 void *KeyToMember = GetKeyForMember(Member); 1177 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember]; 1178 if (!PrevMember) { 1179 PrevMember = Member; 1180 continue; 1181 } 1182 if (FieldDecl *Field = Member->getMember()) 1183 Diag(Member->getSourceLocation(), 1184 diag::error_multiple_mem_initialization) 1185 << Field->getNameAsString(); 1186 else { 1187 Type *BaseClass = Member->getBaseClass(); 1188 assert(BaseClass && "ActOnMemInitializers - neither field or base"); 1189 Diag(Member->getSourceLocation(), 1190 diag::error_multiple_base_initialization) 1191 << BaseClass->getDesugaredType(true); 1192 } 1193 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer) 1194 << 0; 1195 err = true; 1196 } 1197 1198 if (err) 1199 return; 1200 } 1201 1202 BuildBaseOrMemberInitializers(Context, Constructor, 1203 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits), 1204 NumMemInits); 1205 1206 if (Constructor->isDependentContext()) 1207 return; 1208 1209 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) == 1210 Diagnostic::Ignored && 1211 Diags.getDiagnosticLevel(diag::warn_field_initialized) == 1212 Diagnostic::Ignored) 1213 return; 1214 1215 // Also issue warning if order of ctor-initializer list does not match order 1216 // of 1) base class declarations and 2) order of non-static data members. 1217 llvm::SmallVector<const void*, 32> AllBaseOrMembers; 1218 1219 CXXRecordDecl *ClassDecl 1220 = cast<CXXRecordDecl>(Constructor->getDeclContext()); 1221 // Push virtual bases before others. 1222 for (CXXRecordDecl::base_class_iterator VBase = 1223 ClassDecl->vbases_begin(), 1224 E = ClassDecl->vbases_end(); VBase != E; ++VBase) 1225 AllBaseOrMembers.push_back(GetKeyForBase(VBase->getType())); 1226 1227 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 1228 E = ClassDecl->bases_end(); Base != E; ++Base) { 1229 // Virtuals are alread in the virtual base list and are constructed 1230 // first. 1231 if (Base->isVirtual()) 1232 continue; 1233 AllBaseOrMembers.push_back(GetKeyForBase(Base->getType())); 1234 } 1235 1236 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1237 E = ClassDecl->field_end(); Field != E; ++Field) 1238 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field)); 1239 1240 int Last = AllBaseOrMembers.size(); 1241 int curIndex = 0; 1242 CXXBaseOrMemberInitializer *PrevMember = 0; 1243 for (unsigned i = 0; i < NumMemInits; i++) { 1244 CXXBaseOrMemberInitializer *Member = 1245 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]); 1246 void *MemberInCtorList = GetKeyForMember(Member, true); 1247 1248 for (; curIndex < Last; curIndex++) 1249 if (MemberInCtorList == AllBaseOrMembers[curIndex]) 1250 break; 1251 if (curIndex == Last) { 1252 assert(PrevMember && "Member not in member list?!"); 1253 // Initializer as specified in ctor-initializer list is out of order. 1254 // Issue a warning diagnostic. 1255 if (PrevMember->isBaseInitializer()) { 1256 // Diagnostics is for an initialized base class. 1257 Type *BaseClass = PrevMember->getBaseClass(); 1258 Diag(PrevMember->getSourceLocation(), 1259 diag::warn_base_initialized) 1260 << BaseClass->getDesugaredType(true); 1261 } else { 1262 FieldDecl *Field = PrevMember->getMember(); 1263 Diag(PrevMember->getSourceLocation(), 1264 diag::warn_field_initialized) 1265 << Field->getNameAsString(); 1266 } 1267 // Also the note! 1268 if (FieldDecl *Field = Member->getMember()) 1269 Diag(Member->getSourceLocation(), 1270 diag::note_fieldorbase_initialized_here) << 0 1271 << Field->getNameAsString(); 1272 else { 1273 Type *BaseClass = Member->getBaseClass(); 1274 Diag(Member->getSourceLocation(), 1275 diag::note_fieldorbase_initialized_here) << 1 1276 << BaseClass->getDesugaredType(true); 1277 } 1278 for (curIndex = 0; curIndex < Last; curIndex++) 1279 if (MemberInCtorList == AllBaseOrMembers[curIndex]) 1280 break; 1281 } 1282 PrevMember = Member; 1283 } 1284} 1285 1286void 1287Sema::computeBaseOrMembersToDestroy(CXXDestructorDecl *Destructor) { 1288 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Destructor->getDeclContext()); 1289 llvm::SmallVector<uintptr_t, 32> AllToDestruct; 1290 1291 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(), 1292 E = ClassDecl->vbases_end(); VBase != E; ++VBase) { 1293 if (VBase->getType()->isDependentType()) 1294 continue; 1295 // Skip over virtual bases which have trivial destructors. 1296 CXXRecordDecl *BaseClassDecl 1297 = cast<CXXRecordDecl>(VBase->getType()->getAs<RecordType>()->getDecl()); 1298 if (BaseClassDecl->hasTrivialDestructor()) 1299 continue; 1300 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context)) 1301 MarkDeclarationReferenced(Destructor->getLocation(), 1302 const_cast<CXXDestructorDecl*>(Dtor)); 1303 1304 uintptr_t Member = 1305 reinterpret_cast<uintptr_t>(VBase->getType().getTypePtr()) 1306 | CXXDestructorDecl::VBASE; 1307 AllToDestruct.push_back(Member); 1308 } 1309 for (CXXRecordDecl::base_class_iterator Base = 1310 ClassDecl->bases_begin(), 1311 E = ClassDecl->bases_end(); Base != E; ++Base) { 1312 if (Base->isVirtual()) 1313 continue; 1314 if (Base->getType()->isDependentType()) 1315 continue; 1316 // Skip over virtual bases which have trivial destructors. 1317 CXXRecordDecl *BaseClassDecl 1318 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1319 if (BaseClassDecl->hasTrivialDestructor()) 1320 continue; 1321 if (const CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context)) 1322 MarkDeclarationReferenced(Destructor->getLocation(), 1323 const_cast<CXXDestructorDecl*>(Dtor)); 1324 uintptr_t Member = 1325 reinterpret_cast<uintptr_t>(Base->getType().getTypePtr()) 1326 | CXXDestructorDecl::DRCTNONVBASE; 1327 AllToDestruct.push_back(Member); 1328 } 1329 1330 // non-static data members. 1331 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1332 E = ClassDecl->field_end(); Field != E; ++Field) { 1333 QualType FieldType = Context.getBaseElementType((*Field)->getType()); 1334 1335 if (const RecordType* RT = FieldType->getAs<RecordType>()) { 1336 // Skip over virtual bases which have trivial destructors. 1337 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1338 if (FieldClassDecl->hasTrivialDestructor()) 1339 continue; 1340 if (const CXXDestructorDecl *Dtor = 1341 FieldClassDecl->getDestructor(Context)) 1342 MarkDeclarationReferenced(Destructor->getLocation(), 1343 const_cast<CXXDestructorDecl*>(Dtor)); 1344 uintptr_t Member = reinterpret_cast<uintptr_t>(*Field); 1345 AllToDestruct.push_back(Member); 1346 } 1347 } 1348 1349 unsigned NumDestructions = AllToDestruct.size(); 1350 if (NumDestructions > 0) { 1351 Destructor->setNumBaseOrMemberDestructions(NumDestructions); 1352 uintptr_t *BaseOrMemberDestructions = 1353 new (Context) uintptr_t [NumDestructions]; 1354 // Insert in reverse order. 1355 for (int Idx = NumDestructions-1, i=0 ; Idx >= 0; --Idx) 1356 BaseOrMemberDestructions[i++] = AllToDestruct[Idx]; 1357 Destructor->setBaseOrMemberDestructions(BaseOrMemberDestructions); 1358 } 1359} 1360 1361void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) { 1362 if (!CDtorDecl) 1363 return; 1364 1365 AdjustDeclIfTemplate(CDtorDecl); 1366 1367 if (CXXConstructorDecl *Constructor 1368 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>())) 1369 BuildBaseOrMemberInitializers(Context, 1370 Constructor, 1371 (CXXBaseOrMemberInitializer **)0, 0); 1372} 1373 1374namespace { 1375 /// PureVirtualMethodCollector - traverses a class and its superclasses 1376 /// and determines if it has any pure virtual methods. 1377 class VISIBILITY_HIDDEN PureVirtualMethodCollector { 1378 ASTContext &Context; 1379 1380 public: 1381 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList; 1382 1383 private: 1384 MethodList Methods; 1385 1386 void Collect(const CXXRecordDecl* RD, MethodList& Methods); 1387 1388 public: 1389 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD) 1390 : Context(Ctx) { 1391 1392 MethodList List; 1393 Collect(RD, List); 1394 1395 // Copy the temporary list to methods, and make sure to ignore any 1396 // null entries. 1397 for (size_t i = 0, e = List.size(); i != e; ++i) { 1398 if (List[i]) 1399 Methods.push_back(List[i]); 1400 } 1401 } 1402 1403 bool empty() const { return Methods.empty(); } 1404 1405 MethodList::const_iterator methods_begin() { return Methods.begin(); } 1406 MethodList::const_iterator methods_end() { return Methods.end(); } 1407 }; 1408 1409 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD, 1410 MethodList& Methods) { 1411 // First, collect the pure virtual methods for the base classes. 1412 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 1413 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) { 1414 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) { 1415 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl()); 1416 if (BaseDecl && BaseDecl->isAbstract()) 1417 Collect(BaseDecl, Methods); 1418 } 1419 } 1420 1421 // Next, zero out any pure virtual methods that this class overrides. 1422 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy; 1423 1424 MethodSetTy OverriddenMethods; 1425 size_t MethodsSize = Methods.size(); 1426 1427 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end(); 1428 i != e; ++i) { 1429 // Traverse the record, looking for methods. 1430 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) { 1431 // If the method is pure virtual, add it to the methods vector. 1432 if (MD->isPure()) { 1433 Methods.push_back(MD); 1434 continue; 1435 } 1436 1437 // Otherwise, record all the overridden methods in our set. 1438 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 1439 E = MD->end_overridden_methods(); I != E; ++I) { 1440 // Keep track of the overridden methods. 1441 OverriddenMethods.insert(*I); 1442 } 1443 } 1444 } 1445 1446 // Now go through the methods and zero out all the ones we know are 1447 // overridden. 1448 for (size_t i = 0, e = MethodsSize; i != e; ++i) { 1449 if (OverriddenMethods.count(Methods[i])) 1450 Methods[i] = 0; 1451 } 1452 1453 } 1454} 1455 1456 1457bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 1458 unsigned DiagID, AbstractDiagSelID SelID, 1459 const CXXRecordDecl *CurrentRD) { 1460 if (SelID == -1) 1461 return RequireNonAbstractType(Loc, T, 1462 PDiag(DiagID), CurrentRD); 1463 else 1464 return RequireNonAbstractType(Loc, T, 1465 PDiag(DiagID) << SelID, CurrentRD); 1466} 1467 1468bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 1469 const PartialDiagnostic &PD, 1470 const CXXRecordDecl *CurrentRD) { 1471 if (!getLangOptions().CPlusPlus) 1472 return false; 1473 1474 if (const ArrayType *AT = Context.getAsArrayType(T)) 1475 return RequireNonAbstractType(Loc, AT->getElementType(), PD, 1476 CurrentRD); 1477 1478 if (const PointerType *PT = T->getAs<PointerType>()) { 1479 // Find the innermost pointer type. 1480 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>()) 1481 PT = T; 1482 1483 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType())) 1484 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD); 1485 } 1486 1487 const RecordType *RT = T->getAs<RecordType>(); 1488 if (!RT) 1489 return false; 1490 1491 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 1492 if (!RD) 1493 return false; 1494 1495 if (CurrentRD && CurrentRD != RD) 1496 return false; 1497 1498 if (!RD->isAbstract()) 1499 return false; 1500 1501 Diag(Loc, PD) << RD->getDeclName(); 1502 1503 // Check if we've already emitted the list of pure virtual functions for this 1504 // class. 1505 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 1506 return true; 1507 1508 PureVirtualMethodCollector Collector(Context, RD); 1509 1510 for (PureVirtualMethodCollector::MethodList::const_iterator I = 1511 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) { 1512 const CXXMethodDecl *MD = *I; 1513 1514 Diag(MD->getLocation(), diag::note_pure_virtual_function) << 1515 MD->getDeclName(); 1516 } 1517 1518 if (!PureVirtualClassDiagSet) 1519 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 1520 PureVirtualClassDiagSet->insert(RD); 1521 1522 return true; 1523} 1524 1525namespace { 1526 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser 1527 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> { 1528 Sema &SemaRef; 1529 CXXRecordDecl *AbstractClass; 1530 1531 bool VisitDeclContext(const DeclContext *DC) { 1532 bool Invalid = false; 1533 1534 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(), 1535 E = DC->decls_end(); I != E; ++I) 1536 Invalid |= Visit(*I); 1537 1538 return Invalid; 1539 } 1540 1541 public: 1542 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac) 1543 : SemaRef(SemaRef), AbstractClass(ac) { 1544 Visit(SemaRef.Context.getTranslationUnitDecl()); 1545 } 1546 1547 bool VisitFunctionDecl(const FunctionDecl *FD) { 1548 if (FD->isThisDeclarationADefinition()) { 1549 // No need to do the check if we're in a definition, because it requires 1550 // that the return/param types are complete. 1551 // because that requires 1552 return VisitDeclContext(FD); 1553 } 1554 1555 // Check the return type. 1556 QualType RTy = FD->getType()->getAsFunctionType()->getResultType(); 1557 bool Invalid = 1558 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy, 1559 diag::err_abstract_type_in_decl, 1560 Sema::AbstractReturnType, 1561 AbstractClass); 1562 1563 for (FunctionDecl::param_const_iterator I = FD->param_begin(), 1564 E = FD->param_end(); I != E; ++I) { 1565 const ParmVarDecl *VD = *I; 1566 Invalid |= 1567 SemaRef.RequireNonAbstractType(VD->getLocation(), 1568 VD->getOriginalType(), 1569 diag::err_abstract_type_in_decl, 1570 Sema::AbstractParamType, 1571 AbstractClass); 1572 } 1573 1574 return Invalid; 1575 } 1576 1577 bool VisitDecl(const Decl* D) { 1578 if (const DeclContext *DC = dyn_cast<DeclContext>(D)) 1579 return VisitDeclContext(DC); 1580 1581 return false; 1582 } 1583 }; 1584} 1585 1586void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 1587 DeclPtrTy TagDecl, 1588 SourceLocation LBrac, 1589 SourceLocation RBrac) { 1590 if (!TagDecl) 1591 return; 1592 1593 AdjustDeclIfTemplate(TagDecl); 1594 ActOnFields(S, RLoc, TagDecl, 1595 (DeclPtrTy*)FieldCollector->getCurFields(), 1596 FieldCollector->getCurNumFields(), LBrac, RBrac, 0); 1597 1598 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>()); 1599 if (!RD->isAbstract()) { 1600 // Collect all the pure virtual methods and see if this is an abstract 1601 // class after all. 1602 PureVirtualMethodCollector Collector(Context, RD); 1603 if (!Collector.empty()) 1604 RD->setAbstract(true); 1605 } 1606 1607 if (RD->isAbstract()) 1608 AbstractClassUsageDiagnoser(*this, RD); 1609 1610 if (!RD->isDependentType()) 1611 AddImplicitlyDeclaredMembersToClass(RD); 1612} 1613 1614/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 1615/// special functions, such as the default constructor, copy 1616/// constructor, or destructor, to the given C++ class (C++ 1617/// [special]p1). This routine can only be executed just before the 1618/// definition of the class is complete. 1619void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 1620 CanQualType ClassType 1621 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 1622 1623 // FIXME: Implicit declarations have exception specifications, which are 1624 // the union of the specifications of the implicitly called functions. 1625 1626 if (!ClassDecl->hasUserDeclaredConstructor()) { 1627 // C++ [class.ctor]p5: 1628 // A default constructor for a class X is a constructor of class X 1629 // that can be called without an argument. If there is no 1630 // user-declared constructor for class X, a default constructor is 1631 // implicitly declared. An implicitly-declared default constructor 1632 // is an inline public member of its class. 1633 DeclarationName Name 1634 = Context.DeclarationNames.getCXXConstructorName(ClassType); 1635 CXXConstructorDecl *DefaultCon = 1636 CXXConstructorDecl::Create(Context, ClassDecl, 1637 ClassDecl->getLocation(), Name, 1638 Context.getFunctionType(Context.VoidTy, 1639 0, 0, false, 0), 1640 /*DInfo=*/0, 1641 /*isExplicit=*/false, 1642 /*isInline=*/true, 1643 /*isImplicitlyDeclared=*/true); 1644 DefaultCon->setAccess(AS_public); 1645 DefaultCon->setImplicit(); 1646 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor()); 1647 ClassDecl->addDecl(DefaultCon); 1648 } 1649 1650 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 1651 // C++ [class.copy]p4: 1652 // If the class definition does not explicitly declare a copy 1653 // constructor, one is declared implicitly. 1654 1655 // C++ [class.copy]p5: 1656 // The implicitly-declared copy constructor for a class X will 1657 // have the form 1658 // 1659 // X::X(const X&) 1660 // 1661 // if 1662 bool HasConstCopyConstructor = true; 1663 1664 // -- each direct or virtual base class B of X has a copy 1665 // constructor whose first parameter is of type const B& or 1666 // const volatile B&, and 1667 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 1668 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 1669 const CXXRecordDecl *BaseClassDecl 1670 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1671 HasConstCopyConstructor 1672 = BaseClassDecl->hasConstCopyConstructor(Context); 1673 } 1674 1675 // -- for all the nonstatic data members of X that are of a 1676 // class type M (or array thereof), each such class type 1677 // has a copy constructor whose first parameter is of type 1678 // const M& or const volatile M&. 1679 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 1680 HasConstCopyConstructor && Field != ClassDecl->field_end(); 1681 ++Field) { 1682 QualType FieldType = (*Field)->getType(); 1683 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 1684 FieldType = Array->getElementType(); 1685 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 1686 const CXXRecordDecl *FieldClassDecl 1687 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1688 HasConstCopyConstructor 1689 = FieldClassDecl->hasConstCopyConstructor(Context); 1690 } 1691 } 1692 1693 // Otherwise, the implicitly declared copy constructor will have 1694 // the form 1695 // 1696 // X::X(X&) 1697 QualType ArgType = ClassType; 1698 if (HasConstCopyConstructor) 1699 ArgType = ArgType.withConst(); 1700 ArgType = Context.getLValueReferenceType(ArgType); 1701 1702 // An implicitly-declared copy constructor is an inline public 1703 // member of its class. 1704 DeclarationName Name 1705 = Context.DeclarationNames.getCXXConstructorName(ClassType); 1706 CXXConstructorDecl *CopyConstructor 1707 = CXXConstructorDecl::Create(Context, ClassDecl, 1708 ClassDecl->getLocation(), Name, 1709 Context.getFunctionType(Context.VoidTy, 1710 &ArgType, 1, 1711 false, 0), 1712 /*DInfo=*/0, 1713 /*isExplicit=*/false, 1714 /*isInline=*/true, 1715 /*isImplicitlyDeclared=*/true); 1716 CopyConstructor->setAccess(AS_public); 1717 CopyConstructor->setImplicit(); 1718 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor()); 1719 1720 // Add the parameter to the constructor. 1721 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 1722 ClassDecl->getLocation(), 1723 /*IdentifierInfo=*/0, 1724 ArgType, /*DInfo=*/0, 1725 VarDecl::None, 0); 1726 CopyConstructor->setParams(Context, &FromParam, 1); 1727 ClassDecl->addDecl(CopyConstructor); 1728 } 1729 1730 if (!ClassDecl->hasUserDeclaredCopyAssignment()) { 1731 // Note: The following rules are largely analoguous to the copy 1732 // constructor rules. Note that virtual bases are not taken into account 1733 // for determining the argument type of the operator. Note also that 1734 // operators taking an object instead of a reference are allowed. 1735 // 1736 // C++ [class.copy]p10: 1737 // If the class definition does not explicitly declare a copy 1738 // assignment operator, one is declared implicitly. 1739 // The implicitly-defined copy assignment operator for a class X 1740 // will have the form 1741 // 1742 // X& X::operator=(const X&) 1743 // 1744 // if 1745 bool HasConstCopyAssignment = true; 1746 1747 // -- each direct base class B of X has a copy assignment operator 1748 // whose parameter is of type const B&, const volatile B& or B, 1749 // and 1750 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 1751 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) { 1752 const CXXRecordDecl *BaseClassDecl 1753 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1754 const CXXMethodDecl *MD = 0; 1755 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context, 1756 MD); 1757 } 1758 1759 // -- for all the nonstatic data members of X that are of a class 1760 // type M (or array thereof), each such class type has a copy 1761 // assignment operator whose parameter is of type const M&, 1762 // const volatile M& or M. 1763 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 1764 HasConstCopyAssignment && Field != ClassDecl->field_end(); 1765 ++Field) { 1766 QualType FieldType = (*Field)->getType(); 1767 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 1768 FieldType = Array->getElementType(); 1769 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 1770 const CXXRecordDecl *FieldClassDecl 1771 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1772 const CXXMethodDecl *MD = 0; 1773 HasConstCopyAssignment 1774 = FieldClassDecl->hasConstCopyAssignment(Context, MD); 1775 } 1776 } 1777 1778 // Otherwise, the implicitly declared copy assignment operator will 1779 // have the form 1780 // 1781 // X& X::operator=(X&) 1782 QualType ArgType = ClassType; 1783 QualType RetType = Context.getLValueReferenceType(ArgType); 1784 if (HasConstCopyAssignment) 1785 ArgType = ArgType.withConst(); 1786 ArgType = Context.getLValueReferenceType(ArgType); 1787 1788 // An implicitly-declared copy assignment operator is an inline public 1789 // member of its class. 1790 DeclarationName Name = 1791 Context.DeclarationNames.getCXXOperatorName(OO_Equal); 1792 CXXMethodDecl *CopyAssignment = 1793 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name, 1794 Context.getFunctionType(RetType, &ArgType, 1, 1795 false, 0), 1796 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true); 1797 CopyAssignment->setAccess(AS_public); 1798 CopyAssignment->setImplicit(); 1799 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment()); 1800 CopyAssignment->setCopyAssignment(true); 1801 1802 // Add the parameter to the operator. 1803 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 1804 ClassDecl->getLocation(), 1805 /*IdentifierInfo=*/0, 1806 ArgType, /*DInfo=*/0, 1807 VarDecl::None, 0); 1808 CopyAssignment->setParams(Context, &FromParam, 1); 1809 1810 // Don't call addedAssignmentOperator. There is no way to distinguish an 1811 // implicit from an explicit assignment operator. 1812 ClassDecl->addDecl(CopyAssignment); 1813 } 1814 1815 if (!ClassDecl->hasUserDeclaredDestructor()) { 1816 // C++ [class.dtor]p2: 1817 // If a class has no user-declared destructor, a destructor is 1818 // declared implicitly. An implicitly-declared destructor is an 1819 // inline public member of its class. 1820 DeclarationName Name 1821 = Context.DeclarationNames.getCXXDestructorName(ClassType); 1822 CXXDestructorDecl *Destructor 1823 = CXXDestructorDecl::Create(Context, ClassDecl, 1824 ClassDecl->getLocation(), Name, 1825 Context.getFunctionType(Context.VoidTy, 1826 0, 0, false, 0), 1827 /*isInline=*/true, 1828 /*isImplicitlyDeclared=*/true); 1829 Destructor->setAccess(AS_public); 1830 Destructor->setImplicit(); 1831 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 1832 ClassDecl->addDecl(Destructor); 1833 } 1834} 1835 1836void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) { 1837 TemplateDecl *Template = TemplateD.getAs<TemplateDecl>(); 1838 if (!Template) 1839 return; 1840 1841 TemplateParameterList *Params = Template->getTemplateParameters(); 1842 for (TemplateParameterList::iterator Param = Params->begin(), 1843 ParamEnd = Params->end(); 1844 Param != ParamEnd; ++Param) { 1845 NamedDecl *Named = cast<NamedDecl>(*Param); 1846 if (Named->getDeclName()) { 1847 S->AddDecl(DeclPtrTy::make(Named)); 1848 IdResolver.AddDecl(Named); 1849 } 1850 } 1851} 1852 1853/// ActOnStartDelayedCXXMethodDeclaration - We have completed 1854/// parsing a top-level (non-nested) C++ class, and we are now 1855/// parsing those parts of the given Method declaration that could 1856/// not be parsed earlier (C++ [class.mem]p2), such as default 1857/// arguments. This action should enter the scope of the given 1858/// Method declaration as if we had just parsed the qualified method 1859/// name. However, it should not bring the parameters into scope; 1860/// that will be performed by ActOnDelayedCXXMethodParameter. 1861void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 1862 if (!MethodD) 1863 return; 1864 1865 AdjustDeclIfTemplate(MethodD); 1866 1867 CXXScopeSpec SS; 1868 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 1869 QualType ClassTy 1870 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 1871 SS.setScopeRep( 1872 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr())); 1873 ActOnCXXEnterDeclaratorScope(S, SS); 1874} 1875 1876/// ActOnDelayedCXXMethodParameter - We've already started a delayed 1877/// C++ method declaration. We're (re-)introducing the given 1878/// function parameter into scope for use in parsing later parts of 1879/// the method declaration. For example, we could see an 1880/// ActOnParamDefaultArgument event for this parameter. 1881void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) { 1882 if (!ParamD) 1883 return; 1884 1885 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>()); 1886 1887 // If this parameter has an unparsed default argument, clear it out 1888 // to make way for the parsed default argument. 1889 if (Param->hasUnparsedDefaultArg()) 1890 Param->setDefaultArg(0); 1891 1892 S->AddDecl(DeclPtrTy::make(Param)); 1893 if (Param->getDeclName()) 1894 IdResolver.AddDecl(Param); 1895} 1896 1897/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 1898/// processing the delayed method declaration for Method. The method 1899/// declaration is now considered finished. There may be a separate 1900/// ActOnStartOfFunctionDef action later (not necessarily 1901/// immediately!) for this method, if it was also defined inside the 1902/// class body. 1903void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) { 1904 if (!MethodD) 1905 return; 1906 1907 AdjustDeclIfTemplate(MethodD); 1908 1909 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>()); 1910 CXXScopeSpec SS; 1911 QualType ClassTy 1912 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 1913 SS.setScopeRep( 1914 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr())); 1915 ActOnCXXExitDeclaratorScope(S, SS); 1916 1917 // Now that we have our default arguments, check the constructor 1918 // again. It could produce additional diagnostics or affect whether 1919 // the class has implicitly-declared destructors, among other 1920 // things. 1921 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 1922 CheckConstructor(Constructor); 1923 1924 // Check the default arguments, which we may have added. 1925 if (!Method->isInvalidDecl()) 1926 CheckCXXDefaultArguments(Method); 1927} 1928 1929/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 1930/// the well-formedness of the constructor declarator @p D with type @p 1931/// R. If there are any errors in the declarator, this routine will 1932/// emit diagnostics and set the invalid bit to true. In any case, the type 1933/// will be updated to reflect a well-formed type for the constructor and 1934/// returned. 1935QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 1936 FunctionDecl::StorageClass &SC) { 1937 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 1938 1939 // C++ [class.ctor]p3: 1940 // A constructor shall not be virtual (10.3) or static (9.4). A 1941 // constructor can be invoked for a const, volatile or const 1942 // volatile object. A constructor shall not be declared const, 1943 // volatile, or const volatile (9.3.2). 1944 if (isVirtual) { 1945 if (!D.isInvalidType()) 1946 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 1947 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 1948 << SourceRange(D.getIdentifierLoc()); 1949 D.setInvalidType(); 1950 } 1951 if (SC == FunctionDecl::Static) { 1952 if (!D.isInvalidType()) 1953 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 1954 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 1955 << SourceRange(D.getIdentifierLoc()); 1956 D.setInvalidType(); 1957 SC = FunctionDecl::None; 1958 } 1959 1960 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1961 if (FTI.TypeQuals != 0) { 1962 if (FTI.TypeQuals & QualType::Const) 1963 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 1964 << "const" << SourceRange(D.getIdentifierLoc()); 1965 if (FTI.TypeQuals & QualType::Volatile) 1966 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 1967 << "volatile" << SourceRange(D.getIdentifierLoc()); 1968 if (FTI.TypeQuals & QualType::Restrict) 1969 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 1970 << "restrict" << SourceRange(D.getIdentifierLoc()); 1971 } 1972 1973 // Rebuild the function type "R" without any type qualifiers (in 1974 // case any of the errors above fired) and with "void" as the 1975 // return type, since constructors don't have return types. We 1976 // *always* have to do this, because GetTypeForDeclarator will 1977 // put in a result type of "int" when none was specified. 1978 const FunctionProtoType *Proto = R->getAsFunctionProtoType(); 1979 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 1980 Proto->getNumArgs(), 1981 Proto->isVariadic(), 0); 1982} 1983 1984/// CheckConstructor - Checks a fully-formed constructor for 1985/// well-formedness, issuing any diagnostics required. Returns true if 1986/// the constructor declarator is invalid. 1987void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 1988 CXXRecordDecl *ClassDecl 1989 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 1990 if (!ClassDecl) 1991 return Constructor->setInvalidDecl(); 1992 1993 // C++ [class.copy]p3: 1994 // A declaration of a constructor for a class X is ill-formed if 1995 // its first parameter is of type (optionally cv-qualified) X and 1996 // either there are no other parameters or else all other 1997 // parameters have default arguments. 1998 if (!Constructor->isInvalidDecl() && 1999 ((Constructor->getNumParams() == 1) || 2000 (Constructor->getNumParams() > 1 && 2001 Constructor->getParamDecl(1)->hasDefaultArg()))) { 2002 QualType ParamType = Constructor->getParamDecl(0)->getType(); 2003 QualType ClassTy = Context.getTagDeclType(ClassDecl); 2004 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 2005 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 2006 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 2007 << CodeModificationHint::CreateInsertion(ParamLoc, " const &"); 2008 Constructor->setInvalidDecl(); 2009 } 2010 } 2011 2012 // Notify the class that we've added a constructor. 2013 ClassDecl->addedConstructor(Context, Constructor); 2014} 2015 2016static inline bool 2017FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) { 2018 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 2019 FTI.ArgInfo[0].Param && 2020 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()); 2021} 2022 2023/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 2024/// the well-formednes of the destructor declarator @p D with type @p 2025/// R. If there are any errors in the declarator, this routine will 2026/// emit diagnostics and set the declarator to invalid. Even if this happens, 2027/// will be updated to reflect a well-formed type for the destructor and 2028/// returned. 2029QualType Sema::CheckDestructorDeclarator(Declarator &D, 2030 FunctionDecl::StorageClass& SC) { 2031 // C++ [class.dtor]p1: 2032 // [...] A typedef-name that names a class is a class-name 2033 // (7.1.3); however, a typedef-name that names a class shall not 2034 // be used as the identifier in the declarator for a destructor 2035 // declaration. 2036 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType()); 2037 if (isa<TypedefType>(DeclaratorType)) { 2038 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 2039 << DeclaratorType; 2040 D.setInvalidType(); 2041 } 2042 2043 // C++ [class.dtor]p2: 2044 // A destructor is used to destroy objects of its class type. A 2045 // destructor takes no parameters, and no return type can be 2046 // specified for it (not even void). The address of a destructor 2047 // shall not be taken. A destructor shall not be static. A 2048 // destructor can be invoked for a const, volatile or const 2049 // volatile object. A destructor shall not be declared const, 2050 // volatile or const volatile (9.3.2). 2051 if (SC == FunctionDecl::Static) { 2052 if (!D.isInvalidType()) 2053 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 2054 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2055 << SourceRange(D.getIdentifierLoc()); 2056 SC = FunctionDecl::None; 2057 D.setInvalidType(); 2058 } 2059 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 2060 // Destructors don't have return types, but the parser will 2061 // happily parse something like: 2062 // 2063 // class X { 2064 // float ~X(); 2065 // }; 2066 // 2067 // The return type will be eliminated later. 2068 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 2069 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2070 << SourceRange(D.getIdentifierLoc()); 2071 } 2072 2073 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2074 if (FTI.TypeQuals != 0 && !D.isInvalidType()) { 2075 if (FTI.TypeQuals & QualType::Const) 2076 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2077 << "const" << SourceRange(D.getIdentifierLoc()); 2078 if (FTI.TypeQuals & QualType::Volatile) 2079 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2080 << "volatile" << SourceRange(D.getIdentifierLoc()); 2081 if (FTI.TypeQuals & QualType::Restrict) 2082 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 2083 << "restrict" << SourceRange(D.getIdentifierLoc()); 2084 D.setInvalidType(); 2085 } 2086 2087 // Make sure we don't have any parameters. 2088 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) { 2089 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 2090 2091 // Delete the parameters. 2092 FTI.freeArgs(); 2093 D.setInvalidType(); 2094 } 2095 2096 // Make sure the destructor isn't variadic. 2097 if (FTI.isVariadic) { 2098 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 2099 D.setInvalidType(); 2100 } 2101 2102 // Rebuild the function type "R" without any type qualifiers or 2103 // parameters (in case any of the errors above fired) and with 2104 // "void" as the return type, since destructors don't have return 2105 // types. We *always* have to do this, because GetTypeForDeclarator 2106 // will put in a result type of "int" when none was specified. 2107 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0); 2108} 2109 2110/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 2111/// well-formednes of the conversion function declarator @p D with 2112/// type @p R. If there are any errors in the declarator, this routine 2113/// will emit diagnostics and return true. Otherwise, it will return 2114/// false. Either way, the type @p R will be updated to reflect a 2115/// well-formed type for the conversion operator. 2116void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 2117 FunctionDecl::StorageClass& SC) { 2118 // C++ [class.conv.fct]p1: 2119 // Neither parameter types nor return type can be specified. The 2120 // type of a conversion function (8.3.5) is "function taking no 2121 // parameter returning conversion-type-id." 2122 if (SC == FunctionDecl::Static) { 2123 if (!D.isInvalidType()) 2124 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 2125 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 2126 << SourceRange(D.getIdentifierLoc()); 2127 D.setInvalidType(); 2128 SC = FunctionDecl::None; 2129 } 2130 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) { 2131 // Conversion functions don't have return types, but the parser will 2132 // happily parse something like: 2133 // 2134 // class X { 2135 // float operator bool(); 2136 // }; 2137 // 2138 // The return type will be changed later anyway. 2139 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 2140 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 2141 << SourceRange(D.getIdentifierLoc()); 2142 } 2143 2144 // Make sure we don't have any parameters. 2145 if (R->getAsFunctionProtoType()->getNumArgs() > 0) { 2146 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 2147 2148 // Delete the parameters. 2149 D.getTypeObject(0).Fun.freeArgs(); 2150 D.setInvalidType(); 2151 } 2152 2153 // Make sure the conversion function isn't variadic. 2154 if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) { 2155 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 2156 D.setInvalidType(); 2157 } 2158 2159 // C++ [class.conv.fct]p4: 2160 // The conversion-type-id shall not represent a function type nor 2161 // an array type. 2162 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType()); 2163 if (ConvType->isArrayType()) { 2164 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 2165 ConvType = Context.getPointerType(ConvType); 2166 D.setInvalidType(); 2167 } else if (ConvType->isFunctionType()) { 2168 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 2169 ConvType = Context.getPointerType(ConvType); 2170 D.setInvalidType(); 2171 } 2172 2173 // Rebuild the function type "R" without any parameters (in case any 2174 // of the errors above fired) and with the conversion type as the 2175 // return type. 2176 R = Context.getFunctionType(ConvType, 0, 0, false, 2177 R->getAsFunctionProtoType()->getTypeQuals()); 2178 2179 // C++0x explicit conversion operators. 2180 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x) 2181 Diag(D.getDeclSpec().getExplicitSpecLoc(), 2182 diag::warn_explicit_conversion_functions) 2183 << SourceRange(D.getDeclSpec().getExplicitSpecLoc()); 2184} 2185 2186/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 2187/// the declaration of the given C++ conversion function. This routine 2188/// is responsible for recording the conversion function in the C++ 2189/// class, if possible. 2190Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 2191 assert(Conversion && "Expected to receive a conversion function declaration"); 2192 2193 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 2194 2195 // Make sure we aren't redeclaring the conversion function. 2196 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 2197 2198 // C++ [class.conv.fct]p1: 2199 // [...] A conversion function is never used to convert a 2200 // (possibly cv-qualified) object to the (possibly cv-qualified) 2201 // same object type (or a reference to it), to a (possibly 2202 // cv-qualified) base class of that type (or a reference to it), 2203 // or to (possibly cv-qualified) void. 2204 // FIXME: Suppress this warning if the conversion function ends up being a 2205 // virtual function that overrides a virtual function in a base class. 2206 QualType ClassType 2207 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 2208 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 2209 ConvType = ConvTypeRef->getPointeeType(); 2210 if (ConvType->isRecordType()) { 2211 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 2212 if (ConvType == ClassType) 2213 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 2214 << ClassType; 2215 else if (IsDerivedFrom(ClassType, ConvType)) 2216 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 2217 << ClassType << ConvType; 2218 } else if (ConvType->isVoidType()) { 2219 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 2220 << ClassType << ConvType; 2221 } 2222 2223 if (Conversion->getPreviousDeclaration()) { 2224 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration(); 2225 if (FunctionTemplateDecl *ConversionTemplate 2226 = Conversion->getDescribedFunctionTemplate()) 2227 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration(); 2228 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions(); 2229 for (OverloadedFunctionDecl::function_iterator 2230 Conv = Conversions->function_begin(), 2231 ConvEnd = Conversions->function_end(); 2232 Conv != ConvEnd; ++Conv) { 2233 if (*Conv == ExpectedPrevDecl) { 2234 *Conv = Conversion; 2235 return DeclPtrTy::make(Conversion); 2236 } 2237 } 2238 assert(Conversion->isInvalidDecl() && "Conversion should not get here."); 2239 } else if (FunctionTemplateDecl *ConversionTemplate 2240 = Conversion->getDescribedFunctionTemplate()) 2241 ClassDecl->addConversionFunction(Context, ConversionTemplate); 2242 else if (!Conversion->getPrimaryTemplate()) // ignore specializations 2243 ClassDecl->addConversionFunction(Context, Conversion); 2244 2245 return DeclPtrTy::make(Conversion); 2246} 2247 2248//===----------------------------------------------------------------------===// 2249// Namespace Handling 2250//===----------------------------------------------------------------------===// 2251 2252/// ActOnStartNamespaceDef - This is called at the start of a namespace 2253/// definition. 2254Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 2255 SourceLocation IdentLoc, 2256 IdentifierInfo *II, 2257 SourceLocation LBrace) { 2258 NamespaceDecl *Namespc = 2259 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 2260 Namespc->setLBracLoc(LBrace); 2261 2262 Scope *DeclRegionScope = NamespcScope->getParent(); 2263 2264 if (II) { 2265 // C++ [namespace.def]p2: 2266 // The identifier in an original-namespace-definition shall not have been 2267 // previously defined in the declarative region in which the 2268 // original-namespace-definition appears. The identifier in an 2269 // original-namespace-definition is the name of the namespace. Subsequently 2270 // in that declarative region, it is treated as an original-namespace-name. 2271 2272 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName, 2273 true); 2274 2275 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) { 2276 // This is an extended namespace definition. 2277 // Attach this namespace decl to the chain of extended namespace 2278 // definitions. 2279 OrigNS->setNextNamespace(Namespc); 2280 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace()); 2281 2282 // Remove the previous declaration from the scope. 2283 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) { 2284 IdResolver.RemoveDecl(OrigNS); 2285 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS)); 2286 } 2287 } else if (PrevDecl) { 2288 // This is an invalid name redefinition. 2289 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind) 2290 << Namespc->getDeclName(); 2291 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2292 Namespc->setInvalidDecl(); 2293 // Continue on to push Namespc as current DeclContext and return it. 2294 } 2295 2296 PushOnScopeChains(Namespc, DeclRegionScope); 2297 } else { 2298 // FIXME: Handle anonymous namespaces 2299 } 2300 2301 // Although we could have an invalid decl (i.e. the namespace name is a 2302 // redefinition), push it as current DeclContext and try to continue parsing. 2303 // FIXME: We should be able to push Namespc here, so that the each DeclContext 2304 // for the namespace has the declarations that showed up in that particular 2305 // namespace definition. 2306 PushDeclContext(NamespcScope, Namespc); 2307 return DeclPtrTy::make(Namespc); 2308} 2309 2310/// ActOnFinishNamespaceDef - This callback is called after a namespace is 2311/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 2312void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) { 2313 Decl *Dcl = D.getAs<Decl>(); 2314 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 2315 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 2316 Namespc->setRBracLoc(RBrace); 2317 PopDeclContext(); 2318} 2319 2320Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S, 2321 SourceLocation UsingLoc, 2322 SourceLocation NamespcLoc, 2323 const CXXScopeSpec &SS, 2324 SourceLocation IdentLoc, 2325 IdentifierInfo *NamespcName, 2326 AttributeList *AttrList) { 2327 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 2328 assert(NamespcName && "Invalid NamespcName."); 2329 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 2330 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 2331 2332 UsingDirectiveDecl *UDir = 0; 2333 2334 // Lookup namespace name. 2335 LookupResult R = LookupParsedName(S, &SS, NamespcName, 2336 LookupNamespaceName, false); 2337 if (R.isAmbiguous()) { 2338 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc); 2339 return DeclPtrTy(); 2340 } 2341 if (NamedDecl *NS = R) { 2342 assert(isa<NamespaceDecl>(NS) && "expected namespace decl"); 2343 // C++ [namespace.udir]p1: 2344 // A using-directive specifies that the names in the nominated 2345 // namespace can be used in the scope in which the 2346 // using-directive appears after the using-directive. During 2347 // unqualified name lookup (3.4.1), the names appear as if they 2348 // were declared in the nearest enclosing namespace which 2349 // contains both the using-directive and the nominated 2350 // namespace. [Note: in this context, "contains" means "contains 2351 // directly or indirectly". ] 2352 2353 // Find enclosing context containing both using-directive and 2354 // nominated namespace. 2355 DeclContext *CommonAncestor = cast<DeclContext>(NS); 2356 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 2357 CommonAncestor = CommonAncestor->getParent(); 2358 2359 UDir = UsingDirectiveDecl::Create(Context, 2360 CurContext, UsingLoc, 2361 NamespcLoc, 2362 SS.getRange(), 2363 (NestedNameSpecifier *)SS.getScopeRep(), 2364 IdentLoc, 2365 cast<NamespaceDecl>(NS), 2366 CommonAncestor); 2367 PushUsingDirective(S, UDir); 2368 } else { 2369 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 2370 } 2371 2372 // FIXME: We ignore attributes for now. 2373 delete AttrList; 2374 return DeclPtrTy::make(UDir); 2375} 2376 2377void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 2378 // If scope has associated entity, then using directive is at namespace 2379 // or translation unit scope. We add UsingDirectiveDecls, into 2380 // it's lookup structure. 2381 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) 2382 Ctx->addDecl(UDir); 2383 else 2384 // Otherwise it is block-sope. using-directives will affect lookup 2385 // only to the end of scope. 2386 S->PushUsingDirective(DeclPtrTy::make(UDir)); 2387} 2388 2389 2390Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S, 2391 AccessSpecifier AS, 2392 SourceLocation UsingLoc, 2393 const CXXScopeSpec &SS, 2394 SourceLocation IdentLoc, 2395 IdentifierInfo *TargetName, 2396 OverloadedOperatorKind Op, 2397 AttributeList *AttrList, 2398 bool IsTypeName) { 2399 assert((TargetName || Op) && "Invalid TargetName."); 2400 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 2401 2402 DeclarationName Name; 2403 if (TargetName) 2404 Name = TargetName; 2405 else 2406 Name = Context.DeclarationNames.getCXXOperatorName(Op); 2407 2408 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS, IdentLoc, 2409 Name, AttrList, IsTypeName); 2410 if (UD) { 2411 PushOnScopeChains(UD, S); 2412 UD->setAccess(AS); 2413 } 2414 2415 return DeclPtrTy::make(UD); 2416} 2417 2418NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc, 2419 const CXXScopeSpec &SS, 2420 SourceLocation IdentLoc, 2421 DeclarationName Name, 2422 AttributeList *AttrList, 2423 bool IsTypeName) { 2424 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 2425 assert(IdentLoc.isValid() && "Invalid TargetName location."); 2426 2427 // FIXME: We ignore attributes for now. 2428 delete AttrList; 2429 2430 if (SS.isEmpty()) { 2431 Diag(IdentLoc, diag::err_using_requires_qualname); 2432 return 0; 2433 } 2434 2435 NestedNameSpecifier *NNS = 2436 static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 2437 2438 if (isUnknownSpecialization(SS)) { 2439 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc, 2440 SS.getRange(), NNS, 2441 IdentLoc, Name, IsTypeName); 2442 } 2443 2444 DeclContext *LookupContext = 0; 2445 2446 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) { 2447 // C++0x N2914 [namespace.udecl]p3: 2448 // A using-declaration used as a member-declaration shall refer to a member 2449 // of a base class of the class being defined, shall refer to a member of an 2450 // anonymous union that is a member of a base class of the class being 2451 // defined, or shall refer to an enumerator for an enumeration type that is 2452 // a member of a base class of the class being defined. 2453 const Type *Ty = NNS->getAsType(); 2454 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) { 2455 Diag(SS.getRange().getBegin(), 2456 diag::err_using_decl_nested_name_specifier_is_not_a_base_class) 2457 << NNS << RD->getDeclName(); 2458 return 0; 2459 } 2460 2461 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0)); 2462 LookupContext = BaseTy->getAs<RecordType>()->getDecl(); 2463 } else { 2464 // C++0x N2914 [namespace.udecl]p8: 2465 // A using-declaration for a class member shall be a member-declaration. 2466 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) { 2467 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member) 2468 << SS.getRange(); 2469 return 0; 2470 } 2471 2472 // C++0x N2914 [namespace.udecl]p9: 2473 // In a using-declaration, a prefix :: refers to the global namespace. 2474 if (NNS->getKind() == NestedNameSpecifier::Global) 2475 LookupContext = Context.getTranslationUnitDecl(); 2476 else 2477 LookupContext = NNS->getAsNamespace(); 2478 } 2479 2480 2481 // Lookup target name. 2482 LookupResult R = LookupQualifiedName(LookupContext, 2483 Name, LookupOrdinaryName); 2484 2485 if (!R) { 2486 DiagnoseMissingMember(IdentLoc, Name, NNS, SS.getRange()); 2487 return 0; 2488 } 2489 2490 NamedDecl *ND = R.getAsDecl(); 2491 2492 if (IsTypeName && !isa<TypeDecl>(ND)) { 2493 Diag(IdentLoc, diag::err_using_typename_non_type); 2494 return 0; 2495 } 2496 2497 // C++0x N2914 [namespace.udecl]p6: 2498 // A using-declaration shall not name a namespace. 2499 if (isa<NamespaceDecl>(ND)) { 2500 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 2501 << SS.getRange(); 2502 return 0; 2503 } 2504 2505 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(), 2506 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName); 2507} 2508 2509/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 2510/// is a namespace alias, returns the namespace it points to. 2511static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 2512 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 2513 return AD->getNamespace(); 2514 return dyn_cast_or_null<NamespaceDecl>(D); 2515} 2516 2517Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S, 2518 SourceLocation NamespaceLoc, 2519 SourceLocation AliasLoc, 2520 IdentifierInfo *Alias, 2521 const CXXScopeSpec &SS, 2522 SourceLocation IdentLoc, 2523 IdentifierInfo *Ident) { 2524 2525 // Lookup the namespace name. 2526 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false); 2527 2528 // Check if we have a previous declaration with the same name. 2529 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) { 2530 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 2531 // We already have an alias with the same name that points to the same 2532 // namespace, so don't create a new one. 2533 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R)) 2534 return DeclPtrTy(); 2535 } 2536 2537 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition : 2538 diag::err_redefinition_different_kind; 2539 Diag(AliasLoc, DiagID) << Alias; 2540 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2541 return DeclPtrTy(); 2542 } 2543 2544 if (R.isAmbiguous()) { 2545 DiagnoseAmbiguousLookup(R, Ident, IdentLoc); 2546 return DeclPtrTy(); 2547 } 2548 2549 if (!R) { 2550 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange(); 2551 return DeclPtrTy(); 2552 } 2553 2554 NamespaceAliasDecl *AliasDecl = 2555 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 2556 Alias, SS.getRange(), 2557 (NestedNameSpecifier *)SS.getScopeRep(), 2558 IdentLoc, R); 2559 2560 CurContext->addDecl(AliasDecl); 2561 return DeclPtrTy::make(AliasDecl); 2562} 2563 2564void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 2565 CXXConstructorDecl *Constructor) { 2566 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() && 2567 !Constructor->isUsed()) && 2568 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 2569 2570 CXXRecordDecl *ClassDecl 2571 = cast<CXXRecordDecl>(Constructor->getDeclContext()); 2572 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 2573 // Before the implicitly-declared default constructor for a class is 2574 // implicitly defined, all the implicitly-declared default constructors 2575 // for its base class and its non-static data members shall have been 2576 // implicitly defined. 2577 bool err = false; 2578 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2579 E = ClassDecl->bases_end(); Base != E; ++Base) { 2580 CXXRecordDecl *BaseClassDecl 2581 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2582 if (!BaseClassDecl->hasTrivialConstructor()) { 2583 if (CXXConstructorDecl *BaseCtor = 2584 BaseClassDecl->getDefaultConstructor(Context)) 2585 MarkDeclarationReferenced(CurrentLocation, BaseCtor); 2586 else { 2587 Diag(CurrentLocation, diag::err_defining_default_ctor) 2588 << Context.getTagDeclType(ClassDecl) << 1 2589 << Context.getTagDeclType(BaseClassDecl); 2590 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl) 2591 << Context.getTagDeclType(BaseClassDecl); 2592 err = true; 2593 } 2594 } 2595 } 2596 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2597 E = ClassDecl->field_end(); Field != E; ++Field) { 2598 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2599 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2600 FieldType = Array->getElementType(); 2601 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2602 CXXRecordDecl *FieldClassDecl 2603 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2604 if (!FieldClassDecl->hasTrivialConstructor()) { 2605 if (CXXConstructorDecl *FieldCtor = 2606 FieldClassDecl->getDefaultConstructor(Context)) 2607 MarkDeclarationReferenced(CurrentLocation, FieldCtor); 2608 else { 2609 Diag(CurrentLocation, diag::err_defining_default_ctor) 2610 << Context.getTagDeclType(ClassDecl) << 0 << 2611 Context.getTagDeclType(FieldClassDecl); 2612 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl) 2613 << Context.getTagDeclType(FieldClassDecl); 2614 err = true; 2615 } 2616 } 2617 } else if (FieldType->isReferenceType()) { 2618 Diag(CurrentLocation, diag::err_unintialized_member) 2619 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 2620 Diag((*Field)->getLocation(), diag::note_declared_at); 2621 err = true; 2622 } else if (FieldType.isConstQualified()) { 2623 Diag(CurrentLocation, diag::err_unintialized_member) 2624 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 2625 Diag((*Field)->getLocation(), diag::note_declared_at); 2626 err = true; 2627 } 2628 } 2629 if (!err) 2630 Constructor->setUsed(); 2631 else 2632 Constructor->setInvalidDecl(); 2633} 2634 2635void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 2636 CXXDestructorDecl *Destructor) { 2637 assert((Destructor->isImplicit() && !Destructor->isUsed()) && 2638 "DefineImplicitDestructor - call it for implicit default dtor"); 2639 2640 CXXRecordDecl *ClassDecl 2641 = cast<CXXRecordDecl>(Destructor->getDeclContext()); 2642 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 2643 // C++ [class.dtor] p5 2644 // Before the implicitly-declared default destructor for a class is 2645 // implicitly defined, all the implicitly-declared default destructors 2646 // for its base class and its non-static data members shall have been 2647 // implicitly defined. 2648 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2649 E = ClassDecl->bases_end(); Base != E; ++Base) { 2650 CXXRecordDecl *BaseClassDecl 2651 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2652 if (!BaseClassDecl->hasTrivialDestructor()) { 2653 if (CXXDestructorDecl *BaseDtor = 2654 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context))) 2655 MarkDeclarationReferenced(CurrentLocation, BaseDtor); 2656 else 2657 assert(false && 2658 "DefineImplicitDestructor - missing dtor in a base class"); 2659 } 2660 } 2661 2662 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2663 E = ClassDecl->field_end(); Field != E; ++Field) { 2664 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2665 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2666 FieldType = Array->getElementType(); 2667 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2668 CXXRecordDecl *FieldClassDecl 2669 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2670 if (!FieldClassDecl->hasTrivialDestructor()) { 2671 if (CXXDestructorDecl *FieldDtor = 2672 const_cast<CXXDestructorDecl*>( 2673 FieldClassDecl->getDestructor(Context))) 2674 MarkDeclarationReferenced(CurrentLocation, FieldDtor); 2675 else 2676 assert(false && 2677 "DefineImplicitDestructor - missing dtor in class of a data member"); 2678 } 2679 } 2680 } 2681 Destructor->setUsed(); 2682} 2683 2684void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation, 2685 CXXMethodDecl *MethodDecl) { 2686 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() && 2687 MethodDecl->getOverloadedOperator() == OO_Equal && 2688 !MethodDecl->isUsed()) && 2689 "DefineImplicitOverloadedAssign - call it for implicit assignment op"); 2690 2691 CXXRecordDecl *ClassDecl 2692 = cast<CXXRecordDecl>(MethodDecl->getDeclContext()); 2693 2694 // C++[class.copy] p12 2695 // Before the implicitly-declared copy assignment operator for a class is 2696 // implicitly defined, all implicitly-declared copy assignment operators 2697 // for its direct base classes and its nonstatic data members shall have 2698 // been implicitly defined. 2699 bool err = false; 2700 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 2701 E = ClassDecl->bases_end(); Base != E; ++Base) { 2702 CXXRecordDecl *BaseClassDecl 2703 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2704 if (CXXMethodDecl *BaseAssignOpMethod = 2705 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl)) 2706 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod); 2707 } 2708 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2709 E = ClassDecl->field_end(); Field != E; ++Field) { 2710 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2711 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2712 FieldType = Array->getElementType(); 2713 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2714 CXXRecordDecl *FieldClassDecl 2715 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2716 if (CXXMethodDecl *FieldAssignOpMethod = 2717 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl)) 2718 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod); 2719 } else if (FieldType->isReferenceType()) { 2720 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 2721 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 2722 Diag(Field->getLocation(), diag::note_declared_at); 2723 Diag(CurrentLocation, diag::note_first_required_here); 2724 err = true; 2725 } else if (FieldType.isConstQualified()) { 2726 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 2727 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 2728 Diag(Field->getLocation(), diag::note_declared_at); 2729 Diag(CurrentLocation, diag::note_first_required_here); 2730 err = true; 2731 } 2732 } 2733 if (!err) 2734 MethodDecl->setUsed(); 2735} 2736 2737CXXMethodDecl * 2738Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl, 2739 CXXRecordDecl *ClassDecl) { 2740 QualType LHSType = Context.getTypeDeclType(ClassDecl); 2741 QualType RHSType(LHSType); 2742 // If class's assignment operator argument is const/volatile qualified, 2743 // look for operator = (const/volatile B&). Otherwise, look for 2744 // operator = (B&). 2745 if (ParmDecl->getType().isConstQualified()) 2746 RHSType.addConst(); 2747 if (ParmDecl->getType().isVolatileQualified()) 2748 RHSType.addVolatile(); 2749 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl, 2750 LHSType, 2751 SourceLocation())); 2752 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl, 2753 RHSType, 2754 SourceLocation())); 2755 Expr *Args[2] = { &*LHS, &*RHS }; 2756 OverloadCandidateSet CandidateSet; 2757 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2, 2758 CandidateSet); 2759 OverloadCandidateSet::iterator Best; 2760 if (BestViableFunction(CandidateSet, 2761 ClassDecl->getLocation(), Best) == OR_Success) 2762 return cast<CXXMethodDecl>(Best->Function); 2763 assert(false && 2764 "getAssignOperatorMethod - copy assignment operator method not found"); 2765 return 0; 2766} 2767 2768void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 2769 CXXConstructorDecl *CopyConstructor, 2770 unsigned TypeQuals) { 2771 assert((CopyConstructor->isImplicit() && 2772 CopyConstructor->isCopyConstructor(Context, TypeQuals) && 2773 !CopyConstructor->isUsed()) && 2774 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 2775 2776 CXXRecordDecl *ClassDecl 2777 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext()); 2778 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 2779 // C++ [class.copy] p209 2780 // Before the implicitly-declared copy constructor for a class is 2781 // implicitly defined, all the implicitly-declared copy constructors 2782 // for its base class and its non-static data members shall have been 2783 // implicitly defined. 2784 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2785 Base != ClassDecl->bases_end(); ++Base) { 2786 CXXRecordDecl *BaseClassDecl 2787 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 2788 if (CXXConstructorDecl *BaseCopyCtor = 2789 BaseClassDecl->getCopyConstructor(Context, TypeQuals)) 2790 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor); 2791 } 2792 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 2793 FieldEnd = ClassDecl->field_end(); 2794 Field != FieldEnd; ++Field) { 2795 QualType FieldType = Context.getCanonicalType((*Field)->getType()); 2796 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 2797 FieldType = Array->getElementType(); 2798 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 2799 CXXRecordDecl *FieldClassDecl 2800 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 2801 if (CXXConstructorDecl *FieldCopyCtor = 2802 FieldClassDecl->getCopyConstructor(Context, TypeQuals)) 2803 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor); 2804 } 2805 } 2806 CopyConstructor->setUsed(); 2807} 2808 2809Sema::OwningExprResult 2810Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 2811 CXXConstructorDecl *Constructor, 2812 MultiExprArg ExprArgs) { 2813 bool Elidable = false; 2814 2815 // [class.copy]p15: 2816 // Whenever a temporary class object is copied using a copy constructor, and 2817 // this object and the copy have the same cv-unqualified type, an 2818 // implementation is permitted to treat the original and the copy as two 2819 // different ways of referring to the same object and not perform a copy at 2820 //all, even if the class copy constructor or destructor have side effects. 2821 2822 // FIXME: Is this enough? 2823 if (Constructor->isCopyConstructor(Context) && ExprArgs.size() == 1) { 2824 Expr *E = ((Expr **)ExprArgs.get())[0]; 2825 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E)) 2826 E = BE->getSubExpr(); 2827 2828 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E)) 2829 Elidable = true; 2830 } 2831 2832 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor, 2833 Elidable, move(ExprArgs)); 2834} 2835 2836static bool 2837CheckConstructArgumentTypes(Sema &SemaRef, SourceLocation ConstructLoc, 2838 CXXConstructExpr *E) { 2839 CXXConstructorDecl *Ctor = E->getConstructor(); 2840 const FunctionProtoType *Proto = Ctor->getType()->getAsFunctionProtoType(); 2841 2842 unsigned NumArgs = E->getNumArgs(); 2843 unsigned NumArgsInProto = Proto->getNumArgs(); 2844 unsigned NumRequiredArgs = Ctor->getMinRequiredArguments(); 2845 2846 for (unsigned i = 0; i != NumArgsInProto; ++i) { 2847 QualType ProtoArgType = Proto->getArgType(i); 2848 2849 Expr *Arg; 2850 2851 if (i < NumRequiredArgs) { 2852 Arg = E->getArg(i); 2853 2854 // Pass the argument. 2855 // FIXME: Do this. 2856 } else { 2857 // Build a default argument. 2858 ParmVarDecl *Param = Ctor->getParamDecl(i); 2859 2860 Sema::OwningExprResult ArgExpr = 2861 SemaRef.BuildCXXDefaultArgExpr(ConstructLoc, Ctor, Param); 2862 if (ArgExpr.isInvalid()) 2863 return true; 2864 2865 Arg = ArgExpr.takeAs<Expr>(); 2866 } 2867 2868 E->setArg(i, Arg); 2869 } 2870 2871 // If this is a variadic call, handle args passed through "...". 2872 if (Proto->isVariadic()) { 2873 bool Invalid = false; 2874 2875 // Promote the arguments (C99 6.5.2.2p7). 2876 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 2877 Expr *Arg = E->getArg(i); 2878 Invalid |= 2879 SemaRef.DefaultVariadicArgumentPromotion(Arg, 2880 Sema::VariadicConstructor); 2881 E->setArg(i, Arg); 2882 } 2883 2884 return Invalid; 2885 } 2886 2887 return false; 2888} 2889 2890/// BuildCXXConstructExpr - Creates a complete call to a constructor, 2891/// including handling of its default argument expressions. 2892Sema::OwningExprResult 2893Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 2894 CXXConstructorDecl *Constructor, bool Elidable, 2895 MultiExprArg ExprArgs) { 2896 unsigned NumExprs = ExprArgs.size(); 2897 Expr **Exprs = (Expr **)ExprArgs.release(); 2898 2899 ExprOwningPtr<CXXConstructExpr> Temp(this, 2900 CXXConstructExpr::Create(Context, 2901 DeclInitType, 2902 Constructor, 2903 Elidable, 2904 Exprs, 2905 NumExprs)); 2906 2907 if (CheckConstructArgumentTypes(*this, ConstructLoc, Temp.get())) 2908 return ExprError(); 2909 2910 return move(Temp); 2911} 2912 2913Sema::OwningExprResult 2914Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor, 2915 QualType Ty, 2916 SourceLocation TyBeginLoc, 2917 MultiExprArg Args, 2918 SourceLocation RParenLoc) { 2919 CXXTemporaryObjectExpr *E 2920 = new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty, TyBeginLoc, 2921 (Expr **)Args.get(), 2922 Args.size(), RParenLoc); 2923 2924 ExprOwningPtr<CXXTemporaryObjectExpr> Temp(this, E); 2925 2926 if (CheckConstructArgumentTypes(*this, TyBeginLoc, Temp.get())) 2927 return ExprError(); 2928 2929 return move(Temp); 2930} 2931 2932 2933bool Sema::InitializeVarWithConstructor(VarDecl *VD, 2934 CXXConstructorDecl *Constructor, 2935 QualType DeclInitType, 2936 MultiExprArg Exprs) { 2937 OwningExprResult TempResult = 2938 BuildCXXConstructExpr(VD->getLocation(), DeclInitType, Constructor, 2939 move(Exprs)); 2940 if (TempResult.isInvalid()) 2941 return true; 2942 2943 Expr *Temp = TempResult.takeAs<Expr>(); 2944 MarkDeclarationReferenced(VD->getLocation(), Constructor); 2945 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true); 2946 VD->setInit(Context, Temp); 2947 2948 return false; 2949} 2950 2951void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType) { 2952 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>( 2953 DeclInitType->getAs<RecordType>()->getDecl()); 2954 if (!ClassDecl->hasTrivialDestructor()) 2955 if (CXXDestructorDecl *Destructor = 2956 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context))) 2957 MarkDeclarationReferenced(VD->getLocation(), Destructor); 2958} 2959 2960/// AddCXXDirectInitializerToDecl - This action is called immediately after 2961/// ActOnDeclarator, when a C++ direct initializer is present. 2962/// e.g: "int x(1);" 2963void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl, 2964 SourceLocation LParenLoc, 2965 MultiExprArg Exprs, 2966 SourceLocation *CommaLocs, 2967 SourceLocation RParenLoc) { 2968 unsigned NumExprs = Exprs.size(); 2969 assert(NumExprs != 0 && Exprs.get() && "missing expressions"); 2970 Decl *RealDecl = Dcl.getAs<Decl>(); 2971 2972 // If there is no declaration, there was an error parsing it. Just ignore 2973 // the initializer. 2974 if (RealDecl == 0) 2975 return; 2976 2977 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 2978 if (!VDecl) { 2979 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 2980 RealDecl->setInvalidDecl(); 2981 return; 2982 } 2983 2984 // We will represent direct-initialization similarly to copy-initialization: 2985 // int x(1); -as-> int x = 1; 2986 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 2987 // 2988 // Clients that want to distinguish between the two forms, can check for 2989 // direct initializer using VarDecl::hasCXXDirectInitializer(). 2990 // A major benefit is that clients that don't particularly care about which 2991 // exactly form was it (like the CodeGen) can handle both cases without 2992 // special case code. 2993 2994 // If either the declaration has a dependent type or if any of the expressions 2995 // is type-dependent, we represent the initialization via a ParenListExpr for 2996 // later use during template instantiation. 2997 if (VDecl->getType()->isDependentType() || 2998 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) { 2999 // Let clients know that initialization was done with a direct initializer. 3000 VDecl->setCXXDirectInitializer(true); 3001 3002 // Store the initialization expressions as a ParenListExpr. 3003 unsigned NumExprs = Exprs.size(); 3004 VDecl->setInit(Context, 3005 new (Context) ParenListExpr(Context, LParenLoc, 3006 (Expr **)Exprs.release(), 3007 NumExprs, RParenLoc)); 3008 return; 3009 } 3010 3011 3012 // C++ 8.5p11: 3013 // The form of initialization (using parentheses or '=') is generally 3014 // insignificant, but does matter when the entity being initialized has a 3015 // class type. 3016 QualType DeclInitType = VDecl->getType(); 3017 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 3018 DeclInitType = Array->getElementType(); 3019 3020 // FIXME: This isn't the right place to complete the type. 3021 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(), 3022 diag::err_typecheck_decl_incomplete_type)) { 3023 VDecl->setInvalidDecl(); 3024 return; 3025 } 3026 3027 if (VDecl->getType()->isRecordType()) { 3028 CXXConstructorDecl *Constructor 3029 = PerformInitializationByConstructor(DeclInitType, 3030 (Expr **)Exprs.get(), NumExprs, 3031 VDecl->getLocation(), 3032 SourceRange(VDecl->getLocation(), 3033 RParenLoc), 3034 VDecl->getDeclName(), 3035 IK_Direct); 3036 if (!Constructor) 3037 RealDecl->setInvalidDecl(); 3038 else { 3039 VDecl->setCXXDirectInitializer(true); 3040 if (InitializeVarWithConstructor(VDecl, Constructor, DeclInitType, 3041 move(Exprs))) 3042 RealDecl->setInvalidDecl(); 3043 FinalizeVarWithDestructor(VDecl, DeclInitType); 3044 } 3045 return; 3046 } 3047 3048 if (NumExprs > 1) { 3049 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg) 3050 << SourceRange(VDecl->getLocation(), RParenLoc); 3051 RealDecl->setInvalidDecl(); 3052 return; 3053 } 3054 3055 // Let clients know that initialization was done with a direct initializer. 3056 VDecl->setCXXDirectInitializer(true); 3057 3058 assert(NumExprs == 1 && "Expected 1 expression"); 3059 // Set the init expression, handles conversions. 3060 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]), 3061 /*DirectInit=*/true); 3062} 3063 3064/// PerformInitializationByConstructor - Perform initialization by 3065/// constructor (C++ [dcl.init]p14), which may occur as part of 3066/// direct-initialization or copy-initialization. We are initializing 3067/// an object of type @p ClassType with the given arguments @p 3068/// Args. @p Loc is the location in the source code where the 3069/// initializer occurs (e.g., a declaration, member initializer, 3070/// functional cast, etc.) while @p Range covers the whole 3071/// initialization. @p InitEntity is the entity being initialized, 3072/// which may by the name of a declaration or a type. @p Kind is the 3073/// kind of initialization we're performing, which affects whether 3074/// explicit constructors will be considered. When successful, returns 3075/// the constructor that will be used to perform the initialization; 3076/// when the initialization fails, emits a diagnostic and returns 3077/// null. 3078CXXConstructorDecl * 3079Sema::PerformInitializationByConstructor(QualType ClassType, 3080 Expr **Args, unsigned NumArgs, 3081 SourceLocation Loc, SourceRange Range, 3082 DeclarationName InitEntity, 3083 InitializationKind Kind) { 3084 const RecordType *ClassRec = ClassType->getAs<RecordType>(); 3085 assert(ClassRec && "Can only initialize a class type here"); 3086 3087 // C++ [dcl.init]p14: 3088 // 3089 // If the initialization is direct-initialization, or if it is 3090 // copy-initialization where the cv-unqualified version of the 3091 // source type is the same class as, or a derived class of, the 3092 // class of the destination, constructors are considered. The 3093 // applicable constructors are enumerated (13.3.1.3), and the 3094 // best one is chosen through overload resolution (13.3). The 3095 // constructor so selected is called to initialize the object, 3096 // with the initializer expression(s) as its argument(s). If no 3097 // constructor applies, or the overload resolution is ambiguous, 3098 // the initialization is ill-formed. 3099 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 3100 OverloadCandidateSet CandidateSet; 3101 3102 // Add constructors to the overload set. 3103 DeclarationName ConstructorName 3104 = Context.DeclarationNames.getCXXConstructorName( 3105 Context.getCanonicalType(ClassType.getUnqualifiedType())); 3106 DeclContext::lookup_const_iterator Con, ConEnd; 3107 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName); 3108 Con != ConEnd; ++Con) { 3109 // Find the constructor (which may be a template). 3110 CXXConstructorDecl *Constructor = 0; 3111 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con); 3112 if (ConstructorTmpl) 3113 Constructor 3114 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3115 else 3116 Constructor = cast<CXXConstructorDecl>(*Con); 3117 3118 if ((Kind == IK_Direct) || 3119 (Kind == IK_Copy && 3120 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) || 3121 (Kind == IK_Default && Constructor->isDefaultConstructor())) { 3122 if (ConstructorTmpl) 3123 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, 3124 Args, NumArgs, CandidateSet); 3125 else 3126 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet); 3127 } 3128 } 3129 3130 // FIXME: When we decide not to synthesize the implicitly-declared 3131 // constructors, we'll need to make them appear here. 3132 3133 OverloadCandidateSet::iterator Best; 3134 switch (BestViableFunction(CandidateSet, Loc, Best)) { 3135 case OR_Success: 3136 // We found a constructor. Return it. 3137 return cast<CXXConstructorDecl>(Best->Function); 3138 3139 case OR_No_Viable_Function: 3140 if (InitEntity) 3141 Diag(Loc, diag::err_ovl_no_viable_function_in_init) 3142 << InitEntity << Range; 3143 else 3144 Diag(Loc, diag::err_ovl_no_viable_function_in_init) 3145 << ClassType << Range; 3146 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3147 return 0; 3148 3149 case OR_Ambiguous: 3150 if (InitEntity) 3151 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range; 3152 else 3153 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range; 3154 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3155 return 0; 3156 3157 case OR_Deleted: 3158 if (InitEntity) 3159 Diag(Loc, diag::err_ovl_deleted_init) 3160 << Best->Function->isDeleted() 3161 << InitEntity << Range; 3162 else 3163 Diag(Loc, diag::err_ovl_deleted_init) 3164 << Best->Function->isDeleted() 3165 << InitEntity << Range; 3166 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3167 return 0; 3168 } 3169 3170 return 0; 3171} 3172 3173/// CompareReferenceRelationship - Compare the two types T1 and T2 to 3174/// determine whether they are reference-related, 3175/// reference-compatible, reference-compatible with added 3176/// qualification, or incompatible, for use in C++ initialization by 3177/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3178/// type, and the first type (T1) is the pointee type of the reference 3179/// type being initialized. 3180Sema::ReferenceCompareResult 3181Sema::CompareReferenceRelationship(QualType T1, QualType T2, 3182 bool& DerivedToBase) { 3183 assert(!T1->isReferenceType() && 3184 "T1 must be the pointee type of the reference type"); 3185 assert(!T2->isReferenceType() && "T2 cannot be a reference type"); 3186 3187 T1 = Context.getCanonicalType(T1); 3188 T2 = Context.getCanonicalType(T2); 3189 QualType UnqualT1 = T1.getUnqualifiedType(); 3190 QualType UnqualT2 = T2.getUnqualifiedType(); 3191 3192 // C++ [dcl.init.ref]p4: 3193 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3194 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3195 // T1 is a base class of T2. 3196 if (UnqualT1 == UnqualT2) 3197 DerivedToBase = false; 3198 else if (IsDerivedFrom(UnqualT2, UnqualT1)) 3199 DerivedToBase = true; 3200 else 3201 return Ref_Incompatible; 3202 3203 // At this point, we know that T1 and T2 are reference-related (at 3204 // least). 3205 3206 // C++ [dcl.init.ref]p4: 3207 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3208 // reference-related to T2 and cv1 is the same cv-qualification 3209 // as, or greater cv-qualification than, cv2. For purposes of 3210 // overload resolution, cases for which cv1 is greater 3211 // cv-qualification than cv2 are identified as 3212 // reference-compatible with added qualification (see 13.3.3.2). 3213 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3214 return Ref_Compatible; 3215 else if (T1.isMoreQualifiedThan(T2)) 3216 return Ref_Compatible_With_Added_Qualification; 3217 else 3218 return Ref_Related; 3219} 3220 3221/// CheckReferenceInit - Check the initialization of a reference 3222/// variable with the given initializer (C++ [dcl.init.ref]). Init is 3223/// the initializer (either a simple initializer or an initializer 3224/// list), and DeclType is the type of the declaration. When ICS is 3225/// non-null, this routine will compute the implicit conversion 3226/// sequence according to C++ [over.ics.ref] and will not produce any 3227/// diagnostics; when ICS is null, it will emit diagnostics when any 3228/// errors are found. Either way, a return value of true indicates 3229/// that there was a failure, a return value of false indicates that 3230/// the reference initialization succeeded. 3231/// 3232/// When @p SuppressUserConversions, user-defined conversions are 3233/// suppressed. 3234/// When @p AllowExplicit, we also permit explicit user-defined 3235/// conversion functions. 3236/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue. 3237bool 3238Sema::CheckReferenceInit(Expr *&Init, QualType DeclType, 3239 bool SuppressUserConversions, 3240 bool AllowExplicit, bool ForceRValue, 3241 ImplicitConversionSequence *ICS) { 3242 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 3243 3244 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 3245 QualType T2 = Init->getType(); 3246 3247 // If the initializer is the address of an overloaded function, try 3248 // to resolve the overloaded function. If all goes well, T2 is the 3249 // type of the resulting function. 3250 if (Context.getCanonicalType(T2) == Context.OverloadTy) { 3251 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType, 3252 ICS != 0); 3253 if (Fn) { 3254 // Since we're performing this reference-initialization for 3255 // real, update the initializer with the resulting function. 3256 if (!ICS) { 3257 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin())) 3258 return true; 3259 3260 FixOverloadedFunctionReference(Init, Fn); 3261 } 3262 3263 T2 = Fn->getType(); 3264 } 3265 } 3266 3267 // Compute some basic properties of the types and the initializer. 3268 bool isRValRef = DeclType->isRValueReferenceType(); 3269 bool DerivedToBase = false; 3270 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression : 3271 Init->isLvalue(Context); 3272 ReferenceCompareResult RefRelationship 3273 = CompareReferenceRelationship(T1, T2, DerivedToBase); 3274 3275 // Most paths end in a failed conversion. 3276 if (ICS) 3277 ICS->ConversionKind = ImplicitConversionSequence::BadConversion; 3278 3279 // C++ [dcl.init.ref]p5: 3280 // A reference to type "cv1 T1" is initialized by an expression 3281 // of type "cv2 T2" as follows: 3282 3283 // -- If the initializer expression 3284 3285 // Rvalue references cannot bind to lvalues (N2812). 3286 // There is absolutely no situation where they can. In particular, note that 3287 // this is ill-formed, even if B has a user-defined conversion to A&&: 3288 // B b; 3289 // A&& r = b; 3290 if (isRValRef && InitLvalue == Expr::LV_Valid) { 3291 if (!ICS) 3292 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref) 3293 << Init->getSourceRange(); 3294 return true; 3295 } 3296 3297 bool BindsDirectly = false; 3298 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 3299 // reference-compatible with "cv2 T2," or 3300 // 3301 // Note that the bit-field check is skipped if we are just computing 3302 // the implicit conversion sequence (C++ [over.best.ics]p2). 3303 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) && 3304 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 3305 BindsDirectly = true; 3306 3307 if (ICS) { 3308 // C++ [over.ics.ref]p1: 3309 // When a parameter of reference type binds directly (8.5.3) 3310 // to an argument expression, the implicit conversion sequence 3311 // is the identity conversion, unless the argument expression 3312 // has a type that is a derived class of the parameter type, 3313 // in which case the implicit conversion sequence is a 3314 // derived-to-base Conversion (13.3.3.1). 3315 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 3316 ICS->Standard.First = ICK_Identity; 3317 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 3318 ICS->Standard.Third = ICK_Identity; 3319 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 3320 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 3321 ICS->Standard.ReferenceBinding = true; 3322 ICS->Standard.DirectBinding = true; 3323 ICS->Standard.RRefBinding = false; 3324 ICS->Standard.CopyConstructor = 0; 3325 3326 // Nothing more to do: the inaccessibility/ambiguity check for 3327 // derived-to-base conversions is suppressed when we're 3328 // computing the implicit conversion sequence (C++ 3329 // [over.best.ics]p2). 3330 return false; 3331 } else { 3332 // Perform the conversion. 3333 // FIXME: Binding to a subobject of the lvalue is going to require more 3334 // AST annotation than this. 3335 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true); 3336 } 3337 } 3338 3339 // -- has a class type (i.e., T2 is a class type) and can be 3340 // implicitly converted to an lvalue of type "cv3 T3," 3341 // where "cv1 T1" is reference-compatible with "cv3 T3" 3342 // 92) (this conversion is selected by enumerating the 3343 // applicable conversion functions (13.3.1.6) and choosing 3344 // the best one through overload resolution (13.3)), 3345 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() && 3346 !RequireCompleteType(SourceLocation(), T2, 0)) { 3347 // FIXME: Look for conversions in base classes! 3348 CXXRecordDecl *T2RecordDecl 3349 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 3350 3351 OverloadCandidateSet CandidateSet; 3352 OverloadedFunctionDecl *Conversions 3353 = T2RecordDecl->getConversionFunctions(); 3354 for (OverloadedFunctionDecl::function_iterator Func 3355 = Conversions->function_begin(); 3356 Func != Conversions->function_end(); ++Func) { 3357 FunctionTemplateDecl *ConvTemplate 3358 = dyn_cast<FunctionTemplateDecl>(*Func); 3359 CXXConversionDecl *Conv; 3360 if (ConvTemplate) 3361 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3362 else 3363 Conv = cast<CXXConversionDecl>(*Func); 3364 3365 // If the conversion function doesn't return a reference type, 3366 // it can't be considered for this conversion. 3367 if (Conv->getConversionType()->isLValueReferenceType() && 3368 (AllowExplicit || !Conv->isExplicit())) { 3369 if (ConvTemplate) 3370 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType, 3371 CandidateSet); 3372 else 3373 AddConversionCandidate(Conv, Init, DeclType, CandidateSet); 3374 } 3375 } 3376 3377 OverloadCandidateSet::iterator Best; 3378 switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) { 3379 case OR_Success: 3380 // This is a direct binding. 3381 BindsDirectly = true; 3382 3383 if (ICS) { 3384 // C++ [over.ics.ref]p1: 3385 // 3386 // [...] If the parameter binds directly to the result of 3387 // applying a conversion function to the argument 3388 // expression, the implicit conversion sequence is a 3389 // user-defined conversion sequence (13.3.3.1.2), with the 3390 // second standard conversion sequence either an identity 3391 // conversion or, if the conversion function returns an 3392 // entity of a type that is a derived class of the parameter 3393 // type, a derived-to-base Conversion. 3394 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion; 3395 ICS->UserDefined.Before = Best->Conversions[0].Standard; 3396 ICS->UserDefined.After = Best->FinalConversion; 3397 ICS->UserDefined.ConversionFunction = Best->Function; 3398 assert(ICS->UserDefined.After.ReferenceBinding && 3399 ICS->UserDefined.After.DirectBinding && 3400 "Expected a direct reference binding!"); 3401 return false; 3402 } else { 3403 // Perform the conversion. 3404 // FIXME: Binding to a subobject of the lvalue is going to require more 3405 // AST annotation than this. 3406 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true); 3407 } 3408 break; 3409 3410 case OR_Ambiguous: 3411 assert(false && "Ambiguous reference binding conversions not implemented."); 3412 return true; 3413 3414 case OR_No_Viable_Function: 3415 case OR_Deleted: 3416 // There was no suitable conversion, or we found a deleted 3417 // conversion; continue with other checks. 3418 break; 3419 } 3420 } 3421 3422 if (BindsDirectly) { 3423 // C++ [dcl.init.ref]p4: 3424 // [...] In all cases where the reference-related or 3425 // reference-compatible relationship of two types is used to 3426 // establish the validity of a reference binding, and T1 is a 3427 // base class of T2, a program that necessitates such a binding 3428 // is ill-formed if T1 is an inaccessible (clause 11) or 3429 // ambiguous (10.2) base class of T2. 3430 // 3431 // Note that we only check this condition when we're allowed to 3432 // complain about errors, because we should not be checking for 3433 // ambiguity (or inaccessibility) unless the reference binding 3434 // actually happens. 3435 if (DerivedToBase) 3436 return CheckDerivedToBaseConversion(T2, T1, 3437 Init->getSourceRange().getBegin(), 3438 Init->getSourceRange()); 3439 else 3440 return false; 3441 } 3442 3443 // -- Otherwise, the reference shall be to a non-volatile const 3444 // type (i.e., cv1 shall be const), or the reference shall be an 3445 // rvalue reference and the initializer expression shall be an rvalue. 3446 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) { 3447 if (!ICS) 3448 Diag(Init->getSourceRange().getBegin(), 3449 diag::err_not_reference_to_const_init) 3450 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 3451 << T2 << Init->getSourceRange(); 3452 return true; 3453 } 3454 3455 // -- If the initializer expression is an rvalue, with T2 a 3456 // class type, and "cv1 T1" is reference-compatible with 3457 // "cv2 T2," the reference is bound in one of the 3458 // following ways (the choice is implementation-defined): 3459 // 3460 // -- The reference is bound to the object represented by 3461 // the rvalue (see 3.10) or to a sub-object within that 3462 // object. 3463 // 3464 // -- A temporary of type "cv1 T2" [sic] is created, and 3465 // a constructor is called to copy the entire rvalue 3466 // object into the temporary. The reference is bound to 3467 // the temporary or to a sub-object within the 3468 // temporary. 3469 // 3470 // The constructor that would be used to make the copy 3471 // shall be callable whether or not the copy is actually 3472 // done. 3473 // 3474 // Note that C++0x [dcl.init.ref]p5 takes away this implementation 3475 // freedom, so we will always take the first option and never build 3476 // a temporary in this case. FIXME: We will, however, have to check 3477 // for the presence of a copy constructor in C++98/03 mode. 3478 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() && 3479 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 3480 if (ICS) { 3481 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 3482 ICS->Standard.First = ICK_Identity; 3483 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 3484 ICS->Standard.Third = ICK_Identity; 3485 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 3486 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 3487 ICS->Standard.ReferenceBinding = true; 3488 ICS->Standard.DirectBinding = false; 3489 ICS->Standard.RRefBinding = isRValRef; 3490 ICS->Standard.CopyConstructor = 0; 3491 } else { 3492 // FIXME: Binding to a subobject of the rvalue is going to require more 3493 // AST annotation than this. 3494 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/false); 3495 } 3496 return false; 3497 } 3498 3499 // -- Otherwise, a temporary of type "cv1 T1" is created and 3500 // initialized from the initializer expression using the 3501 // rules for a non-reference copy initialization (8.5). The 3502 // reference is then bound to the temporary. If T1 is 3503 // reference-related to T2, cv1 must be the same 3504 // cv-qualification as, or greater cv-qualification than, 3505 // cv2; otherwise, the program is ill-formed. 3506 if (RefRelationship == Ref_Related) { 3507 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 3508 // we would be reference-compatible or reference-compatible with 3509 // added qualification. But that wasn't the case, so the reference 3510 // initialization fails. 3511 if (!ICS) 3512 Diag(Init->getSourceRange().getBegin(), 3513 diag::err_reference_init_drops_quals) 3514 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 3515 << T2 << Init->getSourceRange(); 3516 return true; 3517 } 3518 3519 // If at least one of the types is a class type, the types are not 3520 // related, and we aren't allowed any user conversions, the 3521 // reference binding fails. This case is important for breaking 3522 // recursion, since TryImplicitConversion below will attempt to 3523 // create a temporary through the use of a copy constructor. 3524 if (SuppressUserConversions && RefRelationship == Ref_Incompatible && 3525 (T1->isRecordType() || T2->isRecordType())) { 3526 if (!ICS) 3527 Diag(Init->getSourceRange().getBegin(), 3528 diag::err_typecheck_convert_incompatible) 3529 << DeclType << Init->getType() << "initializing" << Init->getSourceRange(); 3530 return true; 3531 } 3532 3533 // Actually try to convert the initializer to T1. 3534 if (ICS) { 3535 // C++ [over.ics.ref]p2: 3536 // 3537 // When a parameter of reference type is not bound directly to 3538 // an argument expression, the conversion sequence is the one 3539 // required to convert the argument expression to the 3540 // underlying type of the reference according to 3541 // 13.3.3.1. Conceptually, this conversion sequence corresponds 3542 // to copy-initializing a temporary of the underlying type with 3543 // the argument expression. Any difference in top-level 3544 // cv-qualification is subsumed by the initialization itself 3545 // and does not constitute a conversion. 3546 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions, 3547 /*AllowExplicit=*/false, 3548 /*ForceRValue=*/false, 3549 /*InOverloadResolution=*/false); 3550 3551 // Of course, that's still a reference binding. 3552 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) { 3553 ICS->Standard.ReferenceBinding = true; 3554 ICS->Standard.RRefBinding = isRValRef; 3555 } else if (ICS->ConversionKind == 3556 ImplicitConversionSequence::UserDefinedConversion) { 3557 ICS->UserDefined.After.ReferenceBinding = true; 3558 ICS->UserDefined.After.RRefBinding = isRValRef; 3559 } 3560 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion; 3561 } else { 3562 return PerformImplicitConversion(Init, T1, "initializing"); 3563 } 3564} 3565 3566/// CheckOverloadedOperatorDeclaration - Check whether the declaration 3567/// of this overloaded operator is well-formed. If so, returns false; 3568/// otherwise, emits appropriate diagnostics and returns true. 3569bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 3570 assert(FnDecl && FnDecl->isOverloadedOperator() && 3571 "Expected an overloaded operator declaration"); 3572 3573 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 3574 3575 // C++ [over.oper]p5: 3576 // The allocation and deallocation functions, operator new, 3577 // operator new[], operator delete and operator delete[], are 3578 // described completely in 3.7.3. The attributes and restrictions 3579 // found in the rest of this subclause do not apply to them unless 3580 // explicitly stated in 3.7.3. 3581 // FIXME: Write a separate routine for checking this. For now, just allow it. 3582 if (Op == OO_New || Op == OO_Array_New || 3583 Op == OO_Delete || Op == OO_Array_Delete) 3584 return false; 3585 3586 // C++ [over.oper]p6: 3587 // An operator function shall either be a non-static member 3588 // function or be a non-member function and have at least one 3589 // parameter whose type is a class, a reference to a class, an 3590 // enumeration, or a reference to an enumeration. 3591 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 3592 if (MethodDecl->isStatic()) 3593 return Diag(FnDecl->getLocation(), 3594 diag::err_operator_overload_static) << FnDecl->getDeclName(); 3595 } else { 3596 bool ClassOrEnumParam = false; 3597 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 3598 ParamEnd = FnDecl->param_end(); 3599 Param != ParamEnd; ++Param) { 3600 QualType ParamType = (*Param)->getType().getNonReferenceType(); 3601 if (ParamType->isDependentType() || ParamType->isRecordType() || 3602 ParamType->isEnumeralType()) { 3603 ClassOrEnumParam = true; 3604 break; 3605 } 3606 } 3607 3608 if (!ClassOrEnumParam) 3609 return Diag(FnDecl->getLocation(), 3610 diag::err_operator_overload_needs_class_or_enum) 3611 << FnDecl->getDeclName(); 3612 } 3613 3614 // C++ [over.oper]p8: 3615 // An operator function cannot have default arguments (8.3.6), 3616 // except where explicitly stated below. 3617 // 3618 // Only the function-call operator allows default arguments 3619 // (C++ [over.call]p1). 3620 if (Op != OO_Call) { 3621 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 3622 Param != FnDecl->param_end(); ++Param) { 3623 if ((*Param)->hasUnparsedDefaultArg()) 3624 return Diag((*Param)->getLocation(), 3625 diag::err_operator_overload_default_arg) 3626 << FnDecl->getDeclName(); 3627 else if (Expr *DefArg = (*Param)->getDefaultArg()) 3628 return Diag((*Param)->getLocation(), 3629 diag::err_operator_overload_default_arg) 3630 << FnDecl->getDeclName() << DefArg->getSourceRange(); 3631 } 3632 } 3633 3634 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 3635 { false, false, false } 3636#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 3637 , { Unary, Binary, MemberOnly } 3638#include "clang/Basic/OperatorKinds.def" 3639 }; 3640 3641 bool CanBeUnaryOperator = OperatorUses[Op][0]; 3642 bool CanBeBinaryOperator = OperatorUses[Op][1]; 3643 bool MustBeMemberOperator = OperatorUses[Op][2]; 3644 3645 // C++ [over.oper]p8: 3646 // [...] Operator functions cannot have more or fewer parameters 3647 // than the number required for the corresponding operator, as 3648 // described in the rest of this subclause. 3649 unsigned NumParams = FnDecl->getNumParams() 3650 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 3651 if (Op != OO_Call && 3652 ((NumParams == 1 && !CanBeUnaryOperator) || 3653 (NumParams == 2 && !CanBeBinaryOperator) || 3654 (NumParams < 1) || (NumParams > 2))) { 3655 // We have the wrong number of parameters. 3656 unsigned ErrorKind; 3657 if (CanBeUnaryOperator && CanBeBinaryOperator) { 3658 ErrorKind = 2; // 2 -> unary or binary. 3659 } else if (CanBeUnaryOperator) { 3660 ErrorKind = 0; // 0 -> unary 3661 } else { 3662 assert(CanBeBinaryOperator && 3663 "All non-call overloaded operators are unary or binary!"); 3664 ErrorKind = 1; // 1 -> binary 3665 } 3666 3667 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 3668 << FnDecl->getDeclName() << NumParams << ErrorKind; 3669 } 3670 3671 // Overloaded operators other than operator() cannot be variadic. 3672 if (Op != OO_Call && 3673 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) { 3674 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 3675 << FnDecl->getDeclName(); 3676 } 3677 3678 // Some operators must be non-static member functions. 3679 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 3680 return Diag(FnDecl->getLocation(), 3681 diag::err_operator_overload_must_be_member) 3682 << FnDecl->getDeclName(); 3683 } 3684 3685 // C++ [over.inc]p1: 3686 // The user-defined function called operator++ implements the 3687 // prefix and postfix ++ operator. If this function is a member 3688 // function with no parameters, or a non-member function with one 3689 // parameter of class or enumeration type, it defines the prefix 3690 // increment operator ++ for objects of that type. If the function 3691 // is a member function with one parameter (which shall be of type 3692 // int) or a non-member function with two parameters (the second 3693 // of which shall be of type int), it defines the postfix 3694 // increment operator ++ for objects of that type. 3695 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 3696 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 3697 bool ParamIsInt = false; 3698 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType()) 3699 ParamIsInt = BT->getKind() == BuiltinType::Int; 3700 3701 if (!ParamIsInt) 3702 return Diag(LastParam->getLocation(), 3703 diag::err_operator_overload_post_incdec_must_be_int) 3704 << LastParam->getType() << (Op == OO_MinusMinus); 3705 } 3706 3707 // Notify the class if it got an assignment operator. 3708 if (Op == OO_Equal) { 3709 // Would have returned earlier otherwise. 3710 assert(isa<CXXMethodDecl>(FnDecl) && 3711 "Overloaded = not member, but not filtered."); 3712 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 3713 Method->setCopyAssignment(true); 3714 Method->getParent()->addedAssignmentOperator(Context, Method); 3715 } 3716 3717 return false; 3718} 3719 3720/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 3721/// linkage specification, including the language and (if present) 3722/// the '{'. ExternLoc is the location of the 'extern', LangLoc is 3723/// the location of the language string literal, which is provided 3724/// by Lang/StrSize. LBraceLoc, if valid, provides the location of 3725/// the '{' brace. Otherwise, this linkage specification does not 3726/// have any braces. 3727Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S, 3728 SourceLocation ExternLoc, 3729 SourceLocation LangLoc, 3730 const char *Lang, 3731 unsigned StrSize, 3732 SourceLocation LBraceLoc) { 3733 LinkageSpecDecl::LanguageIDs Language; 3734 if (strncmp(Lang, "\"C\"", StrSize) == 0) 3735 Language = LinkageSpecDecl::lang_c; 3736 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 3737 Language = LinkageSpecDecl::lang_cxx; 3738 else { 3739 Diag(LangLoc, diag::err_bad_language); 3740 return DeclPtrTy(); 3741 } 3742 3743 // FIXME: Add all the various semantics of linkage specifications 3744 3745 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, 3746 LangLoc, Language, 3747 LBraceLoc.isValid()); 3748 CurContext->addDecl(D); 3749 PushDeclContext(S, D); 3750 return DeclPtrTy::make(D); 3751} 3752 3753/// ActOnFinishLinkageSpecification - Completely the definition of 3754/// the C++ linkage specification LinkageSpec. If RBraceLoc is 3755/// valid, it's the position of the closing '}' brace in a linkage 3756/// specification that uses braces. 3757Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S, 3758 DeclPtrTy LinkageSpec, 3759 SourceLocation RBraceLoc) { 3760 if (LinkageSpec) 3761 PopDeclContext(); 3762 return LinkageSpec; 3763} 3764 3765/// \brief Perform semantic analysis for the variable declaration that 3766/// occurs within a C++ catch clause, returning the newly-created 3767/// variable. 3768VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType, 3769 DeclaratorInfo *DInfo, 3770 IdentifierInfo *Name, 3771 SourceLocation Loc, 3772 SourceRange Range) { 3773 bool Invalid = false; 3774 3775 // Arrays and functions decay. 3776 if (ExDeclType->isArrayType()) 3777 ExDeclType = Context.getArrayDecayedType(ExDeclType); 3778 else if (ExDeclType->isFunctionType()) 3779 ExDeclType = Context.getPointerType(ExDeclType); 3780 3781 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 3782 // The exception-declaration shall not denote a pointer or reference to an 3783 // incomplete type, other than [cv] void*. 3784 // N2844 forbids rvalue references. 3785 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 3786 Diag(Loc, diag::err_catch_rvalue_ref) << Range; 3787 Invalid = true; 3788 } 3789 3790 QualType BaseType = ExDeclType; 3791 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 3792 unsigned DK = diag::err_catch_incomplete; 3793 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 3794 BaseType = Ptr->getPointeeType(); 3795 Mode = 1; 3796 DK = diag::err_catch_incomplete_ptr; 3797 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 3798 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 3799 BaseType = Ref->getPointeeType(); 3800 Mode = 2; 3801 DK = diag::err_catch_incomplete_ref; 3802 } 3803 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 3804 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 3805 Invalid = true; 3806 3807 if (!Invalid && !ExDeclType->isDependentType() && 3808 RequireNonAbstractType(Loc, ExDeclType, 3809 diag::err_abstract_type_in_decl, 3810 AbstractVariableType)) 3811 Invalid = true; 3812 3813 // FIXME: Need to test for ability to copy-construct and destroy the 3814 // exception variable. 3815 3816 // FIXME: Need to check for abstract classes. 3817 3818 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc, 3819 Name, ExDeclType, DInfo, VarDecl::None); 3820 3821 if (Invalid) 3822 ExDecl->setInvalidDecl(); 3823 3824 return ExDecl; 3825} 3826 3827/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 3828/// handler. 3829Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 3830 DeclaratorInfo *DInfo = 0; 3831 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo); 3832 3833 bool Invalid = D.isInvalidType(); 3834 IdentifierInfo *II = D.getIdentifier(); 3835 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) { 3836 // The scope should be freshly made just for us. There is just no way 3837 // it contains any previous declaration. 3838 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl))); 3839 if (PrevDecl->isTemplateParameter()) { 3840 // Maybe we will complain about the shadowed template parameter. 3841 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 3842 } 3843 } 3844 3845 if (D.getCXXScopeSpec().isSet() && !Invalid) { 3846 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 3847 << D.getCXXScopeSpec().getRange(); 3848 Invalid = true; 3849 } 3850 3851 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo, 3852 D.getIdentifier(), 3853 D.getIdentifierLoc(), 3854 D.getDeclSpec().getSourceRange()); 3855 3856 if (Invalid) 3857 ExDecl->setInvalidDecl(); 3858 3859 // Add the exception declaration into this scope. 3860 if (II) 3861 PushOnScopeChains(ExDecl, S); 3862 else 3863 CurContext->addDecl(ExDecl); 3864 3865 ProcessDeclAttributes(S, ExDecl, D); 3866 return DeclPtrTy::make(ExDecl); 3867} 3868 3869Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc, 3870 ExprArg assertexpr, 3871 ExprArg assertmessageexpr) { 3872 Expr *AssertExpr = (Expr *)assertexpr.get(); 3873 StringLiteral *AssertMessage = 3874 cast<StringLiteral>((Expr *)assertmessageexpr.get()); 3875 3876 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) { 3877 llvm::APSInt Value(32); 3878 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) { 3879 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) << 3880 AssertExpr->getSourceRange(); 3881 return DeclPtrTy(); 3882 } 3883 3884 if (Value == 0) { 3885 std::string str(AssertMessage->getStrData(), 3886 AssertMessage->getByteLength()); 3887 Diag(AssertLoc, diag::err_static_assert_failed) 3888 << str << AssertExpr->getSourceRange(); 3889 } 3890 } 3891 3892 assertexpr.release(); 3893 assertmessageexpr.release(); 3894 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc, 3895 AssertExpr, AssertMessage); 3896 3897 CurContext->addDecl(Decl); 3898 return DeclPtrTy::make(Decl); 3899} 3900 3901Sema::DeclPtrTy Sema::ActOnFriendDecl(Scope *S, 3902 llvm::PointerUnion<const DeclSpec*,Declarator*> DU, 3903 bool IsDefinition) { 3904 if (DU.is<Declarator*>()) 3905 return ActOnFriendFunctionDecl(S, *DU.get<Declarator*>(), IsDefinition); 3906 else 3907 return ActOnFriendTypeDecl(S, *DU.get<const DeclSpec*>(), IsDefinition); 3908} 3909 3910Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, 3911 const DeclSpec &DS, 3912 bool IsDefinition) { 3913 SourceLocation Loc = DS.getSourceRange().getBegin(); 3914 3915 assert(DS.isFriendSpecified()); 3916 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 3917 3918 // Try to convert the decl specifier to a type. 3919 bool invalid = false; 3920 QualType T = ConvertDeclSpecToType(DS, Loc, invalid); 3921 if (invalid) return DeclPtrTy(); 3922 3923 // C++ [class.friend]p2: 3924 // An elaborated-type-specifier shall be used in a friend declaration 3925 // for a class.* 3926 // * The class-key of the elaborated-type-specifier is required. 3927 // This is one of the rare places in Clang where it's legitimate to 3928 // ask about the "spelling" of the type. 3929 if (!getLangOptions().CPlusPlus0x && !isa<ElaboratedType>(T)) { 3930 // If we evaluated the type to a record type, suggest putting 3931 // a tag in front. 3932 if (const RecordType *RT = T->getAs<RecordType>()) { 3933 RecordDecl *RD = RT->getDecl(); 3934 3935 std::string InsertionText = std::string(" ") + RD->getKindName(); 3936 3937 Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type) 3938 << (RD->isUnion()) 3939 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(), 3940 InsertionText); 3941 return DeclPtrTy(); 3942 }else { 3943 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend) 3944 << DS.getSourceRange(); 3945 return DeclPtrTy(); 3946 } 3947 } 3948 3949 FriendDecl::FriendUnion FU = T.getTypePtr(); 3950 3951 // The parser doesn't quite handle 3952 // friend class A { ... } 3953 // optimally, because it might have been the (valid) prefix of 3954 // friend class A { ... } foo(); 3955 // So in a very particular set of circumstances, we need to adjust 3956 // IsDefinition. 3957 // 3958 // Also, if we made a RecordDecl in ActOnTag, we want that to be the 3959 // object of our friend declaration. 3960 switch (DS.getTypeSpecType()) { 3961 default: break; 3962 case DeclSpec::TST_class: 3963 case DeclSpec::TST_struct: 3964 case DeclSpec::TST_union: 3965 CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep()); 3966 if (RD) { 3967 IsDefinition |= RD->isDefinition(); 3968 FU = RD; 3969 } 3970 break; 3971 } 3972 3973 // C++ [class.friend]p2: A class shall not be defined inside 3974 // a friend declaration. 3975 if (IsDefinition) { 3976 Diag(DS.getFriendSpecLoc(), diag::err_friend_decl_defines_class) 3977 << DS.getSourceRange(); 3978 return DeclPtrTy(); 3979 } 3980 3981 // C++98 [class.friend]p1: A friend of a class is a function 3982 // or class that is not a member of the class . . . 3983 // But that's a silly restriction which nobody implements for 3984 // inner classes, and C++0x removes it anyway, so we only report 3985 // this (as a warning) if we're being pedantic. 3986 if (!getLangOptions().CPlusPlus0x) 3987 if (const RecordType *RT = T->getAs<RecordType>()) 3988 if (RT->getDecl()->getDeclContext() == CurContext) 3989 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class); 3990 3991 FriendDecl *FD = FriendDecl::Create(Context, CurContext, Loc, FU, 3992 DS.getFriendSpecLoc()); 3993 FD->setAccess(AS_public); 3994 CurContext->addDecl(FD); 3995 3996 return DeclPtrTy::make(FD); 3997} 3998 3999Sema::DeclPtrTy Sema::ActOnFriendFunctionDecl(Scope *S, 4000 Declarator &D, 4001 bool IsDefinition) { 4002 const DeclSpec &DS = D.getDeclSpec(); 4003 4004 assert(DS.isFriendSpecified()); 4005 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 4006 4007 SourceLocation Loc = D.getIdentifierLoc(); 4008 DeclaratorInfo *DInfo = 0; 4009 QualType T = GetTypeForDeclarator(D, S, &DInfo); 4010 4011 // C++ [class.friend]p1 4012 // A friend of a class is a function or class.... 4013 // Note that this sees through typedefs, which is intended. 4014 // It *doesn't* see through dependent types, which is correct 4015 // according to [temp.arg.type]p3: 4016 // If a declaration acquires a function type through a 4017 // type dependent on a template-parameter and this causes 4018 // a declaration that does not use the syntactic form of a 4019 // function declarator to have a function type, the program 4020 // is ill-formed. 4021 if (!T->isFunctionType()) { 4022 Diag(Loc, diag::err_unexpected_friend); 4023 4024 // It might be worthwhile to try to recover by creating an 4025 // appropriate declaration. 4026 return DeclPtrTy(); 4027 } 4028 4029 // C++ [namespace.memdef]p3 4030 // - If a friend declaration in a non-local class first declares a 4031 // class or function, the friend class or function is a member 4032 // of the innermost enclosing namespace. 4033 // - The name of the friend is not found by simple name lookup 4034 // until a matching declaration is provided in that namespace 4035 // scope (either before or after the class declaration granting 4036 // friendship). 4037 // - If a friend function is called, its name may be found by the 4038 // name lookup that considers functions from namespaces and 4039 // classes associated with the types of the function arguments. 4040 // - When looking for a prior declaration of a class or a function 4041 // declared as a friend, scopes outside the innermost enclosing 4042 // namespace scope are not considered. 4043 4044 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec(); 4045 DeclarationName Name = GetNameForDeclarator(D); 4046 assert(Name); 4047 4048 // The existing declaration we found. 4049 FunctionDecl *FD = NULL; 4050 4051 // The context we found the declaration in, or in which we should 4052 // create the declaration. 4053 DeclContext *DC; 4054 4055 // FIXME: handle local classes 4056 4057 // Recover from invalid scope qualifiers as if they just weren't there. 4058 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) { 4059 DC = computeDeclContext(ScopeQual); 4060 4061 // FIXME: handle dependent contexts 4062 if (!DC) return DeclPtrTy(); 4063 4064 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T); 4065 4066 // If searching in that context implicitly found a declaration in 4067 // a different context, treat it like it wasn't found at all. 4068 // TODO: better diagnostics for this case. Suggesting the right 4069 // qualified scope would be nice... 4070 if (!Dec || Dec->getDeclContext() != DC) { 4071 D.setInvalidType(); 4072 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T; 4073 return DeclPtrTy(); 4074 } 4075 4076 // C++ [class.friend]p1: A friend of a class is a function or 4077 // class that is not a member of the class . . . 4078 if (DC == CurContext) 4079 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 4080 4081 FD = cast<FunctionDecl>(Dec); 4082 4083 // Otherwise walk out to the nearest namespace scope looking for matches. 4084 } else { 4085 // TODO: handle local class contexts. 4086 4087 DC = CurContext; 4088 while (true) { 4089 // Skip class contexts. If someone can cite chapter and verse 4090 // for this behavior, that would be nice --- it's what GCC and 4091 // EDG do, and it seems like a reasonable intent, but the spec 4092 // really only says that checks for unqualified existing 4093 // declarations should stop at the nearest enclosing namespace, 4094 // not that they should only consider the nearest enclosing 4095 // namespace. 4096 while (DC->isRecord()) DC = DC->getParent(); 4097 4098 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T); 4099 4100 // TODO: decide what we think about using declarations. 4101 if (Dec) { 4102 FD = cast<FunctionDecl>(Dec); 4103 break; 4104 } 4105 if (DC->isFileContext()) break; 4106 DC = DC->getParent(); 4107 } 4108 4109 // C++ [class.friend]p1: A friend of a class is a function or 4110 // class that is not a member of the class . . . 4111 // C++0x changes this for both friend types and functions. 4112 // Most C++ 98 compilers do seem to give an error here, so 4113 // we do, too. 4114 if (FD && DC == CurContext && !getLangOptions().CPlusPlus0x) 4115 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member); 4116 } 4117 4118 bool Redeclaration = (FD != 0); 4119 4120 // If we found a match, create a friend function declaration with 4121 // that function as the previous declaration. 4122 if (Redeclaration) { 4123 // Create it in the semantic context of the original declaration. 4124 DC = FD->getDeclContext(); 4125 4126 // If we didn't find something matching the type exactly, create 4127 // a declaration. This declaration should only be findable via 4128 // argument-dependent lookup. 4129 } else { 4130 assert(DC->isFileContext()); 4131 4132 // This implies that it has to be an operator or function. 4133 if (D.getKind() == Declarator::DK_Constructor || 4134 D.getKind() == Declarator::DK_Destructor || 4135 D.getKind() == Declarator::DK_Conversion) { 4136 Diag(Loc, diag::err_introducing_special_friend) << 4137 (D.getKind() == Declarator::DK_Constructor ? 0 : 4138 D.getKind() == Declarator::DK_Destructor ? 1 : 2); 4139 return DeclPtrTy(); 4140 } 4141 } 4142 4143 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo, 4144 /* PrevDecl = */ FD, 4145 MultiTemplateParamsArg(*this), 4146 IsDefinition, 4147 Redeclaration); 4148 if (!ND) return DeclPtrTy(); 4149 4150 assert(cast<FunctionDecl>(ND)->getPreviousDeclaration() == FD && 4151 "lost reference to previous declaration"); 4152 4153 FD = cast<FunctionDecl>(ND); 4154 4155 assert(FD->getDeclContext() == DC); 4156 assert(FD->getLexicalDeclContext() == CurContext); 4157 4158 // Add the function declaration to the appropriate lookup tables, 4159 // adjusting the redeclarations list as necessary. We don't 4160 // want to do this yet if the friending class is dependent. 4161 // 4162 // Also update the scope-based lookup if the target context's 4163 // lookup context is in lexical scope. 4164 if (!CurContext->isDependentContext()) { 4165 DC = DC->getLookupContext(); 4166 DC->makeDeclVisibleInContext(FD, /* Recoverable=*/ false); 4167 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 4168 PushOnScopeChains(FD, EnclosingScope, /*AddToContext=*/ false); 4169 } 4170 4171 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 4172 D.getIdentifierLoc(), FD, 4173 DS.getFriendSpecLoc()); 4174 FrD->setAccess(AS_public); 4175 CurContext->addDecl(FrD); 4176 4177 return DeclPtrTy::make(FD); 4178} 4179 4180void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) { 4181 AdjustDeclIfTemplate(dcl); 4182 4183 Decl *Dcl = dcl.getAs<Decl>(); 4184 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl); 4185 if (!Fn) { 4186 Diag(DelLoc, diag::err_deleted_non_function); 4187 return; 4188 } 4189 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) { 4190 Diag(DelLoc, diag::err_deleted_decl_not_first); 4191 Diag(Prev->getLocation(), diag::note_previous_declaration); 4192 // If the declaration wasn't the first, we delete the function anyway for 4193 // recovery. 4194 } 4195 Fn->setDeleted(); 4196} 4197 4198static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 4199 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E; 4200 ++CI) { 4201 Stmt *SubStmt = *CI; 4202 if (!SubStmt) 4203 continue; 4204 if (isa<ReturnStmt>(SubStmt)) 4205 Self.Diag(SubStmt->getSourceRange().getBegin(), 4206 diag::err_return_in_constructor_handler); 4207 if (!isa<Expr>(SubStmt)) 4208 SearchForReturnInStmt(Self, SubStmt); 4209 } 4210} 4211 4212void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 4213 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 4214 CXXCatchStmt *Handler = TryBlock->getHandler(I); 4215 SearchForReturnInStmt(*this, Handler); 4216 } 4217} 4218 4219bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 4220 const CXXMethodDecl *Old) { 4221 QualType NewTy = New->getType()->getAsFunctionType()->getResultType(); 4222 QualType OldTy = Old->getType()->getAsFunctionType()->getResultType(); 4223 4224 QualType CNewTy = Context.getCanonicalType(NewTy); 4225 QualType COldTy = Context.getCanonicalType(OldTy); 4226 4227 if (CNewTy == COldTy && 4228 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers()) 4229 return false; 4230 4231 // Check if the return types are covariant 4232 QualType NewClassTy, OldClassTy; 4233 4234 /// Both types must be pointers or references to classes. 4235 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) { 4236 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) { 4237 NewClassTy = NewPT->getPointeeType(); 4238 OldClassTy = OldPT->getPointeeType(); 4239 } 4240 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) { 4241 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) { 4242 NewClassTy = NewRT->getPointeeType(); 4243 OldClassTy = OldRT->getPointeeType(); 4244 } 4245 } 4246 4247 // The return types aren't either both pointers or references to a class type. 4248 if (NewClassTy.isNull()) { 4249 Diag(New->getLocation(), 4250 diag::err_different_return_type_for_overriding_virtual_function) 4251 << New->getDeclName() << NewTy << OldTy; 4252 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4253 4254 return true; 4255 } 4256 4257 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) { 4258 // Check if the new class derives from the old class. 4259 if (!IsDerivedFrom(NewClassTy, OldClassTy)) { 4260 Diag(New->getLocation(), 4261 diag::err_covariant_return_not_derived) 4262 << New->getDeclName() << NewTy << OldTy; 4263 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4264 return true; 4265 } 4266 4267 // Check if we the conversion from derived to base is valid. 4268 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy, 4269 diag::err_covariant_return_inaccessible_base, 4270 diag::err_covariant_return_ambiguous_derived_to_base_conv, 4271 // FIXME: Should this point to the return type? 4272 New->getLocation(), SourceRange(), New->getDeclName())) { 4273 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4274 return true; 4275 } 4276 } 4277 4278 // The qualifiers of the return types must be the same. 4279 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) { 4280 Diag(New->getLocation(), 4281 diag::err_covariant_return_type_different_qualifications) 4282 << New->getDeclName() << NewTy << OldTy; 4283 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4284 return true; 4285 }; 4286 4287 4288 // The new class type must have the same or less qualifiers as the old type. 4289 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 4290 Diag(New->getLocation(), 4291 diag::err_covariant_return_type_class_type_more_qualified) 4292 << New->getDeclName() << NewTy << OldTy; 4293 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 4294 return true; 4295 }; 4296 4297 return false; 4298} 4299 4300bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 4301 const CXXMethodDecl *Old) { 4302 return CheckExceptionSpecSubset(diag::err_override_exception_spec, 4303 diag::note_overridden_virtual_function, 4304 Old->getType()->getAsFunctionProtoType(), 4305 Old->getLocation(), 4306 New->getType()->getAsFunctionProtoType(), 4307 New->getLocation()); 4308} 4309 4310/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 4311/// initializer for the declaration 'Dcl'. 4312/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 4313/// static data member of class X, names should be looked up in the scope of 4314/// class X. 4315void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) { 4316 AdjustDeclIfTemplate(Dcl); 4317 4318 Decl *D = Dcl.getAs<Decl>(); 4319 // If there is no declaration, there was an error parsing it. 4320 if (D == 0) 4321 return; 4322 4323 // Check whether it is a declaration with a nested name specifier like 4324 // int foo::bar; 4325 if (!D->isOutOfLine()) 4326 return; 4327 4328 // C++ [basic.lookup.unqual]p13 4329 // 4330 // A name used in the definition of a static data member of class X 4331 // (after the qualified-id of the static member) is looked up as if the name 4332 // was used in a member function of X. 4333 4334 // Change current context into the context of the initializing declaration. 4335 EnterDeclaratorContext(S, D->getDeclContext()); 4336} 4337 4338/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 4339/// initializer for the declaration 'Dcl'. 4340void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) { 4341 AdjustDeclIfTemplate(Dcl); 4342 4343 Decl *D = Dcl.getAs<Decl>(); 4344 // If there is no declaration, there was an error parsing it. 4345 if (D == 0) 4346 return; 4347 4348 // Check whether it is a declaration with a nested name specifier like 4349 // int foo::bar; 4350 if (!D->isOutOfLine()) 4351 return; 4352 4353 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!"); 4354 ExitDeclaratorContext(S); 4355} 4356