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