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