SemaDeclCXX.cpp revision 796da18402f286b897782a298ae3b20c459c102e
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 "clang/AST/ASTConsumer.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/TypeOrdering.h" 18#include "clang/AST/StmtVisitor.h" 19#include "clang/Lex/Preprocessor.h" 20#include "clang/Basic/Diagnostic.h" 21#include "clang/Parse/DeclSpec.h" 22#include "llvm/Support/Compiler.h" 23#include <algorithm> // for std::equal 24#include <map> 25 26using namespace clang; 27 28//===----------------------------------------------------------------------===// 29// CheckDefaultArgumentVisitor 30//===----------------------------------------------------------------------===// 31 32namespace { 33 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 34 /// the default argument of a parameter to determine whether it 35 /// contains any ill-formed subexpressions. For example, this will 36 /// diagnose the use of local variables or parameters within the 37 /// default argument expression. 38 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor 39 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 40 Expr *DefaultArg; 41 Sema *S; 42 43 public: 44 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 45 : DefaultArg(defarg), S(s) {} 46 47 bool VisitExpr(Expr *Node); 48 bool VisitDeclRefExpr(DeclRefExpr *DRE); 49 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 50 }; 51 52 /// VisitExpr - Visit all of the children of this expression. 53 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 54 bool IsInvalid = false; 55 for (Stmt::child_iterator I = Node->child_begin(), 56 E = Node->child_end(); I != E; ++I) 57 IsInvalid |= Visit(*I); 58 return IsInvalid; 59 } 60 61 /// VisitDeclRefExpr - Visit a reference to a declaration, to 62 /// determine whether this declaration can be used in the default 63 /// argument expression. 64 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 65 NamedDecl *Decl = DRE->getDecl(); 66 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 67 // C++ [dcl.fct.default]p9 68 // Default arguments are evaluated each time the function is 69 // called. The order of evaluation of function arguments is 70 // unspecified. Consequently, parameters of a function shall not 71 // be used in default argument expressions, even if they are not 72 // evaluated. Parameters of a function declared before a default 73 // argument expression are in scope and can hide namespace and 74 // class member names. 75 return S->Diag(DRE->getSourceRange().getBegin(), 76 diag::err_param_default_argument_references_param, 77 Param->getName(), DefaultArg->getSourceRange()); 78 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 79 // C++ [dcl.fct.default]p7 80 // Local variables shall not be used in default argument 81 // expressions. 82 if (VDecl->isBlockVarDecl()) 83 return S->Diag(DRE->getSourceRange().getBegin(), 84 diag::err_param_default_argument_references_local, 85 VDecl->getName(), DefaultArg->getSourceRange()); 86 } 87 88 return false; 89 } 90 91 /// VisitCXXThisExpr - Visit a C++ "this" expression. 92 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 93 // C++ [dcl.fct.default]p8: 94 // The keyword this shall not be used in a default argument of a 95 // member function. 96 return S->Diag(ThisE->getSourceRange().getBegin(), 97 diag::err_param_default_argument_references_this, 98 ThisE->getSourceRange()); 99 } 100} 101 102/// ActOnParamDefaultArgument - Check whether the default argument 103/// provided for a function parameter is well-formed. If so, attach it 104/// to the parameter declaration. 105void 106Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc, 107 ExprTy *defarg) { 108 ParmVarDecl *Param = (ParmVarDecl *)param; 109 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg); 110 QualType ParamType = Param->getType(); 111 112 // Default arguments are only permitted in C++ 113 if (!getLangOptions().CPlusPlus) { 114 Diag(EqualLoc, diag::err_param_default_argument, 115 DefaultArg->getSourceRange()); 116 return; 117 } 118 119 // C++ [dcl.fct.default]p5 120 // A default argument expression is implicitly converted (clause 121 // 4) to the parameter type. The default argument expression has 122 // the same semantic constraints as the initializer expression in 123 // a declaration of a variable of the parameter type, using the 124 // copy-initialization semantics (8.5). 125 Expr *DefaultArgPtr = DefaultArg.get(); 126 bool DefaultInitFailed = PerformCopyInitialization(DefaultArgPtr, ParamType, 127 "in default argument"); 128 if (DefaultArgPtr != DefaultArg.get()) { 129 DefaultArg.take(); 130 DefaultArg.reset(DefaultArgPtr); 131 } 132 if (DefaultInitFailed) { 133 return; 134 } 135 136 // Check that the default argument is well-formed 137 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this); 138 if (DefaultArgChecker.Visit(DefaultArg.get())) 139 return; 140 141 // Okay: add the default argument to the parameter 142 Param->setDefaultArg(DefaultArg.take()); 143} 144 145/// CheckExtraCXXDefaultArguments - Check for any extra default 146/// arguments in the declarator, which is not a function declaration 147/// or definition and therefore is not permitted to have default 148/// arguments. This routine should be invoked for every declarator 149/// that is not a function declaration or definition. 150void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 151 // C++ [dcl.fct.default]p3 152 // A default argument expression shall be specified only in the 153 // parameter-declaration-clause of a function declaration or in a 154 // template-parameter (14.1). It shall not be specified for a 155 // parameter pack. If it is specified in a 156 // parameter-declaration-clause, it shall not occur within a 157 // declarator or abstract-declarator of a parameter-declaration. 158 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) { 159 DeclaratorChunk &chunk = D.getTypeObject(i); 160 if (chunk.Kind == DeclaratorChunk::Function) { 161 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) { 162 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param; 163 if (Param->getDefaultArg()) { 164 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc, 165 Param->getDefaultArg()->getSourceRange()); 166 Param->setDefaultArg(0); 167 } 168 } 169 } 170 } 171} 172 173// MergeCXXFunctionDecl - Merge two declarations of the same C++ 174// function, once we already know that they have the same 175// type. Subroutine of MergeFunctionDecl. 176FunctionDecl * 177Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) { 178 // C++ [dcl.fct.default]p4: 179 // 180 // For non-template functions, default arguments can be added in 181 // later declarations of a function in the same 182 // scope. Declarations in different scopes have completely 183 // distinct sets of default arguments. That is, declarations in 184 // inner scopes do not acquire default arguments from 185 // declarations in outer scopes, and vice versa. In a given 186 // function declaration, all parameters subsequent to a 187 // parameter with a default argument shall have default 188 // arguments supplied in this or previous declarations. A 189 // default argument shall not be redefined by a later 190 // declaration (not even to the same value). 191 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) { 192 ParmVarDecl *OldParam = Old->getParamDecl(p); 193 ParmVarDecl *NewParam = New->getParamDecl(p); 194 195 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) { 196 Diag(NewParam->getLocation(), 197 diag::err_param_default_argument_redefinition, 198 NewParam->getDefaultArg()->getSourceRange()); 199 Diag(OldParam->getLocation(), diag::err_previous_definition); 200 } else if (OldParam->getDefaultArg()) { 201 // Merge the old default argument into the new parameter 202 NewParam->setDefaultArg(OldParam->getDefaultArg()); 203 } 204 } 205 206 return New; 207} 208 209/// CheckCXXDefaultArguments - Verify that the default arguments for a 210/// function declaration are well-formed according to C++ 211/// [dcl.fct.default]. 212void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 213 unsigned NumParams = FD->getNumParams(); 214 unsigned p; 215 216 // Find first parameter with a default argument 217 for (p = 0; p < NumParams; ++p) { 218 ParmVarDecl *Param = FD->getParamDecl(p); 219 if (Param->getDefaultArg()) 220 break; 221 } 222 223 // C++ [dcl.fct.default]p4: 224 // In a given function declaration, all parameters 225 // subsequent to a parameter with a default argument shall 226 // have default arguments supplied in this or previous 227 // declarations. A default argument shall not be redefined 228 // by a later declaration (not even to the same value). 229 unsigned LastMissingDefaultArg = 0; 230 for(; p < NumParams; ++p) { 231 ParmVarDecl *Param = FD->getParamDecl(p); 232 if (!Param->getDefaultArg()) { 233 if (Param->getIdentifier()) 234 Diag(Param->getLocation(), 235 diag::err_param_default_argument_missing_name, 236 Param->getIdentifier()->getName()); 237 else 238 Diag(Param->getLocation(), 239 diag::err_param_default_argument_missing); 240 241 LastMissingDefaultArg = p; 242 } 243 } 244 245 if (LastMissingDefaultArg > 0) { 246 // Some default arguments were missing. Clear out all of the 247 // default arguments up to (and including) the last missing 248 // default argument, so that we leave the function parameters 249 // in a semantically valid state. 250 for (p = 0; p <= LastMissingDefaultArg; ++p) { 251 ParmVarDecl *Param = FD->getParamDecl(p); 252 if (Param->getDefaultArg()) { 253 delete Param->getDefaultArg(); 254 Param->setDefaultArg(0); 255 } 256 } 257 } 258} 259 260/// isCurrentClassName - Determine whether the identifier II is the 261/// name of the class type currently being defined. In the case of 262/// nested classes, this will only return true if II is the name of 263/// the innermost class. 264bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *) { 265 if (CXXRecordDecl *CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext)) 266 return &II == CurDecl->getIdentifier(); 267 else 268 return false; 269} 270 271/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 272/// one entry in the base class list of a class specifier, for 273/// example: 274/// class foo : public bar, virtual private baz { 275/// 'public bar' and 'virtual private baz' are each base-specifiers. 276Sema::BaseResult 277Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange, 278 bool Virtual, AccessSpecifier Access, 279 TypeTy *basetype, SourceLocation BaseLoc) { 280 RecordDecl *Decl = (RecordDecl*)classdecl; 281 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype); 282 283 // Base specifiers must be record types. 284 if (!BaseType->isRecordType()) { 285 Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange); 286 return true; 287 } 288 289 // C++ [class.union]p1: 290 // A union shall not be used as a base class. 291 if (BaseType->isUnionType()) { 292 Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange); 293 return true; 294 } 295 296 // C++ [class.union]p1: 297 // A union shall not have base classes. 298 if (Decl->isUnion()) { 299 Diag(Decl->getLocation(), diag::err_base_clause_on_union, 300 SpecifierRange); 301 return true; 302 } 303 304 // C++ [class.derived]p2: 305 // The class-name in a base-specifier shall not be an incompletely 306 // defined class. 307 if (BaseType->isIncompleteType()) { 308 Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange); 309 return true; 310 } 311 312 // Create the base specifier. 313 return new CXXBaseSpecifier(SpecifierRange, Virtual, 314 BaseType->isClassType(), Access, BaseType); 315} 316 317/// ActOnBaseSpecifiers - Attach the given base specifiers to the 318/// class, after checking whether there are any duplicate base 319/// classes. 320void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases, 321 unsigned NumBases) { 322 if (NumBases == 0) 323 return; 324 325 // Used to keep track of which base types we have already seen, so 326 // that we can properly diagnose redundant direct base types. Note 327 // that the key is always the unqualified canonical type of the base 328 // class. 329 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 330 331 // Copy non-redundant base specifiers into permanent storage. 332 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases; 333 unsigned NumGoodBases = 0; 334 for (unsigned idx = 0; idx < NumBases; ++idx) { 335 QualType NewBaseType 336 = Context.getCanonicalType(BaseSpecs[idx]->getType()); 337 NewBaseType = NewBaseType.getUnqualifiedType(); 338 339 if (KnownBaseTypes[NewBaseType]) { 340 // C++ [class.mi]p3: 341 // A class shall not be specified as a direct base class of a 342 // derived class more than once. 343 Diag(BaseSpecs[idx]->getSourceRange().getBegin(), 344 diag::err_duplicate_base_class, 345 KnownBaseTypes[NewBaseType]->getType().getAsString(), 346 BaseSpecs[idx]->getSourceRange()); 347 348 // Delete the duplicate base class specifier; we're going to 349 // overwrite its pointer later. 350 delete BaseSpecs[idx]; 351 } else { 352 // Okay, add this new base class. 353 KnownBaseTypes[NewBaseType] = BaseSpecs[idx]; 354 BaseSpecs[NumGoodBases++] = BaseSpecs[idx]; 355 } 356 } 357 358 // Attach the remaining base class specifiers to the derived class. 359 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl; 360 Decl->setBases(BaseSpecs, NumGoodBases); 361 362 // Delete the remaining (good) base class specifiers, since their 363 // data has been copied into the CXXRecordDecl. 364 for (unsigned idx = 0; idx < NumGoodBases; ++idx) 365 delete BaseSpecs[idx]; 366} 367 368//===----------------------------------------------------------------------===// 369// C++ class member Handling 370//===----------------------------------------------------------------------===// 371 372/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union 373/// definition, when on C++. 374void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) { 375 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D)); 376 PushDeclContext(Dcl); 377 FieldCollector->StartClass(); 378 379 if (Dcl->getIdentifier()) { 380 // C++ [class]p2: 381 // [...] The class-name is also inserted into the scope of the 382 // class itself; this is known as the injected-class-name. For 383 // purposes of access checking, the injected-class-name is treated 384 // as if it were a public member name. 385 TypedefDecl *InjectedClassName 386 = TypedefDecl::Create(Context, Dcl, LBrace, Dcl->getIdentifier(), 387 Context.getTypeDeclType(Dcl), /*PrevDecl=*/0); 388 PushOnScopeChains(InjectedClassName, S); 389 } 390} 391 392/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 393/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 394/// bitfield width if there is one and 'InitExpr' specifies the initializer if 395/// any. 'LastInGroup' is non-null for cases where one declspec has multiple 396/// declarators on it. 397/// 398/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if 399/// an instance field is declared, a new CXXFieldDecl is created but the method 400/// does *not* return it; it returns LastInGroup instead. The other C++ members 401/// (which are all ScopedDecls) are returned after appending them to 402/// LastInGroup. 403Sema::DeclTy * 404Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 405 ExprTy *BW, ExprTy *InitExpr, 406 DeclTy *LastInGroup) { 407 const DeclSpec &DS = D.getDeclSpec(); 408 IdentifierInfo *II = D.getIdentifier(); 409 Expr *BitWidth = static_cast<Expr*>(BW); 410 Expr *Init = static_cast<Expr*>(InitExpr); 411 SourceLocation Loc = D.getIdentifierLoc(); 412 413 // C++ 9.2p6: A member shall not be declared to have automatic storage 414 // duration (auto, register) or with the extern storage-class-specifier. 415 switch (DS.getStorageClassSpec()) { 416 case DeclSpec::SCS_unspecified: 417 case DeclSpec::SCS_typedef: 418 case DeclSpec::SCS_static: 419 // FALL THROUGH. 420 break; 421 default: 422 if (DS.getStorageClassSpecLoc().isValid()) 423 Diag(DS.getStorageClassSpecLoc(), 424 diag::err_storageclass_invalid_for_member); 425 else 426 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member); 427 D.getMutableDeclSpec().ClearStorageClassSpecs(); 428 } 429 430 bool isFunc = D.isFunctionDeclarator(); 431 if (!isFunc && 432 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef && 433 D.getNumTypeObjects() == 0) { 434 // Check also for this case: 435 // 436 // typedef int f(); 437 // f a; 438 // 439 Decl *TD = static_cast<Decl *>(DS.getTypeRep()); 440 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType(); 441 } 442 443 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified && 444 !isFunc); 445 446 Decl *Member; 447 bool InvalidDecl = false; 448 449 if (isInstField) 450 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth)); 451 else 452 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup)); 453 454 if (!Member) return LastInGroup; 455 456 assert((II || isInstField) && "No identifier for non-field ?"); 457 458 // set/getAccess is not part of Decl's interface to avoid bloating it with C++ 459 // specific methods. Use a wrapper class that can be used with all C++ class 460 // member decls. 461 CXXClassMemberWrapper(Member).setAccess(AS); 462 463 if (BitWidth) { 464 // C++ 9.6p2: Only when declaring an unnamed bit-field may the 465 // constant-expression be a value equal to zero. 466 // FIXME: Check this. 467 468 if (D.isFunctionDeclarator()) { 469 // FIXME: Emit diagnostic about only constructors taking base initializers 470 // or something similar, when constructor support is in place. 471 Diag(Loc, diag::err_not_bitfield_type, 472 II->getName(), BitWidth->getSourceRange()); 473 InvalidDecl = true; 474 475 } else if (isInstField) { 476 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 477 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) { 478 Diag(Loc, diag::err_not_integral_type_bitfield, 479 II->getName(), BitWidth->getSourceRange()); 480 InvalidDecl = true; 481 } 482 483 } else if (isa<FunctionDecl>(Member)) { 484 // A function typedef ("typedef int f(); f a;"). 485 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 486 Diag(Loc, diag::err_not_integral_type_bitfield, 487 II->getName(), BitWidth->getSourceRange()); 488 InvalidDecl = true; 489 490 } else if (isa<TypedefDecl>(Member)) { 491 // "cannot declare 'A' to be a bit-field type" 492 Diag(Loc, diag::err_not_bitfield_type, II->getName(), 493 BitWidth->getSourceRange()); 494 InvalidDecl = true; 495 496 } else { 497 assert(isa<CXXClassVarDecl>(Member) && 498 "Didn't we cover all member kinds?"); 499 // C++ 9.6p3: A bit-field shall not be a static member. 500 // "static member 'A' cannot be a bit-field" 501 Diag(Loc, diag::err_static_not_bitfield, II->getName(), 502 BitWidth->getSourceRange()); 503 InvalidDecl = true; 504 } 505 } 506 507 if (Init) { 508 // C++ 9.2p4: A member-declarator can contain a constant-initializer only 509 // if it declares a static member of const integral or const enumeration 510 // type. 511 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) { 512 // ...static member of... 513 CVD->setInit(Init); 514 // ...const integral or const enumeration type. 515 if (Context.getCanonicalType(CVD->getType()).isConstQualified() && 516 CVD->getType()->isIntegralType()) { 517 // constant-initializer 518 if (CheckForConstantInitializer(Init, CVD->getType())) 519 InvalidDecl = true; 520 521 } else { 522 // not const integral. 523 Diag(Loc, diag::err_member_initialization, 524 II->getName(), Init->getSourceRange()); 525 InvalidDecl = true; 526 } 527 528 } else { 529 // not static member. 530 Diag(Loc, diag::err_member_initialization, 531 II->getName(), Init->getSourceRange()); 532 InvalidDecl = true; 533 } 534 } 535 536 if (InvalidDecl) 537 Member->setInvalidDecl(); 538 539 if (isInstField) { 540 FieldCollector->Add(cast<CXXFieldDecl>(Member)); 541 return LastInGroup; 542 } 543 return Member; 544} 545 546void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 547 DeclTy *TagDecl, 548 SourceLocation LBrac, 549 SourceLocation RBrac) { 550 ActOnFields(S, RLoc, TagDecl, 551 (DeclTy**)FieldCollector->getCurFields(), 552 FieldCollector->getCurNumFields(), LBrac, RBrac, 0); 553} 554 555/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 556/// special functions, such as the default constructor, copy 557/// constructor, or destructor, to the given C++ class (C++ 558/// [special]p1). This routine can only be executed just before the 559/// definition of the class is complete. 560void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 561 if (!ClassDecl->hasUserDeclaredConstructor()) { 562 // C++ [class.ctor]p5: 563 // A default constructor for a class X is a constructor of class X 564 // that can be called without an argument. If there is no 565 // user-declared constructor for class X, a default constructor is 566 // implicitly declared. An implicitly-declared default constructor 567 // is an inline public member of its class. 568 CXXConstructorDecl *DefaultCon = 569 CXXConstructorDecl::Create(Context, ClassDecl, 570 ClassDecl->getLocation(), 571 ClassDecl->getIdentifier(), 572 Context.getFunctionType(Context.VoidTy, 573 0, 0, false, 0), 574 /*isExplicit=*/false, 575 /*isInline=*/true, 576 /*isImplicitlyDeclared=*/true); 577 DefaultCon->setAccess(AS_public); 578 ClassDecl->addConstructor(Context, DefaultCon); 579 } 580 581 if (!ClassDecl->hasUserDeclaredCopyConstructor()) { 582 // C++ [class.copy]p4: 583 // If the class definition does not explicitly declare a copy 584 // constructor, one is declared implicitly. 585 586 // C++ [class.copy]p5: 587 // The implicitly-declared copy constructor for a class X will 588 // have the form 589 // 590 // X::X(const X&) 591 // 592 // if 593 bool HasConstCopyConstructor = true; 594 595 // -- each direct or virtual base class B of X has a copy 596 // constructor whose first parameter is of type const B& or 597 // const volatile B&, and 598 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 599 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) { 600 const CXXRecordDecl *BaseClassDecl 601 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl()); 602 HasConstCopyConstructor 603 = BaseClassDecl->hasConstCopyConstructor(Context); 604 } 605 606 // -- for all the nonstatic data members of X that are of a 607 // class type M (or array thereof), each such class type 608 // has a copy constructor whose first parameter is of type 609 // const M& or const volatile M&. 610 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(); 611 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) { 612 QualType FieldType = (*Field)->getType(); 613 if (const ArrayType *Array = Context.getAsArrayType(FieldType)) 614 FieldType = Array->getElementType(); 615 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) { 616 const CXXRecordDecl *FieldClassDecl 617 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 618 HasConstCopyConstructor 619 = FieldClassDecl->hasConstCopyConstructor(Context); 620 } 621 } 622 623 // Otherwise, the implicitly declared copy constructor will have 624 // the form 625 // 626 // X::X(X&) 627 QualType ArgType = Context.getTypeDeclType(ClassDecl); 628 if (HasConstCopyConstructor) 629 ArgType = ArgType.withConst(); 630 ArgType = Context.getReferenceType(ArgType); 631 632 // An implicitly-declared copy constructor is an inline public 633 // member of its class. 634 CXXConstructorDecl *CopyConstructor 635 = CXXConstructorDecl::Create(Context, ClassDecl, 636 ClassDecl->getLocation(), 637 ClassDecl->getIdentifier(), 638 Context.getFunctionType(Context.VoidTy, 639 &ArgType, 1, 640 false, 0), 641 /*isExplicit=*/false, 642 /*isInline=*/true, 643 /*isImplicitlyDeclared=*/true); 644 CopyConstructor->setAccess(AS_public); 645 646 // Add the parameter to the constructor. 647 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 648 ClassDecl->getLocation(), 649 /*IdentifierInfo=*/0, 650 ArgType, VarDecl::None, 0, 0); 651 CopyConstructor->setParams(&FromParam, 1); 652 653 ClassDecl->addConstructor(Context, CopyConstructor); 654 } 655 656 // FIXME: Implicit destructor 657 // FIXME: Implicit copy assignment operator 658} 659 660void Sema::ActOnFinishCXXClassDef(DeclTy *D) { 661 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D)); 662 FieldCollector->FinishClass(); 663 AddImplicitlyDeclaredMembersToClass(Rec); 664 PopDeclContext(); 665 666 // Everything, including inline method definitions, have been parsed. 667 // Let the consumer know of the new TagDecl definition. 668 Consumer.HandleTagDeclDefinition(Rec); 669} 670 671/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete 672/// the declaration of the given C++ constructor ConDecl that was 673/// built from declarator D. This routine is responsible for checking 674/// that the newly-created constructor declaration is well-formed and 675/// for recording it in the C++ class. Example: 676/// 677/// @code 678/// class X { 679/// X(); // X::X() will be the ConDecl. 680/// }; 681/// @endcode 682Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) { 683 assert(ConDecl && "Expected to receive a constructor declaration"); 684 685 // Check default arguments on the constructor 686 CheckCXXDefaultArguments(ConDecl); 687 688 CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 689 if (!ClassDecl) { 690 ConDecl->setInvalidDecl(); 691 return ConDecl; 692 } 693 694 // Make sure this constructor is an overload of the existing 695 // constructors. 696 OverloadedFunctionDecl::function_iterator MatchedDecl; 697 if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) { 698 Diag(ConDecl->getLocation(), 699 diag::err_constructor_redeclared, 700 SourceRange(ConDecl->getLocation())); 701 Diag((*MatchedDecl)->getLocation(), 702 diag::err_previous_declaration, 703 SourceRange((*MatchedDecl)->getLocation())); 704 ConDecl->setInvalidDecl(); 705 return ConDecl; 706 } 707 708 709 // C++ [class.copy]p3: 710 // A declaration of a constructor for a class X is ill-formed if 711 // its first parameter is of type (optionally cv-qualified) X and 712 // either there are no other parameters or else all other 713 // parameters have default arguments. 714 if ((ConDecl->getNumParams() == 1) || 715 (ConDecl->getNumParams() > 1 && 716 ConDecl->getParamDecl(1)->getDefaultArg() != 0)) { 717 QualType ParamType = ConDecl->getParamDecl(0)->getType(); 718 QualType ClassTy = Context.getTagDeclType( 719 const_cast<CXXRecordDecl*>(ConDecl->getParent())); 720 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 721 Diag(ConDecl->getLocation(), 722 diag::err_constructor_byvalue_arg, 723 SourceRange(ConDecl->getParamDecl(0)->getLocation())); 724 ConDecl->setInvalidDecl(); 725 return 0; 726 } 727 } 728 729 // Add this constructor to the set of constructors of the current 730 // class. 731 ClassDecl->addConstructor(Context, ConDecl); 732 733 return (DeclTy *)ConDecl; 734} 735 736//===----------------------------------------------------------------------===// 737// Namespace Handling 738//===----------------------------------------------------------------------===// 739 740/// ActOnStartNamespaceDef - This is called at the start of a namespace 741/// definition. 742Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 743 SourceLocation IdentLoc, 744 IdentifierInfo *II, 745 SourceLocation LBrace) { 746 NamespaceDecl *Namespc = 747 NamespaceDecl::Create(Context, CurContext, IdentLoc, II); 748 Namespc->setLBracLoc(LBrace); 749 750 Scope *DeclRegionScope = NamespcScope->getParent(); 751 752 if (II) { 753 // C++ [namespace.def]p2: 754 // The identifier in an original-namespace-definition shall not have been 755 // previously defined in the declarative region in which the 756 // original-namespace-definition appears. The identifier in an 757 // original-namespace-definition is the name of the namespace. Subsequently 758 // in that declarative region, it is treated as an original-namespace-name. 759 760 Decl *PrevDecl = 761 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope, 762 /*enableLazyBuiltinCreation=*/false); 763 764 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) { 765 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) { 766 // This is an extended namespace definition. 767 // Attach this namespace decl to the chain of extended namespace 768 // definitions. 769 NamespaceDecl *NextNS = OrigNS; 770 while (NextNS->getNextNamespace()) 771 NextNS = NextNS->getNextNamespace(); 772 773 NextNS->setNextNamespace(Namespc); 774 Namespc->setOriginalNamespace(OrigNS); 775 776 // We won't add this decl to the current scope. We want the namespace 777 // name to return the original namespace decl during a name lookup. 778 } else { 779 // This is an invalid name redefinition. 780 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind, 781 Namespc->getName()); 782 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 783 Namespc->setInvalidDecl(); 784 // Continue on to push Namespc as current DeclContext and return it. 785 } 786 } else { 787 // This namespace name is declared for the first time. 788 PushOnScopeChains(Namespc, DeclRegionScope); 789 } 790 } 791 else { 792 // FIXME: Handle anonymous namespaces 793 } 794 795 // Although we could have an invalid decl (i.e. the namespace name is a 796 // redefinition), push it as current DeclContext and try to continue parsing. 797 PushDeclContext(Namespc->getOriginalNamespace()); 798 return Namespc; 799} 800 801/// ActOnFinishNamespaceDef - This callback is called after a namespace is 802/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 803void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) { 804 Decl *Dcl = static_cast<Decl *>(D); 805 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 806 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 807 Namespc->setRBracLoc(RBrace); 808 PopDeclContext(); 809} 810 811 812/// AddCXXDirectInitializerToDecl - This action is called immediately after 813/// ActOnDeclarator, when a C++ direct initializer is present. 814/// e.g: "int x(1);" 815void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc, 816 ExprTy **ExprTys, unsigned NumExprs, 817 SourceLocation *CommaLocs, 818 SourceLocation RParenLoc) { 819 assert(NumExprs != 0 && ExprTys && "missing expressions"); 820 Decl *RealDecl = static_cast<Decl *>(Dcl); 821 822 // If there is no declaration, there was an error parsing it. Just ignore 823 // the initializer. 824 if (RealDecl == 0) { 825 for (unsigned i = 0; i != NumExprs; ++i) 826 delete static_cast<Expr *>(ExprTys[i]); 827 return; 828 } 829 830 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 831 if (!VDecl) { 832 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 833 RealDecl->setInvalidDecl(); 834 return; 835 } 836 837 // We will treat direct-initialization as a copy-initialization: 838 // int x(1); -as-> int x = 1; 839 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 840 // 841 // Clients that want to distinguish between the two forms, can check for 842 // direct initializer using VarDecl::hasCXXDirectInitializer(). 843 // A major benefit is that clients that don't particularly care about which 844 // exactly form was it (like the CodeGen) can handle both cases without 845 // special case code. 846 847 // C++ 8.5p11: 848 // The form of initialization (using parentheses or '=') is generally 849 // insignificant, but does matter when the entity being initialized has a 850 // class type. 851 QualType DeclInitType = VDecl->getType(); 852 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType)) 853 DeclInitType = Array->getElementType(); 854 855 if (VDecl->getType()->isRecordType()) { 856 CXXConstructorDecl *Constructor 857 = PerformDirectInitForClassType(DeclInitType, (Expr **)ExprTys, NumExprs, 858 VDecl->getLocation(), 859 SourceRange(VDecl->getLocation(), 860 RParenLoc), 861 VDecl->getName(), 862 /*HasInitializer=*/true); 863 if (!Constructor) { 864 RealDecl->setInvalidDecl(); 865 } 866 return; 867 } 868 869 if (NumExprs > 1) { 870 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg, 871 SourceRange(VDecl->getLocation(), RParenLoc)); 872 RealDecl->setInvalidDecl(); 873 return; 874 } 875 876 // Let clients know that initialization was done with a direct initializer. 877 VDecl->setCXXDirectInitializer(true); 878 879 assert(NumExprs == 1 && "Expected 1 expression"); 880 // Set the init expression, handles conversions. 881 AddInitializerToDecl(Dcl, ExprTys[0]); 882} 883 884/// PerformDirectInitForClassType - Perform direct-initialization (C++ 885/// [dcl.init]) for a value of the given class type with the given set 886/// of arguments (@p Args). @p Loc is the location in the source code 887/// where the initializer occurs (e.g., a declaration, member 888/// initializer, functional cast, etc.) while @p Range covers the 889/// whole initialization. @p HasInitializer is true if the initializer 890/// was actually written in the source code. When successful, returns 891/// the constructor that will be used to perform the initialization; 892/// when the initialization fails, emits a diagnostic and returns null. 893CXXConstructorDecl * 894Sema::PerformDirectInitForClassType(QualType ClassType, 895 Expr **Args, unsigned NumArgs, 896 SourceLocation Loc, SourceRange Range, 897 std::string InitEntity, 898 bool HasInitializer) { 899 const RecordType *ClassRec = ClassType->getAsRecordType(); 900 assert(ClassRec && "Can only initialize a class type here"); 901 902 // C++ [dcl.init]p14: 903 // 904 // If the initialization is direct-initialization, or if it is 905 // copy-initialization where the cv-unqualified version of the 906 // source type is the same class as, or a derived class of, the 907 // class of the destination, constructors are considered. The 908 // applicable constructors are enumerated (13.3.1.3), and the 909 // best one is chosen through overload resolution (13.3). The 910 // constructor so selected is called to initialize the object, 911 // with the initializer expression(s) as its argument(s). If no 912 // constructor applies, or the overload resolution is ambiguous, 913 // the initialization is ill-formed. 914 // 915 // FIXME: We don't check cv-qualifiers on the class type, because we 916 // don't yet keep track of whether a class type is a POD class type 917 // (or a "trivial" class type, as is used in C++0x). 918 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 919 OverloadCandidateSet CandidateSet; 920 OverloadCandidateSet::iterator Best; 921 AddOverloadCandidates(ClassDecl->getConstructors(), Args, NumArgs, 922 CandidateSet); 923 switch (BestViableFunction(CandidateSet, Best)) { 924 case OR_Success: 925 // We found a constructor. Return it. 926 return cast<CXXConstructorDecl>(Best->Function); 927 928 case OR_No_Viable_Function: 929 if (CandidateSet.empty()) 930 Diag(Loc, diag::err_ovl_no_viable_function_in_init, 931 InitEntity, Range); 932 else { 933 Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands, 934 InitEntity, Range); 935 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 936 } 937 return 0; 938 939 case OR_Ambiguous: 940 Diag(Loc, diag::err_ovl_ambiguous_init, 941 InitEntity, Range); 942 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 943 return 0; 944 } 945 946 return 0; 947} 948 949/// CompareReferenceRelationship - Compare the two types T1 and T2 to 950/// determine whether they are reference-related, 951/// reference-compatible, reference-compatible with added 952/// qualification, or incompatible, for use in C++ initialization by 953/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 954/// type, and the first type (T1) is the pointee type of the reference 955/// type being initialized. 956Sema::ReferenceCompareResult 957Sema::CompareReferenceRelationship(QualType T1, QualType T2, 958 bool& DerivedToBase) { 959 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type"); 960 assert(!T2->isReferenceType() && "T2 cannot be a reference type"); 961 962 T1 = Context.getCanonicalType(T1); 963 T2 = Context.getCanonicalType(T2); 964 QualType UnqualT1 = T1.getUnqualifiedType(); 965 QualType UnqualT2 = T2.getUnqualifiedType(); 966 967 // C++ [dcl.init.ref]p4: 968 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is 969 // reference-related to “cv2 T2” if T1 is the same type as T2, or 970 // T1 is a base class of T2. 971 if (UnqualT1 == UnqualT2) 972 DerivedToBase = false; 973 else if (IsDerivedFrom(UnqualT2, UnqualT1)) 974 DerivedToBase = true; 975 else 976 return Ref_Incompatible; 977 978 // At this point, we know that T1 and T2 are reference-related (at 979 // least). 980 981 // C++ [dcl.init.ref]p4: 982 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is 983 // reference-related to T2 and cv1 is the same cv-qualification 984 // as, or greater cv-qualification than, cv2. For purposes of 985 // overload resolution, cases for which cv1 is greater 986 // cv-qualification than cv2 are identified as 987 // reference-compatible with added qualification (see 13.3.3.2). 988 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 989 return Ref_Compatible; 990 else if (T1.isMoreQualifiedThan(T2)) 991 return Ref_Compatible_With_Added_Qualification; 992 else 993 return Ref_Related; 994} 995 996/// CheckReferenceInit - Check the initialization of a reference 997/// variable with the given initializer (C++ [dcl.init.ref]). Init is 998/// the initializer (either a simple initializer or an initializer 999/// list), and DeclType is the type of the declaration. When ICS is 1000/// non-null, this routine will compute the implicit conversion 1001/// sequence according to C++ [over.ics.ref] and will not produce any 1002/// diagnostics; when ICS is null, it will emit diagnostics when any 1003/// errors are found. Either way, a return value of true indicates 1004/// that there was a failure, a return value of false indicates that 1005/// the reference initialization succeeded. 1006/// 1007/// When @p SuppressUserConversions, user-defined conversions are 1008/// suppressed. 1009bool 1010Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType, 1011 ImplicitConversionSequence *ICS, 1012 bool SuppressUserConversions) { 1013 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 1014 1015 QualType T1 = DeclType->getAsReferenceType()->getPointeeType(); 1016 QualType T2 = Init->getType(); 1017 1018 // Compute some basic properties of the types and the initializer. 1019 bool DerivedToBase = false; 1020 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context); 1021 ReferenceCompareResult RefRelationship 1022 = CompareReferenceRelationship(T1, T2, DerivedToBase); 1023 1024 // Most paths end in a failed conversion. 1025 if (ICS) 1026 ICS->ConversionKind = ImplicitConversionSequence::BadConversion; 1027 1028 // C++ [dcl.init.ref]p5: 1029 // A reference to type “cv1 T1” is initialized by an expression 1030 // of type “cv2 T2” as follows: 1031 1032 // -- If the initializer expression 1033 1034 bool BindsDirectly = false; 1035 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is 1036 // reference-compatible with “cv2 T2,” or 1037 // 1038 // Note that the bit-field check is skipped if we are just computing 1039 // the implicit conversion sequence (C++ [over.best.ics]p2). 1040 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) && 1041 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 1042 BindsDirectly = true; 1043 1044 if (ICS) { 1045 // C++ [over.ics.ref]p1: 1046 // When a parameter of reference type binds directly (8.5.3) 1047 // to an argument expression, the implicit conversion sequence 1048 // is the identity conversion, unless the argument expression 1049 // has a type that is a derived class of the parameter type, 1050 // in which case the implicit conversion sequence is a 1051 // derived-to-base Conversion (13.3.3.1). 1052 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 1053 ICS->Standard.First = ICK_Identity; 1054 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 1055 ICS->Standard.Third = ICK_Identity; 1056 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 1057 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 1058 ICS->Standard.ReferenceBinding = true; 1059 ICS->Standard.DirectBinding = true; 1060 1061 // Nothing more to do: the inaccessibility/ambiguity check for 1062 // derived-to-base conversions is suppressed when we're 1063 // computing the implicit conversion sequence (C++ 1064 // [over.best.ics]p2). 1065 return false; 1066 } else { 1067 // Perform the conversion. 1068 // FIXME: Binding to a subobject of the lvalue is going to require 1069 // more AST annotation than this. 1070 ImpCastExprToType(Init, T1); 1071 } 1072 } 1073 1074 // -- has a class type (i.e., T2 is a class type) and can be 1075 // implicitly converted to an lvalue of type “cv3 T3,” 1076 // where “cv1 T1” is reference-compatible with “cv3 T3” 1077 // 92) (this conversion is selected by enumerating the 1078 // applicable conversion functions (13.3.1.6) and choosing 1079 // the best one through overload resolution (13.3)), 1080 // FIXME: Implement this second bullet, once we have conversion 1081 // functions. Also remember C++ [over.ics.ref]p1, second part. 1082 1083 if (BindsDirectly) { 1084 // C++ [dcl.init.ref]p4: 1085 // [...] In all cases where the reference-related or 1086 // reference-compatible relationship of two types is used to 1087 // establish the validity of a reference binding, and T1 is a 1088 // base class of T2, a program that necessitates such a binding 1089 // is ill-formed if T1 is an inaccessible (clause 11) or 1090 // ambiguous (10.2) base class of T2. 1091 // 1092 // Note that we only check this condition when we're allowed to 1093 // complain about errors, because we should not be checking for 1094 // ambiguity (or inaccessibility) unless the reference binding 1095 // actually happens. 1096 if (DerivedToBase) 1097 return CheckDerivedToBaseConversion(T2, T1, 1098 Init->getSourceRange().getBegin(), 1099 Init->getSourceRange()); 1100 else 1101 return false; 1102 } 1103 1104 // -- Otherwise, the reference shall be to a non-volatile const 1105 // type (i.e., cv1 shall be const). 1106 if (T1.getCVRQualifiers() != QualType::Const) { 1107 if (!ICS) 1108 Diag(Init->getSourceRange().getBegin(), 1109 diag::err_not_reference_to_const_init, 1110 T1.getAsString(), 1111 InitLvalue != Expr::LV_Valid? "temporary" : "value", 1112 T2.getAsString(), Init->getSourceRange()); 1113 return true; 1114 } 1115 1116 // -- If the initializer expression is an rvalue, with T2 a 1117 // class type, and “cv1 T1” is reference-compatible with 1118 // “cv2 T2,” the reference is bound in one of the 1119 // following ways (the choice is implementation-defined): 1120 // 1121 // -- The reference is bound to the object represented by 1122 // the rvalue (see 3.10) or to a sub-object within that 1123 // object. 1124 // 1125 // -- A temporary of type “cv1 T2” [sic] is created, and 1126 // a constructor is called to copy the entire rvalue 1127 // object into the temporary. The reference is bound to 1128 // the temporary or to a sub-object within the 1129 // temporary. 1130 // 1131 // 1132 // The constructor that would be used to make the copy 1133 // shall be callable whether or not the copy is actually 1134 // done. 1135 // 1136 // Note that C++0x [dcl.ref.init]p5 takes away this implementation 1137 // freedom, so we will always take the first option and never build 1138 // a temporary in this case. FIXME: We will, however, have to check 1139 // for the presence of a copy constructor in C++98/03 mode. 1140 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() && 1141 RefRelationship >= Ref_Compatible_With_Added_Qualification) { 1142 if (ICS) { 1143 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion; 1144 ICS->Standard.First = ICK_Identity; 1145 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity; 1146 ICS->Standard.Third = ICK_Identity; 1147 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr(); 1148 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr(); 1149 ICS->Standard.ReferenceBinding = true; 1150 ICS->Standard.DirectBinding = false; 1151 } else { 1152 // FIXME: Binding to a subobject of the rvalue is going to require 1153 // more AST annotation than this. 1154 ImpCastExprToType(Init, T1); 1155 } 1156 return false; 1157 } 1158 1159 // -- Otherwise, a temporary of type “cv1 T1” is created and 1160 // initialized from the initializer expression using the 1161 // rules for a non-reference copy initialization (8.5). The 1162 // reference is then bound to the temporary. If T1 is 1163 // reference-related to T2, cv1 must be the same 1164 // cv-qualification as, or greater cv-qualification than, 1165 // cv2; otherwise, the program is ill-formed. 1166 if (RefRelationship == Ref_Related) { 1167 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 1168 // we would be reference-compatible or reference-compatible with 1169 // added qualification. But that wasn't the case, so the reference 1170 // initialization fails. 1171 if (!ICS) 1172 Diag(Init->getSourceRange().getBegin(), 1173 diag::err_reference_init_drops_quals, 1174 T1.getAsString(), 1175 InitLvalue != Expr::LV_Valid? "temporary" : "value", 1176 T2.getAsString(), Init->getSourceRange()); 1177 return true; 1178 } 1179 1180 // Actually try to convert the initializer to T1. 1181 if (ICS) { 1182 /// C++ [over.ics.ref]p2: 1183 /// 1184 /// When a parameter of reference type is not bound directly to 1185 /// an argument expression, the conversion sequence is the one 1186 /// required to convert the argument expression to the 1187 /// underlying type of the reference according to 1188 /// 13.3.3.1. Conceptually, this conversion sequence corresponds 1189 /// to copy-initializing a temporary of the underlying type with 1190 /// the argument expression. Any difference in top-level 1191 /// cv-qualification is subsumed by the initialization itself 1192 /// and does not constitute a conversion. 1193 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions); 1194 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion; 1195 } else { 1196 return PerformImplicitConversion(Init, T1); 1197 } 1198} 1199