SemaDeclCXX.cpp revision dcd5ef12488e4c7ea844327835896ca86b609a97
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/TypeOrdering.h" 19#include "clang/AST/StmtVisitor.h" 20#include "clang/Lex/Preprocessor.h" 21#include "clang/Basic/Diagnostic.h" 22#include "clang/Parse/DeclSpec.h" 23#include "llvm/ADT/StringExtras.h" 24#include "llvm/Support/Compiler.h" 25#include <algorithm> // for std::equal 26#include <map> 27 28using namespace clang; 29 30//===----------------------------------------------------------------------===// 31// CheckDefaultArgumentVisitor 32//===----------------------------------------------------------------------===// 33 34namespace { 35 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 36 /// the default argument of a parameter to determine whether it 37 /// contains any ill-formed subexpressions. For example, this will 38 /// diagnose the use of local variables or parameters within the 39 /// default argument expression. 40 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor 41 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 42 Expr *DefaultArg; 43 Sema *S; 44 45 public: 46 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 47 : DefaultArg(defarg), S(s) {} 48 49 bool VisitExpr(Expr *Node); 50 bool VisitDeclRefExpr(DeclRefExpr *DRE); 51 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 52 }; 53 54 /// VisitExpr - Visit all of the children of this expression. 55 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 56 bool IsInvalid = false; 57 for (Stmt::child_iterator I = Node->child_begin(), 58 E = Node->child_end(); I != E; ++I) 59 IsInvalid |= Visit(*I); 60 return IsInvalid; 61 } 62 63 /// VisitDeclRefExpr - Visit a reference to a declaration, to 64 /// determine whether this declaration can be used in the default 65 /// argument expression. 66 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 67 NamedDecl *Decl = DRE->getDecl(); 68 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 69 // C++ [dcl.fct.default]p9 70 // Default arguments are evaluated each time the function is 71 // called. The order of evaluation of function arguments is 72 // unspecified. Consequently, parameters of a function shall not 73 // be used in default argument expressions, even if they are not 74 // evaluated. Parameters of a function declared before a default 75 // argument expression are in scope and can hide namespace and 76 // class member names. 77 return S->Diag(DRE->getSourceRange().getBegin(), 78 diag::err_param_default_argument_references_param) 79 << Param->getName() << DefaultArg->getSourceRange(); 80 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 81 // C++ [dcl.fct.default]p7 82 // Local variables shall not be used in default argument 83 // expressions. 84 if (VDecl->isBlockVarDecl()) 85 return S->Diag(DRE->getSourceRange().getBegin(), 86 diag::err_param_default_argument_references_local) 87 << VDecl->getName() << DefaultArg->getSourceRange(); 88 } 89 90 return false; 91 } 92 93 /// VisitCXXThisExpr - Visit a C++ "this" expression. 94 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 95 // C++ [dcl.fct.default]p8: 96 // The keyword this shall not be used in a default argument of a 97 // member function. 98 return S->Diag(ThisE->getSourceRange().getBegin(), 99 diag::err_param_default_argument_references_this) 100 << ThisE->getSourceRange(); 101 } 102} 103 104/// ActOnParamDefaultArgument - Check whether the default argument 105/// provided for a function parameter is well-formed. If so, attach it 106/// to the parameter declaration. 107void 108Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc, 109 ExprTy *defarg) { 110 ParmVarDecl *Param = (ParmVarDecl *)param; 111 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg); 112 QualType ParamType = Param->getType(); 113 114 // Default arguments are only permitted in C++ 115 if (!getLangOptions().CPlusPlus) { 116 Diag(EqualLoc, diag::err_param_default_argument) 117 << DefaultArg->getSourceRange(); 118 return; 119 } 120 121 // C++ [dcl.fct.default]p5 122 // A default argument expression is implicitly converted (clause 123 // 4) to the parameter type. The default argument expression has 124 // the same semantic constraints as the initializer expression in 125 // a declaration of a variable of the parameter type, using the 126 // copy-initialization semantics (8.5). 127 Expr *DefaultArgPtr = DefaultArg.get(); 128 bool DefaultInitFailed = PerformCopyInitialization(DefaultArgPtr, ParamType, 129 "in default argument"); 130 if (DefaultArgPtr != DefaultArg.get()) { 131 DefaultArg.take(); 132 DefaultArg.reset(DefaultArgPtr); 133 } 134 if (DefaultInitFailed) { 135 return; 136 } 137 138 // Check that the default argument is well-formed 139 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 140 if (DefaultArgChecker.Visit(DefaultArg.get())) 141 return; 142 143 // Okay: add the default argument to the parameter 144 Param->setDefaultArg(DefaultArg.take()); 145} 146 147/// CheckExtraCXXDefaultArguments - Check for any extra default 148/// arguments in the declarator, which is not a function declaration 149/// or definition and therefore is not permitted to have default 150/// arguments. This routine should be invoked for every declarator 151/// that is not a function declaration or definition. 152void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 153 // C++ [dcl.fct.default]p3 154 // A default argument expression shall be specified only in the 155 // parameter-declaration-clause of a function declaration or in a 156 // template-parameter (14.1). It shall not be specified for a 157 // parameter pack. If it is specified in a 158 // parameter-declaration-clause, it shall not occur within a 159 // declarator or abstract-declarator of a parameter-declaration. 160 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) { 161 DeclaratorChunk &chunk = D.getTypeObject(i); 162 if (chunk.Kind == DeclaratorChunk::Function) { 163 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) { 164 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param; 165 if (Param->getDefaultArg()) { 166 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 167 << Param->getDefaultArg()->getSourceRange(); 168 Param->setDefaultArg(0); 169 } 170 } 171 } 172 } 173} 174 175// MergeCXXFunctionDecl - Merge two declarations of the same C++ 176// function, once we already know that they have the same 177// type. Subroutine of MergeFunctionDecl. 178FunctionDecl * 179Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 180 // C++ [dcl.fct.default]p4: 181 // 182 // For non-template functions, default arguments can be added in 183 // later declarations of a function in the same 184 // scope. Declarations in different scopes have completely 185 // distinct sets of default arguments. That is, declarations in 186 // inner scopes do not acquire default arguments from 187 // declarations in outer scopes, and vice versa. In a given 188 // function declaration, all parameters subsequent to a 189 // parameter with a default argument shall have default 190 // arguments supplied in this or previous declarations. A 191 // default argument shall not be redefined by a later 192 // declaration (not even to the same value). 193 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 194 ParmVarDecl *OldParam = Old->getParamDecl(p); 195 ParmVarDecl *NewParam = New->getParamDecl(p); 196 197 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) { 198 Diag(NewParam->getLocation(), 199 diag::err_param_default_argument_redefinition) 200 << NewParam->getDefaultArg()->getSourceRange(); 201 Diag(OldParam->getLocation(), diag::err_previous_definition); 202 } else if (OldParam->getDefaultArg()) { 203 // Merge the old default argument into the new parameter 204 NewParam->setDefaultArg(OldParam->getDefaultArg()); 205 } 206 } 207 208 return New; 209} 210 211/// CheckCXXDefaultArguments - Verify that the default arguments for a 212/// function declaration are well-formed according to C++ 213/// [dcl.fct.default]. 214void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 215 unsigned NumParams = FD->getNumParams(); 216 unsigned p; 217 218 // Find first parameter with a default argument 219 for (p = 0; p < NumParams; ++p) { 220 ParmVarDecl *Param = FD->getParamDecl(p); 221 if (Param->getDefaultArg()) 222 break; 223 } 224 225 // C++ [dcl.fct.default]p4: 226 // In a given function declaration, all parameters 227 // subsequent to a parameter with a default argument shall 228 // have default arguments supplied in this or previous 229 // declarations. A default argument shall not be redefined 230 // by a later declaration (not even to the same value). 231 unsigned LastMissingDefaultArg = 0; 232 for(; p < NumParams; ++p) { 233 ParmVarDecl *Param = FD->getParamDecl(p); 234 if (!Param->getDefaultArg()) { 235 if (Param->getIdentifier()) 236 Diag(Param->getLocation(), 237 diag::err_param_default_argument_missing_name) 238 << Param->getIdentifier()->getName(); 239 else 240 Diag(Param->getLocation(), 241 diag::err_param_default_argument_missing); 242 243 LastMissingDefaultArg = p; 244 } 245 } 246 247 if (LastMissingDefaultArg > 0) { 248 // Some default arguments were missing. Clear out all of the 249 // default arguments up to (and including) the last missing 250 // default argument, so that we leave the function parameters 251 // in a semantically valid state. 252 for (p = 0; p <= LastMissingDefaultArg; ++p) { 253 ParmVarDecl *Param = FD->getParamDecl(p); 254 if (Param->getDefaultArg()) { 255 delete Param->getDefaultArg(); 256 Param->setDefaultArg(0); 257 } 258 } 259 } 260} 261 262/// isCurrentClassName - Determine whether the identifier II is the 263/// name of the class type currently being defined. In the case of 264/// nested classes, this will only return true if II is the name of 265/// the innermost class. 266bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *, 267 const CXXScopeSpec *SS) { 268 CXXRecordDecl *CurDecl; 269 if (SS) { 270 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep()); 271 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 272 } else 273 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 274 275 if (CurDecl) 276 return &II == CurDecl->getIdentifier(); 277 else 278 return false; 279} 280 281/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 282/// one entry in the base class list of a class specifier, for 283/// example: 284/// class foo : public bar, virtual private baz { 285/// 'public bar' and 'virtual private baz' are each base-specifiers. 286Sema::BaseResult 287Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange, 288 bool Virtual, AccessSpecifier Access, 289 TypeTy *basetype, SourceLocation BaseLoc) { 290 RecordDecl *Decl = (RecordDecl*)classdecl; 291 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype); 292 293 // Base specifiers must be record types. 294 if (!BaseType->isRecordType()) 295 return Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 296 297 // C++ [class.union]p1: 298 // A union shall not be used as a base class. 299 if (BaseType->isUnionType()) 300 return Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 301 302 // C++ [class.union]p1: 303 // A union shall not have base classes. 304 if (Decl->isUnion()) 305 return Diag(Decl->getLocation(), diag::err_base_clause_on_union) 306 << SpecifierRange; 307 308 // C++ [class.derived]p2: 309 // The class-name in a base-specifier shall not be an incompletely 310 // defined class. 311 if (BaseType->isIncompleteType()) 312 return Diag(BaseLoc, diag::err_incomplete_base_class) << SpecifierRange; 313 314 // If the base class is polymorphic, the new one is, too. 315 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl(); 316 assert(BaseDecl && "Record type has no declaration"); 317 BaseDecl = BaseDecl->getDefinition(Context); 318 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 319 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic()) 320 cast<CXXRecordDecl>(Decl)->setPolymorphic(true); 321 322 // Create the base specifier. 323 return new CXXBaseSpecifier(SpecifierRange, Virtual, 324 BaseType->isClassType(), Access, BaseType); 325} 326 327/// ActOnBaseSpecifiers - Attach the given base specifiers to the 328/// class, after checking whether there are any duplicate base 329/// classes. 330void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases, 331 unsigned NumBases) { 332 if (NumBases == 0) 333 return; 334 335 // Used to keep track of which base types we have already seen, so 336 // that we can properly diagnose redundant direct base types. Note 337 // that the key is always the unqualified canonical type of the base 338 // class. 339 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 340 341 // Copy non-redundant base specifiers into permanent storage. 342 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases; 343 unsigned NumGoodBases = 0; 344 for (unsigned idx = 0; idx < NumBases; ++idx) { 345 QualType NewBaseType 346 = Context.getCanonicalType(BaseSpecs[idx]->getType()); 347 NewBaseType = NewBaseType.getUnqualifiedType(); 348 349 if (KnownBaseTypes[NewBaseType]) { 350 // C++ [class.mi]p3: 351 // A class shall not be specified as a direct base class of a 352 // derived class more than once. 353 Diag(BaseSpecs[idx]->getSourceRange().getBegin(), 354 diag::err_duplicate_base_class) 355 << KnownBaseTypes[NewBaseType]->getType().getAsString() 356 << BaseSpecs[idx]->getSourceRange(); 357 358 // Delete the duplicate base class specifier; we're going to 359 // overwrite its pointer later. 360 delete BaseSpecs[idx]; 361 } else { 362 // Okay, add this new base class. 363 KnownBaseTypes[NewBaseType] = BaseSpecs[idx]; 364 BaseSpecs[NumGoodBases++] = BaseSpecs[idx]; 365 } 366 } 367 368 // Attach the remaining base class specifiers to the derived class. 369 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl; 370 Decl->setBases(BaseSpecs, NumGoodBases); 371 372 // Delete the remaining (good) base class specifiers, since their 373 // data has been copied into the CXXRecordDecl. 374 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 375 delete BaseSpecs[idx]; 376} 377 378//===----------------------------------------------------------------------===// 379// C++ class member Handling 380//===----------------------------------------------------------------------===// 381 382/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union 383/// definition, when on C++. 384void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) { 385 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D)); 386 PushDeclContext(Dcl); 387 FieldCollector->StartClass(); 388 389 if (Dcl->getIdentifier()) { 390 // C++ [class]p2: 391 // [...] The class-name is also inserted into the scope of the 392 // class itself; this is known as the injected-class-name. For 393 // purposes of access checking, the injected-class-name is treated 394 // as if it were a public member name. 395 PushOnScopeChains(Dcl, S); 396 } 397} 398 399/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 400/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 401/// bitfield width if there is one and 'InitExpr' specifies the initializer if 402/// any. 'LastInGroup' is non-null for cases where one declspec has multiple 403/// declarators on it. 404/// 405/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if 406/// an instance field is declared, a new CXXFieldDecl is created but the method 407/// does *not* return it; it returns LastInGroup instead. The other C++ members 408/// (which are all ScopedDecls) are returned after appending them to 409/// LastInGroup. 410Sema::DeclTy * 411Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 412 ExprTy *BW, ExprTy *InitExpr, 413 DeclTy *LastInGroup) { 414 const DeclSpec &DS = D.getDeclSpec(); 415 DeclarationName Name = GetNameForDeclarator(D); 416 Expr *BitWidth = static_cast<Expr*>(BW); 417 Expr *Init = static_cast<Expr*>(InitExpr); 418 SourceLocation Loc = D.getIdentifierLoc(); 419 420 bool isFunc = D.isFunctionDeclarator(); 421 422 // C++ 9.2p6: A member shall not be declared to have automatic storage 423 // duration (auto, register) or with the extern storage-class-specifier. 424 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 425 // data members and cannot be applied to names declared const or static, 426 // and cannot be applied to reference members. 427 switch (DS.getStorageClassSpec()) { 428 case DeclSpec::SCS_unspecified: 429 case DeclSpec::SCS_typedef: 430 case DeclSpec::SCS_static: 431 // FALL THROUGH. 432 break; 433 case DeclSpec::SCS_mutable: 434 if (isFunc) { 435 if (DS.getStorageClassSpecLoc().isValid()) 436 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 437 else 438 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function); 439 440 // FIXME: It would be nicer if the keyword was ignored only for this 441 // declarator. Otherwise we could get follow-up errors. 442 D.getMutableDeclSpec().ClearStorageClassSpecs(); 443 } else { 444 QualType T = GetTypeForDeclarator(D, S); 445 diag::kind err = static_cast<diag::kind>(0); 446 if (T->isReferenceType()) 447 err = diag::err_mutable_reference; 448 else if (T.isConstQualified()) 449 err = diag::err_mutable_const; 450 if (err != 0) { 451 if (DS.getStorageClassSpecLoc().isValid()) 452 Diag(DS.getStorageClassSpecLoc(), err); 453 else 454 Diag(DS.getThreadSpecLoc(), err); 455 // FIXME: It would be nicer if the keyword was ignored only for this 456 // declarator. Otherwise we could get follow-up errors. 457 D.getMutableDeclSpec().ClearStorageClassSpecs(); 458 } 459 } 460 break; 461 default: 462 if (DS.getStorageClassSpecLoc().isValid()) 463 Diag(DS.getStorageClassSpecLoc(), 464 diag::err_storageclass_invalid_for_member); 465 else 466 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 467 D.getMutableDeclSpec().ClearStorageClassSpecs(); 468 } 469 470 if (!isFunc && 471 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef && 472 D.getNumTypeObjects() == 0) { 473 // Check also for this case: 474 // 475 // typedef int f(); 476 // f a; 477 // 478 Decl *TD = static_cast<Decl *>(DS.getTypeRep()); 479 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType(); 480 } 481 482 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 483 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 484 !isFunc); 485 486 Decl *Member; 487 bool InvalidDecl = false; 488 489 if (isInstField) 490 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth)); 491 else 492 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup)); 493 494 if (!Member) return LastInGroup; 495 496 assert((Name || isInstField) && "No identifier for non-field ?"); 497 498 // set/getAccess is not part of Decl's interface to avoid bloating it with C++ 499 // specific methods. Use a wrapper class that can be used with all C++ class 500 // member decls. 501 CXXClassMemberWrapper(Member).setAccess(AS); 502 503 // C++ [dcl.init.aggr]p1: 504 // An aggregate is an array or a class (clause 9) with [...] no 505 // private or protected non-static data members (clause 11). 506 if (isInstField && (AS == AS_private || AS == AS_protected)) 507 cast<CXXRecordDecl>(CurContext)->setAggregate(false); 508 509 if (DS.isVirtualSpecified()) { 510 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) { 511 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function); 512 InvalidDecl = true; 513 } else { 514 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext); 515 CurClass->setAggregate(false); 516 CurClass->setPolymorphic(true); 517 } 518 } 519 520 if (BitWidth) { 521 // C++ 9.6p2: Only when declaring an unnamed bit-field may the 522 // constant-expression be a value equal to zero. 523 // FIXME: Check this. 524 525 if (D.isFunctionDeclarator()) { 526 // FIXME: Emit diagnostic about only constructors taking base initializers 527 // or something similar, when constructor support is in place. 528 Diag(Loc, diag::err_not_bitfield_type) 529 << Name.getAsString() << BitWidth->getSourceRange(); 530 InvalidDecl = true; 531 532 } else if (isInstField) { 533 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 534 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) { 535 Diag(Loc, diag::err_not_integral_type_bitfield) 536 << Name.getAsString() << BitWidth->getSourceRange(); 537 InvalidDecl = true; 538 } 539 540 } else if (isa<FunctionDecl>(Member)) { 541 // A function typedef ("typedef int f(); f a;"). 542 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 543 Diag(Loc, diag::err_not_integral_type_bitfield) 544 << Name.getAsString() << BitWidth->getSourceRange(); 545 InvalidDecl = true; 546 547 } else if (isa<TypedefDecl>(Member)) { 548 // "cannot declare 'A' to be a bit-field type" 549 Diag(Loc, diag::err_not_bitfield_type) 550 << Name.getAsString() << BitWidth->getSourceRange(); 551 InvalidDecl = true; 552 553 } else { 554 assert(isa<CXXClassVarDecl>(Member) && 555 "Didn't we cover all member kinds?"); 556 // C++ 9.6p3: A bit-field shall not be a static member. 557 // "static member 'A' cannot be a bit-field" 558 Diag(Loc, diag::err_static_not_bitfield) 559 << Name.getAsString() << BitWidth->getSourceRange(); 560 InvalidDecl = true; 561 } 562 } 563 564 if (Init) { 565 // C++ 9.2p4: A member-declarator can contain a constant-initializer only 566 // if it declares a static member of const integral or const enumeration 567 // type. 568 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) { 569 // ...static member of... 570 CVD->setInit(Init); 571 // ...const integral or const enumeration type. 572 if (Context.getCanonicalType(CVD->getType()).isConstQualified() && 573 CVD->getType()->isIntegralType()) { 574 // constant-initializer 575 if (CheckForConstantInitializer(Init, CVD->getType())) 576 InvalidDecl = true; 577 578 } else { 579 // not const integral. 580 Diag(Loc, diag::err_member_initialization, 581 Name.getAsString(), Init->getSourceRange()); 582 InvalidDecl = true; 583 } 584 585 } else { 586 // not static member. 587 Diag(Loc, diag::err_member_initialization, 588 Name.getAsString(), Init->getSourceRange()); 589 InvalidDecl = true; 590 } 591 } 592 593 if (InvalidDecl) 594 Member->setInvalidDecl(); 595 596 if (isInstField) { 597 FieldCollector->Add(cast<CXXFieldDecl>(Member)); 598 return LastInGroup; 599 } 600 return Member; 601} 602 603/// ActOnMemInitializer - Handle a C++ member initializer. 604Sema::MemInitResult 605Sema::ActOnMemInitializer(DeclTy *ConstructorD, 606 Scope *S, 607 IdentifierInfo *MemberOrBase, 608 SourceLocation IdLoc, 609 SourceLocation LParenLoc, 610 ExprTy **Args, unsigned NumArgs, 611 SourceLocation *CommaLocs, 612 SourceLocation RParenLoc) { 613 CXXConstructorDecl *Constructor 614 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD); 615 if (!Constructor) { 616 // The user wrote a constructor initializer on a function that is 617 // not a C++ constructor. Ignore the error for now, because we may 618 // have more member initializers coming; we'll diagnose it just 619 // once in ActOnMemInitializers. 620 return true; 621 } 622 623 CXXRecordDecl *ClassDecl = Constructor->getParent(); 624 625 // C++ [class.base.init]p2: 626 // Names in a mem-initializer-id are looked up in the scope of the 627 // constructor’s class and, if not found in that scope, are looked 628 // up in the scope containing the constructor’s 629 // definition. [Note: if the constructor’s class contains a member 630 // with the same name as a direct or virtual base class of the 631 // class, a mem-initializer-id naming the member or base class and 632 // composed of a single identifier refers to the class member. A 633 // mem-initializer-id for the hidden base class may be specified 634 // using a qualified name. ] 635 // Look for a member, first. 636 CXXFieldDecl *Member = ClassDecl->getMember(MemberOrBase); 637 638 // FIXME: Handle members of an anonymous union. 639 640 if (Member) { 641 // FIXME: Perform direct initialization of the member. 642 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs); 643 } 644 645 // It didn't name a member, so see if it names a class. 646 TypeTy *BaseTy = isTypeName(*MemberOrBase, S, 0/*SS*/); 647 if (!BaseTy) 648 return Diag(IdLoc, diag::err_mem_init_not_member_or_class, 649 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc)); 650 651 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy); 652 if (!BaseType->isRecordType()) 653 return Diag(IdLoc, diag::err_base_init_does_not_name_class, 654 BaseType.getAsString(), SourceRange(IdLoc, RParenLoc)); 655 656 // C++ [class.base.init]p2: 657 // [...] Unless the mem-initializer-id names a nonstatic data 658 // member of the constructor’s class or a direct or virtual base 659 // of that class, the mem-initializer is ill-formed. A 660 // mem-initializer-list can initialize a base class using any 661 // name that denotes that base class type. 662 663 // First, check for a direct base class. 664 const CXXBaseSpecifier *DirectBaseSpec = 0; 665 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 666 Base != ClassDecl->bases_end(); ++Base) { 667 if (Context.getCanonicalType(BaseType).getUnqualifiedType() == 668 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) { 669 // We found a direct base of this type. That's what we're 670 // initializing. 671 DirectBaseSpec = &*Base; 672 break; 673 } 674 } 675 676 // Check for a virtual base class. 677 // FIXME: We might be able to short-circuit this if we know in 678 // advance that there are no virtual bases. 679 const CXXBaseSpecifier *VirtualBaseSpec = 0; 680 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 681 // We haven't found a base yet; search the class hierarchy for a 682 // virtual base class. 683 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 684 /*DetectVirtual=*/false); 685 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) { 686 for (BasePaths::paths_iterator Path = Paths.begin(); 687 Path != Paths.end(); ++Path) { 688 if (Path->back().Base->isVirtual()) { 689 VirtualBaseSpec = Path->back().Base; 690 break; 691 } 692 } 693 } 694 } 695 696 // C++ [base.class.init]p2: 697 // If a mem-initializer-id is ambiguous because it designates both 698 // a direct non-virtual base class and an inherited virtual base 699 // class, the mem-initializer is ill-formed. 700 if (DirectBaseSpec && VirtualBaseSpec) 701 return Diag(IdLoc, diag::err_base_init_direct_and_virtual, 702 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc)); 703 704 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs); 705} 706 707 708void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 709 DeclTy *TagDecl, 710 SourceLocation LBrac, 711 SourceLocation RBrac) { 712 ActOnFields(S, RLoc, TagDecl, 713 (DeclTy**)FieldCollector->getCurFields(), 714 FieldCollector->getCurNumFields(), LBrac, RBrac, 0); 715} 716 717/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 718/// special functions, such as the default constructor, copy 719/// constructor, or destructor, to the given C++ class (C++ 720/// [special]p1). This routine can only be executed just before the 721/// definition of the class is complete. 722void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 723 QualType ClassType = Context.getTypeDeclType(ClassDecl); 724 ClassType = Context.getCanonicalType(ClassType); 725 726 if (!ClassDecl->hasUserDeclaredConstructor()) { 727 // C++ [class.ctor]p5: 728 // A default constructor for a class X is a constructor of class X 729 // that can be called without an argument. If there is no 730 // user-declared constructor for class X, a default constructor is 731 // implicitly declared. An implicitly-declared default constructor 732 // is an inline public member of its class. 733 DeclarationName Name 734 = Context.DeclarationNames.getCXXConstructorName(ClassType); 735 CXXConstructorDecl *DefaultCon = 736 CXXConstructorDecl::Create(Context, ClassDecl, 737 ClassDecl->getLocation(), Name, 738 Context.getFunctionType(Context.VoidTy, 739 0, 0, false, 0), 740 /*isExplicit=*/false, 741 /*isInline=*/true, 742 /*isImplicitlyDeclared=*/true); 743 DefaultCon->setAccess(AS_public); 744 ClassDecl->addConstructor(Context, DefaultCon); 745 } 746 747 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 748 // C++ [class.copy]p4: 749 // If the class definition does not explicitly declare a copy 750 // constructor, one is declared implicitly. 751 752 // C++ [class.copy]p5: 753 // The implicitly-declared copy constructor for a class X will 754 // have the form 755 // 756 // X::X(const X&) 757 // 758 // if 759 bool HasConstCopyConstructor = true; 760 761 // -- each direct or virtual base class B of X has a copy 762 // constructor whose first parameter is of type const B& or 763 // const volatile B&, and 764 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 765 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 766 const CXXRecordDecl *BaseClassDecl 767 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl()); 768 HasConstCopyConstructor 769 = BaseClassDecl->hasConstCopyConstructor(Context); 770 } 771 772 // -- for all the nonstatic data members of X that are of a 773 // class type M (or array thereof), each such class type 774 // has a copy constructor whose first parameter is of type 775 // const M& or const volatile M&. 776 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 777 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) { 778 QualType FieldType = (*Field)->getType(); 779 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 780 FieldType = Array->getElementType(); 781 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) { 782 const CXXRecordDecl *FieldClassDecl 783 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 784 HasConstCopyConstructor 785 = FieldClassDecl->hasConstCopyConstructor(Context); 786 } 787 } 788 789 // Otherwise, the implicitly declared copy constructor will have 790 // the form 791 // 792 // X::X(X&) 793 QualType ArgType = Context.getTypeDeclType(ClassDecl); 794 if (HasConstCopyConstructor) 795 ArgType = ArgType.withConst(); 796 ArgType = Context.getReferenceType(ArgType); 797 798 // An implicitly-declared copy constructor is an inline public 799 // member of its class. 800 DeclarationName Name 801 = Context.DeclarationNames.getCXXConstructorName(ClassType); 802 CXXConstructorDecl *CopyConstructor 803 = CXXConstructorDecl::Create(Context, ClassDecl, 804 ClassDecl->getLocation(), Name, 805 Context.getFunctionType(Context.VoidTy, 806 &ArgType, 1, 807 false, 0), 808 /*isExplicit=*/false, 809 /*isInline=*/true, 810 /*isImplicitlyDeclared=*/true); 811 CopyConstructor->setAccess(AS_public); 812 813 // Add the parameter to the constructor. 814 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 815 ClassDecl->getLocation(), 816 /*IdentifierInfo=*/0, 817 ArgType, VarDecl::None, 0, 0); 818 CopyConstructor->setParams(&FromParam, 1); 819 820 ClassDecl->addConstructor(Context, CopyConstructor); 821 } 822 823 if (!ClassDecl->getDestructor()) { 824 // C++ [class.dtor]p2: 825 // If a class has no user-declared destructor, a destructor is 826 // declared implicitly. An implicitly-declared destructor is an 827 // inline public member of its class. 828 DeclarationName Name 829 = Context.DeclarationNames.getCXXDestructorName(ClassType); 830 CXXDestructorDecl *Destructor 831 = CXXDestructorDecl::Create(Context, ClassDecl, 832 ClassDecl->getLocation(), Name, 833 Context.getFunctionType(Context.VoidTy, 834 0, 0, false, 0), 835 /*isInline=*/true, 836 /*isImplicitlyDeclared=*/true); 837 Destructor->setAccess(AS_public); 838 ClassDecl->setDestructor(Destructor); 839 } 840 841 // FIXME: Implicit copy assignment operator 842} 843 844void Sema::ActOnFinishCXXClassDef(DeclTy *D) { 845 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D)); 846 FieldCollector->FinishClass(); 847 AddImplicitlyDeclaredMembersToClass(Rec); 848 PopDeclContext(); 849 850 // Everything, including inline method definitions, have been parsed. 851 // Let the consumer know of the new TagDecl definition. 852 Consumer.HandleTagDeclDefinition(Rec); 853} 854 855/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 856/// the well-formednes of the constructor declarator @p D with type @p 857/// R. If there are any errors in the declarator, this routine will 858/// emit diagnostics and return true. Otherwise, it will return 859/// false. Either way, the type @p R will be updated to reflect a 860/// well-formed type for the constructor. 861bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R, 862 FunctionDecl::StorageClass& SC) { 863 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 864 bool isInvalid = false; 865 866 // C++ [class.ctor]p3: 867 // A constructor shall not be virtual (10.3) or static (9.4). A 868 // constructor can be invoked for a const, volatile or const 869 // volatile object. A constructor shall not be declared const, 870 // volatile, or const volatile (9.3.2). 871 if (isVirtual) { 872 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 873 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 874 << SourceRange(D.getIdentifierLoc()); 875 isInvalid = true; 876 } 877 if (SC == FunctionDecl::Static) { 878 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 879 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 880 << SourceRange(D.getIdentifierLoc()); 881 isInvalid = true; 882 SC = FunctionDecl::None; 883 } 884 if (D.getDeclSpec().hasTypeSpecifier()) { 885 // Constructors don't have return types, but the parser will 886 // happily parse something like: 887 // 888 // class X { 889 // float X(float); 890 // }; 891 // 892 // The return type will be eliminated later. 893 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 894 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 895 << SourceRange(D.getIdentifierLoc()); 896 } 897 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) { 898 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 899 if (FTI.TypeQuals & QualType::Const) 900 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 901 << "const" << SourceRange(D.getIdentifierLoc()); 902 if (FTI.TypeQuals & QualType::Volatile) 903 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 904 << "volatile" << SourceRange(D.getIdentifierLoc()); 905 if (FTI.TypeQuals & QualType::Restrict) 906 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor) 907 << "restrict" << SourceRange(D.getIdentifierLoc()); 908 } 909 910 // Rebuild the function type "R" without any type qualifiers (in 911 // case any of the errors above fired) and with "void" as the 912 // return type, since constructors don't have return types. We 913 // *always* have to do this, because GetTypeForDeclarator will 914 // put in a result type of "int" when none was specified. 915 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto(); 916 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 917 Proto->getNumArgs(), 918 Proto->isVariadic(), 919 0); 920 921 return isInvalid; 922} 923 924/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 925/// the well-formednes of the destructor declarator @p D with type @p 926/// R. If there are any errors in the declarator, this routine will 927/// emit diagnostics and return true. Otherwise, it will return 928/// false. Either way, the type @p R will be updated to reflect a 929/// well-formed type for the destructor. 930bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R, 931 FunctionDecl::StorageClass& SC) { 932 bool isInvalid = false; 933 934 // C++ [class.dtor]p1: 935 // [...] A typedef-name that names a class is a class-name 936 // (7.1.3); however, a typedef-name that names a class shall not 937 // be used as the identifier in the declarator for a destructor 938 // declaration. 939 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType(); 940 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) { 941 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 942 << TypedefD->getName(); 943 isInvalid = true; 944 } 945 946 // C++ [class.dtor]p2: 947 // A destructor is used to destroy objects of its class type. A 948 // destructor takes no parameters, and no return type can be 949 // specified for it (not even void). The address of a destructor 950 // shall not be taken. A destructor shall not be static. A 951 // destructor can be invoked for a const, volatile or const 952 // volatile object. A destructor shall not be declared const, 953 // volatile or const volatile (9.3.2). 954 if (SC == FunctionDecl::Static) { 955 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 956 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 957 << SourceRange(D.getIdentifierLoc()); 958 isInvalid = true; 959 SC = FunctionDecl::None; 960 } 961 if (D.getDeclSpec().hasTypeSpecifier()) { 962 // Destructors don't have return types, but the parser will 963 // happily parse something like: 964 // 965 // class X { 966 // float ~X(); 967 // }; 968 // 969 // The return type will be eliminated later. 970 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 971 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 972 << SourceRange(D.getIdentifierLoc()); 973 } 974 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) { 975 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 976 if (FTI.TypeQuals & QualType::Const) 977 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 978 << "const" << SourceRange(D.getIdentifierLoc()); 979 if (FTI.TypeQuals & QualType::Volatile) 980 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 981 << "volatile" << SourceRange(D.getIdentifierLoc()); 982 if (FTI.TypeQuals & QualType::Restrict) 983 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor) 984 << "restrict" << SourceRange(D.getIdentifierLoc()); 985 } 986 987 // Make sure we don't have any parameters. 988 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) { 989 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 990 991 // Delete the parameters. 992 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 993 if (FTI.NumArgs) { 994 delete [] FTI.ArgInfo; 995 FTI.NumArgs = 0; 996 FTI.ArgInfo = 0; 997 } 998 } 999 1000 // Make sure the destructor isn't variadic. 1001 if (R->getAsFunctionTypeProto()->isVariadic()) 1002 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 1003 1004 // Rebuild the function type "R" without any type qualifiers or 1005 // parameters (in case any of the errors above fired) and with 1006 // "void" as the return type, since destructors don't have return 1007 // types. We *always* have to do this, because GetTypeForDeclarator 1008 // will put in a result type of "int" when none was specified. 1009 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0); 1010 1011 return isInvalid; 1012} 1013 1014/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 1015/// well-formednes of the conversion function declarator @p D with 1016/// type @p R. If there are any errors in the declarator, this routine 1017/// will emit diagnostics and return true. Otherwise, it will return 1018/// false. Either way, the type @p R will be updated to reflect a 1019/// well-formed type for the conversion operator. 1020bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 1021 FunctionDecl::StorageClass& SC) { 1022 bool isInvalid = false; 1023 1024 // C++ [class.conv.fct]p1: 1025 // Neither parameter types nor return type can be specified. The 1026 // type of a conversion function (8.3.5) is “function taking no 1027 // parameter returning conversion-type-id.” 1028 if (SC == FunctionDecl::Static) { 1029 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 1030 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 1031 << SourceRange(D.getIdentifierLoc()); 1032 isInvalid = true; 1033 SC = FunctionDecl::None; 1034 } 1035 if (D.getDeclSpec().hasTypeSpecifier()) { 1036 // Conversion functions don't have return types, but the parser will 1037 // happily parse something like: 1038 // 1039 // class X { 1040 // float operator bool(); 1041 // }; 1042 // 1043 // The return type will be changed later anyway. 1044 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 1045 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 1046 << SourceRange(D.getIdentifierLoc()); 1047 } 1048 1049 // Make sure we don't have any parameters. 1050 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) { 1051 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 1052 1053 // Delete the parameters. 1054 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1055 if (FTI.NumArgs) { 1056 delete [] FTI.ArgInfo; 1057 FTI.NumArgs = 0; 1058 FTI.ArgInfo = 0; 1059 } 1060 } 1061 1062 // Make sure the conversion function isn't variadic. 1063 if (R->getAsFunctionTypeProto()->isVariadic()) 1064 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 1065 1066 // C++ [class.conv.fct]p4: 1067 // The conversion-type-id shall not represent a function type nor 1068 // an array type. 1069 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType()); 1070 if (ConvType->isArrayType()) { 1071 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 1072 ConvType = Context.getPointerType(ConvType); 1073 } else if (ConvType->isFunctionType()) { 1074 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 1075 ConvType = Context.getPointerType(ConvType); 1076 } 1077 1078 // Rebuild the function type "R" without any parameters (in case any 1079 // of the errors above fired) and with the conversion type as the 1080 // return type. 1081 R = Context.getFunctionType(ConvType, 0, 0, false, 1082 R->getAsFunctionTypeProto()->getTypeQuals()); 1083 1084 return isInvalid; 1085} 1086 1087/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete 1088/// the declaration of the given C++ constructor ConDecl that was 1089/// built from declarator D. This routine is responsible for checking 1090/// that the newly-created constructor declaration is well-formed and 1091/// for recording it in the C++ class. Example: 1092/// 1093/// @code 1094/// class X { 1095/// X(); // X::X() will be the ConDecl. 1096/// }; 1097/// @endcode 1098Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) { 1099 assert(ConDecl && "Expected to receive a constructor declaration"); 1100 1101 // Check default arguments on the constructor 1102 CheckCXXDefaultArguments(ConDecl); 1103 1104 CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1105 if (!ClassDecl) { 1106 ConDecl->setInvalidDecl(); 1107 return ConDecl; 1108 } 1109 1110 // Make sure this constructor is an overload of the existing 1111 // constructors. 1112 OverloadedFunctionDecl::function_iterator MatchedDecl; 1113 if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) { 1114 Diag(ConDecl->getLocation(), diag::err_constructor_redeclared) 1115 << SourceRange(ConDecl->getLocation()); 1116 Diag((*MatchedDecl)->getLocation(), diag::err_previous_declaration) 1117 << SourceRange((*MatchedDecl)->getLocation()); 1118 ConDecl->setInvalidDecl(); 1119 return ConDecl; 1120 } 1121 1122 1123 // C++ [class.copy]p3: 1124 // A declaration of a constructor for a class X is ill-formed if 1125 // its first parameter is of type (optionally cv-qualified) X and 1126 // either there are no other parameters or else all other 1127 // parameters have default arguments. 1128 if ((ConDecl->getNumParams() == 1) || 1129 (ConDecl->getNumParams() > 1 && 1130 ConDecl->getParamDecl(1)->getDefaultArg() != 0)) { 1131 QualType ParamType = ConDecl->getParamDecl(0)->getType(); 1132 QualType ClassTy = Context.getTagDeclType( 1133 const_cast<CXXRecordDecl*>(ConDecl->getParent())); 1134 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 1135 Diag(ConDecl->getLocation(), diag::err_constructor_byvalue_arg) 1136 << SourceRange(ConDecl->getParamDecl(0)->getLocation()); 1137 ConDecl->setInvalidDecl(); 1138 return ConDecl; 1139 } 1140 } 1141 1142 // Add this constructor to the set of constructors of the current 1143 // class. 1144 ClassDecl->addConstructor(Context, ConDecl); 1145 return (DeclTy *)ConDecl; 1146} 1147 1148/// ActOnDestructorDeclarator - Called by ActOnDeclarator to complete 1149/// the declaration of the given C++ @p Destructor. This routine is 1150/// responsible for recording the destructor in the C++ class, if 1151/// possible. 1152Sema::DeclTy *Sema::ActOnDestructorDeclarator(CXXDestructorDecl *Destructor) { 1153 assert(Destructor && "Expected to receive a destructor declaration"); 1154 1155 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext); 1156 1157 // Make sure we aren't redeclaring the destructor. 1158 if (CXXDestructorDecl *PrevDestructor = ClassDecl->getDestructor()) { 1159 Diag(Destructor->getLocation(), diag::err_destructor_redeclared); 1160 Diag(PrevDestructor->getLocation(), 1161 PrevDestructor->isThisDeclarationADefinition()? 1162 diag::err_previous_definition 1163 : diag::err_previous_declaration); 1164 Destructor->setInvalidDecl(); 1165 return Destructor; 1166 } 1167 1168 ClassDecl->setDestructor(Destructor); 1169 return (DeclTy *)Destructor; 1170} 1171 1172/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 1173/// the declaration of the given C++ conversion function. This routine 1174/// is responsible for recording the conversion function in the C++ 1175/// class, if possible. 1176Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 1177 assert(Conversion && "Expected to receive a conversion function declaration"); 1178 1179 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext); 1180 1181 // Make sure we aren't redeclaring the conversion function. 1182 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 1183 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions(); 1184 for (OverloadedFunctionDecl::function_iterator Func 1185 = Conversions->function_begin(); 1186 Func != Conversions->function_end(); ++Func) { 1187 CXXConversionDecl *OtherConv = cast<CXXConversionDecl>(*Func); 1188 if (ConvType == Context.getCanonicalType(OtherConv->getConversionType())) { 1189 Diag(Conversion->getLocation(), diag::err_conv_function_redeclared); 1190 Diag(OtherConv->getLocation(), 1191 OtherConv->isThisDeclarationADefinition()? 1192 diag::err_previous_definition 1193 : diag::err_previous_declaration); 1194 Conversion->setInvalidDecl(); 1195 return (DeclTy *)Conversion; 1196 } 1197 } 1198 1199 // C++ [class.conv.fct]p1: 1200 // [...] A conversion function is never used to convert a 1201 // (possibly cv-qualified) object to the (possibly cv-qualified) 1202 // same object type (or a reference to it), to a (possibly 1203 // cv-qualified) base class of that type (or a reference to it), 1204 // or to (possibly cv-qualified) void. 1205 // FIXME: Suppress this warning if the conversion function ends up 1206 // being a virtual function that overrides a virtual function in a 1207 // base class. 1208 QualType ClassType 1209 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 1210 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType()) 1211 ConvType = ConvTypeRef->getPointeeType(); 1212 if (ConvType->isRecordType()) { 1213 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 1214 if (ConvType == ClassType) 1215 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used, 1216 ClassType.getAsString()); 1217 else if (IsDerivedFrom(ClassType, ConvType)) 1218 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used, 1219 ClassType.getAsString(), 1220 ConvType.getAsString()); 1221 } else if (ConvType->isVoidType()) { 1222 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used, 1223 ClassType.getAsString(), ConvType.getAsString()); 1224 } 1225 1226 ClassDecl->addConversionFunction(Context, Conversion); 1227 1228 return (DeclTy *)Conversion; 1229} 1230 1231//===----------------------------------------------------------------------===// 1232// Namespace Handling 1233//===----------------------------------------------------------------------===// 1234 1235/// ActOnStartNamespaceDef - This is called at the start of a namespace 1236/// definition. 1237Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 1238 SourceLocation IdentLoc, 1239 IdentifierInfo *II, 1240 SourceLocation LBrace) { 1241 NamespaceDecl *Namespc = 1242 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 1243 Namespc->setLBracLoc(LBrace); 1244 1245 Scope *DeclRegionScope = NamespcScope->getParent(); 1246 1247 if (II) { 1248 // C++ [namespace.def]p2: 1249 // The identifier in an original-namespace-definition shall not have been 1250 // previously defined in the declarative region in which the 1251 // original-namespace-definition appears. The identifier in an 1252 // original-namespace-definition is the name of the namespace. Subsequently 1253 // in that declarative region, it is treated as an original-namespace-name. 1254 1255 Decl *PrevDecl = 1256 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 0, 1257 /*enableLazyBuiltinCreation=*/false); 1258 1259 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) { 1260 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) { 1261 // This is an extended namespace definition. 1262 // Attach this namespace decl to the chain of extended namespace 1263 // definitions. 1264 NamespaceDecl *NextNS = OrigNS; 1265 while (NextNS->getNextNamespace()) 1266 NextNS = NextNS->getNextNamespace(); 1267 1268 NextNS->setNextNamespace(Namespc); 1269 Namespc->setOriginalNamespace(OrigNS); 1270 1271 // We won't add this decl to the current scope. We want the namespace 1272 // name to return the original namespace decl during a name lookup. 1273 } else { 1274 // This is an invalid name redefinition. 1275 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind, 1276 Namespc->getName()); 1277 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 1278 Namespc->setInvalidDecl(); 1279 // Continue on to push Namespc as current DeclContext and return it. 1280 } 1281 } else { 1282 // This namespace name is declared for the first time. 1283 PushOnScopeChains(Namespc, DeclRegionScope); 1284 } 1285 } 1286 else { 1287 // FIXME: Handle anonymous namespaces 1288 } 1289 1290 // Although we could have an invalid decl (i.e. the namespace name is a 1291 // redefinition), push it as current DeclContext and try to continue parsing. 1292 PushDeclContext(Namespc->getOriginalNamespace()); 1293 return Namespc; 1294} 1295 1296/// ActOnFinishNamespaceDef - This callback is called after a namespace is 1297/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 1298void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) { 1299 Decl *Dcl = static_cast<Decl *>(D); 1300 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 1301 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 1302 Namespc->setRBracLoc(RBrace); 1303 PopDeclContext(); 1304} 1305 1306 1307/// AddCXXDirectInitializerToDecl - This action is called immediately after 1308/// ActOnDeclarator, when a C++ direct initializer is present. 1309/// e.g: "int x(1);" 1310void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc, 1311 ExprTy **ExprTys, unsigned NumExprs, 1312 SourceLocation *CommaLocs, 1313 SourceLocation RParenLoc) { 1314 assert(NumExprs != 0 && ExprTys && "missing expressions"); 1315 Decl *RealDecl = static_cast<Decl *>(Dcl); 1316 1317 // If there is no declaration, there was an error parsing it. Just ignore 1318 // the initializer. 1319 if (RealDecl == 0) { 1320 for (unsigned i = 0; i != NumExprs; ++i) 1321 delete static_cast<Expr *>(ExprTys[i]); 1322 return; 1323 } 1324 1325 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 1326 if (!VDecl) { 1327 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 1328 RealDecl->setInvalidDecl(); 1329 return; 1330 } 1331 1332 // We will treat direct-initialization as a copy-initialization: 1333 // int x(1); -as-> int x = 1; 1334 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 1335 // 1336 // Clients that want to distinguish between the two forms, can check for 1337 // direct initializer using VarDecl::hasCXXDirectInitializer(). 1338 // A major benefit is that clients that don't particularly care about which 1339 // exactly form was it (like the CodeGen) can handle both cases without 1340 // special case code. 1341 1342 // C++ 8.5p11: 1343 // The form of initialization (using parentheses or '=') is generally 1344 // insignificant, but does matter when the entity being initialized has a 1345 // class type. 1346 QualType DeclInitType = VDecl->getType(); 1347 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 1348 DeclInitType = Array->getElementType(); 1349 1350 if (VDecl->getType()->isRecordType()) { 1351 CXXConstructorDecl *Constructor 1352 = PerformInitializationByConstructor(DeclInitType, 1353 (Expr **)ExprTys, NumExprs, 1354 VDecl->getLocation(), 1355 SourceRange(VDecl->getLocation(), 1356 RParenLoc), 1357 VDecl->getName(), 1358 IK_Direct); 1359 if (!Constructor) { 1360 RealDecl->setInvalidDecl(); 1361 } 1362 1363 // Let clients know that initialization was done with a direct 1364 // initializer. 1365 VDecl->setCXXDirectInitializer(true); 1366 1367 // FIXME: Add ExprTys and Constructor to the RealDecl as part of 1368 // the initializer. 1369 return; 1370 } 1371 1372 if (NumExprs > 1) { 1373 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg) 1374 << SourceRange(VDecl->getLocation(), RParenLoc); 1375 RealDecl->setInvalidDecl(); 1376 return; 1377 } 1378 1379 // Let clients know that initialization was done with a direct initializer. 1380 VDecl->setCXXDirectInitializer(true); 1381 1382 assert(NumExprs == 1 && "Expected 1 expression"); 1383 // Set the init expression, handles conversions. 1384 AddInitializerToDecl(Dcl, ExprTys[0]); 1385} 1386 1387/// PerformInitializationByConstructor - Perform initialization by 1388/// constructor (C++ [dcl.init]p14), which may occur as part of 1389/// direct-initialization or copy-initialization. We are initializing 1390/// an object of type @p ClassType with the given arguments @p 1391/// Args. @p Loc is the location in the source code where the 1392/// initializer occurs (e.g., a declaration, member initializer, 1393/// functional cast, etc.) while @p Range covers the whole 1394/// initialization. @p InitEntity is the entity being initialized, 1395/// which may by the name of a declaration or a type. @p Kind is the 1396/// kind of initialization we're performing, which affects whether 1397/// explicit constructors will be considered. When successful, returns 1398/// the constructor that will be used to perform the initialization; 1399/// when the initialization fails, emits a diagnostic and returns 1400/// null. 1401CXXConstructorDecl * 1402Sema::PerformInitializationByConstructor(QualType ClassType, 1403 Expr **Args, unsigned NumArgs, 1404 SourceLocation Loc, SourceRange Range, 1405 std::string InitEntity, 1406 InitializationKind Kind) { 1407 const RecordType *ClassRec = ClassType->getAsRecordType(); 1408 assert(ClassRec && "Can only initialize a class type here"); 1409 1410 // C++ [dcl.init]p14: 1411 // 1412 // If the initialization is direct-initialization, or if it is 1413 // copy-initialization where the cv-unqualified version of the 1414 // source type is the same class as, or a derived class of, the 1415 // class of the destination, constructors are considered. The 1416 // applicable constructors are enumerated (13.3.1.3), and the 1417 // best one is chosen through overload resolution (13.3). The 1418 // constructor so selected is called to initialize the object, 1419 // with the initializer expression(s) as its argument(s). If no 1420 // constructor applies, or the overload resolution is ambiguous, 1421 // the initialization is ill-formed. 1422 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 1423 OverloadCandidateSet CandidateSet; 1424 1425 // Add constructors to the overload set. 1426 OverloadedFunctionDecl *Constructors 1427 = const_cast<OverloadedFunctionDecl *>(ClassDecl->getConstructors()); 1428 for (OverloadedFunctionDecl::function_iterator Con 1429 = Constructors->function_begin(); 1430 Con != Constructors->function_end(); ++Con) { 1431 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 1432 if ((Kind == IK_Direct) || 1433 (Kind == IK_Copy && Constructor->isConvertingConstructor()) || 1434 (Kind == IK_Default && Constructor->isDefaultConstructor())) 1435 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet); 1436 } 1437 1438 OverloadCandidateSet::iterator Best; 1439 switch (BestViableFunction(CandidateSet, Best)) { 1440 case OR_Success: 1441 // We found a constructor. Return it. 1442 return cast<CXXConstructorDecl>(Best->Function); 1443 1444 case OR_No_Viable_Function: 1445 if (CandidateSet.empty()) 1446 Diag(Loc, diag::err_ovl_no_viable_function_in_init, 1447 InitEntity, Range); 1448 else { 1449 Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands, 1450 InitEntity, Range); 1451 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 1452 } 1453 return 0; 1454 1455 case OR_Ambiguous: 1456 Diag(Loc, diag::err_ovl_ambiguous_init, 1457 InitEntity, Range); 1458 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1459 return 0; 1460 } 1461 1462 return 0; 1463} 1464 1465/// CompareReferenceRelationship - Compare the two types T1 and T2 to 1466/// determine whether they are reference-related, 1467/// reference-compatible, reference-compatible with added 1468/// qualification, or incompatible, for use in C++ initialization by 1469/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 1470/// type, and the first type (T1) is the pointee type of the reference 1471/// type being initialized. 1472Sema::ReferenceCompareResult 1473Sema::CompareReferenceRelationship(QualType T1, QualType T2, 1474 bool& DerivedToBase) { 1475 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type"); 1476 assert(!T2->isReferenceType() && "T2 cannot be a reference type"); 1477 1478 T1 = Context.getCanonicalType(T1); 1479 T2 = Context.getCanonicalType(T2); 1480 QualType UnqualT1 = T1.getUnqualifiedType(); 1481 QualType UnqualT2 = T2.getUnqualifiedType(); 1482 1483 // C++ [dcl.init.ref]p4: 1484 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is 1485 // reference-related to “cv2 T2” if T1 is the same type as T2, or 1486 // T1 is a base class of T2. 1487 if (UnqualT1 == UnqualT2) 1488 DerivedToBase = false; 1489 else if (IsDerivedFrom(UnqualT2, UnqualT1)) 1490 DerivedToBase = true; 1491 else 1492 return Ref_Incompatible; 1493 1494 // At this point, we know that T1 and T2 are reference-related (at 1495 // least). 1496 1497 // C++ [dcl.init.ref]p4: 1498 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is 1499 // reference-related to T2 and cv1 is the same cv-qualification 1500 // as, or greater cv-qualification than, cv2. For purposes of 1501 // overload resolution, cases for which cv1 is greater 1502 // cv-qualification than cv2 are identified as 1503 // reference-compatible with added qualification (see 13.3.3.2). 1504 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 1505 return Ref_Compatible; 1506 else if (T1.isMoreQualifiedThan(T2)) 1507 return Ref_Compatible_With_Added_Qualification; 1508 else 1509 return Ref_Related; 1510} 1511 1512/// CheckReferenceInit - Check the initialization of a reference 1513/// variable with the given initializer (C++ [dcl.init.ref]). Init is 1514/// the initializer (either a simple initializer or an initializer 1515/// list), and DeclType is the type of the declaration. When ICS is 1516/// non-null, this routine will compute the implicit conversion 1517/// sequence according to C++ [over.ics.ref] and will not produce any 1518/// diagnostics; when ICS is null, it will emit diagnostics when any 1519/// errors are found. Either way, a return value of true indicates 1520/// that there was a failure, a return value of false indicates that 1521/// the reference initialization succeeded. 1522/// 1523/// When @p SuppressUserConversions, user-defined conversions are 1524/// suppressed. 1525bool 1526Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType, 1527 ImplicitConversionSequence *ICS, 1528 bool SuppressUserConversions) { 1529 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 1530 1531 QualType T1 = DeclType->getAsReferenceType()->getPointeeType(); 1532 QualType T2 = Init->getType(); 1533 1534 // If the initializer is the address of an overloaded function, try 1535 // to resolve the overloaded function. If all goes well, T2 is the 1536 // type of the resulting function. 1537 if (T2->isOverloadType()) { 1538 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType, 1539 ICS != 0); 1540 if (Fn) { 1541 // Since we're performing this reference-initialization for 1542 // real, update the initializer with the resulting function. 1543 if (!ICS) 1544 FixOverloadedFunctionReference(Init, Fn); 1545 1546 T2 = Fn->getType(); 1547 } 1548 } 1549 1550 // Compute some basic properties of the types and the initializer. 1551 bool DerivedToBase = false; 1552 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context); 1553 ReferenceCompareResult RefRelationship 1554 = CompareReferenceRelationship(T1, T2, DerivedToBase); 1555 1556 // Most paths end in a failed conversion. 1557 if (ICS) 1558 ICS->ConversionKind = ImplicitConversionSequence::BadConversion; 1559 1560 // C++ [dcl.init.ref]p5: 1561 // A reference to type “cv1 T1” is initialized by an expression 1562 // of type “cv2 T2” as follows: 1563 1564 // -- If the initializer expression 1565 1566 bool BindsDirectly = false; 1567 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is 1568 // reference-compatible with “cv2 T2,” or 1569 // 1570 // Note that the bit-field check is skipped if we are just computing 1571 // the implicit conversion sequence (C++ [over.best.ics]p2). 1572 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) && 1573 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 1574 BindsDirectly = true; 1575 1576 if (ICS) { 1577 // C++ [over.ics.ref]p1: 1578 // When a parameter of reference type binds directly (8.5.3) 1579 // to an argument expression, the implicit conversion sequence 1580 // is the identity conversion, unless the argument expression 1581 // has a type that is a derived class of the parameter type, 1582 // in which case the implicit conversion sequence is a 1583 // derived-to-base Conversion (13.3.3.1). 1584 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 1585 ICS->Standard.First = ICK_Identity; 1586 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 1587 ICS->Standard.Third = ICK_Identity; 1588 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 1589 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 1590 ICS->Standard.ReferenceBinding = true; 1591 ICS->Standard.DirectBinding = true; 1592 1593 // Nothing more to do: the inaccessibility/ambiguity check for 1594 // derived-to-base conversions is suppressed when we're 1595 // computing the implicit conversion sequence (C++ 1596 // [over.best.ics]p2). 1597 return false; 1598 } else { 1599 // Perform the conversion. 1600 // FIXME: Binding to a subobject of the lvalue is going to require 1601 // more AST annotation than this. 1602 ImpCastExprToType(Init, T1, /*isLvalue=*/true); 1603 } 1604 } 1605 1606 // -- has a class type (i.e., T2 is a class type) and can be 1607 // implicitly converted to an lvalue of type “cv3 T3,” 1608 // where “cv1 T1” is reference-compatible with “cv3 T3” 1609 // 92) (this conversion is selected by enumerating the 1610 // applicable conversion functions (13.3.1.6) and choosing 1611 // the best one through overload resolution (13.3)), 1612 if (!SuppressUserConversions && T2->isRecordType()) { 1613 // FIXME: Look for conversions in base classes! 1614 CXXRecordDecl *T2RecordDecl 1615 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl()); 1616 1617 OverloadCandidateSet CandidateSet; 1618 OverloadedFunctionDecl *Conversions 1619 = T2RecordDecl->getConversionFunctions(); 1620 for (OverloadedFunctionDecl::function_iterator Func 1621 = Conversions->function_begin(); 1622 Func != Conversions->function_end(); ++Func) { 1623 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 1624 1625 // If the conversion function doesn't return a reference type, 1626 // it can't be considered for this conversion. 1627 // FIXME: This will change when we support rvalue references. 1628 if (Conv->getConversionType()->isReferenceType()) 1629 AddConversionCandidate(Conv, Init, DeclType, CandidateSet); 1630 } 1631 1632 OverloadCandidateSet::iterator Best; 1633 switch (BestViableFunction(CandidateSet, Best)) { 1634 case OR_Success: 1635 // This is a direct binding. 1636 BindsDirectly = true; 1637 1638 if (ICS) { 1639 // C++ [over.ics.ref]p1: 1640 // 1641 // [...] If the parameter binds directly to the result of 1642 // applying a conversion function to the argument 1643 // expression, the implicit conversion sequence is a 1644 // user-defined conversion sequence (13.3.3.1.2), with the 1645 // second standard conversion sequence either an identity 1646 // conversion or, if the conversion function returns an 1647 // entity of a type that is a derived class of the parameter 1648 // type, a derived-to-base Conversion. 1649 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion; 1650 ICS->UserDefined.Before = Best->Conversions[0].Standard; 1651 ICS->UserDefined.After = Best->FinalConversion; 1652 ICS->UserDefined.ConversionFunction = Best->Function; 1653 assert(ICS->UserDefined.After.ReferenceBinding && 1654 ICS->UserDefined.After.DirectBinding && 1655 "Expected a direct reference binding!"); 1656 return false; 1657 } else { 1658 // Perform the conversion. 1659 // FIXME: Binding to a subobject of the lvalue is going to require 1660 // more AST annotation than this. 1661 ImpCastExprToType(Init, T1, /*isLvalue=*/true); 1662 } 1663 break; 1664 1665 case OR_Ambiguous: 1666 assert(false && "Ambiguous reference binding conversions not implemented."); 1667 return true; 1668 1669 case OR_No_Viable_Function: 1670 // There was no suitable conversion; continue with other checks. 1671 break; 1672 } 1673 } 1674 1675 if (BindsDirectly) { 1676 // C++ [dcl.init.ref]p4: 1677 // [...] In all cases where the reference-related or 1678 // reference-compatible relationship of two types is used to 1679 // establish the validity of a reference binding, and T1 is a 1680 // base class of T2, a program that necessitates such a binding 1681 // is ill-formed if T1 is an inaccessible (clause 11) or 1682 // ambiguous (10.2) base class of T2. 1683 // 1684 // Note that we only check this condition when we're allowed to 1685 // complain about errors, because we should not be checking for 1686 // ambiguity (or inaccessibility) unless the reference binding 1687 // actually happens. 1688 if (DerivedToBase) 1689 return CheckDerivedToBaseConversion(T2, T1, 1690 Init->getSourceRange().getBegin(), 1691 Init->getSourceRange()); 1692 else 1693 return false; 1694 } 1695 1696 // -- Otherwise, the reference shall be to a non-volatile const 1697 // type (i.e., cv1 shall be const). 1698 if (T1.getCVRQualifiers() != QualType::Const) { 1699 if (!ICS) 1700 Diag(Init->getSourceRange().getBegin(), 1701 diag::err_not_reference_to_const_init) 1702 << T1.getAsString() 1703 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 1704 << T2.getAsString() << Init->getSourceRange(); 1705 return true; 1706 } 1707 1708 // -- If the initializer expression is an rvalue, with T2 a 1709 // class type, and “cv1 T1” is reference-compatible with 1710 // “cv2 T2,” the reference is bound in one of the 1711 // following ways (the choice is implementation-defined): 1712 // 1713 // -- The reference is bound to the object represented by 1714 // the rvalue (see 3.10) or to a sub-object within that 1715 // object. 1716 // 1717 // -- A temporary of type “cv1 T2” [sic] is created, and 1718 // a constructor is called to copy the entire rvalue 1719 // object into the temporary. The reference is bound to 1720 // the temporary or to a sub-object within the 1721 // temporary. 1722 // 1723 // 1724 // The constructor that would be used to make the copy 1725 // shall be callable whether or not the copy is actually 1726 // done. 1727 // 1728 // Note that C++0x [dcl.ref.init]p5 takes away this implementation 1729 // freedom, so we will always take the first option and never build 1730 // a temporary in this case. FIXME: We will, however, have to check 1731 // for the presence of a copy constructor in C++98/03 mode. 1732 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() && 1733 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 1734 if (ICS) { 1735 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 1736 ICS->Standard.First = ICK_Identity; 1737 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 1738 ICS->Standard.Third = ICK_Identity; 1739 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 1740 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 1741 ICS->Standard.ReferenceBinding = true; 1742 ICS->Standard.DirectBinding = false; 1743 } else { 1744 // FIXME: Binding to a subobject of the rvalue is going to require 1745 // more AST annotation than this. 1746 ImpCastExprToType(Init, T1, /*isLvalue=*/true); 1747 } 1748 return false; 1749 } 1750 1751 // -- Otherwise, a temporary of type “cv1 T1” is created and 1752 // initialized from the initializer expression using the 1753 // rules for a non-reference copy initialization (8.5). The 1754 // reference is then bound to the temporary. If T1 is 1755 // reference-related to T2, cv1 must be the same 1756 // cv-qualification as, or greater cv-qualification than, 1757 // cv2; otherwise, the program is ill-formed. 1758 if (RefRelationship == Ref_Related) { 1759 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 1760 // we would be reference-compatible or reference-compatible with 1761 // added qualification. But that wasn't the case, so the reference 1762 // initialization fails. 1763 if (!ICS) 1764 Diag(Init->getSourceRange().getBegin(), 1765 diag::err_reference_init_drops_quals) 1766 << T1.getAsString() 1767 << (InitLvalue != Expr::LV_Valid? "temporary" : "value") 1768 << T2.getAsString() << Init->getSourceRange(); 1769 return true; 1770 } 1771 1772 // Actually try to convert the initializer to T1. 1773 if (ICS) { 1774 /// C++ [over.ics.ref]p2: 1775 /// 1776 /// When a parameter of reference type is not bound directly to 1777 /// an argument expression, the conversion sequence is the one 1778 /// required to convert the argument expression to the 1779 /// underlying type of the reference according to 1780 /// 13.3.3.1. Conceptually, this conversion sequence corresponds 1781 /// to copy-initializing a temporary of the underlying type with 1782 /// the argument expression. Any difference in top-level 1783 /// cv-qualification is subsumed by the initialization itself 1784 /// and does not constitute a conversion. 1785 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions); 1786 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion; 1787 } else { 1788 return PerformImplicitConversion(Init, T1); 1789 } 1790} 1791 1792/// CheckOverloadedOperatorDeclaration - Check whether the declaration 1793/// of this overloaded operator is well-formed. If so, returns false; 1794/// otherwise, emits appropriate diagnostics and returns true. 1795bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 1796 assert(FnDecl && FnDecl->isOverloadedOperator() && 1797 "Expected an overloaded operator declaration"); 1798 1799 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 1800 1801 // C++ [over.oper]p5: 1802 // The allocation and deallocation functions, operator new, 1803 // operator new[], operator delete and operator delete[], are 1804 // described completely in 3.7.3. The attributes and restrictions 1805 // found in the rest of this subclause do not apply to them unless 1806 // explicitly stated in 3.7.3. 1807 // FIXME: Write a separate routine for checking this. For now, just 1808 // allow it. 1809 if (Op == OO_New || Op == OO_Array_New || 1810 Op == OO_Delete || Op == OO_Array_Delete) 1811 return false; 1812 1813 // C++ [over.oper]p6: 1814 // An operator function shall either be a non-static member 1815 // function or be a non-member function and have at least one 1816 // parameter whose type is a class, a reference to a class, an 1817 // enumeration, or a reference to an enumeration. 1818 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 1819 if (MethodDecl->isStatic()) 1820 return Diag(FnDecl->getLocation(), 1821 diag::err_operator_overload_static, 1822 FnDecl->getName()); 1823 } else { 1824 bool ClassOrEnumParam = false; 1825 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(), 1826 ParamEnd = FnDecl->param_end(); 1827 Param != ParamEnd; ++Param) { 1828 QualType ParamType = (*Param)->getType().getNonReferenceType(); 1829 if (ParamType->isRecordType() || ParamType->isEnumeralType()) { 1830 ClassOrEnumParam = true; 1831 break; 1832 } 1833 } 1834 1835 if (!ClassOrEnumParam) 1836 return Diag(FnDecl->getLocation(), 1837 diag::err_operator_overload_needs_class_or_enum, 1838 FnDecl->getName()); 1839 } 1840 1841 // C++ [over.oper]p8: 1842 // An operator function cannot have default arguments (8.3.6), 1843 // except where explicitly stated below. 1844 // 1845 // Only the function-call operator allows default arguments 1846 // (C++ [over.call]p1). 1847 if (Op != OO_Call) { 1848 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(); 1849 Param != FnDecl->param_end(); ++Param) { 1850 if (Expr *DefArg = (*Param)->getDefaultArg()) 1851 return Diag((*Param)->getLocation(), 1852 diag::err_operator_overload_default_arg, 1853 FnDecl->getName(), DefArg->getSourceRange()); 1854 } 1855 } 1856 1857 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 1858 { false, false, false } 1859#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 1860 , { Unary, Binary, MemberOnly } 1861#include "clang/Basic/OperatorKinds.def" 1862 }; 1863 1864 bool CanBeUnaryOperator = OperatorUses[Op][0]; 1865 bool CanBeBinaryOperator = OperatorUses[Op][1]; 1866 bool MustBeMemberOperator = OperatorUses[Op][2]; 1867 1868 // C++ [over.oper]p8: 1869 // [...] Operator functions cannot have more or fewer parameters 1870 // than the number required for the corresponding operator, as 1871 // described in the rest of this subclause. 1872 unsigned NumParams = FnDecl->getNumParams() 1873 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 1874 if (Op != OO_Call && 1875 ((NumParams == 1 && !CanBeUnaryOperator) || 1876 (NumParams == 2 && !CanBeBinaryOperator) || 1877 (NumParams < 1) || (NumParams > 2))) { 1878 // We have the wrong number of parameters. 1879 std::string NumParamsStr = llvm::utostr(NumParams); 1880 1881 diag::kind DK; 1882 1883 if (CanBeUnaryOperator && CanBeBinaryOperator) { 1884 if (NumParams == 1) 1885 DK = diag::err_operator_overload_must_be_unary_or_binary; 1886 else 1887 DK = diag::err_operator_overload_must_be_unary_or_binary; 1888 } else if (CanBeUnaryOperator) { 1889 if (NumParams == 1) 1890 DK = diag::err_operator_overload_must_be_unary; 1891 else 1892 DK = diag::err_operator_overload_must_be_unary_plural; 1893 } else if (CanBeBinaryOperator) { 1894 if (NumParams == 1) 1895 DK = diag::err_operator_overload_must_be_binary; 1896 else 1897 DK = diag::err_operator_overload_must_be_binary_plural; 1898 } else { 1899 assert(false && "All non-call overloaded operators are unary or binary!"); 1900 } 1901 1902 return Diag(FnDecl->getLocation(), DK, 1903 FnDecl->getName(), NumParamsStr); 1904 } 1905 1906 // Overloaded operators other than operator() cannot be variadic. 1907 if (Op != OO_Call && 1908 FnDecl->getType()->getAsFunctionTypeProto()->isVariadic()) { 1909 return Diag(FnDecl->getLocation(), 1910 diag::err_operator_overload_variadic, 1911 FnDecl->getName()); 1912 } 1913 1914 // Some operators must be non-static member functions. 1915 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 1916 return Diag(FnDecl->getLocation(), 1917 diag::err_operator_overload_must_be_member, 1918 FnDecl->getName()); 1919 } 1920 1921 // C++ [over.inc]p1: 1922 // The user-defined function called operator++ implements the 1923 // prefix and postfix ++ operator. If this function is a member 1924 // function with no parameters, or a non-member function with one 1925 // parameter of class or enumeration type, it defines the prefix 1926 // increment operator ++ for objects of that type. If the function 1927 // is a member function with one parameter (which shall be of type 1928 // int) or a non-member function with two parameters (the second 1929 // of which shall be of type int), it defines the postfix 1930 // increment operator ++ for objects of that type. 1931 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 1932 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 1933 bool ParamIsInt = false; 1934 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType()) 1935 ParamIsInt = BT->getKind() == BuiltinType::Int; 1936 1937 if (!ParamIsInt) { 1938 diag::kind DK; 1939 if (Op == OO_PlusPlus) 1940 DK = diag::err_operator_overload_post_inc_must_be_int; 1941 else 1942 DK = diag::err_operator_overload_post_dec_must_be_int; 1943 return Diag(LastParam->getLocation(), DK, 1944 Context.getCanonicalType(LastParam->getType()).getAsString()); 1945 } 1946 } 1947 1948 return false; 1949} 1950