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