SemaDeclCXX.cpp revision 42a552f8200ba5948661aee0106fce0c04e39818
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->getName(), 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->getName(), 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 return; 118 } 119 120 // C++ [dcl.fct.default]p5 121 // A default argument expression is implicitly converted (clause 122 // 4) to the parameter type. The default argument expression has 123 // the same semantic constraints as the initializer expression in 124 // a declaration of a variable of the parameter type, using the 125 // copy-initialization semantics (8.5). 126 Expr *DefaultArgPtr = DefaultArg.get(); 127 bool DefaultInitFailed = PerformCopyInitialization(DefaultArgPtr, ParamType, 128 "in default argument"); 129 if (DefaultArgPtr != DefaultArg.get()) { 130 DefaultArg.take(); 131 DefaultArg.reset(DefaultArgPtr); 132 } 133 if (DefaultInitFailed) { 134 return; 135 } 136 137 // Check that the default argument is well-formed 138 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 139 if (DefaultArgChecker.Visit(DefaultArg.get())) 140 return; 141 142 // Okay: add the default argument to the parameter 143 Param->setDefaultArg(DefaultArg.take()); 144} 145 146/// CheckExtraCXXDefaultArguments - Check for any extra default 147/// arguments in the declarator, which is not a function declaration 148/// or definition and therefore is not permitted to have default 149/// arguments. This routine should be invoked for every declarator 150/// that is not a function declaration or definition. 151void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 152 // C++ [dcl.fct.default]p3 153 // A default argument expression shall be specified only in the 154 // parameter-declaration-clause of a function declaration or in a 155 // template-parameter (14.1). It shall not be specified for a 156 // parameter pack. If it is specified in a 157 // parameter-declaration-clause, it shall not occur within a 158 // declarator or abstract-declarator of a parameter-declaration. 159 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) { 160 DeclaratorChunk &chunk = D.getTypeObject(i); 161 if (chunk.Kind == DeclaratorChunk::Function) { 162 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) { 163 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param; 164 if (Param->getDefaultArg()) { 165 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc, 166 Param->getDefaultArg()->getSourceRange()); 167 Param->setDefaultArg(0); 168 } 169 } 170 } 171 } 172} 173 174// MergeCXXFunctionDecl - Merge two declarations of the same C++ 175// function, once we already know that they have the same 176// type. Subroutine of MergeFunctionDecl. 177FunctionDecl * 178Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 179 // C++ [dcl.fct.default]p4: 180 // 181 // For non-template functions, default arguments can be added in 182 // later declarations of a function in the same 183 // scope. Declarations in different scopes have completely 184 // distinct sets of default arguments. That is, declarations in 185 // inner scopes do not acquire default arguments from 186 // declarations in outer scopes, and vice versa. In a given 187 // function declaration, all parameters subsequent to a 188 // parameter with a default argument shall have default 189 // arguments supplied in this or previous declarations. A 190 // default argument shall not be redefined by a later 191 // declaration (not even to the same value). 192 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 193 ParmVarDecl *OldParam = Old->getParamDecl(p); 194 ParmVarDecl *NewParam = New->getParamDecl(p); 195 196 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) { 197 Diag(NewParam->getLocation(), 198 diag::err_param_default_argument_redefinition, 199 NewParam->getDefaultArg()->getSourceRange()); 200 Diag(OldParam->getLocation(), diag::err_previous_definition); 201 } else if (OldParam->getDefaultArg()) { 202 // Merge the old default argument into the new parameter 203 NewParam->setDefaultArg(OldParam->getDefaultArg()); 204 } 205 } 206 207 return New; 208} 209 210/// CheckCXXDefaultArguments - Verify that the default arguments for a 211/// function declaration are well-formed according to C++ 212/// [dcl.fct.default]. 213void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 214 unsigned NumParams = FD->getNumParams(); 215 unsigned p; 216 217 // Find first parameter with a default argument 218 for (p = 0; p < NumParams; ++p) { 219 ParmVarDecl *Param = FD->getParamDecl(p); 220 if (Param->getDefaultArg()) 221 break; 222 } 223 224 // C++ [dcl.fct.default]p4: 225 // In a given function declaration, all parameters 226 // subsequent to a parameter with a default argument shall 227 // have default arguments supplied in this or previous 228 // declarations. A default argument shall not be redefined 229 // by a later declaration (not even to the same value). 230 unsigned LastMissingDefaultArg = 0; 231 for(; p < NumParams; ++p) { 232 ParmVarDecl *Param = FD->getParamDecl(p); 233 if (!Param->getDefaultArg()) { 234 if (Param->getIdentifier()) 235 Diag(Param->getLocation(), 236 diag::err_param_default_argument_missing_name, 237 Param->getIdentifier()->getName()); 238 else 239 Diag(Param->getLocation(), 240 diag::err_param_default_argument_missing); 241 242 LastMissingDefaultArg = p; 243 } 244 } 245 246 if (LastMissingDefaultArg > 0) { 247 // Some default arguments were missing. Clear out all of the 248 // default arguments up to (and including) the last missing 249 // default argument, so that we leave the function parameters 250 // in a semantically valid state. 251 for (p = 0; p <= LastMissingDefaultArg; ++p) { 252 ParmVarDecl *Param = FD->getParamDecl(p); 253 if (Param->getDefaultArg()) { 254 delete Param->getDefaultArg(); 255 Param->setDefaultArg(0); 256 } 257 } 258 } 259} 260 261/// isCurrentClassName - Determine whether the identifier II is the 262/// name of the class type currently being defined. In the case of 263/// nested classes, this will only return true if II is the name of 264/// the innermost class. 265bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *) { 266 if (CXXRecordDecl *CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext)) 267 return &II == CurDecl->getIdentifier(); 268 else 269 return false; 270} 271 272/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 273/// one entry in the base class list of a class specifier, for 274/// example: 275/// class foo : public bar, virtual private baz { 276/// 'public bar' and 'virtual private baz' are each base-specifiers. 277Sema::BaseResult 278Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange, 279 bool Virtual, AccessSpecifier Access, 280 TypeTy *basetype, SourceLocation BaseLoc) { 281 RecordDecl *Decl = (RecordDecl*)classdecl; 282 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype); 283 284 // Base specifiers must be record types. 285 if (!BaseType->isRecordType()) { 286 Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange); 287 return true; 288 } 289 290 // C++ [class.union]p1: 291 // A union shall not be used as a base class. 292 if (BaseType->isUnionType()) { 293 Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange); 294 return true; 295 } 296 297 // C++ [class.union]p1: 298 // A union shall not have base classes. 299 if (Decl->isUnion()) { 300 Diag(Decl->getLocation(), diag::err_base_clause_on_union, 301 SpecifierRange); 302 return true; 303 } 304 305 // C++ [class.derived]p2: 306 // The class-name in a base-specifier shall not be an incompletely 307 // defined class. 308 if (BaseType->isIncompleteType()) { 309 Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange); 310 return true; 311 } 312 313 // Create the base specifier. 314 return new CXXBaseSpecifier(SpecifierRange, Virtual, 315 BaseType->isClassType(), Access, BaseType); 316} 317 318/// ActOnBaseSpecifiers - Attach the given base specifiers to the 319/// class, after checking whether there are any duplicate base 320/// classes. 321void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases, 322 unsigned NumBases) { 323 if (NumBases == 0) 324 return; 325 326 // Used to keep track of which base types we have already seen, so 327 // that we can properly diagnose redundant direct base types. Note 328 // that the key is always the unqualified canonical type of the base 329 // class. 330 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 331 332 // Copy non-redundant base specifiers into permanent storage. 333 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases; 334 unsigned NumGoodBases = 0; 335 for (unsigned idx = 0; idx < NumBases; ++idx) { 336 QualType NewBaseType 337 = Context.getCanonicalType(BaseSpecs[idx]->getType()); 338 NewBaseType = NewBaseType.getUnqualifiedType(); 339 340 if (KnownBaseTypes[NewBaseType]) { 341 // C++ [class.mi]p3: 342 // A class shall not be specified as a direct base class of a 343 // derived class more than once. 344 Diag(BaseSpecs[idx]->getSourceRange().getBegin(), 345 diag::err_duplicate_base_class, 346 KnownBaseTypes[NewBaseType]->getType().getAsString(), 347 BaseSpecs[idx]->getSourceRange()); 348 349 // Delete the duplicate base class specifier; we're going to 350 // overwrite its pointer later. 351 delete BaseSpecs[idx]; 352 } else { 353 // Okay, add this new base class. 354 KnownBaseTypes[NewBaseType] = BaseSpecs[idx]; 355 BaseSpecs[NumGoodBases++] = BaseSpecs[idx]; 356 } 357 } 358 359 // Attach the remaining base class specifiers to the derived class. 360 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl; 361 Decl->setBases(BaseSpecs, NumGoodBases); 362 363 // Delete the remaining (good) base class specifiers, since their 364 // data has been copied into the CXXRecordDecl. 365 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 366 delete BaseSpecs[idx]; 367} 368 369//===----------------------------------------------------------------------===// 370// C++ class member Handling 371//===----------------------------------------------------------------------===// 372 373/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union 374/// definition, when on C++. 375void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) { 376 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D)); 377 PushDeclContext(Dcl); 378 FieldCollector->StartClass(); 379 380 if (Dcl->getIdentifier()) { 381 // C++ [class]p2: 382 // [...] The class-name is also inserted into the scope of the 383 // class itself; this is known as the injected-class-name. For 384 // purposes of access checking, the injected-class-name is treated 385 // as if it were a public member name. 386 // FIXME: this should probably have its own kind of type node. 387 TypedefDecl *InjectedClassName 388 = TypedefDecl::Create(Context, Dcl, LBrace, Dcl->getIdentifier(), 389 Context.getTypeDeclType(Dcl), /*PrevDecl=*/0); 390 PushOnScopeChains(InjectedClassName, S); 391 } 392} 393 394/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 395/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 396/// bitfield width if there is one and 'InitExpr' specifies the initializer if 397/// any. 'LastInGroup' is non-null for cases where one declspec has multiple 398/// declarators on it. 399/// 400/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if 401/// an instance field is declared, a new CXXFieldDecl is created but the method 402/// does *not* return it; it returns LastInGroup instead. The other C++ members 403/// (which are all ScopedDecls) are returned after appending them to 404/// LastInGroup. 405Sema::DeclTy * 406Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 407 ExprTy *BW, ExprTy *InitExpr, 408 DeclTy *LastInGroup) { 409 const DeclSpec &DS = D.getDeclSpec(); 410 IdentifierInfo *II = D.getIdentifier(); 411 Expr *BitWidth = static_cast<Expr*>(BW); 412 Expr *Init = static_cast<Expr*>(InitExpr); 413 SourceLocation Loc = D.getIdentifierLoc(); 414 415 // C++ 9.2p6: A member shall not be declared to have automatic storage 416 // duration (auto, register) or with the extern storage-class-specifier. 417 switch (DS.getStorageClassSpec()) { 418 case DeclSpec::SCS_unspecified: 419 case DeclSpec::SCS_typedef: 420 case DeclSpec::SCS_static: 421 // FALL THROUGH. 422 break; 423 default: 424 if (DS.getStorageClassSpecLoc().isValid()) 425 Diag(DS.getStorageClassSpecLoc(), 426 diag::err_storageclass_invalid_for_member); 427 else 428 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 429 D.getMutableDeclSpec().ClearStorageClassSpecs(); 430 } 431 432 bool isFunc = D.isFunctionDeclarator(); 433 if (!isFunc && 434 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef && 435 D.getNumTypeObjects() == 0) { 436 // Check also for this case: 437 // 438 // typedef int f(); 439 // f a; 440 // 441 Decl *TD = static_cast<Decl *>(DS.getTypeRep()); 442 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType(); 443 } 444 445 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified && 446 !isFunc); 447 448 Decl *Member; 449 bool InvalidDecl = false; 450 451 if (isInstField) 452 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth)); 453 else 454 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup)); 455 456 if (!Member) return LastInGroup; 457 458 assert((II || isInstField) && "No identifier for non-field ?"); 459 460 // set/getAccess is not part of Decl's interface to avoid bloating it with C++ 461 // specific methods. Use a wrapper class that can be used with all C++ class 462 // member decls. 463 CXXClassMemberWrapper(Member).setAccess(AS); 464 465 // C++ [dcl.init.aggr]p1: 466 // An aggregate is an array or a class (clause 9) with [...] no 467 // private or protected non-static data members (clause 11). 468 if (isInstField && (AS == AS_private || AS == AS_protected)) 469 cast<CXXRecordDecl>(CurContext)->setAggregate(false); 470 471 // FIXME: If the member is a virtual function, mark it its class as 472 // a non-aggregate. 473 474 if (BitWidth) { 475 // C++ 9.6p2: Only when declaring an unnamed bit-field may the 476 // constant-expression be a value equal to zero. 477 // FIXME: Check this. 478 479 if (D.isFunctionDeclarator()) { 480 // FIXME: Emit diagnostic about only constructors taking base initializers 481 // or something similar, when constructor support is in place. 482 Diag(Loc, diag::err_not_bitfield_type, 483 II->getName(), BitWidth->getSourceRange()); 484 InvalidDecl = true; 485 486 } else if (isInstField) { 487 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 488 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) { 489 Diag(Loc, diag::err_not_integral_type_bitfield, 490 II->getName(), BitWidth->getSourceRange()); 491 InvalidDecl = true; 492 } 493 494 } else if (isa<FunctionDecl>(Member)) { 495 // A function typedef ("typedef int f(); f a;"). 496 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 497 Diag(Loc, diag::err_not_integral_type_bitfield, 498 II->getName(), BitWidth->getSourceRange()); 499 InvalidDecl = true; 500 501 } else if (isa<TypedefDecl>(Member)) { 502 // "cannot declare 'A' to be a bit-field type" 503 Diag(Loc, diag::err_not_bitfield_type, II->getName(), 504 BitWidth->getSourceRange()); 505 InvalidDecl = true; 506 507 } else { 508 assert(isa<CXXClassVarDecl>(Member) && 509 "Didn't we cover all member kinds?"); 510 // C++ 9.6p3: A bit-field shall not be a static member. 511 // "static member 'A' cannot be a bit-field" 512 Diag(Loc, diag::err_static_not_bitfield, II->getName(), 513 BitWidth->getSourceRange()); 514 InvalidDecl = true; 515 } 516 } 517 518 if (Init) { 519 // C++ 9.2p4: A member-declarator can contain a constant-initializer only 520 // if it declares a static member of const integral or const enumeration 521 // type. 522 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) { 523 // ...static member of... 524 CVD->setInit(Init); 525 // ...const integral or const enumeration type. 526 if (Context.getCanonicalType(CVD->getType()).isConstQualified() && 527 CVD->getType()->isIntegralType()) { 528 // constant-initializer 529 if (CheckForConstantInitializer(Init, CVD->getType())) 530 InvalidDecl = true; 531 532 } else { 533 // not const integral. 534 Diag(Loc, diag::err_member_initialization, 535 II->getName(), Init->getSourceRange()); 536 InvalidDecl = true; 537 } 538 539 } else { 540 // not static member. 541 Diag(Loc, diag::err_member_initialization, 542 II->getName(), Init->getSourceRange()); 543 InvalidDecl = true; 544 } 545 } 546 547 if (InvalidDecl) 548 Member->setInvalidDecl(); 549 550 if (isInstField) { 551 FieldCollector->Add(cast<CXXFieldDecl>(Member)); 552 return LastInGroup; 553 } 554 return Member; 555} 556 557/// ActOnMemInitializer - Handle a C++ member initializer. 558Sema::MemInitResult 559Sema::ActOnMemInitializer(DeclTy *ConstructorD, 560 Scope *S, 561 IdentifierInfo *MemberOrBase, 562 SourceLocation IdLoc, 563 SourceLocation LParenLoc, 564 ExprTy **Args, unsigned NumArgs, 565 SourceLocation *CommaLocs, 566 SourceLocation RParenLoc) { 567 CXXConstructorDecl *Constructor 568 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD); 569 if (!Constructor) { 570 // The user wrote a constructor initializer on a function that is 571 // not a C++ constructor. Ignore the error for now, because we may 572 // have more member initializers coming; we'll diagnose it just 573 // once in ActOnMemInitializers. 574 return true; 575 } 576 577 CXXRecordDecl *ClassDecl = Constructor->getParent(); 578 579 // C++ [class.base.init]p2: 580 // Names in a mem-initializer-id are looked up in the scope of the 581 // constructor’s class and, if not found in that scope, are looked 582 // up in the scope containing the constructor’s 583 // definition. [Note: if the constructor’s class contains a member 584 // with the same name as a direct or virtual base class of the 585 // class, a mem-initializer-id naming the member or base class and 586 // composed of a single identifier refers to the class member. A 587 // mem-initializer-id for the hidden base class may be specified 588 // using a qualified name. ] 589 // Look for a member, first. 590 CXXFieldDecl *Member = ClassDecl->getMember(MemberOrBase); 591 592 // FIXME: Handle members of an anonymous union. 593 594 if (Member) { 595 // FIXME: Perform direct initialization of the member. 596 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs); 597 } 598 599 // It didn't name a member, so see if it names a class. 600 TypeTy *BaseTy = isTypeName(*MemberOrBase, S); 601 if (!BaseTy) 602 return Diag(IdLoc, diag::err_mem_init_not_member_or_class, 603 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc)); 604 605 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy); 606 if (!BaseType->isRecordType()) 607 return Diag(IdLoc, diag::err_base_init_does_not_name_class, 608 BaseType.getAsString(), SourceRange(IdLoc, RParenLoc)); 609 610 // C++ [class.base.init]p2: 611 // [...] Unless the mem-initializer-id names a nonstatic data 612 // member of the constructor’s class or a direct or virtual base 613 // of that class, the mem-initializer is ill-formed. A 614 // mem-initializer-list can initialize a base class using any 615 // name that denotes that base class type. 616 617 // First, check for a direct base class. 618 const CXXBaseSpecifier *DirectBaseSpec = 0; 619 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 620 Base != ClassDecl->bases_end(); ++Base) { 621 if (Context.getCanonicalType(BaseType).getUnqualifiedType() == 622 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) { 623 // We found a direct base of this type. That's what we're 624 // initializing. 625 DirectBaseSpec = &*Base; 626 break; 627 } 628 } 629 630 // Check for a virtual base class. 631 // FIXME: We might be able to short-circuit this if we know in 632 // advance that there are no virtual bases. 633 const CXXBaseSpecifier *VirtualBaseSpec = 0; 634 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 635 // We haven't found a base yet; search the class hierarchy for a 636 // virtual base class. 637 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 638 /*DetectVirtual=*/false); 639 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) { 640 for (BasePaths::paths_iterator Path = Paths.begin(); 641 Path != Paths.end(); ++Path) { 642 if (Path->back().Base->isVirtual()) { 643 VirtualBaseSpec = Path->back().Base; 644 break; 645 } 646 } 647 } 648 } 649 650 // C++ [base.class.init]p2: 651 // If a mem-initializer-id is ambiguous because it designates both 652 // a direct non-virtual base class and an inherited virtual base 653 // class, the mem-initializer is ill-formed. 654 if (DirectBaseSpec && VirtualBaseSpec) 655 return Diag(IdLoc, diag::err_base_init_direct_and_virtual, 656 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc)); 657 658 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs); 659} 660 661 662void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 663 DeclTy *TagDecl, 664 SourceLocation LBrac, 665 SourceLocation RBrac) { 666 ActOnFields(S, RLoc, TagDecl, 667 (DeclTy**)FieldCollector->getCurFields(), 668 FieldCollector->getCurNumFields(), LBrac, RBrac, 0); 669} 670 671/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 672/// special functions, such as the default constructor, copy 673/// constructor, or destructor, to the given C++ class (C++ 674/// [special]p1). This routine can only be executed just before the 675/// definition of the class is complete. 676void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 677 if (!ClassDecl->hasUserDeclaredConstructor()) { 678 // C++ [class.ctor]p5: 679 // A default constructor for a class X is a constructor of class X 680 // that can be called without an argument. If there is no 681 // user-declared constructor for class X, a default constructor is 682 // implicitly declared. An implicitly-declared default constructor 683 // is an inline public member of its class. 684 CXXConstructorDecl *DefaultCon = 685 CXXConstructorDecl::Create(Context, ClassDecl, 686 ClassDecl->getLocation(), 687 ClassDecl->getIdentifier(), 688 Context.getFunctionType(Context.VoidTy, 689 0, 0, false, 0), 690 /*isExplicit=*/false, 691 /*isInline=*/true, 692 /*isImplicitlyDeclared=*/true); 693 DefaultCon->setAccess(AS_public); 694 ClassDecl->addConstructor(Context, DefaultCon); 695 } 696 697 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 698 // C++ [class.copy]p4: 699 // If the class definition does not explicitly declare a copy 700 // constructor, one is declared implicitly. 701 702 // C++ [class.copy]p5: 703 // The implicitly-declared copy constructor for a class X will 704 // have the form 705 // 706 // X::X(const X&) 707 // 708 // if 709 bool HasConstCopyConstructor = true; 710 711 // -- each direct or virtual base class B of X has a copy 712 // constructor whose first parameter is of type const B& or 713 // const volatile B&, and 714 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 715 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 716 const CXXRecordDecl *BaseClassDecl 717 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl()); 718 HasConstCopyConstructor 719 = BaseClassDecl->hasConstCopyConstructor(Context); 720 } 721 722 // -- for all the nonstatic data members of X that are of a 723 // class type M (or array thereof), each such class type 724 // has a copy constructor whose first parameter is of type 725 // const M& or const volatile M&. 726 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 727 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) { 728 QualType FieldType = (*Field)->getType(); 729 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 730 FieldType = Array->getElementType(); 731 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) { 732 const CXXRecordDecl *FieldClassDecl 733 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 734 HasConstCopyConstructor 735 = FieldClassDecl->hasConstCopyConstructor(Context); 736 } 737 } 738 739 // Otherwise, the implicitly declared copy constructor will have 740 // the form 741 // 742 // X::X(X&) 743 QualType ArgType = Context.getTypeDeclType(ClassDecl); 744 if (HasConstCopyConstructor) 745 ArgType = ArgType.withConst(); 746 ArgType = Context.getReferenceType(ArgType); 747 748 // An implicitly-declared copy constructor is an inline public 749 // member of its class. 750 CXXConstructorDecl *CopyConstructor 751 = CXXConstructorDecl::Create(Context, ClassDecl, 752 ClassDecl->getLocation(), 753 ClassDecl->getIdentifier(), 754 Context.getFunctionType(Context.VoidTy, 755 &ArgType, 1, 756 false, 0), 757 /*isExplicit=*/false, 758 /*isInline=*/true, 759 /*isImplicitlyDeclared=*/true); 760 CopyConstructor->setAccess(AS_public); 761 762 // Add the parameter to the constructor. 763 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 764 ClassDecl->getLocation(), 765 /*IdentifierInfo=*/0, 766 ArgType, VarDecl::None, 0, 0); 767 CopyConstructor->setParams(&FromParam, 1); 768 769 ClassDecl->addConstructor(Context, CopyConstructor); 770 } 771 772 if (!ClassDecl->getDestructor()) { 773 // C++ [class.dtor]p2: 774 // If a class has no user-declared destructor, a destructor is 775 // declared implicitly. An implicitly-declared destructor is an 776 // inline public member of its class. 777 std::string DestructorName = "~"; 778 DestructorName += ClassDecl->getName(); 779 CXXDestructorDecl *Destructor 780 = CXXDestructorDecl::Create(Context, ClassDecl, 781 ClassDecl->getLocation(), 782 &PP.getIdentifierTable().get(DestructorName), 783 Context.getFunctionType(Context.VoidTy, 784 0, 0, false, 0), 785 /*isInline=*/true, 786 /*isImplicitlyDeclared=*/true); 787 Destructor->setAccess(AS_public); 788 ClassDecl->setDestructor(Destructor); 789 } 790 791 // FIXME: Implicit copy assignment operator 792} 793 794void Sema::ActOnFinishCXXClassDef(DeclTy *D) { 795 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D)); 796 FieldCollector->FinishClass(); 797 AddImplicitlyDeclaredMembersToClass(Rec); 798 PopDeclContext(); 799 800 // Everything, including inline method definitions, have been parsed. 801 // Let the consumer know of the new TagDecl definition. 802 Consumer.HandleTagDeclDefinition(Rec); 803} 804 805/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 806/// the well-formednes of the constructor declarator @p D with type @p 807/// R. If there are any errors in the declarator, this routine will 808/// emit diagnostics and return true. Otherwise, it will return 809/// false. Either way, the type @p R will be updated to reflect a 810/// well-formed type for the constructor. 811bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R, 812 FunctionDecl::StorageClass& SC) { 813 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 814 bool isInvalid = false; 815 816 // C++ [class.ctor]p3: 817 // A constructor shall not be virtual (10.3) or static (9.4). A 818 // constructor can be invoked for a const, volatile or const 819 // volatile object. A constructor shall not be declared const, 820 // volatile, or const volatile (9.3.2). 821 if (isVirtual) { 822 Diag(D.getIdentifierLoc(), 823 diag::err_constructor_cannot_be, 824 "virtual", 825 SourceRange(D.getDeclSpec().getVirtualSpecLoc()), 826 SourceRange(D.getIdentifierLoc())); 827 isInvalid = true; 828 } 829 if (SC == FunctionDecl::Static) { 830 Diag(D.getIdentifierLoc(), 831 diag::err_constructor_cannot_be, 832 "static", 833 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()), 834 SourceRange(D.getIdentifierLoc())); 835 isInvalid = true; 836 SC = FunctionDecl::None; 837 } 838 if (D.getDeclSpec().hasTypeSpecifier()) { 839 // Constructors don't have return types, but the parser will 840 // happily parse something like: 841 // 842 // class X { 843 // float X(float); 844 // }; 845 // 846 // The return type will be eliminated later. 847 Diag(D.getIdentifierLoc(), 848 diag::err_constructor_return_type, 849 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()), 850 SourceRange(D.getIdentifierLoc())); 851 } 852 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) { 853 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 854 if (FTI.TypeQuals & QualType::Const) 855 Diag(D.getIdentifierLoc(), 856 diag::err_invalid_qualified_constructor, 857 "const", 858 SourceRange(D.getIdentifierLoc())); 859 if (FTI.TypeQuals & QualType::Volatile) 860 Diag(D.getIdentifierLoc(), 861 diag::err_invalid_qualified_constructor, 862 "volatile", 863 SourceRange(D.getIdentifierLoc())); 864 if (FTI.TypeQuals & QualType::Restrict) 865 Diag(D.getIdentifierLoc(), 866 diag::err_invalid_qualified_constructor, 867 "restrict", 868 SourceRange(D.getIdentifierLoc())); 869 } 870 871 // Rebuild the function type "R" without any type qualifiers (in 872 // case any of the errors above fired) and with "void" as the 873 // return type, since constructors don't have return types. We 874 // *always* have to do this, because GetTypeForDeclarator will 875 // put in a result type of "int" when none was specified. 876 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto(); 877 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 878 Proto->getNumArgs(), 879 Proto->isVariadic(), 880 0); 881 882 return isInvalid; 883} 884 885/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 886/// the well-formednes of the destructor declarator @p D with type @p 887/// R. If there are any errors in the declarator, this routine will 888/// emit diagnostics and return true. Otherwise, it will return 889/// false. Either way, the type @p R will be updated to reflect a 890/// well-formed type for the destructor. 891bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R, 892 FunctionDecl::StorageClass& SC) { 893 bool isInvalid = false; 894 895 // C++ [class.dtor]p1: 896 // [...] A typedef-name that names a class is a class-name 897 // (7.1.3); however, a typedef-name that names a class shall not 898 // be used as the identifier in the declarator for a destructor 899 // declaration. 900 TypeDecl *DeclaratorTypeD = (TypeDecl *)D.getDeclaratorIdType(); 901 if (const TypedefDecl *TypedefD = dyn_cast<TypedefDecl>(DeclaratorTypeD)) { 902 if (TypedefD->getIdentifier() != 903 cast<CXXRecordDecl>(CurContext)->getIdentifier()) { 904 // FIXME: This would be easier if we could just look at whether 905 // we found the injected-class-name. 906 Diag(D.getIdentifierLoc(), 907 diag::err_destructor_typedef_name, 908 TypedefD->getName()); 909 isInvalid = true; 910 } 911 } 912 913 // C++ [class.dtor]p2: 914 // A destructor is used to destroy objects of its class type. A 915 // destructor takes no parameters, and no return type can be 916 // specified for it (not even void). The address of a destructor 917 // shall not be taken. A destructor shall not be static. A 918 // destructor can be invoked for a const, volatile or const 919 // volatile object. A destructor shall not be declared const, 920 // volatile or const volatile (9.3.2). 921 if (SC == FunctionDecl::Static) { 922 Diag(D.getIdentifierLoc(), 923 diag::err_destructor_cannot_be, 924 "static", 925 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()), 926 SourceRange(D.getIdentifierLoc())); 927 isInvalid = true; 928 SC = FunctionDecl::None; 929 } 930 if (D.getDeclSpec().hasTypeSpecifier()) { 931 // Destructors don't have return types, but the parser will 932 // happily parse something like: 933 // 934 // class X { 935 // float ~X(); 936 // }; 937 // 938 // The return type will be eliminated later. 939 Diag(D.getIdentifierLoc(), 940 diag::err_destructor_return_type, 941 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()), 942 SourceRange(D.getIdentifierLoc())); 943 } 944 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) { 945 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 946 if (FTI.TypeQuals & QualType::Const) 947 Diag(D.getIdentifierLoc(), 948 diag::err_invalid_qualified_destructor, 949 "const", 950 SourceRange(D.getIdentifierLoc())); 951 if (FTI.TypeQuals & QualType::Volatile) 952 Diag(D.getIdentifierLoc(), 953 diag::err_invalid_qualified_destructor, 954 "volatile", 955 SourceRange(D.getIdentifierLoc())); 956 if (FTI.TypeQuals & QualType::Restrict) 957 Diag(D.getIdentifierLoc(), 958 diag::err_invalid_qualified_destructor, 959 "restrict", 960 SourceRange(D.getIdentifierLoc())); 961 } 962 963 // Make sure we don't have any parameters. 964 if (R->getAsFunctionTypeProto()->getNumArgs() > 0) { 965 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 966 967 // Delete the parameters. 968 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 969 if (FTI.NumArgs) { 970 delete [] FTI.ArgInfo; 971 FTI.NumArgs = 0; 972 FTI.ArgInfo = 0; 973 } 974 } 975 976 // Make sure the destructor isn't variadic. 977 if (R->getAsFunctionTypeProto()->isVariadic()) 978 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 979 980 // Rebuild the function type "R" without any type qualifiers or 981 // parameters (in case any of the errors above fired) and with 982 // "void" as the return type, since destructors don't have return 983 // types. We *always* have to do this, because GetTypeForDeclarator 984 // will put in a result type of "int" when none was specified. 985 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0); 986 987 return isInvalid; 988} 989 990/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete 991/// the declaration of the given C++ constructor ConDecl that was 992/// built from declarator D. This routine is responsible for checking 993/// that the newly-created constructor declaration is well-formed and 994/// for recording it in the C++ class. Example: 995/// 996/// @code 997/// class X { 998/// X(); // X::X() will be the ConDecl. 999/// }; 1000/// @endcode 1001Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) { 1002 assert(ConDecl && "Expected to receive a constructor declaration"); 1003 1004 // Check default arguments on the constructor 1005 CheckCXXDefaultArguments(ConDecl); 1006 1007 CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 1008 if (!ClassDecl) { 1009 ConDecl->setInvalidDecl(); 1010 return ConDecl; 1011 } 1012 1013 // Make sure this constructor is an overload of the existing 1014 // constructors. 1015 OverloadedFunctionDecl::function_iterator MatchedDecl; 1016 if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) { 1017 Diag(ConDecl->getLocation(), 1018 diag::err_constructor_redeclared, 1019 SourceRange(ConDecl->getLocation())); 1020 Diag((*MatchedDecl)->getLocation(), 1021 diag::err_previous_declaration, 1022 SourceRange((*MatchedDecl)->getLocation())); 1023 ConDecl->setInvalidDecl(); 1024 return ConDecl; 1025 } 1026 1027 1028 // C++ [class.copy]p3: 1029 // A declaration of a constructor for a class X is ill-formed if 1030 // its first parameter is of type (optionally cv-qualified) X and 1031 // either there are no other parameters or else all other 1032 // parameters have default arguments. 1033 if ((ConDecl->getNumParams() == 1) || 1034 (ConDecl->getNumParams() > 1 && 1035 ConDecl->getParamDecl(1)->getDefaultArg() != 0)) { 1036 QualType ParamType = ConDecl->getParamDecl(0)->getType(); 1037 QualType ClassTy = Context.getTagDeclType( 1038 const_cast<CXXRecordDecl*>(ConDecl->getParent())); 1039 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 1040 Diag(ConDecl->getLocation(), 1041 diag::err_constructor_byvalue_arg, 1042 SourceRange(ConDecl->getParamDecl(0)->getLocation())); 1043 ConDecl->setInvalidDecl(); 1044 return ConDecl; 1045 } 1046 } 1047 1048 // Add this constructor to the set of constructors of the current 1049 // class. 1050 ClassDecl->addConstructor(Context, ConDecl); 1051 return (DeclTy *)ConDecl; 1052} 1053 1054/// ActOnDestructorDeclarator - Called by ActOnDeclarator to complete 1055/// the declaration of the given C++ @p Destructor. This routine is 1056/// responsible for recording the destructor in the C++ class, if 1057/// possible. 1058Sema::DeclTy *Sema::ActOnDestructorDeclarator(CXXDestructorDecl *Destructor) { 1059 assert(Destructor && "Expected to receive a destructor declaration"); 1060 1061 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CurContext); 1062 1063 // Make sure we aren't redeclaring the destructor. 1064 if (CXXDestructorDecl *PrevDestructor = ClassDecl->getDestructor()) { 1065 Diag(Destructor->getLocation(), diag::err_destructor_redeclared); 1066 Diag(PrevDestructor->getLocation(), 1067 PrevDestructor->isThisDeclarationADefinition()? 1068 diag::err_previous_definition 1069 : diag::err_previous_declaration); 1070 Destructor->setInvalidDecl(); 1071 return Destructor; 1072 } 1073 1074 ClassDecl->setDestructor(Destructor); 1075 return (DeclTy *)Destructor; 1076} 1077 1078//===----------------------------------------------------------------------===// 1079// Namespace Handling 1080//===----------------------------------------------------------------------===// 1081 1082/// ActOnStartNamespaceDef - This is called at the start of a namespace 1083/// definition. 1084Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 1085 SourceLocation IdentLoc, 1086 IdentifierInfo *II, 1087 SourceLocation LBrace) { 1088 NamespaceDecl *Namespc = 1089 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 1090 Namespc->setLBracLoc(LBrace); 1091 1092 Scope *DeclRegionScope = NamespcScope->getParent(); 1093 1094 if (II) { 1095 // C++ [namespace.def]p2: 1096 // The identifier in an original-namespace-definition shall not have been 1097 // previously defined in the declarative region in which the 1098 // original-namespace-definition appears. The identifier in an 1099 // original-namespace-definition is the name of the namespace. Subsequently 1100 // in that declarative region, it is treated as an original-namespace-name. 1101 1102 Decl *PrevDecl = 1103 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 1104 /*enableLazyBuiltinCreation=*/false); 1105 1106 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) { 1107 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) { 1108 // This is an extended namespace definition. 1109 // Attach this namespace decl to the chain of extended namespace 1110 // definitions. 1111 NamespaceDecl *NextNS = OrigNS; 1112 while (NextNS->getNextNamespace()) 1113 NextNS = NextNS->getNextNamespace(); 1114 1115 NextNS->setNextNamespace(Namespc); 1116 Namespc->setOriginalNamespace(OrigNS); 1117 1118 // We won't add this decl to the current scope. We want the namespace 1119 // name to return the original namespace decl during a name lookup. 1120 } else { 1121 // This is an invalid name redefinition. 1122 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind, 1123 Namespc->getName()); 1124 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 1125 Namespc->setInvalidDecl(); 1126 // Continue on to push Namespc as current DeclContext and return it. 1127 } 1128 } else { 1129 // This namespace name is declared for the first time. 1130 PushOnScopeChains(Namespc, DeclRegionScope); 1131 } 1132 } 1133 else { 1134 // FIXME: Handle anonymous namespaces 1135 } 1136 1137 // Although we could have an invalid decl (i.e. the namespace name is a 1138 // redefinition), push it as current DeclContext and try to continue parsing. 1139 PushDeclContext(Namespc->getOriginalNamespace()); 1140 return Namespc; 1141} 1142 1143/// ActOnFinishNamespaceDef - This callback is called after a namespace is 1144/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 1145void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) { 1146 Decl *Dcl = static_cast<Decl *>(D); 1147 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 1148 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 1149 Namespc->setRBracLoc(RBrace); 1150 PopDeclContext(); 1151} 1152 1153 1154/// AddCXXDirectInitializerToDecl - This action is called immediately after 1155/// ActOnDeclarator, when a C++ direct initializer is present. 1156/// e.g: "int x(1);" 1157void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc, 1158 ExprTy **ExprTys, unsigned NumExprs, 1159 SourceLocation *CommaLocs, 1160 SourceLocation RParenLoc) { 1161 assert(NumExprs != 0 && ExprTys && "missing expressions"); 1162 Decl *RealDecl = static_cast<Decl *>(Dcl); 1163 1164 // If there is no declaration, there was an error parsing it. Just ignore 1165 // the initializer. 1166 if (RealDecl == 0) { 1167 for (unsigned i = 0; i != NumExprs; ++i) 1168 delete static_cast<Expr *>(ExprTys[i]); 1169 return; 1170 } 1171 1172 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 1173 if (!VDecl) { 1174 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 1175 RealDecl->setInvalidDecl(); 1176 return; 1177 } 1178 1179 // We will treat direct-initialization as a copy-initialization: 1180 // int x(1); -as-> int x = 1; 1181 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 1182 // 1183 // Clients that want to distinguish between the two forms, can check for 1184 // direct initializer using VarDecl::hasCXXDirectInitializer(). 1185 // A major benefit is that clients that don't particularly care about which 1186 // exactly form was it (like the CodeGen) can handle both cases without 1187 // special case code. 1188 1189 // C++ 8.5p11: 1190 // The form of initialization (using parentheses or '=') is generally 1191 // insignificant, but does matter when the entity being initialized has a 1192 // class type. 1193 QualType DeclInitType = VDecl->getType(); 1194 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 1195 DeclInitType = Array->getElementType(); 1196 1197 if (VDecl->getType()->isRecordType()) { 1198 CXXConstructorDecl *Constructor 1199 = PerformInitializationByConstructor(DeclInitType, 1200 (Expr **)ExprTys, NumExprs, 1201 VDecl->getLocation(), 1202 SourceRange(VDecl->getLocation(), 1203 RParenLoc), 1204 VDecl->getName(), 1205 IK_Direct); 1206 if (!Constructor) { 1207 RealDecl->setInvalidDecl(); 1208 } 1209 1210 // Let clients know that initialization was done with a direct 1211 // initializer. 1212 VDecl->setCXXDirectInitializer(true); 1213 1214 // FIXME: Add ExprTys and Constructor to the RealDecl as part of 1215 // the initializer. 1216 return; 1217 } 1218 1219 if (NumExprs > 1) { 1220 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg, 1221 SourceRange(VDecl->getLocation(), RParenLoc)); 1222 RealDecl->setInvalidDecl(); 1223 return; 1224 } 1225 1226 // Let clients know that initialization was done with a direct initializer. 1227 VDecl->setCXXDirectInitializer(true); 1228 1229 assert(NumExprs == 1 && "Expected 1 expression"); 1230 // Set the init expression, handles conversions. 1231 AddInitializerToDecl(Dcl, ExprTys[0]); 1232} 1233 1234/// PerformInitializationByConstructor - Perform initialization by 1235/// constructor (C++ [dcl.init]p14), which may occur as part of 1236/// direct-initialization or copy-initialization. We are initializing 1237/// an object of type @p ClassType with the given arguments @p 1238/// Args. @p Loc is the location in the source code where the 1239/// initializer occurs (e.g., a declaration, member initializer, 1240/// functional cast, etc.) while @p Range covers the whole 1241/// initialization. @p InitEntity is the entity being initialized, 1242/// which may by the name of a declaration or a type. @p Kind is the 1243/// kind of initialization we're performing, which affects whether 1244/// explicit constructors will be considered. When successful, returns 1245/// the constructor that will be used to perform the initialization; 1246/// when the initialization fails, emits a diagnostic and returns 1247/// null. 1248CXXConstructorDecl * 1249Sema::PerformInitializationByConstructor(QualType ClassType, 1250 Expr **Args, unsigned NumArgs, 1251 SourceLocation Loc, SourceRange Range, 1252 std::string InitEntity, 1253 InitializationKind Kind) { 1254 const RecordType *ClassRec = ClassType->getAsRecordType(); 1255 assert(ClassRec && "Can only initialize a class type here"); 1256 1257 // C++ [dcl.init]p14: 1258 // 1259 // If the initialization is direct-initialization, or if it is 1260 // copy-initialization where the cv-unqualified version of the 1261 // source type is the same class as, or a derived class of, the 1262 // class of the destination, constructors are considered. The 1263 // applicable constructors are enumerated (13.3.1.3), and the 1264 // best one is chosen through overload resolution (13.3). The 1265 // constructor so selected is called to initialize the object, 1266 // with the initializer expression(s) as its argument(s). If no 1267 // constructor applies, or the overload resolution is ambiguous, 1268 // the initialization is ill-formed. 1269 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 1270 OverloadCandidateSet CandidateSet; 1271 1272 // Add constructors to the overload set. 1273 OverloadedFunctionDecl *Constructors 1274 = const_cast<OverloadedFunctionDecl *>(ClassDecl->getConstructors()); 1275 for (OverloadedFunctionDecl::function_iterator Con 1276 = Constructors->function_begin(); 1277 Con != Constructors->function_end(); ++Con) { 1278 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 1279 if ((Kind == IK_Direct) || 1280 (Kind == IK_Copy && Constructor->isConvertingConstructor()) || 1281 (Kind == IK_Default && Constructor->isDefaultConstructor())) 1282 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet); 1283 } 1284 1285 OverloadCandidateSet::iterator Best; 1286 switch (BestViableFunction(CandidateSet, Best)) { 1287 case OR_Success: 1288 // We found a constructor. Return it. 1289 return cast<CXXConstructorDecl>(Best->Function); 1290 1291 case OR_No_Viable_Function: 1292 if (CandidateSet.empty()) 1293 Diag(Loc, diag::err_ovl_no_viable_function_in_init, 1294 InitEntity, Range); 1295 else { 1296 Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands, 1297 InitEntity, Range); 1298 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 1299 } 1300 return 0; 1301 1302 case OR_Ambiguous: 1303 Diag(Loc, diag::err_ovl_ambiguous_init, 1304 InitEntity, Range); 1305 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1306 return 0; 1307 } 1308 1309 return 0; 1310} 1311 1312/// CompareReferenceRelationship - Compare the two types T1 and T2 to 1313/// determine whether they are reference-related, 1314/// reference-compatible, reference-compatible with added 1315/// qualification, or incompatible, for use in C++ initialization by 1316/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 1317/// type, and the first type (T1) is the pointee type of the reference 1318/// type being initialized. 1319Sema::ReferenceCompareResult 1320Sema::CompareReferenceRelationship(QualType T1, QualType T2, 1321 bool& DerivedToBase) { 1322 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type"); 1323 assert(!T2->isReferenceType() && "T2 cannot be a reference type"); 1324 1325 T1 = Context.getCanonicalType(T1); 1326 T2 = Context.getCanonicalType(T2); 1327 QualType UnqualT1 = T1.getUnqualifiedType(); 1328 QualType UnqualT2 = T2.getUnqualifiedType(); 1329 1330 // C++ [dcl.init.ref]p4: 1331 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is 1332 // reference-related to “cv2 T2” if T1 is the same type as T2, or 1333 // T1 is a base class of T2. 1334 if (UnqualT1 == UnqualT2) 1335 DerivedToBase = false; 1336 else if (IsDerivedFrom(UnqualT2, UnqualT1)) 1337 DerivedToBase = true; 1338 else 1339 return Ref_Incompatible; 1340 1341 // At this point, we know that T1 and T2 are reference-related (at 1342 // least). 1343 1344 // C++ [dcl.init.ref]p4: 1345 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is 1346 // reference-related to T2 and cv1 is the same cv-qualification 1347 // as, or greater cv-qualification than, cv2. For purposes of 1348 // overload resolution, cases for which cv1 is greater 1349 // cv-qualification than cv2 are identified as 1350 // reference-compatible with added qualification (see 13.3.3.2). 1351 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 1352 return Ref_Compatible; 1353 else if (T1.isMoreQualifiedThan(T2)) 1354 return Ref_Compatible_With_Added_Qualification; 1355 else 1356 return Ref_Related; 1357} 1358 1359/// CheckReferenceInit - Check the initialization of a reference 1360/// variable with the given initializer (C++ [dcl.init.ref]). Init is 1361/// the initializer (either a simple initializer or an initializer 1362/// list), and DeclType is the type of the declaration. When ICS is 1363/// non-null, this routine will compute the implicit conversion 1364/// sequence according to C++ [over.ics.ref] and will not produce any 1365/// diagnostics; when ICS is null, it will emit diagnostics when any 1366/// errors are found. Either way, a return value of true indicates 1367/// that there was a failure, a return value of false indicates that 1368/// the reference initialization succeeded. 1369/// 1370/// When @p SuppressUserConversions, user-defined conversions are 1371/// suppressed. 1372bool 1373Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType, 1374 ImplicitConversionSequence *ICS, 1375 bool SuppressUserConversions) { 1376 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 1377 1378 QualType T1 = DeclType->getAsReferenceType()->getPointeeType(); 1379 QualType T2 = Init->getType(); 1380 1381 // Compute some basic properties of the types and the initializer. 1382 bool DerivedToBase = false; 1383 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context); 1384 ReferenceCompareResult RefRelationship 1385 = CompareReferenceRelationship(T1, T2, DerivedToBase); 1386 1387 // Most paths end in a failed conversion. 1388 if (ICS) 1389 ICS->ConversionKind = ImplicitConversionSequence::BadConversion; 1390 1391 // C++ [dcl.init.ref]p5: 1392 // A reference to type “cv1 T1” is initialized by an expression 1393 // of type “cv2 T2” as follows: 1394 1395 // -- If the initializer expression 1396 1397 bool BindsDirectly = false; 1398 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is 1399 // reference-compatible with “cv2 T2,” or 1400 // 1401 // Note that the bit-field check is skipped if we are just computing 1402 // the implicit conversion sequence (C++ [over.best.ics]p2). 1403 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) && 1404 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 1405 BindsDirectly = true; 1406 1407 if (ICS) { 1408 // C++ [over.ics.ref]p1: 1409 // When a parameter of reference type binds directly (8.5.3) 1410 // to an argument expression, the implicit conversion sequence 1411 // is the identity conversion, unless the argument expression 1412 // has a type that is a derived class of the parameter type, 1413 // in which case the implicit conversion sequence is a 1414 // derived-to-base Conversion (13.3.3.1). 1415 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 1416 ICS->Standard.First = ICK_Identity; 1417 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 1418 ICS->Standard.Third = ICK_Identity; 1419 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 1420 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 1421 ICS->Standard.ReferenceBinding = true; 1422 ICS->Standard.DirectBinding = true; 1423 1424 // Nothing more to do: the inaccessibility/ambiguity check for 1425 // derived-to-base conversions is suppressed when we're 1426 // computing the implicit conversion sequence (C++ 1427 // [over.best.ics]p2). 1428 return false; 1429 } else { 1430 // Perform the conversion. 1431 // FIXME: Binding to a subobject of the lvalue is going to require 1432 // more AST annotation than this. 1433 ImpCastExprToType(Init, T1); 1434 } 1435 } 1436 1437 // -- has a class type (i.e., T2 is a class type) and can be 1438 // implicitly converted to an lvalue of type “cv3 T3,” 1439 // where “cv1 T1” is reference-compatible with “cv3 T3” 1440 // 92) (this conversion is selected by enumerating the 1441 // applicable conversion functions (13.3.1.6) and choosing 1442 // the best one through overload resolution (13.3)), 1443 // FIXME: Implement this second bullet, once we have conversion 1444 // functions. Also remember C++ [over.ics.ref]p1, second part. 1445 1446 if (BindsDirectly) { 1447 // C++ [dcl.init.ref]p4: 1448 // [...] In all cases where the reference-related or 1449 // reference-compatible relationship of two types is used to 1450 // establish the validity of a reference binding, and T1 is a 1451 // base class of T2, a program that necessitates such a binding 1452 // is ill-formed if T1 is an inaccessible (clause 11) or 1453 // ambiguous (10.2) base class of T2. 1454 // 1455 // Note that we only check this condition when we're allowed to 1456 // complain about errors, because we should not be checking for 1457 // ambiguity (or inaccessibility) unless the reference binding 1458 // actually happens. 1459 if (DerivedToBase) 1460 return CheckDerivedToBaseConversion(T2, T1, 1461 Init->getSourceRange().getBegin(), 1462 Init->getSourceRange()); 1463 else 1464 return false; 1465 } 1466 1467 // -- Otherwise, the reference shall be to a non-volatile const 1468 // type (i.e., cv1 shall be const). 1469 if (T1.getCVRQualifiers() != QualType::Const) { 1470 if (!ICS) 1471 Diag(Init->getSourceRange().getBegin(), 1472 diag::err_not_reference_to_const_init, 1473 T1.getAsString(), 1474 InitLvalue != Expr::LV_Valid? "temporary" : "value", 1475 T2.getAsString(), Init->getSourceRange()); 1476 return true; 1477 } 1478 1479 // -- If the initializer expression is an rvalue, with T2 a 1480 // class type, and “cv1 T1” is reference-compatible with 1481 // “cv2 T2,” the reference is bound in one of the 1482 // following ways (the choice is implementation-defined): 1483 // 1484 // -- The reference is bound to the object represented by 1485 // the rvalue (see 3.10) or to a sub-object within that 1486 // object. 1487 // 1488 // -- A temporary of type “cv1 T2” [sic] is created, and 1489 // a constructor is called to copy the entire rvalue 1490 // object into the temporary. The reference is bound to 1491 // the temporary or to a sub-object within the 1492 // temporary. 1493 // 1494 // 1495 // The constructor that would be used to make the copy 1496 // shall be callable whether or not the copy is actually 1497 // done. 1498 // 1499 // Note that C++0x [dcl.ref.init]p5 takes away this implementation 1500 // freedom, so we will always take the first option and never build 1501 // a temporary in this case. FIXME: We will, however, have to check 1502 // for the presence of a copy constructor in C++98/03 mode. 1503 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() && 1504 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 1505 if (ICS) { 1506 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 1507 ICS->Standard.First = ICK_Identity; 1508 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 1509 ICS->Standard.Third = ICK_Identity; 1510 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 1511 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 1512 ICS->Standard.ReferenceBinding = true; 1513 ICS->Standard.DirectBinding = false; 1514 } else { 1515 // FIXME: Binding to a subobject of the rvalue is going to require 1516 // more AST annotation than this. 1517 ImpCastExprToType(Init, T1); 1518 } 1519 return false; 1520 } 1521 1522 // -- Otherwise, a temporary of type “cv1 T1” is created and 1523 // initialized from the initializer expression using the 1524 // rules for a non-reference copy initialization (8.5). The 1525 // reference is then bound to the temporary. If T1 is 1526 // reference-related to T2, cv1 must be the same 1527 // cv-qualification as, or greater cv-qualification than, 1528 // cv2; otherwise, the program is ill-formed. 1529 if (RefRelationship == Ref_Related) { 1530 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 1531 // we would be reference-compatible or reference-compatible with 1532 // added qualification. But that wasn't the case, so the reference 1533 // initialization fails. 1534 if (!ICS) 1535 Diag(Init->getSourceRange().getBegin(), 1536 diag::err_reference_init_drops_quals, 1537 T1.getAsString(), 1538 InitLvalue != Expr::LV_Valid? "temporary" : "value", 1539 T2.getAsString(), Init->getSourceRange()); 1540 return true; 1541 } 1542 1543 // Actually try to convert the initializer to T1. 1544 if (ICS) { 1545 /// C++ [over.ics.ref]p2: 1546 /// 1547 /// When a parameter of reference type is not bound directly to 1548 /// an argument expression, the conversion sequence is the one 1549 /// required to convert the argument expression to the 1550 /// underlying type of the reference according to 1551 /// 13.3.3.1. Conceptually, this conversion sequence corresponds 1552 /// to copy-initializing a temporary of the underlying type with 1553 /// the argument expression. Any difference in top-level 1554 /// cv-qualification is subsumed by the initialization itself 1555 /// and does not constitute a conversion. 1556 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions); 1557 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion; 1558 } else { 1559 return PerformImplicitConversion(Init, T1); 1560 } 1561} 1562