SemaDeclCXX.cpp revision 64bffa9a6f40e5a3d5556f994f09f7bf45eecd4c
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 TypedefDecl *InjectedClassName 387 = TypedefDecl::Create(Context, Dcl, LBrace, Dcl->getIdentifier(), 388 Context.getTypeDeclType(Dcl), /*PrevDecl=*/0); 389 PushOnScopeChains(InjectedClassName, S); 390 } 391} 392 393/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 394/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 395/// bitfield width if there is one and 'InitExpr' specifies the initializer if 396/// any. 'LastInGroup' is non-null for cases where one declspec has multiple 397/// declarators on it. 398/// 399/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if 400/// an instance field is declared, a new CXXFieldDecl is created but the method 401/// does *not* return it; it returns LastInGroup instead. The other C++ members 402/// (which are all ScopedDecls) are returned after appending them to 403/// LastInGroup. 404Sema::DeclTy * 405Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 406 ExprTy *BW, ExprTy *InitExpr, 407 DeclTy *LastInGroup) { 408 const DeclSpec &DS = D.getDeclSpec(); 409 IdentifierInfo *II = D.getIdentifier(); 410 Expr *BitWidth = static_cast<Expr*>(BW); 411 Expr *Init = static_cast<Expr*>(InitExpr); 412 SourceLocation Loc = D.getIdentifierLoc(); 413 414 // C++ 9.2p6: A member shall not be declared to have automatic storage 415 // duration (auto, register) or with the extern storage-class-specifier. 416 switch (DS.getStorageClassSpec()) { 417 case DeclSpec::SCS_unspecified: 418 case DeclSpec::SCS_typedef: 419 case DeclSpec::SCS_static: 420 // FALL THROUGH. 421 break; 422 default: 423 if (DS.getStorageClassSpecLoc().isValid()) 424 Diag(DS.getStorageClassSpecLoc(), 425 diag::err_storageclass_invalid_for_member); 426 else 427 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 428 D.getMutableDeclSpec().ClearStorageClassSpecs(); 429 } 430 431 bool isFunc = D.isFunctionDeclarator(); 432 if (!isFunc && 433 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef && 434 D.getNumTypeObjects() == 0) { 435 // Check also for this case: 436 // 437 // typedef int f(); 438 // f a; 439 // 440 Decl *TD = static_cast<Decl *>(DS.getTypeRep()); 441 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType(); 442 } 443 444 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified && 445 !isFunc); 446 447 Decl *Member; 448 bool InvalidDecl = false; 449 450 if (isInstField) 451 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth)); 452 else 453 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup)); 454 455 if (!Member) return LastInGroup; 456 457 assert((II || isInstField) && "No identifier for non-field ?"); 458 459 // set/getAccess is not part of Decl's interface to avoid bloating it with C++ 460 // specific methods. Use a wrapper class that can be used with all C++ class 461 // member decls. 462 CXXClassMemberWrapper(Member).setAccess(AS); 463 464 // C++ [dcl.init.aggr]p1: 465 // An aggregate is an array or a class (clause 9) with [...] no 466 // private or protected non-static data members (clause 11). 467 if (isInstField && (AS == AS_private || AS == AS_protected)) 468 cast<CXXRecordDecl>(CurContext)->setAggregate(false); 469 470 // FIXME: If the member is a virtual function, mark it its class as 471 // a non-aggregate. 472 473 if (BitWidth) { 474 // C++ 9.6p2: Only when declaring an unnamed bit-field may the 475 // constant-expression be a value equal to zero. 476 // FIXME: Check this. 477 478 if (D.isFunctionDeclarator()) { 479 // FIXME: Emit diagnostic about only constructors taking base initializers 480 // or something similar, when constructor support is in place. 481 Diag(Loc, diag::err_not_bitfield_type, 482 II->getName(), BitWidth->getSourceRange()); 483 InvalidDecl = true; 484 485 } else if (isInstField) { 486 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 487 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) { 488 Diag(Loc, diag::err_not_integral_type_bitfield, 489 II->getName(), BitWidth->getSourceRange()); 490 InvalidDecl = true; 491 } 492 493 } else if (isa<FunctionDecl>(Member)) { 494 // A function typedef ("typedef int f(); f a;"). 495 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 496 Diag(Loc, diag::err_not_integral_type_bitfield, 497 II->getName(), BitWidth->getSourceRange()); 498 InvalidDecl = true; 499 500 } else if (isa<TypedefDecl>(Member)) { 501 // "cannot declare 'A' to be a bit-field type" 502 Diag(Loc, diag::err_not_bitfield_type, II->getName(), 503 BitWidth->getSourceRange()); 504 InvalidDecl = true; 505 506 } else { 507 assert(isa<CXXClassVarDecl>(Member) && 508 "Didn't we cover all member kinds?"); 509 // C++ 9.6p3: A bit-field shall not be a static member. 510 // "static member 'A' cannot be a bit-field" 511 Diag(Loc, diag::err_static_not_bitfield, II->getName(), 512 BitWidth->getSourceRange()); 513 InvalidDecl = true; 514 } 515 } 516 517 if (Init) { 518 // C++ 9.2p4: A member-declarator can contain a constant-initializer only 519 // if it declares a static member of const integral or const enumeration 520 // type. 521 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) { 522 // ...static member of... 523 CVD->setInit(Init); 524 // ...const integral or const enumeration type. 525 if (Context.getCanonicalType(CVD->getType()).isConstQualified() && 526 CVD->getType()->isIntegralType()) { 527 // constant-initializer 528 if (CheckForConstantInitializer(Init, CVD->getType())) 529 InvalidDecl = true; 530 531 } else { 532 // not const integral. 533 Diag(Loc, diag::err_member_initialization, 534 II->getName(), Init->getSourceRange()); 535 InvalidDecl = true; 536 } 537 538 } else { 539 // not static member. 540 Diag(Loc, diag::err_member_initialization, 541 II->getName(), Init->getSourceRange()); 542 InvalidDecl = true; 543 } 544 } 545 546 if (InvalidDecl) 547 Member->setInvalidDecl(); 548 549 if (isInstField) { 550 FieldCollector->Add(cast<CXXFieldDecl>(Member)); 551 return LastInGroup; 552 } 553 return Member; 554} 555 556/// ActOnMemInitializer - Handle a C++ member initializer. 557Sema::MemInitResult 558Sema::ActOnMemInitializer(DeclTy *ConstructorD, 559 Scope *S, 560 IdentifierInfo *MemberOrBase, 561 SourceLocation IdLoc, 562 SourceLocation LParenLoc, 563 ExprTy **Args, unsigned NumArgs, 564 SourceLocation *CommaLocs, 565 SourceLocation RParenLoc) { 566 CXXConstructorDecl *Constructor 567 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD); 568 if (!Constructor) { 569 // The user wrote a constructor initializer on a function that is 570 // not a C++ constructor. Ignore the error for now, because we may 571 // have more member initializers coming; we'll diagnose it just 572 // once in ActOnMemInitializers. 573 return true; 574 } 575 576 CXXRecordDecl *ClassDecl = Constructor->getParent(); 577 578 // C++ [class.base.init]p2: 579 // Names in a mem-initializer-id are looked up in the scope of the 580 // constructor’s class and, if not found in that scope, are looked 581 // up in the scope containing the constructor’s 582 // definition. [Note: if the constructor’s class contains a member 583 // with the same name as a direct or virtual base class of the 584 // class, a mem-initializer-id naming the member or base class and 585 // composed of a single identifier refers to the class member. A 586 // mem-initializer-id for the hidden base class may be specified 587 // using a qualified name. ] 588 // Look for a member, first. 589 CXXFieldDecl *Member = ClassDecl->getMember(MemberOrBase); 590 591 // FIXME: Handle members of an anonymous union. 592 593 if (Member) { 594 // FIXME: Perform direct initialization of the member. 595 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs); 596 } 597 598 // It didn't name a member, so see if it names a class. 599 TypeTy *BaseTy = isTypeName(*MemberOrBase, S); 600 if (!BaseTy) 601 return Diag(IdLoc, diag::err_mem_init_not_member_or_class, 602 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc)); 603 604 QualType BaseType = Context.getTypeDeclType((TypeDecl *)BaseTy); 605 if (!BaseType->isRecordType()) 606 return Diag(IdLoc, diag::err_base_init_does_not_name_class, 607 BaseType.getAsString(), SourceRange(IdLoc, RParenLoc)); 608 609 // C++ [class.base.init]p2: 610 // [...] Unless the mem-initializer-id names a nonstatic data 611 // member of the constructor’s class or a direct or virtual base 612 // of that class, the mem-initializer is ill-formed. A 613 // mem-initializer-list can initialize a base class using any 614 // name that denotes that base class type. 615 616 // First, check for a direct base class. 617 const CXXBaseSpecifier *DirectBaseSpec = 0; 618 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 619 Base != ClassDecl->bases_end(); ++Base) { 620 if (Context.getCanonicalType(BaseType).getUnqualifiedType() == 621 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) { 622 // We found a direct base of this type. That's what we're 623 // initializing. 624 DirectBaseSpec = &*Base; 625 break; 626 } 627 } 628 629 // Check for a virtual base class. 630 // FIXME: We might be able to short-circuit this if we know in 631 // advance that there are no virtual bases. 632 const CXXBaseSpecifier *VirtualBaseSpec = 0; 633 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 634 // We haven't found a base yet; search the class hierarchy for a 635 // virtual base class. 636 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 637 /*DetectVirtual=*/false); 638 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) { 639 for (BasePaths::paths_iterator Path = Paths.begin(); 640 Path != Paths.end(); ++Path) { 641 if (Path->back().Base->isVirtual()) { 642 VirtualBaseSpec = Path->back().Base; 643 break; 644 } 645 } 646 } 647 } 648 649 // C++ [base.class.init]p2: 650 // If a mem-initializer-id is ambiguous because it designates both 651 // a direct non-virtual base class and an inherited virtual base 652 // class, the mem-initializer is ill-formed. 653 if (DirectBaseSpec && VirtualBaseSpec) 654 return Diag(IdLoc, diag::err_base_init_direct_and_virtual, 655 MemberOrBase->getName(), SourceRange(IdLoc, RParenLoc)); 656 657 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs); 658} 659 660 661void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 662 DeclTy *TagDecl, 663 SourceLocation LBrac, 664 SourceLocation RBrac) { 665 ActOnFields(S, RLoc, TagDecl, 666 (DeclTy**)FieldCollector->getCurFields(), 667 FieldCollector->getCurNumFields(), LBrac, RBrac, 0); 668} 669 670/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 671/// special functions, such as the default constructor, copy 672/// constructor, or destructor, to the given C++ class (C++ 673/// [special]p1). This routine can only be executed just before the 674/// definition of the class is complete. 675void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 676 if (!ClassDecl->hasUserDeclaredConstructor()) { 677 // C++ [class.ctor]p5: 678 // A default constructor for a class X is a constructor of class X 679 // that can be called without an argument. If there is no 680 // user-declared constructor for class X, a default constructor is 681 // implicitly declared. An implicitly-declared default constructor 682 // is an inline public member of its class. 683 CXXConstructorDecl *DefaultCon = 684 CXXConstructorDecl::Create(Context, ClassDecl, 685 ClassDecl->getLocation(), 686 ClassDecl->getIdentifier(), 687 Context.getFunctionType(Context.VoidTy, 688 0, 0, false, 0), 689 /*isExplicit=*/false, 690 /*isInline=*/true, 691 /*isImplicitlyDeclared=*/true); 692 DefaultCon->setAccess(AS_public); 693 ClassDecl->addConstructor(Context, DefaultCon); 694 } 695 696 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 697 // C++ [class.copy]p4: 698 // If the class definition does not explicitly declare a copy 699 // constructor, one is declared implicitly. 700 701 // C++ [class.copy]p5: 702 // The implicitly-declared copy constructor for a class X will 703 // have the form 704 // 705 // X::X(const X&) 706 // 707 // if 708 bool HasConstCopyConstructor = true; 709 710 // -- each direct or virtual base class B of X has a copy 711 // constructor whose first parameter is of type const B& or 712 // const volatile B&, and 713 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 714 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 715 const CXXRecordDecl *BaseClassDecl 716 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl()); 717 HasConstCopyConstructor 718 = BaseClassDecl->hasConstCopyConstructor(Context); 719 } 720 721 // -- for all the nonstatic data members of X that are of a 722 // class type M (or array thereof), each such class type 723 // has a copy constructor whose first parameter is of type 724 // const M& or const volatile M&. 725 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 726 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) { 727 QualType FieldType = (*Field)->getType(); 728 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 729 FieldType = Array->getElementType(); 730 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) { 731 const CXXRecordDecl *FieldClassDecl 732 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 733 HasConstCopyConstructor 734 = FieldClassDecl->hasConstCopyConstructor(Context); 735 } 736 } 737 738 // Otherwise, the implicitly declared copy constructor will have 739 // the form 740 // 741 // X::X(X&) 742 QualType ArgType = Context.getTypeDeclType(ClassDecl); 743 if (HasConstCopyConstructor) 744 ArgType = ArgType.withConst(); 745 ArgType = Context.getReferenceType(ArgType); 746 747 // An implicitly-declared copy constructor is an inline public 748 // member of its class. 749 CXXConstructorDecl *CopyConstructor 750 = CXXConstructorDecl::Create(Context, ClassDecl, 751 ClassDecl->getLocation(), 752 ClassDecl->getIdentifier(), 753 Context.getFunctionType(Context.VoidTy, 754 &ArgType, 1, 755 false, 0), 756 /*isExplicit=*/false, 757 /*isInline=*/true, 758 /*isImplicitlyDeclared=*/true); 759 CopyConstructor->setAccess(AS_public); 760 761 // Add the parameter to the constructor. 762 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 763 ClassDecl->getLocation(), 764 /*IdentifierInfo=*/0, 765 ArgType, VarDecl::None, 0, 0); 766 CopyConstructor->setParams(&FromParam, 1); 767 768 ClassDecl->addConstructor(Context, CopyConstructor); 769 } 770 771 // FIXME: Implicit destructor 772 // FIXME: Implicit copy assignment operator 773} 774 775void Sema::ActOnFinishCXXClassDef(DeclTy *D) { 776 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D)); 777 FieldCollector->FinishClass(); 778 AddImplicitlyDeclaredMembersToClass(Rec); 779 PopDeclContext(); 780 781 // Everything, including inline method definitions, have been parsed. 782 // Let the consumer know of the new TagDecl definition. 783 Consumer.HandleTagDeclDefinition(Rec); 784} 785 786/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete 787/// the declaration of the given C++ constructor ConDecl that was 788/// built from declarator D. This routine is responsible for checking 789/// that the newly-created constructor declaration is well-formed and 790/// for recording it in the C++ class. Example: 791/// 792/// @code 793/// class X { 794/// X(); // X::X() will be the ConDecl. 795/// }; 796/// @endcode 797Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) { 798 assert(ConDecl && "Expected to receive a constructor declaration"); 799 800 // Check default arguments on the constructor 801 CheckCXXDefaultArguments(ConDecl); 802 803 CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 804 if (!ClassDecl) { 805 ConDecl->setInvalidDecl(); 806 return ConDecl; 807 } 808 809 // Make sure this constructor is an overload of the existing 810 // constructors. 811 OverloadedFunctionDecl::function_iterator MatchedDecl; 812 if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) { 813 Diag(ConDecl->getLocation(), 814 diag::err_constructor_redeclared, 815 SourceRange(ConDecl->getLocation())); 816 Diag((*MatchedDecl)->getLocation(), 817 diag::err_previous_declaration, 818 SourceRange((*MatchedDecl)->getLocation())); 819 ConDecl->setInvalidDecl(); 820 return ConDecl; 821 } 822 823 824 // C++ [class.copy]p3: 825 // A declaration of a constructor for a class X is ill-formed if 826 // its first parameter is of type (optionally cv-qualified) X and 827 // either there are no other parameters or else all other 828 // parameters have default arguments. 829 if ((ConDecl->getNumParams() == 1) || 830 (ConDecl->getNumParams() > 1 && 831 ConDecl->getParamDecl(1)->getDefaultArg() != 0)) { 832 QualType ParamType = ConDecl->getParamDecl(0)->getType(); 833 QualType ClassTy = Context.getTagDeclType( 834 const_cast<CXXRecordDecl*>(ConDecl->getParent())); 835 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 836 Diag(ConDecl->getLocation(), 837 diag::err_constructor_byvalue_arg, 838 SourceRange(ConDecl->getParamDecl(0)->getLocation())); 839 ConDecl->setInvalidDecl(); 840 return 0; 841 } 842 } 843 844 // Add this constructor to the set of constructors of the current 845 // class. 846 ClassDecl->addConstructor(Context, ConDecl); 847 return (DeclTy *)ConDecl; 848} 849 850//===----------------------------------------------------------------------===// 851// Namespace Handling 852//===----------------------------------------------------------------------===// 853 854/// ActOnStartNamespaceDef - This is called at the start of a namespace 855/// definition. 856Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 857 SourceLocation IdentLoc, 858 IdentifierInfo *II, 859 SourceLocation LBrace) { 860 NamespaceDecl *Namespc = 861 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 862 Namespc->setLBracLoc(LBrace); 863 864 Scope *DeclRegionScope = NamespcScope->getParent(); 865 866 if (II) { 867 // C++ [namespace.def]p2: 868 // The identifier in an original-namespace-definition shall not have been 869 // previously defined in the declarative region in which the 870 // original-namespace-definition appears. The identifier in an 871 // original-namespace-definition is the name of the namespace. Subsequently 872 // in that declarative region, it is treated as an original-namespace-name. 873 874 Decl *PrevDecl = 875 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 876 /*enableLazyBuiltinCreation=*/false); 877 878 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) { 879 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) { 880 // This is an extended namespace definition. 881 // Attach this namespace decl to the chain of extended namespace 882 // definitions. 883 NamespaceDecl *NextNS = OrigNS; 884 while (NextNS->getNextNamespace()) 885 NextNS = NextNS->getNextNamespace(); 886 887 NextNS->setNextNamespace(Namespc); 888 Namespc->setOriginalNamespace(OrigNS); 889 890 // We won't add this decl to the current scope. We want the namespace 891 // name to return the original namespace decl during a name lookup. 892 } else { 893 // This is an invalid name redefinition. 894 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind, 895 Namespc->getName()); 896 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 897 Namespc->setInvalidDecl(); 898 // Continue on to push Namespc as current DeclContext and return it. 899 } 900 } else { 901 // This namespace name is declared for the first time. 902 PushOnScopeChains(Namespc, DeclRegionScope); 903 } 904 } 905 else { 906 // FIXME: Handle anonymous namespaces 907 } 908 909 // Although we could have an invalid decl (i.e. the namespace name is a 910 // redefinition), push it as current DeclContext and try to continue parsing. 911 PushDeclContext(Namespc->getOriginalNamespace()); 912 return Namespc; 913} 914 915/// ActOnFinishNamespaceDef - This callback is called after a namespace is 916/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 917void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) { 918 Decl *Dcl = static_cast<Decl *>(D); 919 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 920 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 921 Namespc->setRBracLoc(RBrace); 922 PopDeclContext(); 923} 924 925 926/// AddCXXDirectInitializerToDecl - This action is called immediately after 927/// ActOnDeclarator, when a C++ direct initializer is present. 928/// e.g: "int x(1);" 929void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc, 930 ExprTy **ExprTys, unsigned NumExprs, 931 SourceLocation *CommaLocs, 932 SourceLocation RParenLoc) { 933 assert(NumExprs != 0 && ExprTys && "missing expressions"); 934 Decl *RealDecl = static_cast<Decl *>(Dcl); 935 936 // If there is no declaration, there was an error parsing it. Just ignore 937 // the initializer. 938 if (RealDecl == 0) { 939 for (unsigned i = 0; i != NumExprs; ++i) 940 delete static_cast<Expr *>(ExprTys[i]); 941 return; 942 } 943 944 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 945 if (!VDecl) { 946 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 947 RealDecl->setInvalidDecl(); 948 return; 949 } 950 951 // We will treat direct-initialization as a copy-initialization: 952 // int x(1); -as-> int x = 1; 953 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 954 // 955 // Clients that want to distinguish between the two forms, can check for 956 // direct initializer using VarDecl::hasCXXDirectInitializer(). 957 // A major benefit is that clients that don't particularly care about which 958 // exactly form was it (like the CodeGen) can handle both cases without 959 // special case code. 960 961 // C++ 8.5p11: 962 // The form of initialization (using parentheses or '=') is generally 963 // insignificant, but does matter when the entity being initialized has a 964 // class type. 965 QualType DeclInitType = VDecl->getType(); 966 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 967 DeclInitType = Array->getElementType(); 968 969 if (VDecl->getType()->isRecordType()) { 970 CXXConstructorDecl *Constructor 971 = PerformInitializationByConstructor(DeclInitType, 972 (Expr **)ExprTys, NumExprs, 973 VDecl->getLocation(), 974 SourceRange(VDecl->getLocation(), 975 RParenLoc), 976 VDecl->getName(), 977 IK_Direct); 978 if (!Constructor) { 979 RealDecl->setInvalidDecl(); 980 } 981 982 // Let clients know that initialization was done with a direct 983 // initializer. 984 VDecl->setCXXDirectInitializer(true); 985 986 // FIXME: Add ExprTys and Constructor to the RealDecl as part of 987 // the initializer. 988 return; 989 } 990 991 if (NumExprs > 1) { 992 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg, 993 SourceRange(VDecl->getLocation(), RParenLoc)); 994 RealDecl->setInvalidDecl(); 995 return; 996 } 997 998 // Let clients know that initialization was done with a direct initializer. 999 VDecl->setCXXDirectInitializer(true); 1000 1001 assert(NumExprs == 1 && "Expected 1 expression"); 1002 // Set the init expression, handles conversions. 1003 AddInitializerToDecl(Dcl, ExprTys[0]); 1004} 1005 1006/// PerformInitializationByConstructor - Perform initialization by 1007/// constructor (C++ [dcl.init]p14), which may occur as part of 1008/// direct-initialization or copy-initialization. We are initializing 1009/// an object of type @p ClassType with the given arguments @p 1010/// Args. @p Loc is the location in the source code where the 1011/// initializer occurs (e.g., a declaration, member initializer, 1012/// functional cast, etc.) while @p Range covers the whole 1013/// initialization. @p InitEntity is the entity being initialized, 1014/// which may by the name of a declaration or a type. @p Kind is the 1015/// kind of initialization we're performing, which affects whether 1016/// explicit constructors will be considered. When successful, returns 1017/// the constructor that will be used to perform the initialization; 1018/// when the initialization fails, emits a diagnostic and returns 1019/// null. 1020CXXConstructorDecl * 1021Sema::PerformInitializationByConstructor(QualType ClassType, 1022 Expr **Args, unsigned NumArgs, 1023 SourceLocation Loc, SourceRange Range, 1024 std::string InitEntity, 1025 InitializationKind Kind) { 1026 const RecordType *ClassRec = ClassType->getAsRecordType(); 1027 assert(ClassRec && "Can only initialize a class type here"); 1028 1029 // C++ [dcl.init]p14: 1030 // 1031 // If the initialization is direct-initialization, or if it is 1032 // copy-initialization where the cv-unqualified version of the 1033 // source type is the same class as, or a derived class of, the 1034 // class of the destination, constructors are considered. The 1035 // applicable constructors are enumerated (13.3.1.3), and the 1036 // best one is chosen through overload resolution (13.3). The 1037 // constructor so selected is called to initialize the object, 1038 // with the initializer expression(s) as its argument(s). If no 1039 // constructor applies, or the overload resolution is ambiguous, 1040 // the initialization is ill-formed. 1041 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 1042 OverloadCandidateSet CandidateSet; 1043 1044 // Add constructors to the overload set. 1045 OverloadedFunctionDecl *Constructors 1046 = const_cast<OverloadedFunctionDecl *>(ClassDecl->getConstructors()); 1047 for (OverloadedFunctionDecl::function_iterator Con 1048 = Constructors->function_begin(); 1049 Con != Constructors->function_end(); ++Con) { 1050 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con); 1051 if ((Kind == IK_Direct) || 1052 (Kind == IK_Copy && Constructor->isConvertingConstructor()) || 1053 (Kind == IK_Default && Constructor->isDefaultConstructor())) 1054 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet); 1055 } 1056 1057 OverloadCandidateSet::iterator Best; 1058 switch (BestViableFunction(CandidateSet, Best)) { 1059 case OR_Success: 1060 // We found a constructor. Return it. 1061 return cast<CXXConstructorDecl>(Best->Function); 1062 1063 case OR_No_Viable_Function: 1064 if (CandidateSet.empty()) 1065 Diag(Loc, diag::err_ovl_no_viable_function_in_init, 1066 InitEntity, Range); 1067 else { 1068 Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands, 1069 InitEntity, Range); 1070 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 1071 } 1072 return 0; 1073 1074 case OR_Ambiguous: 1075 Diag(Loc, diag::err_ovl_ambiguous_init, 1076 InitEntity, Range); 1077 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 1078 return 0; 1079 } 1080 1081 return 0; 1082} 1083 1084/// CompareReferenceRelationship - Compare the two types T1 and T2 to 1085/// determine whether they are reference-related, 1086/// reference-compatible, reference-compatible with added 1087/// qualification, or incompatible, for use in C++ initialization by 1088/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 1089/// type, and the first type (T1) is the pointee type of the reference 1090/// type being initialized. 1091Sema::ReferenceCompareResult 1092Sema::CompareReferenceRelationship(QualType T1, QualType T2, 1093 bool& DerivedToBase) { 1094 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type"); 1095 assert(!T2->isReferenceType() && "T2 cannot be a reference type"); 1096 1097 T1 = Context.getCanonicalType(T1); 1098 T2 = Context.getCanonicalType(T2); 1099 QualType UnqualT1 = T1.getUnqualifiedType(); 1100 QualType UnqualT2 = T2.getUnqualifiedType(); 1101 1102 // C++ [dcl.init.ref]p4: 1103 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is 1104 // reference-related to “cv2 T2” if T1 is the same type as T2, or 1105 // T1 is a base class of T2. 1106 if (UnqualT1 == UnqualT2) 1107 DerivedToBase = false; 1108 else if (IsDerivedFrom(UnqualT2, UnqualT1)) 1109 DerivedToBase = true; 1110 else 1111 return Ref_Incompatible; 1112 1113 // At this point, we know that T1 and T2 are reference-related (at 1114 // least). 1115 1116 // C++ [dcl.init.ref]p4: 1117 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is 1118 // reference-related to T2 and cv1 is the same cv-qualification 1119 // as, or greater cv-qualification than, cv2. For purposes of 1120 // overload resolution, cases for which cv1 is greater 1121 // cv-qualification than cv2 are identified as 1122 // reference-compatible with added qualification (see 13.3.3.2). 1123 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 1124 return Ref_Compatible; 1125 else if (T1.isMoreQualifiedThan(T2)) 1126 return Ref_Compatible_With_Added_Qualification; 1127 else 1128 return Ref_Related; 1129} 1130 1131/// CheckReferenceInit - Check the initialization of a reference 1132/// variable with the given initializer (C++ [dcl.init.ref]). Init is 1133/// the initializer (either a simple initializer or an initializer 1134/// list), and DeclType is the type of the declaration. When ICS is 1135/// non-null, this routine will compute the implicit conversion 1136/// sequence according to C++ [over.ics.ref] and will not produce any 1137/// diagnostics; when ICS is null, it will emit diagnostics when any 1138/// errors are found. Either way, a return value of true indicates 1139/// that there was a failure, a return value of false indicates that 1140/// the reference initialization succeeded. 1141/// 1142/// When @p SuppressUserConversions, user-defined conversions are 1143/// suppressed. 1144bool 1145Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType, 1146 ImplicitConversionSequence *ICS, 1147 bool SuppressUserConversions) { 1148 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 1149 1150 QualType T1 = DeclType->getAsReferenceType()->getPointeeType(); 1151 QualType T2 = Init->getType(); 1152 1153 // Compute some basic properties of the types and the initializer. 1154 bool DerivedToBase = false; 1155 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context); 1156 ReferenceCompareResult RefRelationship 1157 = CompareReferenceRelationship(T1, T2, DerivedToBase); 1158 1159 // Most paths end in a failed conversion. 1160 if (ICS) 1161 ICS->ConversionKind = ImplicitConversionSequence::BadConversion; 1162 1163 // C++ [dcl.init.ref]p5: 1164 // A reference to type “cv1 T1” is initialized by an expression 1165 // of type “cv2 T2” as follows: 1166 1167 // -- If the initializer expression 1168 1169 bool BindsDirectly = false; 1170 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is 1171 // reference-compatible with “cv2 T2,” or 1172 // 1173 // Note that the bit-field check is skipped if we are just computing 1174 // the implicit conversion sequence (C++ [over.best.ics]p2). 1175 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) && 1176 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 1177 BindsDirectly = true; 1178 1179 if (ICS) { 1180 // C++ [over.ics.ref]p1: 1181 // When a parameter of reference type binds directly (8.5.3) 1182 // to an argument expression, the implicit conversion sequence 1183 // is the identity conversion, unless the argument expression 1184 // has a type that is a derived class of the parameter type, 1185 // in which case the implicit conversion sequence is a 1186 // derived-to-base Conversion (13.3.3.1). 1187 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 1188 ICS->Standard.First = ICK_Identity; 1189 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 1190 ICS->Standard.Third = ICK_Identity; 1191 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 1192 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 1193 ICS->Standard.ReferenceBinding = true; 1194 ICS->Standard.DirectBinding = true; 1195 1196 // Nothing more to do: the inaccessibility/ambiguity check for 1197 // derived-to-base conversions is suppressed when we're 1198 // computing the implicit conversion sequence (C++ 1199 // [over.best.ics]p2). 1200 return false; 1201 } else { 1202 // Perform the conversion. 1203 // FIXME: Binding to a subobject of the lvalue is going to require 1204 // more AST annotation than this. 1205 ImpCastExprToType(Init, T1); 1206 } 1207 } 1208 1209 // -- has a class type (i.e., T2 is a class type) and can be 1210 // implicitly converted to an lvalue of type “cv3 T3,” 1211 // where “cv1 T1” is reference-compatible with “cv3 T3” 1212 // 92) (this conversion is selected by enumerating the 1213 // applicable conversion functions (13.3.1.6) and choosing 1214 // the best one through overload resolution (13.3)), 1215 // FIXME: Implement this second bullet, once we have conversion 1216 // functions. Also remember C++ [over.ics.ref]p1, second part. 1217 1218 if (BindsDirectly) { 1219 // C++ [dcl.init.ref]p4: 1220 // [...] In all cases where the reference-related or 1221 // reference-compatible relationship of two types is used to 1222 // establish the validity of a reference binding, and T1 is a 1223 // base class of T2, a program that necessitates such a binding 1224 // is ill-formed if T1 is an inaccessible (clause 11) or 1225 // ambiguous (10.2) base class of T2. 1226 // 1227 // Note that we only check this condition when we're allowed to 1228 // complain about errors, because we should not be checking for 1229 // ambiguity (or inaccessibility) unless the reference binding 1230 // actually happens. 1231 if (DerivedToBase) 1232 return CheckDerivedToBaseConversion(T2, T1, 1233 Init->getSourceRange().getBegin(), 1234 Init->getSourceRange()); 1235 else 1236 return false; 1237 } 1238 1239 // -- Otherwise, the reference shall be to a non-volatile const 1240 // type (i.e., cv1 shall be const). 1241 if (T1.getCVRQualifiers() != QualType::Const) { 1242 if (!ICS) 1243 Diag(Init->getSourceRange().getBegin(), 1244 diag::err_not_reference_to_const_init, 1245 T1.getAsString(), 1246 InitLvalue != Expr::LV_Valid? "temporary" : "value", 1247 T2.getAsString(), Init->getSourceRange()); 1248 return true; 1249 } 1250 1251 // -- If the initializer expression is an rvalue, with T2 a 1252 // class type, and “cv1 T1” is reference-compatible with 1253 // “cv2 T2,” the reference is bound in one of the 1254 // following ways (the choice is implementation-defined): 1255 // 1256 // -- The reference is bound to the object represented by 1257 // the rvalue (see 3.10) or to a sub-object within that 1258 // object. 1259 // 1260 // -- A temporary of type “cv1 T2” [sic] is created, and 1261 // a constructor is called to copy the entire rvalue 1262 // object into the temporary. The reference is bound to 1263 // the temporary or to a sub-object within the 1264 // temporary. 1265 // 1266 // 1267 // The constructor that would be used to make the copy 1268 // shall be callable whether or not the copy is actually 1269 // done. 1270 // 1271 // Note that C++0x [dcl.ref.init]p5 takes away this implementation 1272 // freedom, so we will always take the first option and never build 1273 // a temporary in this case. FIXME: We will, however, have to check 1274 // for the presence of a copy constructor in C++98/03 mode. 1275 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() && 1276 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 1277 if (ICS) { 1278 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 1279 ICS->Standard.First = ICK_Identity; 1280 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 1281 ICS->Standard.Third = ICK_Identity; 1282 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 1283 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 1284 ICS->Standard.ReferenceBinding = true; 1285 ICS->Standard.DirectBinding = false; 1286 } else { 1287 // FIXME: Binding to a subobject of the rvalue is going to require 1288 // more AST annotation than this. 1289 ImpCastExprToType(Init, T1); 1290 } 1291 return false; 1292 } 1293 1294 // -- Otherwise, a temporary of type “cv1 T1” is created and 1295 // initialized from the initializer expression using the 1296 // rules for a non-reference copy initialization (8.5). The 1297 // reference is then bound to the temporary. If T1 is 1298 // reference-related to T2, cv1 must be the same 1299 // cv-qualification as, or greater cv-qualification than, 1300 // cv2; otherwise, the program is ill-formed. 1301 if (RefRelationship == Ref_Related) { 1302 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 1303 // we would be reference-compatible or reference-compatible with 1304 // added qualification. But that wasn't the case, so the reference 1305 // initialization fails. 1306 if (!ICS) 1307 Diag(Init->getSourceRange().getBegin(), 1308 diag::err_reference_init_drops_quals, 1309 T1.getAsString(), 1310 InitLvalue != Expr::LV_Valid? "temporary" : "value", 1311 T2.getAsString(), Init->getSourceRange()); 1312 return true; 1313 } 1314 1315 // Actually try to convert the initializer to T1. 1316 if (ICS) { 1317 /// C++ [over.ics.ref]p2: 1318 /// 1319 /// When a parameter of reference type is not bound directly to 1320 /// an argument expression, the conversion sequence is the one 1321 /// required to convert the argument expression to the 1322 /// underlying type of the reference according to 1323 /// 13.3.3.1. Conceptually, this conversion sequence corresponds 1324 /// to copy-initializing a temporary of the underlying type with 1325 /// the argument expression. Any difference in top-level 1326 /// cv-qualification is subsumed by the initialization itself 1327 /// and does not constitute a conversion. 1328 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions); 1329 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion; 1330 } else { 1331 return PerformImplicitConversion(Init, T1); 1332 } 1333} 1334